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
- Variables
- func CalculateFee(ts []types.Transaction) types.Currency
- func NewMnemonic(seed Seed) (string, error)
- func ReadNegotiationAcceptance(r io.Reader) error
- func WriteNegotiationAcceptance(w io.Writer) error
- func WriteNegotiationRejection(w io.Writer, err error) error
- func WriteNegotiationStop(w io.Writer) error
- type BlockCreator
- type BlockFacts
- type BlockStakeOutputDiff
- type ChainStats
- type CoinOutputDiff
- type ConsensusChange
- type ConsensusChangeID
- type ConsensusConflict
- type ConsensusSet
- type ConsensusSetSubscriber
- type DataStore
- type DelayedCoinOutputDiff
- type DiffDirection
- type EncryptionManager
- type Explorer
- type ExplorerConstants
- type Gateway
- type KeyManager
- type NetAddress
- type Peer
- type PeerConn
- type ProcessedInput
- type ProcessedOutput
- type ProcessedTransaction
- type RPCFunc
- type Seed
- type StorageFolderMetadata
- type StorageManager
- type TransactionBuilder
- type TransactionIDDiff
- type TransactionPool
- type TransactionPoolSubscriber
- type Wallet
- type WalletTransactionID
Constants ¶
const ( // DataStoreDir is the name of the subdirectory to create the persistent files DataStoreDir = "datastore" // DataStoreDatabaseSubDir is the name of the subdirectory (within the DataStoreDir) // to create the persistent redis files DataStoreDatabaseSubDir = "database" )
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" // 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 // NegotiateMaxErrorSize indicates the maximum number of bytes that can be // used to encode an error being sent during negotiation. NegotiateMaxErrorSize = 256 // 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 negoitation. NegotiateMaxTransactionSignatureSize = 2e3 // NegotiateMaxTransactionSignaturesSize defines the maximum size that a // transaction signature slice is allowed to be when being sent over the // wire during negoitation. NegotiateMaxTransactionSignaturesSize = 5e3 )
const ( // TransactionSizeLimit defines the size of the largest transaction that // will be accepted by the transaction pool according to the IsStandard // rules. TransactionSizeLimit = 16e3 // TransactionSetSizeLimit defines the largest set of dependent unconfirmed // transactions that will be accepted by the transaction pool. TransactionSetSizeLimit = 250e3 )
const ( // WalletDir is the directory that contains the wallet persistence. WalletDir = "wallet" // SeedChecksumSize is the number of bytes that are used to checksum // addresses to prevent accidental spending. SeedChecksumSize = 6 // PublicKeysPerSeed define the number of public keys that get pregenerated // for a seed at startup when searching for balances in the blockchain. PublicKeysPerSeed = 2500 // WalletSeedPreloadDepth is the number of addresses that get automatically // loaded by the wallet at startup. WalletSeedPreloadDepth = 25 )
const ( // BlockCreatorDir is the name of the directory that is used to store the BlockCreator's // persistent data. BlockCreatorDir = "blockcreator" )
const ( // ExplorerDir is the name of the directory that is typically used for the // explorer. ExplorerDir = "explorer" )
const ( // GatewayDir is the name of the directory used to store the gateway's // persistent data. GatewayDir = "gateway" )
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. TODO: check extreme condition
const ( // StorageManagerDir is standard name used for the directory that contains // all of the storage manager files. StorageManagerDir = "storagemanager" )
Variables ¶
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") // ErrBlockUnsolved indicates that a block did not meet the required POS // 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") )
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") // 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") // 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") // TransactionPoolDir is the name of the directory that is used to store // the transaction pool's persistent data. TransactionPoolDir = "transactionpool" )
var ( // ErrBadEncryptionKey is returned if the incorrect encryption key to a // file is provided. ErrBadEncryptionKey = errors.New("provided encryption key is incorrect") // ErrLowBalance is returned if the wallet does not have enough funds to // complete the desired action. ErrLowBalance = errors.New("insufficient balance") // 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") )
var ( // ErrStopResponse is the error returned by ReadNegotiationAcceptance when // it reads the StopResponse string. ErrStopResponse = errors.New("sender wishes to stop communicating") )
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 )
Functions ¶
func CalculateFee ¶
func CalculateFee(ts []types.Transaction) types.Currency
CalculateFee returns the fee-per-byte of a transaction set.
func NewMnemonic ¶ added in v0.6.0
NewMnemonic converts a wallet seed to a mnemonic, a human friendly string.
func ReadNegotiationAcceptance ¶
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 WriteNegotiationAcceptance ¶
WriteNegotiationAcceptance writes the 'accept' response to w (usually a net.Conn).
func WriteNegotiationRejection ¶
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 ¶
WriteNegotiationStop writes the 'stop' response to w (usually a net.Conn).
Types ¶
type BlockCreator ¶ added in v0.1.0
The BlockCreator interface provides access to BlockCreator features.
type BlockFacts ¶
type BlockFacts struct { BlockID types.BlockID `json:"blockid"` Difficulty types.Difficulty `json:"difficulty"` EstimatedActiveBS types.Difficulty `json:"estimatedactivebs"` Height types.BlockHeight `json:"height"` MaturityTimestamp types.Timestamp `json:"maturitytimestamp"` Target types.Target `json:"target"` TotalCoins types.Currency `json:"totalcoins"` ArbitraryDataTotalSize uint64 `json:"arbitrarydatatotalsize"` // Transaction type counts. MinerPayoutCount uint64 `json:"minerpayoutcount"` TransactionCount uint64 `json:"transactioncount"` CoinInputCount uint64 `json:"coininputcount"` CoinOutputCount uint64 `json:"coinoutputcount"` BlockStakeInputCount uint64 `json:"blockstakeinputcount"` BlockStakeOutputCount uint64 `json:"blockstakeoutputcount"` MinerFeeCount uint64 `json:"minerfeecount"` ArbitraryDataCount uint64 `json:"arbitrarydatacount"` }
BlockFacts returns a bunch of statistics about the consensus set as they were at a specific block.
type BlockStakeOutputDiff ¶
type BlockStakeOutputDiff struct { Direction DiffDirection ID types.BlockStakeOutputID BlockStakeOutput types.BlockStakeOutput }
A BlockStakeOutputDiff indicates the addition or removal of a BlockStakeOutput in the consensus set.
type ChainStats ¶ added in v1.0.4
type ChainStats struct { BlockCount uint32 `json:"blockcount"` // The following fields all have the same length, // and are in the same order. The lenght is equal // to `BlockCount`. BlockHeights []types.BlockHeight `json:"blockheights"` BlockTimeStamps []types.Timestamp `json:"blocktimestamps"` BlockTimes []int64 `json:"blocktimes"` // Time to create this block EstimatedActiveBS []types.Difficulty `json:"estimatedactivebs"` BlockTransactionCounts []uint32 `json:"blocktransactioncounts"` // txns in a single block Difficulties []types.Difficulty `json:"difficulties"` // Who created these blocks and how many Creators map[string]uint32 `json:"creators"` // Some aggregated stats at the time of // the respective block TransactionCounts []uint64 `json:"transactioncounts"` CoinInputCounts []uint64 `json:"coininputcounts"` CoinOutputCounts []uint64 `json:"coinoutputcounts"` BlockStakeInputCounts []uint64 `json:"blockstakeinputcounts"` BlockStakeOutputCounts []uint64 `json:"blockstakeoutputcounts"` }
ChainStats are data points related to a selection of blocks
func NewChainStats ¶ added in v1.0.4
func NewChainStats(size int) *ChainStats
NewChainStats initializes a new `ChainStats` object
type CoinOutputDiff ¶ added in v0.1.0
type CoinOutputDiff struct { Direction DiffDirection ID types.CoinOutputID CoinOutput types.CoinOutput }
A CoinOutputDiff indicates the addition or removal of a CoinOutput in the consensus set.
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 // CoinOutputDiffs contains the set of coin diffs that were applied // to the consensus set in the recent change. The direction for the set of // diffs is 'DiffApply'. CoinOutputDiffs []CoinOutputDiff // BlockStakeOutputDiffs contains the set of blockstake diffs that were applied // to the consensus set in the recent change. The direction for the set of // diffs is 'DiffApply'. BlockStakeOutputDiffs []BlockStakeOutputDiff // 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 }
A ConsensusChange enumerates a set of changes that occurred to the consensus set.
func (ConsensusChange) Append ¶
func (cc ConsensusChange) Append(cc2 ConsensusChange) ConsensusChange
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 ¶
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) // BlockHeightOfBlock returns the blockheight of a given block, with a // bool to indicate whether that block exists. BlockHeightOfBlock(types.Block) (types.BlockHeight, bool) // TransactionAtShortID allows you fetch a transaction from a block within // the blockchain, using a given shortID. // If that transaction does not exist, false is returned. TransactionAtShortID(shortID types.TransactionShortID) (types.Transaction, bool) // TransactionAtID allows you to fetch a transaction from a block within // the blockchain, using a given transaction ID. If that transaction // does not exist, false is returned TransactionAtID(types.TransactionID) (types.Transaction, types.TransactionShortID, bool) // FindParentBlock finds the parent of a block at the given depth. It guarantees that // the correct parent block is found, even if the block is not on the longest fork. FindParentBlock(b types.Block, depth types.BlockHeight) (block types.Block, exists 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. ConsensusSetSubscribe(ConsensusSetSubscriber, ConsensusChangeID) error // CurrentBlock returns the latest block in the heaviest known // blockchain. CurrentBlock() types.Block // 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) // CalculateStakeModifier calculates the stakemodifier from the blockchain. CalculateStakeModifier(height types.BlockHeight, block types.Block, delay types.BlockHeight) *big.Int // TryTransactionSet checks whether the transaction set would be valid if // it were added in the next block. A consensus change is returned // detailing the diffs that would result from the application of the // transaction. TryTransactionSet([]types.Transaction) (ConsensusChange, error) // Unsubscribe removes a subscriber from the list of subscribers, // allowing for garbage collection and rescanning. If the subscriber is // not found in the subscriber database, no action is taken. Unsubscribe(ConsensusSetSubscriber) }
A ConsensusSet accepts blocks and builds an understanding of network consensus.
type ConsensusSetSubscriber ¶
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 DataStore ¶ added in v0.6.0
type DataStore interface { // Close closes the datstore. It will also close the connection to the database Close() error }
DataStore pulls arbitrary data, stored in transactions, from the blockchain, and saves it in a database
type DelayedCoinOutputDiff ¶ added in v0.1.0
type DelayedCoinOutputDiff struct { Direction DiffDirection ID types.CoinOutputID CoinOutput types.CoinOutput MaturityHeight types.BlockHeight }
A DelayedCoinOutputDiff indicates the introduction of a coin output that cannot be spent until after maturing for 144 blocks. When the output has matured, a CoinOutputDiff will be provided.
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 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.TwofishKey, primarySeed Seed) (Seed, error) // Encrypted returns whether or not the wallet has been encrypted yet. // After being encrypted for the first time, the wallet can only be // unlocked using the encryption password. Encrypted() bool // Lock deletes all keys in memory and prevents the wallet from being // used to spend coins or extract keys until 'Unlock' is called. Lock() error // Unlock must be called before the wallet is usable. All wallets and // wallet seeds are encrypted by default, and the wallet will not know // which addresses to watch for on the blockchain until unlock has been // called. // // All items in the wallet are encrypted using different keys which are // derived from the master key. Unlock(masterKey crypto.TwofishKey) error // Unlocked returns true if the wallet is currently unlocked, false // otherwise. Unlocked() bool }
EncryptionManager can encrypt, lock, unlock, and indicate the current status of the EncryptionManager.
type 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 // CoinOutput will return the coin output associated with the // input id. CoinOutput(types.CoinOutputID) (types.CoinOutput, bool) // CoinOutputID returns all of the transaction ids associated with // the provided coin output id. CoinOutputID(types.CoinOutputID) []types.TransactionID // BlockStakeOutput will return the blockstake output associated with the // input id. BlockStakeOutput(types.BlockStakeOutputID) (types.BlockStakeOutput, bool) // BlockStakeOutputID returns all of the transaction ids associated with // the provided blockstake output id. BlockStakeOutputID(types.BlockStakeOutputID) []types.TransactionID // HistoryStats return the stats for the last `history` amount of blocks HistoryStats(types.BlockHeight) (*ChainStats, error) // RangeStats return the stats for the range [`start`, `end`] RangeStats(types.BlockHeight, types.BlockHeight) (*ChainStats, error) // Constants returns the constants in use by the chain Constants() ExplorerConstants Close() error }
Explorer tracks the blockchain and provides tools for gathering statistics and finding objects or patterns within the blockchain.
type ExplorerConstants ¶ added in v1.0.4
type ExplorerConstants struct { GenesisTimestamp types.Timestamp `json:"genesistimestamp"` BlockSizeLimit uint64 `json:"blocksizelimit"` BlockFrequency types.BlockHeight `json:"blockfrequency"` FutureThreshold types.Timestamp `json:"futurethreshold"` ExtremeFutureThreshold types.Timestamp `json:"extremefuturethreshold"` BlockStakeCount types.Currency `json:"blockstakecount"` BlockStakeAging uint64 `json:"blockstakeaging"` BlockCreatorFee types.Currency `json:"blockcreatorfee"` MinimumTransactionFee types.Currency `json:"minimumtransactionfee"` TransactionFeeBeneficiary types.UnlockHash `json:"transactionfeebeneficiary"` MaturityDelay types.BlockHeight `json:"maturitydelay"` MedianTimestampWindow uint64 `json:"mediantimestampwindow"` RootTarget types.Target `json:"roottarget"` RootDepth types.Target `json:"rootdepth"` TargetWindow types.BlockHeight `json:"targetwindow"` MaxAdjustmentUp *big.Rat `json:"maxadjustmentup"` MaxAdjustmentDown *big.Rat `json:"maxadjustmentdown"` OneCoin types.Currency `json:"onecoin"` }
ExplorerConstants represent the constants in use by the chain
type Gateway ¶
type Gateway interface { // Connect establishes a persistent connection to a peer. Connect(NetAddress) error // Disconnect terminates a connection to a peer. Disconnect(NetAddress) error // Address returns the Gateway's address. Address() NetAddress // Peers returns the addresses that the Gateway is currently connected to. Peers() []Peer // RegisterRPC registers a function to handle incoming connections that // supply the given RPC ID. RegisterRPC(string, RPCFunc) // 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 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 // 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) // GetKey allows you to fetch the Public/Private key pair, // which is linked to the given unlock hash (assumed to be the address a user). GetKey(address types.UnlockHash) (types.SiaPublicKey, types.ByteSlice, error) // PrimarySeed returns the current primary seed of the wallet, // unencrypted, with an int indicating how many addresses have been // consumed. PrimarySeed() (Seed, uint64, error) // NextAddress returns a new coin addresses generated from the // primary seed. NextAddress() (types.UnlockHash, error) // CreateBackup will create a backup of the wallet at the provided // filepath. The backup will have all seeds and keys. CreateBackup(string) error // LoadSeed will recreate a wallet file using the recovery phrase. // LoadSeed only needs to be called if the original seed file or // encryption password was lost. The master key is used to encrypt the // recovery seed before saving it to disk. LoadSeed(crypto.TwofishKey, Seed) 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 NetAddress ¶
type NetAddress string
A NetAddress contains the information needed to contact a peer.
func (NetAddress) Host ¶
func (na NetAddress) Host() string
Host removes the port from a NetAddress, returning just the host. If the address is 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.
func (*NetAddress) TryNameResolution ¶ added in v0.1.1
func (na *NetAddress) TryNameResolution() error
TryNameResolution tries to perform dns resolution on a NetAddress, converting a host to an associated ip address. If an error occurs, or no IP is found for the host, the NetAddress remains unchanged
type Peer ¶
type Peer struct { Inbound bool `json:"inbound"` Local bool `json:"local"` NetAddress NetAddress `json:"netaddress"` // Rivine Protocol Version used by peer Version build.ProtocolVersion `json:"version"` }
Peer contains all the info necessary to Broadcast to a peer.
type PeerConn ¶
type PeerConn interface { net.Conn RPCAddr() NetAddress }
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 ProcessedInput ¶
type ProcessedInput struct { FundType types.Specifier `json:"fundtype"` WalletAddress bool `json:"walletaddress"` RelatedAddress types.UnlockHash `json:"relatedaddress"` Value types.Currency `json:"value"` }
A ProcessedInput represents funding to a transaction. The input is coming from an address and going to the outputs. The fund types are 'SiacoinInput', 'SiafundInput'.
type ProcessedOutput ¶
type ProcessedOutput struct { FundType types.Specifier `json:"fundtype"` MaturityHeight types.BlockHeight `json:"maturityheight"` WalletAddress bool `json:"walletaddress"` RelatedAddress types.UnlockHash `json:"relatedaddress"` Value types.Currency `json:"value"` }
A ProcessedOutput is a coin output that appears in a transaction. Some outputs mature immediately, some are delayed.
Fund type can either be 'CoinOutput', 'BlockStakeOutput' 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. CoinInputs and BlockStakeInputs become available immediately. 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 RPCFunc ¶
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 Seed ¶
type Seed [crypto.EntropySize]byte
Seed is cryptographic entropy that is used to derive spendable wallet addresses.
func InitialSeedFromMnemonic ¶ added in v0.6.0
InitialSeedFromMnemonic converts the mnemonic into the initial seed, also called entropy, that was used to create the given mnemonic initially.
func (*Seed) LoadString ¶ added in v1.0.3
LoadString loads a hex-encoded string into this seed.
type StorageFolderMetadata ¶
type StorageFolderMetadata struct { Capacity uint64 `json:"capacity"` // bytes CapacityRemaining uint64 `json:"capacityremaining"` // bytes 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"` }
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, expiryHeight types.BlockHeight, sectorData []byte) 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, expiryHeight types.BlockHeight) 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. RemoveStorageFolder(index int, force bool) error // ResetStorageFolderHealth will reset the health statistics on a // storage folder. ResetStorageFolderHealth(index int) 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. ResizeStorageFolder(index int, newSize uint64) 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 TransactionBuilder ¶
type TransactionBuilder interface { // Fundcoins 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. FundCoins(amount types.Currency) error // FundBlockStakes will add a siafund input of exactly 'amount' to the // transaction. A parent transaction may be needed to achieve an input // with the correct value. The siafund input will not be signed until // 'Sign' is called on the transaction builder. Any siacoins that are // released by spending the siafund outputs will be sent to another // address owned by the wallet. The expectation is that the transaction // will be completed and broadcast within a few hours. Longer risks // double-spends, because the wallet will assume the transaction // failed. FundBlockStakes(amount types.Currency) error // SpendBlockStake will link the unspent block stake to the transaction as an input. // In contrast with FundBlockStakes, this function will not loop over all unspent // block stake output. the ubsoid is an argument. The blockstake input will not be // signed until 'Sign' is called on the transaction builder. SpendBlockStake(ubsoid types.BlockStakeOutputID) 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 // AddCoinInput adds a coin input to the transaction, returning // the index of the coin input within the transaction. When 'Sign' // gets called, this input will be left unsigned. AddCoinInput(types.CoinInput) uint64 // AddCoinOutput adds a coin output to the transaction, returning // the index of the coin output within the transaction. AddCoinOutput(types.CoinOutput) uint64 // AddBlockStakeInput adds a blockstake input to the transaction, returning // the index of the blockstake input within the transaction. When 'Sign' // is called, this input will be left unsigned. AddBlockStakeInput(types.BlockStakeInput) uint64 // AddBlockStakeOutput adds a blockstake output to the transaction, returning // the index of the blockstake output within the transaction. AddBlockStakeOutput(types.BlockStakeOutput) uint64 // AddArbitraryData sets the arbitrary data of the transaction. SetArbitraryData(arb []byte) // Sign will sign any inputs added by 'FundCoins' or 'FundBlockStakes' // 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. // // 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() ([]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 siacoin inputs, siafund inputs, and // parent transactions that have been automatically added by the // builder. Items are returned by index. ViewAdded() (newParents, siacoinInputs, siafundInputs []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' or 'FundSiafunds' call. All modifications are additive.
Parents of the transaction are kept in the transaction builder. A parent is any unconfirmed transaction that is required for the child to be valid.
Transaction builders are not thread safe.
type TransactionIDDiff ¶ added in v0.6.0
type TransactionIDDiff struct { Direction DiffDirection LongID types.TransactionID ShortID types.TransactionShortID }
TransactionIDDiff represents the addition or removal of a mapping between a transactions long ID ands its short ID
type TransactionPool ¶
type TransactionPool interface { // AcceptTransactionSet accepts a set of potentially interdependent // transactions. AcceptTransactionSet([]types.Transaction) error // 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) // IsStandardTransaction returns `err = nil` if the transaction is // standard, otherwise it returns an error explaining what is not standard. IsStandardTransaction(types.Transaction) error // PurgeTransactionPool is a temporary function available to the miner. In // the event that a miner mines an unacceptable block, the transaction pool // will be purged to clear out the transaction pool and get rid of the // illegal transaction. This should never happen, however there are bugs // that make this condition necessary. PurgeTransactionPool() // TransactionList returns a list of all transactions in the transaction // pool. The transactions are provided in an order that can acceptably be // put into a block. TransactionList() []types.Transaction // TransactionPoolSubscribe adds a subscriber to the transaction pool. // Subscribers will receive all consensus set changes as well as // transaction pool changes, and should not subscribe to both. TransactionPoolSubscribe(TransactionPoolSubscriber) // Unsubscribe removes a subscriber from the transaction pool. // This is necessary for clean shutdown of the miner. Unsubscribe(TransactionPoolSubscriber) }
A TransactionPool manages unconfirmed transactions.
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([]types.Transaction, ConsensusChange) }
A TransactionPoolSubscriber receives updates about the confirmed and unconfirmed set from the transaction pool. Generally, there is no need to subscribe to both the consensus set and the transaction pool.
type Wallet ¶
type Wallet interface { EncryptionManager KeyManager // 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, blockstakeBalance types.Currency) // GetUnspentBlockStakeOutputs returns the blockstake outputs where the beneficiary is an // address this wallet has an unlockhash for. GetUnspentBlockStakeOutputs() []types.UnspentBlockStakeOutput // 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'. Siafunds are // not considered in the unconfirmed balance. UnconfirmedBalance() (outgoingSiacoins types.Currency, incomingSiacoins types.Currency) // AddressTransactions returns all of the transactions that are related // to a given address. AddressTransactions(types.UnlockHash) []ProcessedTransaction // AddressUnconfirmedHistory returns all of the unconfirmed // transactions related to a given address. AddressUnconfirmedTransactions(types.UnlockHash) []ProcessedTransaction // Transaction returns the transaction with the given id. The bool // indicates whether the transaction is in the wallet database. The // wallet only stores transactions that are related to the wallet. Transaction(types.TransactionID) (ProcessedTransaction, bool) // Transactions returns all of the transactions that were confirmed at // heights [startHeight, endHeight]. Unconfirmed transactions are not // included. Transactions(startHeight types.BlockHeight, endHeight types.BlockHeight) ([]ProcessedTransaction, error) // UnconfirmedTransactions returns all unconfirmed transactions // relative to the wallet. UnconfirmedTransactions() []ProcessedTransaction // RegisterTransaction takes a transaction and its parents and returns // a TransactionBuilder which can be used to expand the transaction. RegisterTransaction(t types.Transaction, parents []types.Transaction) TransactionBuilder // StartTransaction is a convenience method that calls // RegisterTransaction(types.Transaction{}, nil) StartTransaction() TransactionBuilder // SendCoins is a tool for sending coins from the wallet to an // address. The transaction is automatically given to the transaction pool, and // are also returned to the caller. SendCoins(amount types.Currency, dest types.UnlockHash, data []byte) (types.Transaction, error) // SendBlockStakes is a tool for sending blockstakes 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. SendBlockStakes(amount types.Currency, dest types.UnlockHash) (types.Transaction, error) // SendOutputs is a tool for sending coins and block stakes from the wallet, to one or multiple addreses. // The transaction is automatically given to the transaction pool, and is also returned to the caller. SendOutputs(coinOutputs []types.CoinOutput, blockstakeOutputs []types.BlockStakeOutput, data []byte) (types.Transaction, error) // BlockStakeStats returns the blockstake statistical information of // this wallet of the last 1000 blocks. If the blockcount is less than // 1000 blocks, BlockCount will be the number available. BlockStakeStats() (BCcountLast1000 uint64, BCfeeLast1000 types.Currency, BlockCount uint64) }
Wallet stores and manages siacoins and siafunds. The wallet file is encrypted using a user-specified password. Common addresses are all derived from a single address seed.
type WalletTransactionID ¶
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.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package explorer provides a glimpse into what the network currently looks like.
|
Package explorer provides a glimpse into what the 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. |