modules

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2020 License: MIT Imports: 16 Imported by: 52

Documentation

Index

Constants

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"

	// 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 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
)
View Source
const (
	// TransactionPoolRebroadcastDelay is the amount of blocks we wait for a
	// transaction in the transaction pool to be broadcasted again, if it is not
	// included in a block by then.
	TransactionPoolRebroadcastDelay = 3
	// TransactionPoolMaxRebroadcasts is the maximum amount of times a transaction
	// will get broadcast again.
	TransactionPoolMaxRebroadcasts = 4
)
View Source
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
)
View Source
const (
	// BlockCreatorDir is the name of the directory that is used to store the BlockCreator's
	// persistent data.
	BlockCreatorDir = "blockcreator"
)
View Source
const (
	// ExplorerDir is the name of the directory that is typically used for the
	// explorer.
	ExplorerDir = "explorer"
)
View Source
const (
	// GatewayDir is the name of the directory used to store the gateway's
	// persistent data.
	GatewayDir = "gateway"
)
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. TODO: check extreme condition

View Source
const (
	// StorageManagerDir is standard name used for the directory that contains
	// all of the storage manager files.
	StorageManagerDir = "storagemanager"
)
View Source
const (
	// TransactionPoolDir is the name of the directory that is used to store
	// the transaction pool's persistent data.
	TransactionPoolDir = "transactionpool"
)

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

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

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

	// ErrTransactionNotFound is returned in case no transaction could be found
	// in the transaction pool for a specific ID.
	ErrTransactionNotFound = errors.New("transaction not found")
)
View Source
var (
	// ErrBadEncryptionKey is returned if the incorrect encryption key to a
	// file is provided.
	ErrBadEncryptionKey = errors.New("provided encryption key is incorrect")

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

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

	// ErrEncryptedWallet is returned in case the wallet is encrypted, preventing it from being
	// used for plain purposes.
	ErrEncryptedWallet = errors.New("wallet is encrypted and cannot use plain functionality")
)
View Source
var (

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

Functions

func NewMnemonic added in v0.6.0

func NewMnemonic(seed Seed) (string, error)

NewMnemonic converts a wallet seed to a mnemonic, a human friendly string.

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 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 BlockCreator added in v0.1.0

type BlockCreator interface {
	io.Closer
}

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 length 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 ConsensusBlock added in v1.2.0

type ConsensusBlock struct {
	types.Block

	Height types.BlockHeight

	SpentCoinOutputs       map[types.CoinOutputID]types.CoinOutput
	SpentBlockStakeOutputs map[types.BlockStakeOutputID]types.BlockStakeOutput
}

ConsensusBlock is the block type as exposed by the consensus module, allowing you to easily find the spend coin and blockstake outputs, for any of the by-the-block defined inputs

type ConsensusBlockHeader added in v1.3.1

type ConsensusBlockHeader struct {
	ID             types.BlockID
	ParentID       types.BlockID
	POBSOutput     types.BlockStakeOutputIndexes
	MinerPayouts   []types.MinerPayout
	MinerPayoutIDs []types.CoinOutputID

	Timestamp types.Timestamp
	Height    types.BlockHeight
}

ConsensusBlockHeader is the block header type as exposed by the consensus module.

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

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 ConsensusSet

type ConsensusSet interface {
	// Start the consensusset
	// this function starts a new goroutine and then returns immediately
	Start()

	// 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, <-chan struct{}) 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)

	// GetCoinOutput takes a coin output ID and returns the appropriate coin output
	GetCoinOutput(types.CoinOutputID) (types.CoinOutput, error)

	// GetBlockStakeOutput takes a blockstake output ID and returns the appropriate blockstake output
	GetBlockStakeOutput(types.BlockStakeOutputID) (types.BlockStakeOutput, error)

	// RegisterPlugin takes in a name and plugin and registers this plugin on the consensus
	// When the plugin is registered, all unprocessed changes are synchronously sent to the plugin
	// unless the passed context is cancelled
	RegisterPlugin(ctx context.Context, name string, plugin ConsensusSetPlugin) error

	// UnregisterPlugin takes in a name and plugin and unregisters this plugin off the consensus
	UnregisterPlugin(name string, plugin ConsensusSetPlugin)

	// LoadedPlugins returns a list of all loaded plugins, by nane.
	LoadedPlugins() []string

	// SetTransactionValidators sets the transaction validators used by the ConsensusSet as rules for all transactions,
	// regardless of the version. Use SetTransactionVersionMappedValidators in case you want rules that only apply to a specific tx version.
	// If no validators are passed, the validators returned by the `consensus.StandardTransactionValidators` function are used.
	SetTransactionValidators(validators ...TransactionValidationFunction)

	// SetTransactionVersionMappedValidators sets the transaction validators used by the ConsensusSet as rules for
	// the transactions of the defined version. If no validators are passed, the validators for the given transaction version,
	// as returned by the `consensus.StandardTransactionVersionMappedValidators` function, are used.
	SetTransactionVersionMappedValidators(version types.TransactionVersion, validators ...TransactionValidationFunction)
}

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

type ConsensusSetPlugin added in v1.2.0

type ConsensusSetPlugin interface {
	// Initialize the bucket, could be creating it, migrating it,
	// or simply checking that all is as expected.
	// An error should be returned in case something went wrong.
	// metadata is nil in case the plugin wasn't registered prior to this attempt.
	// This method will be called while registering the plugin.
	InitPlugin(metadata *persist.Metadata, bucket *bolt.Bucket, ps PluginViewStorage, cb PluginUnregisterCallback) (persist.Metadata, error)

	// Apply the block to the plugin.
	// An error should be returned in case something went wrong.
	ApplyBlock(block ConsensusBlock, bucket *persist.LazyBoltBucket) error
	// Revert the block from the plugin.
	// An error should be returned in case something went wrong.
	RevertBlock(block ConsensusBlock, bucket *persist.LazyBoltBucket) error

	// Apply the block header to the plugin.
	// An error should be returned in case something went wrong.
	ApplyBlockHeader(block ConsensusBlockHeader, bucket *persist.LazyBoltBucket) error
	// Revert the block header from the plugin.
	// An error should be returned in case something went wrong.
	RevertBlockHeader(block ConsensusBlockHeader, bucket *persist.LazyBoltBucket) error

	// Apply the transaction to the plugin.
	// An error should be returned in case something went wrong.
	ApplyTransaction(txn ConsensusTransaction, bucket *persist.LazyBoltBucket) error
	// Revert the transaction from the plugin.
	// An error should be returned in case something went wrong.
	RevertTransaction(txn ConsensusTransaction, bucket *persist.LazyBoltBucket) error

	// TransactionValidatorFunctions allows the plugin to provide validation rules for all transaction versions it mapped to
	TransactionValidatorVersionFunctionMapping() map[types.TransactionVersion][]PluginTransactionValidationFunction

	// TransactionValidators allows the plugin to provide validation rules for all transactions versions it wants
	TransactionValidators() []PluginTransactionValidationFunction

	// Close releases any resources helt by the plugin like the PluginViewStorage
	Close() error
}

A ConsensusSetPlugin is an object that receives updates to the consensus set every time there is a change in consensus. The difference with a ConsensusSetSubscriber is that it stores its data within the database of the consensus set.

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 ConsensusTransaction added in v1.2.0

type ConsensusTransaction struct {
	types.Transaction

	BlockHeight types.BlockHeight
	BlockTime   types.Timestamp
	SequenceID  uint16

	SpentCoinOutputs       map[types.CoinOutputID]types.CoinOutput
	SpentBlockStakeOutputs map[types.BlockStakeOutputID]types.BlockStakeOutput
}

ConsensusTransaction is the transaction type as exposed by the consensus module allowing you to easily find the spend coin and blockstake outputs, for any of the by-the-transaction defined inputs

type DaemonConstants added in v1.0.7

type DaemonConstants struct {
	ChainInfo types.BlockchainInfo `json:"chaininfo"`

	// ConsensusPlugins are the plugins loaded in the consensus set module of this daemon
	ConsensusPlugins []string `json:"consensusplugins"`

	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"`
	TransactionFeeConition types.UnlockConditionProxy `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"`

	DefaultTransactionVersion types.TransactionVersion `json:"deftransactionversion"`
}

DaemonConstants represent the constants in use by the daemon

func NewDaemonConstants added in v1.0.7

func NewDaemonConstants(info types.BlockchainInfo, constants types.ChainConstants, consensusPlugins []string) DaemonConstants

NewDaemonConstants returns the Deamon's public constants, using the blockchain (network) info and constants used internally as input.

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

	// MultiSigAddresses returns all multisig addresses this wallet address is involved in.
	MultiSigAddresses(types.UnlockHash) []types.UnlockHash

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

	Close() error
}

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

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

	// 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.PublicKey, 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

	// LoadPlainSeed will recreate a wallet file using the recovery phrase.
	// LoadPlainSeed only needs to be called if the original seed file was lost.
	LoadPlainSeed(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 MultiSigWallet added in v1.0.6

type MultiSigWallet struct {
	Address             types.UnlockHash           `json:"address"`
	CoinOutputIDs       []types.CoinOutputID       `json:"coinoutputids"`
	BlockStakeOutputIDs []types.BlockStakeOutputID `json:"blockstakeoutputids"`

	ConfirmedCoinBalance       types.Currency `json:"confirmedcoinbalance"`
	ConfirmedLockedCoinBalance types.Currency `json:"confirmedlockedcoinbalance"`
	UnconfirmedOutgoingCoins   types.Currency `json:"unconfirmedoutgoingcoins"`
	UnconfirmedIncomingCoins   types.Currency `json:"unconfirmedincomingcoins"`

	ConfirmedBlockStakeBalance       types.Currency `json:"confirmedblockstakebalance"`
	ConfirmedLockedBlockStakeBalance types.Currency `json:"confirmedlockedblockstakebalance"`
	UnconfirmedOutgoingBlockStakes   types.Currency `json:"unconfirmedoutgoingblockstakes"`
	UnconfirmedIncomingBlockStakes   types.Currency `json:"unconfirmedincomingblockstakes"`

	Owners  []types.UnlockHash `json:"owners"`
	MinSigs uint64             `json:"minsigs"`
}

MultiSigWallet is a collection of coin and blockstake outputs, which have the same unlockhash.

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 PluginTransactionValidationFunction added in v1.2.0

type PluginTransactionValidationFunction func(tx ConsensusTransaction, ctx types.TransactionValidationContext, bucket *persist.LazyBoltBucket) error

PluginTransactionValidationFunction is the signature of a validator function that can be used to provide plugin-driven transaction validation, provided by (and linked to) a plugin.

type PluginUnregisterCallback added in v1.2.0

type PluginUnregisterCallback func(plugin ConsensusSetPlugin)

PluginUnregisterCallback allows plugins to unregister

type PluginViewStorage added in v1.2.0

type PluginViewStorage interface {
	View(callback func(bucket *bolt.Bucket) error) error
	Close() error
}

A PluginStorage

type ProcessedInput

type ProcessedInput struct {
	FundType types.Specifier `json:"fundtype"`
	// WalletAddress indicates it's an address owned by this wallet
	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 indicates it's an address owned by this wallet
	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

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

func InitialSeedFromMnemonic(mnemonic string) (out Seed, err error)

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

func (s *Seed) LoadString(str string) error

LoadString loads a hex-encoded string into this seed.

func (Seed) String added in v1.0.3

func (s Seed) String() string

String returns this seed as a hex-encoded string.

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, refundAddress *types.UnlockHash, reuseRefundAddress bool) 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, refundAddress *types.UnlockHash, reuseRefundAddress bool) 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()

	// SignAllPossible tries to sign as much of the inputs —and extension if required—
	// in the tranaction using the keys loaded in the wallet
	SignAllPossible() error
}

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

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

	// Transaction returns the transaction with the given ID from the transaction pool.
	// If no transaction for that ID is found ErrNotFound is returned.
	Transaction(id types.TransactionID) (types.Transaction, error)

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

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 TransactionValidationFunction added in v1.2.0

type TransactionValidationFunction func(tx ConsensusTransaction, ctx types.TransactionValidationContext) error

TransactionValidationFunction is the signature of a validator function that can be used to provide validation rules for transactions.

type Wallet

type Wallet interface {
	EncryptionManager
	KeyManager

	// Init will create the PLAIN wallet using the primary seed,
	// or creating a seed for you if none is given.
	//
	// Init 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.
	//
	// NOTE: the seed is stored in a plain text file on the local FS.
	// This is not recommended, unless you are working in an isolated and controlled environment.
	// Please use the Encrypt method instead, in order to create the wallet using a master key,
	// the generated adddresses will be the same either way, but the seed will be encrypted
	// prior to being stored on the local FS.
	Init(primarySeed Seed) (Seed, 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, blockstakeBalance types.Currency, err error)

	// ConfirmedLockedBalance returns the confirmed balance of the wallet, which is locked,
	// minus any outgoing transactions. ConfirmedLockedBalance will include unconfirmed
	// refund transactions which are locked as well.
	ConfirmedLockedBalance() (siacoinBalance types.Currency, blockstakeBalance types.Currency, err error)

	// GetUnspentBlockStakeOutputs returns the blockstake outputs where the beneficiary is an
	// address this wallet has an unlockhash for.
	GetUnspentBlockStakeOutputs() ([]types.UnspentBlockStakeOutput, 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'. Siafunds are
	// not considered in the unconfirmed balance.
	UnconfirmedBalance() (outgoingSiacoins types.Currency, incomingSiacoins types.Currency, err 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)

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

	// MultiSigWallets returns all multisig wallets which contain at least one unlock hash owned by this wallet.
	// A multisig wallet is in this context defined as a (group of) coin and or blockstake outputs, where the unlockhash
	// of these outputs are exactly the same. In practice, this means that the collection of unlock hashes in the condition,
	// as well as the minimum amount of signatures required, must match
	MultiSigWallets() ([]MultiSigWallet, 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

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

	// SendCoins is a tool for sending coins from the wallet to anyone who can fulfill the
	// given condition (can be nil). The transaction is automatically given to the transaction pool, and
	// are also returned to the caller.
	SendCoins(amount types.Currency, cond types.UnlockConditionProxy, data []byte) (types.Transaction, error)

	// SendBlockStakes is a tool for sending blockstakes from the wallet to anyone who can fulfill the
	// given condition (can be nil). 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, cond types.UnlockConditionProxy) (types.Transaction, error)

	// SendOutputs is a tool for sending coins and/or 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, refundAddress *types.UnlockHash, reuseRefundAddress bool) (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, err error)

	// UnlockedUnspendOutputs returns all unlocked and unspend coin and blockstake outputs
	// owned by this wallet
	UnlockedUnspendOutputs() (map[types.CoinOutputID]types.CoinOutput, map[types.BlockStakeOutputID]types.BlockStakeOutput, error)

	// LockedUnspendOutputs returns all locked and unspend coin and blockstake outputs owned
	// by this wallet
	LockedUnspendOutputs() (map[types.CoinOutputID]types.CoinOutput, map[types.BlockStakeOutputID]types.BlockStakeOutput, error)

	// CreateRawTransaction creates a new transaction with the given inputs and outputs.
	// All inputs must exist in the consensus set at the time this method is called. The total
	// value of the inputs must match the sum of all respective outputs and the transaction fee.
	CreateRawTransaction([]types.CoinOutputID, []types.BlockStakeOutputID, []types.CoinOutput, []types.BlockStakeOutput, []byte) (types.Transaction, error)

	// GreedySign attempts to sign every input which can be signed by the keys loaded
	// in this wallet.
	GreedySign(types.Transaction) (types.Transaction, error)
}

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

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

Jump to

Keyboard shortcuts

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