modules

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2018 License: MIT Imports: 21 Imported by: 25

Documentation

Overview

Package modules contains definitions for all of the major modules of Sia, as well as some helper functions for performing actions that are common to multiple modules.

Index

Constants

View Source
const (
	// ExplorerDir is the name of the directory that is typically used for the
	// explorer.
	ExplorerDir = "explorer"
	// BlockHashType is a label indicating that a hash is that of a block
	BlockHashType = "Blk"
	// TransactionHashType is a label indicating that a hash is that of a tx
	TransactionHashType = "Tx"
	// SiacoinOutputIdHashType is a label indicating that a hash is that of a
	// siacoin output id
	SiacoinOutputIdHashType = "Scoid"
	// FileContractIdHashType is a label indicating that a hash is that of a
	// file contract id
	FileContractIdHashType = "Fcid"
	// UnlockHashType is a label indicating that a hash is that of an unlock
	// hash
	UnlockHashType = "Uh"
)
View Source
const (
	// GatewayDir is the name of the directory used to store the gateway's
	// persistent data.
	GatewayDir = "gateway"
	// ShareNodesCmd requests that a node share a list of the other network
	// nodes it knows
	ShareNodesCmd = "ShareNodes"
	// DiscoverIPCmd requests that a node tell us what our external IP is
	DiscoverIPCmd = "DiscoverIP"
	// SendBlocksCmd requests that a node send us a list of consensus blocks
	SendBlocksCmd = "SendBlocks"
	// SendBlockCmd requests that a node send us a specific consensus block
	SendBlockCmd = "SendBlk"
	// SendHeadersCmd requests that a node send us a list of headers
	SendHeadersCmd = "SndHdrs"
	// SendHeaderCmd requests that a node send us a specific header
	SendHeaderCmd = "SndHdr"
	// RelayHeaderCmd sends a block header to a peer with the expectation
	// that the peer will pass on the header to other nodes
	RelayHeaderCmd = "RelayHeader"
	// RelayTransactionSetCmd sends a transaction set to a peer.
	RelayTransactionSetCmd = "RelayTransactionSet"
)
View Source
const (
	// AcceptResponse is the response given to an RPC call to indicate
	// acceptance, i.e. that the sender wishes to continue communication.
	AcceptResponse = "accept"

	// StopResponse is the response given to an RPC call to indicate graceful
	// termination, i.e. that the sender wishes to cease communication, but
	// not due to an error.
	StopResponse = "stop"
)
View Source
const (
	// NegotiateDownloadTime defines the amount of time that the renter and
	// host have to negotiate a download request batch. The time is set high
	// enough that two nodes behind Tor have a reasonable chance of completing
	// the negotiation.
	NegotiateDownloadTime = 600 * time.Second

	// NegotiateFileContractRevisionTime defines the minimum amount of time
	// that the renter and host have to negotiate a file contract revision. The
	// time is set high enough that a full 4MB can be piped through a
	// connection that is running over Tor.
	NegotiateFileContractRevisionTime = 600 * time.Second

	// NegotiateFileContractTime defines the amount of time that the renter and
	// host have to negotiate a file contract. The time is set high enough that
	// a node behind Tor has a reasonable chance at making the multiple
	// required round trips to complete the negotiation.
	NegotiateFileContractTime = 360 * time.Second

	// NegotiateMaxDownloadActionRequestSize defines the maximum size that a
	// download request can be. Note, this is not a max size for the data that
	// can be requested, but instead is a max size for the definition of the
	// data being requested.
	NegotiateMaxDownloadActionRequestSize = 50e3

	// NegotiateMaxErrorSize indicates the maximum number of bytes that can be
	// used to encode an error being sent during negotiation.
	NegotiateMaxErrorSize = 256

	// NegotiateMaxFileContractRevisionSize specifies the maximum size that a
	// file contract revision is allowed to have when being sent over the wire
	// during negotiation.
	NegotiateMaxFileContractRevisionSize = 3e3

	// NegotiateMaxFileContractSetLen 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.
	NegotiateMaxFileContractSetLen = TransactionSetSizeLimit - 1e3

	// NegotiateMaxHostExternalSettingsLen is the maximum allowed size of an
	// encoded HostExternalSettings.
	NegotiateMaxHostExternalSettingsLen = 16000

	// NegotiateMaxSiaPubkeySize defines the maximum size that a SiaPubkey is
	// allowed to be when being sent over the wire during negotiation.
	NegotiateMaxSiaPubkeySize = 1e3

	// NegotiateMaxTransactionSignatureSize defines the maximum size that a
	// transaction signature is allowed to be when being sent over the wire
	// during negotiation.
	NegotiateMaxTransactionSignatureSize = 2e3

	// NegotiateMaxTransactionSignaturesSize defines the maximum size that a
	// transaction signature slice is allowed to be when being sent over the
	// wire during negotiation.
	NegotiateMaxTransactionSignaturesSize = 5e3

	// NegotiateRecentRevisionTime establishes the minimum amount of time that
	// the connection deadline is expected to be set to when a recent file
	// contract revision is being requested from the host. The deadline is long
	// enough that the connection should be successful even if both parties are
	// running Tor.
	NegotiateRecentRevisionTime = 120 * time.Second

	// NegotiateRenewContractTime defines the minimum amount of time that the
	// renter and host have to negotiate a final contract renewal. The time is
	// high enough that the negotiation can occur over a Tor connection, and
	// that both the host and the renter can have time to process large Merkle
	// tree calculations that may be involved with renewing a file contract.
	NegotiateRenewContractTime = 600 * time.Second
)
View Source
const (
	// RenterDir is the name of the directory that is used to store the
	// renter's persistent data.
	RenterDir = "renter"

	// EstimatedFileContractTransactionSetSize is the estimated blockchain size
	// of a transaction set between a renter and a host that contains a file
	// contract. This transaction set will contain a setup transaction from each
	// the host and the renter, and will also contain a file contract and file
	// contract revision that have each been signed by all parties.
	EstimatedFileContractTransactionSetSize = 2048
)
View Source
const (
	// ContractManagerDir is the standard name used for the directory that
	// contains all files directly related to the contract manager.
	ContractManagerDir = "contractmanager"

	// StorageManagerDir is standard name used for the directory that contains
	// all of the storage manager files.
	StorageManagerDir = "storagemanager"
)
View Source
const (
	// TransactionSetSizeLimit defines the largest set of dependent unconfirmed
	// transactions that will be accepted by the transaction pool.
	TransactionSetSizeLimit = 250e3

	// TransactionSizeLimit defines the size of the largest transaction that
	// will be accepted by the transaction pool according to the IsStandard
	// rules.
	TransactionSizeLimit = 32e3
)
View Source
const (
	// PublicKeysPerSeed define the number of public keys that get pregenerated
	// for a seed at startup when searching for balances in the blockchain.
	PublicKeysPerSeed = 2500

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

	// WalletDir is the directory that contains the wallet persistence.
	WalletDir = "wallet"

	// Bitcoin defaults to 20, but we can create a lot of addresses quickly
	// when we form contracts, so we set to 50.
	DefaultAddressGapLimit = 50
)
View Source
const (
	// HostDir names the directory that contains the host persistence.
	HostDir = "host"
)
View Source
const (
	// IndexDir names the directory that contains the index persistence.
	IndexDir = "index"
)
View Source
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.

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 (
	// PoolDir names the directory that contains the pool persistence.
	PoolDir = "miningpool"
)
View Source
const (
	// StratumMinerDir is the name of the directory that is used to store the miner's
	// persistent data.
	StratumMinerDir = "stratumminer"
)

Variables

View Source
var (
	// ConsensusChangeBeginning is a special consensus change id that tells the
	// consensus set to provide all consensus changes starting from the very
	// first diff, which includes the genesis block diff.
	ConsensusChangeBeginning = ConsensusChangeID{}

	// ConsensusChangeRecent is a special consensus change id that tells the
	// consensus set to provide the most recent consensus change, instead of
	// starting from a specific value (which may not be known to the caller).
	ConsensusChangeRecent = ConsensusChangeID{1}

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

	ErrHeaderKnown = errors.New("header 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 desynchronized. 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 (
	// 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 = build.Select(build.Var{
		Standard: []NetAddress{
			"47.75.72.189:5581",
			"47.75.72.189:25581",
			"139.162.118.62:5581",
			"139.162.198.80:5581",
			"50.116.37.123:5581",
			"45.33.42.181:5581",
			"172.104.155.40:5581",
			"172.104.188.185:5581",
			"47.100.43.104:5581",
			"47.90.212.141:5581",
			"69.195.141.178:5581",
			"45.76.30.176:5581",
			"204.48.22.106:5581",
			"178.128.65.120:5581",
			"52.39.226.32:5581",
			"68.175.125.235:5581",
			"59.167.191.60:5581",
		},
		Dev: []NetAddress{
			"45.33.42.181:5581",
			"139.162.118.62:5581",
			"172.104.155.40:5581",
			"172.104.188.185:5581",
			"47.100.43.104:5581",
			"47.75.72.189:5581",
			"47.75.72.189:25581",
			"47.90.212.141:5581",
		},
		Testing: []NetAddress(nil),
	}).([]NetAddress)

	// SPVBootstrapPeers is the bootstrap nodes for spv
	SPVBootstrapPeers = build.Select(build.Var{
		Standard: []NetAddress{
			"47.75.72.189:5581",
			"47.75.72.189:25581",
			"139.162.118.62:5581",
			"139.162.198.80:5581",
			"47.100.43.104:5581",
			"50.116.37.123:5581",
			"59.167.191.60:5581",
			"45.33.42.181:5581",
		},
		Dev: []NetAddress{
			"47.75.72.189:5581",
			"47.75.72.189:25581",
			"139.162.118.62:5581",
			"139.162.198.80:5581",
			"47.100.43.104:5581",
			"50.116.37.123:5581",
			"45.33.42.181:5581",
		},
		Testing: []NetAddress(nil),
	}).([]NetAddress)
)
View Source
var (
	// BlockBytesPerMonthTerabyte is the conversion rate between block-bytes and month-TB.
	BlockBytesPerMonthTerabyte = BytesPerTerabyte.Mul64(4320)

	// BytesPerTerabyte is the conversion rate between bytes and terabytes.
	BytesPerTerabyte = types.NewCurrency64(1e12)

	// HostConnectabilityStatusChecking is returned from ConnectabilityStatus()
	// if the host is still determining if it is connectable.
	HostConnectabilityStatusChecking = HostConnectabilityStatus("checking")

	// HostConnectabilityStatusConnectable is returned from
	// ConnectabilityStatus() if the host is connectable at its configured
	// netaddress.
	HostConnectabilityStatusConnectable = HostConnectabilityStatus("connectable")

	// HostConnectabilityStatusNotConnectable is returned from
	// ConnectabilityStatus() if the host is not connectable at its configured
	// netaddress.
	HostConnectabilityStatusNotConnectable = HostConnectabilityStatus("not connectable")

	// HostWorkingStatusChecking is returned from WorkingStatus() if the host is
	// still determining if it is working, that is, if settings calls are
	// incrementing.
	HostWorkingStatusChecking = HostWorkingStatus("checking")

	// HostWorkingStatusNotWorking is returned from WorkingStatus() if the host
	// has not received any settings calls over the duration of
	// workingStatusFrequency.
	HostWorkingStatusNotWorking = HostWorkingStatus("not working")

	// HostWorkingStatusWorking is returned from WorkingStatus() if the host has
	// received more than workingThreshold settings calls over the duration of
	// workingStatusFrequency.
	HostWorkingStatusWorking = HostWorkingStatus("working")
)
View Source
var (
	// ActionDelete is the specifier for a RevisionAction that deletes a
	// sector.
	ActionDelete = types.Specifier{'D', 'e', 'l', 'e', 't', 'e'}

	// ActionInsert is the specifier for a RevisionAction that inserts a
	// sector.
	ActionInsert = types.Specifier{'I', 'n', 's', 'e', 'r', 't'}

	// ActionModify is the specifier for a RevisionAction that modifies sector
	// data.
	ActionModify = types.Specifier{'M', 'o', 'd', 'i', 'f', 'y'}

	// ErrAnnNotAnnouncement indicates that the provided host announcement does
	// not use a recognized specifier, indicating that it's either not a host
	// announcement or it's not a recognized version of a host announcement.
	ErrAnnNotAnnouncement = errors.New("provided data does not form a recognized host announcement")

	// ErrAnnUnrecognizedSignature is returned when the signature in a host
	// announcement is not a type of signature that is recognized.
	ErrAnnUnrecognizedSignature = errors.New("the signature provided in the host announcement is not recognized")

	// ErrRevisionCoveredFields is returned if there is a covered fields object
	// in a transaction signature which has the 'WholeTransaction' field set to
	// true, meaning that miner fees cannot be added to the transaction without
	// invalidating the signature.
	ErrRevisionCoveredFields = errors.New("file contract revision transaction signature does not allow miner fees to be added")

	// ErrRevisionSigCount is returned when a file contract revision has the
	// wrong number of transaction signatures.
	ErrRevisionSigCount = errors.New("file contract revision has the wrong number of transaction signatures")

	// ErrStopResponse is the error returned by ReadNegotiationAcceptance when
	// it reads the StopResponse string.
	ErrStopResponse = errors.New("sender wishes to stop communicating")

	// 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'}

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

	// RPCFormContract is the specifier for forming a contract with a host.
	RPCFormContract = types.Specifier{'F', 'o', 'r', 'm', 'C', 'o', 'n', 't', 'r', 'a', 'c', 't', 2}

	// RPCRenewContract is the specifier to renewing an existing contract.
	RPCRenewContract = types.Specifier{'R', 'e', 'n', 'e', 'w', 'C', 'o', 'n', 't', 'r', 'a', 'c', 't', 2}

	// RPCReviseContract is the specifier for revising an existing file
	// contract.
	RPCReviseContract = types.Specifier{'R', 'e', 'v', 'i', 's', 'e', 'C', 'o', 'n', 't', 'r', 'a', 'c', 't', 2}

	// RPCSettings is the specifier for requesting settings from the host.
	RPCSettings = types.Specifier{'S', 'e', 't', 't', 'i', 'n', 'g', 's', 2}

	// SectorSize defines how large a sector should be in bytes. The sector
	// size needs to be a power of two to be compatible with package
	// merkletree. 4MB has been chosen for the live network because large
	// sectors significantly reduce the tracking overhead experienced by the
	// renter and the host.
	SectorSize = build.Select(build.Var{
		Dev:      uint64(1 << 18),
		Standard: uint64(1 << 22),
		Testing:  uint64(1 << 12),
	}).(uint64)
)
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 set contains only duplicate transactions")

	// 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")

	// 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 given to the transaction pool is larger than the limit placed by the
	// IsStandard rules of the transaction pool.
	ErrLargeTransactionSet = errors.New("transaction set is too large for this transaction pool")

	// 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")

	// ErrIncompleteTransactions is returned if the wallet has incomplete
	// transactions being built that are using all of the current outputs, and
	// therefore the wallet is unable to spend money despite it not technically
	// being 'unconfirmed' yet.
	ErrIncompleteTransactions = errors.New("wallet has coins spent in incomplete transactions - not enough remaining coins")

	// 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")

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

	// ErrWalletShutdown is returned when a method can't continue execution due
	// to the wallet shutting down.
	ErrWalletShutdown = errors.New("wallet is shutting down")

	// ErrAddressGapLimit is return when a user tries to create a new address
	// that does not respect the address gap limit as specified in BIP 44
	ErrAddressGapLimit = errors.New("cannot create new address beyond address gap limit")
)
View Source
var ErrHostFault = errors.New("host has returned an error")

ErrHostFault is an error that is usually extended to indicate that an error is the host's fault.

View Source
var (
	// NegotiateSettingsTime establishes the minimum amount of time that the
	// connection deadline is expected to be set to when settings are being
	// requested from the host. The deadline is long enough that the connection
	// should be successful even if both parties are on Tor.
	NegotiateSettingsTime = build.Select(build.Var{
		Dev:      120 * time.Second,
		Standard: 120 * time.Second,
		Testing:  3 * time.Second,
	}).(time.Duration)
)
View Source
var ProdDependencies = new(ProductionDependencies)

ProdDependencies act as a global instance of the production dependencies to avoid having to instantiate new dependencies every time we want to pass production dependencies.

View Source
var (
	// 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 SurpassThreshold = big.NewRat(20, 100)

TODO move this back into the consensus package SurpassThreshold is a percentage that dictates how much heavier a competing chain has to be before the node will switch to mining on that chain. This is not a consensus rule. This percentage is only applied to the most recent block, not the entire chain; see blockNode.heavierThan.

If no threshold were in place, it would be possible to manipulate a block's timestamp to produce a sufficiently heavier block.

Functions

func CalculateFee

func CalculateFee(ts []types.Transaction) types.Currency

CalculateFee returns the fee-per-byte of a transaction set.

func CreateAnnouncement

func CreateAnnouncement(addr NetAddress, pk types.SiaPublicKey, sk crypto.SecretKey) (signedAnnouncement []byte, err error)

CreateAnnouncement will take a host announcement and encode it, returning the exact []byte that should be added to the arbitrary data of a transaction.

func IsHostsFault

func IsHostsFault(err error) bool

IsHostsFault indicates if a returned error is the host's fault.

func ReadNegotiationAcceptance

func ReadNegotiationAcceptance(r io.Reader) error

ReadNegotiationAcceptance reads an accept/reject response from r (usually a net.Conn). If the response is not AcceptResponse, ReadNegotiationAcceptance returns the response as an error. If the response is StopResponse, ErrStopResponse is returned, allowing for direct error comparison.

Note that since errors returned by ReadNegotiationAcceptance are newly allocated, they cannot be compared to other errors in the traditional fashion.

func SeedToString

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

SeedToString converts a wallet seed to a human friendly string.

func VerifyFileContractRevisionTransactionSignatures

func VerifyFileContractRevisionTransactionSignatures(fcr types.FileContractRevision, tsigs []types.TransactionSignature, height types.BlockHeight) error

VerifyFileContractRevisionTransactionSignatures checks that the signatures on a file contract revision are valid and cover the right fields.

func WriteNegotiationAcceptance

func WriteNegotiationAcceptance(w io.Writer) error

WriteNegotiationAcceptance writes the 'accept' response to w (usually a net.Conn).

func WriteNegotiationRejection

func WriteNegotiationRejection(w io.Writer, err error) error

WriteNegotiationRejection will write a rejection response to w (usually a net.Conn) and return the input error. If the write fails, the write error is joined with the input error.

func WriteNegotiationStop

func WriteNegotiationStop(w io.Writer) error

WriteNegotiationStop writes the 'stop' response to w (usually a net.Conn).

Types

type Allowance

type Allowance struct {
	Funds       types.Currency    `json:"funds"`
	Hosts       uint64            `json:"hosts"`
	Period      types.BlockHeight `json:"period"`
	RenewWindow types.BlockHeight `json:"renewwindow"`
}

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.

type BlockFacts

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"`
	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

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

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

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

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

	// ChildTarget defines the target of any block that would be the child
	// of the block most recently appended to the consensus set.
	ChildTarget types.Target

	// MinimumValidChildTimestamp defines the minimum allowed timestamp for
	// any block that is the child of the block most recently appended to
	// the consensus set.
	MinimumValidChildTimestamp types.Timestamp

	// Synced indicates whether or not the ConsensusSet is synced with its
	// peers.
	Synced bool

	// TryTransactionSet is an unlocked version of
	// ConsensusSet.TryTransactionSet. This allows the TryTransactionSet
	// function to be called by a subscriber during
	// ProcessConsensusChange.
	TryTransactionSet func([]types.Transaction) (ConsensusChange, error)
}

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

func (ConsensusChange) Append

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

type ConsensusChangeID crypto.Hash

ConsensusChangeID is the id of a consensus change.

type ConsensusConflict

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

func NewConsensusConflict(s string) ConsensusConflict

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

func (ConsensusConflict) Error

func (cc ConsensusConflict) Error() string

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

type ConsensusSet

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)

	// BlocksByID returns a block found for a given ID and its height, with
	// a bool to indicate whether that block exists.
	BlockByID(types.BlockID) (types.Block, types.BlockHeight, 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

	// ConsensusSetSubscribe adds a subscriber to the list of subscribers
	// and gives them every consensus change that has occurred since the
	// change with the provided id. There are a few special cases,
	// described by the ConsensusChangeX variables in this package.
	// A channel can be provided to abort the subscription process.
	ConsensusSetSubscribe(ConsensusSetSubscriber, ConsensusChangeID, <-chan struct{}) error

	// HeaderConsensusSetSubscribe adds a subscriber to the list of subscribers
	// and gives them every consensus change
	HeaderConsensusSetSubscribe(HeaderConsensusSetSubscriber, ConsensusChangeID, <-chan struct{}) error

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

	// CurrentHeader returns the latest header in the heaviest known blockchain
	CurrentHeader() types.BlockHeader

	// Flush will cause the consensus set to finish all in-progress
	// routines.
	Flush() error

	// 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)

	// HeaderUnsubscribe unsubscribe header change
	HeaderUnsubscribe(HeaderConsensusSetSubscriber)

	Db() *persist.BoltDatabase

	// SpvMode return true if the consensus set is in spv mode
	SpvMode() bool

	// SetGetWalletKeysFuc setup the function for consensus to fetch keys from wallet
	SetGetWalletKeysFunc(func() ([][]byte, error))
}

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

type ConsensusSetSubscriber

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 ContractUtility

type ContractUtility struct {
	GoodForUpload bool
	GoodForRenew  bool
	Locked        bool // Locked utilities can only be set to false.
}

ContractUtility contains metrics internal to the contractor that reflect the utility of a given contract.

type ContractorSpending

type ContractorSpending struct {
	// ContractFees are the sum of all fees in the contract. This means it
	// includes the ContractFee, TxnFee and SiafundFee
	ContractFees types.Currency `json:"contractfees"`
	// DownloadSpending is the money currently spent on downloads.
	DownloadSpending types.Currency `json:"downloadspending"`
	// StorageSpending is the money currently spent on storage.
	StorageSpending types.Currency `json:"storagespending"`
	// 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 `json:"totalallocated"`
	// UploadSpending is the money currently spent on uploads.
	UploadSpending types.Currency `json:"uploadspending"`
	// Unspent is locked-away, unspent money.
	Unspent types.Currency `json:"unspent"`
	// ContractSpendingDeprecated was renamed to TotalAllocated and always has the
	// same value as TotalAllocated.
	ContractSpendingDeprecated types.Currency `json:"contractspending"`
	// WithheldFunds are the funds from the previous period that are tied up
	// in contracts and have not been released yet
	WithheldFunds types.Currency `json:"withheldfunds"`
	// 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 types.BlockHeight `json:"releaseblock"`
	// PreviousSpending is the total spend funds from old contracts
	// that are not included in the current period spending
	PreviousSpending types.Currency `json:"previousspending"`
}

ContractorSpending contains the metrics about how much the Contractor has spent during the current billing period.

type DelayedSiacoinOutputDiff

type DelayedSiacoinOutputDiff struct {
	Direction      DiffDirection         `json:"dir"`
	ID             types.SiacoinOutputID `json:"id"`
	SiacoinOutput  types.SiacoinOutput   `json:"sco"`
	MaturityHeight types.BlockHeight     `json:"mh"`
}

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 Dependencies

type Dependencies interface {
	// AtLeastOne will return a value that is at least one. In production,
	// the value should always be one. This function is used to test the
	// idempotency of actions, so during testing sometimes the value
	// returned will be higher, causing an idempotent action to be
	// committed multiple times. If the action is truly idempotent,
	// committing it multiple times should not cause any problems or
	// changes.
	AtLeastOne() uint64

	// CreateFile gives the host the ability to create files on the
	// operating system.
	CreateFile(string) (File, error)

	// Destruct will clean up the dependencies, panicking if there are
	// unclosed resources.
	Destruct()

	// DialTimeout tries to create a tcp connection to the specified
	// address with a certain timeout.
	DialTimeout(NetAddress, time.Duration) (net.Conn, error)

	// Disrupt can be inserted in the code as a way to inject problems,
	// such as a network call that take 10 minutes or a disk write that
	// never completes. disrupt will return true if the disruption is
	// forcibly triggered. In production, disrupt will always return false.
	Disrupt(string) bool

	// Listen gives the host the ability to receive incoming connections.
	Listen(string, string) (net.Listener, error)

	// LoadFile allows the host to load a persistence structure form disk.
	LoadFile(persist.Metadata, interface{}, string) error

	// LookupIP resolves a hostname to a number of IP addresses. If an IP
	// address is provided as an argument it will just return that IP.
	LookupIP(string) ([]net.IP, error)

	// MkdirAll gives the host the ability to create chains of folders
	// within the filesystem.
	MkdirAll(string, os.FileMode) error

	// NewLogger creates a logger that the host can use to log messages and
	// write critical statements.
	NewLogger(string) (*persist.Logger, error)

	// OpenDatabase creates a database that the host can use to interact
	// with large volumes of persistent data.
	OpenDatabase(persist.Metadata, string) (*persist.BoltDatabase, error)

	// OpenFile opens a file for the host.
	OpenFile(string, int, os.FileMode) (File, error)

	// Resolver returns a Resolver which can resolve hostnames to IPs.
	Resolver() Resolver

	// RandRead fills the input bytes with random data.
	RandRead([]byte) (int, error)

	// ReadFile reads a file in full from the filesystem.
	ReadFile(string) ([]byte, error)

	// RemoveFile removes a file from file filesystem.
	RemoveFile(string) error

	// RenameFile renames a file on disk to another name.
	RenameFile(string, string) error

	// SaveFileSync writes JSON encoded data to disk and syncs the file
	// afterwards.
	SaveFileSync(persist.Metadata, interface{}, string) error

	// Sleep blocks the calling thread for at least the specified duration.
	Sleep(time.Duration)

	// Symlink creates a sym link between a source and a destination.
	Symlink(s1, s2 string) error

	// WriteFile writes data to the filesystem using the provided filename.
	WriteFile(string, []byte, os.FileMode) error
}

Dependencies defines dependencies used by all of Sia's modules. Custom dependencies can be created to inject certain behavior during testing.

type DiffDirection

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 DownloadAction

type DownloadAction struct {
	MerkleRoot crypto.Hash
	Offset     uint64
	Length     uint64
}

A DownloadAction is a description of a download that the renter would like to make. The MerkleRoot indicates the root of the sector, the offset indicates what portion of the sector is being downloaded, and the length indicates how many bytes should be grabbed starting from the offset.

type DownloadInfo

type DownloadInfo struct {
	Destination     string `json:"destination"`     // The destination of the download.
	DestinationType string `json:"destinationtype"` // Can be "file", "memory buffer", or "http stream".
	Length          uint64 `json:"length"`          // The length requested for the download.
	Offset          uint64 `json:"offset"`          // The offset within the siafile requested for the download.
	HyperspacePath  string `json:"hyperspacepath"`  // The hyperspacepath of the file used for the download.

	Completed            bool      `json:"completed"`            // Whether or not the download has completed.
	EndTime              time.Time `json:"endtime"`              // The time when the download fully completed.
	Error                string    `json:"error"`                // Will be the empty string unless there was an error.
	Received             uint64    `json:"received"`             // Amount of data confirmed and decoded.
	StartTime            time.Time `json:"starttime"`            // The time when the download was started.
	StartTimeUnix        int64     `json:"starttimeunix"`        // The time when the download was started in unix format.
	TotalDataTransferred uint64    `json:"totaldatatransferred"` // Total amount of data transferred, including negotiation, etc.
}

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

type EncryptionManager

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.CipherKey) (Seed, error)

	// Reset will reset the wallet, clearing the database and returning it to
	// the unencrypted state. Reset can only be called on a wallet that has
	// already been encrypted.
	Reset() 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, error)

	// InitFromSeed functions like Encrypt, but using a specified seed.
	// Unlike Encrypt, the blockchain will be scanned to determine the
	// seed's progress. For this reason, InitFromSeed should not be called
	// until the blockchain is fully synced.
	InitFromSeed(masterKey crypto.CipherKey, seed Seed) error

	// 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.CipherKey) error

	// ChangeKey changes the wallet's materKey from masterKey to newKey,
	// re-encrypting the wallet with the provided key.
	ChangeKey(masterKey crypto.CipherKey, newKey crypto.CipherKey) error

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

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

type ErasureCoder

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)

	// EncodeShards encodes the input data like Encode but accepts an already
	// sharded input.
	EncodeShards(data [][]byte, pieceSize uint64) ([][]byte, error)

	// Recover recovers the original data from pieces 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

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)

	// LatestBlockFacts returns the block facts of the last block
	// in the explorer's database.
	LatestBlockFacts() BlockFacts

	// 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

	// PendingTransactions gets the list of transactions currently in the mempool
	// These are pruned as transactions are confirmed or reverted, so this should
	// only be used as a snapshot
	PendingTransactions() []types.Transaction

	//HashType returns the type of a hash as a string representation.
	HashType(crypto.Hash) (string, error)

	// 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

	Close() error
}

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

type File

type File interface {
	io.ReadWriteCloser
	Name() string
	ReadAt([]byte, int64) (int, error)
	Sync() error
	Truncate(int64) error
	WriteAt([]byte, int64) (int, error)
}

File implements all of the methods that can be called on an os.File.

type FileContractDiff

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 {
	AccessTime     time.Time         `json:"accesstime"`
	Available      bool              `json:"available"`
	ChangeTime     time.Time         `json:"changetime"`
	CipherType     string            `json:"ciphertype"`
	CreateTime     time.Time         `json:"createtime"`
	Expiration     types.BlockHeight `json:"expiration"`
	Filesize       uint64            `json:"filesize"`
	LocalPath      string            `json:"localpath"`
	ModTime        time.Time         `json:"modtime"`
	OnDisk         bool              `json:"ondisk"`
	Recoverable    bool              `json:"recoverable"`
	Redundancy     float64           `json:"redundancy"`
	Renewing       bool              `json:"renewing"`
	HyperspacePath string            `json:"hyperspacepath"`
	UploadedBytes  uint64            `json:"uploadedbytes"`
	UploadProgress float64           `json:"uploadprogress"`
}

FileInfo provides information about a file.

type FileUploadParams

type FileUploadParams struct {
	Source         string
	HyperspacePath string
	ErasureCode    ErasureCoder
	Overwrite      bool
}

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

	// DiscoverAddress discovers and returns the current public IP address
	// of the gateway. Contrary to Address, DiscoverAddress is blocking and
	// might take multiple minutes to return. A channel to cancel the
	// discovery can be supplied optionally.
	DiscoverAddress(cancel <-chan struct{}) (NetAddress, error)

	// ForwardPort adds a port mapping to the router. It will block until
	// the mapping is established or until it is interrupted by a shutdown.
	ForwardPort(port string) error

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

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

	// RandomPeer returns a random peer currently connected to the Gateway.
	RandomPeer() (Peer, error)

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

	// UnregisterRPC unregisters an RPC and removes all references to the RPCFunc
	// supplied in the corresponding RegisterRPC call. References to RPCFuncs
	// registered with RegisterConnectCall are not removed and should be removed
	// with UnregisterConnectCall. If the RPC does not exist no action is taken.
	UnregisterRPC(string)

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

	// UnregisterConnectCall unregisters an RPC and removes all references to the
	// RPCFunc supplied in the corresponding RegisterConnectCall call. References
	// to RPCFuncs registered with RegisterRPC are not removed and should be
	// removed with UnregisterRPC. If the RPC does not exist no action is taken.
	UnregisterConnectCall(string)

	// 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)

	// Online returns true if the gateway is connected to remote hosts
	Online() bool

	// 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 HeaderConsensusChange

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

	// RevertedBlockHeaders
	RevertedBlockHeaders []ProcessedBlockHeader

	// AppliedBlockHeaders
	AppliedBlockHeaders []ProcessedBlockHeader

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

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

	// Synced indicates whether or not the ConsensusSet is synced with its
	// peers.
	Synced bool

	// GetSiacoinOutputDiff will return the outputdiffs requested
	GetSiacoinOutputDiff func(types.BlockID, DiffDirection) ([]SiacoinOutputDiff, error)

	// GetBlockByID will return the block requested
	GetBlockByID func(types.BlockID) (types.Block, bool)

	// TryTransactionSet is an unlocked version of
	// ConsensusSet.TryTransactionSet. This allows the TryTransactionSet
	// function to be called by a subscriber during
	// ProcessConsensusChange.
	TryTransactionSet func([]types.Transaction) (ConsensusChange, error)
}

HeaderConsensusChange is the header consensus change

func (*HeaderConsensusChange) FetchSpaceCashOutputDiffs added in v0.2.1

func (hcc *HeaderConsensusChange) FetchSpaceCashOutputDiffs(addresses [][]byte) ([]SiacoinOutputDiff, error)

FetchSpaceCashOutputDiffs retrieves output diffs relevant to the addresses given from the header consensus change. If the output diffs are in block connected to the header but the block has not yet been downloaded, FetchSpaceCashOutputDiffs will download the block, parse it for the scods, and then return the result.

type HeaderConsensusSetSubscriber

type HeaderConsensusSetSubscriber interface {
	// In addition to a HeaderConsensusChange, returns a callback where a
	// user can retrieve a set of SiacoinOutputDiffs - reverted or
	// otherwise
	ProcessHeaderConsensusChange(HeaderConsensusChange)
}

HeaderConsensusSetSubscriber sends a consensus update to subscriber

type Host

type Host interface {
	// Announce submits a host announcement to the blockchain.
	Announce() error

	// AnnounceAddress submits an announcement using the given address.
	AnnounceAddress(NetAddress) error

	// ExternalSettings returns the settings of the host as seen by an
	// untrusted node querying the host for settings.
	ExternalSettings() HostExternalSettings

	// FinancialMetrics returns the financial statistics of the host.
	FinancialMetrics() HostFinancialMetrics

	// InternalSettings returns the host's internal settings, including
	// potentially private or sensitive information.
	InternalSettings() HostInternalSettings

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

	// PublicKey returns the public key of the host.
	PublicKey() types.SiaPublicKey

	// SetInternalSettings sets the hosting parameters of the host.
	SetInternalSettings(HostInternalSettings) error

	// StorageObligations returns the set of storage obligations held by
	// the host.
	StorageObligations() []StorageObligation

	// ConnectabilityStatus returns the connectability status of the host, that
	// is, if it can connect to itself on the configured NetAddress.
	ConnectabilityStatus() HostConnectabilityStatus

	// WorkingStatus returns the working state of the host, determined by if
	// settings calls are increasing.
	WorkingStatus() HostWorkingStatus

	// The storage manager provides an interface for adding and removing
	// storage folders and data sectors to the host.
	StorageManager
}

A 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 {
	Specifier  types.Specifier
	NetAddress NetAddress
	PublicKey  types.SiaPublicKey
}

HostAnnouncement is an announcement by the host that appears in the blockchain. 'Specifier' is always 'PrefixHostAnnouncement'. The announcement is always followed by a signature from the public key of the whole announcement.

func DecodeAnnouncementForAnnouncement

func DecodeAnnouncementForAnnouncement(fullAnnouncement []byte) (ha HostAnnouncement, err error)

DecodeAnnouncementForAnnouncement decodes announcement bytes into a host announcement, verifying the prefix and the signature. and return the struct

func FindHostAnnouncementsFromBlock

func FindHostAnnouncementsFromBlock(b types.Block) (has []HostAnnouncement)

FindHostAnnouncementsFromBlock extract announcements from block

type HostConnectabilityStatus

type HostConnectabilityStatus string

HostConnectabilityStatus reports the connectability state of a host. Can be one of "checking", "connectable", or "not connectable"

type HostDBEntry

type HostDBEntry struct {
	HostExternalSettings

	// FirstSeen is the last block height at which this host was announced.
	FirstSeen types.BlockHeight `json:"firstseen"`

	// 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"`

	HistoricFailedInteractions     float64 `json:"historicfailedinteractions"`
	HistoricSuccessfulInteractions float64 `json:"historicsuccessfulinteractions"`
	RecentFailedInteractions       float64 `json:"recentfailedinteractions"`
	RecentSuccessfulInteractions   float64 `json:"recentsuccessfulinteractions"`

	LastHistoricUpdate types.BlockHeight

	// The public key of the host, stored separately to minimize risk of certain
	// MitM based vulnerabilities.
	PublicKey types.SiaPublicKey `json:"publickey"`
}

A HostDBEntry represents one host entry in the Renter's host DB. It aggregates the host's external settings and metrics with its public key.

type HostDBScan

type HostDBScan struct {
	Timestamp time.Time `json:"timestamp"`
	Success   bool      `json:"success"`
}

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 HostExternalSettings

type HostExternalSettings struct {
	// MaxBatchSize indicates the maximum size in bytes that a batch is
	// allowed to be. A batch is an array of revision actions; each
	// revision action can have a different number of bytes, depending on
	// the action, so the number of revision actions allowed depends on the
	// sizes of each.
	AcceptingContracts   bool              `json:"acceptingcontracts"`
	MaxDownloadBatchSize uint64            `json:"maxdownloadbatchsize"`
	MaxDuration          types.BlockHeight `json:"maxduration"`
	MaxReviseBatchSize   uint64            `json:"maxrevisebatchsize"`
	NetAddress           NetAddress        `json:"netaddress"`
	RemainingStorage     uint64            `json:"remainingstorage"`
	SectorSize           uint64            `json:"sectorsize"`
	TotalStorage         uint64            `json:"totalstorage"`
	UnlockHash           types.UnlockHash  `json:"unlockhash"`
	WindowSize           types.BlockHeight `json:"windowsize"`

	// Collateral is the amount of collateral that the host will put up for
	// storage in 'bytes per block', as an assurance to the renter that the
	// host really is committed to keeping the file. But, because the file
	// contract is created with no data available, this does leave the host
	// exposed to an attack by a wealthy renter whereby the renter causes
	// the host to lockup in-advance a bunch of funds that the renter then
	// never uses, meaning the host will not have collateral for other
	// clients.
	//
	// MaxCollateral indicates the maximum number of coins that a host is
	// willing to put into a file contract.
	Collateral    types.Currency `json:"collateral"`
	MaxCollateral types.Currency `json:"maxcollateral"`

	// ContractPrice is the number of coins that the renter needs to pay to
	// the host just to open a file contract with them. Generally, the
	// price is only to cover the siacoin fees that the host will suffer
	// when submitting the file contract revision and storage proof to the
	// blockchain.
	//
	// The storage price is the cost per-byte-per-block in hastings of
	// storing data on the host.
	//
	// 'Download' bandwidth price is the cost per byte of downloading data
	// from the host.
	//
	// 'Upload' bandwidth price is the cost per byte of uploading data to
	// the host.
	ContractPrice          types.Currency `json:"contractprice"`
	DownloadBandwidthPrice types.Currency `json:"downloadbandwidthprice"`
	StoragePrice           types.Currency `json:"storageprice"`
	UploadBandwidthPrice   types.Currency `json:"uploadbandwidthprice"`

	// Because the host has a public key, and settings are signed, and
	// because settings may be MITM'd, settings need a revision number so
	// that a renter can compare multiple sets of settings and determine
	// which is the most recent.
	RevisionNumber uint64 `json:"revisionnumber"`
	Version        string `json:"version"`
}

HostExternalSettings 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 HostFinancialMetrics

type HostFinancialMetrics struct {
	// Every time a renter forms a contract with a host, a contract fee is
	// paid by the renter. These stats track the total contract fees.
	ContractCount                 uint64         `json:"contractcount"`
	ContractCompensation          types.Currency `json:"contractcompensation"`
	PotentialContractCompensation types.Currency `json:"potentialcontractcompensation"`

	// Metrics related to storage proofs, collateral, and submitting
	// transactions to the blockchain.
	LockedStorageCollateral types.Currency `json:"lockedstoragecollateral"`
	LostRevenue             types.Currency `json:"lostrevenue"`
	LostStorageCollateral   types.Currency `json:"loststoragecollateral"`
	PotentialStorageRevenue types.Currency `json:"potentialstoragerevenue"`
	RiskedStorageCollateral types.Currency `json:"riskedstoragecollateral"`
	StorageRevenue          types.Currency `json:"storagerevenue"`
	TransactionFeeExpenses  types.Currency `json:"transactionfeeexpenses"`

	// Bandwidth financial metrics.
	DownloadBandwidthRevenue          types.Currency `json:"downloadbandwidthrevenue"`
	PotentialDownloadBandwidthRevenue types.Currency `json:"potentialdownloadbandwidthrevenue"`
	PotentialUploadBandwidthRevenue   types.Currency `json:"potentialuploadbandwidthrevenue"`
	UploadBandwidthRevenue            types.Currency `json:"uploadbandwidthrevenue"`
}

HostFinancialMetrics provides financial statistics for the host, including money that is locked in contracts. Though verbose, these statistics should provide a clear picture of where the host's money is currently being used. The front end can consolidate stats where desired. Potential revenue refers to revenue that is available in a file contract for which the file contract window has not yet closed.

type HostInternalSettings

type HostInternalSettings struct {
	AcceptingContracts   bool              `json:"acceptingcontracts"`
	MaxDownloadBatchSize uint64            `json:"maxdownloadbatchsize"`
	MaxDuration          types.BlockHeight `json:"maxduration"`
	MaxReviseBatchSize   uint64            `json:"maxrevisebatchsize"`
	NetAddress           NetAddress        `json:"netaddress"`
	WindowSize           types.BlockHeight `json:"windowsize"`

	Collateral       types.Currency `json:"collateral"`
	CollateralBudget types.Currency `json:"collateralbudget"`
	MaxCollateral    types.Currency `json:"maxcollateral"`

	MinContractPrice          types.Currency `json:"mincontractprice"`
	MinDownloadBandwidthPrice types.Currency `json:"mindownloadbandwidthprice"`
	MinStoragePrice           types.Currency `json:"minstorageprice"`
	MinUploadBandwidthPrice   types.Currency `json:"minuploadbandwidthprice"`
}

HostInternalSettings contains a list of settings that can be changed.

type HostNetworkMetrics

type HostNetworkMetrics struct {
	DownloadCalls     uint64 `json:"downloadcalls"`
	ErrorCalls        uint64 `json:"errorcalls"`
	FormContractCalls uint64 `json:"formcontractcalls"`
	RenewCalls        uint64 `json:"renewcalls"`
	ReviseCalls       uint64 `json:"revisecalls"`
	SettingsCalls     uint64 `json:"settingscalls"`
	UnrecognizedCalls uint64 `json:"unrecognizedcalls"`
}

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

type HostScoreBreakdown

type HostScoreBreakdown struct {
	Score          types.Currency `json:"score"`
	ConversionRate float64        `json:"conversionrate"`

	AgeAdjustment              float64 `json:"ageadjustment"`
	BurnAdjustment             float64 `json:"burnadjustment"`
	CollateralAdjustment       float64 `json:"collateraladjustment"`
	InteractionAdjustment      float64 `json:"interactionadjustment"`
	PriceAdjustment            float64 `json:"pricesmultiplier"`
	StorageRemainingAdjustment float64 `json:"storageremainingadjustment"`
	UptimeAdjustment           float64 `json:"uptimeadjustment"`
	VersionAdjustment          float64 `json:"versionadjustment"`
}

HostScoreBreakdown provides a piece-by-piece explanation of why a host has the score that they do.

NOTE: Renters are free to use whatever scoring they feel appropriate for hosts. Some renters will outright blacklist or whitelist sets of hosts. The results provided by this struct can only be used as a guide, and may vary significantly from machine to machine.

type HostWorkingStatus

type HostWorkingStatus string

HostWorkingStatus reports the working state of a host. Can be one of "checking", "working", or "not working".

type Index

type Index interface {
	// Scan will go through every block and try to sync every block info
	Scan() error

	// Close closes the Index.
	Close() error
}

Index is a module help import info to RDB like Mysql and caculat all address coin info

type KeyManager

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, error)

	// 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)

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

	// GetAddress returns an existing coin address. This address is at an
	// index of 1 greater than the highest index seen on the blockchain.
	GetAddress() (types.UnlockConditions, 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 to encrypt the
	// recovery seed before saving it to disk.
	LoadSeed(crypto.CipherKey, 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.CipherKey, []string) error

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

	// NextAddresses returns n new coin addresses generated from the primary
	// seed.
	NextAddresses(uint64) ([]types.UnlockConditions, error)

	// PrimarySeed returns the unencrypted primary seed of the wallet,
	// along with a uint64 indicating how many addresses may be safely
	// generated from the seed.
	PrimarySeed() (Seed, uint64, error)

	// SignTransaction signs txn using secret keys known to the wallet.
	// The transaction should be complete with the exception of the
	// Signature fields of each TransactionSignature referenced by toSign.
	SignTransaction(txn *types.Transaction, toSign []crypto.Hash) error

	// SweepSeed scans the blockchain for outputs generated from seed and
	// creates a transaction that transfers them to the wallet. Note that
	// this incurs a transaction fee. It returns the total value of the
	// outputs, minus the fee.
	SweepSeed(seed Seed) (coins, funds types.Currency, err 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 MerkleRootSet

type MerkleRootSet []crypto.Hash

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

func (MerkleRootSet) MarshalJSON

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

MarshalJSON defines a JSON encoding for a MerkleRootSet.

func (*MerkleRootSet) UnmarshalJSON

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

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

type Miner

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 DecodeAnnouncement

func DecodeAnnouncement(fullAnnouncement []byte) (na NetAddress, spk types.SiaPublicKey, 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.

func (NetAddress) IsValid

func (na NetAddress) IsValid() error

IsValid is an extension to IsStdValid that also forbids the loopback address. 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 Peer

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

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

type PeerConn

type PeerConn interface {
	net.Conn
	RPCAddr() NetAddress
	Version() string
}

A PeerConn is the connection type used when communicating with peers during an RPC. It is identical to a net.Conn with the additional RPCAddr method. This method acts as an identifier for peers and is the address that the peer can be dialed on. It is also the address that should be used when calling an RPC on the peer.

type Pool

type Pool interface {
	// InternalSettings returns the pool's internal settings, including
	// potentially private or sensitive information.
	InternalSettings() PoolInternalSettings

	// SetInternalSettings sets the parameters of the pool.
	SetInternalSettings(PoolInternalSettings) error

	// Close closes the Pool.
	Close() error

	// Returns the number of open tcp connections the pool currently is servicing
	NumConnections() int

	// Returns the number of open tcp connections the pool has opened since startup
	NumConnectionsOpened() uint64
}

A Pool accepts incoming target solutions, tracks the share (an attempted solution), checks to see if we have a new block, and if so, pays all the share submitters, proportionally based on their share of the solution (minus a percentage to the pool operator )

type PoolBlock

type PoolBlock struct {
	BlockNumber uint64    `json:"blocknumber"`
	BlockHeight uint64    `json:"blockheight"`
	BlockReward string    `json:"blockreward"`
	BlockTime   time.Time `json:"blocktime"`
	BlockStatus string    `json:"blockstatus"`
}

PoolBlock represents a block mined by the pool

type PoolBlockClient

type PoolBlockClient struct {
	ClientName       string  `json:"clientname"`
	ClientPercentage float64 `json:"clientpercentage"`
	ClientReward     string  `json:"clientreward"`
}

PoolBlockClient represents a block mined by the pool

type PoolClient

type PoolClient struct {
	ClientName  string       `json:"clientname"`
	Balance     string       `json:"balance"`
	BlocksMined uint64       `json:"blocksminer"`
	Workers     []PoolWorker `json:"workers"`
}

PoolClient contains summary info for a mining client

type PoolClientTransaction

type PoolClientTransaction struct {
	BalanceChange string    `json:"balancechange"`
	TxTime        time.Time `json:"txtime"`
	Memo          string    `json:"memo"`
}

PoolClientTransaction represents a mining client transaction

type PoolConnectabilityStatus

type PoolConnectabilityStatus string

PoolConnectabilityStatus reports the connectability state of a pool. Can be one of "checking", "connectable", or "not connectable"

type PoolInternalSettings

type PoolInternalSettings struct {
	PoolNetworkPort  int               `json:"networkport"`
	PoolName         string            `json:"name"`
	PoolID           uint64            `json:"poolid"`
	PoolDBConnection string            `json:"dbconnection"`
	PoolDBName       string            `json:"dbname"`
	PoolWallet       types.UnlockHash  `json:"poolwallet"`
	Luck             bool              `json:"luck"`
	Difficulty       map[string]string `json:"difficulty"`
}

PoolInternalSettings contains a list of settings that can be changed.

type PoolWorker

type PoolWorker struct {
	WorkerName             string    `json:"workername"`
	LastShareTime          time.Time `json:"lastsharetime"`
	CurrentDifficulty      float64   `json:"currentdifficulty"`
	CumulativeDifficulty   float64   `json:"cumulativedifficulty"`
	SharesThisBlock        uint64    `json:"sharesthisblock"`
	InvalidSharesThisBlock uint64    `json:"invalidsharesthisblock"`
	StaleSharesThisBlock   uint64    `json:"stalesharesthisblock"`
	BlocksFound            uint64    `json:"blocksfound"`
}

PoolWorker represents a mining client worker

type PoolWorkingStatus

type PoolWorkingStatus string

PoolWorkingStatus reports the working state of a pool. Can be one of "starting", "accepting", or "not accepting".

type ProcessedBlockHeader

type ProcessedBlockHeader struct {
	BlockHeader               types.BlockHeader
	Height                    types.BlockHeight
	Depth                     types.Target
	ChildTarget               types.Target
	GCSFilter                 types.GCSFilter
	SiacoinOutputDiffs        []SiacoinOutputDiff
	DelayedSiacoinOutputDiffs []DelayedSiacoinOutputDiff
	Announcements             []HostAnnouncement
}

ProcessedBlockHeader is a header with more info

func (*ProcessedBlockHeader) ChildDepth

func (pbh *ProcessedBlockHeader) ChildDepth() types.Target

ChildDepth returns the depth of a headerNode's child nodes. The depth is the "sum" of the current depth and current difficulty. See target.Add for more detailed information.

func (ProcessedBlockHeader) ForSend

ForSend will only reserve BlockHeader, GCSFilter, Announcements

func (*ProcessedBlockHeader) HeavierThan

func (pbh *ProcessedBlockHeader) HeavierThan(cmp *ProcessedBlockHeader) bool

HeavierThan compare processed header difficulty

type ProcessedInput

type ProcessedInput struct {
	ParentID       types.OutputID   `json:"parentid"`
	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 type is 'SiacoinInput'.

type ProcessedOutput

type ProcessedOutput struct {
	ID             types.OutputID    `json:"id"`
	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', '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 become available immediately. ClaimInputs and MinerPayouts become available after 144 confirmations.

type ProcessedTransaction

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 ProductionDependencies

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

ProductionDependencies are the dependencies used in a Release or Debug production build.

func (*ProductionDependencies) AtLeastOne

func (*ProductionDependencies) AtLeastOne() uint64

AtLeastOne will return a value that is equal to 1 if debugging is disabled. If debugging is enabled, a higher value may be returned.

func (*ProductionDependencies) CreateFile

func (pd *ProductionDependencies) CreateFile(s string) (File, error)

CreateFile gives the host the ability to create files on the operating system.

func (*ProductionDependencies) Destruct

func (pd *ProductionDependencies) Destruct()

Destruct checks that all resources have been cleaned up correctly.

func (*ProductionDependencies) DialTimeout

func (*ProductionDependencies) DialTimeout(addr NetAddress, timeout time.Duration) (net.Conn, error)

DialTimeout creates a tcp connection to a certain address with the specified timeout.

func (*ProductionDependencies) Disrupt

Disrupt can be used to inject specific behavior into a module by overwriting it using a custom dependency.

func (*ProductionDependencies) Listen

func (*ProductionDependencies) Listen(s1, s2 string) (net.Listener, error)

Listen gives the host the ability to receive incoming connections.

func (*ProductionDependencies) LoadFile

func (*ProductionDependencies) LoadFile(meta persist.Metadata, data interface{}, filename string) error

LoadFile loads JSON encoded data from a file.

func (*ProductionDependencies) LookupIP

func (*ProductionDependencies) LookupIP(host string) ([]net.IP, error)

LookupIP resolves a hostname to a number of IP addresses. If an IP address is provided as an argument it will just return that IP.

func (*ProductionDependencies) MkdirAll

func (*ProductionDependencies) MkdirAll(s string, fm os.FileMode) error

MkdirAll gives the host the ability to create chains of folders within the filesystem.

func (*ProductionDependencies) NewLogger

func (*ProductionDependencies) NewLogger(s string) (*persist.Logger, error)

NewLogger creates a logger that the host can use to log messages and write critical statements.

func (*ProductionDependencies) OpenDatabase

OpenDatabase creates a database that the host can use to interact with large volumes of persistent data.

func (*ProductionDependencies) OpenFile

func (pd *ProductionDependencies) OpenFile(s string, i int, fm os.FileMode) (File, error)

OpenFile opens a file for the contract manager.

func (*ProductionDependencies) RandRead

func (*ProductionDependencies) RandRead(b []byte) (int, error)

RandRead fills the input bytes with random data.

func (*ProductionDependencies) ReadFile

func (*ProductionDependencies) ReadFile(s string) ([]byte, error)

ReadFile reads a file from the filesystem.

func (*ProductionDependencies) RemoveFile

func (pd *ProductionDependencies) RemoveFile(s string) error

RemoveFile will remove a file from disk.

func (*ProductionDependencies) RenameFile

func (pd *ProductionDependencies) RenameFile(s1 string, s2 string) error

RenameFile renames a file on disk.

func (*ProductionDependencies) Resolver

func (*ProductionDependencies) Resolver() Resolver

Resolver returns the ProductionResolver.

func (*ProductionDependencies) SaveFileSync

func (*ProductionDependencies) SaveFileSync(meta persist.Metadata, data interface{}, filename string) error

SaveFileSync writes JSON encoded data to a file and syncs the file to disk afterwards.

func (*ProductionDependencies) Sleep

Sleep blocks the calling thread for a certain duration.

func (*ProductionDependencies) Symlink(s1, s2 string) error

Symlink creates a symlink between a source and a destination file.

func (*ProductionDependencies) WriteFile

func (*ProductionDependencies) WriteFile(s string, b []byte, fm os.FileMode) error

WriteFile writes a file to the filesystem.

type ProductionFile

type ProductionFile struct {
	*os.File
	// contains filtered or unexported fields
}

ProductionFile is the implementation of the File interface that is used in a Release or Debug production build.

func (*ProductionFile) Close

func (pf *ProductionFile) Close() error

Close will close a file, checking whether the file handle is open somewhere else before closing completely. This check is performed on Windows but not Linux, therefore a mock is used to ensure that linux testing picks up potential problems that would be seen on Windows.

type ProductionResolver

type ProductionResolver struct{}

ProductionResolver is the hostname resolver used in production builds.

func (ProductionResolver) LookupIP

func (ProductionResolver) LookupIP(host string) ([]net.IP, error)

LookupIP is a passthrough function to net.LookupIP. In testing builds it returns a random IP.

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 provides the list of hosts that the renter is selecting,
	// sorted by preference.
	ActiveHosts() []HostDBEntry

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

	// Close closes the Renter.
	Close() error

	// CancelContract cancels a specific contract of the renter.
	CancelContract(id types.FileContractID) error

	// Contracts returns the staticContracts of the renter's hostContractor.
	Contracts() []RenterContract

	// OldContracts returns the oldContracts of the renter's hostContractor.
	OldContracts() []RenterContract

	// ContractUtility provides the contract utility for a given host key.
	ContractUtility(pk types.SiaPublicKey) (ContractUtility, bool)

	// CurrentPeriod returns the height at which the current allowance period
	// began.
	CurrentPeriod() types.BlockHeight

	// PeriodSpending returns the amount spent on contracts in the current
	// billing period.
	PeriodSpending() ContractorSpending

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

	// Download performs a download according to the parameters passed, including
	// downloads of `offset` and `length` type.
	Download(params RenterDownloadParameters) error

	// Download performs a download according to the parameters passed without
	// blocking, including downloads of `offset` and `length` type.
	DownloadAsync(params RenterDownloadParameters) error

	// ClearDownloadHistory clears the download history of the renter
	// inclusive for before and after times.
	ClearDownloadHistory(after, before time.Time) error

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

	// File returns information on specific file queried by user
	File(siaPath string) (FileInfo, error)

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

	// Host provides the DB entry and score breakdown for the requested host.
	Host(pk types.SiaPublicKey) (HostDBEntry, bool)

	// InitialScanComplete returns a boolean indicating if the initial scan of the
	// hostdb is completed.
	InitialScanComplete() (bool, error)

	// 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)

	// PriceEstimation estimates the cost in siacoins of performing various
	// storage and data operations.
	PriceEstimation() RenterPriceEstimation

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

	// EstimateHostScore will return the score for a host with the provided
	// settings, assuming perfect age and uptime adjustments
	EstimateHostScore(entry HostDBEntry) HostScoreBreakdown

	// ScoreBreakdown will return the score for a host db entry using the
	// hostdb's weighting algorithm.
	ScoreBreakdown(entry HostDBEntry) HostScoreBreakdown

	// Settings returns the Renter's current settings.
	Settings() RenterSettings

	// SetSettings sets the Renter's settings.
	SetSettings(RenterSettings) error

	// SetFileTrackingPath sets the on-disk location of an uploaded file to a
	// new value. Useful if files need to be moved on disk.
	SetFileTrackingPath(siaPath, 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)

	// Streamer creates a io.ReadSeeker that can be used to stream downloads
	// from the Sia network and also returns the fileName of the streamed
	// resource.
	Streamer(siaPath string) (string, io.ReadSeeker, error)

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

	// CreateDir creates a directory for the renter
	CreateDir(siaPath string) error
}

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

type RenterContract

type RenterContract struct {
	ID            types.FileContractID
	HostPublicKey types.SiaPublicKey
	Transaction   types.Transaction

	StartHeight types.BlockHeight
	EndHeight   types.BlockHeight

	// 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
	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.
	ContractFee types.Currency

	TxnFee types.Currency
}

A RenterContract contains metadata about a file contract. It is read-only; modifying a RenterContract does not modify the actual file contract.

type RenterDownloadParameters

type RenterDownloadParameters struct {
	Async          bool
	Httpwriter     io.Writer
	Length         uint64
	Offset         uint64
	HyperspacePath string
	Destination    string
}

RenterDownloadParameters defines the parameters passed to the Renter's Download method.

type RenterPriceEstimation

type RenterPriceEstimation struct {
	// The cost of downloading 1 TB of data.
	DownloadTerabyte types.Currency `json:"downloadterabyte"`

	// The cost of forming a set of contracts using the defaults.
	FormContracts types.Currency `json:"formcontracts"`

	// The cost of storing 1 TB for a month, including redundancy.
	StorageTerabyteMonth types.Currency `json:"storageterabytemonth"`

	// The cost of consuming 1 TB of upload bandwidth from the host, including
	// redundancy.
	UploadTerabyte types.Currency `json:"uploadterabyte"`
}

RenterPriceEstimation contains a bunch of files estimating the costs of various operations on the network.

type RenterSettings

type RenterSettings struct {
	Allowance        Allowance `json:"allowance"`
	MaxUploadSpeed   int64     `json:"maxuploadspeed"`
	MaxDownloadSpeed int64     `json:"maxdownloadspeed"`
	StreamCacheSize  uint64    `json:"streamcachesize"`
}

RenterSettings control the behavior of the Renter.

type Resolver

type Resolver interface {
	LookupIP(string) ([]net.IP, error)
}

Resolver is an interface that allows resolving a hostname into IP addresses.

type RevisionAction

type RevisionAction struct {
	Type        types.Specifier
	SectorIndex uint64
	Offset      uint64
	Data        []byte
}

A RevisionAction is a description of an edit to be performed on a file contract. Three types are allowed, 'ActionDelete', 'ActionInsert', and 'ActionModify'. ActionDelete just takes a sector index, indicating which sector is going to be deleted. ActionInsert takes a sector index, and a full sector of data, indicating that a sector at the index should be inserted with the provided data. 'Modify' revises the sector at the given index, rewriting it with the provided data starting from the 'offset' within the sector.

Modify could be simulated with an insert and a delete, however an insert requires a full sector to be uploaded, and a modify can be just a few kb, which can be significantly faster.

type Seed

type Seed [crypto.EntropySize]byte

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

func StringToSeed

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

StringToSeed converts a string to a wallet seed.

type SiacoinOutputDiff

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 StorageFolderMetadata

type StorageFolderMetadata struct {
	Capacity          uint64 `json:"capacity"`          // bytes
	CapacityRemaining uint64 `json:"capacityremaining"` // bytes
	Index             uint16 `json:"index"`
	Path              string `json:"path"`

	// Below are statistics about the filesystem. FailedReads and
	// FailedWrites are only incremented if the filesystem is returning
	// errors when operations are being performed. A large number of
	// FailedWrites can indicate that more space has been allocated on a
	// drive than is physically available. A high number of failures can
	// also indicate disk trouble.
	FailedReads      uint64 `json:"failedreads"`
	FailedWrites     uint64 `json:"failedwrites"`
	SuccessfulReads  uint64 `json:"successfulreads"`
	SuccessfulWrites uint64 `json:"successfulwrites"`

	// Certain operations on a storage folder can take a long time (Add,
	// Remove, and Resize). The fields below indicate the progress of any
	// long running operations that might be under way in the storage
	// folder. Progress is always reported in bytes.
	ProgressNumerator   uint64
	ProgressDenominator uint64
}

StorageFolderMetadata contains metadata about a storage folder that is tracked by the storage folder manager.

type StorageManager

type StorageManager interface {
	// AddSector will add a sector to the storage manager. If the sector
	// already exists, a virtual sector will be added, meaning that the
	// 'sectorData' will be ignored and no new disk space will be consumed.
	// The expiry height is used to track what height the sector can be
	// safely deleted at, though typically the host will manually delete
	// the sector before the expiry height. The same sector can be added
	// multiple times at different expiry heights, and the storage manager
	// is expected to only store the data once.
	AddSector(sectorRoot crypto.Hash, sectorData []byte) error

	// AddSectorBatch is a performance optimization over AddSector when
	// adding a bunch of virtual sectors. It is necessary because otherwise
	// potentially thousands or even tens-of-thousands of fsync calls would
	// need to be made in serial, which would prevent renters from ever
	// successfully renewing.
	AddSectorBatch(sectorRoots []crypto.Hash) error

	// AddStorageFolder adds a storage folder to the manager. The manager
	// may not check that there is enough space available on-disk to
	// support as much storage as requested, though the manager should
	// gracefully handle running out of storage unexpectedly.
	AddStorageFolder(path string, size uint64) error

	// The storage manager needs to be able to shut down.
	Close() error

	// DeleteSector deletes a sector, meaning that the manager will be
	// unable to upload that sector and be unable to provide a storage
	// proof on that sector. DeleteSector is for removing the data
	// entirely, and will remove instances of the sector appearing at all
	// heights. The primary purpose of DeleteSector is to comply with legal
	// requests to remove data.
	DeleteSector(sectorRoot crypto.Hash) error

	// ReadSector will read a sector from the storage manager, returning the
	// bytes that match the input sector root.
	ReadSector(sectorRoot crypto.Hash) ([]byte, error)

	// RemoveSector will remove a sector from the storage manager. The
	// height at which the sector expires should be provided, so that the
	// auto-expiry information for that sector can be properly updated.
	RemoveSector(sectorRoot crypto.Hash) error

	// RemoveSectorBatch is a non-ACID performance optimization to remove a
	// ton of sectors from the storage manager all at once. This is
	// necessary when clearing out an entire contract from the host.
	RemoveSectorBatch(sectorRoots []crypto.Hash) error

	// RemoveStorageFolder will remove a storage folder from the manager.
	// All storage on the folder will be moved to other storage folders,
	// meaning that no data will be lost. If the manager is unable to save
	// data, an error will be returned and the operation will be stopped. If
	// the force flag is set to true, errors will be ignored and the remove
	// operation will be completed, meaning that data will be lost.
	RemoveStorageFolder(index uint16, force bool) error

	// ResetStorageFolderHealth will reset the health statistics on a
	// storage folder.
	ResetStorageFolderHealth(index uint16) error

	// ResizeStorageFolder will grow or shrink a storage folder in the
	// manager. The manager may not check that there is enough space
	// on-disk to support growing the storage folder, but should gracefully
	// handle running out of space unexpectedly. When shrinking a storage
	// folder, any data in the folder that needs to be moved will be placed
	// into other storage folders, meaning that no data will be lost. If
	// the manager is unable to migrate the data, an error will be returned
	// and the operation will be stopped. If the force flag is set to true,
	// errors will be ignored and the resize operation completed, meaning
	// that data will be lost.
	ResizeStorageFolder(index uint16, newSize uint64, force bool) error

	// StorageFolders will return a list of storage folders tracked by the
	// manager.
	StorageFolders() []StorageFolderMetadata
}

A StorageManager is responsible for managing storage folders and sectors. Sectors are the base unit of storage that gets moved between renters and hosts, and primarily is stored on the hosts.

type StorageObligation

type StorageObligation struct {
	ContractCost             types.Currency       `json:"contractcost"`
	DataSize                 uint64               `json:"datasize"`
	LockedCollateral         types.Currency       `json:"lockedcollateral"`
	ObligationId             types.FileContractID `json:"obligationid"`
	PotentialDownloadRevenue types.Currency       `json:"potentialdownloadrevenue"`
	PotentialStorageRevenue  types.Currency       `json:"potentialstoragerevenue"`
	PotentialUploadRevenue   types.Currency       `json:"potentialuploadrevenue"`
	RiskedCollateral         types.Currency       `json:"riskedcollateral"`
	SectorRootsCount         uint64               `json:"sectorrootscount"`
	TransactionFeesAdded     types.Currency       `json:"transactionfeesadded"`

	// The negotiation height specifies the block height at which the file
	// contract was negotiated. The expiration height and the proof deadline
	// are equal to the window start and window end. Between the expiration height
	// and the proof deadline, the host must submit the storage proof.
	ExpirationHeight  types.BlockHeight `json:"expirationheight"`
	NegotiationHeight types.BlockHeight `json:"negotiationheight"`
	ProofDeadLine     types.BlockHeight `json:"proofdeadline"`

	// Variables indicating whether the critical transactions in a storage
	// obligation have been confirmed on the blockchain.
	ObligationStatus    string `json:"obligationstatus"`
	OriginConfirmed     bool   `json:"originconfirmed"`
	ProofConfirmed      bool   `json:"proofconfirmed"`
	ProofConstructed    bool   `json:"proofconstructed"`
	RevisionConfirmed   bool   `json:"revisionconfirmed"`
	RevisionConstructed bool   `json:"revisionconstructed"`
}

StorageObligation contains information about a storage obligation that the host has accepted.

type StratumMiner

type StratumMiner interface {
	// Hashrate returns the hashrate of the stratum miner in hashes per second.
	Hashrate() float64

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

	// Submissions returns the number of shares the miner has submitted
	Submissions() uint64

	// StartStratumMining turns on the miner, which will endlessly work for new
	// blocks.
	StartStratumMining(server, username string)

	// StopStratumMining turns off the miner
	StopStratumMining()

	io.Closer
}

StratumMiner provides access to a stratum miner.

type TestMiner

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
	// solved.
	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)

	AddBlockWithAddress(types.UnlockHash) (types.Block, error)

	// Needs to have all other miner functions in addition to shortcuts for
	// mining blocks.
	Miner
}

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

type TransactionBuilder

type TransactionBuilder interface {
	// FundSiacoins will add a siacoin input of exactly '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

	FundContract(amount types.Currency) ([]types.SiacoinOutput, error)

	// AddParents adds a set of parents to the transaction.
	AddParents([]types.Transaction)

	// 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

	// 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'.
	AddTransactionSignature(types.TransactionSignature) uint64

	// Sign will sign any inputs added by 'FundSiacoins' 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.
	//
	// An error will be returned if there are multiple calls to 'Sign',
	// sometimes even if the first call to Sign has failed. Sign should
	// only ever be called once, and if the first signing fails, the
	// transaction should be dropped.
	Sign(wholeTransaction bool) ([]types.Transaction, error)

	// UnconfirmedParents returns any unconfirmed parents the transaction set that
	// is being built by the transaction builder could have.
	UnconfirmedParents() ([]types.Transaction, error)

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

	// ViewAdded returns all of the space cash inputs and
	// parent transactions that have been automatically added by the
	// builder. Items are returned by index.
	ViewAdded() (newParents, siacoinInputs, transactionSignatures []int)

	// Drop indicates that a transaction is no longer useful and 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 initialized 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' 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

	// Broadcast broadcasts a transaction set to all of the transaction pool's
	// peers.
	Broadcast(ts []types.Transaction)

	// Close is necessary for clean shutdown (e.g. during testing).
	Close() error

	// FeeEstimation returns an estimation for how high the transaction fee
	// needs to be per byte. The minimum recommended targets getting accepted
	// in ~3 blocks, and the maximum recommended targets getting accepted
	// immediately. Taking the average has a moderate chance of being accepted
	// within one block. The minimum has a strong chance of getting accepted
	// within 10 blocks.
	FeeEstimation() (minimumRecommended, maximumRecommended types.Currency)

	// 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()

	// Transaction returns the transaction and unconfirmed parents
	// corresponding to the provided transaction id.
	Transaction(id types.TransactionID) (txn types.Transaction, unconfirmedParents []types.Transaction, exists bool)

	// TransactionConfirmed returns true if the transaction has been seen on the
	// blockchain. Note, however, that the block containing the transaction may
	// later be invalidated by a reorg.
	TransactionConfirmed(id types.TransactionID) (bool, error)

	// 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)

	// TransactionSet returns the transaction set the provided object
	// appears in.
	TransactionSet(crypto.Hash) []types.Transaction

	// Unsubscribe removes a subscriber from the transaction pool.
	// This is necessary for clean shutdown of the miner.
	Unsubscribe(TransactionPoolSubscriber)

	// SetGetWalletKeysFuc setup the function for consensus to fetch keys from wallet
	SetGetWalletKeysFunc(func() (map[types.UnlockHash]bool, error))

	// StartSubscribeHeaders will subscribe after wallet unlock done
	StartSubscribeHeaders() error
}

A TransactionPool manages unconfirmed transactions.

type TransactionPoolDiff

type TransactionPoolDiff struct {
	AppliedTransactions  []*UnconfirmedTransactionSet
	RevertedTransactions []TransactionSetID
}

A TransactionPoolDiff indicates the adding or removal of a transaction set to the transaction pool. The transactions in the pool are not persisted, so at startup modules should assume an empty transaction pool.

type TransactionPoolSubscriber

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(*TransactionPoolDiff)
}

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 TransactionSetBuilder added in v0.2.3

type TransactionSetBuilder interface {
	// FundOutputs will aggregate enough inputs to cover the
	// total value of the outputs and the miner fee if any. A refund
	// output will be generated if necessary. All the outputs will be
	// added to the transaction being built along with a miner fee if
	// one is passed. The transaction will not be signed.
	FundOutputs(outputs []types.SiacoinOutput, fee types.Currency) error
	// FundOutput is a convenience function that does the same as FundOutputs
	// but for just one output. Beware, it creates a refund transaction for
	// each call!
	FundOutput(output types.SiacoinOutput, fee types.Currency) error

	// AddOutput adds a siacoin output to the transaction, returning
	// the index of the siacoin output within the transaction.
	AddOutput(types.SiacoinOutput) uint64
	// AddInput 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.
	AddInput(types.SiacoinInput) uint64

	// Sign will sign any inputs added by 'FundOutputs' 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.
	//
	// An error will be returned if there are multiple calls to 'Sign',
	// sometimes even if the first call to Sign has failed. Sign should
	// only ever be called once, and if the first signing fails, the
	// transaction should be dropped.
	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 and will not be
	// broadcast, and that all of the outputs can be reclaimed. 'Drop'
	// should only be used before signatures are added.
	Drop()

	// Size return the encoded size of the whole transaction set.
	Size() (size int)
}

type TransactionSetID

type TransactionSetID crypto.Hash

TransactionSetID is a type-safe wrapper for a crypto.Hash that represents the ID of an entire transaction set.

type TransmittedBlockHeader

type TransmittedBlockHeader struct {
	BlockHeader   types.BlockHeader
	GCSFilter     types.GCSFilter
	Announcements []HostAnnouncement
}

TransmittedBlockHeader is a header to send to spv peers

type UnconfirmedTransactionSet

type UnconfirmedTransactionSet struct {
	Change *ConsensusChange
	ID     TransactionSetID

	IDs          []types.TransactionID
	Sizes        []uint64
	Transactions []types.Transaction
}

UnconfirmedTransactionSet defines a new unconfirmed transaction that has been added to the transaction pool. ID is the ID of the set, IDs contains an ID for each transaction, eliminating the need to recompute it (because that's an expensive operation).

type UnspentOutput

type UnspentOutput struct {
	ID                 types.OutputID    `json:"id"`
	FundType           types.Specifier   `json:"fundtype"`
	UnlockHash         types.UnlockHash  `json:"unlockhash"`
	Value              types.Currency    `json:"value"`
	ConfirmationHeight types.BlockHeight `json:"confirmationheight"`
}

A UnspentOutput is a SiacoinOutput or SiafundOutput that the wallet is tracking.

type Wallet

type Wallet interface {
	EncryptionManager
	KeyManager

	// AddUnlockConditions adds a set of UnlockConditions to the wallet database.
	AddUnlockConditions(uc types.UnlockConditions) error

	// AddWatchAddresses instructs the wallet to begin tracking a set of
	// addresses, in addition to the addresses it was previously tracking.
	// If none of the addresses have appeared in the blockchain, the
	// unused flag may be set to true. Otherwise, the wallet must rescan
	// the blockchain to search for transactions containing the addresses.
	AddWatchAddresses(addrs []types.UnlockHash, unused bool) error

	// Close permits clean shutdown during testing and serving.
	Close() error

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

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

	// Height returns the wallet's internal processed consensus height
	Height() (types.BlockHeight, error)

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

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

	// FilteredTransactions returns all transactions meeting a variety of optional
	// filter criteria. Count specifies how many matchin transactions should be
	// returned. If count is -1, an unlimited amount of matching transactions are
	// returned. watchOnly specifies that only transactions matching watched
	// addresses should be returned. category has three possible values: "send",
	// "receive", and "". A value of "" indicates that all matching transactions
	// should be returned. A value of "send" indicates that transactions where coins
	// were sent from this wallet should be returned. A value of "receive" indicates
	// that transactions where coins were received by this wallet should be returned.
	FilteredTransactions(count uint64, watchOnly bool, category string) ([]ProcessedTransaction, error)

	// FilteredUnconfirmedTransactions returns all transactions meeting watch-only and
	// category criteria. If the watch-only filter is true, only transactions matching
	// watched addresses will be returned. If category is "", all transactions matching
	// the watch-only filter criteria will be returned. If category is "receive", only
	// transactions with a relevant output will be returned. If category is "send", only
	// transactions with a relevant input will be returned.
	FilteredUnconfirmedTransactions(watchOnly bool, category string) ([]ProcessedTransaction, error)

	// 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, error)

	// 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, error)

	// RegisterTransaction takes a transaction and its parents and returns
	// a TransactionBuilder which can be used to expand the transaction.
	RegisterTransaction(t types.Transaction, parents []types.Transaction) (TransactionBuilder, error)

	// NewTransactionSet takes a list of outputs and a tx fee and
	// returns an unsigned transaction set constructed from the wallet's
	// unspent outputs
	NewTransactionSet(outputs []types.SiacoinOutput, fee types.Currency) ([]types.Transaction, error)

	// NewTransactionSetForAddress takes a destination unlock hash, transfer amount,
	// and a tx fee, and returns an unsigned transaction set constructed from the
	// wallet's unspent outputs
	NewTransactionSetForAddress(dest types.UnlockHash, amount, fee types.Currency) ([]types.Transaction, error)

	// RemoveWatchAddresses instructs the wallet to stop tracking a set of
	// addresses and delete their associated transactions. If none of the
	// addresses have appeared in the blockchain, the unused flag may be
	// set to true. Otherwise, the wallet must rescan the blockchain to
	// rebuild its transaction history.
	RemoveWatchAddresses(addrs []types.UnlockHash, unused bool) error

	// Rescanning reports whether the wallet is currently rescanning the
	// blockchain.
	Rescanning() (bool, error)

	// Settings returns the Wallet's current settings.
	Settings() (WalletSettings, error)

	// SetSettings sets the Wallet's settings.
	SetSettings(WalletSettings) error

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

	// SendSiacoins is a tool for sending space cash 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)

	// SendSiacoinsMulti sends coins to multiple addresses.
	SendSiacoinsMulti(outputs []types.SiacoinOutput) ([]types.Transaction, error)

	// DustThreshold returns the quantity per byte below which a Currency is
	// considered to be Dust.
	DustThreshold() (types.Currency, error)

	// UnspentOutputs returns the unspent outputs tracked by the wallet.
	UnspentOutputs() ([]UnspentOutput, error)

	// UnlockConditions returns the UnlockConditions for the specified
	// address, if they are known to the wallet.
	UnlockConditions(addr types.UnlockHash) (types.UnlockConditions, error)

	// WatchAddresses returns the set of addresses that the wallet is
	// currently watching.
	WatchAddresses() ([]types.UnlockHash, error)
}

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

type WalletSettings

type WalletSettings struct {
	NoDefrag bool `json:"noDefrag"`
}

WalletSettings control the behavior of the Wallet.

type WalletTransactionID

type WalletTransactionID crypto.Hash

WalletTransactionID is a unique identifier for a wallet transaction.

func CalculateWalletTransactionID

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
Package explorer provides a glimpse into what the Sia network currently looks like.
Package explorer provides a glimpse into what the Sia network currently looks like.
Package gateway connects a Sia node to the Sia flood network.
Package gateway connects a Sia node to the Sia flood network.
Package host is an implementation of the host module, and is responsible for participating in the storage ecosystem, turning available disk space an internet bandwidth into profit for the user.
Package host is an implementation of the host module, and is responsible for participating in the storage ecosystem, turning available disk space an internet bandwidth into profit for the user.
Package miner is responsible for creating and submitting siacoin blocks
Package miner is responsible for creating and submitting siacoin blocks
Package pool is an implementation of the pool module, and is responsible for creating a mining pool, accepting incoming potential block solutions and rewarding the submitters proportionally for their shares.
Package pool is an implementation of the pool module, and is responsible for creating a mining pool, accepting incoming potential block solutions and rewarding the submitters proportionally for their shares.
Package renter is responsible for uploading and downloading files on the sia network.
Package renter is responsible for uploading and downloading files on the sia network.
contractor
Package contractor is responsible for forming and renewing file contracts with hosts.
Package contractor is responsible for forming and renewing file contracts with hosts.
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.
Package stratumminer provides some utilities and common code for specific client implementations Package stratumminer is responsible for finding valid block headers and submitting them to a stratum server Package stratumminer implements the basic stratum protocol.
Package stratumminer provides some utilities and common code for specific client implementations Package stratumminer is responsible for finding valid block headers and submitting them to a stratum server Package stratumminer implements the basic stratum protocol.

Jump to

Keyboard shortcuts

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