wallet

package
v0.0.0-...-3680526 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2023 License: MIT Imports: 46 Imported by: 0

Documentation

Overview

Copyright (c) 2018-2020 The qitmeer developers Copyright (c) 2013-2017 The btcsuite developers Copyright (c) 2015-2016 The Decred developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Index

Constants

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"

	ImportTxID       = "0000000000000000000000000000000000000000000000000000000000000000"
	ImportTxIndex    = types.SupperPrevOutIndex
	ImportTxSequence = types.TxTypeCrossChainImport
)
View Source
const (
	PageUseDefault  = -1
	PageDefaultNo   = 1
	PageDefaultSize = 10
	PageMaxSize     = 1000000000
	FilterIn        = 0
	FilterOut       = 1
	FilterAll       = 2
)
View Source
const CoinBaseMaturity = 720

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

Functions

func Create

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

func DecodeToken

func DecodeToken(bytes []byte) (*json.TokenState, error)

func EncodeToken

func EncodeToken(state json.TokenState) []byte

func IsValidIDType

func IsValidIDType(id interface{}) bool

IsValidIDType id string number

func NewHtpc

func NewHtpc(cfg *config.Config) (*httpConfig, error)

NewHtpc make qitmeerd http client

func NewHtpcByCfg

func NewHtpcByCfg(cfg *client.Config) (*httpConfig, error)

NewHtpcByCfg new httpConfig by cfg

func NewNotificationRpc

func NewNotificationRpc(cfg *config.Config, handlers client.NotificationHandlers) (*client.Client, error)

func TxEncode

func TxEncode(version uint32, lockTime uint32, timestamp *time.Time, inputs []Input, outputs []qx.Output) (string, error)

Types

type API

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

API for wallet

func NewAPI

func NewAPI(cfg *config.Config, wt *Wallet) *API

NewAPI make api

func (*API) CreateAccount

func (api *API) CreateAccount(name string) error

CreateAccount create account

func (*API) CreateAddress

func (api *API) CreateAddress(accountName string) (string, error)

CreateAddress by accountName

func (*API) DumpPrivKey

func (api *API) DumpPrivKey(addrStr string) (string, error)

DumpPrivKey dump a single address private key

dumpPriKey handles a DumpPrivKey request with the private key for a single address, or an appropiate error if the wallet is locked.

func (*API) GetAccountByAddress

func (api *API) GetAccountByAddress(addrStr string) (string, error)

GetAccountByAddress get account name

func (*API) GetAccountsAndBalance

func (api *API) GetAccountsAndBalance(coin types.CoinID) (map[string]*Value, error)

GetAccountsAndBalance List all accounts[{account,balance}]

func (*API) GetAddressesByAccount

func (api *API) GetAddressesByAccount(accountName string) ([]string, error)

GetAddressesByAccount by account

func (*API) GetBalanceByAccount

func (api *API) GetBalanceByAccount(name string, coin types.CoinID) (*Value, error)

GetBalanceByAccount get account balance

func (*API) GetBalanceByAddr

func (api *API) GetBalanceByAddr(addrStr string, coin types.CoinID) (map[string]Value, error)

GetBalanceByAddr get balance by address

func (*API) GetBillByAddr

func (api *API) GetBillByAddr(addr string, filter int, page int, pageSize int) (*clijson.PagedBillResult, error)

GetBillByAddr get bill of payments affecting specific address, one payment could affect ONE address

func (*API) GetTx

func (api *API) GetTx(txID string) (*corejson.TxRawResult, error)

GetTx get transaction by ID

func (*API) GetTxListByAddr

func (api *API) GetTxListByAddr(addr string, sType int, page int, pageSize int) (*clijson.PageTxRawResult, error)

GetTxListByAddr get transactions affecting specific address, one transaction could affect MULTIPLE addresses

func (*API) GetUTxo

func (api *API) GetUTxo(addr string, coin types.CoinID) ([]wtxmgr.UTxo, error)

GetUTxo addr unSpend UTxo

func (*API) ImportPrivKey

func (api *API) ImportPrivKey(accountName string, key string) error

ImportPrivKey import pri key

func (*API) ImportWifPrivKey

func (api *API) ImportWifPrivKey(accountName string, key string) error

ImportWifPrivKey import a WIF-encoded private key and adding it to an account a WIF-encoded private key and adding it to an account.

func (*API) Lock

func (api *API) Lock() error

Lock wallet

func (*API) SendLockedToAddress

func (api *API) SendLockedToAddress(addressStr string, amount float64, coin types.CoinID, lockHeight uint64) (string, error)

SendToAddress handles a sendtoaddress RPC request by creating a new transaction spending unspent transaction outputs for a wallet to another payment address. Leftover inputs not sent to the payment address or a fee for the miner are sent back to a new address in the wallet. Upon success, the TxID for the created transaction is returned.

func (*API) SendToAddress

func (api *API) SendToAddress(addressStr string, amount float64, coin types.CoinID, byAddress string) (string, error)

SendToAddress handles a sendtoaddress RPC request by creating a new transaction spending unspent transaction outputs for a wallet to another payment address. Leftover inputs not sent to the payment address or a fee for the miner are sent back to a new address in the wallet. Upon success, the TxID for the created transaction is returned.

func (*API) SendToAddressByAccount

func (api *API) SendToAddressByAccount(accountName string, addressStr string, amount float64, coin types.CoinID, comment string, commentTo string) (string, error)

SendToAddressByAccount by account

func (*API) SendToMany

func (api *API) SendToMany(addAmounts map[string]float64, coin types.CoinID, byAddress string) (string, error)

func (*API) SyncStats

func (api *API) SyncStats() (*SyncStats, error)

SyncStats block update stats

func (*API) Unlock

func (api *API) Unlock(walletPriPass string, second int64) error

Unlock wallet

type AccountAddress

type AccountAddress struct {
	AccountNumber uint32
	AccountName   string
	Addrs         []types.Address
}

type AccountAndAddressResult

type AccountAndAddressResult struct {
	AccountNumber uint32
	AccountName   string
	AddrsOutput   []AddrAndAddrTxOutput
}

type AccountBalanceResult

type AccountBalanceResult struct {
	AccountNumber      uint32 `json:"-"`
	AccountName        string
	AccountBalanceList []Balance
}

AccountBalanceResult is a single result for the Wallet.AccountBalances method.

type AddrAndAddrTxOutput

type AddrAndAddrTxOutput struct {
	Addr string

	TxoutputMap map[types.CoinID][]wtxmgr.AddrTxOutput
	// contains filtered or unexported fields
}

func NewAddrAndAddrTxOutput

func NewAddrAndAddrTxOutput() *AddrAndAddrTxOutput

type Amount

type Amount struct {
	Value int64
	Id    types.CoinID `json:"-"`
}

func NewAmount

func NewAmount(value int64, id types.CoinID) *Amount

func (*Amount) ToCoin

func (a *Amount) ToCoin() float64

type ApiAmount

type ApiAmount struct {
	Value float64
	Coin  string
}

type Balance

type Balance struct {
	TotalAmount       *Amount // 总余额
	UnspentAmount     *Amount // 可用余额
	LockAmount        *Amount // 锁定
	UnconfirmedAmount *Amount // 待确认
	SpendAmount       *Amount // 已花费
}

func NewBalance

func NewBalance(coinId types.CoinID) *Balance

type Input

type Input struct {
	TxID       string
	OutIndex   uint32
	SignScript []byte
	Sequence   uint32
	InputType  txscript.ScriptClass
	LockTime   int64
}

type Loader

type Loader struct {
	Cfg *config.Config
	// contains filtered or unexported fields
}

func NewLoader

func NewLoader(chainParams *chaincfg.Params, dbDirPath string,
	recoveryWindow uint32, cfg *config.Config) *Loader

func (*Loader) CreateNewWallet

func (l *Loader) CreateNewWallet(pubPassphrase, privPassphrase, seed []byte,
	bday time.Time) (*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 enables these prompts.

func (*Loader) OpenWallet

func (l *Loader) OpenWallet() (*Wallet, error)

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 QitmeerToken

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

func NewQitmeerToken

func NewQitmeerToken(ns walletdb.ReadWriteBucket) *QitmeerToken

func (*QitmeerToken) Add

func (q *QitmeerToken) Add(t json.TokenState)

func (*QitmeerToken) Encode

func (q *QitmeerToken) Encode() []byte

func (*QitmeerToken) GetToken

func (q *QitmeerToken) GetToken(coin types.CoinID) (*json.TokenState, error)

type RPCError

type RPCError struct {
	Code    RPCErrorCode `json:"code,omitempty"`
	Message string       `json:"message,omitempty"`
}

RPCError represents an error that is used as a part of a JSON-RPC Response object.

func (RPCError) Error

func (e RPCError) Error() string

type RPCErrorCode

type RPCErrorCode int

A specific type is used to help ensure the wrong errors aren't used.

type Request

type Request struct {
	Jsonrpc string            `json:"jsonrpc"`
	Method  string            `json:"method"`
	Params  []json.RawMessage `json:"params"`
	ID      interface{}       `json:"id"`
}

Request json req

type Response

type Response struct {
	Jsonrpc string          `json:"jsonrpc"`
	Result  json.RawMessage `json:"result"`
	Error   *RPCError       `json:"error"`
	ID      *interface{}    `json:"id"`
}

type SyncStats

type SyncStats struct {
	Order uint32
}

SyncStats block update stats

type TxOutput

type TxOutput struct {
	Amount     types.Amount
	Address    string
	PkScript   []byte
	LockHeight uint64
}

type Value

type Value struct {
	TotalAmount       int64 // 总余额
	UnspentAmount     int64 // 可用余额
	LockAmount        int64 // 锁定
	UnconfirmedAmount int64 // 待确认
	SpendAmount       int64 // 已花费
}

type Wallet

type Wallet struct {
	Manager *waddrmgr.Manager
	TxStore *wtxmgr.Store

	HttpClient *httpConfig

	UploadRun bool
	// contains filtered or unexported fields
}

func Open

func Open(db walletdb.DB, pubPass []byte, _ *waddrmgr.OpenCallbacks,
	params *chaincfg.Params, _ uint32, cfg *config.Config) (*Wallet, error)

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

func (*Wallet) AccountAddresses

func (w *Wallet) AccountAddresses(account uint32) (addrs []types.Address, err error)

AccountAddresses returns the addresses for every created address for an account.

func (*Wallet) AccountBalances

func (w *Wallet) AccountBalances(scope waddrmgr.KeyScope) ([]AccountBalanceResult, error)

AccountBalances returns all accounts in the wallet and their balances. Balances are determined by excluding transactions that have not met requiredConfs confirmations.

func (*Wallet) AccountEVMAddresses

func (w *Wallet) AccountEVMAddresses(account uint32) (addrs []common2.Address, err error)

AccountEVMAddresses returns the addresses for every created address for an account.

func (*Wallet) AccountName

func (w *Wallet) AccountName(scope waddrmgr.KeyScope, accountNumber uint32) (string, error)

AccountName returns the name of an account.

func (*Wallet) AccountNumber

func (w *Wallet) AccountNumber(scope waddrmgr.KeyScope, accountName string) (uint32, error)

AccountNumber returns the account number for an account name under a particular key scope.

func (*Wallet) AccountOfAddress

func (w *Wallet) AccountOfAddress(a types.Address) (uint32, error)

AccountOfAddress finds the account that an address is associated with.

func (*Wallet) ChainParams

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

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

func (*Wallet) ClearTxData

func (w *Wallet) ClearTxData() error

func (*Wallet) CoinID

func (w *Wallet) CoinID(coin types.CoinID) (types.CoinID, error)

func (*Wallet) Database

func (w *Wallet) Database() walletdb.DB

Database returns the underlying walletdb database. This method is provided in order to allow applications wrapping btcwallet to store app-specific data with the wallet's database.

func (*Wallet) DumpWIFPrivateKey

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

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

func (*Wallet) EVMToUTXO

func (w *Wallet) EVMToUTXO(amounts map[string]types.Amount,
	account int64, feeSatPerKb int64, lockHeight uint64, byAddress string) (string, error)

EVMToUTXO send the amount to utxo account

func (*Wallet) GetAccountAddress

func (w *Wallet) GetAccountAddress(scope waddrmgr.KeyScope) ([]types.Address, error)

func (*Wallet) GetAccountAndAddress

func (w *Wallet) GetAccountAndAddress(scope waddrmgr.KeyScope) ([]AccountAndAddressResult, error)

func (*Wallet) GetAddress

func (w *Wallet) GetAddress(scope waddrmgr.KeyScope, account int) ([]AccountAndAddressResult, error)

func (*Wallet) GetBalance

func (w *Wallet) GetBalance(addr string) (map[types.CoinID]Balance, error)

func (*Wallet) GetBalanceByCoin

func (w *Wallet) GetBalanceByCoin(addr string, coin types.CoinID) (map[string]Value, error)

func (*Wallet) GetBillByAddr

func (w *Wallet) GetBillByAddr(addr string, filter int, pageNo int, pageSize int) (*clijson.PagedBillResult, error)

request the bill of a specific address, a bill is the log of payments, which are the effects that a transaction makes on a specific address a payment can affect only ONE address

func (*Wallet) GetListTxByAddr

func (w *Wallet) GetListTxByAddr(addr string, sType int, pageNo int, pageSize int) (*clijson.PageTxRawResult, error)

* request all the transactions that affect a specific address, a transaction can have MULTIPLE payments and affect MULTIPLE addresses

sType 0 Turn in 1 Turn out 2 all no page

func (*Wallet) GetSyncBlockOrder

func (w *Wallet) GetSyncBlockOrder() uint32

func (*Wallet) GetTx

func (w *Wallet) GetTx(txId string) (corejson.TxRawResult, error)

func (*Wallet) GetTxSpendInfo

func (w *Wallet) GetTxSpendInfo(txId string) ([]*wtxmgr.AddrTxOutput, error)

func (*Wallet) GetUTXOByAddress

func (w *Wallet) GetUTXOByAddress(addrs []types.Address, amount types.Amount) ([]*wtxmgr.AddrTxOutput, int64, error)

func (*Wallet) GetUnspentAddrOutput

func (w *Wallet) GetUnspentAddrOutput(addr string, coin types.CoinID) ([]*wtxmgr.AddrTxOutput, error)

func (*Wallet) GetUnspentUTXO

func (w *Wallet) GetUnspentUTXO(addr string, coin types.CoinID) ([]wtxmgr.UTxo, error)

func (*Wallet) ImportPrivateKey

func (w *Wallet) ImportPrivateKey(scope waddrmgr.KeyScope, wif *utils.WIF) (string, error)

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

NOTE: If a block stamp is not provided, then the wallet's birthday will be set to the genesis block of the corresponding chain.

func (*Wallet) Lock

func (w *Wallet) Lock()

// Lock locks the wallet's address manager.

func (*Wallet) Locked

func (w *Wallet) Locked() bool

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

func (*Wallet) NewAddress

func (w *Wallet) NewAddress(
	scope waddrmgr.KeyScope, account uint32) (types.Address, error)

NewAddress returns the next external chained address for a wallet.

func (*Wallet) NextAccount

func (w *Wallet) NextAccount(scope waddrmgr.KeyScope, name string) (uint32, error)

NextAccount creates the next account and returns its account number. The name must be unique to the account. In order to support automatic seed restoring, new accounts may not be created when all of the previous 100 accounts have no transaction history (this is a deviation from the BIP0044 spec, which allows no unused account gaps).

func (*Wallet) OnBlockConnected

func (w *Wallet) OnBlockConnected(hash *hash.Hash, height int64, order int64, t time.Time, txs []*types.Transaction)

func (*Wallet) OnNodeExit

func (w *Wallet) OnNodeExit(nodeExit *cmds.NodeExitNtfn)

func (*Wallet) OnRescanFinish

func (w *Wallet) OnRescanFinish(rescanFinish *cmds.RescanFinishedNtfn)

func (*Wallet) OnRescanProgress

func (w *Wallet) OnRescanProgress(rescanPro *cmds.RescanProgressNtfn)

func (*Wallet) OnTxAcceptedVerbose

func (w *Wallet) OnTxAcceptedVerbose(c *client.Client, tx *j.DecodeRawTransactionResult)

func (*Wallet) OnTxConfirm

func (w *Wallet) OnTxConfirm(txConfirm *cmds.TxConfirmResult)

func (*Wallet) SendOutputs

func (w *Wallet) SendOutputs(coin2outputs []*TxOutput, coinId types.CoinID, account int64, satPerKb int64, byAddr string) (*string, error)

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

func (*Wallet) SendPairs

func (w *Wallet) SendPairs(amounts map[string]types.Amount,
	account int64, feeSatPerKb int64, lockHeight uint64, byAddress string) (string, error)

sendPairs creates and sends payment transactions. It returns the transaction hash in string format upon success All errors are returned in btcjson.RPCError format

func (*Wallet) SetConfig

func (w *Wallet) SetConfig(cfg *config.Config)

func (*Wallet) SetSyncedToNum

func (w *Wallet) SetSyncedToNum(order int64) error

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

func (w *Wallet) UnLockManager(passphrase []byte) error

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

func (w *Wallet) UpdateBlock(toOrder uint64) error

func (*Wallet) WaitForShutdown

func (w *Wallet) WaitForShutdown()

WaitForShutdown blocks until all wallet goroutines have finished executing.

Directories

Path Synopsis
Package txrules provides transaction rules that should be followed by transaction authors for wide mempool acceptance and quick mining.
Package txrules provides transaction rules that should be followed by transaction authors for wide mempool acceptance and quick mining.

Jump to

Keyboard shortcuts

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