wallet

package
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2016 License: ISC Imports: 36 Imported by: 0

README

wallet

Feature Overview

TODO: Flesh out this section

Documentation

[GoDoc] (http://godoc.org/github.com/decred/dcrwallet/wallet)

Full go doc style documentation for the project can be viewed online without installing this package by using the GoDoc site here: http://godoc.org/github.com/decred/dcrwallet/wallet

You can also view the documentation locally once the package is installed with the godoc tool by running godoc -http=":6060" and pointing your browser to http://localhost:6060/pkg/github.com/decred/dcrwallet/wallet

Installation

$ go get github.com/decred/dcrwallet/wallet

Package wallet is licensed under the copyfree ISC License.

Documentation

Overview

Package wallet provides ... TODO: Flesh out this section

Overview

Index

Constants

View Source
const EstMaxTicketFeeAmount = 0.1 * 1e8

EstMaxTicketFeeAmount is the estimated max ticket fee to be used for size calculation for eligible utxos for ticket purchasing.

View Source
const (
	// InsecurePubPassphrase is the default outer encryption passphrase used
	// for public data (everything but private keys).  Using a non-default
	// public passphrase can prevent an attacker without the public
	// passphrase from discovering all past and future wallet addresses if
	// they gain access to the wallet database.
	//
	// NOTE: at time of writing, public encryption only applies to public
	// data in the waddrmgr namespace.  Transactions are not yet encrypted.
	InsecurePubPassphrase = "public"
)
View Source
const TicketFeeIncrement = 1e6

TicketFeeIncrement is the default minimum stake transaction fees per KB (0.01 coin, measured in atoms).

Variables

View Source
var (
	// ErrLoaded describes the error condition of attempting to load or
	// create a wallet when the loader has already done so.
	ErrLoaded = errors.New("wallet already loaded")

	// ErrNotLoaded describes the error condition of attempting to close a
	// loaded wallet when a wallet has not been loaded.
	ErrNotLoaded = errors.New("wallet is not loaded")

	// ErrExists describes the error condition of attempting to create a new
	// wallet when one exists already.
	ErrExists = errors.New("wallet already exists")
)
View Source
var ErrBlockchainReorganizing = errors.New("blockchain is currently " +
	"reorganizing")

ErrBlockchainReorganizing indicates that the blockchain is currently reorganizing.

View Source
var ErrNegativeFee = errors.New("fee is negative")

ErrNegativeFee represents an error where a fee is erroneously negative.

View Source
var ErrNoOutsToConsolidate = errors.New("no outputs to consolidate")

ErrNoOutsToConsolidate indicates that there were no outputs available to compress.

View Source
var ErrNonPositiveAmount = errors.New("amount is not positive")

ErrNonPositiveAmount represents an error where an amount is not positive (either negative, or zero).

View Source
var ErrNotSynced = errors.New("wallet is not synchronized with the chain server")

ErrNotSynced describes an error where an operation cannot complete due wallet being out of sync (and perhaps currently syncing with) the remote chain server.

View Source
var ErrSStxInputOverflow = errors.New("too many inputs to purchase ticket with")

ErrSStxInputOverflow indicates that too many inputs were used to generate a ticket.

View Source
var ErrSStxNotEnoughFunds = errors.New("not enough to purchase sstx")

ErrSStxNotEnoughFunds indicates that not enough funds were available in the wallet to purchase a ticket.

View Source
var ErrSStxPriceExceedsSpendLimit = errors.New("ticket price exceeds spend limit")

ErrSStxPriceExceedsSpendLimit indicates that the current ticket price exceeds the specified spend maximum spend limit.

View Source
var ErrTicketPriceNotSet = errors.New("ticket price not yet established")

ErrTicketPriceNotSet indicates that the wallet was recently connected and that the ticket price has not yet been set.

View Source
var ErrUnsupportedTransactionType = errors.New("Only P2PKH transactions " +
	"are supported")

ErrUnsupportedTransactionType represents an error where a transaction cannot be signed as the API only supports spending P2PKH outputs.

View Source
var (
	// SimulationPassphrase is the password for a wallet created for simnet
	// with --createtemp.
	SimulationPassphrase = []byte("password")
)

Functions

func Create

func Create(db walletdb.DB, pubPass, privPass, seed []byte, params *chaincfg.Params, unsafeMainNet bool) error

Create creates an new wallet, writing it to an empty database. If the passed seed is non-nil, it is used. Otherwise, a secure random seed of the recommended length is generated.

func CreateWatchOnly

func CreateWatchOnly(db walletdb.DB, extendedPubKey string, pubPass []byte, params *chaincfg.Params) error

CreateWatchOnly creates a watchonly wallet on the provided db.

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until either UseLogger or SetLogWriter are called.

func EstimateTxSize

func EstimateTxSize(numInputs, numOutputs int) int

EstimateTxSize is the exported version of estimateTxSize which provides an estimate of the tx size based on the number of inputs, outputs, and some assumed overhead.

func FeeForSize

func FeeForSize(incr dcrutil.Amount, sz int) dcrutil.Amount

FeeForSize is the exported version of feeForSize which returns a fee based on the provided feeIncrement and provided size.

func ListTransactions

func ListTransactions(details *wtxmgr.TxDetails, addrMgr *waddrmgr.Manager,
	syncHeight int32, net *chaincfg.Params) []dcrjson.ListTransactionsResult

ListTransactions creates a object that may be marshalled to a response result for a listtransactions RPC.

TODO: This should be moved to the legacyrpc package.

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info. This should be used in preference to SetLogWriter if the caller is also using btclog.

Types

type AccountBalance

type AccountBalance struct {
	Account      uint32
	TotalBalance dcrutil.Amount
}

AccountBalance associates a total (zero confirmation) balance with an account. Balances for other minimum confirmation counts require more expensive logic and it is not clear which minimums a client is interested in, so they are not included.

type AccountNotification

type AccountNotification struct {
	AccountNumber    uint32
	AccountName      string
	ExternalKeyCount uint32
	InternalKeyCount uint32
	ImportedKeyCount uint32
}

AccountNotification contains properties regarding an account, such as its name and the number of derived and imported keys. When any of these properties change, the notification is fired.

type AccountNotificationsClient

type AccountNotificationsClient struct {
	C chan *AccountNotification
	// contains filtered or unexported fields
}

AccountNotificationsClient receives AccountNotifications over the channel C.

func (*AccountNotificationsClient) Done

func (c *AccountNotificationsClient) Done()

Done deregisters the client from the server and drains any remaining messages. It must be called exactly once when the client is finished receiving notifications.

type AccountResult

type AccountResult struct {
	waddrmgr.AccountProperties
	TotalBalance dcrutil.Amount
}

AccountResult is a single account result for the AccountsResult type.

type AccountsResult

type AccountsResult struct {
	Accounts           []AccountResult
	CurrentBlockHash   *chainhash.Hash
	CurrentBlockHeight int32
}

AccountsResult is the resutl of the wallet's Accounts method. See that method for more details.

type Block

type Block struct {
	Hash         *chainhash.Hash
	Height       int32
	Timestamp    int64
	Transactions []TransactionSummary
}

Block contains the properties and all relevant transactions of an attached block.

type BlockIdentifier

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

BlockIdentifier identifies a block by either a height or a hash.

func NewBlockIdentifierFromHash

func NewBlockIdentifierFromHash(hash *chainhash.Hash) *BlockIdentifier

NewBlockIdentifierFromHash constructs a BlockIdentifier for a block hash.

func NewBlockIdentifierFromHeight

func NewBlockIdentifierFromHeight(height int32) *BlockIdentifier

NewBlockIdentifierFromHeight constructs a BlockIdentifier for a block height.

type CreatedTx

type CreatedTx struct {
	MsgTx       *wire.MsgTx
	ChangeAddr  dcrutil.Address
	ChangeIndex int // negative if no change
	Fee         dcrutil.Amount
}

CreatedTx holds the state of a newly-created transaction and the change output (if one was added).

type CreditCategory

type CreditCategory byte

CreditCategory describes the type of wallet transaction output. The category of "sent transactions" (debits) is always "send", and is not expressed by this type.

TODO: This is a requirement of the RPC server and should be moved.

const (
	CreditReceive CreditCategory = iota
	CreditGenerate
	CreditImmature
)

These constants define the possible credit categories.

func RecvCategory

func RecvCategory(details *wtxmgr.TxDetails, syncHeight int32,
	chainParams *chaincfg.Params) CreditCategory

RecvCategory returns the category of received credit outputs from a transaction record. The passed block chain height is used to distinguish immature from mature coinbase outputs.

TODO: This is intended for use by the RPC server and should be moved out of this package at a later time.

func (CreditCategory) String

func (c CreditCategory) String() string

String returns the category as a string. This string may be used as the JSON string for categories as part of listtransactions and gettransaction RPC responses.

type GetTransactionsResult

type GetTransactionsResult struct {
	MinedTransactions   []Block
	UnminedTransactions []TransactionSummary
}

GetTransactionsResult is the result of the wallet's GetTransactions method. See GetTransactions for more details.

type HeldUnlock

type HeldUnlock chan struct{}

HeldUnlock is a tool to prevent the wallet from automatically locking after some timeout before an operation which needed the unlocked wallet has finished. Any aquired HeldUnlock *must* be released (preferably with a defer) or the wallet will forever remain unlocked.

func (HeldUnlock) Release

func (c HeldUnlock) Release()

Release releases the hold on the unlocked-state of the wallet and allows the wallet to be locked again. If a lock timeout has already expired, the wallet is locked again as soon as Release is called.

type Loader

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

Loader implements the creating of new and opening of existing wallets, while providing a callback system for other subsystems to handle the loading of a wallet. This is primarely intended for use by the RPC servers, to enable methods and services which require the wallet when the wallet is loaded by another subsystem.

Loader is safe for concurrent access.

func NewLoader

func NewLoader(chainParams *chaincfg.Params, dbDirPath string,
	stakeOptions *StakeOptions, autoRepair bool, unsafeMainNet bool,
	addrIdxScanLen int, allowHighFees bool) *Loader

NewLoader constructs a Loader.

func (*Loader) CreateNewWallet

func (l *Loader) CreateNewWallet(pubPassphrase, privPassphrase, seed []byte) (*Wallet, error)

CreateNewWallet creates a new wallet using the provided public and private passphrases. The seed is optional. If non-nil, addresses are derived from this seed. If nil, a secure random seed is generated.

func (*Loader) LoadedWallet

func (l *Loader) LoadedWallet() (*Wallet, bool)

LoadedWallet returns the loaded wallet, if any, and a bool for whether the wallet has been loaded or not. If true, the wallet pointer should be safe to dereference.

func (*Loader) OpenExistingWallet

func (l *Loader) OpenExistingWallet(pubPassphrase []byte, canConsolePrompt bool) (*Wallet, error)

OpenExistingWallet opens the wallet from the loader's wallet database path and the public passphrase. If the loader is being called by a context where standard input prompts may be used during wallet upgrades, setting canConsolePrompt will enable these prompts.

func (*Loader) RunAfterLoad

func (l *Loader) RunAfterLoad(fn func(*Wallet))

RunAfterLoad adds a function to be executed when the loader creates or opens a wallet. Functions are executed in a single goroutine in the order they are added.

func (*Loader) UnloadWallet

func (l *Loader) UnloadWallet() error

UnloadWallet stops the loaded wallet, if any, and closes the wallet database. This returns ErrNotLoaded if the wallet has not been loaded with CreateNewWallet or LoadExistingWallet. The Loader may be reused if this function returns without error.

func (*Loader) WalletExists

func (l *Loader) WalletExists() (bool, error)

WalletExists returns whether a file exists at the loader's database path. This may return an error for unexpected I/O failures.

type NotificationServer

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

NotificationServer is a server that interested clients may hook into to receive notifications of changes in a wallet. A client is created for each registered notification. Clients are guaranteed to receive messages in the order wallet created them, but there is no guaranteed synchronization between different clients.

func (*NotificationServer) AccountNotifications

func (s *NotificationServer) AccountNotifications() AccountNotificationsClient

AccountNotifications returns a client for receiving AccountNotifications over a channel. The channel is unbuffered. When finished, the client's Done method should be called to disassociate the client from the server.

func (*NotificationServer) AccountSpentnessNotifications

func (s *NotificationServer) AccountSpentnessNotifications(account uint32) SpentnessNotificationsClient

AccountSpentnessNotifications registers a client for spentness changes of outputs controlled by the account.

func (*NotificationServer) TransactionNotifications

func (s *NotificationServer) TransactionNotifications() TransactionNotificationsClient

TransactionNotifications returns a client for receiving TransactionNotifiations notifications over a channel. The channel is unbuffered.

When finished, the Done method should be called on the client to disassociate it from the server.

type RescanFinishedMsg

type RescanFinishedMsg struct {
	Addresses    []dcrutil.Address
	Notification *chain.RescanFinished
}

RescanFinishedMsg reports the addresses that were rescanned when a rescanfinished message was received rescanning a batch of addresses.

type RescanJob

type RescanJob struct {
	InitialSync bool
	Addrs       []dcrutil.Address
	OutPoints   []*wire.OutPoint
	BlockStamp  waddrmgr.BlockStamp
	// contains filtered or unexported fields
}

RescanJob is a job to be processed by the RescanManager. The job includes a set of wallet addresses, a starting height to begin the rescan, and outpoints spendable by the addresses thought to be unspent. After the rescan completes, the error result of the rescan RPC is sent on the Err channel.

type RescanProgressMsg

type RescanProgressMsg struct {
	Addresses    []dcrutil.Address
	Notification *chain.RescanProgress
}

RescanProgressMsg reports the current progress made by a rescan for a set of wallet addresses.

type SignatureError

type SignatureError struct {
	InputIndex uint32
	Error      error
}

SignatureError records the underlying error when validating a transaction input signature.

type SpentnessNotifications

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

SpentnessNotifications is a notification that is fired for transaction outputs controlled by some account's keys. The notification may be about a newly added unspent transaction output or that a previously unspent output is now spent. When spent, the notification includes the spending transaction's hash and input index.

func (*SpentnessNotifications) Hash

Hash returns the transaction hash of the spent output.

func (*SpentnessNotifications) Index

func (n *SpentnessNotifications) Index() uint32

Index returns the transaction output index of the spent output.

func (*SpentnessNotifications) Spender

func (n *SpentnessNotifications) Spender() (*chainhash.Hash, uint32, bool)

Spender returns the spending transction's hash and input index, if any. If the output is unspent, the final bool return is false.

type SpentnessNotificationsClient

type SpentnessNotificationsClient struct {
	C <-chan *SpentnessNotifications
	// contains filtered or unexported fields
}

SpentnessNotificationsClient receives SpentnessNotifications from the NotificationServer over the channel C.

func (*SpentnessNotificationsClient) Done

func (c *SpentnessNotificationsClient) Done()

Done deregisters the client from the server and drains any remaining messages. It must be called exactly once when the client is finished receiving notifications.

type StakeDifficultyInfo

type StakeDifficultyInfo struct {
	BlockHash       *chainhash.Hash
	BlockHeight     int64
	StakeDifficulty int64
}

StakeDifficultyInfo is a container for stake difficulty information updates.

type StakeOptions

type StakeOptions struct {
	VoteBits            uint16
	StakeMiningEnabled  bool
	BalanceToMaintain   float64
	RollbackTest        bool
	PruneTickets        bool
	AddressReuse        bool
	TicketAddress       string
	TicketMaxPrice      float64
	TicketBuyFreq       int
	PoolAddress         string
	PoolFees            float64
	StakePoolColdExtKey string
}

StakeOptions contains the various options necessary for stake mining.

type TransactionNotifications

type TransactionNotifications struct {
	AttachedBlocks           []Block
	DetachedBlocks           []*chainhash.Hash
	UnminedTransactions      []TransactionSummary
	UnminedTransactionHashes []*chainhash.Hash
	NewBalances              []AccountBalance
}

TransactionNotifications is a notification of changes to the wallet's transaction set and the current chain tip that wallet is considered to be synced with. All transactions added to the blockchain are organized by the block they were mined in.

During a chain switch, all removed block hashes are included. Detached blocks are sorted in the reverse order they were mined. Attached blocks are sorted in the order mined.

All newly added unmined transactions are included. Removed unmined transactions are not explicitly included. Instead, the hashes of all transactions still unmined are included.

If any transactions were involved, each affected account's new total balance is included.

TODO: Because this includes stuff about blocks and can be fired without any changes to transactions, it needs a better name.

type TransactionNotificationsClient

type TransactionNotificationsClient struct {
	C <-chan *TransactionNotifications
	// contains filtered or unexported fields
}

TransactionNotificationsClient receives TransactionNotifications from the NotificationServer over the channel C.

func (*TransactionNotificationsClient) Done

Done deregisters the client from the server and drains any remaining messages. It must be called exactly once when the client is finished receiving notifications.

type TransactionSummary

type TransactionSummary struct {
	Hash        *chainhash.Hash
	Transaction []byte
	MyInputs    []TransactionSummaryInput
	MyOutputs   []TransactionSummaryOutput
	Fee         dcrutil.Amount
	Timestamp   int64
}

TransactionSummary contains a transaction relevant to the wallet and marks which inputs and outputs were relevant.

type TransactionSummaryInput

type TransactionSummaryInput struct {
	Index           uint32
	PreviousAccount uint32
	PreviousAmount  dcrutil.Amount
}

TransactionSummaryInput describes a transaction input that is relevant to the wallet. The Index field marks the transaction input index of the transaction (not included here). The PreviousAccount and PreviousAmount fields describe how much this input debits from a wallet account.

type TransactionSummaryOutput

type TransactionSummaryOutput struct {
	Index    uint32
	Account  uint32
	Internal bool
}

TransactionSummaryOutput describes wallet properties of a transaction output controlled by the wallet. The Index field marks the transaction output index of the transaction (not included here).

type VotingInfo

type VotingInfo struct {
	BlockHash   *chainhash.Hash
	BlockHeight int64
	Tickets     []*chainhash.Hash
}

VotingInfo is a container for the current height, hash, and list of eligible tickets.

type Wallet

type Wallet struct {
	Manager  *waddrmgr.Manager
	TxStore  *wtxmgr.Store
	StakeMgr *wstakemgr.StakeStore

	VoteBits           uint16
	StakeMiningEnabled bool
	CurrentStakeDiff   *StakeDifficultyInfo
	CurrentVotingInfo  *VotingInfo
	TicketMaxPrice     dcrutil.Amount

	DisallowFree  bool
	AllowHighFees bool

	NtfnServer *NotificationServer
	// contains filtered or unexported fields
}

Wallet is a structure containing all the components for a complete wallet. It contains the Armory-style key store addresses and keys),

func Open

func Open(db walletdb.DB, pubPass []byte, cbs *waddrmgr.OpenCallbacks,
	voteBits uint16, stakeMiningEnabled bool, balanceToMaintain float64,
	addressReuse bool, rollbackTest bool, pruneTickets bool, ticketAddress string,
	ticketMaxPrice float64, ticketBuyFreq int, poolAddress string,
	poolFees float64, addrIdxScanLen int, stakePoolColdExtKey string,
	autoRepair, allowHighFees bool, params *chaincfg.Params) (*Wallet, error)

Open loads an already-created wallet from the passed database and namespaces.

func (*Wallet) AccountUsed

func (w *Wallet) AccountUsed(account uint32) (bool, error)

AccountUsed returns whether there are any recorded transactions spending to a given account. It returns true if atleast one address in the account was used and false if no address in the account was used.

func (*Wallet) Accounts

func (w *Wallet) Accounts() (*AccountsResult, error)

Accounts returns the current names, numbers, and total balances of all accounts in the wallet. The current chain tip is included in the result for atomicity reasons.

TODO(jrick): Is the chain tip really needed, since only the total balances are included?

func (*Wallet) AddressPoolIndex added in v0.0.10

func (w *Wallet) AddressPoolIndex(account uint32, branch uint32) (uint32, error)

AddressPoolIndex returns the next to use address index for the passed branch of the passed account.

func (*Wallet) BalanceToMaintain

func (w *Wallet) BalanceToMaintain() dcrutil.Amount

BalanceToMaintain is used to get the current balancetomaintain for the wallet.

func (*Wallet) CalculateAccountBalance

func (w *Wallet) CalculateAccountBalance(account uint32, confirms int32,
	balanceType wtxmgr.BehaviorFlags) (dcrutil.Amount, error)

CalculateAccountBalance sums the amounts of all unspent transaction outputs to the given account of a wallet and returns the balance.

func (*Wallet) CalculateAccountBalances

func (w *Wallet) CalculateAccountBalances(account uint32,
	confirms int32) (wtxmgr.Balances, error)

CalculateAccountBalances calculates the values for the wtxmgr struct Balance, which includes the total balance, the spendable balance, and the balance which has yet to mature.

func (*Wallet) CalculateBalance

func (w *Wallet) CalculateBalance(confirms int32, balanceType wtxmgr.BehaviorFlags) (dcrutil.Amount, error)

CalculateBalance sums the amounts of all unspent transaction outputs to addresses of a wallet and returns the balance.

If confirmations is 0, all UTXOs, even those not present in a block (height -1), will be used to get the balance. Otherwise, a UTXO must be in a block. If confirmations is 1 or greater, the balance will be calculated based on how many how many blocks include a UTXO.

func (*Wallet) ChainClient

func (w *Wallet) ChainClient() *chain.RPCClient

ChainClient returns the optional consensus RPC client associated with the wallet.

This function is unstable and will be removed once sync logic is moved out of the wallet.

func (*Wallet) ChainParams

func (w *Wallet) ChainParams() *chaincfg.Params

ChainParams returns the network parameters for the blockchain the wallet belongs to.

func (*Wallet) ChainSynced

func (w *Wallet) ChainSynced() bool

ChainSynced returns whether the wallet has been attached to a chain server and synced up to the best block on the main chain.

func (*Wallet) ChangePassphrase

func (w *Wallet) ChangePassphrase(old, new []byte) error

ChangePassphrase attempts to change the passphrase for a wallet from old to new. Changing the passphrase is synchronized with all other address manager locking and unlocking. The lock state will be the same as it was before the password change.

func (*Wallet) CheckAddressPoolsInitialized

func (w *Wallet) CheckAddressPoolsInitialized(account uint32) error

CheckAddressPoolsInitialized checks to make sure an address pool exists that that one can safely access functions and internal memory such as mutexes.

func (*Wallet) CloseAddressPools

func (w *Wallet) CloseAddressPools()

CloseAddressPools grabs one last new address for both internal and external acounts. Then it inserts them into the address manager database, so that the address manager can be used upon startup to restore the cursor position in the address pool.

func (*Wallet) CloseDatabases

func (w *Wallet) CloseDatabases()

CloseDatabases triggers the wallet databases to shut down.

func (*Wallet) Consolidate

func (w *Wallet) Consolidate(inputs int, account uint32) (*chainhash.Hash, error)

Consolidate consolidates as many UTXOs as are passed in the inputs argument. If that many UTXOs can not be found, it will use the maximum it finds. This will only compress UTXOs in the default account

func (*Wallet) CreateMultisigTx

func (w *Wallet) CreateMultisigTx(account uint32, amount dcrutil.Amount,
	pubkeys []*dcrutil.AddressSecpPubKey, nrequired int8,
	minconf int32) (*CreatedTx, dcrutil.Address, []byte, error)

CreateMultisigTx receives a request from the RPC and ships it to txCreator to generate a new multisigtx.

func (*Wallet) CreatePurchaseTicket

func (w *Wallet) CreatePurchaseTicket(minBalance, spendLimit dcrutil.Amount,
	minConf int32, ticketAddr dcrutil.Address, account uint32,
	numTickets int, poolAddress dcrutil.Address,
	poolFees float64, expiry int32) (interface{}, error)

CreatePurchaseTicket receives a request from the RPC and ships it to txCreator to purchase a new ticket.

func (*Wallet) CreateSSGenTx

func (w *Wallet) CreateSSGenTx(ticketHash chainhash.Hash,
	blockHash chainhash.Hash,
	height int64,
	voteBits uint16) (*CreatedTx, error)

CreateSSGenTx receives a request from the RPC and ships it to txCreator to generate a new SSGen.

func (*Wallet) CreateSSRtx

func (w *Wallet) CreateSSRtx(ticketHash chainhash.Hash) (*CreatedTx, error)

CreateSSRtx receives a request from the RPC and ships it to txCreator to generate a new SSRtx.

func (*Wallet) CreateSStxTx

func (w *Wallet) CreateSStxTx(pair map[string]dcrutil.Amount,
	usedInputs []wtxmgr.Credit,
	inputs []dcrjson.SStxInput,
	couts []dcrjson.SStxCommitOut,
	minconf int32) (*CreatedTx, error)

CreateSStxTx receives a request from the RPC and ships it to txCreator to generate a new SStx.

func (*Wallet) CreateSimpleTx

func (w *Wallet) CreateSimpleTx(account uint32, outputs []*wire.TxOut,
	minconf int32) (*txauthor.AuthoredTx, error)

CreateSimpleTx creates a new signed transaction spending unspent P2PKH outputs with at laest minconf confirmations spending to any number of address/amount pairs. Change and an appropriate transaction fee are automatically included, if necessary. All transaction creation through this function is serialized to prevent the creation of many transactions which spend the same outputs.

func (*Wallet) CurrentAddress

func (w *Wallet) CurrentAddress(account uint32) (dcrutil.Address, error)

CurrentAddress gets the most recently requested payment address from a wallet. If the address has already been used (there is at least one transaction spending to it in the blockchain or dcrd mempool), the next chained address is returned.

func (*Wallet) DumpPrivKeys

func (w *Wallet) DumpPrivKeys() ([]string, error)

DumpPrivKeys returns the WIF-encoded private keys for all addresses with private keys in a wallet.

func (*Wallet) DumpWIFPrivateKey

func (w *Wallet) DumpWIFPrivateKey(addr dcrutil.Address) (string, error)

DumpWIFPrivateKey returns the WIF encoded private key for a single wallet address.

func (*Wallet) ExistsAddressOnChain

func (w *Wallet) ExistsAddressOnChain(address dcrutil.Address) (bool, error)

ExistsAddressOnChain is the exported version of existsAddressOnChain that is safe for concurrent access.

func (*Wallet) FindEligibleOutputs

func (w *Wallet) FindEligibleOutputs(account uint32, minconf int32,
	bs *waddrmgr.BlockStamp) ([]wtxmgr.Credit, error)

FindEligibleOutputs is the exported version of findEligibleOutputs (which tried to find unspent outputs that pass a maturity check).

func (*Wallet) Generate added in v0.0.10

func (w *Wallet) Generate() bool

Generate returns the current status of the generation stake of the wallet.

func (*Wallet) GetCurrentVotingInfo

func (w *Wallet) GetCurrentVotingInfo() *VotingInfo

GetCurrentVotingInfo returns a copy of the current voting information.

func (*Wallet) GetStakeDifficulty

func (w *Wallet) GetStakeDifficulty() *StakeDifficultyInfo

GetStakeDifficulty is used to get CurrentStakeDiff information in the wallet. It returns a pointer to a copy of the data.

func (*Wallet) GetTicketMaxPrice

func (w *Wallet) GetTicketMaxPrice() dcrutil.Amount

GetTicketMaxPrice gets the current maximum price the user is willing to pay for a ticket.

func (*Wallet) GetTransactions

func (w *Wallet) GetTransactions(startBlock, endBlock *BlockIdentifier, cancel <-chan struct{}) (*GetTransactionsResult, error)

GetTransactions returns transaction results between a starting and ending block. Blocks in the block range may be specified by either a height or a hash.

Because this is a possibly lenghtly operation, a cancel channel is provided to cancel the task. If this channel unblocks, the results created thus far will be returned.

Transaction results are organized by blocks in ascending order and unmined transactions in an unspecified order. Mined transactions are saved in a Block structure which records properties about the block.

func (*Wallet) HoldUnlock

func (w *Wallet) HoldUnlock() (HeldUnlock, error)

HoldUnlock prevents the wallet from being locked. The HeldUnlock object *must* be released, or the wallet will forever remain unlocked.

TODO: To prevent the above scenario, perhaps closures should be passed to the walletLocker goroutine and disallow callers from explicitly handling the locking mechanism.

func (*Wallet) ImportPrivateKey

func (w *Wallet) ImportPrivateKey(wif *dcrutil.WIF, bs *waddrmgr.BlockStamp,
	rescan bool, scanFrom int32) (string, error)

ImportPrivateKey imports a private key to the wallet and writes the new wallet to disk.

func (*Wallet) ImportScript added in v0.1.5

func (w *Wallet) ImportScript(rs []byte, rescan bool, scanFrom int32) error

ImportScript imports a redeemscript to the wallet. If it also allows the user to specify whether or not they want the redeemscript to be rescanned, and how far back they wish to rescan.

func (*Wallet) ListAddressTransactions

func (w *Wallet) ListAddressTransactions(pkHashes map[string]struct{}) (
	[]dcrjson.ListTransactionsResult, error)

ListAddressTransactions returns a slice of objects with details about recorded transactions to or from any address belonging to a set. This is intended to be used for listaddresstransactions RPC replies.

func (*Wallet) ListAllTransactions

func (w *Wallet) ListAllTransactions() ([]dcrjson.ListTransactionsResult, error)

ListAllTransactions returns a slice of objects with details about a recorded transaction. This is intended to be used for listalltransactions RPC replies.

func (*Wallet) ListSinceBlock

func (w *Wallet) ListSinceBlock(start, end, syncHeight int32) ([]dcrjson.ListTransactionsResult, error)

ListSinceBlock returns a slice of objects with details about transactions since the given block. If the block is -1 then all transactions are included. This is intended to be used for listsinceblock RPC replies.

func (*Wallet) ListTransactions

func (w *Wallet) ListTransactions(from, count int) ([]dcrjson.ListTransactionsResult, error)

ListTransactions returns a slice of objects with details about a recorded transaction. This is intended to be used for listtransactions RPC replies.

func (*Wallet) ListUnspent

func (w *Wallet) ListUnspent(minconf, maxconf int32,
	addresses map[string]struct{}) ([]*dcrjson.ListUnspentResult, error)

ListUnspent returns a slice of objects representing the unspent wallet transactions fitting the given criteria. The confirmations will be more than minconf, less than maxconf and if addresses is populated only the addresses contained within it will be considered. If we know nothing about a transaction an empty array will be returned.

func (*Wallet) Lock

func (w *Wallet) Lock()

Lock locks the wallet's address manager.

func (*Wallet) LockOutpoint

func (w *Wallet) LockOutpoint(op wire.OutPoint)

LockOutpoint marks an outpoint as locked, that is, it should not be used as an input for newly created transactions.

func (*Wallet) Locked

func (w *Wallet) Locked() bool

Locked returns whether the account manager for a wallet is locked.

func (*Wallet) LockedOutpoint

func (w *Wallet) LockedOutpoint(op wire.OutPoint) bool

LockedOutpoint returns whether an outpoint has been marked as locked and should not be used as an input for created transactions.

func (*Wallet) LockedOutpoints

func (w *Wallet) LockedOutpoints() []dcrjson.TransactionInput

LockedOutpoints returns a slice of currently locked outpoints. This is intended to be used by marshaling the result as a JSON array for listlockunspent RPC results.

func (*Wallet) NewAddress

func (w *Wallet) NewAddress(account uint32, branch uint32) (dcrutil.Address,
	error)

NewAddress checks the address pools and then attempts to return a new address for the account and branch requested.

func (*Wallet) NextAccount

func (w *Wallet) NextAccount(name string) (uint32, error)

NextAccount creates the next account and returns its account number. The name must be unique to the account.

func (*Wallet) PoolAddress added in v0.1.0

func (w *Wallet) PoolAddress() dcrutil.Address

PoolAddress gets the pool address for the wallet to give ticket fees to.

func (*Wallet) PoolFees added in v0.1.0

func (w *Wallet) PoolFees() float64

PoolFees gets the per-ticket pool fee for the wallet.

func (*Wallet) PublishTransaction

func (w *Wallet) PublishTransaction(tx *wire.MsgTx) error

PublishTransaction sends the transaction to the consensus RPC server so it can be propigated to other nodes and eventually mined.

This function is unstable and will be removed once syncing code is moved out of the wallet.

func (*Wallet) RelayFee

func (w *Wallet) RelayFee() dcrutil.Amount

RelayFee returns the current minimum relay fee (per kB of serialized transaction) used when constructing transactions.

func (*Wallet) RenameAccount

func (w *Wallet) RenameAccount(account uint32, newName string) error

RenameAccount sets the name for an account number to newName.

func (*Wallet) Rescan

func (w *Wallet) Rescan(addrs []dcrutil.Address, unspent []*wire.OutPoint) error

Rescan begins a rescan for all active addresses and unspent outputs of a wallet. This is intended to be used to sync a wallet back up to the current best block in the main chain, and is considered an initial sync.

func (*Wallet) ResendUnminedTxs

func (w *Wallet) ResendUnminedTxs()

ResendUnminedTxs iterates through all transactions that spend from wallet credits that are not known to have been mined into a block, and attempts to send each to the chain server for relay.

func (*Wallet) ResetLockedOutpoints

func (w *Wallet) ResetLockedOutpoints()

ResetLockedOutpoints resets the set of locked outpoints so all may be used as inputs for new transactions.

func (*Wallet) ReusedAddress

func (w *Wallet) ReusedAddress() (dcrutil.Address, error)

ReusedAddress returns an address that is reused from the external branch of the wallet, to cut down on new address usage for wallets. Should be used judiciously.

func (*Wallet) SendOutputs

func (w *Wallet) SendOutputs(outputs []*wire.TxOut, account uint32,
	minconf int32) (*chainhash.Hash, error)

SendOutputs creates and sends payment transactions. It returns the transaction hash upon success

func (*Wallet) SetBalanceToMaintain

func (w *Wallet) SetBalanceToMaintain(balance dcrutil.Amount)

SetBalanceToMaintain is used to set the current w.balancetomaintain for the wallet.

func (*Wallet) SetChainSynced

func (w *Wallet) SetChainSynced(synced bool)

SetChainSynced marks whether the wallet is connected to and currently in sync with the latest block notified by the chain server.

NOTE: Due to an API limitation with dcrrpcclient, this may return true after the client disconnected (and is attempting a reconnect). This will be unknown until the reconnect notification is received, at which point the wallet can be marked out of sync again until after the next rescan completes.

func (*Wallet) SetCurrentVotingInfo

func (w *Wallet) SetCurrentVotingInfo(blockHash *chainhash.Hash,
	blockHeight int64,
	tickets []*chainhash.Hash)

SetCurrentVotingInfo is used to set the current tickets eligible to vote on the top block, along with that block's hash and height.

func (*Wallet) SetGenerate

func (w *Wallet) SetGenerate(flag bool) error

SetGenerate is used to enable or disable stake mining in the wallet.

func (*Wallet) SetInitiallyUnlocked added in v0.1.5

func (w *Wallet) SetInitiallyUnlocked(set bool)

SetInitiallyUnlocked sets whether or not the wallet is initially unlocked. This allows the user to resync accounts, dictating some of the start up syncing behaviour. It should only be called before the wallet RPC servers are accessible. It is not safe for concurrent access.

func (*Wallet) SetRelayFee

func (w *Wallet) SetRelayFee(relayFee dcrutil.Amount)

SetRelayFee sets a new minimum relay fee (per kB of serialized transaction) used when constructing transactions.

func (*Wallet) SetStakeDifficulty

func (w *Wallet) SetStakeDifficulty(sdi *StakeDifficultyInfo)

SetStakeDifficulty is used to set CurrentStakeDiff information in the wallet.

func (*Wallet) SetTicketFeeIncrement

func (w *Wallet) SetTicketFeeIncrement(fee dcrutil.Amount)

SetTicketFeeIncrement is used to set the current w.ticketFeeIncrement for the wallet.

func (*Wallet) SetTicketMaxPrice

func (w *Wallet) SetTicketMaxPrice(amt dcrutil.Amount)

SetTicketMaxPrice sets the current maximum price the user is willing to pay for a ticket.

func (*Wallet) ShuttingDown

func (w *Wallet) ShuttingDown() bool

ShuttingDown returns whether the wallet is currently in the process of shutting down or not.

func (*Wallet) SignTransaction

func (w *Wallet) SignTransaction(tx *wire.MsgTx, hashType txscript.SigHashType,
	additionalPrevScripts map[wire.OutPoint][]byte,
	additionalKeysByAddress map[string]*dcrutil.WIF,
	p2shRedeemScriptsByAddress map[string][]byte) ([]SignatureError, error)

SignTransaction uses secrets of the wallet, as well as additional secrets passed in by the caller, to create and add input signatures to a transaction.

Transaction input script validation is used to confirm that all signatures are valid. For any invalid input, a SignatureError is added to the returns. The final error return is reserved for unexpected or fatal errors, such as being unable to determine a previous output script to redeem.

The transaction pointed to by tx is modified by this function.

func (*Wallet) SortedActivePaymentAddresses

func (w *Wallet) SortedActivePaymentAddresses() ([]string, error)

SortedActivePaymentAddresses returns a slice of all active payment addresses in a wallet.

func (*Wallet) Start

func (w *Wallet) Start()

Start starts the goroutines necessary to manage a wallet.

func (*Wallet) Stop

func (w *Wallet) Stop()

Stop signals all wallet goroutines to shutdown.

func (*Wallet) SubmitRescan

func (w *Wallet) SubmitRescan(job *RescanJob) <-chan error

SubmitRescan submits a RescanJob to the RescanManager. A channel is returned with the final error of the rescan. The channel is buffered and does not need to be read to prevent a deadlock.

func (*Wallet) SyncAddressPoolIndex added in v0.0.10

func (w *Wallet) SyncAddressPoolIndex(account uint32, branch uint32,
	index uint32) error

SyncAddressPoolIndex synchronizes an account's branch to the given address by iteratively calling getNewAddress on the respective address pool.

func (*Wallet) SynchronizeRPC

func (w *Wallet) SynchronizeRPC(chainClient *chain.RPCClient)

SynchronizeRPC associates the wallet with the consensus RPC client, synchronizes the wallet with the latest changes to the blockchain, and continuously updates the wallet through RPC notifications.

This method is unstable and will be removed when all syncing logic is moved outside of the wallet package.

func (*Wallet) SynchronizingToNetwork

func (w *Wallet) SynchronizingToNetwork() bool

SynchronizingToNetwork returns whether the wallet is currently synchronizing with the Bitcoin network.

func (*Wallet) TicketAddress added in v0.1.0

func (w *Wallet) TicketAddress() dcrutil.Address

TicketAddress gets the ticket address for the wallet to give the ticket voting rights to.

func (*Wallet) TicketFeeIncrement

func (w *Wallet) TicketFeeIncrement() dcrutil.Amount

TicketFeeIncrement is used to get the current feeIncrement for the wallet.

func (*Wallet) TotalReceivedForAccount

func (w *Wallet) TotalReceivedForAccount(account uint32, minConf int32) (dcrutil.Amount, int32, error)

TotalReceivedForAccount iterates through a wallet's transaction history, returning the total amount of decred received for a single wallet account.

func (*Wallet) TotalReceivedForAddr

func (w *Wallet) TotalReceivedForAddr(addr dcrutil.Address, minConf int32) (dcrutil.Amount, error)

TotalReceivedForAddr iterates through a wallet's transaction history, returning the total amount of decred received for a single wallet address.

func (*Wallet) TxToOutputs added in v0.1.1

func (w *Wallet) TxToOutputs(outputs []*wire.TxOut, account uint32, minconf int32,
	randomizeChangeIdx bool) (atx *txauthor.AuthoredTx, err error)

TxToOutputs is the exported version of txToOutputs that does all relevant locking to ensure the safety of the wallet state to generate a transaction. It then calls txToOutputs to generate a transaction.

func (*Wallet) Unlock

func (w *Wallet) Unlock(passphrase []byte, lock <-chan time.Time) error

Unlock unlocks the wallet's address manager and relocks it after timeout has expired. If the wallet is already unlocked and the new passphrase is correct, the current timeout is replaced with the new one. The wallet will be locked if the passphrase is incorrect or any other error occurs during the unlock.

func (*Wallet) UnlockOutpoint

func (w *Wallet) UnlockOutpoint(op wire.OutPoint)

UnlockOutpoint marks an outpoint as unlocked, that is, it may be used as an input for newly created transactions.

func (*Wallet) WaitForShutdown

func (w *Wallet) WaitForShutdown()

WaitForShutdown blocks until all wallet goroutines have finished executing.

Directories

Path Synopsis
internal
Package txauthor provides transaction creation code for wallets.
Package txauthor provides transaction creation code for wallets.
Package txrules provides functions that are help establish whether or not a transaction abides by non-consensus rules for things like the daemon and stake pool.
Package txrules provides functions that are help establish whether or not a transaction abides by non-consensus rules for things like the daemon and stake pool.

Jump to

Keyboard shortcuts

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