repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
btcsuite/btcwallet
wtxmgr/query.go
unminedTxDetails
func (s *Store) unminedTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash, v []byte) (*TxDetails, error) { details := TxDetails{ Block: BlockMeta{Block: Block{Height: -1}}, } err := readRawTxRecord(txHash, v, &details.TxRecord) if err != nil { return nil, err } it := makeReadUnminedCreditIterator(ns, txHash) for it.next() { if int(it.elem.Index) >= len(details.MsgTx.TxOut) { str := "saved credit index exceeds number of outputs" return nil, storeError(ErrData, str, nil) } // Set the Spent field since this is not done by the iterator. it.elem.Spent = existsRawUnminedInput(ns, it.ck) != nil details.Credits = append(details.Credits, it.elem) } if it.err != nil { return nil, it.err } // Debit records are not saved for unmined transactions. Instead, they // must be looked up for each transaction input manually. There are two // kinds of previous credits that may be debited by an unmined // transaction: mined unspent outputs (which remain marked unspent even // when spent by an unmined transaction), and credits from other unmined // transactions. Both situations must be considered. for i, output := range details.MsgTx.TxIn { opKey := canonicalOutPoint(&output.PreviousOutPoint.Hash, output.PreviousOutPoint.Index) credKey := existsRawUnspent(ns, opKey) if credKey != nil { v := existsRawCredit(ns, credKey) amount, err := fetchRawCreditAmount(v) if err != nil { return nil, err } details.Debits = append(details.Debits, DebitRecord{ Amount: amount, Index: uint32(i), }) continue } v := existsRawUnminedCredit(ns, opKey) if v == nil { continue } amount, err := fetchRawCreditAmount(v) if err != nil { return nil, err } details.Debits = append(details.Debits, DebitRecord{ Amount: amount, Index: uint32(i), }) } return &details, nil }
go
func (s *Store) unminedTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash, v []byte) (*TxDetails, error) { details := TxDetails{ Block: BlockMeta{Block: Block{Height: -1}}, } err := readRawTxRecord(txHash, v, &details.TxRecord) if err != nil { return nil, err } it := makeReadUnminedCreditIterator(ns, txHash) for it.next() { if int(it.elem.Index) >= len(details.MsgTx.TxOut) { str := "saved credit index exceeds number of outputs" return nil, storeError(ErrData, str, nil) } // Set the Spent field since this is not done by the iterator. it.elem.Spent = existsRawUnminedInput(ns, it.ck) != nil details.Credits = append(details.Credits, it.elem) } if it.err != nil { return nil, it.err } // Debit records are not saved for unmined transactions. Instead, they // must be looked up for each transaction input manually. There are two // kinds of previous credits that may be debited by an unmined // transaction: mined unspent outputs (which remain marked unspent even // when spent by an unmined transaction), and credits from other unmined // transactions. Both situations must be considered. for i, output := range details.MsgTx.TxIn { opKey := canonicalOutPoint(&output.PreviousOutPoint.Hash, output.PreviousOutPoint.Index) credKey := existsRawUnspent(ns, opKey) if credKey != nil { v := existsRawCredit(ns, credKey) amount, err := fetchRawCreditAmount(v) if err != nil { return nil, err } details.Debits = append(details.Debits, DebitRecord{ Amount: amount, Index: uint32(i), }) continue } v := existsRawUnminedCredit(ns, opKey) if v == nil { continue } amount, err := fetchRawCreditAmount(v) if err != nil { return nil, err } details.Debits = append(details.Debits, DebitRecord{ Amount: amount, Index: uint32(i), }) } return &details, nil }
[ "func", "(", "s", "*", "Store", ")", "unminedTxDetails", "(", "ns", "walletdb", ".", "ReadBucket", ",", "txHash", "*", "chainhash", ".", "Hash", ",", "v", "[", "]", "byte", ")", "(", "*", "TxDetails", ",", "error", ")", "{", "details", ":=", "TxDetails", "{", "Block", ":", "BlockMeta", "{", "Block", ":", "Block", "{", "Height", ":", "-", "1", "}", "}", ",", "}", "\n", "err", ":=", "readRawTxRecord", "(", "txHash", ",", "v", ",", "&", "details", ".", "TxRecord", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "it", ":=", "makeReadUnminedCreditIterator", "(", "ns", ",", "txHash", ")", "\n", "for", "it", ".", "next", "(", ")", "{", "if", "int", "(", "it", ".", "elem", ".", "Index", ")", ">=", "len", "(", "details", ".", "MsgTx", ".", "TxOut", ")", "{", "str", ":=", "\"", "\"", "\n", "return", "nil", ",", "storeError", "(", "ErrData", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "// Set the Spent field since this is not done by the iterator.", "it", ".", "elem", ".", "Spent", "=", "existsRawUnminedInput", "(", "ns", ",", "it", ".", "ck", ")", "!=", "nil", "\n", "details", ".", "Credits", "=", "append", "(", "details", ".", "Credits", ",", "it", ".", "elem", ")", "\n", "}", "\n", "if", "it", ".", "err", "!=", "nil", "{", "return", "nil", ",", "it", ".", "err", "\n", "}", "\n\n", "// Debit records are not saved for unmined transactions. Instead, they", "// must be looked up for each transaction input manually. There are two", "// kinds of previous credits that may be debited by an unmined", "// transaction: mined unspent outputs (which remain marked unspent even", "// when spent by an unmined transaction), and credits from other unmined", "// transactions. Both situations must be considered.", "for", "i", ",", "output", ":=", "range", "details", ".", "MsgTx", ".", "TxIn", "{", "opKey", ":=", "canonicalOutPoint", "(", "&", "output", ".", "PreviousOutPoint", ".", "Hash", ",", "output", ".", "PreviousOutPoint", ".", "Index", ")", "\n", "credKey", ":=", "existsRawUnspent", "(", "ns", ",", "opKey", ")", "\n", "if", "credKey", "!=", "nil", "{", "v", ":=", "existsRawCredit", "(", "ns", ",", "credKey", ")", "\n", "amount", ",", "err", ":=", "fetchRawCreditAmount", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "details", ".", "Debits", "=", "append", "(", "details", ".", "Debits", ",", "DebitRecord", "{", "Amount", ":", "amount", ",", "Index", ":", "uint32", "(", "i", ")", ",", "}", ")", "\n", "continue", "\n", "}", "\n\n", "v", ":=", "existsRawUnminedCredit", "(", "ns", ",", "opKey", ")", "\n", "if", "v", "==", "nil", "{", "continue", "\n", "}", "\n\n", "amount", ",", "err", ":=", "fetchRawCreditAmount", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "details", ".", "Debits", "=", "append", "(", "details", ".", "Debits", ",", "DebitRecord", "{", "Amount", ":", "amount", ",", "Index", ":", "uint32", "(", "i", ")", ",", "}", ")", "\n", "}", "\n\n", "return", "&", "details", ",", "nil", "\n", "}" ]
// unminedTxDetails fetches the TxDetails for the unmined transaction with the // hash txHash and the passed unmined record value.
[ "unminedTxDetails", "fetches", "the", "TxDetails", "for", "the", "unmined", "transaction", "with", "the", "hash", "txHash", "and", "the", "passed", "unmined", "record", "value", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/query.go#L98-L162
train
btcsuite/btcwallet
wtxmgr/query.go
TxDetails
func (s *Store) TxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash) (*TxDetails, error) { // First, check whether there exists an unmined transaction with this // hash. Use it if found. v := existsRawUnmined(ns, txHash[:]) if v != nil { return s.unminedTxDetails(ns, txHash, v) } // Otherwise, if there exists a mined transaction with this matching // hash, skip over to the newest and begin fetching all details. k, v := latestTxRecord(ns, txHash) if v == nil { // not found return nil, nil } return s.minedTxDetails(ns, txHash, k, v) }
go
func (s *Store) TxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash) (*TxDetails, error) { // First, check whether there exists an unmined transaction with this // hash. Use it if found. v := existsRawUnmined(ns, txHash[:]) if v != nil { return s.unminedTxDetails(ns, txHash, v) } // Otherwise, if there exists a mined transaction with this matching // hash, skip over to the newest and begin fetching all details. k, v := latestTxRecord(ns, txHash) if v == nil { // not found return nil, nil } return s.minedTxDetails(ns, txHash, k, v) }
[ "func", "(", "s", "*", "Store", ")", "TxDetails", "(", "ns", "walletdb", ".", "ReadBucket", ",", "txHash", "*", "chainhash", ".", "Hash", ")", "(", "*", "TxDetails", ",", "error", ")", "{", "// First, check whether there exists an unmined transaction with this", "// hash. Use it if found.", "v", ":=", "existsRawUnmined", "(", "ns", ",", "txHash", "[", ":", "]", ")", "\n", "if", "v", "!=", "nil", "{", "return", "s", ".", "unminedTxDetails", "(", "ns", ",", "txHash", ",", "v", ")", "\n", "}", "\n\n", "// Otherwise, if there exists a mined transaction with this matching", "// hash, skip over to the newest and begin fetching all details.", "k", ",", "v", ":=", "latestTxRecord", "(", "ns", ",", "txHash", ")", "\n", "if", "v", "==", "nil", "{", "// not found", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "s", ".", "minedTxDetails", "(", "ns", ",", "txHash", ",", "k", ",", "v", ")", "\n", "}" ]
// 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.
[ "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", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/query.go#L170-L186
train
btcsuite/btcwallet
wtxmgr/query.go
UniqueTxDetails
func (s *Store) UniqueTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash, block *Block) (*TxDetails, error) { if block == nil { v := existsRawUnmined(ns, txHash[:]) if v == nil { return nil, nil } return s.unminedTxDetails(ns, txHash, v) } k, v := existsTxRecord(ns, txHash, block) if v == nil { return nil, nil } return s.minedTxDetails(ns, txHash, k, v) }
go
func (s *Store) UniqueTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash, block *Block) (*TxDetails, error) { if block == nil { v := existsRawUnmined(ns, txHash[:]) if v == nil { return nil, nil } return s.unminedTxDetails(ns, txHash, v) } k, v := existsTxRecord(ns, txHash, block) if v == nil { return nil, nil } return s.minedTxDetails(ns, txHash, k, v) }
[ "func", "(", "s", "*", "Store", ")", "UniqueTxDetails", "(", "ns", "walletdb", ".", "ReadBucket", ",", "txHash", "*", "chainhash", ".", "Hash", ",", "block", "*", "Block", ")", "(", "*", "TxDetails", ",", "error", ")", "{", "if", "block", "==", "nil", "{", "v", ":=", "existsRawUnmined", "(", "ns", ",", "txHash", "[", ":", "]", ")", "\n", "if", "v", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "s", ".", "unminedTxDetails", "(", "ns", ",", "txHash", ",", "v", ")", "\n", "}", "\n\n", "k", ",", "v", ":=", "existsTxRecord", "(", "ns", ",", "txHash", ",", "block", ")", "\n", "if", "v", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "s", ".", "minedTxDetails", "(", "ns", ",", "txHash", ",", "k", ",", "v", ")", "\n", "}" ]
// 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.
[ "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", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/query.go#L193-L209
train
btcsuite/btcwallet
wtxmgr/query.go
PreviousPkScripts
func (s *Store) PreviousPkScripts(ns walletdb.ReadBucket, rec *TxRecord, block *Block) ([][]byte, error) { var pkScripts [][]byte if block == nil { for _, input := range rec.MsgTx.TxIn { prevOut := &input.PreviousOutPoint // Input may spend a previous unmined output, a // mined output (which would still be marked // unspent), or neither. v := existsRawUnmined(ns, prevOut.Hash[:]) if v != nil { // Ensure a credit exists for this // unmined transaction before including // the output script. k := canonicalOutPoint(&prevOut.Hash, prevOut.Index) if existsRawUnminedCredit(ns, k) == nil { continue } pkScript, err := fetchRawTxRecordPkScript( prevOut.Hash[:], v, prevOut.Index) if err != nil { return nil, err } pkScripts = append(pkScripts, pkScript) continue } _, credKey := existsUnspent(ns, prevOut) if credKey != nil { k := extractRawCreditTxRecordKey(credKey) v = existsRawTxRecord(ns, k) pkScript, err := fetchRawTxRecordPkScript(k, v, prevOut.Index) if err != nil { return nil, err } pkScripts = append(pkScripts, pkScript) continue } } return pkScripts, nil } recKey := keyTxRecord(&rec.Hash, block) it := makeReadDebitIterator(ns, recKey) for it.next() { credKey := extractRawDebitCreditKey(it.cv) index := extractRawCreditIndex(credKey) k := extractRawCreditTxRecordKey(credKey) v := existsRawTxRecord(ns, k) pkScript, err := fetchRawTxRecordPkScript(k, v, index) if err != nil { return nil, err } pkScripts = append(pkScripts, pkScript) } if it.err != nil { return nil, it.err } return pkScripts, nil }
go
func (s *Store) PreviousPkScripts(ns walletdb.ReadBucket, rec *TxRecord, block *Block) ([][]byte, error) { var pkScripts [][]byte if block == nil { for _, input := range rec.MsgTx.TxIn { prevOut := &input.PreviousOutPoint // Input may spend a previous unmined output, a // mined output (which would still be marked // unspent), or neither. v := existsRawUnmined(ns, prevOut.Hash[:]) if v != nil { // Ensure a credit exists for this // unmined transaction before including // the output script. k := canonicalOutPoint(&prevOut.Hash, prevOut.Index) if existsRawUnminedCredit(ns, k) == nil { continue } pkScript, err := fetchRawTxRecordPkScript( prevOut.Hash[:], v, prevOut.Index) if err != nil { return nil, err } pkScripts = append(pkScripts, pkScript) continue } _, credKey := existsUnspent(ns, prevOut) if credKey != nil { k := extractRawCreditTxRecordKey(credKey) v = existsRawTxRecord(ns, k) pkScript, err := fetchRawTxRecordPkScript(k, v, prevOut.Index) if err != nil { return nil, err } pkScripts = append(pkScripts, pkScript) continue } } return pkScripts, nil } recKey := keyTxRecord(&rec.Hash, block) it := makeReadDebitIterator(ns, recKey) for it.next() { credKey := extractRawDebitCreditKey(it.cv) index := extractRawCreditIndex(credKey) k := extractRawCreditTxRecordKey(credKey) v := existsRawTxRecord(ns, k) pkScript, err := fetchRawTxRecordPkScript(k, v, index) if err != nil { return nil, err } pkScripts = append(pkScripts, pkScript) } if it.err != nil { return nil, it.err } return pkScripts, nil }
[ "func", "(", "s", "*", "Store", ")", "PreviousPkScripts", "(", "ns", "walletdb", ".", "ReadBucket", ",", "rec", "*", "TxRecord", ",", "block", "*", "Block", ")", "(", "[", "]", "[", "]", "byte", ",", "error", ")", "{", "var", "pkScripts", "[", "]", "[", "]", "byte", "\n\n", "if", "block", "==", "nil", "{", "for", "_", ",", "input", ":=", "range", "rec", ".", "MsgTx", ".", "TxIn", "{", "prevOut", ":=", "&", "input", ".", "PreviousOutPoint", "\n\n", "// Input may spend a previous unmined output, a", "// mined output (which would still be marked", "// unspent), or neither.", "v", ":=", "existsRawUnmined", "(", "ns", ",", "prevOut", ".", "Hash", "[", ":", "]", ")", "\n", "if", "v", "!=", "nil", "{", "// Ensure a credit exists for this", "// unmined transaction before including", "// the output script.", "k", ":=", "canonicalOutPoint", "(", "&", "prevOut", ".", "Hash", ",", "prevOut", ".", "Index", ")", "\n", "if", "existsRawUnminedCredit", "(", "ns", ",", "k", ")", "==", "nil", "{", "continue", "\n", "}", "\n\n", "pkScript", ",", "err", ":=", "fetchRawTxRecordPkScript", "(", "prevOut", ".", "Hash", "[", ":", "]", ",", "v", ",", "prevOut", ".", "Index", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "pkScripts", "=", "append", "(", "pkScripts", ",", "pkScript", ")", "\n", "continue", "\n", "}", "\n\n", "_", ",", "credKey", ":=", "existsUnspent", "(", "ns", ",", "prevOut", ")", "\n", "if", "credKey", "!=", "nil", "{", "k", ":=", "extractRawCreditTxRecordKey", "(", "credKey", ")", "\n", "v", "=", "existsRawTxRecord", "(", "ns", ",", "k", ")", "\n", "pkScript", ",", "err", ":=", "fetchRawTxRecordPkScript", "(", "k", ",", "v", ",", "prevOut", ".", "Index", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "pkScripts", "=", "append", "(", "pkScripts", ",", "pkScript", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "return", "pkScripts", ",", "nil", "\n", "}", "\n\n", "recKey", ":=", "keyTxRecord", "(", "&", "rec", ".", "Hash", ",", "block", ")", "\n", "it", ":=", "makeReadDebitIterator", "(", "ns", ",", "recKey", ")", "\n", "for", "it", ".", "next", "(", ")", "{", "credKey", ":=", "extractRawDebitCreditKey", "(", "it", ".", "cv", ")", "\n", "index", ":=", "extractRawCreditIndex", "(", "credKey", ")", "\n", "k", ":=", "extractRawCreditTxRecordKey", "(", "credKey", ")", "\n", "v", ":=", "existsRawTxRecord", "(", "ns", ",", "k", ")", "\n", "pkScript", ",", "err", ":=", "fetchRawTxRecordPkScript", "(", "k", ",", "v", ",", "index", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "pkScripts", "=", "append", "(", "pkScripts", ",", "pkScript", ")", "\n", "}", "\n", "if", "it", ".", "err", "!=", "nil", "{", "return", "nil", ",", "it", ".", "err", "\n", "}", "\n\n", "return", "pkScripts", ",", "nil", "\n", "}" ]
// PreviousPkScripts returns a slice of previous output scripts for each credit // output this transaction record debits from.
[ "PreviousPkScripts", "returns", "a", "slice", "of", "previous", "output", "scripts", "for", "each", "credit", "output", "this", "transaction", "record", "debits", "from", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/query.go#L391-L455
train
btcsuite/btcwallet
wallet/loader.go
NewLoader
func NewLoader(chainParams *chaincfg.Params, dbDirPath string, recoveryWindow uint32) *Loader { return &Loader{ chainParams: chainParams, dbDirPath: dbDirPath, recoveryWindow: recoveryWindow, } }
go
func NewLoader(chainParams *chaincfg.Params, dbDirPath string, recoveryWindow uint32) *Loader { return &Loader{ chainParams: chainParams, dbDirPath: dbDirPath, recoveryWindow: recoveryWindow, } }
[ "func", "NewLoader", "(", "chainParams", "*", "chaincfg", ".", "Params", ",", "dbDirPath", "string", ",", "recoveryWindow", "uint32", ")", "*", "Loader", "{", "return", "&", "Loader", "{", "chainParams", ":", "chainParams", ",", "dbDirPath", ":", "dbDirPath", ",", "recoveryWindow", ":", "recoveryWindow", ",", "}", "\n", "}" ]
// NewLoader constructs a Loader with an optional recovery window. If the // recovery window is non-zero, the wallet will attempt to recovery addresses // starting from the last SyncedTo height.
[ "NewLoader", "constructs", "a", "Loader", "with", "an", "optional", "recovery", "window", ".", "If", "the", "recovery", "window", "is", "non", "-", "zero", "the", "wallet", "will", "attempt", "to", "recovery", "addresses", "starting", "from", "the", "last", "SyncedTo", "height", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/loader.go#L58-L66
train
btcsuite/btcwallet
wallet/loader.go
onLoaded
func (l *Loader) onLoaded(w *Wallet, db walletdb.DB) { for _, fn := range l.callbacks { fn(w) } l.wallet = w l.db = db l.callbacks = nil // not needed anymore }
go
func (l *Loader) onLoaded(w *Wallet, db walletdb.DB) { for _, fn := range l.callbacks { fn(w) } l.wallet = w l.db = db l.callbacks = nil // not needed anymore }
[ "func", "(", "l", "*", "Loader", ")", "onLoaded", "(", "w", "*", "Wallet", ",", "db", "walletdb", ".", "DB", ")", "{", "for", "_", ",", "fn", ":=", "range", "l", ".", "callbacks", "{", "fn", "(", "w", ")", "\n", "}", "\n\n", "l", ".", "wallet", "=", "w", "\n", "l", ".", "db", "=", "db", "\n", "l", ".", "callbacks", "=", "nil", "// not needed anymore", "\n", "}" ]
// onLoaded executes each added callback and prevents loader from loading any // additional wallets. Requires mutex to be locked.
[ "onLoaded", "executes", "each", "added", "callback", "and", "prevents", "loader", "from", "loading", "any", "additional", "wallets", ".", "Requires", "mutex", "to", "be", "locked", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/loader.go#L70-L78
train
btcsuite/btcwallet
wallet/loader.go
RunAfterLoad
func (l *Loader) RunAfterLoad(fn func(*Wallet)) { l.mu.Lock() if l.wallet != nil { w := l.wallet l.mu.Unlock() fn(w) } else { l.callbacks = append(l.callbacks, fn) l.mu.Unlock() } }
go
func (l *Loader) RunAfterLoad(fn func(*Wallet)) { l.mu.Lock() if l.wallet != nil { w := l.wallet l.mu.Unlock() fn(w) } else { l.callbacks = append(l.callbacks, fn) l.mu.Unlock() } }
[ "func", "(", "l", "*", "Loader", ")", "RunAfterLoad", "(", "fn", "func", "(", "*", "Wallet", ")", ")", "{", "l", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "l", ".", "wallet", "!=", "nil", "{", "w", ":=", "l", ".", "wallet", "\n", "l", ".", "mu", ".", "Unlock", "(", ")", "\n", "fn", "(", "w", ")", "\n", "}", "else", "{", "l", ".", "callbacks", "=", "append", "(", "l", ".", "callbacks", ",", "fn", ")", "\n", "l", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "}" ]
// 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.
[ "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", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/loader.go#L83-L93
train
btcsuite/btcwallet
wallet/loader.go
CreateNewWallet
func (l *Loader) CreateNewWallet(pubPassphrase, privPassphrase, seed []byte, bday time.Time) (*Wallet, error) { defer l.mu.Unlock() l.mu.Lock() if l.wallet != nil { return nil, ErrLoaded } dbPath := filepath.Join(l.dbDirPath, walletDbName) exists, err := fileExists(dbPath) if err != nil { return nil, err } if exists { return nil, ErrExists } // Create the wallet database backed by bolt db. err = os.MkdirAll(l.dbDirPath, 0700) if err != nil { return nil, err } db, err := walletdb.Create("bdb", dbPath) if err != nil { return nil, err } // Initialize the newly created database for the wallet before opening. err = Create( db, pubPassphrase, privPassphrase, seed, l.chainParams, bday, ) if err != nil { return nil, err } // Open the newly-created wallet. w, err := Open(db, pubPassphrase, nil, l.chainParams, l.recoveryWindow) if err != nil { return nil, err } w.Start() l.onLoaded(w, db) return w, nil }
go
func (l *Loader) CreateNewWallet(pubPassphrase, privPassphrase, seed []byte, bday time.Time) (*Wallet, error) { defer l.mu.Unlock() l.mu.Lock() if l.wallet != nil { return nil, ErrLoaded } dbPath := filepath.Join(l.dbDirPath, walletDbName) exists, err := fileExists(dbPath) if err != nil { return nil, err } if exists { return nil, ErrExists } // Create the wallet database backed by bolt db. err = os.MkdirAll(l.dbDirPath, 0700) if err != nil { return nil, err } db, err := walletdb.Create("bdb", dbPath) if err != nil { return nil, err } // Initialize the newly created database for the wallet before opening. err = Create( db, pubPassphrase, privPassphrase, seed, l.chainParams, bday, ) if err != nil { return nil, err } // Open the newly-created wallet. w, err := Open(db, pubPassphrase, nil, l.chainParams, l.recoveryWindow) if err != nil { return nil, err } w.Start() l.onLoaded(w, db) return w, nil }
[ "func", "(", "l", "*", "Loader", ")", "CreateNewWallet", "(", "pubPassphrase", ",", "privPassphrase", ",", "seed", "[", "]", "byte", ",", "bday", "time", ".", "Time", ")", "(", "*", "Wallet", ",", "error", ")", "{", "defer", "l", ".", "mu", ".", "Unlock", "(", ")", "\n", "l", ".", "mu", ".", "Lock", "(", ")", "\n\n", "if", "l", ".", "wallet", "!=", "nil", "{", "return", "nil", ",", "ErrLoaded", "\n", "}", "\n\n", "dbPath", ":=", "filepath", ".", "Join", "(", "l", ".", "dbDirPath", ",", "walletDbName", ")", "\n", "exists", ",", "err", ":=", "fileExists", "(", "dbPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "exists", "{", "return", "nil", ",", "ErrExists", "\n", "}", "\n\n", "// Create the wallet database backed by bolt db.", "err", "=", "os", ".", "MkdirAll", "(", "l", ".", "dbDirPath", ",", "0700", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "db", ",", "err", ":=", "walletdb", ".", "Create", "(", "\"", "\"", ",", "dbPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Initialize the newly created database for the wallet before opening.", "err", "=", "Create", "(", "db", ",", "pubPassphrase", ",", "privPassphrase", ",", "seed", ",", "l", ".", "chainParams", ",", "bday", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Open the newly-created wallet.", "w", ",", "err", ":=", "Open", "(", "db", ",", "pubPassphrase", ",", "nil", ",", "l", ".", "chainParams", ",", "l", ".", "recoveryWindow", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "w", ".", "Start", "(", ")", "\n\n", "l", ".", "onLoaded", "(", "w", ",", "db", ")", "\n", "return", "w", ",", "nil", "\n", "}" ]
// 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.
[ "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", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/loader.go#L98-L144
train
btcsuite/btcwallet
wallet/loader.go
OpenExistingWallet
func (l *Loader) OpenExistingWallet(pubPassphrase []byte, canConsolePrompt bool) (*Wallet, error) { defer l.mu.Unlock() l.mu.Lock() if l.wallet != nil { return nil, ErrLoaded } // Ensure that the network directory exists. if err := checkCreateDir(l.dbDirPath); err != nil { return nil, err } // Open the database using the boltdb backend. dbPath := filepath.Join(l.dbDirPath, walletDbName) db, err := walletdb.Open("bdb", dbPath) if err != nil { log.Errorf("Failed to open database: %v", err) return nil, err } var cbs *waddrmgr.OpenCallbacks if canConsolePrompt { cbs = &waddrmgr.OpenCallbacks{ ObtainSeed: prompt.ProvideSeed, ObtainPrivatePass: prompt.ProvidePrivPassphrase, } } else { cbs = &waddrmgr.OpenCallbacks{ ObtainSeed: noConsole, ObtainPrivatePass: noConsole, } } w, err := Open(db, pubPassphrase, cbs, l.chainParams, l.recoveryWindow) if err != nil { // If opening the wallet fails (e.g. because of wrong // passphrase), we must close the backing database to // allow future calls to walletdb.Open(). e := db.Close() if e != nil { log.Warnf("Error closing database: %v", e) } return nil, err } w.Start() l.onLoaded(w, db) return w, nil }
go
func (l *Loader) OpenExistingWallet(pubPassphrase []byte, canConsolePrompt bool) (*Wallet, error) { defer l.mu.Unlock() l.mu.Lock() if l.wallet != nil { return nil, ErrLoaded } // Ensure that the network directory exists. if err := checkCreateDir(l.dbDirPath); err != nil { return nil, err } // Open the database using the boltdb backend. dbPath := filepath.Join(l.dbDirPath, walletDbName) db, err := walletdb.Open("bdb", dbPath) if err != nil { log.Errorf("Failed to open database: %v", err) return nil, err } var cbs *waddrmgr.OpenCallbacks if canConsolePrompt { cbs = &waddrmgr.OpenCallbacks{ ObtainSeed: prompt.ProvideSeed, ObtainPrivatePass: prompt.ProvidePrivPassphrase, } } else { cbs = &waddrmgr.OpenCallbacks{ ObtainSeed: noConsole, ObtainPrivatePass: noConsole, } } w, err := Open(db, pubPassphrase, cbs, l.chainParams, l.recoveryWindow) if err != nil { // If opening the wallet fails (e.g. because of wrong // passphrase), we must close the backing database to // allow future calls to walletdb.Open(). e := db.Close() if e != nil { log.Warnf("Error closing database: %v", e) } return nil, err } w.Start() l.onLoaded(w, db) return w, nil }
[ "func", "(", "l", "*", "Loader", ")", "OpenExistingWallet", "(", "pubPassphrase", "[", "]", "byte", ",", "canConsolePrompt", "bool", ")", "(", "*", "Wallet", ",", "error", ")", "{", "defer", "l", ".", "mu", ".", "Unlock", "(", ")", "\n", "l", ".", "mu", ".", "Lock", "(", ")", "\n\n", "if", "l", ".", "wallet", "!=", "nil", "{", "return", "nil", ",", "ErrLoaded", "\n", "}", "\n\n", "// Ensure that the network directory exists.", "if", "err", ":=", "checkCreateDir", "(", "l", ".", "dbDirPath", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Open the database using the boltdb backend.", "dbPath", ":=", "filepath", ".", "Join", "(", "l", ".", "dbDirPath", ",", "walletDbName", ")", "\n", "db", ",", "err", ":=", "walletdb", ".", "Open", "(", "\"", "\"", ",", "dbPath", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "cbs", "*", "waddrmgr", ".", "OpenCallbacks", "\n", "if", "canConsolePrompt", "{", "cbs", "=", "&", "waddrmgr", ".", "OpenCallbacks", "{", "ObtainSeed", ":", "prompt", ".", "ProvideSeed", ",", "ObtainPrivatePass", ":", "prompt", ".", "ProvidePrivPassphrase", ",", "}", "\n", "}", "else", "{", "cbs", "=", "&", "waddrmgr", ".", "OpenCallbacks", "{", "ObtainSeed", ":", "noConsole", ",", "ObtainPrivatePass", ":", "noConsole", ",", "}", "\n", "}", "\n", "w", ",", "err", ":=", "Open", "(", "db", ",", "pubPassphrase", ",", "cbs", ",", "l", ".", "chainParams", ",", "l", ".", "recoveryWindow", ")", "\n", "if", "err", "!=", "nil", "{", "// If opening the wallet fails (e.g. because of wrong", "// passphrase), we must close the backing database to", "// allow future calls to walletdb.Open().", "e", ":=", "db", ".", "Close", "(", ")", "\n", "if", "e", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "e", ")", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "w", ".", "Start", "(", ")", "\n\n", "l", ".", "onLoaded", "(", "w", ",", "db", ")", "\n", "return", "w", ",", "nil", "\n", "}" ]
// 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.
[ "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", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/loader.go#L156-L204
train
btcsuite/btcwallet
wallet/loader.go
LoadedWallet
func (l *Loader) LoadedWallet() (*Wallet, bool) { l.mu.Lock() w := l.wallet l.mu.Unlock() return w, w != nil }
go
func (l *Loader) LoadedWallet() (*Wallet, bool) { l.mu.Lock() w := l.wallet l.mu.Unlock() return w, w != nil }
[ "func", "(", "l", "*", "Loader", ")", "LoadedWallet", "(", ")", "(", "*", "Wallet", ",", "bool", ")", "{", "l", ".", "mu", ".", "Lock", "(", ")", "\n", "w", ":=", "l", ".", "wallet", "\n", "l", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "w", ",", "w", "!=", "nil", "\n", "}" ]
// 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.
[ "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", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/loader.go#L216-L221
train
btcsuite/btcwallet
wallet/loader.go
UnloadWallet
func (l *Loader) UnloadWallet() error { defer l.mu.Unlock() l.mu.Lock() if l.wallet == nil { return ErrNotLoaded } l.wallet.Stop() l.wallet.WaitForShutdown() err := l.db.Close() if err != nil { return err } l.wallet = nil l.db = nil return nil }
go
func (l *Loader) UnloadWallet() error { defer l.mu.Unlock() l.mu.Lock() if l.wallet == nil { return ErrNotLoaded } l.wallet.Stop() l.wallet.WaitForShutdown() err := l.db.Close() if err != nil { return err } l.wallet = nil l.db = nil return nil }
[ "func", "(", "l", "*", "Loader", ")", "UnloadWallet", "(", ")", "error", "{", "defer", "l", ".", "mu", ".", "Unlock", "(", ")", "\n", "l", ".", "mu", ".", "Lock", "(", ")", "\n\n", "if", "l", ".", "wallet", "==", "nil", "{", "return", "ErrNotLoaded", "\n", "}", "\n\n", "l", ".", "wallet", ".", "Stop", "(", ")", "\n", "l", ".", "wallet", ".", "WaitForShutdown", "(", ")", "\n", "err", ":=", "l", ".", "db", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "l", ".", "wallet", "=", "nil", "\n", "l", ".", "db", "=", "nil", "\n", "return", "nil", "\n", "}" ]
// 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.
[ "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", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/loader.go#L227-L245
train
btcsuite/btcwallet
wallet/rescan.go
SubmitRescan
func (w *Wallet) SubmitRescan(job *RescanJob) <-chan error { errChan := make(chan error, 1) job.err = errChan w.rescanAddJob <- job return errChan }
go
func (w *Wallet) SubmitRescan(job *RescanJob) <-chan error { errChan := make(chan error, 1) job.err = errChan w.rescanAddJob <- job return errChan }
[ "func", "(", "w", "*", "Wallet", ")", "SubmitRescan", "(", "job", "*", "RescanJob", ")", "<-", "chan", "error", "{", "errChan", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "job", ".", "err", "=", "errChan", "\n", "w", ".", "rescanAddJob", "<-", "job", "\n", "return", "errChan", "\n", "}" ]
// 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.
[ "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", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L56-L61
train
btcsuite/btcwallet
wallet/rescan.go
batch
func (job *RescanJob) batch() *rescanBatch { return &rescanBatch{ initialSync: job.InitialSync, addrs: job.Addrs, outpoints: job.OutPoints, bs: job.BlockStamp, errChans: []chan error{job.err}, } }
go
func (job *RescanJob) batch() *rescanBatch { return &rescanBatch{ initialSync: job.InitialSync, addrs: job.Addrs, outpoints: job.OutPoints, bs: job.BlockStamp, errChans: []chan error{job.err}, } }
[ "func", "(", "job", "*", "RescanJob", ")", "batch", "(", ")", "*", "rescanBatch", "{", "return", "&", "rescanBatch", "{", "initialSync", ":", "job", ".", "InitialSync", ",", "addrs", ":", "job", ".", "Addrs", ",", "outpoints", ":", "job", ".", "OutPoints", ",", "bs", ":", "job", ".", "BlockStamp", ",", "errChans", ":", "[", "]", "chan", "error", "{", "job", ".", "err", "}", ",", "}", "\n", "}" ]
// batch creates the rescanBatch for a single rescan job.
[ "batch", "creates", "the", "rescanBatch", "for", "a", "single", "rescan", "job", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L64-L72
train
btcsuite/btcwallet
wallet/rescan.go
merge
func (b *rescanBatch) merge(job *RescanJob) { if job.InitialSync { b.initialSync = true } b.addrs = append(b.addrs, job.Addrs...) for op, addr := range job.OutPoints { b.outpoints[op] = addr } if job.BlockStamp.Height < b.bs.Height { b.bs = job.BlockStamp } b.errChans = append(b.errChans, job.err) }
go
func (b *rescanBatch) merge(job *RescanJob) { if job.InitialSync { b.initialSync = true } b.addrs = append(b.addrs, job.Addrs...) for op, addr := range job.OutPoints { b.outpoints[op] = addr } if job.BlockStamp.Height < b.bs.Height { b.bs = job.BlockStamp } b.errChans = append(b.errChans, job.err) }
[ "func", "(", "b", "*", "rescanBatch", ")", "merge", "(", "job", "*", "RescanJob", ")", "{", "if", "job", ".", "InitialSync", "{", "b", ".", "initialSync", "=", "true", "\n", "}", "\n", "b", ".", "addrs", "=", "append", "(", "b", ".", "addrs", ",", "job", ".", "Addrs", "...", ")", "\n\n", "for", "op", ",", "addr", ":=", "range", "job", ".", "OutPoints", "{", "b", ".", "outpoints", "[", "op", "]", "=", "addr", "\n", "}", "\n\n", "if", "job", ".", "BlockStamp", ".", "Height", "<", "b", ".", "bs", ".", "Height", "{", "b", ".", "bs", "=", "job", ".", "BlockStamp", "\n", "}", "\n", "b", ".", "errChans", "=", "append", "(", "b", ".", "errChans", ",", "job", ".", "err", ")", "\n", "}" ]
// merge merges the work from k into j, setting the starting height to // the minimum of the two jobs. This method does not check for // duplicate addresses or outpoints.
[ "merge", "merges", "the", "work", "from", "k", "into", "j", "setting", "the", "starting", "height", "to", "the", "minimum", "of", "the", "two", "jobs", ".", "This", "method", "does", "not", "check", "for", "duplicate", "addresses", "or", "outpoints", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L77-L91
train
btcsuite/btcwallet
wallet/rescan.go
rescanBatchHandler
func (w *Wallet) rescanBatchHandler() { var curBatch, nextBatch *rescanBatch quit := w.quitChan() out: for { select { case job := <-w.rescanAddJob: if curBatch == nil { // Set current batch as this job and send // request. curBatch = job.batch() w.rescanBatch <- curBatch } else { // Create next batch if it doesn't exist, or // merge the job. if nextBatch == nil { nextBatch = job.batch() } else { nextBatch.merge(job) } } case n := <-w.rescanNotifications: switch n := n.(type) { case *chain.RescanProgress: if curBatch == nil { log.Warnf("Received rescan progress " + "notification but no rescan " + "currently running") continue } w.rescanProgress <- &RescanProgressMsg{ Addresses: curBatch.addrs, Notification: n, } case *chain.RescanFinished: if curBatch == nil { log.Warnf("Received rescan finished " + "notification but no rescan " + "currently running") continue } w.rescanFinished <- &RescanFinishedMsg{ Addresses: curBatch.addrs, Notification: n, } curBatch, nextBatch = nextBatch, nil if curBatch != nil { w.rescanBatch <- curBatch } default: // Unexpected message panic(n) } case <-quit: break out } } w.wg.Done() }
go
func (w *Wallet) rescanBatchHandler() { var curBatch, nextBatch *rescanBatch quit := w.quitChan() out: for { select { case job := <-w.rescanAddJob: if curBatch == nil { // Set current batch as this job and send // request. curBatch = job.batch() w.rescanBatch <- curBatch } else { // Create next batch if it doesn't exist, or // merge the job. if nextBatch == nil { nextBatch = job.batch() } else { nextBatch.merge(job) } } case n := <-w.rescanNotifications: switch n := n.(type) { case *chain.RescanProgress: if curBatch == nil { log.Warnf("Received rescan progress " + "notification but no rescan " + "currently running") continue } w.rescanProgress <- &RescanProgressMsg{ Addresses: curBatch.addrs, Notification: n, } case *chain.RescanFinished: if curBatch == nil { log.Warnf("Received rescan finished " + "notification but no rescan " + "currently running") continue } w.rescanFinished <- &RescanFinishedMsg{ Addresses: curBatch.addrs, Notification: n, } curBatch, nextBatch = nextBatch, nil if curBatch != nil { w.rescanBatch <- curBatch } default: // Unexpected message panic(n) } case <-quit: break out } } w.wg.Done() }
[ "func", "(", "w", "*", "Wallet", ")", "rescanBatchHandler", "(", ")", "{", "var", "curBatch", ",", "nextBatch", "*", "rescanBatch", "\n", "quit", ":=", "w", ".", "quitChan", "(", ")", "\n\n", "out", ":", "for", "{", "select", "{", "case", "job", ":=", "<-", "w", ".", "rescanAddJob", ":", "if", "curBatch", "==", "nil", "{", "// Set current batch as this job and send", "// request.", "curBatch", "=", "job", ".", "batch", "(", ")", "\n", "w", ".", "rescanBatch", "<-", "curBatch", "\n", "}", "else", "{", "// Create next batch if it doesn't exist, or", "// merge the job.", "if", "nextBatch", "==", "nil", "{", "nextBatch", "=", "job", ".", "batch", "(", ")", "\n", "}", "else", "{", "nextBatch", ".", "merge", "(", "job", ")", "\n", "}", "\n", "}", "\n\n", "case", "n", ":=", "<-", "w", ".", "rescanNotifications", ":", "switch", "n", ":=", "n", ".", "(", "type", ")", "{", "case", "*", "chain", ".", "RescanProgress", ":", "if", "curBatch", "==", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ")", "\n", "continue", "\n", "}", "\n", "w", ".", "rescanProgress", "<-", "&", "RescanProgressMsg", "{", "Addresses", ":", "curBatch", ".", "addrs", ",", "Notification", ":", "n", ",", "}", "\n\n", "case", "*", "chain", ".", "RescanFinished", ":", "if", "curBatch", "==", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ")", "\n", "continue", "\n", "}", "\n", "w", ".", "rescanFinished", "<-", "&", "RescanFinishedMsg", "{", "Addresses", ":", "curBatch", ".", "addrs", ",", "Notification", ":", "n", ",", "}", "\n\n", "curBatch", ",", "nextBatch", "=", "nextBatch", ",", "nil", "\n\n", "if", "curBatch", "!=", "nil", "{", "w", ".", "rescanBatch", "<-", "curBatch", "\n", "}", "\n\n", "default", ":", "// Unexpected message", "panic", "(", "n", ")", "\n", "}", "\n\n", "case", "<-", "quit", ":", "break", "out", "\n", "}", "\n", "}", "\n\n", "w", ".", "wg", ".", "Done", "(", ")", "\n", "}" ]
// rescanBatchHandler handles incoming rescan request, serializing rescan // submissions, and possibly batching many waiting requests together so they // can be handled by a single rescan after the current one completes.
[ "rescanBatchHandler", "handles", "incoming", "rescan", "request", "serializing", "rescan", "submissions", "and", "possibly", "batching", "many", "waiting", "requests", "together", "so", "they", "can", "be", "handled", "by", "a", "single", "rescan", "after", "the", "current", "one", "completes", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L105-L171
train
btcsuite/btcwallet
wallet/rescan.go
rescanProgressHandler
func (w *Wallet) rescanProgressHandler() { quit := w.quitChan() out: for { // These can't be processed out of order since both chans are // unbuffured and are sent from same context (the batch // handler). select { case msg := <-w.rescanProgress: n := msg.Notification log.Infof("Rescanned through block %v (height %d)", n.Hash, n.Height) case msg := <-w.rescanFinished: n := msg.Notification addrs := msg.Addresses noun := pickNoun(len(addrs), "address", "addresses") log.Infof("Finished rescan for %d %s (synced to block "+ "%s, height %d)", len(addrs), noun, n.Hash, n.Height) go w.resendUnminedTxs() case <-quit: break out } } w.wg.Done() }
go
func (w *Wallet) rescanProgressHandler() { quit := w.quitChan() out: for { // These can't be processed out of order since both chans are // unbuffured and are sent from same context (the batch // handler). select { case msg := <-w.rescanProgress: n := msg.Notification log.Infof("Rescanned through block %v (height %d)", n.Hash, n.Height) case msg := <-w.rescanFinished: n := msg.Notification addrs := msg.Addresses noun := pickNoun(len(addrs), "address", "addresses") log.Infof("Finished rescan for %d %s (synced to block "+ "%s, height %d)", len(addrs), noun, n.Hash, n.Height) go w.resendUnminedTxs() case <-quit: break out } } w.wg.Done() }
[ "func", "(", "w", "*", "Wallet", ")", "rescanProgressHandler", "(", ")", "{", "quit", ":=", "w", ".", "quitChan", "(", ")", "\n", "out", ":", "for", "{", "// These can't be processed out of order since both chans are", "// unbuffured and are sent from same context (the batch", "// handler).", "select", "{", "case", "msg", ":=", "<-", "w", ".", "rescanProgress", ":", "n", ":=", "msg", ".", "Notification", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "n", ".", "Hash", ",", "n", ".", "Height", ")", "\n\n", "case", "msg", ":=", "<-", "w", ".", "rescanFinished", ":", "n", ":=", "msg", ".", "Notification", "\n", "addrs", ":=", "msg", ".", "Addresses", "\n", "noun", ":=", "pickNoun", "(", "len", "(", "addrs", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", "+", "\"", "\"", ",", "len", "(", "addrs", ")", ",", "noun", ",", "n", ".", "Hash", ",", "n", ".", "Height", ")", "\n\n", "go", "w", ".", "resendUnminedTxs", "(", ")", "\n\n", "case", "<-", "quit", ":", "break", "out", "\n", "}", "\n", "}", "\n", "w", ".", "wg", ".", "Done", "(", ")", "\n", "}" ]
// rescanProgressHandler handles notifications for partially and fully completed // rescans by marking each rescanned address as partially or fully synced.
[ "rescanProgressHandler", "handles", "notifications", "for", "partially", "and", "fully", "completed", "rescans", "by", "marking", "each", "rescanned", "address", "as", "partially", "or", "fully", "synced", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L175-L203
train
btcsuite/btcwallet
wallet/rescan.go
rescanRPCHandler
func (w *Wallet) rescanRPCHandler() { chainClient, err := w.requireChainClient() if err != nil { log.Errorf("rescanRPCHandler called without an RPC client") w.wg.Done() return } quit := w.quitChan() out: for { select { case batch := <-w.rescanBatch: // Log the newly-started rescan. numAddrs := len(batch.addrs) noun := pickNoun(numAddrs, "address", "addresses") log.Infof("Started rescan from block %v (height %d) for %d %s", batch.bs.Hash, batch.bs.Height, numAddrs, noun) err := chainClient.Rescan(&batch.bs.Hash, batch.addrs, batch.outpoints) if err != nil { log.Errorf("Rescan for %d %s failed: %v", numAddrs, noun, err) } batch.done(err) case <-quit: break out } } w.wg.Done() }
go
func (w *Wallet) rescanRPCHandler() { chainClient, err := w.requireChainClient() if err != nil { log.Errorf("rescanRPCHandler called without an RPC client") w.wg.Done() return } quit := w.quitChan() out: for { select { case batch := <-w.rescanBatch: // Log the newly-started rescan. numAddrs := len(batch.addrs) noun := pickNoun(numAddrs, "address", "addresses") log.Infof("Started rescan from block %v (height %d) for %d %s", batch.bs.Hash, batch.bs.Height, numAddrs, noun) err := chainClient.Rescan(&batch.bs.Hash, batch.addrs, batch.outpoints) if err != nil { log.Errorf("Rescan for %d %s failed: %v", numAddrs, noun, err) } batch.done(err) case <-quit: break out } } w.wg.Done() }
[ "func", "(", "w", "*", "Wallet", ")", "rescanRPCHandler", "(", ")", "{", "chainClient", ",", "err", ":=", "w", ".", "requireChainClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "w", ".", "wg", ".", "Done", "(", ")", "\n", "return", "\n", "}", "\n\n", "quit", ":=", "w", ".", "quitChan", "(", ")", "\n\n", "out", ":", "for", "{", "select", "{", "case", "batch", ":=", "<-", "w", ".", "rescanBatch", ":", "// Log the newly-started rescan.", "numAddrs", ":=", "len", "(", "batch", ".", "addrs", ")", "\n", "noun", ":=", "pickNoun", "(", "numAddrs", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "batch", ".", "bs", ".", "Hash", ",", "batch", ".", "bs", ".", "Height", ",", "numAddrs", ",", "noun", ")", "\n\n", "err", ":=", "chainClient", ".", "Rescan", "(", "&", "batch", ".", "bs", ".", "Hash", ",", "batch", ".", "addrs", ",", "batch", ".", "outpoints", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "numAddrs", ",", "noun", ",", "err", ")", "\n", "}", "\n", "batch", ".", "done", "(", "err", ")", "\n", "case", "<-", "quit", ":", "break", "out", "\n", "}", "\n", "}", "\n\n", "w", ".", "wg", ".", "Done", "(", ")", "\n", "}" ]
// rescanRPCHandler reads batch jobs sent by rescanBatchHandler and sends the // RPC requests to perform a rescan. New jobs are not read until a rescan // finishes.
[ "rescanRPCHandler", "reads", "batch", "jobs", "sent", "by", "rescanBatchHandler", "and", "sends", "the", "RPC", "requests", "to", "perform", "a", "rescan", ".", "New", "jobs", "are", "not", "read", "until", "a", "rescan", "finishes", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L208-L241
train
btcsuite/btcwallet
wallet/rescan.go
Rescan
func (w *Wallet) Rescan(addrs []btcutil.Address, unspent []wtxmgr.Credit) error { return w.rescanWithTarget(addrs, unspent, nil) }
go
func (w *Wallet) Rescan(addrs []btcutil.Address, unspent []wtxmgr.Credit) error { return w.rescanWithTarget(addrs, unspent, nil) }
[ "func", "(", "w", "*", "Wallet", ")", "Rescan", "(", "addrs", "[", "]", "btcutil", ".", "Address", ",", "unspent", "[", "]", "wtxmgr", ".", "Credit", ")", "error", "{", "return", "w", ".", "rescanWithTarget", "(", "addrs", ",", "unspent", ",", "nil", ")", "\n", "}" ]
// 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 // rescan.
[ "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", "rescan", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L247-L249
train
btcsuite/btcwallet
wallet/rescan.go
rescanWithTarget
func (w *Wallet) rescanWithTarget(addrs []btcutil.Address, unspent []wtxmgr.Credit, startStamp *waddrmgr.BlockStamp) error { outpoints := make(map[wire.OutPoint]btcutil.Address, len(unspent)) for _, output := range unspent { _, outputAddrs, _, err := txscript.ExtractPkScriptAddrs( output.PkScript, w.chainParams, ) if err != nil { return err } outpoints[output.OutPoint] = outputAddrs[0] } // If a start block stamp was provided, we will use that as the initial // starting point for the rescan. if startStamp == nil { startStamp = &waddrmgr.BlockStamp{} *startStamp = w.Manager.SyncedTo() } job := &RescanJob{ InitialSync: true, Addrs: addrs, OutPoints: outpoints, BlockStamp: *startStamp, } // Submit merged job and block until rescan completes. return <-w.SubmitRescan(job) }
go
func (w *Wallet) rescanWithTarget(addrs []btcutil.Address, unspent []wtxmgr.Credit, startStamp *waddrmgr.BlockStamp) error { outpoints := make(map[wire.OutPoint]btcutil.Address, len(unspent)) for _, output := range unspent { _, outputAddrs, _, err := txscript.ExtractPkScriptAddrs( output.PkScript, w.chainParams, ) if err != nil { return err } outpoints[output.OutPoint] = outputAddrs[0] } // If a start block stamp was provided, we will use that as the initial // starting point for the rescan. if startStamp == nil { startStamp = &waddrmgr.BlockStamp{} *startStamp = w.Manager.SyncedTo() } job := &RescanJob{ InitialSync: true, Addrs: addrs, OutPoints: outpoints, BlockStamp: *startStamp, } // Submit merged job and block until rescan completes. return <-w.SubmitRescan(job) }
[ "func", "(", "w", "*", "Wallet", ")", "rescanWithTarget", "(", "addrs", "[", "]", "btcutil", ".", "Address", ",", "unspent", "[", "]", "wtxmgr", ".", "Credit", ",", "startStamp", "*", "waddrmgr", ".", "BlockStamp", ")", "error", "{", "outpoints", ":=", "make", "(", "map", "[", "wire", ".", "OutPoint", "]", "btcutil", ".", "Address", ",", "len", "(", "unspent", ")", ")", "\n", "for", "_", ",", "output", ":=", "range", "unspent", "{", "_", ",", "outputAddrs", ",", "_", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "output", ".", "PkScript", ",", "w", ".", "chainParams", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "outpoints", "[", "output", ".", "OutPoint", "]", "=", "outputAddrs", "[", "0", "]", "\n", "}", "\n\n", "// If a start block stamp was provided, we will use that as the initial", "// starting point for the rescan.", "if", "startStamp", "==", "nil", "{", "startStamp", "=", "&", "waddrmgr", ".", "BlockStamp", "{", "}", "\n", "*", "startStamp", "=", "w", ".", "Manager", ".", "SyncedTo", "(", ")", "\n", "}", "\n\n", "job", ":=", "&", "RescanJob", "{", "InitialSync", ":", "true", ",", "Addrs", ":", "addrs", ",", "OutPoints", ":", "outpoints", ",", "BlockStamp", ":", "*", "startStamp", ",", "}", "\n\n", "// Submit merged job and block until rescan completes.", "return", "<-", "w", ".", "SubmitRescan", "(", "job", ")", "\n", "}" ]
// rescanWithTarget performs a rescan starting at the optional startStamp. If // none is provided, the rescan will begin from the manager's sync tip.
[ "rescanWithTarget", "performs", "a", "rescan", "starting", "at", "the", "optional", "startStamp", ".", "If", "none", "is", "provided", "the", "rescan", "will", "begin", "from", "the", "manager", "s", "sync", "tip", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L253-L284
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
unimplemented
func unimplemented(interface{}, *wallet.Wallet) (interface{}, error) { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCUnimplemented, Message: "Method unimplemented", } }
go
func unimplemented(interface{}, *wallet.Wallet) (interface{}, error) { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCUnimplemented, Message: "Method unimplemented", } }
[ "func", "unimplemented", "(", "interface", "{", "}", ",", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCUnimplemented", ",", "Message", ":", "\"", "\"", ",", "}", "\n", "}" ]
// unimplemented handles an unimplemented RPC request with the // appropiate error.
[ "unimplemented", "handles", "an", "unimplemented", "RPC", "request", "with", "the", "appropiate", "error", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L143-L148
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
makeResponse
func makeResponse(id, result interface{}, err error) btcjson.Response { idPtr := idPointer(id) if err != nil { return btcjson.Response{ ID: idPtr, Error: jsonError(err), } } resultBytes, err := json.Marshal(result) if err != nil { return btcjson.Response{ ID: idPtr, Error: &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: "Unexpected error marshalling result", }, } } return btcjson.Response{ ID: idPtr, Result: json.RawMessage(resultBytes), } }
go
func makeResponse(id, result interface{}, err error) btcjson.Response { idPtr := idPointer(id) if err != nil { return btcjson.Response{ ID: idPtr, Error: jsonError(err), } } resultBytes, err := json.Marshal(result) if err != nil { return btcjson.Response{ ID: idPtr, Error: &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: "Unexpected error marshalling result", }, } } return btcjson.Response{ ID: idPtr, Result: json.RawMessage(resultBytes), } }
[ "func", "makeResponse", "(", "id", ",", "result", "interface", "{", "}", ",", "err", "error", ")", "btcjson", ".", "Response", "{", "idPtr", ":=", "idPointer", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "btcjson", ".", "Response", "{", "ID", ":", "idPtr", ",", "Error", ":", "jsonError", "(", "err", ")", ",", "}", "\n", "}", "\n", "resultBytes", ",", "err", ":=", "json", ".", "Marshal", "(", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "btcjson", ".", "Response", "{", "ID", ":", "idPtr", ",", "Error", ":", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCInternal", ".", "Code", ",", "Message", ":", "\"", "\"", ",", "}", ",", "}", "\n", "}", "\n", "return", "btcjson", ".", "Response", "{", "ID", ":", "idPtr", ",", "Result", ":", "json", ".", "RawMessage", "(", "resultBytes", ")", ",", "}", "\n", "}" ]
// makeResponse makes the JSON-RPC response struct for the result and error // returned by a requestHandler. The returned response is not ready for // marshaling and sending off to a client, but must be
[ "makeResponse", "makes", "the", "JSON", "-", "RPC", "response", "struct", "for", "the", "result", "and", "error", "returned", "by", "a", "requestHandler", ".", "The", "returned", "response", "is", "not", "ready", "for", "marshaling", "and", "sending", "off", "to", "a", "client", "but", "must", "be" ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L234-L256
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
jsonError
func jsonError(err error) *btcjson.RPCError { if err == nil { return nil } code := btcjson.ErrRPCWallet switch e := err.(type) { case btcjson.RPCError: return &e case *btcjson.RPCError: return e case DeserializationError: code = btcjson.ErrRPCDeserialization case InvalidParameterError: code = btcjson.ErrRPCInvalidParameter case ParseError: code = btcjson.ErrRPCParse.Code case waddrmgr.ManagerError: switch e.ErrorCode { case waddrmgr.ErrWrongPassphrase: code = btcjson.ErrRPCWalletPassphraseIncorrect } } return &btcjson.RPCError{ Code: code, Message: err.Error(), } }
go
func jsonError(err error) *btcjson.RPCError { if err == nil { return nil } code := btcjson.ErrRPCWallet switch e := err.(type) { case btcjson.RPCError: return &e case *btcjson.RPCError: return e case DeserializationError: code = btcjson.ErrRPCDeserialization case InvalidParameterError: code = btcjson.ErrRPCInvalidParameter case ParseError: code = btcjson.ErrRPCParse.Code case waddrmgr.ManagerError: switch e.ErrorCode { case waddrmgr.ErrWrongPassphrase: code = btcjson.ErrRPCWalletPassphraseIncorrect } } return &btcjson.RPCError{ Code: code, Message: err.Error(), } }
[ "func", "jsonError", "(", "err", "error", ")", "*", "btcjson", ".", "RPCError", "{", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "code", ":=", "btcjson", ".", "ErrRPCWallet", "\n", "switch", "e", ":=", "err", ".", "(", "type", ")", "{", "case", "btcjson", ".", "RPCError", ":", "return", "&", "e", "\n", "case", "*", "btcjson", ".", "RPCError", ":", "return", "e", "\n", "case", "DeserializationError", ":", "code", "=", "btcjson", ".", "ErrRPCDeserialization", "\n", "case", "InvalidParameterError", ":", "code", "=", "btcjson", ".", "ErrRPCInvalidParameter", "\n", "case", "ParseError", ":", "code", "=", "btcjson", ".", "ErrRPCParse", ".", "Code", "\n", "case", "waddrmgr", ".", "ManagerError", ":", "switch", "e", ".", "ErrorCode", "{", "case", "waddrmgr", ".", "ErrWrongPassphrase", ":", "code", "=", "btcjson", ".", "ErrRPCWalletPassphraseIncorrect", "\n", "}", "\n", "}", "\n", "return", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "code", ",", "Message", ":", "err", ".", "Error", "(", ")", ",", "}", "\n", "}" ]
// jsonError creates a JSON-RPC error from the Go error.
[ "jsonError", "creates", "a", "JSON", "-", "RPC", "error", "from", "the", "Go", "error", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L259-L286
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
makeMultiSigScript
func makeMultiSigScript(w *wallet.Wallet, keys []string, nRequired int) ([]byte, error) { keysesPrecious := make([]*btcutil.AddressPubKey, len(keys)) // The address list will made up either of addreseses (pubkey hash), for // which we need to look up the keys in wallet, straight pubkeys, or a // mixture of the two. for i, a := range keys { // try to parse as pubkey address a, err := decodeAddress(a, w.ChainParams()) if err != nil { return nil, err } switch addr := a.(type) { case *btcutil.AddressPubKey: keysesPrecious[i] = addr default: pubKey, err := w.PubKeyForAddress(addr) if err != nil { return nil, err } pubKeyAddr, err := btcutil.NewAddressPubKey( pubKey.SerializeCompressed(), w.ChainParams()) if err != nil { return nil, err } keysesPrecious[i] = pubKeyAddr } } return txscript.MultiSigScript(keysesPrecious, nRequired) }
go
func makeMultiSigScript(w *wallet.Wallet, keys []string, nRequired int) ([]byte, error) { keysesPrecious := make([]*btcutil.AddressPubKey, len(keys)) // The address list will made up either of addreseses (pubkey hash), for // which we need to look up the keys in wallet, straight pubkeys, or a // mixture of the two. for i, a := range keys { // try to parse as pubkey address a, err := decodeAddress(a, w.ChainParams()) if err != nil { return nil, err } switch addr := a.(type) { case *btcutil.AddressPubKey: keysesPrecious[i] = addr default: pubKey, err := w.PubKeyForAddress(addr) if err != nil { return nil, err } pubKeyAddr, err := btcutil.NewAddressPubKey( pubKey.SerializeCompressed(), w.ChainParams()) if err != nil { return nil, err } keysesPrecious[i] = pubKeyAddr } } return txscript.MultiSigScript(keysesPrecious, nRequired) }
[ "func", "makeMultiSigScript", "(", "w", "*", "wallet", ".", "Wallet", ",", "keys", "[", "]", "string", ",", "nRequired", "int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "keysesPrecious", ":=", "make", "(", "[", "]", "*", "btcutil", ".", "AddressPubKey", ",", "len", "(", "keys", ")", ")", "\n\n", "// The address list will made up either of addreseses (pubkey hash), for", "// which we need to look up the keys in wallet, straight pubkeys, or a", "// mixture of the two.", "for", "i", ",", "a", ":=", "range", "keys", "{", "// try to parse as pubkey address", "a", ",", "err", ":=", "decodeAddress", "(", "a", ",", "w", ".", "ChainParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "switch", "addr", ":=", "a", ".", "(", "type", ")", "{", "case", "*", "btcutil", ".", "AddressPubKey", ":", "keysesPrecious", "[", "i", "]", "=", "addr", "\n", "default", ":", "pubKey", ",", "err", ":=", "w", ".", "PubKeyForAddress", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "pubKeyAddr", ",", "err", ":=", "btcutil", ".", "NewAddressPubKey", "(", "pubKey", ".", "SerializeCompressed", "(", ")", ",", "w", ".", "ChainParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "keysesPrecious", "[", "i", "]", "=", "pubKeyAddr", "\n", "}", "\n", "}", "\n\n", "return", "txscript", ".", "MultiSigScript", "(", "keysesPrecious", ",", "nRequired", ")", "\n", "}" ]
// makeMultiSigScript is a helper function to combine common logic for // AddMultiSig and CreateMultiSig.
[ "makeMultiSigScript", "is", "a", "helper", "function", "to", "combine", "common", "logic", "for", "AddMultiSig", "and", "CreateMultiSig", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L290-L321
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
addMultiSigAddress
func addMultiSigAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.AddMultisigAddressCmd) // If an account is specified, ensure that is the imported account. if cmd.Account != nil && *cmd.Account != waddrmgr.ImportedAddrAccountName { return nil, &ErrNotImportedAccount } secp256k1Addrs := make([]btcutil.Address, len(cmd.Keys)) for i, k := range cmd.Keys { addr, err := decodeAddress(k, w.ChainParams()) if err != nil { return nil, ParseError{err} } secp256k1Addrs[i] = addr } script, err := w.MakeMultiSigScript(secp256k1Addrs, cmd.NRequired) if err != nil { return nil, err } p2shAddr, err := w.ImportP2SHRedeemScript(script) if err != nil { return nil, err } return p2shAddr.EncodeAddress(), nil }
go
func addMultiSigAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.AddMultisigAddressCmd) // If an account is specified, ensure that is the imported account. if cmd.Account != nil && *cmd.Account != waddrmgr.ImportedAddrAccountName { return nil, &ErrNotImportedAccount } secp256k1Addrs := make([]btcutil.Address, len(cmd.Keys)) for i, k := range cmd.Keys { addr, err := decodeAddress(k, w.ChainParams()) if err != nil { return nil, ParseError{err} } secp256k1Addrs[i] = addr } script, err := w.MakeMultiSigScript(secp256k1Addrs, cmd.NRequired) if err != nil { return nil, err } p2shAddr, err := w.ImportP2SHRedeemScript(script) if err != nil { return nil, err } return p2shAddr.EncodeAddress(), nil }
[ "func", "addMultiSigAddress", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "AddMultisigAddressCmd", ")", "\n\n", "// If an account is specified, ensure that is the imported account.", "if", "cmd", ".", "Account", "!=", "nil", "&&", "*", "cmd", ".", "Account", "!=", "waddrmgr", ".", "ImportedAddrAccountName", "{", "return", "nil", ",", "&", "ErrNotImportedAccount", "\n", "}", "\n\n", "secp256k1Addrs", ":=", "make", "(", "[", "]", "btcutil", ".", "Address", ",", "len", "(", "cmd", ".", "Keys", ")", ")", "\n", "for", "i", ",", "k", ":=", "range", "cmd", ".", "Keys", "{", "addr", ",", "err", ":=", "decodeAddress", "(", "k", ",", "w", ".", "ChainParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "ParseError", "{", "err", "}", "\n", "}", "\n", "secp256k1Addrs", "[", "i", "]", "=", "addr", "\n", "}", "\n\n", "script", ",", "err", ":=", "w", ".", "MakeMultiSigScript", "(", "secp256k1Addrs", ",", "cmd", ".", "NRequired", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "p2shAddr", ",", "err", ":=", "w", ".", "ImportP2SHRedeemScript", "(", "script", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "p2shAddr", ".", "EncodeAddress", "(", ")", ",", "nil", "\n", "}" ]
// addMultiSigAddress handles an addmultisigaddress request by adding a // multisig address to the given wallet.
[ "addMultiSigAddress", "handles", "an", "addmultisigaddress", "request", "by", "adding", "a", "multisig", "address", "to", "the", "given", "wallet", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L325-L353
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
createMultiSig
func createMultiSig(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.CreateMultisigCmd) script, err := makeMultiSigScript(w, cmd.Keys, cmd.NRequired) if err != nil { return nil, ParseError{err} } address, err := btcutil.NewAddressScriptHash(script, w.ChainParams()) if err != nil { // above is a valid script, shouldn't happen. return nil, err } return btcjson.CreateMultiSigResult{ Address: address.EncodeAddress(), RedeemScript: hex.EncodeToString(script), }, nil }
go
func createMultiSig(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.CreateMultisigCmd) script, err := makeMultiSigScript(w, cmd.Keys, cmd.NRequired) if err != nil { return nil, ParseError{err} } address, err := btcutil.NewAddressScriptHash(script, w.ChainParams()) if err != nil { // above is a valid script, shouldn't happen. return nil, err } return btcjson.CreateMultiSigResult{ Address: address.EncodeAddress(), RedeemScript: hex.EncodeToString(script), }, nil }
[ "func", "createMultiSig", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "CreateMultisigCmd", ")", "\n\n", "script", ",", "err", ":=", "makeMultiSigScript", "(", "w", ",", "cmd", ".", "Keys", ",", "cmd", ".", "NRequired", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "ParseError", "{", "err", "}", "\n", "}", "\n\n", "address", ",", "err", ":=", "btcutil", ".", "NewAddressScriptHash", "(", "script", ",", "w", ".", "ChainParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "// above is a valid script, shouldn't happen.", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "btcjson", ".", "CreateMultiSigResult", "{", "Address", ":", "address", ".", "EncodeAddress", "(", ")", ",", "RedeemScript", ":", "hex", ".", "EncodeToString", "(", "script", ")", ",", "}", ",", "nil", "\n", "}" ]
// createMultiSig handles an createmultisig request by returning a // multisig address for the given inputs.
[ "createMultiSig", "handles", "an", "createmultisig", "request", "by", "returning", "a", "multisig", "address", "for", "the", "given", "inputs", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L357-L375
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
dumpPrivKey
func dumpPrivKey(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.DumpPrivKeyCmd) addr, err := decodeAddress(cmd.Address, w.ChainParams()) if err != nil { return nil, err } key, err := w.DumpWIFPrivateKey(addr) if waddrmgr.IsError(err, waddrmgr.ErrLocked) { // Address was found, but the private key isn't // accessible. return nil, &ErrWalletUnlockNeeded } return key, err }
go
func dumpPrivKey(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.DumpPrivKeyCmd) addr, err := decodeAddress(cmd.Address, w.ChainParams()) if err != nil { return nil, err } key, err := w.DumpWIFPrivateKey(addr) if waddrmgr.IsError(err, waddrmgr.ErrLocked) { // Address was found, but the private key isn't // accessible. return nil, &ErrWalletUnlockNeeded } return key, err }
[ "func", "dumpPrivKey", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "DumpPrivKeyCmd", ")", "\n\n", "addr", ",", "err", ":=", "decodeAddress", "(", "cmd", ".", "Address", ",", "w", ".", "ChainParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "key", ",", "err", ":=", "w", ".", "DumpWIFPrivateKey", "(", "addr", ")", "\n", "if", "waddrmgr", ".", "IsError", "(", "err", ",", "waddrmgr", ".", "ErrLocked", ")", "{", "// Address was found, but the private key isn't", "// accessible.", "return", "nil", ",", "&", "ErrWalletUnlockNeeded", "\n", "}", "\n", "return", "key", ",", "err", "\n", "}" ]
// dumpPrivKey handles a dumpprivkey request with the private key // for a single address, or an appropiate error if the wallet // is locked.
[ "dumpPrivKey", "handles", "a", "dumpprivkey", "request", "with", "the", "private", "key", "for", "a", "single", "address", "or", "an", "appropiate", "error", "if", "the", "wallet", "is", "locked", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L380-L395
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
getAddressesByAccount
func getAddressesByAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.GetAddressesByAccountCmd) account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.Account) if err != nil { return nil, err } addrs, err := w.AccountAddresses(account) if err != nil { return nil, err } addrStrs := make([]string, len(addrs)) for i, a := range addrs { addrStrs[i] = a.EncodeAddress() } return addrStrs, nil }
go
func getAddressesByAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.GetAddressesByAccountCmd) account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.Account) if err != nil { return nil, err } addrs, err := w.AccountAddresses(account) if err != nil { return nil, err } addrStrs := make([]string, len(addrs)) for i, a := range addrs { addrStrs[i] = a.EncodeAddress() } return addrStrs, nil }
[ "func", "getAddressesByAccount", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "GetAddressesByAccountCmd", ")", "\n\n", "account", ",", "err", ":=", "w", ".", "AccountNumber", "(", "waddrmgr", ".", "KeyScopeBIP0044", ",", "cmd", ".", "Account", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "addrs", ",", "err", ":=", "w", ".", "AccountAddresses", "(", "account", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "addrStrs", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "addrs", ")", ")", "\n", "for", "i", ",", "a", ":=", "range", "addrs", "{", "addrStrs", "[", "i", "]", "=", "a", ".", "EncodeAddress", "(", ")", "\n", "}", "\n", "return", "addrStrs", ",", "nil", "\n", "}" ]
// getAddressesByAccount handles a getaddressesbyaccount request by returning // all addresses for an account, or an error if the requested account does // not exist.
[ "getAddressesByAccount", "handles", "a", "getaddressesbyaccount", "request", "by", "returning", "all", "addresses", "for", "an", "account", "or", "an", "error", "if", "the", "requested", "account", "does", "not", "exist", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L412-L430
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
getBestBlock
func getBestBlock(icmd interface{}, w *wallet.Wallet) (interface{}, error) { blk := w.Manager.SyncedTo() result := &btcjson.GetBestBlockResult{ Hash: blk.Hash.String(), Height: blk.Height, } return result, nil }
go
func getBestBlock(icmd interface{}, w *wallet.Wallet) (interface{}, error) { blk := w.Manager.SyncedTo() result := &btcjson.GetBestBlockResult{ Hash: blk.Hash.String(), Height: blk.Height, } return result, nil }
[ "func", "getBestBlock", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "blk", ":=", "w", ".", "Manager", ".", "SyncedTo", "(", ")", "\n", "result", ":=", "&", "btcjson", ".", "GetBestBlockResult", "{", "Hash", ":", "blk", ".", "Hash", ".", "String", "(", ")", ",", "Height", ":", "blk", ".", "Height", ",", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// getBestBlock handles a getbestblock request by returning a JSON object // with the height and hash of the most recently processed block.
[ "getBestBlock", "handles", "a", "getbestblock", "request", "by", "returning", "a", "JSON", "object", "with", "the", "height", "and", "hash", "of", "the", "most", "recently", "processed", "block", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L466-L473
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
getBestBlockHash
func getBestBlockHash(icmd interface{}, w *wallet.Wallet) (interface{}, error) { blk := w.Manager.SyncedTo() return blk.Hash.String(), nil }
go
func getBestBlockHash(icmd interface{}, w *wallet.Wallet) (interface{}, error) { blk := w.Manager.SyncedTo() return blk.Hash.String(), nil }
[ "func", "getBestBlockHash", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "blk", ":=", "w", ".", "Manager", ".", "SyncedTo", "(", ")", "\n", "return", "blk", ".", "Hash", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// getBestBlockHash handles a getbestblockhash request by returning the hash // of the most recently processed block.
[ "getBestBlockHash", "handles", "a", "getbestblockhash", "request", "by", "returning", "the", "hash", "of", "the", "most", "recently", "processed", "block", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L477-L480
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
getBlockCount
func getBlockCount(icmd interface{}, w *wallet.Wallet) (interface{}, error) { blk := w.Manager.SyncedTo() return blk.Height, nil }
go
func getBlockCount(icmd interface{}, w *wallet.Wallet) (interface{}, error) { blk := w.Manager.SyncedTo() return blk.Height, nil }
[ "func", "getBlockCount", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "blk", ":=", "w", ".", "Manager", ".", "SyncedTo", "(", ")", "\n", "return", "blk", ".", "Height", ",", "nil", "\n", "}" ]
// getBlockCount handles a getblockcount request by returning the chain height // of the most recently processed block.
[ "getBlockCount", "handles", "a", "getblockcount", "request", "by", "returning", "the", "chain", "height", "of", "the", "most", "recently", "processed", "block", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L484-L487
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
getInfo
func getInfo(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) { // Call down to btcd for all of the information in this command known // by them. info, err := chainClient.GetInfo() if err != nil { return nil, err } bal, err := w.CalculateBalance(1) if err != nil { return nil, err } // TODO(davec): This should probably have a database version as opposed // to using the manager version. info.WalletVersion = int32(waddrmgr.LatestMgrVersion) info.Balance = bal.ToBTC() info.PaytxFee = float64(txrules.DefaultRelayFeePerKb) // We don't set the following since they don't make much sense in the // wallet architecture: // - unlocked_until // - errors return info, nil }
go
func getInfo(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) { // Call down to btcd for all of the information in this command known // by them. info, err := chainClient.GetInfo() if err != nil { return nil, err } bal, err := w.CalculateBalance(1) if err != nil { return nil, err } // TODO(davec): This should probably have a database version as opposed // to using the manager version. info.WalletVersion = int32(waddrmgr.LatestMgrVersion) info.Balance = bal.ToBTC() info.PaytxFee = float64(txrules.DefaultRelayFeePerKb) // We don't set the following since they don't make much sense in the // wallet architecture: // - unlocked_until // - errors return info, nil }
[ "func", "getInfo", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ",", "chainClient", "*", "chain", ".", "RPCClient", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "// Call down to btcd for all of the information in this command known", "// by them.", "info", ",", "err", ":=", "chainClient", ".", "GetInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "bal", ",", "err", ":=", "w", ".", "CalculateBalance", "(", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// TODO(davec): This should probably have a database version as opposed", "// to using the manager version.", "info", ".", "WalletVersion", "=", "int32", "(", "waddrmgr", ".", "LatestMgrVersion", ")", "\n", "info", ".", "Balance", "=", "bal", ".", "ToBTC", "(", ")", "\n", "info", ".", "PaytxFee", "=", "float64", "(", "txrules", ".", "DefaultRelayFeePerKb", ")", "\n", "// We don't set the following since they don't make much sense in the", "// wallet architecture:", "// - unlocked_until", "// - errors", "return", "info", ",", "nil", "\n", "}" ]
// getInfo handles a getinfo request by returning the a structure containing // information about the current state of btcwallet. // exist.
[ "getInfo", "handles", "a", "getinfo", "request", "by", "returning", "the", "a", "structure", "containing", "information", "about", "the", "current", "state", "of", "btcwallet", ".", "exist", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L492-L516
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
getAccount
func getAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.GetAccountCmd) addr, err := decodeAddress(cmd.Address, w.ChainParams()) if err != nil { return nil, err } // Fetch the associated account account, err := w.AccountOfAddress(addr) if err != nil { return nil, &ErrAddressNotInWallet } acctName, err := w.AccountName(waddrmgr.KeyScopeBIP0044, account) if err != nil { return nil, &ErrAccountNameNotFound } return acctName, nil }
go
func getAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.GetAccountCmd) addr, err := decodeAddress(cmd.Address, w.ChainParams()) if err != nil { return nil, err } // Fetch the associated account account, err := w.AccountOfAddress(addr) if err != nil { return nil, &ErrAddressNotInWallet } acctName, err := w.AccountName(waddrmgr.KeyScopeBIP0044, account) if err != nil { return nil, &ErrAccountNameNotFound } return acctName, nil }
[ "func", "getAccount", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "GetAccountCmd", ")", "\n\n", "addr", ",", "err", ":=", "decodeAddress", "(", "cmd", ".", "Address", ",", "w", ".", "ChainParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Fetch the associated account", "account", ",", "err", ":=", "w", ".", "AccountOfAddress", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "&", "ErrAddressNotInWallet", "\n", "}", "\n\n", "acctName", ",", "err", ":=", "w", ".", "AccountName", "(", "waddrmgr", ".", "KeyScopeBIP0044", ",", "account", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "&", "ErrAccountNameNotFound", "\n", "}", "\n", "return", "acctName", ",", "nil", "\n", "}" ]
// getAccount handles a getaccount request by returning the account name // associated with a single address.
[ "getAccount", "handles", "a", "getaccount", "request", "by", "returning", "the", "account", "name", "associated", "with", "a", "single", "address", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L540-L559
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
getUnconfirmedBalance
func getUnconfirmedBalance(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.GetUnconfirmedBalanceCmd) acctName := "default" if cmd.Account != nil { acctName = *cmd.Account } account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, acctName) if err != nil { return nil, err } bals, err := w.CalculateAccountBalances(account, 1) if err != nil { return nil, err } return (bals.Total - bals.Spendable).ToBTC(), nil }
go
func getUnconfirmedBalance(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.GetUnconfirmedBalanceCmd) acctName := "default" if cmd.Account != nil { acctName = *cmd.Account } account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, acctName) if err != nil { return nil, err } bals, err := w.CalculateAccountBalances(account, 1) if err != nil { return nil, err } return (bals.Total - bals.Spendable).ToBTC(), nil }
[ "func", "getUnconfirmedBalance", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "GetUnconfirmedBalanceCmd", ")", "\n\n", "acctName", ":=", "\"", "\"", "\n", "if", "cmd", ".", "Account", "!=", "nil", "{", "acctName", "=", "*", "cmd", ".", "Account", "\n", "}", "\n", "account", ",", "err", ":=", "w", ".", "AccountNumber", "(", "waddrmgr", ".", "KeyScopeBIP0044", ",", "acctName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "bals", ",", "err", ":=", "w", ".", "CalculateAccountBalances", "(", "account", ",", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "(", "bals", ".", "Total", "-", "bals", ".", "Spendable", ")", ".", "ToBTC", "(", ")", ",", "nil", "\n", "}" ]
// getUnconfirmedBalance handles a getunconfirmedbalance extension request // by returning the current unconfirmed balance of an account.
[ "getUnconfirmedBalance", "handles", "a", "getunconfirmedbalance", "extension", "request", "by", "returning", "the", "current", "unconfirmed", "balance", "of", "an", "account", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L584-L601
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
importPrivKey
func importPrivKey(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.ImportPrivKeyCmd) // Ensure that private keys are only imported to the correct account. // // Yes, Label is the account name. if cmd.Label != nil && *cmd.Label != waddrmgr.ImportedAddrAccountName { return nil, &ErrNotImportedAccount } wif, err := btcutil.DecodeWIF(cmd.PrivKey) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidAddressOrKey, Message: "WIF decode failed: " + err.Error(), } } if !wif.IsForNet(w.ChainParams()) { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidAddressOrKey, Message: "Key is not intended for " + w.ChainParams().Name, } } // Import the private key, handling any errors. _, err = w.ImportPrivateKey(waddrmgr.KeyScopeBIP0044, wif, nil, *cmd.Rescan) switch { case waddrmgr.IsError(err, waddrmgr.ErrDuplicateAddress): // Do not return duplicate key errors to the client. return nil, nil case waddrmgr.IsError(err, waddrmgr.ErrLocked): return nil, &ErrWalletUnlockNeeded } return nil, err }
go
func importPrivKey(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.ImportPrivKeyCmd) // Ensure that private keys are only imported to the correct account. // // Yes, Label is the account name. if cmd.Label != nil && *cmd.Label != waddrmgr.ImportedAddrAccountName { return nil, &ErrNotImportedAccount } wif, err := btcutil.DecodeWIF(cmd.PrivKey) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidAddressOrKey, Message: "WIF decode failed: " + err.Error(), } } if !wif.IsForNet(w.ChainParams()) { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidAddressOrKey, Message: "Key is not intended for " + w.ChainParams().Name, } } // Import the private key, handling any errors. _, err = w.ImportPrivateKey(waddrmgr.KeyScopeBIP0044, wif, nil, *cmd.Rescan) switch { case waddrmgr.IsError(err, waddrmgr.ErrDuplicateAddress): // Do not return duplicate key errors to the client. return nil, nil case waddrmgr.IsError(err, waddrmgr.ErrLocked): return nil, &ErrWalletUnlockNeeded } return nil, err }
[ "func", "importPrivKey", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "ImportPrivKeyCmd", ")", "\n\n", "// Ensure that private keys are only imported to the correct account.", "//", "// Yes, Label is the account name.", "if", "cmd", ".", "Label", "!=", "nil", "&&", "*", "cmd", ".", "Label", "!=", "waddrmgr", ".", "ImportedAddrAccountName", "{", "return", "nil", ",", "&", "ErrNotImportedAccount", "\n", "}", "\n\n", "wif", ",", "err", ":=", "btcutil", ".", "DecodeWIF", "(", "cmd", ".", "PrivKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCInvalidAddressOrKey", ",", "Message", ":", "\"", "\"", "+", "err", ".", "Error", "(", ")", ",", "}", "\n", "}", "\n", "if", "!", "wif", ".", "IsForNet", "(", "w", ".", "ChainParams", "(", ")", ")", "{", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCInvalidAddressOrKey", ",", "Message", ":", "\"", "\"", "+", "w", ".", "ChainParams", "(", ")", ".", "Name", ",", "}", "\n", "}", "\n\n", "// Import the private key, handling any errors.", "_", ",", "err", "=", "w", ".", "ImportPrivateKey", "(", "waddrmgr", ".", "KeyScopeBIP0044", ",", "wif", ",", "nil", ",", "*", "cmd", ".", "Rescan", ")", "\n", "switch", "{", "case", "waddrmgr", ".", "IsError", "(", "err", ",", "waddrmgr", ".", "ErrDuplicateAddress", ")", ":", "// Do not return duplicate key errors to the client.", "return", "nil", ",", "nil", "\n", "case", "waddrmgr", ".", "IsError", "(", "err", ",", "waddrmgr", ".", "ErrLocked", ")", ":", "return", "nil", ",", "&", "ErrWalletUnlockNeeded", "\n", "}", "\n\n", "return", "nil", ",", "err", "\n", "}" ]
// importPrivKey handles an importprivkey request by parsing // a WIF-encoded private key and adding it to an account.
[ "importPrivKey", "handles", "an", "importprivkey", "request", "by", "parsing", "a", "WIF", "-", "encoded", "private", "key", "and", "adding", "it", "to", "an", "account", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L605-L640
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
createNewAccount
func createNewAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.CreateNewAccountCmd) // The wildcard * is reserved by the rpc server with the special meaning // of "all accounts", so disallow naming accounts to this string. if cmd.Account == "*" { return nil, &ErrReservedAccountName } _, err := w.NextAccount(waddrmgr.KeyScopeBIP0044, cmd.Account) if waddrmgr.IsError(err, waddrmgr.ErrLocked) { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCWalletUnlockNeeded, Message: "Creating an account requires the wallet to be unlocked. " + "Enter the wallet passphrase with walletpassphrase to unlock", } } return nil, err }
go
func createNewAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.CreateNewAccountCmd) // The wildcard * is reserved by the rpc server with the special meaning // of "all accounts", so disallow naming accounts to this string. if cmd.Account == "*" { return nil, &ErrReservedAccountName } _, err := w.NextAccount(waddrmgr.KeyScopeBIP0044, cmd.Account) if waddrmgr.IsError(err, waddrmgr.ErrLocked) { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCWalletUnlockNeeded, Message: "Creating an account requires the wallet to be unlocked. " + "Enter the wallet passphrase with walletpassphrase to unlock", } } return nil, err }
[ "func", "createNewAccount", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "CreateNewAccountCmd", ")", "\n\n", "// The wildcard * is reserved by the rpc server with the special meaning", "// of \"all accounts\", so disallow naming accounts to this string.", "if", "cmd", ".", "Account", "==", "\"", "\"", "{", "return", "nil", ",", "&", "ErrReservedAccountName", "\n", "}", "\n\n", "_", ",", "err", ":=", "w", ".", "NextAccount", "(", "waddrmgr", ".", "KeyScopeBIP0044", ",", "cmd", ".", "Account", ")", "\n", "if", "waddrmgr", ".", "IsError", "(", "err", ",", "waddrmgr", ".", "ErrLocked", ")", "{", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCWalletUnlockNeeded", ",", "Message", ":", "\"", "\"", "+", "\"", "\"", ",", "}", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}" ]
// createNewAccount handles a createnewaccount request by creating and // returning a new account. If the last account has no transaction history // as per BIP 0044 a new account cannot be created so an error will be returned.
[ "createNewAccount", "handles", "a", "createnewaccount", "request", "by", "creating", "and", "returning", "a", "new", "account", ".", "If", "the", "last", "account", "has", "no", "transaction", "history", "as", "per", "BIP", "0044", "a", "new", "account", "cannot", "be", "created", "so", "an", "error", "will", "be", "returned", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L651-L669
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
renameAccount
func renameAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.RenameAccountCmd) // The wildcard * is reserved by the rpc server with the special meaning // of "all accounts", so disallow naming accounts to this string. if cmd.NewAccount == "*" { return nil, &ErrReservedAccountName } // Check that given account exists account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.OldAccount) if err != nil { return nil, err } return nil, w.RenameAccount(waddrmgr.KeyScopeBIP0044, account, cmd.NewAccount) }
go
func renameAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.RenameAccountCmd) // The wildcard * is reserved by the rpc server with the special meaning // of "all accounts", so disallow naming accounts to this string. if cmd.NewAccount == "*" { return nil, &ErrReservedAccountName } // Check that given account exists account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.OldAccount) if err != nil { return nil, err } return nil, w.RenameAccount(waddrmgr.KeyScopeBIP0044, account, cmd.NewAccount) }
[ "func", "renameAccount", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "RenameAccountCmd", ")", "\n\n", "// The wildcard * is reserved by the rpc server with the special meaning", "// of \"all accounts\", so disallow naming accounts to this string.", "if", "cmd", ".", "NewAccount", "==", "\"", "\"", "{", "return", "nil", ",", "&", "ErrReservedAccountName", "\n", "}", "\n\n", "// Check that given account exists", "account", ",", "err", ":=", "w", ".", "AccountNumber", "(", "waddrmgr", ".", "KeyScopeBIP0044", ",", "cmd", ".", "OldAccount", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "nil", ",", "w", ".", "RenameAccount", "(", "waddrmgr", ".", "KeyScopeBIP0044", ",", "account", ",", "cmd", ".", "NewAccount", ")", "\n", "}" ]
// renameAccount handles a renameaccount request by renaming an account. // If the account does not exist an appropiate error will be returned.
[ "renameAccount", "handles", "a", "renameaccount", "request", "by", "renaming", "an", "account", ".", "If", "the", "account", "does", "not", "exist", "an", "appropiate", "error", "will", "be", "returned", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L673-L688
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
getReceivedByAccount
func getReceivedByAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.GetReceivedByAccountCmd) account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.Account) if err != nil { return nil, err } // TODO: This is more inefficient that it could be, but the entire // algorithm is already dominated by reading every transaction in the // wallet's history. results, err := w.TotalReceivedForAccounts( waddrmgr.KeyScopeBIP0044, int32(*cmd.MinConf), ) if err != nil { return nil, err } acctIndex := int(account) if account == waddrmgr.ImportedAddrAccount { acctIndex = len(results) - 1 } return results[acctIndex].TotalReceived.ToBTC(), nil }
go
func getReceivedByAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.GetReceivedByAccountCmd) account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.Account) if err != nil { return nil, err } // TODO: This is more inefficient that it could be, but the entire // algorithm is already dominated by reading every transaction in the // wallet's history. results, err := w.TotalReceivedForAccounts( waddrmgr.KeyScopeBIP0044, int32(*cmd.MinConf), ) if err != nil { return nil, err } acctIndex := int(account) if account == waddrmgr.ImportedAddrAccount { acctIndex = len(results) - 1 } return results[acctIndex].TotalReceived.ToBTC(), nil }
[ "func", "getReceivedByAccount", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "GetReceivedByAccountCmd", ")", "\n\n", "account", ",", "err", ":=", "w", ".", "AccountNumber", "(", "waddrmgr", ".", "KeyScopeBIP0044", ",", "cmd", ".", "Account", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// TODO: This is more inefficient that it could be, but the entire", "// algorithm is already dominated by reading every transaction in the", "// wallet's history.", "results", ",", "err", ":=", "w", ".", "TotalReceivedForAccounts", "(", "waddrmgr", ".", "KeyScopeBIP0044", ",", "int32", "(", "*", "cmd", ".", "MinConf", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "acctIndex", ":=", "int", "(", "account", ")", "\n", "if", "account", "==", "waddrmgr", ".", "ImportedAddrAccount", "{", "acctIndex", "=", "len", "(", "results", ")", "-", "1", "\n", "}", "\n", "return", "results", "[", "acctIndex", "]", ".", "TotalReceived", ".", "ToBTC", "(", ")", ",", "nil", "\n", "}" ]
// getReceivedByAccount handles a getreceivedbyaccount request by returning // the total amount received by addresses of an account.
[ "getReceivedByAccount", "handles", "a", "getreceivedbyaccount", "request", "by", "returning", "the", "total", "amount", "received", "by", "addresses", "of", "an", "account", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L742-L764
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
getReceivedByAddress
func getReceivedByAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.GetReceivedByAddressCmd) addr, err := decodeAddress(cmd.Address, w.ChainParams()) if err != nil { return nil, err } total, err := w.TotalReceivedForAddr(addr, int32(*cmd.MinConf)) if err != nil { return nil, err } return total.ToBTC(), nil }
go
func getReceivedByAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.GetReceivedByAddressCmd) addr, err := decodeAddress(cmd.Address, w.ChainParams()) if err != nil { return nil, err } total, err := w.TotalReceivedForAddr(addr, int32(*cmd.MinConf)) if err != nil { return nil, err } return total.ToBTC(), nil }
[ "func", "getReceivedByAddress", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "GetReceivedByAddressCmd", ")", "\n\n", "addr", ",", "err", ":=", "decodeAddress", "(", "cmd", ".", "Address", ",", "w", ".", "ChainParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "total", ",", "err", ":=", "w", ".", "TotalReceivedForAddr", "(", "addr", ",", "int32", "(", "*", "cmd", ".", "MinConf", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "total", ".", "ToBTC", "(", ")", ",", "nil", "\n", "}" ]
// getReceivedByAddress handles a getreceivedbyaddress request by returning // the total amount received by a single address.
[ "getReceivedByAddress", "handles", "a", "getreceivedbyaddress", "request", "by", "returning", "the", "total", "amount", "received", "by", "a", "single", "address", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L768-L781
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
helpWithChainRPC
func helpWithChainRPC(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) { return help(icmd, w, chainClient) }
go
func helpWithChainRPC(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) { return help(icmd, w, chainClient) }
[ "func", "helpWithChainRPC", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ",", "chainClient", "*", "chain", ".", "RPCClient", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "help", "(", "icmd", ",", "w", ",", "chainClient", ")", "\n", "}" ]
// helpWithChainRPC handles the help request when the RPC server has been // associated with a consensus RPC client. The additional RPC client is used to // include help messages for methods implemented by the consensus server via RPC // passthrough.
[ "helpWithChainRPC", "handles", "the", "help", "request", "when", "the", "RPC", "server", "has", "been", "associated", "with", "a", "consensus", "RPC", "client", ".", "The", "additional", "RPC", "client", "is", "used", "to", "include", "help", "messages", "for", "methods", "implemented", "by", "the", "consensus", "server", "via", "RPC", "passthrough", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L946-L948
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
helpNoChainRPC
func helpNoChainRPC(icmd interface{}, w *wallet.Wallet) (interface{}, error) { return help(icmd, w, nil) }
go
func helpNoChainRPC(icmd interface{}, w *wallet.Wallet) (interface{}, error) { return help(icmd, w, nil) }
[ "func", "helpNoChainRPC", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "help", "(", "icmd", ",", "w", ",", "nil", ")", "\n", "}" ]
// helpNoChainRPC handles the help request when the RPC server has not been // associated with a consensus RPC client. No help messages are included for // passthrough requests.
[ "helpNoChainRPC", "handles", "the", "help", "request", "when", "the", "RPC", "server", "has", "not", "been", "associated", "with", "a", "consensus", "RPC", "client", ".", "No", "help", "messages", "are", "included", "for", "passthrough", "requests", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L953-L955
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
help
func help(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) { cmd := icmd.(*btcjson.HelpCmd) // btcd returns different help messages depending on the kind of // connection the client is using. Only methods availble to HTTP POST // clients are available to be used by wallet clients, even though // wallet itself is a websocket client to btcd. Therefore, create a // POST client as needed. // // Returns nil if chainClient is currently nil or there is an error // creating the client. // // This is hacky and is probably better handled by exposing help usage // texts in a non-internal btcd package. postClient := func() *rpcclient.Client { if chainClient == nil { return nil } c, err := chainClient.POSTClient() if err != nil { return nil } return c } if cmd.Command == nil || *cmd.Command == "" { // Prepend chain server usage if it is available. usages := requestUsages client := postClient() if client != nil { rawChainUsage, err := client.RawRequest("help", nil) var chainUsage string if err == nil { _ = json.Unmarshal([]byte(rawChainUsage), &chainUsage) } if chainUsage != "" { usages = "Chain server usage:\n\n" + chainUsage + "\n\n" + "Wallet server usage (overrides chain requests):\n\n" + requestUsages } } return usages, nil } defer helpDescsMu.Unlock() helpDescsMu.Lock() if helpDescs == nil { // TODO: Allow other locales to be set via config or detemine // this from environment variables. For now, hardcode US // English. helpDescs = localeHelpDescs["en_US"]() } helpText, ok := helpDescs[*cmd.Command] if ok { return helpText, nil } // Return the chain server's detailed help if possible. var chainHelp string client := postClient() if client != nil { param := make([]byte, len(*cmd.Command)+2) param[0] = '"' copy(param[1:], *cmd.Command) param[len(param)-1] = '"' rawChainHelp, err := client.RawRequest("help", []json.RawMessage{param}) if err == nil { _ = json.Unmarshal([]byte(rawChainHelp), &chainHelp) } } if chainHelp != "" { return chainHelp, nil } return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParameter, Message: fmt.Sprintf("No help for method '%s'", *cmd.Command), } }
go
func help(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) { cmd := icmd.(*btcjson.HelpCmd) // btcd returns different help messages depending on the kind of // connection the client is using. Only methods availble to HTTP POST // clients are available to be used by wallet clients, even though // wallet itself is a websocket client to btcd. Therefore, create a // POST client as needed. // // Returns nil if chainClient is currently nil or there is an error // creating the client. // // This is hacky and is probably better handled by exposing help usage // texts in a non-internal btcd package. postClient := func() *rpcclient.Client { if chainClient == nil { return nil } c, err := chainClient.POSTClient() if err != nil { return nil } return c } if cmd.Command == nil || *cmd.Command == "" { // Prepend chain server usage if it is available. usages := requestUsages client := postClient() if client != nil { rawChainUsage, err := client.RawRequest("help", nil) var chainUsage string if err == nil { _ = json.Unmarshal([]byte(rawChainUsage), &chainUsage) } if chainUsage != "" { usages = "Chain server usage:\n\n" + chainUsage + "\n\n" + "Wallet server usage (overrides chain requests):\n\n" + requestUsages } } return usages, nil } defer helpDescsMu.Unlock() helpDescsMu.Lock() if helpDescs == nil { // TODO: Allow other locales to be set via config or detemine // this from environment variables. For now, hardcode US // English. helpDescs = localeHelpDescs["en_US"]() } helpText, ok := helpDescs[*cmd.Command] if ok { return helpText, nil } // Return the chain server's detailed help if possible. var chainHelp string client := postClient() if client != nil { param := make([]byte, len(*cmd.Command)+2) param[0] = '"' copy(param[1:], *cmd.Command) param[len(param)-1] = '"' rawChainHelp, err := client.RawRequest("help", []json.RawMessage{param}) if err == nil { _ = json.Unmarshal([]byte(rawChainHelp), &chainHelp) } } if chainHelp != "" { return chainHelp, nil } return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParameter, Message: fmt.Sprintf("No help for method '%s'", *cmd.Command), } }
[ "func", "help", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ",", "chainClient", "*", "chain", ".", "RPCClient", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "HelpCmd", ")", "\n\n", "// btcd returns different help messages depending on the kind of", "// connection the client is using. Only methods availble to HTTP POST", "// clients are available to be used by wallet clients, even though", "// wallet itself is a websocket client to btcd. Therefore, create a", "// POST client as needed.", "//", "// Returns nil if chainClient is currently nil or there is an error", "// creating the client.", "//", "// This is hacky and is probably better handled by exposing help usage", "// texts in a non-internal btcd package.", "postClient", ":=", "func", "(", ")", "*", "rpcclient", ".", "Client", "{", "if", "chainClient", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "c", ",", "err", ":=", "chainClient", ".", "POSTClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "c", "\n", "}", "\n", "if", "cmd", ".", "Command", "==", "nil", "||", "*", "cmd", ".", "Command", "==", "\"", "\"", "{", "// Prepend chain server usage if it is available.", "usages", ":=", "requestUsages", "\n", "client", ":=", "postClient", "(", ")", "\n", "if", "client", "!=", "nil", "{", "rawChainUsage", ",", "err", ":=", "client", ".", "RawRequest", "(", "\"", "\"", ",", "nil", ")", "\n", "var", "chainUsage", "string", "\n", "if", "err", "==", "nil", "{", "_", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "rawChainUsage", ")", ",", "&", "chainUsage", ")", "\n", "}", "\n", "if", "chainUsage", "!=", "\"", "\"", "{", "usages", "=", "\"", "\\n", "\\n", "\"", "+", "chainUsage", "+", "\"", "\\n", "\\n", "\"", "+", "\"", "\\n", "\\n", "\"", "+", "requestUsages", "\n", "}", "\n", "}", "\n", "return", "usages", ",", "nil", "\n", "}", "\n\n", "defer", "helpDescsMu", ".", "Unlock", "(", ")", "\n", "helpDescsMu", ".", "Lock", "(", ")", "\n\n", "if", "helpDescs", "==", "nil", "{", "// TODO: Allow other locales to be set via config or detemine", "// this from environment variables. For now, hardcode US", "// English.", "helpDescs", "=", "localeHelpDescs", "[", "\"", "\"", "]", "(", ")", "\n", "}", "\n\n", "helpText", ",", "ok", ":=", "helpDescs", "[", "*", "cmd", ".", "Command", "]", "\n", "if", "ok", "{", "return", "helpText", ",", "nil", "\n", "}", "\n\n", "// Return the chain server's detailed help if possible.", "var", "chainHelp", "string", "\n", "client", ":=", "postClient", "(", ")", "\n", "if", "client", "!=", "nil", "{", "param", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "*", "cmd", ".", "Command", ")", "+", "2", ")", "\n", "param", "[", "0", "]", "=", "'\"'", "\n", "copy", "(", "param", "[", "1", ":", "]", ",", "*", "cmd", ".", "Command", ")", "\n", "param", "[", "len", "(", "param", ")", "-", "1", "]", "=", "'\"'", "\n", "rawChainHelp", ",", "err", ":=", "client", ".", "RawRequest", "(", "\"", "\"", ",", "[", "]", "json", ".", "RawMessage", "{", "param", "}", ")", "\n", "if", "err", "==", "nil", "{", "_", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "rawChainHelp", ")", ",", "&", "chainHelp", ")", "\n", "}", "\n", "}", "\n", "if", "chainHelp", "!=", "\"", "\"", "{", "return", "chainHelp", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCInvalidParameter", ",", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "*", "cmd", ".", "Command", ")", ",", "}", "\n", "}" ]
// help handles the help request by returning one line usage of all available // methods, or full help for a specific method. The chainClient is optional, // and this is simply a helper function for the HelpNoChainRPC and // HelpWithChainRPC handlers.
[ "help", "handles", "the", "help", "request", "by", "returning", "one", "line", "usage", "of", "all", "available", "methods", "or", "full", "help", "for", "a", "specific", "method", ".", "The", "chainClient", "is", "optional", "and", "this", "is", "simply", "a", "helper", "function", "for", "the", "HelpNoChainRPC", "and", "HelpWithChainRPC", "handlers", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L961-L1039
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
listAccounts
func listAccounts(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.ListAccountsCmd) accountBalances := map[string]float64{} results, err := w.AccountBalances(waddrmgr.KeyScopeBIP0044, int32(*cmd.MinConf)) if err != nil { return nil, err } for _, result := range results { accountBalances[result.AccountName] = result.AccountBalance.ToBTC() } // Return the map. This will be marshaled into a JSON object. return accountBalances, nil }
go
func listAccounts(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.ListAccountsCmd) accountBalances := map[string]float64{} results, err := w.AccountBalances(waddrmgr.KeyScopeBIP0044, int32(*cmd.MinConf)) if err != nil { return nil, err } for _, result := range results { accountBalances[result.AccountName] = result.AccountBalance.ToBTC() } // Return the map. This will be marshaled into a JSON object. return accountBalances, nil }
[ "func", "listAccounts", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "ListAccountsCmd", ")", "\n\n", "accountBalances", ":=", "map", "[", "string", "]", "float64", "{", "}", "\n", "results", ",", "err", ":=", "w", ".", "AccountBalances", "(", "waddrmgr", ".", "KeyScopeBIP0044", ",", "int32", "(", "*", "cmd", ".", "MinConf", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "result", ":=", "range", "results", "{", "accountBalances", "[", "result", ".", "AccountName", "]", "=", "result", ".", "AccountBalance", ".", "ToBTC", "(", ")", "\n", "}", "\n", "// Return the map. This will be marshaled into a JSON object.", "return", "accountBalances", ",", "nil", "\n", "}" ]
// listAccounts handles a listaccounts request by returning a map of account // names to their balances.
[ "listAccounts", "handles", "a", "listaccounts", "request", "by", "returning", "a", "map", "of", "account", "names", "to", "their", "balances", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1043-L1056
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
listSinceBlock
func listSinceBlock(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) { cmd := icmd.(*btcjson.ListSinceBlockCmd) syncBlock := w.Manager.SyncedTo() targetConf := int64(*cmd.TargetConfirmations) // For the result we need the block hash for the last block counted // in the blockchain due to confirmations. We send this off now so that // it can arrive asynchronously while we figure out the rest. gbh := chainClient.GetBlockHashAsync(int64(syncBlock.Height) + 1 - targetConf) var start int32 if cmd.BlockHash != nil { hash, err := chainhash.NewHashFromStr(*cmd.BlockHash) if err != nil { return nil, DeserializationError{err} } block, err := chainClient.GetBlockVerboseTx(hash) if err != nil { return nil, err } start = int32(block.Height) + 1 } txInfoList, err := w.ListSinceBlock(start, -1, syncBlock.Height) if err != nil { return nil, err } // Done with work, get the response. blockHash, err := gbh.Receive() if err != nil { return nil, err } res := btcjson.ListSinceBlockResult{ Transactions: txInfoList, LastBlock: blockHash.String(), } return res, nil }
go
func listSinceBlock(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) { cmd := icmd.(*btcjson.ListSinceBlockCmd) syncBlock := w.Manager.SyncedTo() targetConf := int64(*cmd.TargetConfirmations) // For the result we need the block hash for the last block counted // in the blockchain due to confirmations. We send this off now so that // it can arrive asynchronously while we figure out the rest. gbh := chainClient.GetBlockHashAsync(int64(syncBlock.Height) + 1 - targetConf) var start int32 if cmd.BlockHash != nil { hash, err := chainhash.NewHashFromStr(*cmd.BlockHash) if err != nil { return nil, DeserializationError{err} } block, err := chainClient.GetBlockVerboseTx(hash) if err != nil { return nil, err } start = int32(block.Height) + 1 } txInfoList, err := w.ListSinceBlock(start, -1, syncBlock.Height) if err != nil { return nil, err } // Done with work, get the response. blockHash, err := gbh.Receive() if err != nil { return nil, err } res := btcjson.ListSinceBlockResult{ Transactions: txInfoList, LastBlock: blockHash.String(), } return res, nil }
[ "func", "listSinceBlock", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ",", "chainClient", "*", "chain", ".", "RPCClient", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "ListSinceBlockCmd", ")", "\n\n", "syncBlock", ":=", "w", ".", "Manager", ".", "SyncedTo", "(", ")", "\n", "targetConf", ":=", "int64", "(", "*", "cmd", ".", "TargetConfirmations", ")", "\n\n", "// For the result we need the block hash for the last block counted", "// in the blockchain due to confirmations. We send this off now so that", "// it can arrive asynchronously while we figure out the rest.", "gbh", ":=", "chainClient", ".", "GetBlockHashAsync", "(", "int64", "(", "syncBlock", ".", "Height", ")", "+", "1", "-", "targetConf", ")", "\n\n", "var", "start", "int32", "\n", "if", "cmd", ".", "BlockHash", "!=", "nil", "{", "hash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "*", "cmd", ".", "BlockHash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "DeserializationError", "{", "err", "}", "\n", "}", "\n", "block", ",", "err", ":=", "chainClient", ".", "GetBlockVerboseTx", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "start", "=", "int32", "(", "block", ".", "Height", ")", "+", "1", "\n", "}", "\n\n", "txInfoList", ",", "err", ":=", "w", ".", "ListSinceBlock", "(", "start", ",", "-", "1", ",", "syncBlock", ".", "Height", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Done with work, get the response.", "blockHash", ",", "err", ":=", "gbh", ".", "Receive", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "res", ":=", "btcjson", ".", "ListSinceBlockResult", "{", "Transactions", ":", "txInfoList", ",", "LastBlock", ":", "blockHash", ".", "String", "(", ")", ",", "}", "\n", "return", "res", ",", "nil", "\n", "}" ]
// listSinceBlock handles a listsinceblock request by returning an array of maps // with details of sent and received wallet transactions since the given block.
[ "listSinceBlock", "handles", "a", "listsinceblock", "request", "by", "returning", "an", "array", "of", "maps", "with", "details", "of", "sent", "and", "received", "wallet", "transactions", "since", "the", "given", "block", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1196-L1236
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
listTransactions
func listTransactions(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.ListTransactionsCmd) // TODO: ListTransactions does not currently understand the difference // between transactions pertaining to one account from another. This // will be resolved when wtxmgr is combined with the waddrmgr namespace. if cmd.Account != nil && *cmd.Account != "*" { // For now, don't bother trying to continue if the user // specified an account, since this can't be (easily or // efficiently) calculated. return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCWallet, Message: "Transactions are not yet grouped by account", } } return w.ListTransactions(*cmd.From, *cmd.Count) }
go
func listTransactions(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.ListTransactionsCmd) // TODO: ListTransactions does not currently understand the difference // between transactions pertaining to one account from another. This // will be resolved when wtxmgr is combined with the waddrmgr namespace. if cmd.Account != nil && *cmd.Account != "*" { // For now, don't bother trying to continue if the user // specified an account, since this can't be (easily or // efficiently) calculated. return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCWallet, Message: "Transactions are not yet grouped by account", } } return w.ListTransactions(*cmd.From, *cmd.Count) }
[ "func", "listTransactions", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "ListTransactionsCmd", ")", "\n\n", "// TODO: ListTransactions does not currently understand the difference", "// between transactions pertaining to one account from another. This", "// will be resolved when wtxmgr is combined with the waddrmgr namespace.", "if", "cmd", ".", "Account", "!=", "nil", "&&", "*", "cmd", ".", "Account", "!=", "\"", "\"", "{", "// For now, don't bother trying to continue if the user", "// specified an account, since this can't be (easily or", "// efficiently) calculated.", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCWallet", ",", "Message", ":", "\"", "\"", ",", "}", "\n", "}", "\n\n", "return", "w", ".", "ListTransactions", "(", "*", "cmd", ".", "From", ",", "*", "cmd", ".", "Count", ")", "\n", "}" ]
// listTransactions handles a listtransactions request by returning an // array of maps with details of sent and recevied wallet transactions.
[ "listTransactions", "handles", "a", "listtransactions", "request", "by", "returning", "an", "array", "of", "maps", "with", "details", "of", "sent", "and", "recevied", "wallet", "transactions", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1240-L1258
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
listAddressTransactions
func listAddressTransactions(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.ListAddressTransactionsCmd) if cmd.Account != nil && *cmd.Account != "*" { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParameter, Message: "Listing transactions for addresses may only be done for all accounts", } } // Decode addresses. hash160Map := make(map[string]struct{}) for _, addrStr := range cmd.Addresses { addr, err := decodeAddress(addrStr, w.ChainParams()) if err != nil { return nil, err } hash160Map[string(addr.ScriptAddress())] = struct{}{} } return w.ListAddressTransactions(hash160Map) }
go
func listAddressTransactions(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.ListAddressTransactionsCmd) if cmd.Account != nil && *cmd.Account != "*" { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParameter, Message: "Listing transactions for addresses may only be done for all accounts", } } // Decode addresses. hash160Map := make(map[string]struct{}) for _, addrStr := range cmd.Addresses { addr, err := decodeAddress(addrStr, w.ChainParams()) if err != nil { return nil, err } hash160Map[string(addr.ScriptAddress())] = struct{}{} } return w.ListAddressTransactions(hash160Map) }
[ "func", "listAddressTransactions", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "ListAddressTransactionsCmd", ")", "\n\n", "if", "cmd", ".", "Account", "!=", "nil", "&&", "*", "cmd", ".", "Account", "!=", "\"", "\"", "{", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCInvalidParameter", ",", "Message", ":", "\"", "\"", ",", "}", "\n", "}", "\n\n", "// Decode addresses.", "hash160Map", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "addrStr", ":=", "range", "cmd", ".", "Addresses", "{", "addr", ",", "err", ":=", "decodeAddress", "(", "addrStr", ",", "w", ".", "ChainParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "hash160Map", "[", "string", "(", "addr", ".", "ScriptAddress", "(", ")", ")", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "return", "w", ".", "ListAddressTransactions", "(", "hash160Map", ")", "\n", "}" ]
// listAddressTransactions handles a listaddresstransactions request by // returning an array of maps with details of spent and received wallet // transactions. The form of the reply is identical to listtransactions, // but the array elements are limited to transaction details which are // about the addresess included in the request.
[ "listAddressTransactions", "handles", "a", "listaddresstransactions", "request", "by", "returning", "an", "array", "of", "maps", "with", "details", "of", "spent", "and", "received", "wallet", "transactions", ".", "The", "form", "of", "the", "reply", "is", "identical", "to", "listtransactions", "but", "the", "array", "elements", "are", "limited", "to", "transaction", "details", "which", "are", "about", "the", "addresess", "included", "in", "the", "request", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1265-L1286
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
listAllTransactions
func listAllTransactions(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.ListAllTransactionsCmd) if cmd.Account != nil && *cmd.Account != "*" { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParameter, Message: "Listing all transactions may only be done for all accounts", } } return w.ListAllTransactions() }
go
func listAllTransactions(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.ListAllTransactionsCmd) if cmd.Account != nil && *cmd.Account != "*" { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParameter, Message: "Listing all transactions may only be done for all accounts", } } return w.ListAllTransactions() }
[ "func", "listAllTransactions", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "ListAllTransactionsCmd", ")", "\n\n", "if", "cmd", ".", "Account", "!=", "nil", "&&", "*", "cmd", ".", "Account", "!=", "\"", "\"", "{", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCInvalidParameter", ",", "Message", ":", "\"", "\"", ",", "}", "\n", "}", "\n\n", "return", "w", ".", "ListAllTransactions", "(", ")", "\n", "}" ]
// listAllTransactions handles a listalltransactions request by returning // a map with details of sent and recevied wallet transactions. This is // similar to ListTransactions, except it takes only a single optional // argument for the account name and replies with all transactions.
[ "listAllTransactions", "handles", "a", "listalltransactions", "request", "by", "returning", "a", "map", "with", "details", "of", "sent", "and", "recevied", "wallet", "transactions", ".", "This", "is", "similar", "to", "ListTransactions", "except", "it", "takes", "only", "a", "single", "optional", "argument", "for", "the", "account", "name", "and", "replies", "with", "all", "transactions", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1292-L1303
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
listUnspent
func listUnspent(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.ListUnspentCmd) var addresses map[string]struct{} if cmd.Addresses != nil { addresses = make(map[string]struct{}) // confirm that all of them are good: for _, as := range *cmd.Addresses { a, err := decodeAddress(as, w.ChainParams()) if err != nil { return nil, err } addresses[a.EncodeAddress()] = struct{}{} } } return w.ListUnspent(int32(*cmd.MinConf), int32(*cmd.MaxConf), addresses) }
go
func listUnspent(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.ListUnspentCmd) var addresses map[string]struct{} if cmd.Addresses != nil { addresses = make(map[string]struct{}) // confirm that all of them are good: for _, as := range *cmd.Addresses { a, err := decodeAddress(as, w.ChainParams()) if err != nil { return nil, err } addresses[a.EncodeAddress()] = struct{}{} } } return w.ListUnspent(int32(*cmd.MinConf), int32(*cmd.MaxConf), addresses) }
[ "func", "listUnspent", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "ListUnspentCmd", ")", "\n\n", "var", "addresses", "map", "[", "string", "]", "struct", "{", "}", "\n", "if", "cmd", ".", "Addresses", "!=", "nil", "{", "addresses", "=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "// confirm that all of them are good:", "for", "_", ",", "as", ":=", "range", "*", "cmd", ".", "Addresses", "{", "a", ",", "err", ":=", "decodeAddress", "(", "as", ",", "w", ".", "ChainParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "addresses", "[", "a", ".", "EncodeAddress", "(", ")", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n\n", "return", "w", ".", "ListUnspent", "(", "int32", "(", "*", "cmd", ".", "MinConf", ")", ",", "int32", "(", "*", "cmd", ".", "MaxConf", ")", ",", "addresses", ")", "\n", "}" ]
// listUnspent handles the listunspent command.
[ "listUnspent", "handles", "the", "listunspent", "command", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1306-L1323
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
lockUnspent
func lockUnspent(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.LockUnspentCmd) switch { case cmd.Unlock && len(cmd.Transactions) == 0: w.ResetLockedOutpoints() default: for _, input := range cmd.Transactions { txHash, err := chainhash.NewHashFromStr(input.Txid) if err != nil { return nil, ParseError{err} } op := wire.OutPoint{Hash: *txHash, Index: input.Vout} if cmd.Unlock { w.UnlockOutpoint(op) } else { w.LockOutpoint(op) } } } return true, nil }
go
func lockUnspent(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.LockUnspentCmd) switch { case cmd.Unlock && len(cmd.Transactions) == 0: w.ResetLockedOutpoints() default: for _, input := range cmd.Transactions { txHash, err := chainhash.NewHashFromStr(input.Txid) if err != nil { return nil, ParseError{err} } op := wire.OutPoint{Hash: *txHash, Index: input.Vout} if cmd.Unlock { w.UnlockOutpoint(op) } else { w.LockOutpoint(op) } } } return true, nil }
[ "func", "lockUnspent", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "LockUnspentCmd", ")", "\n\n", "switch", "{", "case", "cmd", ".", "Unlock", "&&", "len", "(", "cmd", ".", "Transactions", ")", "==", "0", ":", "w", ".", "ResetLockedOutpoints", "(", ")", "\n", "default", ":", "for", "_", ",", "input", ":=", "range", "cmd", ".", "Transactions", "{", "txHash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "input", ".", "Txid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "ParseError", "{", "err", "}", "\n", "}", "\n", "op", ":=", "wire", ".", "OutPoint", "{", "Hash", ":", "*", "txHash", ",", "Index", ":", "input", ".", "Vout", "}", "\n", "if", "cmd", ".", "Unlock", "{", "w", ".", "UnlockOutpoint", "(", "op", ")", "\n", "}", "else", "{", "w", ".", "LockOutpoint", "(", "op", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// lockUnspent handles the lockunspent command.
[ "lockUnspent", "handles", "the", "lockunspent", "command", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1326-L1347
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
makeOutputs
func makeOutputs(pairs map[string]btcutil.Amount, chainParams *chaincfg.Params) ([]*wire.TxOut, error) { outputs := make([]*wire.TxOut, 0, len(pairs)) for addrStr, amt := range pairs { addr, err := btcutil.DecodeAddress(addrStr, chainParams) if err != nil { return nil, fmt.Errorf("cannot decode address: %s", err) } pkScript, err := txscript.PayToAddrScript(addr) if err != nil { return nil, fmt.Errorf("cannot create txout script: %s", err) } outputs = append(outputs, wire.NewTxOut(int64(amt), pkScript)) } return outputs, nil }
go
func makeOutputs(pairs map[string]btcutil.Amount, chainParams *chaincfg.Params) ([]*wire.TxOut, error) { outputs := make([]*wire.TxOut, 0, len(pairs)) for addrStr, amt := range pairs { addr, err := btcutil.DecodeAddress(addrStr, chainParams) if err != nil { return nil, fmt.Errorf("cannot decode address: %s", err) } pkScript, err := txscript.PayToAddrScript(addr) if err != nil { return nil, fmt.Errorf("cannot create txout script: %s", err) } outputs = append(outputs, wire.NewTxOut(int64(amt), pkScript)) } return outputs, nil }
[ "func", "makeOutputs", "(", "pairs", "map", "[", "string", "]", "btcutil", ".", "Amount", ",", "chainParams", "*", "chaincfg", ".", "Params", ")", "(", "[", "]", "*", "wire", ".", "TxOut", ",", "error", ")", "{", "outputs", ":=", "make", "(", "[", "]", "*", "wire", ".", "TxOut", ",", "0", ",", "len", "(", "pairs", ")", ")", "\n", "for", "addrStr", ",", "amt", ":=", "range", "pairs", "{", "addr", ",", "err", ":=", "btcutil", ".", "DecodeAddress", "(", "addrStr", ",", "chainParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "pkScript", ",", "err", ":=", "txscript", ".", "PayToAddrScript", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "outputs", "=", "append", "(", "outputs", ",", "wire", ".", "NewTxOut", "(", "int64", "(", "amt", ")", ",", "pkScript", ")", ")", "\n", "}", "\n", "return", "outputs", ",", "nil", "\n", "}" ]
// makeOutputs creates a slice of transaction outputs from a pair of address // strings to amounts. This is used to create the outputs to include in newly // created transactions from a JSON object describing the output destinations // and amounts.
[ "makeOutputs", "creates", "a", "slice", "of", "transaction", "outputs", "from", "a", "pair", "of", "address", "strings", "to", "amounts", ".", "This", "is", "used", "to", "create", "the", "outputs", "to", "include", "in", "newly", "created", "transactions", "from", "a", "JSON", "object", "describing", "the", "output", "destinations", "and", "amounts", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1353-L1369
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
sendPairs
func sendPairs(w *wallet.Wallet, amounts map[string]btcutil.Amount, account uint32, minconf int32, feeSatPerKb btcutil.Amount) (string, error) { outputs, err := makeOutputs(amounts, w.ChainParams()) if err != nil { return "", err } tx, err := w.SendOutputs(outputs, account, minconf, feeSatPerKb) if err != nil { if err == txrules.ErrAmountNegative { return "", ErrNeedPositiveAmount } if waddrmgr.IsError(err, waddrmgr.ErrLocked) { return "", &ErrWalletUnlockNeeded } switch err.(type) { case btcjson.RPCError: return "", err } return "", &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: err.Error(), } } txHashStr := tx.TxHash().String() log.Infof("Successfully sent transaction %v", txHashStr) return txHashStr, nil }
go
func sendPairs(w *wallet.Wallet, amounts map[string]btcutil.Amount, account uint32, minconf int32, feeSatPerKb btcutil.Amount) (string, error) { outputs, err := makeOutputs(amounts, w.ChainParams()) if err != nil { return "", err } tx, err := w.SendOutputs(outputs, account, minconf, feeSatPerKb) if err != nil { if err == txrules.ErrAmountNegative { return "", ErrNeedPositiveAmount } if waddrmgr.IsError(err, waddrmgr.ErrLocked) { return "", &ErrWalletUnlockNeeded } switch err.(type) { case btcjson.RPCError: return "", err } return "", &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: err.Error(), } } txHashStr := tx.TxHash().String() log.Infof("Successfully sent transaction %v", txHashStr) return txHashStr, nil }
[ "func", "sendPairs", "(", "w", "*", "wallet", ".", "Wallet", ",", "amounts", "map", "[", "string", "]", "btcutil", ".", "Amount", ",", "account", "uint32", ",", "minconf", "int32", ",", "feeSatPerKb", "btcutil", ".", "Amount", ")", "(", "string", ",", "error", ")", "{", "outputs", ",", "err", ":=", "makeOutputs", "(", "amounts", ",", "w", ".", "ChainParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "tx", ",", "err", ":=", "w", ".", "SendOutputs", "(", "outputs", ",", "account", ",", "minconf", ",", "feeSatPerKb", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "txrules", ".", "ErrAmountNegative", "{", "return", "\"", "\"", ",", "ErrNeedPositiveAmount", "\n", "}", "\n", "if", "waddrmgr", ".", "IsError", "(", "err", ",", "waddrmgr", ".", "ErrLocked", ")", "{", "return", "\"", "\"", ",", "&", "ErrWalletUnlockNeeded", "\n", "}", "\n", "switch", "err", ".", "(", "type", ")", "{", "case", "btcjson", ".", "RPCError", ":", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "\"", "\"", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCInternal", ".", "Code", ",", "Message", ":", "err", ".", "Error", "(", ")", ",", "}", "\n", "}", "\n\n", "txHashStr", ":=", "tx", ".", "TxHash", "(", ")", ".", "String", "(", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "txHashStr", ")", "\n", "return", "txHashStr", ",", "nil", "\n", "}" ]
// sendPairs creates and sends payment transactions. // It returns the transaction hash in string format upon success // All errors are returned in btcjson.RPCError format
[ "sendPairs", "creates", "and", "sends", "payment", "transactions", ".", "It", "returns", "the", "transaction", "hash", "in", "string", "format", "upon", "success", "All", "errors", "are", "returned", "in", "btcjson", ".", "RPCError", "format" ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1374-L1403
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
sendFrom
func sendFrom(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) { cmd := icmd.(*btcjson.SendFromCmd) // Transaction comments are not yet supported. Error instead of // pretending to save them. if !isNilOrEmpty(cmd.Comment) || !isNilOrEmpty(cmd.CommentTo) { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCUnimplemented, Message: "Transaction comments are not yet supported", } } account, err := w.AccountNumber( waddrmgr.KeyScopeBIP0044, cmd.FromAccount, ) if err != nil { return nil, err } // Check that signed integer parameters are positive. if cmd.Amount < 0 { return nil, ErrNeedPositiveAmount } minConf := int32(*cmd.MinConf) if minConf < 0 { return nil, ErrNeedPositiveMinconf } // Create map of address and amount pairs. amt, err := btcutil.NewAmount(cmd.Amount) if err != nil { return nil, err } pairs := map[string]btcutil.Amount{ cmd.ToAddress: amt, } return sendPairs(w, pairs, account, minConf, txrules.DefaultRelayFeePerKb) }
go
func sendFrom(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) { cmd := icmd.(*btcjson.SendFromCmd) // Transaction comments are not yet supported. Error instead of // pretending to save them. if !isNilOrEmpty(cmd.Comment) || !isNilOrEmpty(cmd.CommentTo) { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCUnimplemented, Message: "Transaction comments are not yet supported", } } account, err := w.AccountNumber( waddrmgr.KeyScopeBIP0044, cmd.FromAccount, ) if err != nil { return nil, err } // Check that signed integer parameters are positive. if cmd.Amount < 0 { return nil, ErrNeedPositiveAmount } minConf := int32(*cmd.MinConf) if minConf < 0 { return nil, ErrNeedPositiveMinconf } // Create map of address and amount pairs. amt, err := btcutil.NewAmount(cmd.Amount) if err != nil { return nil, err } pairs := map[string]btcutil.Amount{ cmd.ToAddress: amt, } return sendPairs(w, pairs, account, minConf, txrules.DefaultRelayFeePerKb) }
[ "func", "sendFrom", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ",", "chainClient", "*", "chain", ".", "RPCClient", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "SendFromCmd", ")", "\n\n", "// Transaction comments are not yet supported. Error instead of", "// pretending to save them.", "if", "!", "isNilOrEmpty", "(", "cmd", ".", "Comment", ")", "||", "!", "isNilOrEmpty", "(", "cmd", ".", "CommentTo", ")", "{", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCUnimplemented", ",", "Message", ":", "\"", "\"", ",", "}", "\n", "}", "\n\n", "account", ",", "err", ":=", "w", ".", "AccountNumber", "(", "waddrmgr", ".", "KeyScopeBIP0044", ",", "cmd", ".", "FromAccount", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Check that signed integer parameters are positive.", "if", "cmd", ".", "Amount", "<", "0", "{", "return", "nil", ",", "ErrNeedPositiveAmount", "\n", "}", "\n", "minConf", ":=", "int32", "(", "*", "cmd", ".", "MinConf", ")", "\n", "if", "minConf", "<", "0", "{", "return", "nil", ",", "ErrNeedPositiveMinconf", "\n", "}", "\n", "// Create map of address and amount pairs.", "amt", ",", "err", ":=", "btcutil", ".", "NewAmount", "(", "cmd", ".", "Amount", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "pairs", ":=", "map", "[", "string", "]", "btcutil", ".", "Amount", "{", "cmd", ".", "ToAddress", ":", "amt", ",", "}", "\n\n", "return", "sendPairs", "(", "w", ",", "pairs", ",", "account", ",", "minConf", ",", "txrules", ".", "DefaultRelayFeePerKb", ")", "\n", "}" ]
// sendFrom handles a sendfrom 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.
[ "sendFrom", "handles", "a", "sendfrom", "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", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1414-L1452
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
sendMany
func sendMany(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.SendManyCmd) // Transaction comments are not yet supported. Error instead of // pretending to save them. if !isNilOrEmpty(cmd.Comment) { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCUnimplemented, Message: "Transaction comments are not yet supported", } } account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.FromAccount) if err != nil { return nil, err } // Check that minconf is positive. minConf := int32(*cmd.MinConf) if minConf < 0 { return nil, ErrNeedPositiveMinconf } // Recreate address/amount pairs, using dcrutil.Amount. pairs := make(map[string]btcutil.Amount, len(cmd.Amounts)) for k, v := range cmd.Amounts { amt, err := btcutil.NewAmount(v) if err != nil { return nil, err } pairs[k] = amt } return sendPairs(w, pairs, account, minConf, txrules.DefaultRelayFeePerKb) }
go
func sendMany(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.SendManyCmd) // Transaction comments are not yet supported. Error instead of // pretending to save them. if !isNilOrEmpty(cmd.Comment) { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCUnimplemented, Message: "Transaction comments are not yet supported", } } account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.FromAccount) if err != nil { return nil, err } // Check that minconf is positive. minConf := int32(*cmd.MinConf) if minConf < 0 { return nil, ErrNeedPositiveMinconf } // Recreate address/amount pairs, using dcrutil.Amount. pairs := make(map[string]btcutil.Amount, len(cmd.Amounts)) for k, v := range cmd.Amounts { amt, err := btcutil.NewAmount(v) if err != nil { return nil, err } pairs[k] = amt } return sendPairs(w, pairs, account, minConf, txrules.DefaultRelayFeePerKb) }
[ "func", "sendMany", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "SendManyCmd", ")", "\n\n", "// Transaction comments are not yet supported. Error instead of", "// pretending to save them.", "if", "!", "isNilOrEmpty", "(", "cmd", ".", "Comment", ")", "{", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCUnimplemented", ",", "Message", ":", "\"", "\"", ",", "}", "\n", "}", "\n\n", "account", ",", "err", ":=", "w", ".", "AccountNumber", "(", "waddrmgr", ".", "KeyScopeBIP0044", ",", "cmd", ".", "FromAccount", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Check that minconf is positive.", "minConf", ":=", "int32", "(", "*", "cmd", ".", "MinConf", ")", "\n", "if", "minConf", "<", "0", "{", "return", "nil", ",", "ErrNeedPositiveMinconf", "\n", "}", "\n\n", "// Recreate address/amount pairs, using dcrutil.Amount.", "pairs", ":=", "make", "(", "map", "[", "string", "]", "btcutil", ".", "Amount", ",", "len", "(", "cmd", ".", "Amounts", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "cmd", ".", "Amounts", "{", "amt", ",", "err", ":=", "btcutil", ".", "NewAmount", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "pairs", "[", "k", "]", "=", "amt", "\n", "}", "\n\n", "return", "sendPairs", "(", "w", ",", "pairs", ",", "account", ",", "minConf", ",", "txrules", ".", "DefaultRelayFeePerKb", ")", "\n", "}" ]
// sendMany handles a sendmany RPC request by creating a new transaction // spending unspent transaction outputs for a wallet to any number of // payment addresses. 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.
[ "sendMany", "handles", "a", "sendmany", "RPC", "request", "by", "creating", "a", "new", "transaction", "spending", "unspent", "transaction", "outputs", "for", "a", "wallet", "to", "any", "number", "of", "payment", "addresses", ".", "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", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1459-L1493
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
sendToAddress
func sendToAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.SendToAddressCmd) // Transaction comments are not yet supported. Error instead of // pretending to save them. if !isNilOrEmpty(cmd.Comment) || !isNilOrEmpty(cmd.CommentTo) { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCUnimplemented, Message: "Transaction comments are not yet supported", } } amt, err := btcutil.NewAmount(cmd.Amount) if err != nil { return nil, err } // Check that signed integer parameters are positive. if amt < 0 { return nil, ErrNeedPositiveAmount } // Mock up map of address and amount pairs. pairs := map[string]btcutil.Amount{ cmd.Address: amt, } // sendtoaddress always spends from the default account, this matches bitcoind return sendPairs(w, pairs, waddrmgr.DefaultAccountNum, 1, txrules.DefaultRelayFeePerKb) }
go
func sendToAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.SendToAddressCmd) // Transaction comments are not yet supported. Error instead of // pretending to save them. if !isNilOrEmpty(cmd.Comment) || !isNilOrEmpty(cmd.CommentTo) { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCUnimplemented, Message: "Transaction comments are not yet supported", } } amt, err := btcutil.NewAmount(cmd.Amount) if err != nil { return nil, err } // Check that signed integer parameters are positive. if amt < 0 { return nil, ErrNeedPositiveAmount } // Mock up map of address and amount pairs. pairs := map[string]btcutil.Amount{ cmd.Address: amt, } // sendtoaddress always spends from the default account, this matches bitcoind return sendPairs(w, pairs, waddrmgr.DefaultAccountNum, 1, txrules.DefaultRelayFeePerKb) }
[ "func", "sendToAddress", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "SendToAddressCmd", ")", "\n\n", "// Transaction comments are not yet supported. Error instead of", "// pretending to save them.", "if", "!", "isNilOrEmpty", "(", "cmd", ".", "Comment", ")", "||", "!", "isNilOrEmpty", "(", "cmd", ".", "CommentTo", ")", "{", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCUnimplemented", ",", "Message", ":", "\"", "\"", ",", "}", "\n", "}", "\n\n", "amt", ",", "err", ":=", "btcutil", ".", "NewAmount", "(", "cmd", ".", "Amount", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Check that signed integer parameters are positive.", "if", "amt", "<", "0", "{", "return", "nil", ",", "ErrNeedPositiveAmount", "\n", "}", "\n\n", "// Mock up map of address and amount pairs.", "pairs", ":=", "map", "[", "string", "]", "btcutil", ".", "Amount", "{", "cmd", ".", "Address", ":", "amt", ",", "}", "\n\n", "// sendtoaddress always spends from the default account, this matches bitcoind", "return", "sendPairs", "(", "w", ",", "pairs", ",", "waddrmgr", ".", "DefaultAccountNum", ",", "1", ",", "txrules", ".", "DefaultRelayFeePerKb", ")", "\n", "}" ]
// 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.
[ "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", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1500-L1530
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
setTxFee
func setTxFee(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.SetTxFeeCmd) // Check that amount is not negative. if cmd.Amount < 0 { return nil, ErrNeedPositiveAmount } // A boolean true result is returned upon success. return true, nil }
go
func setTxFee(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.SetTxFeeCmd) // Check that amount is not negative. if cmd.Amount < 0 { return nil, ErrNeedPositiveAmount } // A boolean true result is returned upon success. return true, nil }
[ "func", "setTxFee", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "SetTxFeeCmd", ")", "\n\n", "// Check that amount is not negative.", "if", "cmd", ".", "Amount", "<", "0", "{", "return", "nil", ",", "ErrNeedPositiveAmount", "\n", "}", "\n\n", "// A boolean true result is returned upon success.", "return", "true", ",", "nil", "\n", "}" ]
// setTxFee sets the transaction fee per kilobyte added to transactions.
[ "setTxFee", "sets", "the", "transaction", "fee", "per", "kilobyte", "added", "to", "transactions", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1533-L1543
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
signMessage
func signMessage(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.SignMessageCmd) addr, err := decodeAddress(cmd.Address, w.ChainParams()) if err != nil { return nil, err } privKey, err := w.PrivKeyForAddress(addr) if err != nil { return nil, err } var buf bytes.Buffer wire.WriteVarString(&buf, 0, "Bitcoin Signed Message:\n") wire.WriteVarString(&buf, 0, cmd.Message) messageHash := chainhash.DoubleHashB(buf.Bytes()) sigbytes, err := btcec.SignCompact(btcec.S256(), privKey, messageHash, true) if err != nil { return nil, err } return base64.StdEncoding.EncodeToString(sigbytes), nil }
go
func signMessage(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.SignMessageCmd) addr, err := decodeAddress(cmd.Address, w.ChainParams()) if err != nil { return nil, err } privKey, err := w.PrivKeyForAddress(addr) if err != nil { return nil, err } var buf bytes.Buffer wire.WriteVarString(&buf, 0, "Bitcoin Signed Message:\n") wire.WriteVarString(&buf, 0, cmd.Message) messageHash := chainhash.DoubleHashB(buf.Bytes()) sigbytes, err := btcec.SignCompact(btcec.S256(), privKey, messageHash, true) if err != nil { return nil, err } return base64.StdEncoding.EncodeToString(sigbytes), nil }
[ "func", "signMessage", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "SignMessageCmd", ")", "\n\n", "addr", ",", "err", ":=", "decodeAddress", "(", "cmd", ".", "Address", ",", "w", ".", "ChainParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "privKey", ",", "err", ":=", "w", ".", "PrivKeyForAddress", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "buf", "bytes", ".", "Buffer", "\n", "wire", ".", "WriteVarString", "(", "&", "buf", ",", "0", ",", "\"", "\\n", "\"", ")", "\n", "wire", ".", "WriteVarString", "(", "&", "buf", ",", "0", ",", "cmd", ".", "Message", ")", "\n", "messageHash", ":=", "chainhash", ".", "DoubleHashB", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "sigbytes", ",", "err", ":=", "btcec", ".", "SignCompact", "(", "btcec", ".", "S256", "(", ")", ",", "privKey", ",", "messageHash", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "sigbytes", ")", ",", "nil", "\n", "}" ]
// signMessage signs the given message with the private key for the given // address
[ "signMessage", "signs", "the", "given", "message", "with", "the", "private", "key", "for", "the", "given", "address" ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1547-L1571
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
validateAddress
func validateAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.ValidateAddressCmd) result := btcjson.ValidateAddressWalletResult{} addr, err := decodeAddress(cmd.Address, w.ChainParams()) if err != nil { // Use result zero value (IsValid=false). return result, nil } // We could put whether or not the address is a script here, // by checking the type of "addr", however, the reference // implementation only puts that information if the script is // "ismine", and we follow that behaviour. result.Address = addr.EncodeAddress() result.IsValid = true ainfo, err := w.AddressInfo(addr) if err != nil { if waddrmgr.IsError(err, waddrmgr.ErrAddressNotFound) { // No additional information available about the address. return result, nil } return nil, err } // The address lookup was successful which means there is further // information about it available and it is "mine". result.IsMine = true acctName, err := w.AccountName(waddrmgr.KeyScopeBIP0044, ainfo.Account()) if err != nil { return nil, &ErrAccountNameNotFound } result.Account = acctName switch ma := ainfo.(type) { case waddrmgr.ManagedPubKeyAddress: result.IsCompressed = ma.Compressed() result.PubKey = ma.ExportPubKey() case waddrmgr.ManagedScriptAddress: result.IsScript = true // The script is only available if the manager is unlocked, so // just break out now if there is an error. script, err := ma.Script() if err != nil { break } result.Hex = hex.EncodeToString(script) // This typically shouldn't fail unless an invalid script was // imported. However, if it fails for any reason, there is no // further information available, so just set the script type // a non-standard and break out now. class, addrs, reqSigs, err := txscript.ExtractPkScriptAddrs( script, w.ChainParams()) if err != nil { result.Script = txscript.NonStandardTy.String() break } addrStrings := make([]string, len(addrs)) for i, a := range addrs { addrStrings[i] = a.EncodeAddress() } result.Addresses = addrStrings // Multi-signature scripts also provide the number of required // signatures. result.Script = class.String() if class == txscript.MultiSigTy { result.SigsRequired = int32(reqSigs) } } return result, nil }
go
func validateAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.ValidateAddressCmd) result := btcjson.ValidateAddressWalletResult{} addr, err := decodeAddress(cmd.Address, w.ChainParams()) if err != nil { // Use result zero value (IsValid=false). return result, nil } // We could put whether or not the address is a script here, // by checking the type of "addr", however, the reference // implementation only puts that information if the script is // "ismine", and we follow that behaviour. result.Address = addr.EncodeAddress() result.IsValid = true ainfo, err := w.AddressInfo(addr) if err != nil { if waddrmgr.IsError(err, waddrmgr.ErrAddressNotFound) { // No additional information available about the address. return result, nil } return nil, err } // The address lookup was successful which means there is further // information about it available and it is "mine". result.IsMine = true acctName, err := w.AccountName(waddrmgr.KeyScopeBIP0044, ainfo.Account()) if err != nil { return nil, &ErrAccountNameNotFound } result.Account = acctName switch ma := ainfo.(type) { case waddrmgr.ManagedPubKeyAddress: result.IsCompressed = ma.Compressed() result.PubKey = ma.ExportPubKey() case waddrmgr.ManagedScriptAddress: result.IsScript = true // The script is only available if the manager is unlocked, so // just break out now if there is an error. script, err := ma.Script() if err != nil { break } result.Hex = hex.EncodeToString(script) // This typically shouldn't fail unless an invalid script was // imported. However, if it fails for any reason, there is no // further information available, so just set the script type // a non-standard and break out now. class, addrs, reqSigs, err := txscript.ExtractPkScriptAddrs( script, w.ChainParams()) if err != nil { result.Script = txscript.NonStandardTy.String() break } addrStrings := make([]string, len(addrs)) for i, a := range addrs { addrStrings[i] = a.EncodeAddress() } result.Addresses = addrStrings // Multi-signature scripts also provide the number of required // signatures. result.Script = class.String() if class == txscript.MultiSigTy { result.SigsRequired = int32(reqSigs) } } return result, nil }
[ "func", "validateAddress", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "ValidateAddressCmd", ")", "\n\n", "result", ":=", "btcjson", ".", "ValidateAddressWalletResult", "{", "}", "\n", "addr", ",", "err", ":=", "decodeAddress", "(", "cmd", ".", "Address", ",", "w", ".", "ChainParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "// Use result zero value (IsValid=false).", "return", "result", ",", "nil", "\n", "}", "\n\n", "// We could put whether or not the address is a script here,", "// by checking the type of \"addr\", however, the reference", "// implementation only puts that information if the script is", "// \"ismine\", and we follow that behaviour.", "result", ".", "Address", "=", "addr", ".", "EncodeAddress", "(", ")", "\n", "result", ".", "IsValid", "=", "true", "\n\n", "ainfo", ",", "err", ":=", "w", ".", "AddressInfo", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "if", "waddrmgr", ".", "IsError", "(", "err", ",", "waddrmgr", ".", "ErrAddressNotFound", ")", "{", "// No additional information available about the address.", "return", "result", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// The address lookup was successful which means there is further", "// information about it available and it is \"mine\".", "result", ".", "IsMine", "=", "true", "\n", "acctName", ",", "err", ":=", "w", ".", "AccountName", "(", "waddrmgr", ".", "KeyScopeBIP0044", ",", "ainfo", ".", "Account", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "&", "ErrAccountNameNotFound", "\n", "}", "\n", "result", ".", "Account", "=", "acctName", "\n\n", "switch", "ma", ":=", "ainfo", ".", "(", "type", ")", "{", "case", "waddrmgr", ".", "ManagedPubKeyAddress", ":", "result", ".", "IsCompressed", "=", "ma", ".", "Compressed", "(", ")", "\n", "result", ".", "PubKey", "=", "ma", ".", "ExportPubKey", "(", ")", "\n\n", "case", "waddrmgr", ".", "ManagedScriptAddress", ":", "result", ".", "IsScript", "=", "true", "\n\n", "// The script is only available if the manager is unlocked, so", "// just break out now if there is an error.", "script", ",", "err", ":=", "ma", ".", "Script", "(", ")", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "result", ".", "Hex", "=", "hex", ".", "EncodeToString", "(", "script", ")", "\n\n", "// This typically shouldn't fail unless an invalid script was", "// imported. However, if it fails for any reason, there is no", "// further information available, so just set the script type", "// a non-standard and break out now.", "class", ",", "addrs", ",", "reqSigs", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "script", ",", "w", ".", "ChainParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Script", "=", "txscript", ".", "NonStandardTy", ".", "String", "(", ")", "\n", "break", "\n", "}", "\n\n", "addrStrings", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "addrs", ")", ")", "\n", "for", "i", ",", "a", ":=", "range", "addrs", "{", "addrStrings", "[", "i", "]", "=", "a", ".", "EncodeAddress", "(", ")", "\n", "}", "\n", "result", ".", "Addresses", "=", "addrStrings", "\n\n", "// Multi-signature scripts also provide the number of required", "// signatures.", "result", ".", "Script", "=", "class", ".", "String", "(", ")", "\n", "if", "class", "==", "txscript", ".", "MultiSigTy", "{", "result", ".", "SigsRequired", "=", "int32", "(", "reqSigs", ")", "\n", "}", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// validateAddress handles the validateaddress command.
[ "validateAddress", "handles", "the", "validateaddress", "command", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1748-L1825
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
verifyMessage
func verifyMessage(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.VerifyMessageCmd) addr, err := decodeAddress(cmd.Address, w.ChainParams()) if err != nil { return nil, err } // decode base64 signature sig, err := base64.StdEncoding.DecodeString(cmd.Signature) if err != nil { return nil, err } // Validate the signature - this just shows that it was valid at all. // we will compare it with the key next. var buf bytes.Buffer wire.WriteVarString(&buf, 0, "Bitcoin Signed Message:\n") wire.WriteVarString(&buf, 0, cmd.Message) expectedMessageHash := chainhash.DoubleHashB(buf.Bytes()) pk, wasCompressed, err := btcec.RecoverCompact(btcec.S256(), sig, expectedMessageHash) if err != nil { return nil, err } var serializedPubKey []byte if wasCompressed { serializedPubKey = pk.SerializeCompressed() } else { serializedPubKey = pk.SerializeUncompressed() } // Verify that the signed-by address matches the given address switch checkAddr := addr.(type) { case *btcutil.AddressPubKeyHash: // ok return bytes.Equal(btcutil.Hash160(serializedPubKey), checkAddr.Hash160()[:]), nil case *btcutil.AddressPubKey: // ok return string(serializedPubKey) == checkAddr.String(), nil default: return nil, errors.New("address type not supported") } }
go
func verifyMessage(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.VerifyMessageCmd) addr, err := decodeAddress(cmd.Address, w.ChainParams()) if err != nil { return nil, err } // decode base64 signature sig, err := base64.StdEncoding.DecodeString(cmd.Signature) if err != nil { return nil, err } // Validate the signature - this just shows that it was valid at all. // we will compare it with the key next. var buf bytes.Buffer wire.WriteVarString(&buf, 0, "Bitcoin Signed Message:\n") wire.WriteVarString(&buf, 0, cmd.Message) expectedMessageHash := chainhash.DoubleHashB(buf.Bytes()) pk, wasCompressed, err := btcec.RecoverCompact(btcec.S256(), sig, expectedMessageHash) if err != nil { return nil, err } var serializedPubKey []byte if wasCompressed { serializedPubKey = pk.SerializeCompressed() } else { serializedPubKey = pk.SerializeUncompressed() } // Verify that the signed-by address matches the given address switch checkAddr := addr.(type) { case *btcutil.AddressPubKeyHash: // ok return bytes.Equal(btcutil.Hash160(serializedPubKey), checkAddr.Hash160()[:]), nil case *btcutil.AddressPubKey: // ok return string(serializedPubKey) == checkAddr.String(), nil default: return nil, errors.New("address type not supported") } }
[ "func", "verifyMessage", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "VerifyMessageCmd", ")", "\n\n", "addr", ",", "err", ":=", "decodeAddress", "(", "cmd", ".", "Address", ",", "w", ".", "ChainParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// decode base64 signature", "sig", ",", "err", ":=", "base64", ".", "StdEncoding", ".", "DecodeString", "(", "cmd", ".", "Signature", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Validate the signature - this just shows that it was valid at all.", "// we will compare it with the key next.", "var", "buf", "bytes", ".", "Buffer", "\n", "wire", ".", "WriteVarString", "(", "&", "buf", ",", "0", ",", "\"", "\\n", "\"", ")", "\n", "wire", ".", "WriteVarString", "(", "&", "buf", ",", "0", ",", "cmd", ".", "Message", ")", "\n", "expectedMessageHash", ":=", "chainhash", ".", "DoubleHashB", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "pk", ",", "wasCompressed", ",", "err", ":=", "btcec", ".", "RecoverCompact", "(", "btcec", ".", "S256", "(", ")", ",", "sig", ",", "expectedMessageHash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "serializedPubKey", "[", "]", "byte", "\n", "if", "wasCompressed", "{", "serializedPubKey", "=", "pk", ".", "SerializeCompressed", "(", ")", "\n", "}", "else", "{", "serializedPubKey", "=", "pk", ".", "SerializeUncompressed", "(", ")", "\n", "}", "\n", "// Verify that the signed-by address matches the given address", "switch", "checkAddr", ":=", "addr", ".", "(", "type", ")", "{", "case", "*", "btcutil", ".", "AddressPubKeyHash", ":", "// ok", "return", "bytes", ".", "Equal", "(", "btcutil", ".", "Hash160", "(", "serializedPubKey", ")", ",", "checkAddr", ".", "Hash160", "(", ")", "[", ":", "]", ")", ",", "nil", "\n", "case", "*", "btcutil", ".", "AddressPubKey", ":", "// ok", "return", "string", "(", "serializedPubKey", ")", "==", "checkAddr", ".", "String", "(", ")", ",", "nil", "\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// verifyMessage handles the verifymessage command by verifying the provided // compact signature for the given address and message.
[ "verifyMessage", "handles", "the", "verifymessage", "command", "by", "verifying", "the", "provided", "compact", "signature", "for", "the", "given", "address", "and", "message", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1829-L1870
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
walletPassphrase
func walletPassphrase(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.WalletPassphraseCmd) timeout := time.Second * time.Duration(cmd.Timeout) var unlockAfter <-chan time.Time if timeout != 0 { unlockAfter = time.After(timeout) } err := w.Unlock([]byte(cmd.Passphrase), unlockAfter) return nil, err }
go
func walletPassphrase(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.WalletPassphraseCmd) timeout := time.Second * time.Duration(cmd.Timeout) var unlockAfter <-chan time.Time if timeout != 0 { unlockAfter = time.After(timeout) } err := w.Unlock([]byte(cmd.Passphrase), unlockAfter) return nil, err }
[ "func", "walletPassphrase", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "WalletPassphraseCmd", ")", "\n\n", "timeout", ":=", "time", ".", "Second", "*", "time", ".", "Duration", "(", "cmd", ".", "Timeout", ")", "\n", "var", "unlockAfter", "<-", "chan", "time", ".", "Time", "\n", "if", "timeout", "!=", "0", "{", "unlockAfter", "=", "time", ".", "After", "(", "timeout", ")", "\n", "}", "\n", "err", ":=", "w", ".", "Unlock", "(", "[", "]", "byte", "(", "cmd", ".", "Passphrase", ")", ",", "unlockAfter", ")", "\n", "return", "nil", ",", "err", "\n", "}" ]
// walletPassphrase responds to the walletpassphrase request by unlocking // the wallet. The decryption key is saved in the wallet until timeout // seconds expires, after which the wallet is locked.
[ "walletPassphrase", "responds", "to", "the", "walletpassphrase", "request", "by", "unlocking", "the", "wallet", ".", "The", "decryption", "key", "is", "saved", "in", "the", "wallet", "until", "timeout", "seconds", "expires", "after", "which", "the", "wallet", "is", "locked", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1890-L1900
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
walletPassphraseChange
func walletPassphraseChange(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.WalletPassphraseChangeCmd) err := w.ChangePrivatePassphrase([]byte(cmd.OldPassphrase), []byte(cmd.NewPassphrase)) if waddrmgr.IsError(err, waddrmgr.ErrWrongPassphrase) { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCWalletPassphraseIncorrect, Message: "Incorrect passphrase", } } return nil, err }
go
func walletPassphraseChange(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.WalletPassphraseChangeCmd) err := w.ChangePrivatePassphrase([]byte(cmd.OldPassphrase), []byte(cmd.NewPassphrase)) if waddrmgr.IsError(err, waddrmgr.ErrWrongPassphrase) { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCWalletPassphraseIncorrect, Message: "Incorrect passphrase", } } return nil, err }
[ "func", "walletPassphraseChange", "(", "icmd", "interface", "{", "}", ",", "w", "*", "wallet", ".", "Wallet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ":=", "icmd", ".", "(", "*", "btcjson", ".", "WalletPassphraseChangeCmd", ")", "\n\n", "err", ":=", "w", ".", "ChangePrivatePassphrase", "(", "[", "]", "byte", "(", "cmd", ".", "OldPassphrase", ")", ",", "[", "]", "byte", "(", "cmd", ".", "NewPassphrase", ")", ")", "\n", "if", "waddrmgr", ".", "IsError", "(", "err", ",", "waddrmgr", ".", "ErrWrongPassphrase", ")", "{", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCWalletPassphraseIncorrect", ",", "Message", ":", "\"", "\"", ",", "}", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}" ]
// walletPassphraseChange responds to the walletpassphrasechange request // by unlocking all accounts with the provided old passphrase, and // re-encrypting each private key with an AES key derived from the new // passphrase. // // If the old passphrase is correct and the passphrase is changed, all // wallets will be immediately locked.
[ "walletPassphraseChange", "responds", "to", "the", "walletpassphrasechange", "request", "by", "unlocking", "all", "accounts", "with", "the", "provided", "old", "passphrase", "and", "re", "-", "encrypting", "each", "private", "key", "with", "an", "AES", "key", "derived", "from", "the", "new", "passphrase", ".", "If", "the", "old", "passphrase", "is", "correct", "and", "the", "passphrase", "is", "changed", "all", "wallets", "will", "be", "immediately", "locked", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1909-L1921
train
btcsuite/btcwallet
rpc/legacyrpc/methods.go
decodeHexStr
func decodeHexStr(hexStr string) ([]byte, error) { if len(hexStr)%2 != 0 { hexStr = "0" + hexStr } decoded, err := hex.DecodeString(hexStr) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDecodeHexString, Message: "Hex string decode failed: " + err.Error(), } } return decoded, nil }
go
func decodeHexStr(hexStr string) ([]byte, error) { if len(hexStr)%2 != 0 { hexStr = "0" + hexStr } decoded, err := hex.DecodeString(hexStr) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDecodeHexString, Message: "Hex string decode failed: " + err.Error(), } } return decoded, nil }
[ "func", "decodeHexStr", "(", "hexStr", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "len", "(", "hexStr", ")", "%", "2", "!=", "0", "{", "hexStr", "=", "\"", "\"", "+", "hexStr", "\n", "}", "\n", "decoded", ",", "err", ":=", "hex", ".", "DecodeString", "(", "hexStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCDecodeHexString", ",", "Message", ":", "\"", "\"", "+", "err", ".", "Error", "(", ")", ",", "}", "\n", "}", "\n", "return", "decoded", ",", "nil", "\n", "}" ]
// decodeHexStr decodes the hex encoding of a string, possibly prepending a // leading '0' character if there is an odd number of bytes in the hex string. // This is to prevent an error for an invalid hex string when using an odd // number of bytes when calling hex.Decode.
[ "decodeHexStr", "decodes", "the", "hex", "encoding", "of", "a", "string", "possibly", "prepending", "a", "leading", "0", "character", "if", "there", "is", "an", "odd", "number", "of", "bytes", "in", "the", "hex", "string", ".", "This", "is", "to", "prevent", "an", "error", "for", "an", "invalid", "hex", "string", "when", "using", "an", "odd", "number", "of", "bytes", "when", "calling", "hex", ".", "Decode", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1927-L1939
train
btcsuite/btcwallet
internal/cfgutil/normalization.go
NormalizeAddress
func NormalizeAddress(addr string, defaultPort string) (hostport string, err error) { // If the first SplitHostPort errors because of a missing port and not // for an invalid host, add the port. If the second SplitHostPort // fails, then a port is not missing and the original error should be // returned. host, port, origErr := net.SplitHostPort(addr) if origErr == nil { return net.JoinHostPort(host, port), nil } addr = net.JoinHostPort(addr, defaultPort) _, _, err = net.SplitHostPort(addr) if err != nil { return "", origErr } return addr, nil }
go
func NormalizeAddress(addr string, defaultPort string) (hostport string, err error) { // If the first SplitHostPort errors because of a missing port and not // for an invalid host, add the port. If the second SplitHostPort // fails, then a port is not missing and the original error should be // returned. host, port, origErr := net.SplitHostPort(addr) if origErr == nil { return net.JoinHostPort(host, port), nil } addr = net.JoinHostPort(addr, defaultPort) _, _, err = net.SplitHostPort(addr) if err != nil { return "", origErr } return addr, nil }
[ "func", "NormalizeAddress", "(", "addr", "string", ",", "defaultPort", "string", ")", "(", "hostport", "string", ",", "err", "error", ")", "{", "// If the first SplitHostPort errors because of a missing port and not", "// for an invalid host, add the port. If the second SplitHostPort", "// fails, then a port is not missing and the original error should be", "// returned.", "host", ",", "port", ",", "origErr", ":=", "net", ".", "SplitHostPort", "(", "addr", ")", "\n", "if", "origErr", "==", "nil", "{", "return", "net", ".", "JoinHostPort", "(", "host", ",", "port", ")", ",", "nil", "\n", "}", "\n", "addr", "=", "net", ".", "JoinHostPort", "(", "addr", ",", "defaultPort", ")", "\n", "_", ",", "_", ",", "err", "=", "net", ".", "SplitHostPort", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "origErr", "\n", "}", "\n", "return", "addr", ",", "nil", "\n", "}" ]
// NormalizeAddress returns the normalized form of the address, adding a default // port if necessary. An error is returned if the address, even without a port, // is not valid.
[ "NormalizeAddress", "returns", "the", "normalized", "form", "of", "the", "address", "adding", "a", "default", "port", "if", "necessary", ".", "An", "error", "is", "returned", "if", "the", "address", "even", "without", "a", "port", "is", "not", "valid", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/cfgutil/normalization.go#L12-L27
train
btcsuite/btcwallet
internal/cfgutil/normalization.go
NormalizeAddresses
func NormalizeAddresses(addrs []string, defaultPort string) ([]string, error) { var ( normalized = make([]string, 0, len(addrs)) seenSet = make(map[string]struct{}) ) for _, addr := range addrs { normalizedAddr, err := NormalizeAddress(addr, defaultPort) if err != nil { return nil, err } _, seen := seenSet[normalizedAddr] if !seen { normalized = append(normalized, normalizedAddr) seenSet[normalizedAddr] = struct{}{} } } return normalized, nil }
go
func NormalizeAddresses(addrs []string, defaultPort string) ([]string, error) { var ( normalized = make([]string, 0, len(addrs)) seenSet = make(map[string]struct{}) ) for _, addr := range addrs { normalizedAddr, err := NormalizeAddress(addr, defaultPort) if err != nil { return nil, err } _, seen := seenSet[normalizedAddr] if !seen { normalized = append(normalized, normalizedAddr) seenSet[normalizedAddr] = struct{}{} } } return normalized, nil }
[ "func", "NormalizeAddresses", "(", "addrs", "[", "]", "string", ",", "defaultPort", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "(", "normalized", "=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "addrs", ")", ")", "\n", "seenSet", "=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", ")", "\n\n", "for", "_", ",", "addr", ":=", "range", "addrs", "{", "normalizedAddr", ",", "err", ":=", "NormalizeAddress", "(", "addr", ",", "defaultPort", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "_", ",", "seen", ":=", "seenSet", "[", "normalizedAddr", "]", "\n", "if", "!", "seen", "{", "normalized", "=", "append", "(", "normalized", ",", "normalizedAddr", ")", "\n", "seenSet", "[", "normalizedAddr", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n\n", "return", "normalized", ",", "nil", "\n", "}" ]
// NormalizeAddresses returns a new slice with all the passed peer addresses // normalized with the given default port, and all duplicates removed.
[ "NormalizeAddresses", "returns", "a", "new", "slice", "with", "all", "the", "passed", "peer", "addresses", "normalized", "with", "the", "given", "default", "port", "and", "all", "duplicates", "removed", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/cfgutil/normalization.go#L31-L50
train
btcsuite/btcwallet
chain/bitcoind_client.go
GetBestBlock
func (c *BitcoindClient) GetBestBlock() (*chainhash.Hash, int32, error) { bcinfo, err := c.chainConn.client.GetBlockChainInfo() if err != nil { return nil, 0, err } hash, err := chainhash.NewHashFromStr(bcinfo.BestBlockHash) if err != nil { return nil, 0, err } return hash, bcinfo.Blocks, nil }
go
func (c *BitcoindClient) GetBestBlock() (*chainhash.Hash, int32, error) { bcinfo, err := c.chainConn.client.GetBlockChainInfo() if err != nil { return nil, 0, err } hash, err := chainhash.NewHashFromStr(bcinfo.BestBlockHash) if err != nil { return nil, 0, err } return hash, bcinfo.Blocks, nil }
[ "func", "(", "c", "*", "BitcoindClient", ")", "GetBestBlock", "(", ")", "(", "*", "chainhash", ".", "Hash", ",", "int32", ",", "error", ")", "{", "bcinfo", ",", "err", ":=", "c", ".", "chainConn", ".", "client", ".", "GetBlockChainInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n\n", "hash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "bcinfo", ".", "BestBlockHash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n\n", "return", "hash", ",", "bcinfo", ".", "Blocks", ",", "nil", "\n", "}" ]
// GetBestBlock returns the highest block known to bitcoind.
[ "GetBestBlock", "returns", "the", "highest", "block", "known", "to", "bitcoind", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L121-L133
train
btcsuite/btcwallet
chain/bitcoind_client.go
GetBlockHeight
func (c *BitcoindClient) GetBlockHeight(hash *chainhash.Hash) (int32, error) { header, err := c.chainConn.client.GetBlockHeaderVerbose(hash) if err != nil { return 0, err } return header.Height, nil }
go
func (c *BitcoindClient) GetBlockHeight(hash *chainhash.Hash) (int32, error) { header, err := c.chainConn.client.GetBlockHeaderVerbose(hash) if err != nil { return 0, err } return header.Height, nil }
[ "func", "(", "c", "*", "BitcoindClient", ")", "GetBlockHeight", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "int32", ",", "error", ")", "{", "header", ",", "err", ":=", "c", ".", "chainConn", ".", "client", ".", "GetBlockHeaderVerbose", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "header", ".", "Height", ",", "nil", "\n", "}" ]
// GetBlockHeight returns the height for the hash, if known, or returns an // error.
[ "GetBlockHeight", "returns", "the", "height", "for", "the", "hash", "if", "known", "or", "returns", "an", "error", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L137-L144
train
btcsuite/btcwallet
chain/bitcoind_client.go
GetBlock
func (c *BitcoindClient) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error) { return c.chainConn.client.GetBlock(hash) }
go
func (c *BitcoindClient) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error) { return c.chainConn.client.GetBlock(hash) }
[ "func", "(", "c", "*", "BitcoindClient", ")", "GetBlock", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "wire", ".", "MsgBlock", ",", "error", ")", "{", "return", "c", ".", "chainConn", ".", "client", ".", "GetBlock", "(", "hash", ")", "\n", "}" ]
// GetBlock returns a block from the hash.
[ "GetBlock", "returns", "a", "block", "from", "the", "hash", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L147-L149
train
btcsuite/btcwallet
chain/bitcoind_client.go
GetBlockVerbose
func (c *BitcoindClient) GetBlockVerbose( hash *chainhash.Hash) (*btcjson.GetBlockVerboseResult, error) { return c.chainConn.client.GetBlockVerbose(hash) }
go
func (c *BitcoindClient) GetBlockVerbose( hash *chainhash.Hash) (*btcjson.GetBlockVerboseResult, error) { return c.chainConn.client.GetBlockVerbose(hash) }
[ "func", "(", "c", "*", "BitcoindClient", ")", "GetBlockVerbose", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "btcjson", ".", "GetBlockVerboseResult", ",", "error", ")", "{", "return", "c", ".", "chainConn", ".", "client", ".", "GetBlockVerbose", "(", "hash", ")", "\n", "}" ]
// GetBlockVerbose returns a verbose block from the hash.
[ "GetBlockVerbose", "returns", "a", "verbose", "block", "from", "the", "hash", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L152-L156
train
btcsuite/btcwallet
chain/bitcoind_client.go
GetBlockHash
func (c *BitcoindClient) GetBlockHash(height int64) (*chainhash.Hash, error) { return c.chainConn.client.GetBlockHash(height) }
go
func (c *BitcoindClient) GetBlockHash(height int64) (*chainhash.Hash, error) { return c.chainConn.client.GetBlockHash(height) }
[ "func", "(", "c", "*", "BitcoindClient", ")", "GetBlockHash", "(", "height", "int64", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "return", "c", ".", "chainConn", ".", "client", ".", "GetBlockHash", "(", "height", ")", "\n", "}" ]
// GetBlockHash returns a block hash from the height.
[ "GetBlockHash", "returns", "a", "block", "hash", "from", "the", "height", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L159-L161
train
btcsuite/btcwallet
chain/bitcoind_client.go
GetBlockHeader
func (c *BitcoindClient) GetBlockHeader( hash *chainhash.Hash) (*wire.BlockHeader, error) { return c.chainConn.client.GetBlockHeader(hash) }
go
func (c *BitcoindClient) GetBlockHeader( hash *chainhash.Hash) (*wire.BlockHeader, error) { return c.chainConn.client.GetBlockHeader(hash) }
[ "func", "(", "c", "*", "BitcoindClient", ")", "GetBlockHeader", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "wire", ".", "BlockHeader", ",", "error", ")", "{", "return", "c", ".", "chainConn", ".", "client", ".", "GetBlockHeader", "(", "hash", ")", "\n", "}" ]
// GetBlockHeader returns a block header from the hash.
[ "GetBlockHeader", "returns", "a", "block", "header", "from", "the", "hash", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L164-L168
train
btcsuite/btcwallet
chain/bitcoind_client.go
GetBlockHeaderVerbose
func (c *BitcoindClient) GetBlockHeaderVerbose( hash *chainhash.Hash) (*btcjson.GetBlockHeaderVerboseResult, error) { return c.chainConn.client.GetBlockHeaderVerbose(hash) }
go
func (c *BitcoindClient) GetBlockHeaderVerbose( hash *chainhash.Hash) (*btcjson.GetBlockHeaderVerboseResult, error) { return c.chainConn.client.GetBlockHeaderVerbose(hash) }
[ "func", "(", "c", "*", "BitcoindClient", ")", "GetBlockHeaderVerbose", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "btcjson", ".", "GetBlockHeaderVerboseResult", ",", "error", ")", "{", "return", "c", ".", "chainConn", ".", "client", ".", "GetBlockHeaderVerbose", "(", "hash", ")", "\n", "}" ]
// GetBlockHeaderVerbose returns a block header from the hash.
[ "GetBlockHeaderVerbose", "returns", "a", "block", "header", "from", "the", "hash", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L171-L175
train
btcsuite/btcwallet
chain/bitcoind_client.go
GetRawTransactionVerbose
func (c *BitcoindClient) GetRawTransactionVerbose( hash *chainhash.Hash) (*btcjson.TxRawResult, error) { return c.chainConn.client.GetRawTransactionVerbose(hash) }
go
func (c *BitcoindClient) GetRawTransactionVerbose( hash *chainhash.Hash) (*btcjson.TxRawResult, error) { return c.chainConn.client.GetRawTransactionVerbose(hash) }
[ "func", "(", "c", "*", "BitcoindClient", ")", "GetRawTransactionVerbose", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "btcjson", ".", "TxRawResult", ",", "error", ")", "{", "return", "c", ".", "chainConn", ".", "client", ".", "GetRawTransactionVerbose", "(", "hash", ")", "\n", "}" ]
// GetRawTransactionVerbose returns a transaction from the tx hash.
[ "GetRawTransactionVerbose", "returns", "a", "transaction", "from", "the", "tx", "hash", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L178-L182
train
btcsuite/btcwallet
chain/bitcoind_client.go
GetTxOut
func (c *BitcoindClient) GetTxOut(txHash *chainhash.Hash, index uint32, mempool bool) (*btcjson.GetTxOutResult, error) { return c.chainConn.client.GetTxOut(txHash, index, mempool) }
go
func (c *BitcoindClient) GetTxOut(txHash *chainhash.Hash, index uint32, mempool bool) (*btcjson.GetTxOutResult, error) { return c.chainConn.client.GetTxOut(txHash, index, mempool) }
[ "func", "(", "c", "*", "BitcoindClient", ")", "GetTxOut", "(", "txHash", "*", "chainhash", ".", "Hash", ",", "index", "uint32", ",", "mempool", "bool", ")", "(", "*", "btcjson", ".", "GetTxOutResult", ",", "error", ")", "{", "return", "c", ".", "chainConn", ".", "client", ".", "GetTxOut", "(", "txHash", ",", "index", ",", "mempool", ")", "\n", "}" ]
// GetTxOut returns a txout from the outpoint info provided.
[ "GetTxOut", "returns", "a", "txout", "from", "the", "outpoint", "info", "provided", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L185-L189
train
btcsuite/btcwallet
chain/bitcoind_client.go
SendRawTransaction
func (c *BitcoindClient) SendRawTransaction(tx *wire.MsgTx, allowHighFees bool) (*chainhash.Hash, error) { return c.chainConn.client.SendRawTransaction(tx, allowHighFees) }
go
func (c *BitcoindClient) SendRawTransaction(tx *wire.MsgTx, allowHighFees bool) (*chainhash.Hash, error) { return c.chainConn.client.SendRawTransaction(tx, allowHighFees) }
[ "func", "(", "c", "*", "BitcoindClient", ")", "SendRawTransaction", "(", "tx", "*", "wire", ".", "MsgTx", ",", "allowHighFees", "bool", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "return", "c", ".", "chainConn", ".", "client", ".", "SendRawTransaction", "(", "tx", ",", "allowHighFees", ")", "\n", "}" ]
// SendRawTransaction sends a raw transaction via bitcoind.
[ "SendRawTransaction", "sends", "a", "raw", "transaction", "via", "bitcoind", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L192-L196
train
btcsuite/btcwallet
chain/bitcoind_client.go
NotifySpent
func (c *BitcoindClient) NotifySpent(outPoints []*wire.OutPoint) error { c.NotifyBlocks() select { case c.rescanUpdate <- outPoints: case <-c.quit: return ErrBitcoindClientShuttingDown } return nil }
go
func (c *BitcoindClient) NotifySpent(outPoints []*wire.OutPoint) error { c.NotifyBlocks() select { case c.rescanUpdate <- outPoints: case <-c.quit: return ErrBitcoindClientShuttingDown } return nil }
[ "func", "(", "c", "*", "BitcoindClient", ")", "NotifySpent", "(", "outPoints", "[", "]", "*", "wire", ".", "OutPoint", ")", "error", "{", "c", ".", "NotifyBlocks", "(", ")", "\n\n", "select", "{", "case", "c", ".", "rescanUpdate", "<-", "outPoints", ":", "case", "<-", "c", ".", "quit", ":", "return", "ErrBitcoindClientShuttingDown", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// NotifySpent allows the chain backend to notify the caller whenever a // transaction spends any of the given outpoints.
[ "NotifySpent", "allows", "the", "chain", "backend", "to", "notify", "the", "caller", "whenever", "a", "transaction", "spends", "any", "of", "the", "given", "outpoints", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L223-L233
train
btcsuite/btcwallet
chain/bitcoind_client.go
NotifyTx
func (c *BitcoindClient) NotifyTx(txids []chainhash.Hash) error { c.NotifyBlocks() select { case c.rescanUpdate <- txids: case <-c.quit: return ErrBitcoindClientShuttingDown } return nil }
go
func (c *BitcoindClient) NotifyTx(txids []chainhash.Hash) error { c.NotifyBlocks() select { case c.rescanUpdate <- txids: case <-c.quit: return ErrBitcoindClientShuttingDown } return nil }
[ "func", "(", "c", "*", "BitcoindClient", ")", "NotifyTx", "(", "txids", "[", "]", "chainhash", ".", "Hash", ")", "error", "{", "c", ".", "NotifyBlocks", "(", ")", "\n\n", "select", "{", "case", "c", ".", "rescanUpdate", "<-", "txids", ":", "case", "<-", "c", ".", "quit", ":", "return", "ErrBitcoindClientShuttingDown", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// NotifyTx allows the chain backend to notify the caller whenever any of the // given transactions confirm within the chain.
[ "NotifyTx", "allows", "the", "chain", "backend", "to", "notify", "the", "caller", "whenever", "any", "of", "the", "given", "transactions", "confirm", "within", "the", "chain", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L237-L247
train
btcsuite/btcwallet
chain/bitcoind_client.go
Rescan
func (c *BitcoindClient) Rescan(blockHash *chainhash.Hash, addresses []btcutil.Address, outPoints map[wire.OutPoint]btcutil.Address) error { // A block hash is required to use as the starting point of the rescan. if blockHash == nil { return errors.New("rescan requires a starting block hash") } // We'll then update our filters with the given outpoints and addresses. select { case c.rescanUpdate <- addresses: case <-c.quit: return ErrBitcoindClientShuttingDown } select { case c.rescanUpdate <- outPoints: case <-c.quit: return ErrBitcoindClientShuttingDown } // Once the filters have been updated, we can begin the rescan. select { case c.rescanUpdate <- *blockHash: case <-c.quit: return ErrBitcoindClientShuttingDown } return nil }
go
func (c *BitcoindClient) Rescan(blockHash *chainhash.Hash, addresses []btcutil.Address, outPoints map[wire.OutPoint]btcutil.Address) error { // A block hash is required to use as the starting point of the rescan. if blockHash == nil { return errors.New("rescan requires a starting block hash") } // We'll then update our filters with the given outpoints and addresses. select { case c.rescanUpdate <- addresses: case <-c.quit: return ErrBitcoindClientShuttingDown } select { case c.rescanUpdate <- outPoints: case <-c.quit: return ErrBitcoindClientShuttingDown } // Once the filters have been updated, we can begin the rescan. select { case c.rescanUpdate <- *blockHash: case <-c.quit: return ErrBitcoindClientShuttingDown } return nil }
[ "func", "(", "c", "*", "BitcoindClient", ")", "Rescan", "(", "blockHash", "*", "chainhash", ".", "Hash", ",", "addresses", "[", "]", "btcutil", ".", "Address", ",", "outPoints", "map", "[", "wire", ".", "OutPoint", "]", "btcutil", ".", "Address", ")", "error", "{", "// A block hash is required to use as the starting point of the rescan.", "if", "blockHash", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// We'll then update our filters with the given outpoints and addresses.", "select", "{", "case", "c", ".", "rescanUpdate", "<-", "addresses", ":", "case", "<-", "c", ".", "quit", ":", "return", "ErrBitcoindClientShuttingDown", "\n", "}", "\n\n", "select", "{", "case", "c", ".", "rescanUpdate", "<-", "outPoints", ":", "case", "<-", "c", ".", "quit", ":", "return", "ErrBitcoindClientShuttingDown", "\n", "}", "\n\n", "// Once the filters have been updated, we can begin the rescan.", "select", "{", "case", "c", ".", "rescanUpdate", "<-", "*", "blockHash", ":", "case", "<-", "c", ".", "quit", ":", "return", "ErrBitcoindClientShuttingDown", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Rescan rescans from the block with the given hash until the current block, // after adding the passed addresses and outpoints to the client's watch list.
[ "Rescan", "rescans", "from", "the", "block", "with", "the", "given", "hash", "until", "the", "current", "block", "after", "adding", "the", "passed", "addresses", "and", "outpoints", "to", "the", "client", "s", "watch", "list", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L360-L389
train
btcsuite/btcwallet
chain/bitcoind_client.go
onBlockConnected
func (c *BitcoindClient) onBlockConnected(hash *chainhash.Hash, height int32, timestamp time.Time) { if c.shouldNotifyBlocks() { select { case c.notificationQueue.ChanIn() <- BlockConnected{ Block: wtxmgr.Block{ Hash: *hash, Height: height, }, Time: timestamp, }: case <-c.quit: } } }
go
func (c *BitcoindClient) onBlockConnected(hash *chainhash.Hash, height int32, timestamp time.Time) { if c.shouldNotifyBlocks() { select { case c.notificationQueue.ChanIn() <- BlockConnected{ Block: wtxmgr.Block{ Hash: *hash, Height: height, }, Time: timestamp, }: case <-c.quit: } } }
[ "func", "(", "c", "*", "BitcoindClient", ")", "onBlockConnected", "(", "hash", "*", "chainhash", ".", "Hash", ",", "height", "int32", ",", "timestamp", "time", ".", "Time", ")", "{", "if", "c", ".", "shouldNotifyBlocks", "(", ")", "{", "select", "{", "case", "c", ".", "notificationQueue", ".", "ChanIn", "(", ")", "<-", "BlockConnected", "{", "Block", ":", "wtxmgr", ".", "Block", "{", "Hash", ":", "*", "hash", ",", "Height", ":", "height", ",", "}", ",", "Time", ":", "timestamp", ",", "}", ":", "case", "<-", "c", ".", "quit", ":", "}", "\n", "}", "\n", "}" ]
// onBlockConnected is a callback that's executed whenever a new block has been // detected. This will queue a BlockConnected notification to the caller.
[ "onBlockConnected", "is", "a", "callback", "that", "s", "executed", "whenever", "a", "new", "block", "has", "been", "detected", ".", "This", "will", "queue", "a", "BlockConnected", "notification", "to", "the", "caller", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L623-L638
train
btcsuite/btcwallet
chain/bitcoind_client.go
onFilteredBlockConnected
func (c *BitcoindClient) onFilteredBlockConnected(height int32, header *wire.BlockHeader, relevantTxs []*wtxmgr.TxRecord) { if c.shouldNotifyBlocks() { select { case c.notificationQueue.ChanIn() <- FilteredBlockConnected{ Block: &wtxmgr.BlockMeta{ Block: wtxmgr.Block{ Hash: header.BlockHash(), Height: height, }, Time: header.Timestamp, }, RelevantTxs: relevantTxs, }: case <-c.quit: } } }
go
func (c *BitcoindClient) onFilteredBlockConnected(height int32, header *wire.BlockHeader, relevantTxs []*wtxmgr.TxRecord) { if c.shouldNotifyBlocks() { select { case c.notificationQueue.ChanIn() <- FilteredBlockConnected{ Block: &wtxmgr.BlockMeta{ Block: wtxmgr.Block{ Hash: header.BlockHash(), Height: height, }, Time: header.Timestamp, }, RelevantTxs: relevantTxs, }: case <-c.quit: } } }
[ "func", "(", "c", "*", "BitcoindClient", ")", "onFilteredBlockConnected", "(", "height", "int32", ",", "header", "*", "wire", ".", "BlockHeader", ",", "relevantTxs", "[", "]", "*", "wtxmgr", ".", "TxRecord", ")", "{", "if", "c", ".", "shouldNotifyBlocks", "(", ")", "{", "select", "{", "case", "c", ".", "notificationQueue", ".", "ChanIn", "(", ")", "<-", "FilteredBlockConnected", "{", "Block", ":", "&", "wtxmgr", ".", "BlockMeta", "{", "Block", ":", "wtxmgr", ".", "Block", "{", "Hash", ":", "header", ".", "BlockHash", "(", ")", ",", "Height", ":", "height", ",", "}", ",", "Time", ":", "header", ".", "Timestamp", ",", "}", ",", "RelevantTxs", ":", "relevantTxs", ",", "}", ":", "case", "<-", "c", ".", "quit", ":", "}", "\n", "}", "\n", "}" ]
// onFilteredBlockConnected is an alternative callback that's executed whenever // a new block has been detected. It serves the same purpose as // onBlockConnected, but it also includes a list of the relevant transactions // found within the block being connected. This will queue a // FilteredBlockConnected notification to the caller.
[ "onFilteredBlockConnected", "is", "an", "alternative", "callback", "that", "s", "executed", "whenever", "a", "new", "block", "has", "been", "detected", ".", "It", "serves", "the", "same", "purpose", "as", "onBlockConnected", "but", "it", "also", "includes", "a", "list", "of", "the", "relevant", "transactions", "found", "within", "the", "block", "being", "connected", ".", "This", "will", "queue", "a", "FilteredBlockConnected", "notification", "to", "the", "caller", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L645-L663
train
btcsuite/btcwallet
chain/bitcoind_client.go
onRelevantTx
func (c *BitcoindClient) onRelevantTx(tx *wtxmgr.TxRecord, blockDetails *btcjson.BlockDetails) { block, err := parseBlock(blockDetails) if err != nil { log.Errorf("Unable to send onRelevantTx notification, failed "+ "parse block: %v", err) return } select { case c.notificationQueue.ChanIn() <- RelevantTx{ TxRecord: tx, Block: block, }: case <-c.quit: } }
go
func (c *BitcoindClient) onRelevantTx(tx *wtxmgr.TxRecord, blockDetails *btcjson.BlockDetails) { block, err := parseBlock(blockDetails) if err != nil { log.Errorf("Unable to send onRelevantTx notification, failed "+ "parse block: %v", err) return } select { case c.notificationQueue.ChanIn() <- RelevantTx{ TxRecord: tx, Block: block, }: case <-c.quit: } }
[ "func", "(", "c", "*", "BitcoindClient", ")", "onRelevantTx", "(", "tx", "*", "wtxmgr", ".", "TxRecord", ",", "blockDetails", "*", "btcjson", ".", "BlockDetails", ")", "{", "block", ",", "err", ":=", "parseBlock", "(", "blockDetails", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "select", "{", "case", "c", ".", "notificationQueue", ".", "ChanIn", "(", ")", "<-", "RelevantTx", "{", "TxRecord", ":", "tx", ",", "Block", ":", "block", ",", "}", ":", "case", "<-", "c", ".", "quit", ":", "}", "\n", "}" ]
// onRelevantTx is a callback that's executed whenever a transaction is relevant // to the caller. This means that the transaction matched a specific item in the // client's different filters. This will queue a RelevantTx notification to the // caller.
[ "onRelevantTx", "is", "a", "callback", "that", "s", "executed", "whenever", "a", "transaction", "is", "relevant", "to", "the", "caller", ".", "This", "means", "that", "the", "transaction", "matched", "a", "specific", "item", "in", "the", "client", "s", "different", "filters", ".", "This", "will", "queue", "a", "RelevantTx", "notification", "to", "the", "caller", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L689-L706
train
btcsuite/btcwallet
chain/bitcoind_client.go
onRescanProgress
func (c *BitcoindClient) onRescanProgress(hash *chainhash.Hash, height int32, timestamp time.Time) { select { case c.notificationQueue.ChanIn() <- &RescanProgress{ Hash: hash, Height: height, Time: timestamp, }: case <-c.quit: } }
go
func (c *BitcoindClient) onRescanProgress(hash *chainhash.Hash, height int32, timestamp time.Time) { select { case c.notificationQueue.ChanIn() <- &RescanProgress{ Hash: hash, Height: height, Time: timestamp, }: case <-c.quit: } }
[ "func", "(", "c", "*", "BitcoindClient", ")", "onRescanProgress", "(", "hash", "*", "chainhash", ".", "Hash", ",", "height", "int32", ",", "timestamp", "time", ".", "Time", ")", "{", "select", "{", "case", "c", ".", "notificationQueue", ".", "ChanIn", "(", ")", "<-", "&", "RescanProgress", "{", "Hash", ":", "hash", ",", "Height", ":", "height", ",", "Time", ":", "timestamp", ",", "}", ":", "case", "<-", "c", ".", "quit", ":", "}", "\n", "}" ]
// onRescanProgress is a callback that's executed whenever a rescan is in // progress. This will queue a RescanProgress notification to the caller with // the current rescan progress details.
[ "onRescanProgress", "is", "a", "callback", "that", "s", "executed", "whenever", "a", "rescan", "is", "in", "progress", ".", "This", "will", "queue", "a", "RescanProgress", "notification", "to", "the", "caller", "with", "the", "current", "rescan", "progress", "details", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L711-L722
train
btcsuite/btcwallet
chain/bitcoind_client.go
onRescanFinished
func (c *BitcoindClient) onRescanFinished(hash *chainhash.Hash, height int32, timestamp time.Time) { log.Infof("Rescan finished at %d (%s)", height, hash) select { case c.notificationQueue.ChanIn() <- &RescanFinished{ Hash: hash, Height: height, Time: timestamp, }: case <-c.quit: } }
go
func (c *BitcoindClient) onRescanFinished(hash *chainhash.Hash, height int32, timestamp time.Time) { log.Infof("Rescan finished at %d (%s)", height, hash) select { case c.notificationQueue.ChanIn() <- &RescanFinished{ Hash: hash, Height: height, Time: timestamp, }: case <-c.quit: } }
[ "func", "(", "c", "*", "BitcoindClient", ")", "onRescanFinished", "(", "hash", "*", "chainhash", ".", "Hash", ",", "height", "int32", ",", "timestamp", "time", ".", "Time", ")", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "height", ",", "hash", ")", "\n\n", "select", "{", "case", "c", ".", "notificationQueue", ".", "ChanIn", "(", ")", "<-", "&", "RescanFinished", "{", "Hash", ":", "hash", ",", "Height", ":", "height", ",", "Time", ":", "timestamp", ",", "}", ":", "case", "<-", "c", ".", "quit", ":", "}", "\n", "}" ]
// onRescanFinished is a callback that's executed whenever a rescan has // finished. This will queue a RescanFinished notification to the caller with // the details of the last block in the range of the rescan.
[ "onRescanFinished", "is", "a", "callback", "that", "s", "executed", "whenever", "a", "rescan", "has", "finished", ".", "This", "will", "queue", "a", "RescanFinished", "notification", "to", "the", "caller", "with", "the", "details", "of", "the", "last", "block", "in", "the", "range", "of", "the", "rescan", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L727-L740
train
btcsuite/btcwallet
chain/bitcoind_client.go
reorg
func (c *BitcoindClient) reorg(currentBlock waddrmgr.BlockStamp, reorgBlock *wire.MsgBlock) error { log.Debugf("Possible reorg at block %s", reorgBlock.BlockHash()) // Retrieve the best known height based on the block which caused the // reorg. This way, we can preserve the chain of blocks we need to // retrieve. bestHash := reorgBlock.BlockHash() bestHeight, err := c.GetBlockHeight(&bestHash) if err != nil { return err } if bestHeight < currentBlock.Height { log.Debug("Detected multiple reorgs") return nil } // We'll now keep track of all the blocks known to the *chain*, starting // from the best block known to us until the best block in the chain. // This will let us fast-forward despite any future reorgs. blocksToNotify := list.New() blocksToNotify.PushFront(reorgBlock) previousBlock := reorgBlock.Header.PrevBlock for i := bestHeight - 1; i >= currentBlock.Height; i-- { block, err := c.GetBlock(&previousBlock) if err != nil { return err } blocksToNotify.PushFront(block) previousBlock = block.Header.PrevBlock } // Rewind back to the last common ancestor block using the previous // block hash from each header to avoid any race conditions. If we // encounter more reorgs, they'll be queued and we'll repeat the cycle. // // We'll start by retrieving the header to the best block known to us. currentHeader, err := c.GetBlockHeader(&currentBlock.Hash) if err != nil { return err } // Then, we'll walk backwards in the chain until we find our common // ancestor. for previousBlock != currentHeader.PrevBlock { // Since the previous hashes don't match, the current block has // been reorged out of the chain, so we should send a // BlockDisconnected notification for it. log.Debugf("Disconnecting block %d (%v)", currentBlock.Height, currentBlock.Hash) c.onBlockDisconnected( &currentBlock.Hash, currentBlock.Height, currentBlock.Timestamp, ) // Our current block should now reflect the previous one to // continue the common ancestor search. currentHeader, err = c.GetBlockHeader(&currentHeader.PrevBlock) if err != nil { return err } currentBlock.Height-- currentBlock.Hash = currentHeader.PrevBlock currentBlock.Timestamp = currentHeader.Timestamp // Store the correct block in our list in order to notify it // once we've found our common ancestor. block, err := c.GetBlock(&previousBlock) if err != nil { return err } blocksToNotify.PushFront(block) previousBlock = block.Header.PrevBlock } // Disconnect the last block from the old chain. Since the previous // block remains the same between the old and new chains, the tip will // now be the last common ancestor. log.Debugf("Disconnecting block %d (%v)", currentBlock.Height, currentBlock.Hash) c.onBlockDisconnected( &currentBlock.Hash, currentBlock.Height, currentHeader.Timestamp, ) currentBlock.Height-- // Now we fast-forward to the new block, notifying along the way. for blocksToNotify.Front() != nil { nextBlock := blocksToNotify.Front().Value.(*wire.MsgBlock) nextHeight := currentBlock.Height + 1 nextHash := nextBlock.BlockHash() nextHeader, err := c.GetBlockHeader(&nextHash) if err != nil { return err } _, err = c.filterBlock(nextBlock, nextHeight, true) if err != nil { return err } currentBlock.Height = nextHeight currentBlock.Hash = nextHash currentBlock.Timestamp = nextHeader.Timestamp blocksToNotify.Remove(blocksToNotify.Front()) } c.bestBlockMtx.Lock() c.bestBlock = currentBlock c.bestBlockMtx.Unlock() return nil }
go
func (c *BitcoindClient) reorg(currentBlock waddrmgr.BlockStamp, reorgBlock *wire.MsgBlock) error { log.Debugf("Possible reorg at block %s", reorgBlock.BlockHash()) // Retrieve the best known height based on the block which caused the // reorg. This way, we can preserve the chain of blocks we need to // retrieve. bestHash := reorgBlock.BlockHash() bestHeight, err := c.GetBlockHeight(&bestHash) if err != nil { return err } if bestHeight < currentBlock.Height { log.Debug("Detected multiple reorgs") return nil } // We'll now keep track of all the blocks known to the *chain*, starting // from the best block known to us until the best block in the chain. // This will let us fast-forward despite any future reorgs. blocksToNotify := list.New() blocksToNotify.PushFront(reorgBlock) previousBlock := reorgBlock.Header.PrevBlock for i := bestHeight - 1; i >= currentBlock.Height; i-- { block, err := c.GetBlock(&previousBlock) if err != nil { return err } blocksToNotify.PushFront(block) previousBlock = block.Header.PrevBlock } // Rewind back to the last common ancestor block using the previous // block hash from each header to avoid any race conditions. If we // encounter more reorgs, they'll be queued and we'll repeat the cycle. // // We'll start by retrieving the header to the best block known to us. currentHeader, err := c.GetBlockHeader(&currentBlock.Hash) if err != nil { return err } // Then, we'll walk backwards in the chain until we find our common // ancestor. for previousBlock != currentHeader.PrevBlock { // Since the previous hashes don't match, the current block has // been reorged out of the chain, so we should send a // BlockDisconnected notification for it. log.Debugf("Disconnecting block %d (%v)", currentBlock.Height, currentBlock.Hash) c.onBlockDisconnected( &currentBlock.Hash, currentBlock.Height, currentBlock.Timestamp, ) // Our current block should now reflect the previous one to // continue the common ancestor search. currentHeader, err = c.GetBlockHeader(&currentHeader.PrevBlock) if err != nil { return err } currentBlock.Height-- currentBlock.Hash = currentHeader.PrevBlock currentBlock.Timestamp = currentHeader.Timestamp // Store the correct block in our list in order to notify it // once we've found our common ancestor. block, err := c.GetBlock(&previousBlock) if err != nil { return err } blocksToNotify.PushFront(block) previousBlock = block.Header.PrevBlock } // Disconnect the last block from the old chain. Since the previous // block remains the same between the old and new chains, the tip will // now be the last common ancestor. log.Debugf("Disconnecting block %d (%v)", currentBlock.Height, currentBlock.Hash) c.onBlockDisconnected( &currentBlock.Hash, currentBlock.Height, currentHeader.Timestamp, ) currentBlock.Height-- // Now we fast-forward to the new block, notifying along the way. for blocksToNotify.Front() != nil { nextBlock := blocksToNotify.Front().Value.(*wire.MsgBlock) nextHeight := currentBlock.Height + 1 nextHash := nextBlock.BlockHash() nextHeader, err := c.GetBlockHeader(&nextHash) if err != nil { return err } _, err = c.filterBlock(nextBlock, nextHeight, true) if err != nil { return err } currentBlock.Height = nextHeight currentBlock.Hash = nextHash currentBlock.Timestamp = nextHeader.Timestamp blocksToNotify.Remove(blocksToNotify.Front()) } c.bestBlockMtx.Lock() c.bestBlock = currentBlock c.bestBlockMtx.Unlock() return nil }
[ "func", "(", "c", "*", "BitcoindClient", ")", "reorg", "(", "currentBlock", "waddrmgr", ".", "BlockStamp", ",", "reorgBlock", "*", "wire", ".", "MsgBlock", ")", "error", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "reorgBlock", ".", "BlockHash", "(", ")", ")", "\n\n", "// Retrieve the best known height based on the block which caused the", "// reorg. This way, we can preserve the chain of blocks we need to", "// retrieve.", "bestHash", ":=", "reorgBlock", ".", "BlockHash", "(", ")", "\n", "bestHeight", ",", "err", ":=", "c", ".", "GetBlockHeight", "(", "&", "bestHash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "bestHeight", "<", "currentBlock", ".", "Height", "{", "log", ".", "Debug", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// We'll now keep track of all the blocks known to the *chain*, starting", "// from the best block known to us until the best block in the chain.", "// This will let us fast-forward despite any future reorgs.", "blocksToNotify", ":=", "list", ".", "New", "(", ")", "\n", "blocksToNotify", ".", "PushFront", "(", "reorgBlock", ")", "\n", "previousBlock", ":=", "reorgBlock", ".", "Header", ".", "PrevBlock", "\n", "for", "i", ":=", "bestHeight", "-", "1", ";", "i", ">=", "currentBlock", ".", "Height", ";", "i", "--", "{", "block", ",", "err", ":=", "c", ".", "GetBlock", "(", "&", "previousBlock", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "blocksToNotify", ".", "PushFront", "(", "block", ")", "\n", "previousBlock", "=", "block", ".", "Header", ".", "PrevBlock", "\n", "}", "\n\n", "// Rewind back to the last common ancestor block using the previous", "// block hash from each header to avoid any race conditions. If we", "// encounter more reorgs, they'll be queued and we'll repeat the cycle.", "//", "// We'll start by retrieving the header to the best block known to us.", "currentHeader", ",", "err", ":=", "c", ".", "GetBlockHeader", "(", "&", "currentBlock", ".", "Hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Then, we'll walk backwards in the chain until we find our common", "// ancestor.", "for", "previousBlock", "!=", "currentHeader", ".", "PrevBlock", "{", "// Since the previous hashes don't match, the current block has", "// been reorged out of the chain, so we should send a", "// BlockDisconnected notification for it.", "log", ".", "Debugf", "(", "\"", "\"", ",", "currentBlock", ".", "Height", ",", "currentBlock", ".", "Hash", ")", "\n\n", "c", ".", "onBlockDisconnected", "(", "&", "currentBlock", ".", "Hash", ",", "currentBlock", ".", "Height", ",", "currentBlock", ".", "Timestamp", ",", ")", "\n\n", "// Our current block should now reflect the previous one to", "// continue the common ancestor search.", "currentHeader", ",", "err", "=", "c", ".", "GetBlockHeader", "(", "&", "currentHeader", ".", "PrevBlock", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "currentBlock", ".", "Height", "--", "\n", "currentBlock", ".", "Hash", "=", "currentHeader", ".", "PrevBlock", "\n", "currentBlock", ".", "Timestamp", "=", "currentHeader", ".", "Timestamp", "\n\n", "// Store the correct block in our list in order to notify it", "// once we've found our common ancestor.", "block", ",", "err", ":=", "c", ".", "GetBlock", "(", "&", "previousBlock", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "blocksToNotify", ".", "PushFront", "(", "block", ")", "\n", "previousBlock", "=", "block", ".", "Header", ".", "PrevBlock", "\n", "}", "\n\n", "// Disconnect the last block from the old chain. Since the previous", "// block remains the same between the old and new chains, the tip will", "// now be the last common ancestor.", "log", ".", "Debugf", "(", "\"", "\"", ",", "currentBlock", ".", "Height", ",", "currentBlock", ".", "Hash", ")", "\n\n", "c", ".", "onBlockDisconnected", "(", "&", "currentBlock", ".", "Hash", ",", "currentBlock", ".", "Height", ",", "currentHeader", ".", "Timestamp", ",", ")", "\n\n", "currentBlock", ".", "Height", "--", "\n\n", "// Now we fast-forward to the new block, notifying along the way.", "for", "blocksToNotify", ".", "Front", "(", ")", "!=", "nil", "{", "nextBlock", ":=", "blocksToNotify", ".", "Front", "(", ")", ".", "Value", ".", "(", "*", "wire", ".", "MsgBlock", ")", "\n", "nextHeight", ":=", "currentBlock", ".", "Height", "+", "1", "\n", "nextHash", ":=", "nextBlock", ".", "BlockHash", "(", ")", "\n", "nextHeader", ",", "err", ":=", "c", ".", "GetBlockHeader", "(", "&", "nextHash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "_", ",", "err", "=", "c", ".", "filterBlock", "(", "nextBlock", ",", "nextHeight", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "currentBlock", ".", "Height", "=", "nextHeight", "\n", "currentBlock", ".", "Hash", "=", "nextHash", "\n", "currentBlock", ".", "Timestamp", "=", "nextHeader", ".", "Timestamp", "\n\n", "blocksToNotify", ".", "Remove", "(", "blocksToNotify", ".", "Front", "(", ")", ")", "\n", "}", "\n\n", "c", ".", "bestBlockMtx", ".", "Lock", "(", ")", "\n", "c", ".", "bestBlock", "=", "currentBlock", "\n", "c", ".", "bestBlockMtx", ".", "Unlock", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// reorg processes a reorganization during chain synchronization. This is // separate from a rescan's handling of a reorg. This will rewind back until it // finds a common ancestor and notify all the new blocks since then.
[ "reorg", "processes", "a", "reorganization", "during", "chain", "synchronization", ".", "This", "is", "separate", "from", "a", "rescan", "s", "handling", "of", "a", "reorg", ".", "This", "will", "rewind", "back", "until", "it", "finds", "a", "common", "ancestor", "and", "notify", "all", "the", "new", "blocks", "since", "then", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L745-L863
train
btcsuite/btcwallet
chain/bitcoind_client.go
filterBlock
func (c *BitcoindClient) filterBlock(block *wire.MsgBlock, height int32, notify bool) ([]*wtxmgr.TxRecord, error) { // If this block happened before the client's birthday, then we'll skip // it entirely. if block.Header.Timestamp.Before(c.birthday) { return nil, nil } if c.shouldNotifyBlocks() { log.Debugf("Filtering block %d (%s) with %d transactions", height, block.BlockHash(), len(block.Transactions)) } // Create a block details template to use for all of the confirmed // transactions found within this block. blockHash := block.BlockHash() blockDetails := &btcjson.BlockDetails{ Hash: blockHash.String(), Height: height, Time: block.Header.Timestamp.Unix(), } // Now, we'll through all of the transactions in the block keeping track // of any relevant to the caller. var relevantTxs []*wtxmgr.TxRecord confirmedTxs := make(map[chainhash.Hash]struct{}) for i, tx := range block.Transactions { // Update the index in the block details with the index of this // transaction. blockDetails.Index = i isRelevant, rec, err := c.filterTx(tx, blockDetails, notify) if err != nil { log.Warnf("Unable to filter transaction %v: %v", tx.TxHash(), err) continue } if isRelevant { relevantTxs = append(relevantTxs, rec) confirmedTxs[tx.TxHash()] = struct{}{} } } // Update the expiration map by setting the block's confirmed // transactions and deleting any in the mempool that were confirmed // over 288 blocks ago. c.watchMtx.Lock() c.expiredMempool[height] = confirmedTxs if oldBlock, ok := c.expiredMempool[height-288]; ok { for txHash := range oldBlock { delete(c.mempool, txHash) } delete(c.expiredMempool, height-288) } c.watchMtx.Unlock() if notify { c.onFilteredBlockConnected(height, &block.Header, relevantTxs) c.onBlockConnected(&blockHash, height, block.Header.Timestamp) } return relevantTxs, nil }
go
func (c *BitcoindClient) filterBlock(block *wire.MsgBlock, height int32, notify bool) ([]*wtxmgr.TxRecord, error) { // If this block happened before the client's birthday, then we'll skip // it entirely. if block.Header.Timestamp.Before(c.birthday) { return nil, nil } if c.shouldNotifyBlocks() { log.Debugf("Filtering block %d (%s) with %d transactions", height, block.BlockHash(), len(block.Transactions)) } // Create a block details template to use for all of the confirmed // transactions found within this block. blockHash := block.BlockHash() blockDetails := &btcjson.BlockDetails{ Hash: blockHash.String(), Height: height, Time: block.Header.Timestamp.Unix(), } // Now, we'll through all of the transactions in the block keeping track // of any relevant to the caller. var relevantTxs []*wtxmgr.TxRecord confirmedTxs := make(map[chainhash.Hash]struct{}) for i, tx := range block.Transactions { // Update the index in the block details with the index of this // transaction. blockDetails.Index = i isRelevant, rec, err := c.filterTx(tx, blockDetails, notify) if err != nil { log.Warnf("Unable to filter transaction %v: %v", tx.TxHash(), err) continue } if isRelevant { relevantTxs = append(relevantTxs, rec) confirmedTxs[tx.TxHash()] = struct{}{} } } // Update the expiration map by setting the block's confirmed // transactions and deleting any in the mempool that were confirmed // over 288 blocks ago. c.watchMtx.Lock() c.expiredMempool[height] = confirmedTxs if oldBlock, ok := c.expiredMempool[height-288]; ok { for txHash := range oldBlock { delete(c.mempool, txHash) } delete(c.expiredMempool, height-288) } c.watchMtx.Unlock() if notify { c.onFilteredBlockConnected(height, &block.Header, relevantTxs) c.onBlockConnected(&blockHash, height, block.Header.Timestamp) } return relevantTxs, nil }
[ "func", "(", "c", "*", "BitcoindClient", ")", "filterBlock", "(", "block", "*", "wire", ".", "MsgBlock", ",", "height", "int32", ",", "notify", "bool", ")", "(", "[", "]", "*", "wtxmgr", ".", "TxRecord", ",", "error", ")", "{", "// If this block happened before the client's birthday, then we'll skip", "// it entirely.", "if", "block", ".", "Header", ".", "Timestamp", ".", "Before", "(", "c", ".", "birthday", ")", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "if", "c", ".", "shouldNotifyBlocks", "(", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "height", ",", "block", ".", "BlockHash", "(", ")", ",", "len", "(", "block", ".", "Transactions", ")", ")", "\n", "}", "\n\n", "// Create a block details template to use for all of the confirmed", "// transactions found within this block.", "blockHash", ":=", "block", ".", "BlockHash", "(", ")", "\n", "blockDetails", ":=", "&", "btcjson", ".", "BlockDetails", "{", "Hash", ":", "blockHash", ".", "String", "(", ")", ",", "Height", ":", "height", ",", "Time", ":", "block", ".", "Header", ".", "Timestamp", ".", "Unix", "(", ")", ",", "}", "\n\n", "// Now, we'll through all of the transactions in the block keeping track", "// of any relevant to the caller.", "var", "relevantTxs", "[", "]", "*", "wtxmgr", ".", "TxRecord", "\n", "confirmedTxs", ":=", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "struct", "{", "}", ")", "\n", "for", "i", ",", "tx", ":=", "range", "block", ".", "Transactions", "{", "// Update the index in the block details with the index of this", "// transaction.", "blockDetails", ".", "Index", "=", "i", "\n", "isRelevant", ",", "rec", ",", "err", ":=", "c", ".", "filterTx", "(", "tx", ",", "blockDetails", ",", "notify", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "tx", ".", "TxHash", "(", ")", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "if", "isRelevant", "{", "relevantTxs", "=", "append", "(", "relevantTxs", ",", "rec", ")", "\n", "confirmedTxs", "[", "tx", ".", "TxHash", "(", ")", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n\n", "// Update the expiration map by setting the block's confirmed", "// transactions and deleting any in the mempool that were confirmed", "// over 288 blocks ago.", "c", ".", "watchMtx", ".", "Lock", "(", ")", "\n", "c", ".", "expiredMempool", "[", "height", "]", "=", "confirmedTxs", "\n", "if", "oldBlock", ",", "ok", ":=", "c", ".", "expiredMempool", "[", "height", "-", "288", "]", ";", "ok", "{", "for", "txHash", ":=", "range", "oldBlock", "{", "delete", "(", "c", ".", "mempool", ",", "txHash", ")", "\n", "}", "\n", "delete", "(", "c", ".", "expiredMempool", ",", "height", "-", "288", ")", "\n", "}", "\n", "c", ".", "watchMtx", ".", "Unlock", "(", ")", "\n\n", "if", "notify", "{", "c", ".", "onFilteredBlockConnected", "(", "height", ",", "&", "block", ".", "Header", ",", "relevantTxs", ")", "\n", "c", ".", "onBlockConnected", "(", "&", "blockHash", ",", "height", ",", "block", ".", "Header", ".", "Timestamp", ")", "\n", "}", "\n\n", "return", "relevantTxs", ",", "nil", "\n", "}" ]
// filterBlock filters a block for watched outpoints and addresses, and returns // any matching transactions, sending notifications along the way.
[ "filterBlock", "filters", "a", "block", "for", "watched", "outpoints", "and", "addresses", "and", "returns", "any", "matching", "transactions", "sending", "notifications", "along", "the", "way", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L1103-L1166
train
btcsuite/btcwallet
chain/bitcoind_client.go
filterTx
func (c *BitcoindClient) filterTx(tx *wire.MsgTx, blockDetails *btcjson.BlockDetails, notify bool) (bool, *wtxmgr.TxRecord, error) { txDetails := btcutil.NewTx(tx) if blockDetails != nil { txDetails.SetIndex(blockDetails.Index) } rec, err := wtxmgr.NewTxRecordFromMsgTx(txDetails.MsgTx(), time.Now()) if err != nil { log.Errorf("Cannot create transaction record for relevant "+ "tx: %v", err) return false, nil, err } if blockDetails != nil { rec.Received = time.Unix(blockDetails.Time, 0) } // We'll begin the filtering process by holding the lock to ensure we // match exactly against what's currently in the filters. c.watchMtx.Lock() defer c.watchMtx.Unlock() // If we've already seen this transaction and it's now been confirmed, // then we'll shortcut the filter process by immediately sending a // notification to the caller that the filter matches. if _, ok := c.mempool[tx.TxHash()]; ok { if notify && blockDetails != nil { c.onRelevantTx(rec, blockDetails) } return true, rec, nil } // Otherwise, this is a new transaction we have yet to see. We'll need // to determine if this transaction is somehow relevant to the caller. var isRelevant bool // We'll start by checking all inputs and determining whether it spends // an existing outpoint or a pkScript encoded as an address in our watch // list. for _, txIn := range tx.TxIn { // If it matches an outpoint in our watch list, we can exit our // loop early. if _, ok := c.watchedOutPoints[txIn.PreviousOutPoint]; ok { isRelevant = true break } // Otherwise, we'll check whether it matches a pkScript in our // watch list encoded as an address. To do so, we'll re-derive // the pkScript of the output the input is attempting to spend. pkScript, err := txscript.ComputePkScript( txIn.SignatureScript, txIn.Witness, ) if err != nil { // Non-standard outputs can be safely skipped. continue } addr, err := pkScript.Address(c.chainParams) if err != nil { // Non-standard outputs can be safely skipped. continue } if _, ok := c.watchedAddresses[addr.String()]; ok { isRelevant = true break } } // We'll also cycle through its outputs to determine if it pays to // any of the currently watched addresses. If an output matches, we'll // add it to our watch list. for i, txOut := range tx.TxOut { _, addrs, _, err := txscript.ExtractPkScriptAddrs( txOut.PkScript, c.chainParams, ) if err != nil { // Non-standard outputs can be safely skipped. continue } for _, addr := range addrs { if _, ok := c.watchedAddresses[addr.String()]; ok { isRelevant = true op := wire.OutPoint{ Hash: tx.TxHash(), Index: uint32(i), } c.watchedOutPoints[op] = struct{}{} } } } // If the transaction didn't pay to any of our watched addresses, we'll // check if we're currently watching for the hash of this transaction. if !isRelevant { if _, ok := c.watchedTxs[tx.TxHash()]; ok { isRelevant = true } } // If the transaction is not relevant to us, we can simply exit. if !isRelevant { return false, rec, nil } // Otherwise, the transaction matched our filters, so we should dispatch // a notification for it. If it's still unconfirmed, we'll include it in // our mempool so that it can also be notified as part of // FilteredBlockConnected once it confirms. if blockDetails == nil { c.mempool[tx.TxHash()] = struct{}{} } c.onRelevantTx(rec, blockDetails) return true, rec, nil }
go
func (c *BitcoindClient) filterTx(tx *wire.MsgTx, blockDetails *btcjson.BlockDetails, notify bool) (bool, *wtxmgr.TxRecord, error) { txDetails := btcutil.NewTx(tx) if blockDetails != nil { txDetails.SetIndex(blockDetails.Index) } rec, err := wtxmgr.NewTxRecordFromMsgTx(txDetails.MsgTx(), time.Now()) if err != nil { log.Errorf("Cannot create transaction record for relevant "+ "tx: %v", err) return false, nil, err } if blockDetails != nil { rec.Received = time.Unix(blockDetails.Time, 0) } // We'll begin the filtering process by holding the lock to ensure we // match exactly against what's currently in the filters. c.watchMtx.Lock() defer c.watchMtx.Unlock() // If we've already seen this transaction and it's now been confirmed, // then we'll shortcut the filter process by immediately sending a // notification to the caller that the filter matches. if _, ok := c.mempool[tx.TxHash()]; ok { if notify && blockDetails != nil { c.onRelevantTx(rec, blockDetails) } return true, rec, nil } // Otherwise, this is a new transaction we have yet to see. We'll need // to determine if this transaction is somehow relevant to the caller. var isRelevant bool // We'll start by checking all inputs and determining whether it spends // an existing outpoint or a pkScript encoded as an address in our watch // list. for _, txIn := range tx.TxIn { // If it matches an outpoint in our watch list, we can exit our // loop early. if _, ok := c.watchedOutPoints[txIn.PreviousOutPoint]; ok { isRelevant = true break } // Otherwise, we'll check whether it matches a pkScript in our // watch list encoded as an address. To do so, we'll re-derive // the pkScript of the output the input is attempting to spend. pkScript, err := txscript.ComputePkScript( txIn.SignatureScript, txIn.Witness, ) if err != nil { // Non-standard outputs can be safely skipped. continue } addr, err := pkScript.Address(c.chainParams) if err != nil { // Non-standard outputs can be safely skipped. continue } if _, ok := c.watchedAddresses[addr.String()]; ok { isRelevant = true break } } // We'll also cycle through its outputs to determine if it pays to // any of the currently watched addresses. If an output matches, we'll // add it to our watch list. for i, txOut := range tx.TxOut { _, addrs, _, err := txscript.ExtractPkScriptAddrs( txOut.PkScript, c.chainParams, ) if err != nil { // Non-standard outputs can be safely skipped. continue } for _, addr := range addrs { if _, ok := c.watchedAddresses[addr.String()]; ok { isRelevant = true op := wire.OutPoint{ Hash: tx.TxHash(), Index: uint32(i), } c.watchedOutPoints[op] = struct{}{} } } } // If the transaction didn't pay to any of our watched addresses, we'll // check if we're currently watching for the hash of this transaction. if !isRelevant { if _, ok := c.watchedTxs[tx.TxHash()]; ok { isRelevant = true } } // If the transaction is not relevant to us, we can simply exit. if !isRelevant { return false, rec, nil } // Otherwise, the transaction matched our filters, so we should dispatch // a notification for it. If it's still unconfirmed, we'll include it in // our mempool so that it can also be notified as part of // FilteredBlockConnected once it confirms. if blockDetails == nil { c.mempool[tx.TxHash()] = struct{}{} } c.onRelevantTx(rec, blockDetails) return true, rec, nil }
[ "func", "(", "c", "*", "BitcoindClient", ")", "filterTx", "(", "tx", "*", "wire", ".", "MsgTx", ",", "blockDetails", "*", "btcjson", ".", "BlockDetails", ",", "notify", "bool", ")", "(", "bool", ",", "*", "wtxmgr", ".", "TxRecord", ",", "error", ")", "{", "txDetails", ":=", "btcutil", ".", "NewTx", "(", "tx", ")", "\n", "if", "blockDetails", "!=", "nil", "{", "txDetails", ".", "SetIndex", "(", "blockDetails", ".", "Index", ")", "\n", "}", "\n\n", "rec", ",", "err", ":=", "wtxmgr", ".", "NewTxRecordFromMsgTx", "(", "txDetails", ".", "MsgTx", "(", ")", ",", "time", ".", "Now", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "return", "false", ",", "nil", ",", "err", "\n", "}", "\n", "if", "blockDetails", "!=", "nil", "{", "rec", ".", "Received", "=", "time", ".", "Unix", "(", "blockDetails", ".", "Time", ",", "0", ")", "\n", "}", "\n\n", "// We'll begin the filtering process by holding the lock to ensure we", "// match exactly against what's currently in the filters.", "c", ".", "watchMtx", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "watchMtx", ".", "Unlock", "(", ")", "\n\n", "// If we've already seen this transaction and it's now been confirmed,", "// then we'll shortcut the filter process by immediately sending a", "// notification to the caller that the filter matches.", "if", "_", ",", "ok", ":=", "c", ".", "mempool", "[", "tx", ".", "TxHash", "(", ")", "]", ";", "ok", "{", "if", "notify", "&&", "blockDetails", "!=", "nil", "{", "c", ".", "onRelevantTx", "(", "rec", ",", "blockDetails", ")", "\n", "}", "\n", "return", "true", ",", "rec", ",", "nil", "\n", "}", "\n\n", "// Otherwise, this is a new transaction we have yet to see. We'll need", "// to determine if this transaction is somehow relevant to the caller.", "var", "isRelevant", "bool", "\n\n", "// We'll start by checking all inputs and determining whether it spends", "// an existing outpoint or a pkScript encoded as an address in our watch", "// list.", "for", "_", ",", "txIn", ":=", "range", "tx", ".", "TxIn", "{", "// If it matches an outpoint in our watch list, we can exit our", "// loop early.", "if", "_", ",", "ok", ":=", "c", ".", "watchedOutPoints", "[", "txIn", ".", "PreviousOutPoint", "]", ";", "ok", "{", "isRelevant", "=", "true", "\n", "break", "\n", "}", "\n\n", "// Otherwise, we'll check whether it matches a pkScript in our", "// watch list encoded as an address. To do so, we'll re-derive", "// the pkScript of the output the input is attempting to spend.", "pkScript", ",", "err", ":=", "txscript", ".", "ComputePkScript", "(", "txIn", ".", "SignatureScript", ",", "txIn", ".", "Witness", ",", ")", "\n", "if", "err", "!=", "nil", "{", "// Non-standard outputs can be safely skipped.", "continue", "\n", "}", "\n", "addr", ",", "err", ":=", "pkScript", ".", "Address", "(", "c", ".", "chainParams", ")", "\n", "if", "err", "!=", "nil", "{", "// Non-standard outputs can be safely skipped.", "continue", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "c", ".", "watchedAddresses", "[", "addr", ".", "String", "(", ")", "]", ";", "ok", "{", "isRelevant", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n\n", "// We'll also cycle through its outputs to determine if it pays to", "// any of the currently watched addresses. If an output matches, we'll", "// add it to our watch list.", "for", "i", ",", "txOut", ":=", "range", "tx", ".", "TxOut", "{", "_", ",", "addrs", ",", "_", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "txOut", ".", "PkScript", ",", "c", ".", "chainParams", ",", ")", "\n", "if", "err", "!=", "nil", "{", "// Non-standard outputs can be safely skipped.", "continue", "\n", "}", "\n\n", "for", "_", ",", "addr", ":=", "range", "addrs", "{", "if", "_", ",", "ok", ":=", "c", ".", "watchedAddresses", "[", "addr", ".", "String", "(", ")", "]", ";", "ok", "{", "isRelevant", "=", "true", "\n", "op", ":=", "wire", ".", "OutPoint", "{", "Hash", ":", "tx", ".", "TxHash", "(", ")", ",", "Index", ":", "uint32", "(", "i", ")", ",", "}", "\n", "c", ".", "watchedOutPoints", "[", "op", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// If the transaction didn't pay to any of our watched addresses, we'll", "// check if we're currently watching for the hash of this transaction.", "if", "!", "isRelevant", "{", "if", "_", ",", "ok", ":=", "c", ".", "watchedTxs", "[", "tx", ".", "TxHash", "(", ")", "]", ";", "ok", "{", "isRelevant", "=", "true", "\n", "}", "\n", "}", "\n\n", "// If the transaction is not relevant to us, we can simply exit.", "if", "!", "isRelevant", "{", "return", "false", ",", "rec", ",", "nil", "\n", "}", "\n\n", "// Otherwise, the transaction matched our filters, so we should dispatch", "// a notification for it. If it's still unconfirmed, we'll include it in", "// our mempool so that it can also be notified as part of", "// FilteredBlockConnected once it confirms.", "if", "blockDetails", "==", "nil", "{", "c", ".", "mempool", "[", "tx", ".", "TxHash", "(", ")", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "c", ".", "onRelevantTx", "(", "rec", ",", "blockDetails", ")", "\n\n", "return", "true", ",", "rec", ",", "nil", "\n", "}" ]
// filterTx determines whether a transaction is relevant to the client by // inspecting the client's different filters.
[ "filterTx", "determines", "whether", "a", "transaction", "is", "relevant", "to", "the", "client", "by", "inspecting", "the", "client", "s", "different", "filters", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L1170-L1288
train
btcsuite/btcwallet
wtxmgr/migrations.go
dropTransactionHistory
func dropTransactionHistory(ns walletdb.ReadWriteBucket) error { log.Info("Dropping wallet transaction history") // To drop the store's transaction history, we'll need to remove all of // the relevant descendant buckets and key/value pairs. if err := deleteBuckets(ns); err != nil { return err } if err := ns.Delete(rootMinedBalance); err != nil { return err } // With everything removed, we'll now recreate our buckets. if err := createBuckets(ns); err != nil { return err } // Finally, we'll insert a 0 value for our mined balance. return putMinedBalance(ns, 0) }
go
func dropTransactionHistory(ns walletdb.ReadWriteBucket) error { log.Info("Dropping wallet transaction history") // To drop the store's transaction history, we'll need to remove all of // the relevant descendant buckets and key/value pairs. if err := deleteBuckets(ns); err != nil { return err } if err := ns.Delete(rootMinedBalance); err != nil { return err } // With everything removed, we'll now recreate our buckets. if err := createBuckets(ns); err != nil { return err } // Finally, we'll insert a 0 value for our mined balance. return putMinedBalance(ns, 0) }
[ "func", "dropTransactionHistory", "(", "ns", "walletdb", ".", "ReadWriteBucket", ")", "error", "{", "log", ".", "Info", "(", "\"", "\"", ")", "\n\n", "// To drop the store's transaction history, we'll need to remove all of", "// the relevant descendant buckets and key/value pairs.", "if", "err", ":=", "deleteBuckets", "(", "ns", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "ns", ".", "Delete", "(", "rootMinedBalance", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// With everything removed, we'll now recreate our buckets.", "if", "err", ":=", "createBuckets", "(", "ns", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Finally, we'll insert a 0 value for our mined balance.", "return", "putMinedBalance", "(", "ns", ",", "0", ")", "\n", "}" ]
// dropTransactionHistory is a migration that attempts to recreate the // transaction store with a clean state.
[ "dropTransactionHistory", "is", "a", "migration", "that", "attempts", "to", "recreate", "the", "transaction", "store", "with", "a", "clean", "state", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/migrations.go#L91-L110
train
btcsuite/btcwallet
waddrmgr/sync.go
newSyncState
func newSyncState(startBlock, syncedTo *BlockStamp) *syncState { return &syncState{ startBlock: *startBlock, syncedTo: *syncedTo, } }
go
func newSyncState(startBlock, syncedTo *BlockStamp) *syncState { return &syncState{ startBlock: *startBlock, syncedTo: *syncedTo, } }
[ "func", "newSyncState", "(", "startBlock", ",", "syncedTo", "*", "BlockStamp", ")", "*", "syncState", "{", "return", "&", "syncState", "{", "startBlock", ":", "*", "startBlock", ",", "syncedTo", ":", "*", "syncedTo", ",", "}", "\n", "}" ]
// newSyncState returns a new sync state with the provided parameters.
[ "newSyncState", "returns", "a", "new", "sync", "state", "with", "the", "provided", "parameters", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L37-L43
train
btcsuite/btcwallet
waddrmgr/sync.go
SetSyncedTo
func (m *Manager) SetSyncedTo(ns walletdb.ReadWriteBucket, bs *BlockStamp) error { m.mtx.Lock() defer m.mtx.Unlock() // Use the stored start blockstamp and reset recent hashes and height // when the provided blockstamp is nil. if bs == nil { bs = &m.syncState.startBlock } // Update the database. err := PutSyncedTo(ns, bs) if err != nil { return err } // Update memory now that the database is updated. m.syncState.syncedTo = *bs return nil }
go
func (m *Manager) SetSyncedTo(ns walletdb.ReadWriteBucket, bs *BlockStamp) error { m.mtx.Lock() defer m.mtx.Unlock() // Use the stored start blockstamp and reset recent hashes and height // when the provided blockstamp is nil. if bs == nil { bs = &m.syncState.startBlock } // Update the database. err := PutSyncedTo(ns, bs) if err != nil { return err } // Update memory now that the database is updated. m.syncState.syncedTo = *bs return nil }
[ "func", "(", "m", "*", "Manager", ")", "SetSyncedTo", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "bs", "*", "BlockStamp", ")", "error", "{", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// Use the stored start blockstamp and reset recent hashes and height", "// when the provided blockstamp is nil.", "if", "bs", "==", "nil", "{", "bs", "=", "&", "m", ".", "syncState", ".", "startBlock", "\n", "}", "\n\n", "// Update the database.", "err", ":=", "PutSyncedTo", "(", "ns", ",", "bs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Update memory now that the database is updated.", "m", ".", "syncState", ".", "syncedTo", "=", "*", "bs", "\n", "return", "nil", "\n", "}" ]
// SetSyncedTo marks the address manager to be in sync with the recently-seen // block described by the blockstamp. When the provided blockstamp is nil, the // oldest blockstamp of the block the manager was created at and of all // imported addresses will be used. This effectively allows the manager to be // marked as unsynced back to the oldest known point any of the addresses have // appeared in the block chain.
[ "SetSyncedTo", "marks", "the", "address", "manager", "to", "be", "in", "sync", "with", "the", "recently", "-", "seen", "block", "described", "by", "the", "blockstamp", ".", "When", "the", "provided", "blockstamp", "is", "nil", "the", "oldest", "blockstamp", "of", "the", "block", "the", "manager", "was", "created", "at", "and", "of", "all", "imported", "addresses", "will", "be", "used", ".", "This", "effectively", "allows", "the", "manager", "to", "be", "marked", "as", "unsynced", "back", "to", "the", "oldest", "known", "point", "any", "of", "the", "addresses", "have", "appeared", "in", "the", "block", "chain", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L51-L70
train
btcsuite/btcwallet
waddrmgr/sync.go
SyncedTo
func (m *Manager) SyncedTo() BlockStamp { m.mtx.Lock() defer m.mtx.Unlock() return m.syncState.syncedTo }
go
func (m *Manager) SyncedTo() BlockStamp { m.mtx.Lock() defer m.mtx.Unlock() return m.syncState.syncedTo }
[ "func", "(", "m", "*", "Manager", ")", "SyncedTo", "(", ")", "BlockStamp", "{", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "return", "m", ".", "syncState", ".", "syncedTo", "\n", "}" ]
// SyncedTo returns details about the block height and hash that the address // manager is synced through at the very least. The intention is that callers // can use this information for intelligently initiating rescans to sync back to // the best chain from the last known good block.
[ "SyncedTo", "returns", "details", "about", "the", "block", "height", "and", "hash", "that", "the", "address", "manager", "is", "synced", "through", "at", "the", "very", "least", ".", "The", "intention", "is", "that", "callers", "can", "use", "this", "information", "for", "intelligently", "initiating", "rescans", "to", "sync", "back", "to", "the", "best", "chain", "from", "the", "last", "known", "good", "block", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L76-L81
train
btcsuite/btcwallet
waddrmgr/sync.go
BlockHash
func (m *Manager) BlockHash(ns walletdb.ReadBucket, height int32) ( *chainhash.Hash, error) { m.mtx.Lock() defer m.mtx.Unlock() return fetchBlockHash(ns, height) }
go
func (m *Manager) BlockHash(ns walletdb.ReadBucket, height int32) ( *chainhash.Hash, error) { m.mtx.Lock() defer m.mtx.Unlock() return fetchBlockHash(ns, height) }
[ "func", "(", "m", "*", "Manager", ")", "BlockHash", "(", "ns", "walletdb", ".", "ReadBucket", ",", "height", "int32", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "return", "fetchBlockHash", "(", "ns", ",", "height", ")", "\n", "}" ]
// BlockHash returns the block hash at a particular block height. This // information is useful for comparing against the chain back-end to see if a // reorg is taking place and how far back it goes.
[ "BlockHash", "returns", "the", "block", "hash", "at", "a", "particular", "block", "height", ".", "This", "information", "is", "useful", "for", "comparing", "against", "the", "chain", "back", "-", "end", "to", "see", "if", "a", "reorg", "is", "taking", "place", "and", "how", "far", "back", "it", "goes", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L86-L92
train
btcsuite/btcwallet
waddrmgr/sync.go
Birthday
func (m *Manager) Birthday() time.Time { m.mtx.Lock() defer m.mtx.Unlock() return m.birthday }
go
func (m *Manager) Birthday() time.Time { m.mtx.Lock() defer m.mtx.Unlock() return m.birthday }
[ "func", "(", "m", "*", "Manager", ")", "Birthday", "(", ")", "time", ".", "Time", "{", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "return", "m", ".", "birthday", "\n", "}" ]
// Birthday returns the birthday, or earliest time a key could have been used, // for the manager.
[ "Birthday", "returns", "the", "birthday", "or", "earliest", "time", "a", "key", "could", "have", "been", "used", "for", "the", "manager", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L96-L101
train
btcsuite/btcwallet
waddrmgr/sync.go
SetBirthday
func (m *Manager) SetBirthday(ns walletdb.ReadWriteBucket, birthday time.Time) error { m.mtx.Lock() defer m.mtx.Unlock() m.birthday = birthday return putBirthday(ns, birthday) }
go
func (m *Manager) SetBirthday(ns walletdb.ReadWriteBucket, birthday time.Time) error { m.mtx.Lock() defer m.mtx.Unlock() m.birthday = birthday return putBirthday(ns, birthday) }
[ "func", "(", "m", "*", "Manager", ")", "SetBirthday", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "birthday", "time", ".", "Time", ")", "error", "{", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "m", ".", "birthday", "=", "birthday", "\n", "return", "putBirthday", "(", "ns", ",", "birthday", ")", "\n", "}" ]
// SetBirthday sets the birthday, or earliest time a key could have been used, // for the manager.
[ "SetBirthday", "sets", "the", "birthday", "or", "earliest", "time", "a", "key", "could", "have", "been", "used", "for", "the", "manager", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L105-L112
train
btcsuite/btcwallet
waddrmgr/sync.go
BirthdayBlock
func (m *Manager) BirthdayBlock(ns walletdb.ReadBucket) (BlockStamp, bool, error) { birthdayBlock, err := FetchBirthdayBlock(ns) if err != nil { return BlockStamp{}, false, err } return birthdayBlock, fetchBirthdayBlockVerification(ns), nil }
go
func (m *Manager) BirthdayBlock(ns walletdb.ReadBucket) (BlockStamp, bool, error) { birthdayBlock, err := FetchBirthdayBlock(ns) if err != nil { return BlockStamp{}, false, err } return birthdayBlock, fetchBirthdayBlockVerification(ns), nil }
[ "func", "(", "m", "*", "Manager", ")", "BirthdayBlock", "(", "ns", "walletdb", ".", "ReadBucket", ")", "(", "BlockStamp", ",", "bool", ",", "error", ")", "{", "birthdayBlock", ",", "err", ":=", "FetchBirthdayBlock", "(", "ns", ")", "\n", "if", "err", "!=", "nil", "{", "return", "BlockStamp", "{", "}", ",", "false", ",", "err", "\n", "}", "\n\n", "return", "birthdayBlock", ",", "fetchBirthdayBlockVerification", "(", "ns", ")", ",", "nil", "\n", "}" ]
// BirthdayBlock returns the birthday block, or earliest block a key could have // been used, for the manager. A boolean is also returned to indicate whether // the birthday block has been verified as correct.
[ "BirthdayBlock", "returns", "the", "birthday", "block", "or", "earliest", "block", "a", "key", "could", "have", "been", "used", "for", "the", "manager", ".", "A", "boolean", "is", "also", "returned", "to", "indicate", "whether", "the", "birthday", "block", "has", "been", "verified", "as", "correct", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L117-L124
train
btcsuite/btcwallet
waddrmgr/sync.go
SetBirthdayBlock
func (m *Manager) SetBirthdayBlock(ns walletdb.ReadWriteBucket, block BlockStamp, verified bool) error { if err := putBirthdayBlock(ns, block); err != nil { return err } return putBirthdayBlockVerification(ns, verified) }
go
func (m *Manager) SetBirthdayBlock(ns walletdb.ReadWriteBucket, block BlockStamp, verified bool) error { if err := putBirthdayBlock(ns, block); err != nil { return err } return putBirthdayBlockVerification(ns, verified) }
[ "func", "(", "m", "*", "Manager", ")", "SetBirthdayBlock", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "block", "BlockStamp", ",", "verified", "bool", ")", "error", "{", "if", "err", ":=", "putBirthdayBlock", "(", "ns", ",", "block", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "putBirthdayBlockVerification", "(", "ns", ",", "verified", ")", "\n", "}" ]
// SetBirthdayBlock sets the birthday block, or earliest time a key could have // been used, for the manager. The verified boolean can be used to specify // whether this birthday block should be sanity checked to determine if there // exists a better candidate to prevent less block fetching.
[ "SetBirthdayBlock", "sets", "the", "birthday", "block", "or", "earliest", "time", "a", "key", "could", "have", "been", "used", "for", "the", "manager", ".", "The", "verified", "boolean", "can", "be", "used", "to", "specify", "whether", "this", "birthday", "block", "should", "be", "sanity", "checked", "to", "determine", "if", "there", "exists", "a", "better", "candidate", "to", "prevent", "less", "block", "fetching", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L130-L137
train
btcsuite/btcwallet
wallet/recovery.go
NewRecoveryManager
func NewRecoveryManager(recoveryWindow, batchSize uint32, chainParams *chaincfg.Params) *RecoveryManager { return &RecoveryManager{ recoveryWindow: recoveryWindow, blockBatch: make([]wtxmgr.BlockMeta, 0, batchSize), chainParams: chainParams, state: NewRecoveryState(recoveryWindow), } }
go
func NewRecoveryManager(recoveryWindow, batchSize uint32, chainParams *chaincfg.Params) *RecoveryManager { return &RecoveryManager{ recoveryWindow: recoveryWindow, blockBatch: make([]wtxmgr.BlockMeta, 0, batchSize), chainParams: chainParams, state: NewRecoveryState(recoveryWindow), } }
[ "func", "NewRecoveryManager", "(", "recoveryWindow", ",", "batchSize", "uint32", ",", "chainParams", "*", "chaincfg", ".", "Params", ")", "*", "RecoveryManager", "{", "return", "&", "RecoveryManager", "{", "recoveryWindow", ":", "recoveryWindow", ",", "blockBatch", ":", "make", "(", "[", "]", "wtxmgr", ".", "BlockMeta", ",", "0", ",", "batchSize", ")", ",", "chainParams", ":", "chainParams", ",", "state", ":", "NewRecoveryState", "(", "recoveryWindow", ")", ",", "}", "\n", "}" ]
// NewRecoveryManager initializes a new RecoveryManager with a derivation // look-ahead of `recoveryWindow` child indexes, and pre-allocates a backing // array for `batchSize` blocks to scan at once.
[ "NewRecoveryManager", "initializes", "a", "new", "RecoveryManager", "with", "a", "derivation", "look", "-", "ahead", "of", "recoveryWindow", "child", "indexes", "and", "pre", "-", "allocates", "a", "backing", "array", "for", "batchSize", "blocks", "to", "scan", "at", "once", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L43-L52
train
btcsuite/btcwallet
wallet/recovery.go
Resurrect
func (rm *RecoveryManager) Resurrect(ns walletdb.ReadBucket, scopedMgrs map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager, credits []wtxmgr.Credit) error { // First, for each scope that we are recovering, rederive all of the // addresses up to the last found address known to each branch. for keyScope, scopedMgr := range scopedMgrs { // Load the current account properties for this scope, using the // the default account number. // TODO(conner): rescan for all created accounts if we allow // users to use non-default address scopeState := rm.state.StateForScope(keyScope) acctProperties, err := scopedMgr.AccountProperties( ns, waddrmgr.DefaultAccountNum, ) if err != nil { return err } // Fetch the external key count, which bounds the indexes we // will need to rederive. externalCount := acctProperties.ExternalKeyCount // Walk through all indexes through the last external key, // deriving each address and adding it to the external branch // recovery state's set of addresses to look for. for i := uint32(0); i < externalCount; i++ { keyPath := externalKeyPath(i) addr, err := scopedMgr.DeriveFromKeyPath(ns, keyPath) if err != nil && err != hdkeychain.ErrInvalidChild { return err } else if err == hdkeychain.ErrInvalidChild { scopeState.ExternalBranch.MarkInvalidChild(i) continue } scopeState.ExternalBranch.AddAddr(i, addr.Address()) } // Fetch the internal key count, which bounds the indexes we // will need to rederive. internalCount := acctProperties.InternalKeyCount // Walk through all indexes through the last internal key, // deriving each address and adding it to the internal branch // recovery state's set of addresses to look for. for i := uint32(0); i < internalCount; i++ { keyPath := internalKeyPath(i) addr, err := scopedMgr.DeriveFromKeyPath(ns, keyPath) if err != nil && err != hdkeychain.ErrInvalidChild { return err } else if err == hdkeychain.ErrInvalidChild { scopeState.InternalBranch.MarkInvalidChild(i) continue } scopeState.InternalBranch.AddAddr(i, addr.Address()) } // The key counts will point to the next key that can be // derived, so we subtract one to point to last known key. If // the key count is zero, then no addresses have been found. if externalCount > 0 { scopeState.ExternalBranch.ReportFound(externalCount - 1) } if internalCount > 0 { scopeState.InternalBranch.ReportFound(internalCount - 1) } } // In addition, we will re-add any outpoints that are known the wallet // to our global set of watched outpoints, so that we can watch them for // spends. for _, credit := range credits { _, addrs, _, err := txscript.ExtractPkScriptAddrs( credit.PkScript, rm.chainParams, ) if err != nil { return err } rm.state.AddWatchedOutPoint(&credit.OutPoint, addrs[0]) } return nil }
go
func (rm *RecoveryManager) Resurrect(ns walletdb.ReadBucket, scopedMgrs map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager, credits []wtxmgr.Credit) error { // First, for each scope that we are recovering, rederive all of the // addresses up to the last found address known to each branch. for keyScope, scopedMgr := range scopedMgrs { // Load the current account properties for this scope, using the // the default account number. // TODO(conner): rescan for all created accounts if we allow // users to use non-default address scopeState := rm.state.StateForScope(keyScope) acctProperties, err := scopedMgr.AccountProperties( ns, waddrmgr.DefaultAccountNum, ) if err != nil { return err } // Fetch the external key count, which bounds the indexes we // will need to rederive. externalCount := acctProperties.ExternalKeyCount // Walk through all indexes through the last external key, // deriving each address and adding it to the external branch // recovery state's set of addresses to look for. for i := uint32(0); i < externalCount; i++ { keyPath := externalKeyPath(i) addr, err := scopedMgr.DeriveFromKeyPath(ns, keyPath) if err != nil && err != hdkeychain.ErrInvalidChild { return err } else if err == hdkeychain.ErrInvalidChild { scopeState.ExternalBranch.MarkInvalidChild(i) continue } scopeState.ExternalBranch.AddAddr(i, addr.Address()) } // Fetch the internal key count, which bounds the indexes we // will need to rederive. internalCount := acctProperties.InternalKeyCount // Walk through all indexes through the last internal key, // deriving each address and adding it to the internal branch // recovery state's set of addresses to look for. for i := uint32(0); i < internalCount; i++ { keyPath := internalKeyPath(i) addr, err := scopedMgr.DeriveFromKeyPath(ns, keyPath) if err != nil && err != hdkeychain.ErrInvalidChild { return err } else if err == hdkeychain.ErrInvalidChild { scopeState.InternalBranch.MarkInvalidChild(i) continue } scopeState.InternalBranch.AddAddr(i, addr.Address()) } // The key counts will point to the next key that can be // derived, so we subtract one to point to last known key. If // the key count is zero, then no addresses have been found. if externalCount > 0 { scopeState.ExternalBranch.ReportFound(externalCount - 1) } if internalCount > 0 { scopeState.InternalBranch.ReportFound(internalCount - 1) } } // In addition, we will re-add any outpoints that are known the wallet // to our global set of watched outpoints, so that we can watch them for // spends. for _, credit := range credits { _, addrs, _, err := txscript.ExtractPkScriptAddrs( credit.PkScript, rm.chainParams, ) if err != nil { return err } rm.state.AddWatchedOutPoint(&credit.OutPoint, addrs[0]) } return nil }
[ "func", "(", "rm", "*", "RecoveryManager", ")", "Resurrect", "(", "ns", "walletdb", ".", "ReadBucket", ",", "scopedMgrs", "map", "[", "waddrmgr", ".", "KeyScope", "]", "*", "waddrmgr", ".", "ScopedKeyManager", ",", "credits", "[", "]", "wtxmgr", ".", "Credit", ")", "error", "{", "// First, for each scope that we are recovering, rederive all of the", "// addresses up to the last found address known to each branch.", "for", "keyScope", ",", "scopedMgr", ":=", "range", "scopedMgrs", "{", "// Load the current account properties for this scope, using the", "// the default account number.", "// TODO(conner): rescan for all created accounts if we allow", "// users to use non-default address", "scopeState", ":=", "rm", ".", "state", ".", "StateForScope", "(", "keyScope", ")", "\n", "acctProperties", ",", "err", ":=", "scopedMgr", ".", "AccountProperties", "(", "ns", ",", "waddrmgr", ".", "DefaultAccountNum", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Fetch the external key count, which bounds the indexes we", "// will need to rederive.", "externalCount", ":=", "acctProperties", ".", "ExternalKeyCount", "\n\n", "// Walk through all indexes through the last external key,", "// deriving each address and adding it to the external branch", "// recovery state's set of addresses to look for.", "for", "i", ":=", "uint32", "(", "0", ")", ";", "i", "<", "externalCount", ";", "i", "++", "{", "keyPath", ":=", "externalKeyPath", "(", "i", ")", "\n", "addr", ",", "err", ":=", "scopedMgr", ".", "DeriveFromKeyPath", "(", "ns", ",", "keyPath", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "hdkeychain", ".", "ErrInvalidChild", "{", "return", "err", "\n", "}", "else", "if", "err", "==", "hdkeychain", ".", "ErrInvalidChild", "{", "scopeState", ".", "ExternalBranch", ".", "MarkInvalidChild", "(", "i", ")", "\n", "continue", "\n", "}", "\n\n", "scopeState", ".", "ExternalBranch", ".", "AddAddr", "(", "i", ",", "addr", ".", "Address", "(", ")", ")", "\n", "}", "\n\n", "// Fetch the internal key count, which bounds the indexes we", "// will need to rederive.", "internalCount", ":=", "acctProperties", ".", "InternalKeyCount", "\n\n", "// Walk through all indexes through the last internal key,", "// deriving each address and adding it to the internal branch", "// recovery state's set of addresses to look for.", "for", "i", ":=", "uint32", "(", "0", ")", ";", "i", "<", "internalCount", ";", "i", "++", "{", "keyPath", ":=", "internalKeyPath", "(", "i", ")", "\n", "addr", ",", "err", ":=", "scopedMgr", ".", "DeriveFromKeyPath", "(", "ns", ",", "keyPath", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "hdkeychain", ".", "ErrInvalidChild", "{", "return", "err", "\n", "}", "else", "if", "err", "==", "hdkeychain", ".", "ErrInvalidChild", "{", "scopeState", ".", "InternalBranch", ".", "MarkInvalidChild", "(", "i", ")", "\n", "continue", "\n", "}", "\n\n", "scopeState", ".", "InternalBranch", ".", "AddAddr", "(", "i", ",", "addr", ".", "Address", "(", ")", ")", "\n", "}", "\n\n", "// The key counts will point to the next key that can be", "// derived, so we subtract one to point to last known key. If", "// the key count is zero, then no addresses have been found.", "if", "externalCount", ">", "0", "{", "scopeState", ".", "ExternalBranch", ".", "ReportFound", "(", "externalCount", "-", "1", ")", "\n", "}", "\n", "if", "internalCount", ">", "0", "{", "scopeState", ".", "InternalBranch", ".", "ReportFound", "(", "internalCount", "-", "1", ")", "\n", "}", "\n", "}", "\n\n", "// In addition, we will re-add any outpoints that are known the wallet", "// to our global set of watched outpoints, so that we can watch them for", "// spends.", "for", "_", ",", "credit", ":=", "range", "credits", "{", "_", ",", "addrs", ",", "_", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "credit", ".", "PkScript", ",", "rm", ".", "chainParams", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "rm", ".", "state", ".", "AddWatchedOutPoint", "(", "&", "credit", ".", "OutPoint", ",", "addrs", "[", "0", "]", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Resurrect restores all known addresses for the provided scopes that can be // found in the walletdb namespace, in addition to restoring all outpoints that // have been previously found. This method ensures that the recovery state's // horizons properly start from the last found address of a prior recovery // attempt.
[ "Resurrect", "restores", "all", "known", "addresses", "for", "the", "provided", "scopes", "that", "can", "be", "found", "in", "the", "walletdb", "namespace", "in", "addition", "to", "restoring", "all", "outpoints", "that", "have", "been", "previously", "found", ".", "This", "method", "ensures", "that", "the", "recovery", "state", "s", "horizons", "properly", "start", "from", "the", "last", "found", "address", "of", "a", "prior", "recovery", "attempt", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L59-L144
train
btcsuite/btcwallet
wallet/recovery.go
AddToBlockBatch
func (rm *RecoveryManager) AddToBlockBatch(hash *chainhash.Hash, height int32, timestamp time.Time) { if !rm.started { log.Infof("Seed birthday surpassed, starting recovery "+ "of wallet from height=%d hash=%v with "+ "recovery-window=%d", height, *hash, rm.recoveryWindow) rm.started = true } block := wtxmgr.BlockMeta{ Block: wtxmgr.Block{ Hash: *hash, Height: height, }, Time: timestamp, } rm.blockBatch = append(rm.blockBatch, block) }
go
func (rm *RecoveryManager) AddToBlockBatch(hash *chainhash.Hash, height int32, timestamp time.Time) { if !rm.started { log.Infof("Seed birthday surpassed, starting recovery "+ "of wallet from height=%d hash=%v with "+ "recovery-window=%d", height, *hash, rm.recoveryWindow) rm.started = true } block := wtxmgr.BlockMeta{ Block: wtxmgr.Block{ Hash: *hash, Height: height, }, Time: timestamp, } rm.blockBatch = append(rm.blockBatch, block) }
[ "func", "(", "rm", "*", "RecoveryManager", ")", "AddToBlockBatch", "(", "hash", "*", "chainhash", ".", "Hash", ",", "height", "int32", ",", "timestamp", "time", ".", "Time", ")", "{", "if", "!", "rm", ".", "started", "{", "log", ".", "Infof", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "height", ",", "*", "hash", ",", "rm", ".", "recoveryWindow", ")", "\n", "rm", ".", "started", "=", "true", "\n", "}", "\n\n", "block", ":=", "wtxmgr", ".", "BlockMeta", "{", "Block", ":", "wtxmgr", ".", "Block", "{", "Hash", ":", "*", "hash", ",", "Height", ":", "height", ",", "}", ",", "Time", ":", "timestamp", ",", "}", "\n", "rm", ".", "blockBatch", "=", "append", "(", "rm", ".", "blockBatch", ",", "block", ")", "\n", "}" ]
// AddToBlockBatch appends the block information, consisting of hash and height, // to the batch of blocks to be searched.
[ "AddToBlockBatch", "appends", "the", "block", "information", "consisting", "of", "hash", "and", "height", "to", "the", "batch", "of", "blocks", "to", "be", "searched", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L148-L166
train
btcsuite/btcwallet
wallet/recovery.go
NewRecoveryState
func NewRecoveryState(recoveryWindow uint32) *RecoveryState { scopes := make(map[waddrmgr.KeyScope]*ScopeRecoveryState) return &RecoveryState{ recoveryWindow: recoveryWindow, scopes: scopes, watchedOutPoints: make(map[wire.OutPoint]btcutil.Address), } }
go
func NewRecoveryState(recoveryWindow uint32) *RecoveryState { scopes := make(map[waddrmgr.KeyScope]*ScopeRecoveryState) return &RecoveryState{ recoveryWindow: recoveryWindow, scopes: scopes, watchedOutPoints: make(map[wire.OutPoint]btcutil.Address), } }
[ "func", "NewRecoveryState", "(", "recoveryWindow", "uint32", ")", "*", "RecoveryState", "{", "scopes", ":=", "make", "(", "map", "[", "waddrmgr", ".", "KeyScope", "]", "*", "ScopeRecoveryState", ")", "\n\n", "return", "&", "RecoveryState", "{", "recoveryWindow", ":", "recoveryWindow", ",", "scopes", ":", "scopes", ",", "watchedOutPoints", ":", "make", "(", "map", "[", "wire", ".", "OutPoint", "]", "btcutil", ".", "Address", ")", ",", "}", "\n", "}" ]
// NewRecoveryState creates a new RecoveryState using the provided // recoveryWindow. Each RecoveryState that is subsequently initialized for a // particular key scope will receive the same recoveryWindow.
[ "NewRecoveryState", "creates", "a", "new", "RecoveryState", "using", "the", "provided", "recoveryWindow", ".", "Each", "RecoveryState", "that", "is", "subsequently", "initialized", "for", "a", "particular", "key", "scope", "will", "receive", "the", "same", "recoveryWindow", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L216-L224
train
btcsuite/btcwallet
wallet/recovery.go
StateForScope
func (rs *RecoveryState) StateForScope( keyScope waddrmgr.KeyScope) *ScopeRecoveryState { // If the account recovery state already exists, return it. if scopeState, ok := rs.scopes[keyScope]; ok { return scopeState } // Otherwise, initialize the recovery state for this scope with the // chosen recovery window. rs.scopes[keyScope] = NewScopeRecoveryState(rs.recoveryWindow) return rs.scopes[keyScope] }
go
func (rs *RecoveryState) StateForScope( keyScope waddrmgr.KeyScope) *ScopeRecoveryState { // If the account recovery state already exists, return it. if scopeState, ok := rs.scopes[keyScope]; ok { return scopeState } // Otherwise, initialize the recovery state for this scope with the // chosen recovery window. rs.scopes[keyScope] = NewScopeRecoveryState(rs.recoveryWindow) return rs.scopes[keyScope] }
[ "func", "(", "rs", "*", "RecoveryState", ")", "StateForScope", "(", "keyScope", "waddrmgr", ".", "KeyScope", ")", "*", "ScopeRecoveryState", "{", "// If the account recovery state already exists, return it.", "if", "scopeState", ",", "ok", ":=", "rs", ".", "scopes", "[", "keyScope", "]", ";", "ok", "{", "return", "scopeState", "\n", "}", "\n\n", "// Otherwise, initialize the recovery state for this scope with the", "// chosen recovery window.", "rs", ".", "scopes", "[", "keyScope", "]", "=", "NewScopeRecoveryState", "(", "rs", ".", "recoveryWindow", ")", "\n\n", "return", "rs", ".", "scopes", "[", "keyScope", "]", "\n", "}" ]
// StateForScope returns a ScopeRecoveryState for the provided key scope. If one // does not already exist, a new one will be generated with the RecoveryState's // recoveryWindow.
[ "StateForScope", "returns", "a", "ScopeRecoveryState", "for", "the", "provided", "key", "scope", ".", "If", "one", "does", "not", "already", "exist", "a", "new", "one", "will", "be", "generated", "with", "the", "RecoveryState", "s", "recoveryWindow", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L229-L242
train
btcsuite/btcwallet
wallet/recovery.go
AddWatchedOutPoint
func (rs *RecoveryState) AddWatchedOutPoint(outPoint *wire.OutPoint, addr btcutil.Address) { rs.watchedOutPoints[*outPoint] = addr }
go
func (rs *RecoveryState) AddWatchedOutPoint(outPoint *wire.OutPoint, addr btcutil.Address) { rs.watchedOutPoints[*outPoint] = addr }
[ "func", "(", "rs", "*", "RecoveryState", ")", "AddWatchedOutPoint", "(", "outPoint", "*", "wire", ".", "OutPoint", ",", "addr", "btcutil", ".", "Address", ")", "{", "rs", ".", "watchedOutPoints", "[", "*", "outPoint", "]", "=", "addr", "\n", "}" ]
// AddWatchedOutPoint updates the recovery state's set of known outpoints that // we will monitor for spends during recovery.
[ "AddWatchedOutPoint", "updates", "the", "recovery", "state", "s", "set", "of", "known", "outpoints", "that", "we", "will", "monitor", "for", "spends", "during", "recovery", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L252-L256
train
btcsuite/btcwallet
wallet/recovery.go
NewScopeRecoveryState
func NewScopeRecoveryState(recoveryWindow uint32) *ScopeRecoveryState { return &ScopeRecoveryState{ ExternalBranch: NewBranchRecoveryState(recoveryWindow), InternalBranch: NewBranchRecoveryState(recoveryWindow), } }
go
func NewScopeRecoveryState(recoveryWindow uint32) *ScopeRecoveryState { return &ScopeRecoveryState{ ExternalBranch: NewBranchRecoveryState(recoveryWindow), InternalBranch: NewBranchRecoveryState(recoveryWindow), } }
[ "func", "NewScopeRecoveryState", "(", "recoveryWindow", "uint32", ")", "*", "ScopeRecoveryState", "{", "return", "&", "ScopeRecoveryState", "{", "ExternalBranch", ":", "NewBranchRecoveryState", "(", "recoveryWindow", ")", ",", "InternalBranch", ":", "NewBranchRecoveryState", "(", "recoveryWindow", ")", ",", "}", "\n", "}" ]
// NewScopeRecoveryState initializes an ScopeRecoveryState with the chosen // recovery window.
[ "NewScopeRecoveryState", "initializes", "an", "ScopeRecoveryState", "with", "the", "chosen", "recovery", "window", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L273-L278
train
btcsuite/btcwallet
wallet/recovery.go
NewBranchRecoveryState
func NewBranchRecoveryState(recoveryWindow uint32) *BranchRecoveryState { return &BranchRecoveryState{ recoveryWindow: recoveryWindow, addresses: make(map[uint32]btcutil.Address), invalidChildren: make(map[uint32]struct{}), } }
go
func NewBranchRecoveryState(recoveryWindow uint32) *BranchRecoveryState { return &BranchRecoveryState{ recoveryWindow: recoveryWindow, addresses: make(map[uint32]btcutil.Address), invalidChildren: make(map[uint32]struct{}), } }
[ "func", "NewBranchRecoveryState", "(", "recoveryWindow", "uint32", ")", "*", "BranchRecoveryState", "{", "return", "&", "BranchRecoveryState", "{", "recoveryWindow", ":", "recoveryWindow", ",", "addresses", ":", "make", "(", "map", "[", "uint32", "]", "btcutil", ".", "Address", ")", ",", "invalidChildren", ":", "make", "(", "map", "[", "uint32", "]", "struct", "{", "}", ")", ",", "}", "\n", "}" ]
// NewBranchRecoveryState creates a new BranchRecoveryState that can be used to // track either the external or internal branch of an account's derivation path.
[ "NewBranchRecoveryState", "creates", "a", "new", "BranchRecoveryState", "that", "can", "be", "used", "to", "track", "either", "the", "external", "or", "internal", "branch", "of", "an", "account", "s", "derivation", "path", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L314-L320
train