udb

package
v0.0.0-...-516309f Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2022 License: ISC Imports: 28 Imported by: 4

Documentation

Index

Constants

View Source
const (
	// MaxAccountNum is the maximum allowed account number.  This value was
	// chosen because accounts are hardened children and therefore must
	// not exceed the hardened child range of extended keys and it provides
	// a reserved account at the top of the range for supporting imported
	// addresses.
	MaxAccountNum = hdkeychain.HardenedKeyStart - 2 // 2^31 - 2

	// MaxAddressesPerAccount is the maximum allowed number of addresses
	// per account number.  This value is based on the limitation of
	// the underlying hierarchical deterministic key derivation.
	MaxAddressesPerAccount = hdkeychain.HardenedKeyStart - 1

	// ImportedAddrAccount is the account number to use for all imported
	// addresses.  This is useful since normal accounts are derived from the
	// root hierarchical deterministic key and imported addresses do not
	// fit into that model.
	ImportedAddrAccount = MaxAccountNum + 1 // 2^31 - 1

	// ImportedAddrAccountName is the name of the imported account.
	ImportedAddrAccountName = "imported"

	// DefaultAccountNum is the number of the default account.
	DefaultAccountNum = 0

	// ExternalBranch is the child number to use when performing BIP0044
	// style hierarchical deterministic key derivation for the external
	// branch.
	ExternalBranch uint32 = 0

	// InternalBranch is the child number to use when performing BIP0044
	// style hierarchical deterministic key derivation for the internal
	// branch.
	InternalBranch uint32 = 1
)
View Source
const (
	// TSImmatureOrLive indicates that the ticket is either
	// live or immature.
	TSImmatureOrLive = iota

	// TSVoted indicates that the ticket was spent as a vote.
	TSVoted

	// TSMissed indicates that the ticket was spent as a
	// revocation.
	TSMissed
)
View Source
const (

	// DBVersion is the latest version of the database that is understood by the
	// program.  Databases with recorded versions higher than this will fail to
	// open (meaning any upgrades prevent reverting to older software).
	DBVersion = hasExpiryFixedVersion
)

Variables

This section is empty.

Functions

func AgendaPreference

func AgendaPreference(tx walletdb.ReadTx, version uint32, agendaID string) (choiceID string)

AgendaPreference returns the saved choice ID, if any, for an agenda ID and deployment version. If no choice has been saved, this returns the empty string.

func DisableLog

func DisableLog()

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

func ExtractBlockHeaderHeight

func ExtractBlockHeaderHeight(header []byte) int32

ExtractBlockHeaderHeight returns the height field that is encoded in the header. Must only be called on known good input.

TODO: This really should not be exported by this package.

func ExtractBlockHeaderParentHash

func ExtractBlockHeaderParentHash(header []byte) []byte

ExtractBlockHeaderParentHash subslices the header to return the bytes of the parent block's hash. Must only be called on known good input.

TODO: This really should not be exported by this package.

func ExtractBlockHeaderTime

func ExtractBlockHeaderTime(header []byte) int64

ExtractBlockHeaderTime returns the unix timestamp that is encoded in the header. Must only be called on known good input. Header timestamps are only 4 bytes and this value is actually limited to a maximum unix time of 2^32-1.

TODO: This really should not be exported by this package.

func Initialize

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

Initialize prepares an empty database for usage by initializing all buckets and key/value pairs. The database is initialized with the latest version and does not require any upgrades to use.

func InitializeWatchOnly

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

InitializeWatchOnly prepares an empty database for watching-only wallet usage by initializing all buckets and key/value pairs. The database is initialized with the latest version and does not require any upgrades to use.

func Migrate

func Migrate(db walletdb.DB, params *chaincfg.Params) error

Migrate converts a database to the first version of the unified database format. If any old upgrades are necessary, they are performed first. Upgrades added after the migration was implemented may still need to be performed.

func NeedsMigration

func NeedsMigration(db walletdb.DB) (bool, error)

NeedsMigration checks whether the database needs to be converted to the unified database format.

func Open

func Open(db walletdb.DB, params *chaincfg.Params, pubPass []byte) (addrMgr *Manager, txStore *Store, stakeStore *StakeStore, err error)

Open opens the database and returns various "manager" types that must be used to access and modify data in the database.

A apperrors.E with an error code of ErrNoExist will be returned if the database has not been initialized. The recorded database version must match exactly with DBVersion. If the version is too low, the erorr code ErrNeedsUpgrade is used and the database must be upgraded. If the version is greater than the one understood by this code, the error code will be ErrUnknownVersion.

func SetAgendaPreference

func SetAgendaPreference(tx walletdb.ReadWriteTx, version uint32, agendaID, choiceID string) error

SetAgendaPreference saves an agenda choice ID for an agenda ID and deployment version.

func Upgrade

func Upgrade(db walletdb.DB, publicPassphrase []byte) error

Upgrade checks whether the any upgrades are necessary before the database is ready for application usage. If any are, they are performed.

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.

func ValidateAccountName

func ValidateAccountName(name string) error

ValidateAccountName validates the given account name and returns an error, if any.

Types

type AccountProperties

type AccountProperties struct {
	AccountNumber             uint32
	AccountName               string
	LastUsedExternalIndex     uint32
	LastUsedInternalIndex     uint32
	LastReturnedExternalIndex uint32
	LastReturnedInternalIndex uint32
	ImportedKeyCount          uint32
}

AccountProperties contains properties associated with each account, such as the account name, number, and the nubmer of derived and imported keys. If no address usage has been recorded on any of the external or internal branches, the child index is ^uint32(0).

type Balances

type Balances struct {
	Account                 uint32
	ImmatureCoinbaseRewards exccutil.Amount
	ImmatureStakeGeneration exccutil.Amount
	LockedByTickets         exccutil.Amount
	Spendable               exccutil.Amount
	Total                   exccutil.Amount
	VotingAuthority         exccutil.Amount
	Unconfirmed             exccutil.Amount
}

Balances is an convenience type.

type Block

type Block struct {
	Hash   chainhash.Hash
	Height int32
}

Block contains the minimum amount of data to uniquely identify any block on either the best or side chain.

type BlockHeaderData

type BlockHeaderData struct {
	BlockHash        chainhash.Hash
	SerializedHeader RawBlockHeader
}

BlockHeaderData contains the block hashes and serialized blocks headers that are inserted into the database. At time of writing this only supports wire protocol version 0 blocks and changes will need to be made if the block header size changes.

type BlockMeta

type BlockMeta struct {
	Block
	Time     time.Time
	VoteBits uint16
}

BlockMeta contains the unique identification for a block and any metadata pertaining to the block. At the moment, this additional metadata only includes the block time from the block header.

type Credit

type Credit struct {
	wire.OutPoint
	BlockMeta
	Amount       exccutil.Amount
	PkScript     []byte
	Received     time.Time
	FromCoinBase bool
	HasExpiry    bool
}

Credit is the type representing a transaction output which was spent or is still spendable by wallet. A UTXO is an unspent Credit, but not all Credits are UTXOs.

type CreditRecord

type CreditRecord struct {
	Index      uint32
	Amount     exccutil.Amount
	Spent      bool
	Change     bool
	OpCode     uint8
	IsCoinbase bool
	HasExpiry  bool
}

CreditRecord contains metadata regarding a transaction credit for a known transaction. Further details may be looked up by indexing a wire.MsgTx.TxOut with the Index field.

type CryptoKeyType

type CryptoKeyType byte

CryptoKeyType is used to differentiate between different kinds of crypto keys.

const (
	// CKTPrivate specifies the key that is used for encryption of private
	// key material such as derived extended private keys and imported
	// private keys.
	CKTPrivate CryptoKeyType = iota

	// CKTScript specifies the key that is used for encryption of scripts.
	CKTScript

	// CKTPublic specifies the key that is used for encryption of public
	// key material such as dervied extended public keys and imported public
	// keys.
	CKTPublic
)

Crypto key types.

type DebitRecord

type DebitRecord struct {
	Amount exccutil.Amount
	Index  uint32
}

DebitRecord contains metadata regarding a transaction debit for a known transaction. Further details may be looked up by indexing a wire.MsgTx.TxIn with the Index field.

type EncryptorDecryptor

type EncryptorDecryptor interface {
	Encrypt(in []byte) ([]byte, error)
	Decrypt(in []byte) ([]byte, error)
	Bytes() []byte
	CopyBytes([]byte)
	Zero()
}

EncryptorDecryptor provides an abstraction on top of snacl.CryptoKey so that our tests can use dependency injection to force the behaviour they need.

type InputSource

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

InputSource provides a method (SelectInputs) to incrementally select unspent outputs to use as transaction inputs.

func (*InputSource) SelectInputs

func (s *InputSource) SelectInputs(target exccutil.Amount) (exccutil.Amount, []*wire.TxIn, [][]byte, error)

SelectInputs selects transaction inputs to redeem unspent outputs stored in the database. It may be called multiple times with increasing target amounts to return additional inputs for a higher target amount. It returns the total input amount referenced by the previous transaction outputs, a slice of transaction inputs referencing these outputs, and a slice of previous output scripts from each previous output referenced by the corresponding input.

type ManagedAddress

type ManagedAddress interface {
	// Account returns the account the address is associated with.
	Account() uint32

	// Address returns a exccutil.Address for the backing address.
	Address() exccutil.Address

	// AddrHash returns the key or script hash related to the address
	AddrHash() []byte

	// Imported returns true if the backing address was imported instead
	// of being part of an address chain.
	Imported() bool

	// Internal returns true if the backing address was created for internal
	// use such as a change output of a transaction.
	Internal() bool

	// Multisig returns true if the backing address was created for multisig
	// use.
	Multisig() bool

	// Compressed returns true if the backing address is compressed.
	Compressed() bool
}

ManagedAddress is an interface that provides acces to information regarding an address managed by an address manager. Concrete implementations of this type may provide further fields to provide information specific to that type of address.

type ManagedPubKeyAddress

type ManagedPubKeyAddress interface {
	ManagedAddress

	// PubKey returns the public key associated with the address.
	PubKey() chainec.PublicKey

	// ExportPubKey returns the public key associated with the address
	// serialized as a hex encoded string.
	ExportPubKey() string
}

ManagedPubKeyAddress extends ManagedAddress and additionally provides the public and private keys for pubkey-based addresses.

type ManagedScriptAddress

type ManagedScriptAddress interface {
	ManagedAddress
	// contains filtered or unexported methods
}

ManagedScriptAddress extends ManagedAddress and represents a pay-to-script-hash style of addresses.

type Manager

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

Manager represents a concurrency safe crypto currency address manager and key store.

func (*Manager) AccountBranchExtendedPubKey

func (m *Manager) AccountBranchExtendedPubKey(dbtx walletdb.ReadTx, account, branch uint32) (*hdkeychain.ExtendedKey, error)

AccountBranchExtendedPubKey returns the extended public key of an account's branch, which then can be used to derive addresses belonging to the account.

func (*Manager) AccountExtendedPubKey

func (m *Manager) AccountExtendedPubKey(dbtx walletdb.ReadTx, account uint32) (*hdkeychain.ExtendedKey, error)

AccountExtendedPubKey returns the extended public key for an account, which can then be used to derive BIP0044 branch keys.

func (*Manager) AccountName

func (m *Manager) AccountName(ns walletdb.ReadBucket, account uint32) (string, error)

AccountName returns the account name for the given account number stored in the manager.

func (*Manager) AccountProperties

func (m *Manager) AccountProperties(ns walletdb.ReadBucket, account uint32) (*AccountProperties, error)

AccountProperties returns properties associated with the account, such as the account number, name, and the number of derived and imported keys.

TODO: Instead of opening a second read transaction after making a change, and then fetching the account properties with a new read tx, this can be made more performant by simply returning the new account properties during the change.

func (*Manager) AddrAccount

func (m *Manager) AddrAccount(ns walletdb.ReadBucket, address exccutil.Address) (uint32, error)

AddrAccount returns the account to which the given address belongs.

func (*Manager) Address

func (m *Manager) Address(ns walletdb.ReadBucket, address exccutil.Address) (ManagedAddress, error)

Address returns a managed address given the passed address if it is known to the address manager. A managed address differs from the passed address in that it also potentially contains extra information needed to sign transactions such as the associated private key for pay-to-pubkey and pay-to-pubkey-hash addresses and the script associated with pay-to-script-hash addresses.

func (*Manager) ChainParams

func (m *Manager) ChainParams() *chaincfg.Params

ChainParams returns the chain parameters for this address manager.

func (*Manager) ChangePassphrase

func (m *Manager) ChangePassphrase(ns walletdb.ReadWriteBucket, oldPassphrase, newPassphrase []byte,
	private bool) error

ChangePassphrase changes either the public or private passphrase to the provided value depending on the private flag. In order to change the private password, the address manager must not be watching-only. The new passphrase keys are derived using the scrypt parameters in the options, so changing the passphrase may be used to bump the computational difficulty needed to brute force the passphrase.

func (*Manager) Close

func (m *Manager) Close() error

Close cleanly shuts down the manager. It makes a best try effort to remove and zero all private key and sensitive public key material associated with the address manager from memory.

func (*Manager) CoinTypePrivKey

func (m *Manager) CoinTypePrivKey(dbtx walletdb.ReadTx) (*hdkeychain.ExtendedKey, error)

CoinTypePrivKey returns the coin type private key at the BIP0044 path m/44'/<coin type>' (coin type child indexes differ by the network). The key and all derived private keys should be cleared by the caller when finished. This method requires the wallet to be unlocked.

func (*Manager) ConvertToWatchingOnly

func (m *Manager) ConvertToWatchingOnly(ns walletdb.ReadWriteBucket) error

ConvertToWatchingOnly converts the current address manager to a locked watching-only address manager.

WARNING: This function removes private keys from the existing address manager which means they will no longer be available. Typically the caller will make a copy of the existing wallet database and modify the copy since otherwise it would mean permanent loss of any imported private keys and scripts.

Executing this function on a manager that is already watching-only will have no effect.

func (*Manager) Decrypt

func (m *Manager) Decrypt(keyType CryptoKeyType, in []byte) ([]byte, error)

Decrypt in using the crypto key type specified by keyType.

func (*Manager) Encrypt

func (m *Manager) Encrypt(keyType CryptoKeyType, in []byte) ([]byte, error)

Encrypt in using the crypto key type specified by keyType.

func (*Manager) ExistsHash160

func (m *Manager) ExistsHash160(ns walletdb.ReadBucket, hash160 []byte) bool

ExistsHash160 returns whether or not the 20 byte P2PKH or P2SH HASH160 is known to the address manager.

func (*Manager) ForEachAccount

func (m *Manager) ForEachAccount(ns walletdb.ReadBucket, fn func(account uint32) error) error

ForEachAccount calls the given function with each account stored in the manager, breaking early on error.

func (*Manager) ForEachAccountAddress

func (m *Manager) ForEachAccountAddress(ns walletdb.ReadBucket, account uint32,
	fn func(maddr ManagedAddress) error) error

ForEachAccountAddress calls the given function with each address of the given account stored in the manager, breaking early on error.

func (*Manager) ForEachActiveAccountAddress

func (m *Manager) ForEachActiveAccountAddress(ns walletdb.ReadBucket, account uint32,
	fn func(maddr ManagedAddress) error) error

ForEachActiveAccountAddress calls the given function with each active address of the given account stored in the manager, breaking early on error. TODO(tuxcanfly): actually return only active addresses

func (*Manager) ForEachActiveAddress

func (m *Manager) ForEachActiveAddress(ns walletdb.ReadBucket, fn func(addr exccutil.Address) error) error

ForEachActiveAddress calls the given function with each active address stored in the manager, breaking early on error.

func (*Manager) GetMasterPubkey

func (m *Manager) GetMasterPubkey(ns walletdb.ReadBucket, account uint32) (string, error)

GetMasterPubkey gives the encoded string version of the HD master public key for the default account of the wallet.

func (*Manager) ImportPrivateKey

func (m *Manager) ImportPrivateKey(ns walletdb.ReadWriteBucket, wif *exccutil.WIF) (ManagedPubKeyAddress, error)

ImportPrivateKey imports a WIF private key into the address manager. The imported address is created using either a compressed or uncompressed serialized public key, depending on the CompressPubKey bool of the WIF.

All imported addresses will be part of the account defined by the ImportedAddrAccount constant.

NOTE: When the address manager is watching-only, the private key itself will not be stored or available since it is private data. Instead, only the public key will be stored. This means it is paramount the private key is kept elsewhere as the watching-only address manager will NOT ever have access to it.

This function will return an error if the address manager is locked and not watching-only, or not for the same network as the key trying to be imported. It will also return an error if the address already exists. Any other errors returned are generally unexpected.

func (*Manager) ImportScript

func (m *Manager) ImportScript(ns walletdb.ReadWriteBucket, script []byte) (ManagedScriptAddress, error)

ImportScript imports a user-provided script into the address manager. The imported script will act as a pay-to-script-hash address.

All imported script addresses will be part of the account defined by the ImportedAddrAccount constant.

When the address manager is watching-only, the script itself will not be stored or available since it is considered private data.

This function will return an error if the address manager is locked and not watching-only, or the address already exists. Any other errors returned are generally unexpected.

func (*Manager) IsLocked

func (m *Manager) IsLocked() bool

IsLocked returns whether or not the address managed is locked. When it is unlocked, the decryption key needed to decrypt private keys used for signing is in memory.

func (*Manager) LastAccount

func (m *Manager) LastAccount(ns walletdb.ReadBucket) (uint32, error)

LastAccount returns the last account stored in the manager.

func (*Manager) Lock

func (m *Manager) Lock() error

Lock performs a best try effort to remove and zero all secret keys associated with the address manager.

This function will return an error if invoked on a watching-only address manager.

func (*Manager) LookupAccount

func (m *Manager) LookupAccount(ns walletdb.ReadBucket, name string) (uint32, error)

LookupAccount loads account number stored in the manager for the given account name

func (*Manager) MarkReturnedChildIndex

func (m *Manager) MarkReturnedChildIndex(tx walletdb.ReadWriteTx, account, branch, child uint32) error

MarkReturnedChildIndex marks a BIP0044 account branch child as returned to a caller. This method will write returned child indexes that are lower than the currently-recorded last returned indexes, but these indexes will never be lower than the last used index.

func (*Manager) MarkUsed

func (m *Manager) MarkUsed(ns walletdb.ReadWriteBucket, address exccutil.Address) error

MarkUsed updates usage statistics of a BIP0044 account address so that the last used address index can be tracked. There is no effect when called on P2SH addresses or any imported addresses.

func (*Manager) MarkUsedChildIndex

func (m *Manager) MarkUsedChildIndex(tx walletdb.ReadWriteTx, account, branch, child uint32) error

MarkUsedChildIndex marks a BIP0044 account branch child as used.

func (*Manager) NewAccount

func (m *Manager) NewAccount(ns walletdb.ReadWriteBucket, name string) (uint32, error)

NewAccount creates and returns a new account stored in the manager based on the given account name. If an account with the same name already exists, ErrDuplicateAccount will be returned. Since creating a new account requires access to the cointype keys (from which extended account keys are derived), it requires the manager to be unlocked.

func (*Manager) PrivateKey

func (m *Manager) PrivateKey(ns walletdb.ReadBucket, addr exccutil.Address) (key chainec.PrivateKey, done func(), err error)

PrivateKey retreives the private key for a P2PK or P2PKH address. If this function returns without error, the returned 'done' function must be called when the private key is no longer being used. Failure to do so will cause deadlocks when the manager is locked.

func (*Manager) RedeemScript

func (m *Manager) RedeemScript(ns walletdb.ReadBucket, addr exccutil.Address) (script []byte, done func(), err error)

RedeemScript retreives the redeem script to redeem an output paid to a P2SH address. If this function returns without error, the returned 'done' function must be called when the script is no longer being used. Failure to do so will cause deadlocks when the manager is locked.

func (*Manager) RenameAccount

func (m *Manager) RenameAccount(ns walletdb.ReadWriteBucket, account uint32, name string) error

RenameAccount renames an account stored in the manager based on the given account number with the given name. If an account with the same name already exists, ErrDuplicateAccount will be returned.

func (*Manager) SyncAccountToAddrIndex

func (m *Manager) SyncAccountToAddrIndex(ns walletdb.ReadWriteBucket, account uint32, syncToIndex uint32, branch uint32) error

SyncAccountToAddrIndex returns the specified number of next chained addresses that are intended for internal use such as change from the address manager.

func (*Manager) Unlock

func (m *Manager) Unlock(ns walletdb.ReadBucket, passphrase []byte) error

Unlock derives the master private key from the specified passphrase. An invalid passphrase will return an error. Otherwise, the derived secret key is stored in memory until the address manager is locked. Any failures that occur during this function will result in the address manager being locked, even if it was already unlocked prior to calling this function.

This function will return an error if invoked on a watching-only address manager.

func (*Manager) WatchingOnly

func (m *Manager) WatchingOnly() bool

WatchingOnly returns whether or not the wallet is in watching only mode.

type MultisigCredit

type MultisigCredit struct {
	OutPoint   *wire.OutPoint
	ScriptHash [ripemd160.Size]byte
	MSScript   []byte
	M          uint8
	N          uint8
	Amount     exccutil.Amount
}

MultisigCredit is a redeemable P2SH multisignature credit.

type MultisigOut

type MultisigOut struct {
	OutPoint     *wire.OutPoint
	Tree         int8
	ScriptHash   [ripemd160.Size]byte
	M            uint8
	N            uint8
	TxHash       chainhash.Hash
	BlockHash    chainhash.Hash
	BlockHeight  uint32
	Amount       exccutil.Amount
	Spent        bool
	SpentBy      chainhash.Hash
	SpentByIndex uint32
}

MultisigOut represents a spendable multisignature outpoint contain a script hash.

type ObtainUserInputFunc

type ObtainUserInputFunc func() ([]byte, error)

ObtainUserInputFunc is a function that reads a user input and returns it as a byte stream. It is used to accept data required during upgrades, for e.g. wallet seed and private passphrase.

type PoolTicket

type PoolTicket struct {
	Ticket       chainhash.Hash
	HeightTicket uint32 // Not used or guaranteed to be correct
	Status       TicketStatus
	HeightSpent  uint32
	SpentBy      chainhash.Hash
}

PoolTicket is a 73-byte struct that is used to preserve user's ticket information when they have an account at the stake pool.

type RawBlockHeader

type RawBlockHeader [wire.MaxBlockHeaderPayload]byte

RawBlockHeader is block header of max possible len (always true for version 0 blocks).

func (*RawBlockHeader) Height

func (h *RawBlockHeader) Height() int32

Height extracts the height encoded in a block header.

type ScryptOptions

type ScryptOptions struct {
	N, R, P int
}

ScryptOptions is used to hold the scrypt parameters needed when deriving new passphrase keys.

type StakePoolUser

type StakePoolUser struct {
	Tickets        []*PoolTicket
	InvalidTickets []*chainhash.Hash
}

StakePoolUser is a list of tickets for a given user (P2SH address) in the stake pool.

type StakeStore

type StakeStore struct {
	Params  *chaincfg.Params
	Manager *Manager
	// contains filtered or unexported fields
}

StakeStore represents a safely accessible database of stake transactions.

func (*StakeStore) DumpSStxHashes

func (s *StakeStore) DumpSStxHashes() []chainhash.Hash

DumpSStxHashes returns the hashes of all wallet ticket purchase transactions.

func (*StakeStore) DumpSStxHashesForAddress

func (s *StakeStore) DumpSStxHashesForAddress(ns walletdb.ReadBucket, addr exccutil.Address) ([]chainhash.Hash, error)

DumpSStxHashesForAddress returns the hashes of all wallet ticket purchase transactions for an address.

func (*StakeStore) InsertSStx

func (s *StakeStore) InsertSStx(ns walletdb.ReadWriteBucket, sstx *exccutil.Tx) error

InsertSStx is the exported version of insertSStx that is safe for concurrent access.

func (*StakeStore) OwnTicket

func (s *StakeStore) OwnTicket(hash *chainhash.Hash) bool

OwnTicket returns whether the ticket is tracked by the stake manager.

func (*StakeStore) RemoveStakePoolUserInvalTickets

func (s *StakeStore) RemoveStakePoolUserInvalTickets(ns walletdb.ReadWriteBucket, user exccutil.Address,
	ticket *chainhash.Hash) error

RemoveStakePoolUserInvalTickets is the exported and concurrency safe form of removetStakePoolUserInvalTickets.

func (*StakeStore) SStxAddress

func (s *StakeStore) SStxAddress(ns walletdb.ReadBucket, hash *chainhash.Hash) (exccutil.Address, error)

SStxAddress is the exported, concurrency safe version of sstxAddress.

func (*StakeStore) StakePoolUserInfo

func (s *StakeStore) StakePoolUserInfo(ns walletdb.ReadBucket, user exccutil.Address) (*StakePoolUser, error)

StakePoolUserInfo returns the stake pool user information for a given stake pool user, keyed to their P2SH voting address.

func (*StakeStore) TicketPurchase

func (s *StakeStore) TicketPurchase(dbtx walletdb.ReadTx, hash *chainhash.Hash) (*wire.MsgTx, error)

TicketPurchase returns the ticket purchase transaction recorded in the "stake manager" portion of the DB.

TODO: This is redundant and should be looked up in from the transaction manager. Left for now for compatibility.

func (*StakeStore) UpdateStakePoolUserInvalTickets

func (s *StakeStore) UpdateStakePoolUserInvalTickets(ns walletdb.ReadWriteBucket, user exccutil.Address, ticket *chainhash.Hash) error

UpdateStakePoolUserInvalTickets is the exported and concurrency safe form of updateStakePoolUserInvalTickets.

func (*StakeStore) UpdateStakePoolUserTickets

func (s *StakeStore) UpdateStakePoolUserTickets(ns walletdb.ReadWriteBucket, user exccutil.Address, ticket *PoolTicket) error

UpdateStakePoolUserTickets is the exported and concurrency safe form of updateStakePoolUserTickets.

type Store

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

Store implements a transaction store for storing and managing wallet transactions.

func (*Store) AccountBalance

func (s *Store) AccountBalance(ns, addrmgrNs walletdb.ReadBucket, minConf int32,
	account uint32) (Balances, error)

AccountBalance returns a Balances struct for some given account at syncHeight block height with all UTXOS that have minConf manyn confirms.

func (*Store) AccountBalances

func (s *Store) AccountBalances(ns, addrmgrNs walletdb.ReadBucket,
	minConf int32) (map[uint32]*Balances, error)

AccountBalances returns a map of all account balances at syncHeight block height with all UTXOs that have minConf many confirms.

func (*Store) AddCredit

func (s *Store) AddCredit(ns walletdb.ReadWriteBucket, rec *TxRecord, block *BlockMeta,
	index uint32, change bool, account uint32) error

AddCredit marks a transaction record as containing a transaction output spendable by wallet. The output is added unspent, and is marked spent when a new transaction spending the output is inserted into the store.

TODO(jrick): This should not be necessary. Instead, pass the indexes that are known to contain credits when a transaction or merkleblock is inserted into the store.

func (*Store) AddMultisigOut

func (s *Store) AddMultisigOut(ns walletdb.ReadWriteBucket, rec *TxRecord, block *BlockMeta,
	index uint32) error

AddMultisigOut adds a P2SH multisignature spendable output into the transaction manager. In the event that the output already existed but was not mined, the output is updated so its value reflects the block it was included in.

func (*Store) BlockInMainChain

func (s *Store) BlockInMainChain(dbtx walletdb.ReadTx, blockHash *chainhash.Hash) (inMainChain bool, invalidated bool)

BlockInMainChain returns whether a block identified by its hash is in the current main chain and if so, whether it has been stake invalidated by the next main chain block.

func (*Store) BlockLocators

func (s *Store) BlockLocators(ns walletdb.ReadBucket) []*chainhash.Hash

BlockLocators returns, in reversed order (newest blocks first), hashes of blocks believed to be on the main chain. For memory and lookup efficiency, many older hashes are skipped, with increasing gaps between included hashes. This returns the block locators that should be included in a getheaders wire message or RPC request.

func (*Store) ExistsTx

func (s *Store) ExistsTx(ns walletdb.ReadBucket, txHash *chainhash.Hash) bool

ExistsTx checks to see if a transaction exists in the database.

func (*Store) ExistsUTXO

func (s *Store) ExistsUTXO(dbtx walletdb.ReadTx, op *wire.OutPoint) bool

ExistsUTXO checks to see if op refers to an unspent transaction output or a credit spent by an unmined transaction. This check is sufficient to determine whether a transaction input is relevant to the wallet by spending a UTXO or conflicting with another mempool transaction that double spends the output.

func (*Store) ExtendMainChain

func (s *Store) ExtendMainChain(ns walletdb.ReadWriteBucket, header *BlockHeaderData) error

ExtendMainChain inserts a block header into the database. It must connect to the existing tip block.

If the block is already inserted and part of the main chain, an error with code ErrDuplicate is returned.

func (*Store) GetBlockMetaForHash

func (s *Store) GetBlockMetaForHash(ns walletdb.ReadBucket, blockHash *chainhash.Hash) (BlockMeta, error)

GetBlockMetaForHash returns the BlockMeta for a block specified by its hash.

TODO: This is legacy code now that headers are saved. BlockMeta can be removed.

func (*Store) GetMainChainBlockHashForHeight

func (s *Store) GetMainChainBlockHashForHeight(ns walletdb.ReadBucket, height int32) (chainhash.Hash, error)

GetMainChainBlockHashForHeight returns the block hash of the block on the main chain at a given height.

func (*Store) GetMainChainBlockHashes

func (s *Store) GetMainChainBlockHashes(ns walletdb.ReadBucket, startHash *chainhash.Hash,
	inclusive bool, storage []chainhash.Hash) ([]chainhash.Hash, error)

GetMainChainBlockHashes returns block hashes from the main chain, starting at startHash, copying as many as possible into the storage slice and returning a subslice for the total number of results. If the start hash is not in the main chain, this function errors. If inclusive is true, the startHash is included in the results, otherwise only blocks after the startHash are included.

func (*Store) GetMultisigCredit

func (s *Store) GetMultisigCredit(ns walletdb.ReadBucket, op *wire.OutPoint) (*MultisigCredit, error)

GetMultisigCredit takes an outpoint and returns multisignature credit data stored about it.

func (*Store) GetMultisigOutput

func (s *Store) GetMultisigOutput(ns walletdb.ReadBucket, op *wire.OutPoint) (*MultisigOut, error)

GetMultisigOutput takes an outpoint and returns multisignature credit data stored about it.

func (*Store) GetSerializedBlockHeader

func (s *Store) GetSerializedBlockHeader(ns walletdb.ReadBucket, blockHash *chainhash.Hash) ([]byte, error)

GetSerializedBlockHeader returns the bytes of the serialized header for the block specified by its hash. These bytes are a copy of the value returned from the DB and are usable outside of the transaction.

func (*Store) GetTxScript

func (s *Store) GetTxScript(ns walletdb.ReadBucket, hash []byte) ([]byte, error)

GetTxScript is the exported version of getTxScript.

func (*Store) InsertMainChainHeaders

func (s *Store) InsertMainChainHeaders(ns walletdb.ReadWriteBucket, addrmgrNs walletdb.ReadBucket,
	headers []BlockHeaderData) error

InsertMainChainHeaders permanently saves block headers. Headers should be in order of increasing heights and there should not be any gaps between blocks. After inserting headers, if the existing recorded tip block is behind the last main chain block header that was inserted, a chain switch occurs and the new tip block is recorded.

func (*Store) InsertMemPoolTx

func (s *Store) InsertMemPoolTx(ns walletdb.ReadWriteBucket, rec *TxRecord) error

InsertMemPoolTx inserts a memory pool transaction record. It also marks previous outputs referenced by its inputs as spent. Errors with the apperrors.ErrDoubleSpend code if another unmined transaction is a double spend of this transaction.

func (*Store) InsertMinedTx

func (s *Store) InsertMinedTx(ns walletdb.ReadWriteBucket, addrmgrNs walletdb.ReadBucket, rec *TxRecord,
	blockHash *chainhash.Hash) error

InsertMinedTx inserts a new transaction record for a mined transaction into the database. The block header must have been previously saved. If the exact transaction is already saved as an unmined transaction, it is moved to a block. Other unmined transactions which become double spends are removed.

func (*Store) InsertTxScript

func (s *Store) InsertTxScript(ns walletdb.ReadWriteBucket, script []byte) error

InsertTxScript is the exported version of insertTxScript.

func (*Store) IterateTickets

func (s *Store) IterateTickets(dbtx walletdb.ReadTx) *TicketIterator

IterateTickets returns an object used to iterate over all ticket purchase transactions.

func (*Store) MainChainTip

func (s *Store) MainChainTip(ns walletdb.ReadBucket) (chainhash.Hash, int32)

MainChainTip returns the hash and height of the currently marked tip-most block of the main chain.

func (*Store) MakeInputSource

func (s *Store) MakeInputSource(ns, addrmgrNs walletdb.ReadBucket, account uint32, minConf, syncHeight int32) InputSource

MakeInputSource creates an InputSource to redeem unspent outputs from an account. The minConf and syncHeight parameters are used to filter outputs based on some spendable policy.

func (*Store) OwnTicket

func (s *Store) OwnTicket(dbtx walletdb.ReadTx, ticketHash *chainhash.Hash) bool

OwnTicket returns whether ticketHash is the hash of a ticket purchase transaction managed by the wallet.

func (*Store) PreviousPkScripts

func (s *Store) PreviousPkScripts(ns walletdb.ReadBucket, rec *TxRecord, block *Block) ([][]byte, error)

PreviousPkScripts returns a slice of previous output scripts for each credit output this transaction record debits from.

func (*Store) PruneUnmined

func (s *Store) PruneUnmined(dbtx walletdb.ReadWriteTx, stakeDiff int64) error

PruneUnmined removes unmined transactions that no longer belong in the unmined tx set. This includes:

  • Any transactions past a set expiry
  • Ticket purchases with a different ticket price than the passed stake difficulty
  • Votes that do not vote on the tip block

func (*Store) RangeTransactions

func (s *Store) RangeTransactions(ns walletdb.ReadBucket, begin, end int32,
	f func([]TxDetails) (bool, error)) error

RangeTransactions runs the function f on all transaction details between blocks on the best chain over the height range [begin,end]. The special height -1 may be used to also include unmined transactions. If the end height comes before the begin height, blocks are iterated in reverse order and unmined transactions (if any) are processed first.

The function f may return an error which, if non-nil, is propagated to the caller. Additionally, a boolean return value allows exiting the function early without reading any additional transactions early when true.

All calls to f are guaranteed to be passed a slice with more than zero elements. The slice may be reused for multiple blocks, so it is not safe to use it after the loop iteration it was acquired.

func (*Store) Rollback

func (s *Store) Rollback(ns walletdb.ReadWriteBucket, addrmgrNs walletdb.ReadBucket, height int32) error

Rollback removes all blocks at height onwards, moving any transactions within each block to the unconfirmed pool.

func (*Store) SpendMultisigOut

func (s *Store) SpendMultisigOut(ns walletdb.ReadWriteBucket, op *wire.OutPoint,
	spendHash chainhash.Hash, spendIndex uint32) error

SpendMultisigOut spends a multisignature output by making it spent in the general bucket and removing it from the unspent bucket.

func (*Store) StoredTxScripts

func (s *Store) StoredTxScripts(ns walletdb.ReadBucket) ([][]byte, error)

StoredTxScripts is the exported version of storedTxScripts.

func (*Store) TicketDetails

func (s *Store) TicketDetails(ns walletdb.ReadBucket, txDetails *TxDetails) (*TicketDetails, error)

TicketDetails looks up all recorded details regarding a ticket with some hash.

Not finding a ticket with this hash is not an error. In this case, a nil TicketDetiails is returned.

func (*Store) TotalInput

func (s *Store) TotalInput(dbtx walletdb.ReadTx, tx *wire.MsgTx) (exccutil.Amount, error)

TotalInput calculates the input value referenced by all transaction inputs. If this is not calculable, this returns 0.

func (*Store) Tx

func (s *Store) Tx(ns walletdb.ReadBucket, txHash *chainhash.Hash) (*wire.MsgTx, error)

Tx looks up all the stored wire.MsgTx for a transaction with some hash. In case of a hash collision, the most recent transaction with a matching hash is returned.

Not finding a transaction with this hash is not an error. In this case, a nil TxDetails is returned.

func (*Store) TxBlockHeight

func (s *Store) TxBlockHeight(dbtx walletdb.ReadTx, txHash *chainhash.Hash) (int32, error)

TxBlockHeight returns the block height of a mined transaction, or -1 for any unmined transactions.

func (*Store) TxDetails

func (s *Store) TxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash) (*TxDetails, error)

TxDetails looks up all recorded details regarding a transaction with some hash. In case of a hash collision, the most recent transaction with a matching hash is returned.

Not finding a transaction with this hash is not an error. In this case, a nil TxDetails is returned.

func (*Store) UniqueTxDetails

func (s *Store) UniqueTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash,
	block *Block) (*TxDetails, error)

UniqueTxDetails looks up all recorded details for a transaction recorded mined in some particular block, or an unmined transaction if block is nil.

Not finding a transaction with this hash from this block is not an error. In this case, a nil TxDetails is returned.

func (*Store) UnminedTxHashes

func (s *Store) UnminedTxHashes(ns walletdb.ReadBucket) ([]*chainhash.Hash, error)

UnminedTxHashes returns the hashes of all transactions not known to have been mined in a block.

func (*Store) UnminedTxs

func (s *Store) UnminedTxs(ns walletdb.ReadBucket) ([]*wire.MsgTx, error)

UnminedTxs returns the underlying transactions for all unmined transactions which are not known to have been mined in a block. Transactions are guaranteed to be sorted by their dependency order.

func (*Store) UnspentMultisigCredits

func (s *Store) UnspentMultisigCredits(ns walletdb.ReadBucket) ([]*MultisigCredit, error)

UnspentMultisigCredits returns all unspent multisignature P2SH credits in the wallet.

func (*Store) UnspentMultisigCreditsForAddress

func (s *Store) UnspentMultisigCreditsForAddress(ns walletdb.ReadBucket,
	addr exccutil.Address) ([]*MultisigCredit, error)

UnspentMultisigCreditsForAddress returns all unspent multisignature P2SH credits in the wallet for some specified address.

func (*Store) UnspentOutpoints

func (s *Store) UnspentOutpoints(ns walletdb.ReadBucket) ([]wire.OutPoint, error)

UnspentOutpoints returns all unspent received transaction outpoints. The order is undefined.

func (*Store) UnspentOutputs

func (s *Store) UnspentOutputs(ns walletdb.ReadBucket) ([]*Credit, error)

UnspentOutputs returns all unspent received transaction outputs. The order is undefined.

func (*Store) UnspentOutputsForAmount

func (s *Store) UnspentOutputsForAmount(ns, addrmgrNs walletdb.ReadBucket,
	amt exccutil.Amount, height int32, minConf int32, all bool,
	account uint32) ([]*Credit, error)

UnspentOutputsForAmount returns all non-stake outputs that sum up to the amount passed. If not enough funds are found, a nil pointer is returned without error.

func (*Store) UnspentTickets

func (s *Store) UnspentTickets(dbtx walletdb.ReadTx, syncHeight int32, includeImmature bool) ([]chainhash.Hash, error)

UnspentTickets returns all unspent tickets that are known for this wallet. Tickets that have been spent by an unmined vote that is not a vote on the tip block are also considered unspent and are returned. The order of the hashes is undefined.

type Ticket

type Ticket struct {
	TxRecord
	Block       Block          // Height -1 if unmined
	SpenderHash chainhash.Hash // Zero value if unspent
}

Ticket embeds a TxRecord for a ticket purchase transaction, the block it is mined in (if any), and the transaction hash of the vote or revocation transaction that spends the ticket (if any).

type TicketDetails

type TicketDetails struct {
	Ticket  *TxDetails
	Spender *TxDetails
}

TicketDetails is intended to provide callers with access to rich details regarding a relevant transaction and which inputs and outputs are credit or debits.

type TicketIterator

type TicketIterator struct {
	Ticket
	// contains filtered or unexported fields
}

TicketIterator is used to iterate over all ticket purchase transactions.

func (*TicketIterator) Err

func (it *TicketIterator) Err() error

Err returns the final error state of the iterator. It should be checked after iteration completes when Next returns false.

func (*TicketIterator) Next

func (it *TicketIterator) Next() bool

Next reads the next Ticket from the database, writing it to the iterator's embedded Ticket member. Returns false after all tickets have been iterated over or an error occurs.

type TicketStatus

type TicketStatus uint8

TicketStatus is the current status of a stake pool ticket.

type TxDetails

type TxDetails struct {
	TxRecord
	Block   BlockMeta
	Credits []CreditRecord
	Debits  []DebitRecord
}

TxDetails is intended to provide callers with access to rich details regarding a relevant transaction and which inputs and outputs are credit or debits.

func (*TxDetails) Height

func (t *TxDetails) Height() int32

Height returns the height of a transaction according to the BlockMeta.

type TxRecord

type TxRecord struct {
	MsgTx        wire.MsgTx
	Hash         chainhash.Hash
	Received     time.Time
	SerializedTx []byte // Optional: may be nil
	TxType       stake.TxType
}

TxRecord represents a transaction managed by the Store.

func NewTxRecord

func NewTxRecord(serializedTx []byte, received time.Time) (*TxRecord, error)

NewTxRecord creates a new transaction record that may be inserted into the store. It uses memoization to save the transaction hash and the serialized transaction.

func NewTxRecordFromMsgTx

func NewTxRecordFromMsgTx(msgTx *wire.MsgTx, received time.Time) (*TxRecord, error)

NewTxRecordFromMsgTx creates a new transaction record that may be inserted into the store.

Jump to

Keyboard shortcuts

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