repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
btcsuite/btcwallet | wallet/wallet.go | AccountOfAddress | func (w *Wallet) AccountOfAddress(a btcutil.Address) (uint32, error) {
var account uint32
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
_, account, err = w.Manager.AddrAccount(addrmgrNs, a)
return err
})
return account, err
} | go | func (w *Wallet) AccountOfAddress(a btcutil.Address) (uint32, error) {
var account uint32
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
_, account, err = w.Manager.AddrAccount(addrmgrNs, a)
return err
})
return account, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"AccountOfAddress",
"(",
"a",
"btcutil",
".",
"Address",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"var",
"account",
"uint32",
"\n",
"err",
":=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"("... | // AccountOfAddress finds the account that an address is associated with. | [
"AccountOfAddress",
"finds",
"the",
"account",
"that",
"an",
"address",
"is",
"associated",
"with",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1699-L1708 | train |
btcsuite/btcwallet | wallet/wallet.go | AddressInfo | func (w *Wallet) AddressInfo(a btcutil.Address) (waddrmgr.ManagedAddress, error) {
var managedAddress waddrmgr.ManagedAddress
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
managedAddress, err = w.Manager.Address(addrmgrNs, a)
return err
})
return managedAddress, err
} | go | func (w *Wallet) AddressInfo(a btcutil.Address) (waddrmgr.ManagedAddress, error) {
var managedAddress waddrmgr.ManagedAddress
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
managedAddress, err = w.Manager.Address(addrmgrNs, a)
return err
})
return managedAddress, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"AddressInfo",
"(",
"a",
"btcutil",
".",
"Address",
")",
"(",
"waddrmgr",
".",
"ManagedAddress",
",",
"error",
")",
"{",
"var",
"managedAddress",
"waddrmgr",
".",
"ManagedAddress",
"\n",
"err",
":=",
"walletdb",
".",
... | // AddressInfo returns detailed information regarding a wallet address. | [
"AddressInfo",
"returns",
"detailed",
"information",
"regarding",
"a",
"wallet",
"address",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1711-L1720 | train |
btcsuite/btcwallet | wallet/wallet.go | AccountNumber | func (w *Wallet) AccountNumber(scope waddrmgr.KeyScope, accountName string) (uint32, error) {
manager, err := w.Manager.FetchScopedKeyManager(scope)
if err != nil {
return 0, err
}
var account uint32
err = walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
account, err = manager.LookupAccount(addrmgrNs, accountName)
return err
})
return account, err
} | go | func (w *Wallet) AccountNumber(scope waddrmgr.KeyScope, accountName string) (uint32, error) {
manager, err := w.Manager.FetchScopedKeyManager(scope)
if err != nil {
return 0, err
}
var account uint32
err = walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
account, err = manager.LookupAccount(addrmgrNs, accountName)
return err
})
return account, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"AccountNumber",
"(",
"scope",
"waddrmgr",
".",
"KeyScope",
",",
"accountName",
"string",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"manager",
",",
"err",
":=",
"w",
".",
"Manager",
".",
"FetchScopedKeyManager",
"(... | // AccountNumber returns the account number for an account name under a
// particular key scope. | [
"AccountNumber",
"returns",
"the",
"account",
"number",
"for",
"an",
"account",
"name",
"under",
"a",
"particular",
"key",
"scope",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1724-L1738 | train |
btcsuite/btcwallet | wallet/wallet.go | AccountProperties | func (w *Wallet) AccountProperties(scope waddrmgr.KeyScope, acct uint32) (*waddrmgr.AccountProperties, error) {
manager, err := w.Manager.FetchScopedKeyManager(scope)
if err != nil {
return nil, err
}
var props *waddrmgr.AccountProperties
err = walletdb.View(w.db, func(tx walletdb.ReadTx) error {
waddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
props, err = manager.AccountProperties(waddrmgrNs, acct)
return err
})
return props, err
} | go | func (w *Wallet) AccountProperties(scope waddrmgr.KeyScope, acct uint32) (*waddrmgr.AccountProperties, error) {
manager, err := w.Manager.FetchScopedKeyManager(scope)
if err != nil {
return nil, err
}
var props *waddrmgr.AccountProperties
err = walletdb.View(w.db, func(tx walletdb.ReadTx) error {
waddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
props, err = manager.AccountProperties(waddrmgrNs, acct)
return err
})
return props, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"AccountProperties",
"(",
"scope",
"waddrmgr",
".",
"KeyScope",
",",
"acct",
"uint32",
")",
"(",
"*",
"waddrmgr",
".",
"AccountProperties",
",",
"error",
")",
"{",
"manager",
",",
"err",
":=",
"w",
".",
"Manager",
... | // AccountProperties returns the properties of an account, including address
// indexes and name. It first fetches the desynced information from the address
// manager, then updates the indexes based on the address pools. | [
"AccountProperties",
"returns",
"the",
"properties",
"of",
"an",
"account",
"including",
"address",
"indexes",
"and",
"name",
".",
"It",
"first",
"fetches",
"the",
"desynced",
"information",
"from",
"the",
"address",
"manager",
"then",
"updates",
"the",
"indexes",... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1760-L1774 | train |
btcsuite/btcwallet | wallet/wallet.go | RenameAccount | func (w *Wallet) RenameAccount(scope waddrmgr.KeyScope, account uint32, newName string) error {
manager, err := w.Manager.FetchScopedKeyManager(scope)
if err != nil {
return err
}
var props *waddrmgr.AccountProperties
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
err := manager.RenameAccount(addrmgrNs, account, newName)
if err != nil {
return err
}
props, err = manager.AccountProperties(addrmgrNs, account)
return err
})
if err == nil {
w.NtfnServer.notifyAccountProperties(props)
}
return err
} | go | func (w *Wallet) RenameAccount(scope waddrmgr.KeyScope, account uint32, newName string) error {
manager, err := w.Manager.FetchScopedKeyManager(scope)
if err != nil {
return err
}
var props *waddrmgr.AccountProperties
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
err := manager.RenameAccount(addrmgrNs, account, newName)
if err != nil {
return err
}
props, err = manager.AccountProperties(addrmgrNs, account)
return err
})
if err == nil {
w.NtfnServer.notifyAccountProperties(props)
}
return err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"RenameAccount",
"(",
"scope",
"waddrmgr",
".",
"KeyScope",
",",
"account",
"uint32",
",",
"newName",
"string",
")",
"error",
"{",
"manager",
",",
"err",
":=",
"w",
".",
"Manager",
".",
"FetchScopedKeyManager",
"(",
... | // RenameAccount sets the name for an account number to newName. | [
"RenameAccount",
"sets",
"the",
"name",
"for",
"an",
"account",
"number",
"to",
"newName",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1777-L1797 | train |
btcsuite/btcwallet | wallet/wallet.go | ListSinceBlock | func (w *Wallet) ListSinceBlock(start, end, syncHeight int32) ([]btcjson.ListTransactionsResult, error) {
txList := []btcjson.ListTransactionsResult{}
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
rangeFn := func(details []wtxmgr.TxDetails) (bool, error) {
for _, detail := range details {
jsonResults := listTransactions(tx, &detail,
w.Manager, syncHeight, w.chainParams)
txList = append(txList, jsonResults...)
}
return false, nil
}
return w.TxStore.RangeTransactions(txmgrNs, start, end, rangeFn)
})
return txList, err
} | go | func (w *Wallet) ListSinceBlock(start, end, syncHeight int32) ([]btcjson.ListTransactionsResult, error) {
txList := []btcjson.ListTransactionsResult{}
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
rangeFn := func(details []wtxmgr.TxDetails) (bool, error) {
for _, detail := range details {
jsonResults := listTransactions(tx, &detail,
w.Manager, syncHeight, w.chainParams)
txList = append(txList, jsonResults...)
}
return false, nil
}
return w.TxStore.RangeTransactions(txmgrNs, start, end, rangeFn)
})
return txList, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"ListSinceBlock",
"(",
"start",
",",
"end",
",",
"syncHeight",
"int32",
")",
"(",
"[",
"]",
"btcjson",
".",
"ListTransactionsResult",
",",
"error",
")",
"{",
"txList",
":=",
"[",
"]",
"btcjson",
".",
"ListTransaction... | // ListSinceBlock returns a slice of objects with details about transactions
// since the given block. If the block is -1 then all transactions are included.
// This is intended to be used for listsinceblock RPC replies. | [
"ListSinceBlock",
"returns",
"a",
"slice",
"of",
"objects",
"with",
"details",
"about",
"transactions",
"since",
"the",
"given",
"block",
".",
"If",
"the",
"block",
"is",
"-",
"1",
"then",
"all",
"transactions",
"are",
"included",
".",
"This",
"is",
"intende... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L2014-L2031 | train |
btcsuite/btcwallet | wallet/wallet.go | ListTransactions | func (w *Wallet) ListTransactions(from, count int) ([]btcjson.ListTransactionsResult, error) {
txList := []btcjson.ListTransactionsResult{}
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
// Get current block. The block height used for calculating
// the number of tx confirmations.
syncBlock := w.Manager.SyncedTo()
// Need to skip the first from transactions, and after those, only
// include the next count transactions.
skipped := 0
n := 0
rangeFn := func(details []wtxmgr.TxDetails) (bool, error) {
// Iterate over transactions at this height in reverse order.
// This does nothing for unmined transactions, which are
// unsorted, but it will process mined transactions in the
// reverse order they were marked mined.
for i := len(details) - 1; i >= 0; i-- {
if from > skipped {
skipped++
continue
}
n++
if n > count {
return true, nil
}
jsonResults := listTransactions(tx, &details[i],
w.Manager, syncBlock.Height, w.chainParams)
txList = append(txList, jsonResults...)
if len(jsonResults) > 0 {
n++
}
}
return false, nil
}
// Return newer results first by starting at mempool height and working
// down to the genesis block.
return w.TxStore.RangeTransactions(txmgrNs, -1, 0, rangeFn)
})
return txList, err
} | go | func (w *Wallet) ListTransactions(from, count int) ([]btcjson.ListTransactionsResult, error) {
txList := []btcjson.ListTransactionsResult{}
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
// Get current block. The block height used for calculating
// the number of tx confirmations.
syncBlock := w.Manager.SyncedTo()
// Need to skip the first from transactions, and after those, only
// include the next count transactions.
skipped := 0
n := 0
rangeFn := func(details []wtxmgr.TxDetails) (bool, error) {
// Iterate over transactions at this height in reverse order.
// This does nothing for unmined transactions, which are
// unsorted, but it will process mined transactions in the
// reverse order they were marked mined.
for i := len(details) - 1; i >= 0; i-- {
if from > skipped {
skipped++
continue
}
n++
if n > count {
return true, nil
}
jsonResults := listTransactions(tx, &details[i],
w.Manager, syncBlock.Height, w.chainParams)
txList = append(txList, jsonResults...)
if len(jsonResults) > 0 {
n++
}
}
return false, nil
}
// Return newer results first by starting at mempool height and working
// down to the genesis block.
return w.TxStore.RangeTransactions(txmgrNs, -1, 0, rangeFn)
})
return txList, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"ListTransactions",
"(",
"from",
",",
"count",
"int",
")",
"(",
"[",
"]",
"btcjson",
".",
"ListTransactionsResult",
",",
"error",
")",
"{",
"txList",
":=",
"[",
"]",
"btcjson",
".",
"ListTransactionsResult",
"{",
"}"... | // ListTransactions returns a slice of objects with details about a recorded
// transaction. This is intended to be used for listtransactions RPC
// replies. | [
"ListTransactions",
"returns",
"a",
"slice",
"of",
"objects",
"with",
"details",
"about",
"a",
"recorded",
"transaction",
".",
"This",
"is",
"intended",
"to",
"be",
"used",
"for",
"listtransactions",
"RPC",
"replies",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L2036-L2084 | train |
btcsuite/btcwallet | wallet/wallet.go | ListAddressTransactions | func (w *Wallet) ListAddressTransactions(pkHashes map[string]struct{}) ([]btcjson.ListTransactionsResult, error) {
txList := []btcjson.ListTransactionsResult{}
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
// Get current block. The block height used for calculating
// the number of tx confirmations.
syncBlock := w.Manager.SyncedTo()
rangeFn := func(details []wtxmgr.TxDetails) (bool, error) {
loopDetails:
for i := range details {
detail := &details[i]
for _, cred := range detail.Credits {
pkScript := detail.MsgTx.TxOut[cred.Index].PkScript
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
pkScript, w.chainParams)
if err != nil || len(addrs) != 1 {
continue
}
apkh, ok := addrs[0].(*btcutil.AddressPubKeyHash)
if !ok {
continue
}
_, ok = pkHashes[string(apkh.ScriptAddress())]
if !ok {
continue
}
jsonResults := listTransactions(tx, detail,
w.Manager, syncBlock.Height, w.chainParams)
if err != nil {
return false, err
}
txList = append(txList, jsonResults...)
continue loopDetails
}
}
return false, nil
}
return w.TxStore.RangeTransactions(txmgrNs, 0, -1, rangeFn)
})
return txList, err
} | go | func (w *Wallet) ListAddressTransactions(pkHashes map[string]struct{}) ([]btcjson.ListTransactionsResult, error) {
txList := []btcjson.ListTransactionsResult{}
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
// Get current block. The block height used for calculating
// the number of tx confirmations.
syncBlock := w.Manager.SyncedTo()
rangeFn := func(details []wtxmgr.TxDetails) (bool, error) {
loopDetails:
for i := range details {
detail := &details[i]
for _, cred := range detail.Credits {
pkScript := detail.MsgTx.TxOut[cred.Index].PkScript
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
pkScript, w.chainParams)
if err != nil || len(addrs) != 1 {
continue
}
apkh, ok := addrs[0].(*btcutil.AddressPubKeyHash)
if !ok {
continue
}
_, ok = pkHashes[string(apkh.ScriptAddress())]
if !ok {
continue
}
jsonResults := listTransactions(tx, detail,
w.Manager, syncBlock.Height, w.chainParams)
if err != nil {
return false, err
}
txList = append(txList, jsonResults...)
continue loopDetails
}
}
return false, nil
}
return w.TxStore.RangeTransactions(txmgrNs, 0, -1, rangeFn)
})
return txList, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"ListAddressTransactions",
"(",
"pkHashes",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"(",
"[",
"]",
"btcjson",
".",
"ListTransactionsResult",
",",
"error",
")",
"{",
"txList",
":=",
"[",
"]",
"btcjson",
... | // ListAddressTransactions returns a slice of objects with details about
// recorded transactions to or from any address belonging to a set. This is
// intended to be used for listaddresstransactions RPC replies. | [
"ListAddressTransactions",
"returns",
"a",
"slice",
"of",
"objects",
"with",
"details",
"about",
"recorded",
"transactions",
"to",
"or",
"from",
"any",
"address",
"belonging",
"to",
"a",
"set",
".",
"This",
"is",
"intended",
"to",
"be",
"used",
"for",
"listadd... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L2089-L2133 | train |
btcsuite/btcwallet | wallet/wallet.go | AccountBalances | func (w *Wallet) AccountBalances(scope waddrmgr.KeyScope,
requiredConfs int32) ([]AccountBalanceResult, error) {
manager, err := w.Manager.FetchScopedKeyManager(scope)
if err != nil {
return nil, err
}
var results []AccountBalanceResult
err = walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
syncBlock := w.Manager.SyncedTo()
// Fill out all account info except for the balances.
lastAcct, err := manager.LastAccount(addrmgrNs)
if err != nil {
return err
}
results = make([]AccountBalanceResult, lastAcct+2)
for i := range results[:len(results)-1] {
accountName, err := manager.AccountName(addrmgrNs, uint32(i))
if err != nil {
return err
}
results[i].AccountNumber = uint32(i)
results[i].AccountName = accountName
}
results[len(results)-1].AccountNumber = waddrmgr.ImportedAddrAccount
results[len(results)-1].AccountName = waddrmgr.ImportedAddrAccountName
// Fetch all unspent outputs, and iterate over them tallying each
// account's balance where the output script pays to an account address
// and the required number of confirmations is met.
unspentOutputs, err := w.TxStore.UnspentOutputs(txmgrNs)
if err != nil {
return err
}
for i := range unspentOutputs {
output := &unspentOutputs[i]
if !confirmed(requiredConfs, output.Height, syncBlock.Height) {
continue
}
if output.FromCoinBase && !confirmed(int32(w.ChainParams().CoinbaseMaturity),
output.Height, syncBlock.Height) {
continue
}
_, addrs, _, err := txscript.ExtractPkScriptAddrs(output.PkScript, w.chainParams)
if err != nil || len(addrs) == 0 {
continue
}
outputAcct, err := manager.AddrAccount(addrmgrNs, addrs[0])
if err != nil {
continue
}
switch {
case outputAcct == waddrmgr.ImportedAddrAccount:
results[len(results)-1].AccountBalance += output.Amount
case outputAcct > lastAcct:
return errors.New("waddrmgr.Manager.AddrAccount returned account " +
"beyond recorded last account")
default:
results[outputAcct].AccountBalance += output.Amount
}
}
return nil
})
return results, err
} | go | func (w *Wallet) AccountBalances(scope waddrmgr.KeyScope,
requiredConfs int32) ([]AccountBalanceResult, error) {
manager, err := w.Manager.FetchScopedKeyManager(scope)
if err != nil {
return nil, err
}
var results []AccountBalanceResult
err = walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
syncBlock := w.Manager.SyncedTo()
// Fill out all account info except for the balances.
lastAcct, err := manager.LastAccount(addrmgrNs)
if err != nil {
return err
}
results = make([]AccountBalanceResult, lastAcct+2)
for i := range results[:len(results)-1] {
accountName, err := manager.AccountName(addrmgrNs, uint32(i))
if err != nil {
return err
}
results[i].AccountNumber = uint32(i)
results[i].AccountName = accountName
}
results[len(results)-1].AccountNumber = waddrmgr.ImportedAddrAccount
results[len(results)-1].AccountName = waddrmgr.ImportedAddrAccountName
// Fetch all unspent outputs, and iterate over them tallying each
// account's balance where the output script pays to an account address
// and the required number of confirmations is met.
unspentOutputs, err := w.TxStore.UnspentOutputs(txmgrNs)
if err != nil {
return err
}
for i := range unspentOutputs {
output := &unspentOutputs[i]
if !confirmed(requiredConfs, output.Height, syncBlock.Height) {
continue
}
if output.FromCoinBase && !confirmed(int32(w.ChainParams().CoinbaseMaturity),
output.Height, syncBlock.Height) {
continue
}
_, addrs, _, err := txscript.ExtractPkScriptAddrs(output.PkScript, w.chainParams)
if err != nil || len(addrs) == 0 {
continue
}
outputAcct, err := manager.AddrAccount(addrmgrNs, addrs[0])
if err != nil {
continue
}
switch {
case outputAcct == waddrmgr.ImportedAddrAccount:
results[len(results)-1].AccountBalance += output.Amount
case outputAcct > lastAcct:
return errors.New("waddrmgr.Manager.AddrAccount returned account " +
"beyond recorded last account")
default:
results[outputAcct].AccountBalance += output.Amount
}
}
return nil
})
return results, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"AccountBalances",
"(",
"scope",
"waddrmgr",
".",
"KeyScope",
",",
"requiredConfs",
"int32",
")",
"(",
"[",
"]",
"AccountBalanceResult",
",",
"error",
")",
"{",
"manager",
",",
"err",
":=",
"w",
".",
"Manager",
".",
... | // AccountBalances returns all accounts in the wallet and their balances.
// Balances are determined by excluding transactions that have not met
// requiredConfs confirmations. | [
"AccountBalances",
"returns",
"all",
"accounts",
"in",
"the",
"wallet",
"and",
"their",
"balances",
".",
"Balances",
"are",
"determined",
"by",
"excluding",
"transactions",
"that",
"have",
"not",
"met",
"requiredConfs",
"confirmations",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L2406-L2475 | train |
btcsuite/btcwallet | wallet/wallet.go | DumpPrivKeys | func (w *Wallet) DumpPrivKeys() ([]string, error) {
var privkeys []string
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
// Iterate over each active address, appending the private key to
// privkeys.
return w.Manager.ForEachActiveAddress(addrmgrNs, func(addr btcutil.Address) error {
ma, err := w.Manager.Address(addrmgrNs, addr)
if err != nil {
return err
}
// Only those addresses with keys needed.
pka, ok := ma.(waddrmgr.ManagedPubKeyAddress)
if !ok {
return nil
}
wif, err := pka.ExportPrivKey()
if err != nil {
// It would be nice to zero out the array here. However,
// since strings in go are immutable, and we have no
// control over the caller I don't think we can. :(
return err
}
privkeys = append(privkeys, wif.String())
return nil
})
})
return privkeys, err
} | go | func (w *Wallet) DumpPrivKeys() ([]string, error) {
var privkeys []string
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
// Iterate over each active address, appending the private key to
// privkeys.
return w.Manager.ForEachActiveAddress(addrmgrNs, func(addr btcutil.Address) error {
ma, err := w.Manager.Address(addrmgrNs, addr)
if err != nil {
return err
}
// Only those addresses with keys needed.
pka, ok := ma.(waddrmgr.ManagedPubKeyAddress)
if !ok {
return nil
}
wif, err := pka.ExportPrivKey()
if err != nil {
// It would be nice to zero out the array here. However,
// since strings in go are immutable, and we have no
// control over the caller I don't think we can. :(
return err
}
privkeys = append(privkeys, wif.String())
return nil
})
})
return privkeys, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"DumpPrivKeys",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"privkeys",
"[",
"]",
"string",
"\n",
"err",
":=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"wa... | // DumpPrivKeys returns the WIF-encoded private keys for all addresses with
// private keys in a wallet. | [
"DumpPrivKeys",
"returns",
"the",
"WIF",
"-",
"encoded",
"private",
"keys",
"for",
"all",
"addresses",
"with",
"private",
"keys",
"in",
"a",
"wallet",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L2657-L2687 | train |
btcsuite/btcwallet | wallet/wallet.go | DumpWIFPrivateKey | func (w *Wallet) DumpWIFPrivateKey(addr btcutil.Address) (string, error) {
var maddr waddrmgr.ManagedAddress
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
waddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
// Get private key from wallet if it exists.
var err error
maddr, err = w.Manager.Address(waddrmgrNs, addr)
return err
})
if err != nil {
return "", err
}
pka, ok := maddr.(waddrmgr.ManagedPubKeyAddress)
if !ok {
return "", fmt.Errorf("address %s is not a key type", addr)
}
wif, err := pka.ExportPrivKey()
if err != nil {
return "", err
}
return wif.String(), nil
} | go | func (w *Wallet) DumpWIFPrivateKey(addr btcutil.Address) (string, error) {
var maddr waddrmgr.ManagedAddress
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
waddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
// Get private key from wallet if it exists.
var err error
maddr, err = w.Manager.Address(waddrmgrNs, addr)
return err
})
if err != nil {
return "", err
}
pka, ok := maddr.(waddrmgr.ManagedPubKeyAddress)
if !ok {
return "", fmt.Errorf("address %s is not a key type", addr)
}
wif, err := pka.ExportPrivKey()
if err != nil {
return "", err
}
return wif.String(), nil
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"DumpWIFPrivateKey",
"(",
"addr",
"btcutil",
".",
"Address",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"maddr",
"waddrmgr",
".",
"ManagedAddress",
"\n",
"err",
":=",
"walletdb",
".",
"View",
"(",
"w",
".",... | // DumpWIFPrivateKey returns the WIF encoded private key for a
// single wallet address. | [
"DumpWIFPrivateKey",
"returns",
"the",
"WIF",
"encoded",
"private",
"key",
"for",
"a",
"single",
"wallet",
"address",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L2691-L2714 | train |
btcsuite/btcwallet | wallet/wallet.go | LockedOutpoint | func (w *Wallet) LockedOutpoint(op wire.OutPoint) bool {
_, locked := w.lockedOutpoints[op]
return locked
} | go | func (w *Wallet) LockedOutpoint(op wire.OutPoint) bool {
_, locked := w.lockedOutpoints[op]
return locked
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"LockedOutpoint",
"(",
"op",
"wire",
".",
"OutPoint",
")",
"bool",
"{",
"_",
",",
"locked",
":=",
"w",
".",
"lockedOutpoints",
"[",
"op",
"]",
"\n",
"return",
"locked",
"\n",
"}"
] | // LockedOutpoint returns whether an outpoint has been marked as locked and
// should not be used as an input for created transactions. | [
"LockedOutpoint",
"returns",
"whether",
"an",
"outpoint",
"has",
"been",
"marked",
"as",
"locked",
"and",
"should",
"not",
"be",
"used",
"as",
"an",
"input",
"for",
"created",
"transactions",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L2822-L2825 | train |
btcsuite/btcwallet | wallet/wallet.go | UnlockOutpoint | func (w *Wallet) UnlockOutpoint(op wire.OutPoint) {
delete(w.lockedOutpoints, op)
} | go | func (w *Wallet) UnlockOutpoint(op wire.OutPoint) {
delete(w.lockedOutpoints, op)
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"UnlockOutpoint",
"(",
"op",
"wire",
".",
"OutPoint",
")",
"{",
"delete",
"(",
"w",
".",
"lockedOutpoints",
",",
"op",
")",
"\n",
"}"
] | // UnlockOutpoint marks an outpoint as unlocked, that is, it may be used as an
// input for newly created transactions. | [
"UnlockOutpoint",
"marks",
"an",
"outpoint",
"as",
"unlocked",
"that",
"is",
"it",
"may",
"be",
"used",
"as",
"an",
"input",
"for",
"newly",
"created",
"transactions",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L2835-L2837 | train |
btcsuite/btcwallet | wallet/wallet.go | LockedOutpoints | func (w *Wallet) LockedOutpoints() []btcjson.TransactionInput {
locked := make([]btcjson.TransactionInput, len(w.lockedOutpoints))
i := 0
for op := range w.lockedOutpoints {
locked[i] = btcjson.TransactionInput{
Txid: op.Hash.String(),
Vout: op.Index,
}
i++
}
return locked
} | go | func (w *Wallet) LockedOutpoints() []btcjson.TransactionInput {
locked := make([]btcjson.TransactionInput, len(w.lockedOutpoints))
i := 0
for op := range w.lockedOutpoints {
locked[i] = btcjson.TransactionInput{
Txid: op.Hash.String(),
Vout: op.Index,
}
i++
}
return locked
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"LockedOutpoints",
"(",
")",
"[",
"]",
"btcjson",
".",
"TransactionInput",
"{",
"locked",
":=",
"make",
"(",
"[",
"]",
"btcjson",
".",
"TransactionInput",
",",
"len",
"(",
"w",
".",
"lockedOutpoints",
")",
")",
"\n... | // LockedOutpoints returns a slice of currently locked outpoints. This is
// intended to be used by marshaling the result as a JSON array for
// listlockunspent RPC results. | [
"LockedOutpoints",
"returns",
"a",
"slice",
"of",
"currently",
"locked",
"outpoints",
".",
"This",
"is",
"intended",
"to",
"be",
"used",
"by",
"marshaling",
"the",
"result",
"as",
"a",
"JSON",
"array",
"for",
"listlockunspent",
"RPC",
"results",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L2848-L2859 | train |
btcsuite/btcwallet | wallet/wallet.go | resendUnminedTxs | func (w *Wallet) resendUnminedTxs() {
var txs []*wire.MsgTx
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
var err error
txs, err = w.TxStore.UnminedTxs(txmgrNs)
return err
})
if err != nil {
log.Errorf("Unable to retrieve unconfirmed transactions to "+
"resend: %v", err)
return
}
for _, tx := range txs {
txHash, err := w.publishTransaction(tx)
if err != nil {
log.Debugf("Unable to rebroadcast transaction %v: %v",
tx.TxHash(), err)
continue
}
log.Debugf("Successfully rebroadcast unconfirmed transaction %v",
txHash)
}
} | go | func (w *Wallet) resendUnminedTxs() {
var txs []*wire.MsgTx
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
var err error
txs, err = w.TxStore.UnminedTxs(txmgrNs)
return err
})
if err != nil {
log.Errorf("Unable to retrieve unconfirmed transactions to "+
"resend: %v", err)
return
}
for _, tx := range txs {
txHash, err := w.publishTransaction(tx)
if err != nil {
log.Debugf("Unable to rebroadcast transaction %v: %v",
tx.TxHash(), err)
continue
}
log.Debugf("Successfully rebroadcast unconfirmed transaction %v",
txHash)
}
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"resendUnminedTxs",
"(",
")",
"{",
"var",
"txs",
"[",
"]",
"*",
"wire",
".",
"MsgTx",
"\n",
"err",
":=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
... | // resendUnminedTxs iterates through all transactions that spend from wallet
// credits that are not known to have been mined into a block, and attempts
// to send each to the chain server for relay. | [
"resendUnminedTxs",
"iterates",
"through",
"all",
"transactions",
"that",
"spend",
"from",
"wallet",
"credits",
"that",
"are",
"not",
"known",
"to",
"have",
"been",
"mined",
"into",
"a",
"block",
"and",
"attempts",
"to",
"send",
"each",
"to",
"the",
"chain",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L2864-L2889 | train |
btcsuite/btcwallet | wallet/wallet.go | SortedActivePaymentAddresses | func (w *Wallet) SortedActivePaymentAddresses() ([]string, error) {
var addrStrs []string
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
return w.Manager.ForEachActiveAddress(addrmgrNs, func(addr btcutil.Address) error {
addrStrs = append(addrStrs, addr.EncodeAddress())
return nil
})
})
if err != nil {
return nil, err
}
sort.Sort(sort.StringSlice(addrStrs))
return addrStrs, nil
} | go | func (w *Wallet) SortedActivePaymentAddresses() ([]string, error) {
var addrStrs []string
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
return w.Manager.ForEachActiveAddress(addrmgrNs, func(addr btcutil.Address) error {
addrStrs = append(addrStrs, addr.EncodeAddress())
return nil
})
})
if err != nil {
return nil, err
}
sort.Sort(sort.StringSlice(addrStrs))
return addrStrs, nil
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"SortedActivePaymentAddresses",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"addrStrs",
"[",
"]",
"string",
"\n",
"err",
":=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(... | // SortedActivePaymentAddresses returns a slice of all active payment
// addresses in a wallet. | [
"SortedActivePaymentAddresses",
"returns",
"a",
"slice",
"of",
"all",
"active",
"payment",
"addresses",
"in",
"a",
"wallet",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L2893-L2908 | train |
btcsuite/btcwallet | wallet/wallet.go | NewAddress | func (w *Wallet) NewAddress(account uint32,
scope waddrmgr.KeyScope) (btcutil.Address, error) {
chainClient, err := w.requireChainClient()
if err != nil {
return nil, err
}
var (
addr btcutil.Address
props *waddrmgr.AccountProperties
)
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
var err error
addr, props, err = w.newAddress(addrmgrNs, account, scope)
return err
})
if err != nil {
return nil, err
}
// Notify the rpc server about the newly created address.
err = chainClient.NotifyReceived([]btcutil.Address{addr})
if err != nil {
return nil, err
}
w.NtfnServer.notifyAccountProperties(props)
return addr, nil
} | go | func (w *Wallet) NewAddress(account uint32,
scope waddrmgr.KeyScope) (btcutil.Address, error) {
chainClient, err := w.requireChainClient()
if err != nil {
return nil, err
}
var (
addr btcutil.Address
props *waddrmgr.AccountProperties
)
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
var err error
addr, props, err = w.newAddress(addrmgrNs, account, scope)
return err
})
if err != nil {
return nil, err
}
// Notify the rpc server about the newly created address.
err = chainClient.NotifyReceived([]btcutil.Address{addr})
if err != nil {
return nil, err
}
w.NtfnServer.notifyAccountProperties(props)
return addr, nil
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"NewAddress",
"(",
"account",
"uint32",
",",
"scope",
"waddrmgr",
".",
"KeyScope",
")",
"(",
"btcutil",
".",
"Address",
",",
"error",
")",
"{",
"chainClient",
",",
"err",
":=",
"w",
".",
"requireChainClient",
"(",
... | // NewAddress returns the next external chained address for a wallet. | [
"NewAddress",
"returns",
"the",
"next",
"external",
"chained",
"address",
"for",
"a",
"wallet",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L2911-L2942 | train |
btcsuite/btcwallet | wallet/wallet.go | NewChangeAddress | func (w *Wallet) NewChangeAddress(account uint32,
scope waddrmgr.KeyScope) (btcutil.Address, error) {
chainClient, err := w.requireChainClient()
if err != nil {
return nil, err
}
var addr btcutil.Address
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
var err error
addr, err = w.newChangeAddress(addrmgrNs, account)
return err
})
if err != nil {
return nil, err
}
// Notify the rpc server about the newly created address.
err = chainClient.NotifyReceived([]btcutil.Address{addr})
if err != nil {
return nil, err
}
return addr, nil
} | go | func (w *Wallet) NewChangeAddress(account uint32,
scope waddrmgr.KeyScope) (btcutil.Address, error) {
chainClient, err := w.requireChainClient()
if err != nil {
return nil, err
}
var addr btcutil.Address
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
var err error
addr, err = w.newChangeAddress(addrmgrNs, account)
return err
})
if err != nil {
return nil, err
}
// Notify the rpc server about the newly created address.
err = chainClient.NotifyReceived([]btcutil.Address{addr})
if err != nil {
return nil, err
}
return addr, nil
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"NewChangeAddress",
"(",
"account",
"uint32",
",",
"scope",
"waddrmgr",
".",
"KeyScope",
")",
"(",
"btcutil",
".",
"Address",
",",
"error",
")",
"{",
"chainClient",
",",
"err",
":=",
"w",
".",
"requireChainClient",
"... | // NewChangeAddress returns a new change address for a wallet. | [
"NewChangeAddress",
"returns",
"a",
"new",
"change",
"address",
"for",
"a",
"wallet",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L2969-L2995 | train |
btcsuite/btcwallet | wallet/wallet.go | confirmed | func confirmed(minconf, txHeight, curHeight int32) bool {
return confirms(txHeight, curHeight) >= minconf
} | go | func confirmed(minconf, txHeight, curHeight int32) bool {
return confirms(txHeight, curHeight) >= minconf
} | [
"func",
"confirmed",
"(",
"minconf",
",",
"txHeight",
",",
"curHeight",
"int32",
")",
"bool",
"{",
"return",
"confirms",
"(",
"txHeight",
",",
"curHeight",
")",
">=",
"minconf",
"\n",
"}"
] | // confirmed checks whether a transaction at height txHeight has met minconf
// confirmations for a blockchain at height curHeight. | [
"confirmed",
"checks",
"whether",
"a",
"transaction",
"at",
"height",
"txHeight",
"has",
"met",
"minconf",
"confirmations",
"for",
"a",
"blockchain",
"at",
"height",
"curHeight",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L3026-L3028 | train |
btcsuite/btcwallet | wallet/wallet.go | TotalReceivedForAccounts | func (w *Wallet) TotalReceivedForAccounts(scope waddrmgr.KeyScope,
minConf int32) ([]AccountTotalReceivedResult, error) {
manager, err := w.Manager.FetchScopedKeyManager(scope)
if err != nil {
return nil, err
}
var results []AccountTotalReceivedResult
err = walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
syncBlock := w.Manager.SyncedTo()
err := manager.ForEachAccount(addrmgrNs, func(account uint32) error {
accountName, err := manager.AccountName(addrmgrNs, account)
if err != nil {
return err
}
results = append(results, AccountTotalReceivedResult{
AccountNumber: account,
AccountName: accountName,
})
return nil
})
if err != nil {
return err
}
var stopHeight int32
if minConf > 0 {
stopHeight = syncBlock.Height - minConf + 1
} else {
stopHeight = -1
}
rangeFn := func(details []wtxmgr.TxDetails) (bool, error) {
for i := range details {
detail := &details[i]
for _, cred := range detail.Credits {
pkScript := detail.MsgTx.TxOut[cred.Index].PkScript
var outputAcct uint32
_, addrs, _, err := txscript.ExtractPkScriptAddrs(pkScript, w.chainParams)
if err == nil && len(addrs) > 0 {
_, outputAcct, err = w.Manager.AddrAccount(addrmgrNs, addrs[0])
}
if err == nil {
acctIndex := int(outputAcct)
if outputAcct == waddrmgr.ImportedAddrAccount {
acctIndex = len(results) - 1
}
res := &results[acctIndex]
res.TotalReceived += cred.Amount
res.LastConfirmation = confirms(
detail.Block.Height, syncBlock.Height)
}
}
}
return false, nil
}
return w.TxStore.RangeTransactions(txmgrNs, 0, stopHeight, rangeFn)
})
return results, err
} | go | func (w *Wallet) TotalReceivedForAccounts(scope waddrmgr.KeyScope,
minConf int32) ([]AccountTotalReceivedResult, error) {
manager, err := w.Manager.FetchScopedKeyManager(scope)
if err != nil {
return nil, err
}
var results []AccountTotalReceivedResult
err = walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
syncBlock := w.Manager.SyncedTo()
err := manager.ForEachAccount(addrmgrNs, func(account uint32) error {
accountName, err := manager.AccountName(addrmgrNs, account)
if err != nil {
return err
}
results = append(results, AccountTotalReceivedResult{
AccountNumber: account,
AccountName: accountName,
})
return nil
})
if err != nil {
return err
}
var stopHeight int32
if minConf > 0 {
stopHeight = syncBlock.Height - minConf + 1
} else {
stopHeight = -1
}
rangeFn := func(details []wtxmgr.TxDetails) (bool, error) {
for i := range details {
detail := &details[i]
for _, cred := range detail.Credits {
pkScript := detail.MsgTx.TxOut[cred.Index].PkScript
var outputAcct uint32
_, addrs, _, err := txscript.ExtractPkScriptAddrs(pkScript, w.chainParams)
if err == nil && len(addrs) > 0 {
_, outputAcct, err = w.Manager.AddrAccount(addrmgrNs, addrs[0])
}
if err == nil {
acctIndex := int(outputAcct)
if outputAcct == waddrmgr.ImportedAddrAccount {
acctIndex = len(results) - 1
}
res := &results[acctIndex]
res.TotalReceived += cred.Amount
res.LastConfirmation = confirms(
detail.Block.Height, syncBlock.Height)
}
}
}
return false, nil
}
return w.TxStore.RangeTransactions(txmgrNs, 0, stopHeight, rangeFn)
})
return results, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"TotalReceivedForAccounts",
"(",
"scope",
"waddrmgr",
".",
"KeyScope",
",",
"minConf",
"int32",
")",
"(",
"[",
"]",
"AccountTotalReceivedResult",
",",
"error",
")",
"{",
"manager",
",",
"err",
":=",
"w",
".",
"Manager"... | // TotalReceivedForAccounts iterates through a wallet's transaction history,
// returning the total amount of Bitcoin received for all accounts. | [
"TotalReceivedForAccounts",
"iterates",
"through",
"a",
"wallet",
"s",
"transaction",
"history",
"returning",
"the",
"total",
"amount",
"of",
"Bitcoin",
"received",
"for",
"all",
"accounts",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L3053-L3118 | train |
btcsuite/btcwallet | wallet/wallet.go | TotalReceivedForAddr | func (w *Wallet) TotalReceivedForAddr(addr btcutil.Address, minConf int32) (btcutil.Amount, error) {
var amount btcutil.Amount
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
syncBlock := w.Manager.SyncedTo()
var (
addrStr = addr.EncodeAddress()
stopHeight int32
)
if minConf > 0 {
stopHeight = syncBlock.Height - minConf + 1
} else {
stopHeight = -1
}
rangeFn := func(details []wtxmgr.TxDetails) (bool, error) {
for i := range details {
detail := &details[i]
for _, cred := range detail.Credits {
pkScript := detail.MsgTx.TxOut[cred.Index].PkScript
_, addrs, _, err := txscript.ExtractPkScriptAddrs(pkScript,
w.chainParams)
// An error creating addresses from the output script only
// indicates a non-standard script, so ignore this credit.
if err != nil {
continue
}
for _, a := range addrs {
if addrStr == a.EncodeAddress() {
amount += cred.Amount
break
}
}
}
}
return false, nil
}
return w.TxStore.RangeTransactions(txmgrNs, 0, stopHeight, rangeFn)
})
return amount, err
} | go | func (w *Wallet) TotalReceivedForAddr(addr btcutil.Address, minConf int32) (btcutil.Amount, error) {
var amount btcutil.Amount
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
syncBlock := w.Manager.SyncedTo()
var (
addrStr = addr.EncodeAddress()
stopHeight int32
)
if minConf > 0 {
stopHeight = syncBlock.Height - minConf + 1
} else {
stopHeight = -1
}
rangeFn := func(details []wtxmgr.TxDetails) (bool, error) {
for i := range details {
detail := &details[i]
for _, cred := range detail.Credits {
pkScript := detail.MsgTx.TxOut[cred.Index].PkScript
_, addrs, _, err := txscript.ExtractPkScriptAddrs(pkScript,
w.chainParams)
// An error creating addresses from the output script only
// indicates a non-standard script, so ignore this credit.
if err != nil {
continue
}
for _, a := range addrs {
if addrStr == a.EncodeAddress() {
amount += cred.Amount
break
}
}
}
}
return false, nil
}
return w.TxStore.RangeTransactions(txmgrNs, 0, stopHeight, rangeFn)
})
return amount, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"TotalReceivedForAddr",
"(",
"addr",
"btcutil",
".",
"Address",
",",
"minConf",
"int32",
")",
"(",
"btcutil",
".",
"Amount",
",",
"error",
")",
"{",
"var",
"amount",
"btcutil",
".",
"Amount",
"\n",
"err",
":=",
"wa... | // TotalReceivedForAddr iterates through a wallet's transaction history,
// returning the total amount of bitcoins received for a single wallet
// address. | [
"TotalReceivedForAddr",
"iterates",
"through",
"a",
"wallet",
"s",
"transaction",
"history",
"returning",
"the",
"total",
"amount",
"of",
"bitcoins",
"received",
"for",
"a",
"single",
"wallet",
"address",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L3123-L3165 | train |
btcsuite/btcwallet | wallet/wallet.go | SendOutputs | func (w *Wallet) SendOutputs(outputs []*wire.TxOut, account uint32,
minconf int32, satPerKb btcutil.Amount) (*wire.MsgTx, error) {
// Ensure the outputs to be created adhere to the network's consensus
// rules.
for _, output := range outputs {
if err := txrules.CheckOutput(output, satPerKb); err != nil {
return nil, err
}
}
// Create the transaction and broadcast it to the network. The
// transaction will be added to the database in order to ensure that we
// continue to re-broadcast the transaction upon restarts until it has
// been confirmed.
createdTx, err := w.CreateSimpleTx(
account, outputs, minconf, satPerKb, false,
)
if err != nil {
return nil, err
}
txHash, err := w.reliablyPublishTransaction(createdTx.Tx)
if err != nil {
return nil, err
}
// Sanity check on the returned tx hash.
if *txHash != createdTx.Tx.TxHash() {
return nil, errors.New("tx hash mismatch")
}
return createdTx.Tx, nil
} | go | func (w *Wallet) SendOutputs(outputs []*wire.TxOut, account uint32,
minconf int32, satPerKb btcutil.Amount) (*wire.MsgTx, error) {
// Ensure the outputs to be created adhere to the network's consensus
// rules.
for _, output := range outputs {
if err := txrules.CheckOutput(output, satPerKb); err != nil {
return nil, err
}
}
// Create the transaction and broadcast it to the network. The
// transaction will be added to the database in order to ensure that we
// continue to re-broadcast the transaction upon restarts until it has
// been confirmed.
createdTx, err := w.CreateSimpleTx(
account, outputs, minconf, satPerKb, false,
)
if err != nil {
return nil, err
}
txHash, err := w.reliablyPublishTransaction(createdTx.Tx)
if err != nil {
return nil, err
}
// Sanity check on the returned tx hash.
if *txHash != createdTx.Tx.TxHash() {
return nil, errors.New("tx hash mismatch")
}
return createdTx.Tx, nil
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"SendOutputs",
"(",
"outputs",
"[",
"]",
"*",
"wire",
".",
"TxOut",
",",
"account",
"uint32",
",",
"minconf",
"int32",
",",
"satPerKb",
"btcutil",
".",
"Amount",
")",
"(",
"*",
"wire",
".",
"MsgTx",
",",
"error",... | // SendOutputs creates and sends payment transactions. It returns the
// transaction upon success. | [
"SendOutputs",
"creates",
"and",
"sends",
"payment",
"transactions",
".",
"It",
"returns",
"the",
"transaction",
"upon",
"success",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L3169-L3202 | train |
btcsuite/btcwallet | wallet/wallet.go | PublishTransaction | func (w *Wallet) PublishTransaction(tx *wire.MsgTx) error {
_, err := w.reliablyPublishTransaction(tx)
return err
} | go | func (w *Wallet) PublishTransaction(tx *wire.MsgTx) error {
_, err := w.reliablyPublishTransaction(tx)
return err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"PublishTransaction",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
")",
"error",
"{",
"_",
",",
"err",
":=",
"w",
".",
"reliablyPublishTransaction",
"(",
"tx",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // PublishTransaction sends the transaction to the consensus RPC server so it
// can be propagated to other nodes and eventually mined.
//
// This function is unstable and will be removed once syncing code is moved out
// of the wallet. | [
"PublishTransaction",
"sends",
"the",
"transaction",
"to",
"the",
"consensus",
"RPC",
"server",
"so",
"it",
"can",
"be",
"propagated",
"to",
"other",
"nodes",
"and",
"eventually",
"mined",
".",
"This",
"function",
"is",
"unstable",
"and",
"will",
"be",
"remove... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L3346-L3349 | train |
btcsuite/btcwallet | wallet/wallet.go | publishTransaction | func (w *Wallet) publishTransaction(tx *wire.MsgTx) (*chainhash.Hash, error) {
chainClient, err := w.requireChainClient()
if err != nil {
return nil, err
}
txid, err := chainClient.SendRawTransaction(tx, false)
switch {
case err == nil:
return txid, nil
// Since we have different backends that can be used with the wallet,
// we'll need to check specific errors for each one.
//
// If the transaction is already in the mempool, we can just return now.
//
// This error is returned when broadcasting/sending a transaction to a
// btcd node that already has it in their mempool.
case strings.Contains(err.Error(), "already have transaction"):
fallthrough
// This error is returned when broadcasting a transaction to a bitcoind
// node that already has it in their mempool.
case strings.Contains(err.Error(), "txn-already-in-mempool"):
return txid, nil
// If the transaction has already confirmed, we can safely remove it
// from the unconfirmed store as it should already exist within the
// confirmed store. We'll avoid returning an error as the broadcast was
// in a sense successful.
//
// This error is returned when broadcasting/sending a transaction that
// has already confirmed to a btcd node.
case strings.Contains(err.Error(), "transaction already exists"):
fallthrough
// This error is returned when broadcasting a transaction that has
// already confirmed to a bitcoind node.
case strings.Contains(err.Error(), "txn-already-known"):
fallthrough
// This error is returned when sending a transaction that has already
// confirmed to a bitcoind node over RPC.
case strings.Contains(err.Error(), "transaction already in block chain"):
dbErr := walletdb.Update(w.db, func(dbTx walletdb.ReadWriteTx) error {
txmgrNs := dbTx.ReadWriteBucket(wtxmgrNamespaceKey)
txRec, err := wtxmgr.NewTxRecordFromMsgTx(tx, time.Now())
if err != nil {
return err
}
return w.TxStore.RemoveUnminedTx(txmgrNs, txRec)
})
if dbErr != nil {
log.Warnf("Unable to remove confirmed transaction %v "+
"from unconfirmed store: %v", tx.TxHash(), dbErr)
}
return txid, nil
// If the transaction was rejected for whatever other reason, then we'll
// remove it from the transaction store, as otherwise, we'll attempt to
// continually re-broadcast it, and the UTXO state of the wallet won't
// be accurate.
default:
dbErr := walletdb.Update(w.db, func(dbTx walletdb.ReadWriteTx) error {
txmgrNs := dbTx.ReadWriteBucket(wtxmgrNamespaceKey)
txRec, err := wtxmgr.NewTxRecordFromMsgTx(tx, time.Now())
if err != nil {
return err
}
return w.TxStore.RemoveUnminedTx(txmgrNs, txRec)
})
if dbErr != nil {
log.Warnf("Unable to remove invalid transaction %v: %v",
tx.TxHash(), dbErr)
} else {
log.Infof("Removed invalid transaction: %v",
spew.Sdump(tx))
}
return nil, err
}
} | go | func (w *Wallet) publishTransaction(tx *wire.MsgTx) (*chainhash.Hash, error) {
chainClient, err := w.requireChainClient()
if err != nil {
return nil, err
}
txid, err := chainClient.SendRawTransaction(tx, false)
switch {
case err == nil:
return txid, nil
// Since we have different backends that can be used with the wallet,
// we'll need to check specific errors for each one.
//
// If the transaction is already in the mempool, we can just return now.
//
// This error is returned when broadcasting/sending a transaction to a
// btcd node that already has it in their mempool.
case strings.Contains(err.Error(), "already have transaction"):
fallthrough
// This error is returned when broadcasting a transaction to a bitcoind
// node that already has it in their mempool.
case strings.Contains(err.Error(), "txn-already-in-mempool"):
return txid, nil
// If the transaction has already confirmed, we can safely remove it
// from the unconfirmed store as it should already exist within the
// confirmed store. We'll avoid returning an error as the broadcast was
// in a sense successful.
//
// This error is returned when broadcasting/sending a transaction that
// has already confirmed to a btcd node.
case strings.Contains(err.Error(), "transaction already exists"):
fallthrough
// This error is returned when broadcasting a transaction that has
// already confirmed to a bitcoind node.
case strings.Contains(err.Error(), "txn-already-known"):
fallthrough
// This error is returned when sending a transaction that has already
// confirmed to a bitcoind node over RPC.
case strings.Contains(err.Error(), "transaction already in block chain"):
dbErr := walletdb.Update(w.db, func(dbTx walletdb.ReadWriteTx) error {
txmgrNs := dbTx.ReadWriteBucket(wtxmgrNamespaceKey)
txRec, err := wtxmgr.NewTxRecordFromMsgTx(tx, time.Now())
if err != nil {
return err
}
return w.TxStore.RemoveUnminedTx(txmgrNs, txRec)
})
if dbErr != nil {
log.Warnf("Unable to remove confirmed transaction %v "+
"from unconfirmed store: %v", tx.TxHash(), dbErr)
}
return txid, nil
// If the transaction was rejected for whatever other reason, then we'll
// remove it from the transaction store, as otherwise, we'll attempt to
// continually re-broadcast it, and the UTXO state of the wallet won't
// be accurate.
default:
dbErr := walletdb.Update(w.db, func(dbTx walletdb.ReadWriteTx) error {
txmgrNs := dbTx.ReadWriteBucket(wtxmgrNamespaceKey)
txRec, err := wtxmgr.NewTxRecordFromMsgTx(tx, time.Now())
if err != nil {
return err
}
return w.TxStore.RemoveUnminedTx(txmgrNs, txRec)
})
if dbErr != nil {
log.Warnf("Unable to remove invalid transaction %v: %v",
tx.TxHash(), dbErr)
} else {
log.Infof("Removed invalid transaction: %v",
spew.Sdump(tx))
}
return nil, err
}
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"publishTransaction",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"chainClient",
",",
"err",
":=",
"w",
".",
"requireChainClient",
"(",
")",
"\n",
"if",
... | // publishTransaction attempts to send an unconfirmed transaction to the
// wallet's current backend. In the event that sending the transaction fails for
// whatever reason, it will be removed from the wallet's unconfirmed transaction
// store. | [
"publishTransaction",
"attempts",
"to",
"send",
"an",
"unconfirmed",
"transaction",
"to",
"the",
"wallet",
"s",
"current",
"backend",
".",
"In",
"the",
"event",
"that",
"sending",
"the",
"transaction",
"fails",
"for",
"whatever",
"reason",
"it",
"will",
"be",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L3410-L3492 | train |
btcsuite/btcwallet | wallet/wallet.go | Create | func Create(db walletdb.DB, pubPass, privPass, seed []byte, params *chaincfg.Params,
birthday time.Time) error {
// If a seed was provided, ensure that it is of valid length. Otherwise,
// we generate a random seed for the wallet with the recommended seed
// length.
if seed == nil {
hdSeed, err := hdkeychain.GenerateSeed(
hdkeychain.RecommendedSeedLen)
if err != nil {
return err
}
seed = hdSeed
}
if len(seed) < hdkeychain.MinSeedBytes ||
len(seed) > hdkeychain.MaxSeedBytes {
return hdkeychain.ErrInvalidSeedLen
}
return walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs, err := tx.CreateTopLevelBucket(waddrmgrNamespaceKey)
if err != nil {
return err
}
txmgrNs, err := tx.CreateTopLevelBucket(wtxmgrNamespaceKey)
if err != nil {
return err
}
err = waddrmgr.Create(
addrmgrNs, seed, pubPass, privPass, params, nil,
birthday,
)
if err != nil {
return err
}
return wtxmgr.Create(txmgrNs)
})
} | go | func Create(db walletdb.DB, pubPass, privPass, seed []byte, params *chaincfg.Params,
birthday time.Time) error {
// If a seed was provided, ensure that it is of valid length. Otherwise,
// we generate a random seed for the wallet with the recommended seed
// length.
if seed == nil {
hdSeed, err := hdkeychain.GenerateSeed(
hdkeychain.RecommendedSeedLen)
if err != nil {
return err
}
seed = hdSeed
}
if len(seed) < hdkeychain.MinSeedBytes ||
len(seed) > hdkeychain.MaxSeedBytes {
return hdkeychain.ErrInvalidSeedLen
}
return walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs, err := tx.CreateTopLevelBucket(waddrmgrNamespaceKey)
if err != nil {
return err
}
txmgrNs, err := tx.CreateTopLevelBucket(wtxmgrNamespaceKey)
if err != nil {
return err
}
err = waddrmgr.Create(
addrmgrNs, seed, pubPass, privPass, params, nil,
birthday,
)
if err != nil {
return err
}
return wtxmgr.Create(txmgrNs)
})
} | [
"func",
"Create",
"(",
"db",
"walletdb",
".",
"DB",
",",
"pubPass",
",",
"privPass",
",",
"seed",
"[",
"]",
"byte",
",",
"params",
"*",
"chaincfg",
".",
"Params",
",",
"birthday",
"time",
".",
"Time",
")",
"error",
"{",
"if",
"seed",
"==",
"nil",
"... | // Create creates an new wallet, writing it to an empty database. If the passed
// seed is non-nil, it is used. Otherwise, a secure random seed of the
// recommended length is generated. | [
"Create",
"creates",
"an",
"new",
"wallet",
"writing",
"it",
"to",
"an",
"empty",
"database",
".",
"If",
"the",
"passed",
"seed",
"is",
"non",
"-",
"nil",
"it",
"is",
"used",
".",
"Otherwise",
"a",
"secure",
"random",
"seed",
"of",
"the",
"recommended",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L3510-L3548 | train |
btcsuite/btcwallet | wallet/wallet.go | Open | func Open(db walletdb.DB, pubPass []byte, cbs *waddrmgr.OpenCallbacks,
params *chaincfg.Params, recoveryWindow uint32) (*Wallet, error) {
var (
addrMgr *waddrmgr.Manager
txMgr *wtxmgr.Store
)
// Before attempting to open the wallet, we'll check if there are any
// database upgrades for us to proceed. We'll also create our references
// to the address and transaction managers, as they are backed by the
// database.
err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
addrMgrBucket := tx.ReadWriteBucket(waddrmgrNamespaceKey)
if addrMgrBucket == nil {
return errors.New("missing address manager namespace")
}
txMgrBucket := tx.ReadWriteBucket(wtxmgrNamespaceKey)
if txMgrBucket == nil {
return errors.New("missing transaction manager namespace")
}
addrMgrUpgrader := waddrmgr.NewMigrationManager(addrMgrBucket)
txMgrUpgrader := wtxmgr.NewMigrationManager(txMgrBucket)
err := migration.Upgrade(txMgrUpgrader, addrMgrUpgrader)
if err != nil {
return err
}
addrMgr, err = waddrmgr.Open(addrMgrBucket, pubPass, params)
if err != nil {
return err
}
txMgr, err = wtxmgr.Open(txMgrBucket, params)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
log.Infof("Opened wallet") // TODO: log balance? last sync height?
w := &Wallet{
publicPassphrase: pubPass,
db: db,
Manager: addrMgr,
TxStore: txMgr,
lockedOutpoints: map[wire.OutPoint]struct{}{},
recoveryWindow: recoveryWindow,
rescanAddJob: make(chan *RescanJob),
rescanBatch: make(chan *rescanBatch),
rescanNotifications: make(chan interface{}),
rescanProgress: make(chan *RescanProgressMsg),
rescanFinished: make(chan *RescanFinishedMsg),
createTxRequests: make(chan createTxRequest),
unlockRequests: make(chan unlockRequest),
lockRequests: make(chan struct{}),
holdUnlockRequests: make(chan chan heldUnlock),
lockState: make(chan bool),
changePassphrase: make(chan changePassphraseRequest),
changePassphrases: make(chan changePassphrasesRequest),
chainParams: params,
quit: make(chan struct{}),
}
w.NtfnServer = newNotificationServer(w)
w.TxStore.NotifyUnspent = func(hash *chainhash.Hash, index uint32) {
w.NtfnServer.notifyUnspentOutput(0, hash, index)
}
return w, nil
} | go | func Open(db walletdb.DB, pubPass []byte, cbs *waddrmgr.OpenCallbacks,
params *chaincfg.Params, recoveryWindow uint32) (*Wallet, error) {
var (
addrMgr *waddrmgr.Manager
txMgr *wtxmgr.Store
)
// Before attempting to open the wallet, we'll check if there are any
// database upgrades for us to proceed. We'll also create our references
// to the address and transaction managers, as they are backed by the
// database.
err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
addrMgrBucket := tx.ReadWriteBucket(waddrmgrNamespaceKey)
if addrMgrBucket == nil {
return errors.New("missing address manager namespace")
}
txMgrBucket := tx.ReadWriteBucket(wtxmgrNamespaceKey)
if txMgrBucket == nil {
return errors.New("missing transaction manager namespace")
}
addrMgrUpgrader := waddrmgr.NewMigrationManager(addrMgrBucket)
txMgrUpgrader := wtxmgr.NewMigrationManager(txMgrBucket)
err := migration.Upgrade(txMgrUpgrader, addrMgrUpgrader)
if err != nil {
return err
}
addrMgr, err = waddrmgr.Open(addrMgrBucket, pubPass, params)
if err != nil {
return err
}
txMgr, err = wtxmgr.Open(txMgrBucket, params)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
log.Infof("Opened wallet") // TODO: log balance? last sync height?
w := &Wallet{
publicPassphrase: pubPass,
db: db,
Manager: addrMgr,
TxStore: txMgr,
lockedOutpoints: map[wire.OutPoint]struct{}{},
recoveryWindow: recoveryWindow,
rescanAddJob: make(chan *RescanJob),
rescanBatch: make(chan *rescanBatch),
rescanNotifications: make(chan interface{}),
rescanProgress: make(chan *RescanProgressMsg),
rescanFinished: make(chan *RescanFinishedMsg),
createTxRequests: make(chan createTxRequest),
unlockRequests: make(chan unlockRequest),
lockRequests: make(chan struct{}),
holdUnlockRequests: make(chan chan heldUnlock),
lockState: make(chan bool),
changePassphrase: make(chan changePassphraseRequest),
changePassphrases: make(chan changePassphrasesRequest),
chainParams: params,
quit: make(chan struct{}),
}
w.NtfnServer = newNotificationServer(w)
w.TxStore.NotifyUnspent = func(hash *chainhash.Hash, index uint32) {
w.NtfnServer.notifyUnspentOutput(0, hash, index)
}
return w, nil
} | [
"func",
"Open",
"(",
"db",
"walletdb",
".",
"DB",
",",
"pubPass",
"[",
"]",
"byte",
",",
"cbs",
"*",
"waddrmgr",
".",
"OpenCallbacks",
",",
"params",
"*",
"chaincfg",
".",
"Params",
",",
"recoveryWindow",
"uint32",
")",
"(",
"*",
"Wallet",
",",
"error"... | // Open loads an already-created wallet from the passed database and namespaces. | [
"Open",
"loads",
"an",
"already",
"-",
"created",
"wallet",
"from",
"the",
"passed",
"database",
"and",
"namespaces",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L3551-L3626 | train |
btcsuite/btcwallet | internal/helpers/helpers.go | SumOutputValues | func SumOutputValues(outputs []*wire.TxOut) (totalOutput btcutil.Amount) {
for _, txOut := range outputs {
totalOutput += btcutil.Amount(txOut.Value)
}
return totalOutput
} | go | func SumOutputValues(outputs []*wire.TxOut) (totalOutput btcutil.Amount) {
for _, txOut := range outputs {
totalOutput += btcutil.Amount(txOut.Value)
}
return totalOutput
} | [
"func",
"SumOutputValues",
"(",
"outputs",
"[",
"]",
"*",
"wire",
".",
"TxOut",
")",
"(",
"totalOutput",
"btcutil",
".",
"Amount",
")",
"{",
"for",
"_",
",",
"txOut",
":=",
"range",
"outputs",
"{",
"totalOutput",
"+=",
"btcutil",
".",
"Amount",
"(",
"t... | // SumOutputValues sums up the list of TxOuts and returns an Amount. | [
"SumOutputValues",
"sums",
"up",
"the",
"list",
"of",
"TxOuts",
"and",
"returns",
"an",
"Amount",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/helpers/helpers.go#L15-L20 | train |
btcsuite/btcwallet | internal/helpers/helpers.go | SumOutputSerializeSizes | func SumOutputSerializeSizes(outputs []*wire.TxOut) (serializeSize int) {
for _, txOut := range outputs {
serializeSize += txOut.SerializeSize()
}
return serializeSize
} | go | func SumOutputSerializeSizes(outputs []*wire.TxOut) (serializeSize int) {
for _, txOut := range outputs {
serializeSize += txOut.SerializeSize()
}
return serializeSize
} | [
"func",
"SumOutputSerializeSizes",
"(",
"outputs",
"[",
"]",
"*",
"wire",
".",
"TxOut",
")",
"(",
"serializeSize",
"int",
")",
"{",
"for",
"_",
",",
"txOut",
":=",
"range",
"outputs",
"{",
"serializeSize",
"+=",
"txOut",
".",
"SerializeSize",
"(",
")",
"... | // SumOutputSerializeSizes sums up the serialized size of the supplied outputs. | [
"SumOutputSerializeSizes",
"sums",
"up",
"the",
"serialized",
"size",
"of",
"the",
"supplied",
"outputs",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/helpers/helpers.go#L23-L28 | train |
btcsuite/btcwallet | wallet/unstable.go | TxDetails | func (u unstableAPI) TxDetails(txHash *chainhash.Hash) (*wtxmgr.TxDetails, error) {
var details *wtxmgr.TxDetails
err := walletdb.View(u.w.db, func(dbtx walletdb.ReadTx) error {
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
var err error
details, err = u.w.TxStore.TxDetails(txmgrNs, txHash)
return err
})
return details, err
} | go | func (u unstableAPI) TxDetails(txHash *chainhash.Hash) (*wtxmgr.TxDetails, error) {
var details *wtxmgr.TxDetails
err := walletdb.View(u.w.db, func(dbtx walletdb.ReadTx) error {
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
var err error
details, err = u.w.TxStore.TxDetails(txmgrNs, txHash)
return err
})
return details, err
} | [
"func",
"(",
"u",
"unstableAPI",
")",
"TxDetails",
"(",
"txHash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"wtxmgr",
".",
"TxDetails",
",",
"error",
")",
"{",
"var",
"details",
"*",
"wtxmgr",
".",
"TxDetails",
"\n",
"err",
":=",
"walletdb",
".",
... | // TxDetails calls wtxmgr.Store.TxDetails under a single database view transaction. | [
"TxDetails",
"calls",
"wtxmgr",
".",
"Store",
".",
"TxDetails",
"under",
"a",
"single",
"database",
"view",
"transaction",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/unstable.go#L26-L35 | train |
btcsuite/btcwallet | wallet/unstable.go | RangeTransactions | func (u unstableAPI) RangeTransactions(begin, end int32, f func([]wtxmgr.TxDetails) (bool, error)) error {
return walletdb.View(u.w.db, func(dbtx walletdb.ReadTx) error {
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
return u.w.TxStore.RangeTransactions(txmgrNs, begin, end, f)
})
} | go | func (u unstableAPI) RangeTransactions(begin, end int32, f func([]wtxmgr.TxDetails) (bool, error)) error {
return walletdb.View(u.w.db, func(dbtx walletdb.ReadTx) error {
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
return u.w.TxStore.RangeTransactions(txmgrNs, begin, end, f)
})
} | [
"func",
"(",
"u",
"unstableAPI",
")",
"RangeTransactions",
"(",
"begin",
",",
"end",
"int32",
",",
"f",
"func",
"(",
"[",
"]",
"wtxmgr",
".",
"TxDetails",
")",
"(",
"bool",
",",
"error",
")",
")",
"error",
"{",
"return",
"walletdb",
".",
"View",
"(",... | // RangeTransactions calls wtxmgr.Store.RangeTransactions under a single
// database view tranasction. | [
"RangeTransactions",
"calls",
"wtxmgr",
".",
"Store",
".",
"RangeTransactions",
"under",
"a",
"single",
"database",
"view",
"tranasction",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/unstable.go#L39-L44 | train |
btcsuite/btcwallet | cmd/sweepaccount/main.go | init | func init() {
// Unset localhost defaults if certificate file can not be found.
certFileExists, err := cfgutil.FileExists(opts.RPCCertificateFile)
if err != nil {
fatalf("%v", err)
}
if !certFileExists {
opts.RPCConnect = ""
opts.RPCCertificateFile = ""
}
_, err = flags.Parse(&opts)
if err != nil {
os.Exit(1)
}
if opts.TestNet3 && opts.SimNet {
fatalf("Multiple bitcoin networks may not be used simultaneously")
}
var activeNet = &netparams.MainNetParams
if opts.TestNet3 {
activeNet = &netparams.TestNet3Params
} else if opts.SimNet {
activeNet = &netparams.SimNetParams
}
if opts.RPCConnect == "" {
fatalf("RPC hostname[:port] is required")
}
rpcConnect, err := cfgutil.NormalizeAddress(opts.RPCConnect, activeNet.RPCServerPort)
if err != nil {
fatalf("Invalid RPC network address `%v`: %v", opts.RPCConnect, err)
}
opts.RPCConnect = rpcConnect
if opts.RPCUsername == "" {
fatalf("RPC username is required")
}
certFileExists, err = cfgutil.FileExists(opts.RPCCertificateFile)
if err != nil {
fatalf("%v", err)
}
if !certFileExists {
fatalf("RPC certificate file `%s` not found", opts.RPCCertificateFile)
}
if opts.FeeRate.Amount > 1e6 {
fatalf("Fee rate `%v/kB` is exceptionally high", opts.FeeRate.Amount)
}
if opts.FeeRate.Amount < 1e2 {
fatalf("Fee rate `%v/kB` is exceptionally low", opts.FeeRate.Amount)
}
if opts.SourceAccount == opts.DestinationAccount {
fatalf("Source and destination accounts should not be equal")
}
if opts.RequiredConfirmations < 0 {
fatalf("Required confirmations must be non-negative")
}
} | go | func init() {
// Unset localhost defaults if certificate file can not be found.
certFileExists, err := cfgutil.FileExists(opts.RPCCertificateFile)
if err != nil {
fatalf("%v", err)
}
if !certFileExists {
opts.RPCConnect = ""
opts.RPCCertificateFile = ""
}
_, err = flags.Parse(&opts)
if err != nil {
os.Exit(1)
}
if opts.TestNet3 && opts.SimNet {
fatalf("Multiple bitcoin networks may not be used simultaneously")
}
var activeNet = &netparams.MainNetParams
if opts.TestNet3 {
activeNet = &netparams.TestNet3Params
} else if opts.SimNet {
activeNet = &netparams.SimNetParams
}
if opts.RPCConnect == "" {
fatalf("RPC hostname[:port] is required")
}
rpcConnect, err := cfgutil.NormalizeAddress(opts.RPCConnect, activeNet.RPCServerPort)
if err != nil {
fatalf("Invalid RPC network address `%v`: %v", opts.RPCConnect, err)
}
opts.RPCConnect = rpcConnect
if opts.RPCUsername == "" {
fatalf("RPC username is required")
}
certFileExists, err = cfgutil.FileExists(opts.RPCCertificateFile)
if err != nil {
fatalf("%v", err)
}
if !certFileExists {
fatalf("RPC certificate file `%s` not found", opts.RPCCertificateFile)
}
if opts.FeeRate.Amount > 1e6 {
fatalf("Fee rate `%v/kB` is exceptionally high", opts.FeeRate.Amount)
}
if opts.FeeRate.Amount < 1e2 {
fatalf("Fee rate `%v/kB` is exceptionally low", opts.FeeRate.Amount)
}
if opts.SourceAccount == opts.DestinationAccount {
fatalf("Source and destination accounts should not be equal")
}
if opts.RequiredConfirmations < 0 {
fatalf("Required confirmations must be non-negative")
}
} | [
"func",
"init",
"(",
")",
"{",
"certFileExists",
",",
"err",
":=",
"cfgutil",
".",
"FileExists",
"(",
"opts",
".",
"RPCCertificateFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fatalf",
"(",
"\"%v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"!",
... | // Parse and validate flags. | [
"Parse",
"and",
"validate",
"flags",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/cmd/sweepaccount/main.go#L67-L126 | train |
btcsuite/btcwallet | cmd/sweepaccount/main.go | makeInputSource | func makeInputSource(outputs []btcjson.ListUnspentResult) txauthor.InputSource {
var (
totalInputValue btcutil.Amount
inputs = make([]*wire.TxIn, 0, len(outputs))
inputValues = make([]btcutil.Amount, 0, len(outputs))
sourceErr error
)
for _, output := range outputs {
outputAmount, err := btcutil.NewAmount(output.Amount)
if err != nil {
sourceErr = fmt.Errorf(
"invalid amount `%v` in listunspent result",
output.Amount)
break
}
if outputAmount == 0 {
continue
}
if !saneOutputValue(outputAmount) {
sourceErr = fmt.Errorf(
"impossible output amount `%v` in listunspent result",
outputAmount)
break
}
totalInputValue += outputAmount
previousOutPoint, err := parseOutPoint(&output)
if err != nil {
sourceErr = fmt.Errorf(
"invalid data in listunspent result: %v",
err)
break
}
inputs = append(inputs, wire.NewTxIn(&previousOutPoint, nil, nil))
inputValues = append(inputValues, outputAmount)
}
if sourceErr == nil && totalInputValue == 0 {
sourceErr = noInputValue{}
}
return func(btcutil.Amount) (btcutil.Amount, []*wire.TxIn, []btcutil.Amount, [][]byte, error) {
return totalInputValue, inputs, inputValues, nil, sourceErr
}
} | go | func makeInputSource(outputs []btcjson.ListUnspentResult) txauthor.InputSource {
var (
totalInputValue btcutil.Amount
inputs = make([]*wire.TxIn, 0, len(outputs))
inputValues = make([]btcutil.Amount, 0, len(outputs))
sourceErr error
)
for _, output := range outputs {
outputAmount, err := btcutil.NewAmount(output.Amount)
if err != nil {
sourceErr = fmt.Errorf(
"invalid amount `%v` in listunspent result",
output.Amount)
break
}
if outputAmount == 0 {
continue
}
if !saneOutputValue(outputAmount) {
sourceErr = fmt.Errorf(
"impossible output amount `%v` in listunspent result",
outputAmount)
break
}
totalInputValue += outputAmount
previousOutPoint, err := parseOutPoint(&output)
if err != nil {
sourceErr = fmt.Errorf(
"invalid data in listunspent result: %v",
err)
break
}
inputs = append(inputs, wire.NewTxIn(&previousOutPoint, nil, nil))
inputValues = append(inputValues, outputAmount)
}
if sourceErr == nil && totalInputValue == 0 {
sourceErr = noInputValue{}
}
return func(btcutil.Amount) (btcutil.Amount, []*wire.TxIn, []btcutil.Amount, [][]byte, error) {
return totalInputValue, inputs, inputValues, nil, sourceErr
}
} | [
"func",
"makeInputSource",
"(",
"outputs",
"[",
"]",
"btcjson",
".",
"ListUnspentResult",
")",
"txauthor",
".",
"InputSource",
"{",
"var",
"(",
"totalInputValue",
"btcutil",
".",
"Amount",
"\n",
"inputs",
"=",
"make",
"(",
"[",
"]",
"*",
"wire",
".",
"TxIn... | // makeInputSource creates an InputSource that creates inputs for every unspent
// output with non-zero output values. The target amount is ignored since every
// output is consumed. The InputSource does not return any previous output
// scripts as they are not needed for creating the unsinged transaction and are
// looked up again by the wallet during the call to signrawtransaction. | [
"makeInputSource",
"creates",
"an",
"InputSource",
"that",
"creates",
"inputs",
"for",
"every",
"unspent",
"output",
"with",
"non",
"-",
"zero",
"output",
"values",
".",
"The",
"target",
"amount",
"is",
"ignored",
"since",
"every",
"output",
"is",
"consumed",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/cmd/sweepaccount/main.go#L141-L186 | train |
btcsuite/btcwallet | cmd/sweepaccount/main.go | makeDestinationScriptSource | func makeDestinationScriptSource(rpcClient *rpcclient.Client, accountName string) txauthor.ChangeSource {
return func() ([]byte, error) {
destinationAddress, err := rpcClient.GetNewAddress(accountName)
if err != nil {
return nil, err
}
return txscript.PayToAddrScript(destinationAddress)
}
} | go | func makeDestinationScriptSource(rpcClient *rpcclient.Client, accountName string) txauthor.ChangeSource {
return func() ([]byte, error) {
destinationAddress, err := rpcClient.GetNewAddress(accountName)
if err != nil {
return nil, err
}
return txscript.PayToAddrScript(destinationAddress)
}
} | [
"func",
"makeDestinationScriptSource",
"(",
"rpcClient",
"*",
"rpcclient",
".",
"Client",
",",
"accountName",
"string",
")",
"txauthor",
".",
"ChangeSource",
"{",
"return",
"func",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"destinationAddress",
... | // makeDestinationScriptSource creates a ChangeSource which is used to receive
// all correlated previous input value. A non-change address is created by this
// function. | [
"makeDestinationScriptSource",
"creates",
"a",
"ChangeSource",
"which",
"is",
"used",
"to",
"receive",
"all",
"correlated",
"previous",
"input",
"value",
".",
"A",
"non",
"-",
"change",
"address",
"is",
"created",
"by",
"this",
"function",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/cmd/sweepaccount/main.go#L191-L199 | train |
btcsuite/btcwallet | wallet/txauthor/author.go | RandomizeOutputPosition | func RandomizeOutputPosition(outputs []*wire.TxOut, index int) int {
r := cprng.Int31n(int32(len(outputs)))
outputs[r], outputs[index] = outputs[index], outputs[r]
return int(r)
} | go | func RandomizeOutputPosition(outputs []*wire.TxOut, index int) int {
r := cprng.Int31n(int32(len(outputs)))
outputs[r], outputs[index] = outputs[index], outputs[r]
return int(r)
} | [
"func",
"RandomizeOutputPosition",
"(",
"outputs",
"[",
"]",
"*",
"wire",
".",
"TxOut",
",",
"index",
"int",
")",
"int",
"{",
"r",
":=",
"cprng",
".",
"Int31n",
"(",
"int32",
"(",
"len",
"(",
"outputs",
")",
")",
")",
"\n",
"outputs",
"[",
"r",
"]"... | // RandomizeOutputPosition randomizes the position of a transaction's output by
// swapping it with a random output. The new index is returned. This should be
// done before signing. | [
"RandomizeOutputPosition",
"randomizes",
"the",
"position",
"of",
"a",
"transaction",
"s",
"output",
"by",
"swapping",
"it",
"with",
"a",
"random",
"output",
".",
"The",
"new",
"index",
"is",
"returned",
".",
"This",
"should",
"be",
"done",
"before",
"signing"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/txauthor/author.go#L158-L162 | train |
btcsuite/btcwallet | wallet/txauthor/author.go | RandomizeChangePosition | func (tx *AuthoredTx) RandomizeChangePosition() {
tx.ChangeIndex = RandomizeOutputPosition(tx.Tx.TxOut, tx.ChangeIndex)
} | go | func (tx *AuthoredTx) RandomizeChangePosition() {
tx.ChangeIndex = RandomizeOutputPosition(tx.Tx.TxOut, tx.ChangeIndex)
} | [
"func",
"(",
"tx",
"*",
"AuthoredTx",
")",
"RandomizeChangePosition",
"(",
")",
"{",
"tx",
".",
"ChangeIndex",
"=",
"RandomizeOutputPosition",
"(",
"tx",
".",
"Tx",
".",
"TxOut",
",",
"tx",
".",
"ChangeIndex",
")",
"\n",
"}"
] | // RandomizeChangePosition randomizes the position of an authored transaction's
// change output. This should be done before signing. | [
"RandomizeChangePosition",
"randomizes",
"the",
"position",
"of",
"an",
"authored",
"transaction",
"s",
"change",
"output",
".",
"This",
"should",
"be",
"done",
"before",
"signing",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/txauthor/author.go#L166-L168 | train |
btcsuite/btcwallet | wallet/txauthor/author.go | AddAllInputScripts | func AddAllInputScripts(tx *wire.MsgTx, prevPkScripts [][]byte, inputValues []btcutil.Amount,
secrets SecretsSource) error {
inputs := tx.TxIn
hashCache := txscript.NewTxSigHashes(tx)
chainParams := secrets.ChainParams()
if len(inputs) != len(prevPkScripts) {
return errors.New("tx.TxIn and prevPkScripts slices must " +
"have equal length")
}
for i := range inputs {
pkScript := prevPkScripts[i]
switch {
// If this is a p2sh output, who's script hash pre-image is a
// witness program, then we'll need to use a modified signing
// function which generates both the sigScript, and the witness
// script.
case txscript.IsPayToScriptHash(pkScript):
err := spendNestedWitnessPubKeyHash(inputs[i], pkScript,
int64(inputValues[i]), chainParams, secrets,
tx, hashCache, i)
if err != nil {
return err
}
case txscript.IsPayToWitnessPubKeyHash(pkScript):
err := spendWitnessKeyHash(inputs[i], pkScript,
int64(inputValues[i]), chainParams, secrets,
tx, hashCache, i)
if err != nil {
return err
}
default:
sigScript := inputs[i].SignatureScript
script, err := txscript.SignTxOutput(chainParams, tx, i,
pkScript, txscript.SigHashAll, secrets, secrets,
sigScript)
if err != nil {
return err
}
inputs[i].SignatureScript = script
}
}
return nil
} | go | func AddAllInputScripts(tx *wire.MsgTx, prevPkScripts [][]byte, inputValues []btcutil.Amount,
secrets SecretsSource) error {
inputs := tx.TxIn
hashCache := txscript.NewTxSigHashes(tx)
chainParams := secrets.ChainParams()
if len(inputs) != len(prevPkScripts) {
return errors.New("tx.TxIn and prevPkScripts slices must " +
"have equal length")
}
for i := range inputs {
pkScript := prevPkScripts[i]
switch {
// If this is a p2sh output, who's script hash pre-image is a
// witness program, then we'll need to use a modified signing
// function which generates both the sigScript, and the witness
// script.
case txscript.IsPayToScriptHash(pkScript):
err := spendNestedWitnessPubKeyHash(inputs[i], pkScript,
int64(inputValues[i]), chainParams, secrets,
tx, hashCache, i)
if err != nil {
return err
}
case txscript.IsPayToWitnessPubKeyHash(pkScript):
err := spendWitnessKeyHash(inputs[i], pkScript,
int64(inputValues[i]), chainParams, secrets,
tx, hashCache, i)
if err != nil {
return err
}
default:
sigScript := inputs[i].SignatureScript
script, err := txscript.SignTxOutput(chainParams, tx, i,
pkScript, txscript.SigHashAll, secrets, secrets,
sigScript)
if err != nil {
return err
}
inputs[i].SignatureScript = script
}
}
return nil
} | [
"func",
"AddAllInputScripts",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
",",
"prevPkScripts",
"[",
"]",
"[",
"]",
"byte",
",",
"inputValues",
"[",
"]",
"btcutil",
".",
"Amount",
",",
"secrets",
"SecretsSource",
")",
"error",
"{",
"inputs",
":=",
"tx",
".",
... | // AddAllInputScripts modifies transaction a transaction by adding inputs
// scripts for each input. Previous output scripts being redeemed by each input
// are passed in prevPkScripts and the slice length must match the number of
// inputs. Private keys and redeem scripts are looked up using a SecretsSource
// based on the previous output script. | [
"AddAllInputScripts",
"modifies",
"transaction",
"a",
"transaction",
"by",
"adding",
"inputs",
"scripts",
"for",
"each",
"input",
".",
"Previous",
"output",
"scripts",
"being",
"redeemed",
"by",
"each",
"input",
"are",
"passed",
"in",
"prevPkScripts",
"and",
"the"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/txauthor/author.go#L192-L239 | train |
btcsuite/btcwallet | wallet/txauthor/author.go | AddAllInputScripts | func (tx *AuthoredTx) AddAllInputScripts(secrets SecretsSource) error {
return AddAllInputScripts(tx.Tx, tx.PrevScripts, tx.PrevInputValues, secrets)
} | go | func (tx *AuthoredTx) AddAllInputScripts(secrets SecretsSource) error {
return AddAllInputScripts(tx.Tx, tx.PrevScripts, tx.PrevInputValues, secrets)
} | [
"func",
"(",
"tx",
"*",
"AuthoredTx",
")",
"AddAllInputScripts",
"(",
"secrets",
"SecretsSource",
")",
"error",
"{",
"return",
"AddAllInputScripts",
"(",
"tx",
".",
"Tx",
",",
"tx",
".",
"PrevScripts",
",",
"tx",
".",
"PrevInputValues",
",",
"secrets",
")",
... | // AddAllInputScripts modifies an authored transaction by adding inputs scripts
// for each input of an authored transaction. Private keys and redeem scripts
// are looked up using a SecretsSource based on the previous output script. | [
"AddAllInputScripts",
"modifies",
"an",
"authored",
"transaction",
"by",
"adding",
"inputs",
"scripts",
"for",
"each",
"input",
"of",
"an",
"authored",
"transaction",
".",
"Private",
"keys",
"and",
"redeem",
"scripts",
"are",
"looked",
"up",
"using",
"a",
"Secre... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/txauthor/author.go#L359-L361 | train |
btcsuite/btcwallet | wallet/utxos.go | UnspentOutputs | func (w *Wallet) UnspentOutputs(policy OutputSelectionPolicy) ([]*TransactionOutput, error) {
var outputResults []*TransactionOutput
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
syncBlock := w.Manager.SyncedTo()
// TODO: actually stream outputs from the db instead of fetching
// all of them at once.
outputs, err := w.TxStore.UnspentOutputs(txmgrNs)
if err != nil {
return err
}
for _, output := range outputs {
// Ignore outputs that haven't reached the required
// number of confirmations.
if !policy.meetsRequiredConfs(output.Height, syncBlock.Height) {
continue
}
// Ignore outputs that are not controlled by the account.
_, addrs, _, err := txscript.ExtractPkScriptAddrs(output.PkScript,
w.chainParams)
if err != nil || len(addrs) == 0 {
// Cannot determine which account this belongs
// to without a valid address. TODO: Fix this
// by saving outputs per account, or accounts
// per output.
continue
}
_, outputAcct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0])
if err != nil {
return err
}
if outputAcct != policy.Account {
continue
}
// Stakebase isn't exposed by wtxmgr so those will be
// OutputKindNormal for now.
outputSource := OutputKindNormal
if output.FromCoinBase {
outputSource = OutputKindCoinbase
}
result := &TransactionOutput{
OutPoint: output.OutPoint,
Output: wire.TxOut{
Value: int64(output.Amount),
PkScript: output.PkScript,
},
OutputKind: outputSource,
ContainingBlock: BlockIdentity(output.Block),
ReceiveTime: output.Received,
}
outputResults = append(outputResults, result)
}
return nil
})
return outputResults, err
} | go | func (w *Wallet) UnspentOutputs(policy OutputSelectionPolicy) ([]*TransactionOutput, error) {
var outputResults []*TransactionOutput
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
syncBlock := w.Manager.SyncedTo()
// TODO: actually stream outputs from the db instead of fetching
// all of them at once.
outputs, err := w.TxStore.UnspentOutputs(txmgrNs)
if err != nil {
return err
}
for _, output := range outputs {
// Ignore outputs that haven't reached the required
// number of confirmations.
if !policy.meetsRequiredConfs(output.Height, syncBlock.Height) {
continue
}
// Ignore outputs that are not controlled by the account.
_, addrs, _, err := txscript.ExtractPkScriptAddrs(output.PkScript,
w.chainParams)
if err != nil || len(addrs) == 0 {
// Cannot determine which account this belongs
// to without a valid address. TODO: Fix this
// by saving outputs per account, or accounts
// per output.
continue
}
_, outputAcct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0])
if err != nil {
return err
}
if outputAcct != policy.Account {
continue
}
// Stakebase isn't exposed by wtxmgr so those will be
// OutputKindNormal for now.
outputSource := OutputKindNormal
if output.FromCoinBase {
outputSource = OutputKindCoinbase
}
result := &TransactionOutput{
OutPoint: output.OutPoint,
Output: wire.TxOut{
Value: int64(output.Amount),
PkScript: output.PkScript,
},
OutputKind: outputSource,
ContainingBlock: BlockIdentity(output.Block),
ReceiveTime: output.Received,
}
outputResults = append(outputResults, result)
}
return nil
})
return outputResults, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"UnspentOutputs",
"(",
"policy",
"OutputSelectionPolicy",
")",
"(",
"[",
"]",
"*",
"TransactionOutput",
",",
"error",
")",
"{",
"var",
"outputResults",
"[",
"]",
"*",
"TransactionOutput",
"\n",
"err",
":=",
"walletdb",
... | // UnspentOutputs fetches all unspent outputs from the wallet that match rules
// described in the passed policy. | [
"UnspentOutputs",
"fetches",
"all",
"unspent",
"outputs",
"from",
"the",
"wallet",
"that",
"match",
"rules",
"described",
"in",
"the",
"passed",
"policy",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/utxos.go#L27-L90 | train |
btcsuite/btcwallet | waddrmgr/manager.go | defaultNewSecretKey | func defaultNewSecretKey(passphrase *[]byte,
config *ScryptOptions) (*snacl.SecretKey, error) {
return snacl.NewSecretKey(passphrase, config.N, config.R, config.P)
} | go | func defaultNewSecretKey(passphrase *[]byte,
config *ScryptOptions) (*snacl.SecretKey, error) {
return snacl.NewSecretKey(passphrase, config.N, config.R, config.P)
} | [
"func",
"defaultNewSecretKey",
"(",
"passphrase",
"*",
"[",
"]",
"byte",
",",
"config",
"*",
"ScryptOptions",
")",
"(",
"*",
"snacl",
".",
"SecretKey",
",",
"error",
")",
"{",
"return",
"snacl",
".",
"NewSecretKey",
"(",
"passphrase",
",",
"config",
".",
... | // defaultNewSecretKey returns a new secret key. See newSecretKey. | [
"defaultNewSecretKey",
"returns",
"a",
"new",
"secret",
"key",
".",
"See",
"newSecretKey",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L183-L186 | train |
btcsuite/btcwallet | waddrmgr/manager.go | SetSecretKeyGen | func SetSecretKeyGen(keyGen SecretKeyGenerator) SecretKeyGenerator {
secretKeyGenMtx.Lock()
oldKeyGen := secretKeyGen
secretKeyGen = keyGen
secretKeyGenMtx.Unlock()
return oldKeyGen
} | go | func SetSecretKeyGen(keyGen SecretKeyGenerator) SecretKeyGenerator {
secretKeyGenMtx.Lock()
oldKeyGen := secretKeyGen
secretKeyGen = keyGen
secretKeyGenMtx.Unlock()
return oldKeyGen
} | [
"func",
"SetSecretKeyGen",
"(",
"keyGen",
"SecretKeyGenerator",
")",
"SecretKeyGenerator",
"{",
"secretKeyGenMtx",
".",
"Lock",
"(",
")",
"\n",
"oldKeyGen",
":=",
"secretKeyGen",
"\n",
"secretKeyGen",
"=",
"keyGen",
"\n",
"secretKeyGenMtx",
".",
"Unlock",
"(",
")"... | // SetSecretKeyGen replaces the existing secret key generator, and returns the
// previous generator. | [
"SetSecretKeyGen",
"replaces",
"the",
"existing",
"secret",
"key",
"generator",
"and",
"returns",
"the",
"previous",
"generator",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L200-L207 | train |
btcsuite/btcwallet | waddrmgr/manager.go | newSecretKey | func newSecretKey(passphrase *[]byte,
config *ScryptOptions) (*snacl.SecretKey, error) {
secretKeyGenMtx.RLock()
defer secretKeyGenMtx.RUnlock()
return secretKeyGen(passphrase, config)
} | go | func newSecretKey(passphrase *[]byte,
config *ScryptOptions) (*snacl.SecretKey, error) {
secretKeyGenMtx.RLock()
defer secretKeyGenMtx.RUnlock()
return secretKeyGen(passphrase, config)
} | [
"func",
"newSecretKey",
"(",
"passphrase",
"*",
"[",
"]",
"byte",
",",
"config",
"*",
"ScryptOptions",
")",
"(",
"*",
"snacl",
".",
"SecretKey",
",",
"error",
")",
"{",
"secretKeyGenMtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"secretKeyGenMtx",
".",
"RU... | // newSecretKey generates a new secret key using the active secretKeyGen. | [
"newSecretKey",
"generates",
"a",
"new",
"secret",
"key",
"using",
"the",
"active",
"secretKeyGen",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L210-L216 | train |
btcsuite/btcwallet | waddrmgr/manager.go | defaultNewCryptoKey | func defaultNewCryptoKey() (EncryptorDecryptor, error) {
key, err := snacl.GenerateCryptoKey()
if err != nil {
return nil, err
}
return &cryptoKey{*key}, nil
} | go | func defaultNewCryptoKey() (EncryptorDecryptor, error) {
key, err := snacl.GenerateCryptoKey()
if err != nil {
return nil, err
}
return &cryptoKey{*key}, nil
} | [
"func",
"defaultNewCryptoKey",
"(",
")",
"(",
"EncryptorDecryptor",
",",
"error",
")",
"{",
"key",
",",
"err",
":=",
"snacl",
".",
"GenerateCryptoKey",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return... | // defaultNewCryptoKey returns a new CryptoKey. See newCryptoKey. | [
"defaultNewCryptoKey",
"returns",
"a",
"new",
"CryptoKey",
".",
"See",
"newCryptoKey",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L244-L250 | train |
btcsuite/btcwallet | waddrmgr/manager.go | WatchOnly | func (m *Manager) WatchOnly() bool {
m.mtx.RLock()
defer m.mtx.RUnlock()
return m.watchOnly()
} | go | func (m *Manager) WatchOnly() bool {
m.mtx.RLock()
defer m.mtx.RUnlock()
return m.watchOnly()
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"WatchOnly",
"(",
")",
"bool",
"{",
"m",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"m",
".",
"watchOnly",
"(",
")",
"\n",
"}"
] | // WatchOnly returns true if the root manager is in watch only mode, and false
// otherwise. | [
"WatchOnly",
"returns",
"true",
"if",
"the",
"root",
"manager",
"is",
"in",
"watch",
"only",
"mode",
"and",
"false",
"otherwise",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L336-L341 | train |
btcsuite/btcwallet | waddrmgr/manager.go | lock | func (m *Manager) lock() {
for _, manager := range m.scopedManagers {
// Clear all of the account private keys.
for _, acctInfo := range manager.acctInfo {
if acctInfo.acctKeyPriv != nil {
acctInfo.acctKeyPriv.Zero()
}
acctInfo.acctKeyPriv = nil
}
}
// Remove clear text private keys and scripts from all address entries.
for _, manager := range m.scopedManagers {
for _, ma := range manager.addrs {
switch addr := ma.(type) {
case *managedAddress:
addr.lock()
case *scriptAddress:
addr.lock()
}
}
}
// Remove clear text private master and crypto keys from memory.
m.cryptoKeyScript.Zero()
m.cryptoKeyPriv.Zero()
m.masterKeyPriv.Zero()
// Zero the hashed passphrase.
zero.Bytea64(&m.hashedPrivPassphrase)
// NOTE: m.cryptoKeyPub is intentionally not cleared here as the address
// manager needs to be able to continue to read and decrypt public data
// which uses a separate derived key from the database even when it is
// locked.
m.locked = true
} | go | func (m *Manager) lock() {
for _, manager := range m.scopedManagers {
// Clear all of the account private keys.
for _, acctInfo := range manager.acctInfo {
if acctInfo.acctKeyPriv != nil {
acctInfo.acctKeyPriv.Zero()
}
acctInfo.acctKeyPriv = nil
}
}
// Remove clear text private keys and scripts from all address entries.
for _, manager := range m.scopedManagers {
for _, ma := range manager.addrs {
switch addr := ma.(type) {
case *managedAddress:
addr.lock()
case *scriptAddress:
addr.lock()
}
}
}
// Remove clear text private master and crypto keys from memory.
m.cryptoKeyScript.Zero()
m.cryptoKeyPriv.Zero()
m.masterKeyPriv.Zero()
// Zero the hashed passphrase.
zero.Bytea64(&m.hashedPrivPassphrase)
// NOTE: m.cryptoKeyPub is intentionally not cleared here as the address
// manager needs to be able to continue to read and decrypt public data
// which uses a separate derived key from the database even when it is
// locked.
m.locked = true
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"lock",
"(",
")",
"{",
"for",
"_",
",",
"manager",
":=",
"range",
"m",
".",
"scopedManagers",
"{",
"for",
"_",
",",
"acctInfo",
":=",
"range",
"manager",
".",
"acctInfo",
"{",
"if",
"acctInfo",
".",
"acctKeyPriv... | // lock performs a best try effort to remove and zero all secret keys associated
// with the address manager.
//
// This function MUST be called with the manager lock held for writes. | [
"lock",
"performs",
"a",
"best",
"try",
"effort",
"to",
"remove",
"and",
"zero",
"all",
"secret",
"keys",
"associated",
"with",
"the",
"address",
"manager",
".",
"This",
"function",
"MUST",
"be",
"called",
"with",
"the",
"manager",
"lock",
"held",
"for",
"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L355-L392 | train |
btcsuite/btcwallet | waddrmgr/manager.go | FetchScopedKeyManager | func (m *Manager) FetchScopedKeyManager(scope KeyScope) (*ScopedKeyManager, error) {
m.mtx.RLock()
defer m.mtx.RUnlock()
sm, ok := m.scopedManagers[scope]
if !ok {
str := fmt.Sprintf("scope %v not found", scope)
return nil, managerError(ErrScopeNotFound, str, nil)
}
return sm, nil
} | go | func (m *Manager) FetchScopedKeyManager(scope KeyScope) (*ScopedKeyManager, error) {
m.mtx.RLock()
defer m.mtx.RUnlock()
sm, ok := m.scopedManagers[scope]
if !ok {
str := fmt.Sprintf("scope %v not found", scope)
return nil, managerError(ErrScopeNotFound, str, nil)
}
return sm, nil
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"FetchScopedKeyManager",
"(",
"scope",
"KeyScope",
")",
"(",
"*",
"ScopedKeyManager",
",",
"error",
")",
"{",
"m",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"mtx",
".",
"RUnlock",
"(",
")",
... | // FetchScopedKeyManager attempts to fetch an active scoped manager according to
// its registered scope. If the manger is found, then a nil error is returned
// along with the active scoped manager. Otherwise, a nil manager and a non-nil
// error will be returned. | [
"FetchScopedKeyManager",
"attempts",
"to",
"fetch",
"an",
"active",
"scoped",
"manager",
"according",
"to",
"its",
"registered",
"scope",
".",
"If",
"the",
"manger",
"is",
"found",
"then",
"a",
"nil",
"error",
"is",
"returned",
"along",
"with",
"the",
"active"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L539-L550 | train |
btcsuite/btcwallet | waddrmgr/manager.go | ActiveScopedKeyManagers | func (m *Manager) ActiveScopedKeyManagers() []*ScopedKeyManager {
m.mtx.RLock()
defer m.mtx.RUnlock()
var scopedManagers []*ScopedKeyManager
for _, smgr := range m.scopedManagers {
scopedManagers = append(scopedManagers, smgr)
}
return scopedManagers
} | go | func (m *Manager) ActiveScopedKeyManagers() []*ScopedKeyManager {
m.mtx.RLock()
defer m.mtx.RUnlock()
var scopedManagers []*ScopedKeyManager
for _, smgr := range m.scopedManagers {
scopedManagers = append(scopedManagers, smgr)
}
return scopedManagers
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"ActiveScopedKeyManagers",
"(",
")",
"[",
"]",
"*",
"ScopedKeyManager",
"{",
"m",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"var",
"scopedManagers",
"[",... | // ActiveScopedKeyManagers returns a slice of all the active scoped key
// managers currently known by the root key manager. | [
"ActiveScopedKeyManagers",
"returns",
"a",
"slice",
"of",
"all",
"the",
"active",
"scoped",
"key",
"managers",
"currently",
"known",
"by",
"the",
"root",
"key",
"manager",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L554-L564 | train |
btcsuite/btcwallet | waddrmgr/manager.go | ScopesForExternalAddrType | func (m *Manager) ScopesForExternalAddrType(addrType AddressType) []KeyScope {
m.mtx.RLock()
defer m.mtx.RUnlock()
scopes, _ := m.externalAddrSchemas[addrType]
return scopes
} | go | func (m *Manager) ScopesForExternalAddrType(addrType AddressType) []KeyScope {
m.mtx.RLock()
defer m.mtx.RUnlock()
scopes, _ := m.externalAddrSchemas[addrType]
return scopes
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"ScopesForExternalAddrType",
"(",
"addrType",
"AddressType",
")",
"[",
"]",
"KeyScope",
"{",
"m",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"scopes",
","... | // ScopesForExternalAddrType returns the set of key scopes that are able to
// produce the target address type as external addresses. | [
"ScopesForExternalAddrType",
"returns",
"the",
"set",
"of",
"key",
"scopes",
"that",
"are",
"able",
"to",
"produce",
"the",
"target",
"address",
"type",
"as",
"external",
"addresses",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L568-L574 | train |
btcsuite/btcwallet | waddrmgr/manager.go | ScopesForInternalAddrTypes | func (m *Manager) ScopesForInternalAddrTypes(addrType AddressType) []KeyScope {
m.mtx.RLock()
defer m.mtx.RUnlock()
scopes, _ := m.internalAddrSchemas[addrType]
return scopes
} | go | func (m *Manager) ScopesForInternalAddrTypes(addrType AddressType) []KeyScope {
m.mtx.RLock()
defer m.mtx.RUnlock()
scopes, _ := m.internalAddrSchemas[addrType]
return scopes
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"ScopesForInternalAddrTypes",
"(",
"addrType",
"AddressType",
")",
"[",
"]",
"KeyScope",
"{",
"m",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"scopes",
",... | // ScopesForInternalAddrTypes returns the set of key scopes that are able to
// produce the target address type as internal addresses. | [
"ScopesForInternalAddrTypes",
"returns",
"the",
"set",
"of",
"key",
"scopes",
"that",
"are",
"able",
"to",
"produce",
"the",
"target",
"address",
"type",
"as",
"internal",
"addresses",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L578-L584 | train |
btcsuite/btcwallet | waddrmgr/manager.go | AddrAccount | func (m *Manager) AddrAccount(ns walletdb.ReadBucket,
address btcutil.Address) (*ScopedKeyManager, uint32, error) {
m.mtx.RLock()
defer m.mtx.RUnlock()
for _, scopedMgr := range m.scopedManagers {
if _, err := scopedMgr.Address(ns, address); err != nil {
continue
}
// We've found the manager that this address belongs to, so we
// can retrieve the address' account along with the manager
// that the addr belongs to.
accNo, err := scopedMgr.AddrAccount(ns, address)
if err != nil {
return nil, 0, err
}
return scopedMgr, accNo, err
}
// If we get to this point, then we weren't able to find the address in
// any of the managers, so we'll exit with an error.
str := fmt.Sprintf("unable to find key for addr %v", address)
return nil, 0, managerError(ErrAddressNotFound, str, nil)
} | go | func (m *Manager) AddrAccount(ns walletdb.ReadBucket,
address btcutil.Address) (*ScopedKeyManager, uint32, error) {
m.mtx.RLock()
defer m.mtx.RUnlock()
for _, scopedMgr := range m.scopedManagers {
if _, err := scopedMgr.Address(ns, address); err != nil {
continue
}
// We've found the manager that this address belongs to, so we
// can retrieve the address' account along with the manager
// that the addr belongs to.
accNo, err := scopedMgr.AddrAccount(ns, address)
if err != nil {
return nil, 0, err
}
return scopedMgr, accNo, err
}
// If we get to this point, then we weren't able to find the address in
// any of the managers, so we'll exit with an error.
str := fmt.Sprintf("unable to find key for addr %v", address)
return nil, 0, managerError(ErrAddressNotFound, str, nil)
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"AddrAccount",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"address",
"btcutil",
".",
"Address",
")",
"(",
"*",
"ScopedKeyManager",
",",
"uint32",
",",
"error",
")",
"{",
"m",
".",
"mtx",
".",
"RLock",
"(",
"... | // AddrAccount returns the account to which the given address belongs. We also
// return the scoped manager that owns the addr+account combo. | [
"AddrAccount",
"returns",
"the",
"account",
"to",
"which",
"the",
"given",
"address",
"belongs",
".",
"We",
"also",
"return",
"the",
"scoped",
"manager",
"that",
"owns",
"the",
"addr",
"+",
"account",
"combo",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L668-L694 | train |
btcsuite/btcwallet | waddrmgr/manager.go | IsLocked | func (m *Manager) IsLocked() bool {
m.mtx.RLock()
defer m.mtx.RUnlock()
return m.isLocked()
} | go | func (m *Manager) IsLocked() bool {
m.mtx.RLock()
defer m.mtx.RUnlock()
return m.isLocked()
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"IsLocked",
"(",
")",
"bool",
"{",
"m",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"m",
".",
"isLocked",
"(",
")",
"\n",
"}"
] | // IsLocked returns whether or not the address managed is locked. When it is
// unlocked, the decryption key needed to decrypt private keys used for signing
// is in memory. | [
"IsLocked",
"returns",
"whether",
"or",
"not",
"the",
"address",
"managed",
"is",
"locked",
".",
"When",
"it",
"is",
"unlocked",
"the",
"decryption",
"key",
"needed",
"to",
"decrypt",
"private",
"keys",
"used",
"for",
"signing",
"is",
"in",
"memory",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1007-L1012 | train |
btcsuite/btcwallet | waddrmgr/manager.go | Lock | func (m *Manager) Lock() error {
// A watching-only address manager can't be locked.
if m.watchingOnly {
return managerError(ErrWatchingOnly, errWatchingOnly, nil)
}
m.mtx.Lock()
defer m.mtx.Unlock()
// Error on attempt to lock an already locked manager.
if m.locked {
return managerError(ErrLocked, errLocked, nil)
}
m.lock()
return nil
} | go | func (m *Manager) Lock() error {
// A watching-only address manager can't be locked.
if m.watchingOnly {
return managerError(ErrWatchingOnly, errWatchingOnly, nil)
}
m.mtx.Lock()
defer m.mtx.Unlock()
// Error on attempt to lock an already locked manager.
if m.locked {
return managerError(ErrLocked, errLocked, nil)
}
m.lock()
return nil
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"Lock",
"(",
")",
"error",
"{",
"if",
"m",
".",
"watchingOnly",
"{",
"return",
"managerError",
"(",
"ErrWatchingOnly",
",",
"errWatchingOnly",
",",
"nil",
")",
"\n",
"}",
"\n",
"m",
".",
"mtx",
".",
"Lock",
"(",... | // Lock performs a best try effort to remove and zero all secret keys associated
// with the address manager.
//
// This function will return an error if invoked on a watching-only address
// manager. | [
"Lock",
"performs",
"a",
"best",
"try",
"effort",
"to",
"remove",
"and",
"zero",
"all",
"secret",
"keys",
"associated",
"with",
"the",
"address",
"manager",
".",
"This",
"function",
"will",
"return",
"an",
"error",
"if",
"invoked",
"on",
"a",
"watching",
"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1028-L1044 | train |
btcsuite/btcwallet | waddrmgr/manager.go | ValidateAccountName | func ValidateAccountName(name string) error {
if name == "" {
str := "accounts may not be named the empty string"
return managerError(ErrInvalidAccount, str, nil)
}
if isReservedAccountName(name) {
str := "reserved account name"
return managerError(ErrInvalidAccount, str, nil)
}
return nil
} | go | func ValidateAccountName(name string) error {
if name == "" {
str := "accounts may not be named the empty string"
return managerError(ErrInvalidAccount, str, nil)
}
if isReservedAccountName(name) {
str := "reserved account name"
return managerError(ErrInvalidAccount, str, nil)
}
return nil
} | [
"func",
"ValidateAccountName",
"(",
"name",
"string",
")",
"error",
"{",
"if",
"name",
"==",
"\"\"",
"{",
"str",
":=",
"\"accounts may not be named the empty string\"",
"\n",
"return",
"managerError",
"(",
"ErrInvalidAccount",
",",
"str",
",",
"nil",
")",
"\n",
... | // ValidateAccountName validates the given account name and returns an error, if any. | [
"ValidateAccountName",
"validates",
"the",
"given",
"account",
"name",
"and",
"returns",
"an",
"error",
"if",
"any",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1172-L1182 | train |
btcsuite/btcwallet | waddrmgr/manager.go | selectCryptoKey | func (m *Manager) selectCryptoKey(keyType CryptoKeyType) (EncryptorDecryptor, error) {
if keyType == CKTPrivate || keyType == CKTScript {
// The manager must be unlocked to work with the private keys.
if m.locked || m.watchingOnly {
return nil, managerError(ErrLocked, errLocked, nil)
}
}
var cryptoKey EncryptorDecryptor
switch keyType {
case CKTPrivate:
cryptoKey = m.cryptoKeyPriv
case CKTScript:
cryptoKey = m.cryptoKeyScript
case CKTPublic:
cryptoKey = m.cryptoKeyPub
default:
return nil, managerError(ErrInvalidKeyType, "invalid key type",
nil)
}
return cryptoKey, nil
} | go | func (m *Manager) selectCryptoKey(keyType CryptoKeyType) (EncryptorDecryptor, error) {
if keyType == CKTPrivate || keyType == CKTScript {
// The manager must be unlocked to work with the private keys.
if m.locked || m.watchingOnly {
return nil, managerError(ErrLocked, errLocked, nil)
}
}
var cryptoKey EncryptorDecryptor
switch keyType {
case CKTPrivate:
cryptoKey = m.cryptoKeyPriv
case CKTScript:
cryptoKey = m.cryptoKeyScript
case CKTPublic:
cryptoKey = m.cryptoKeyPub
default:
return nil, managerError(ErrInvalidKeyType, "invalid key type",
nil)
}
return cryptoKey, nil
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"selectCryptoKey",
"(",
"keyType",
"CryptoKeyType",
")",
"(",
"EncryptorDecryptor",
",",
"error",
")",
"{",
"if",
"keyType",
"==",
"CKTPrivate",
"||",
"keyType",
"==",
"CKTScript",
"{",
"if",
"m",
".",
"locked",
"||",... | // selectCryptoKey selects the appropriate crypto key based on the key type. An
// error is returned when an invalid key type is specified or the requested key
// requires the manager to be unlocked when it isn't.
//
// This function MUST be called with the manager lock held for reads. | [
"selectCryptoKey",
"selects",
"the",
"appropriate",
"crypto",
"key",
"based",
"on",
"the",
"key",
"type",
".",
"An",
"error",
"is",
"returned",
"when",
"an",
"invalid",
"key",
"type",
"is",
"specified",
"or",
"the",
"requested",
"key",
"requires",
"the",
"ma... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1189-L1211 | train |
btcsuite/btcwallet | waddrmgr/manager.go | Encrypt | func (m *Manager) Encrypt(keyType CryptoKeyType, in []byte) ([]byte, error) {
// Encryption must be performed under the manager mutex since the
// keys are cleared when the manager is locked.
m.mtx.Lock()
defer m.mtx.Unlock()
cryptoKey, err := m.selectCryptoKey(keyType)
if err != nil {
return nil, err
}
encrypted, err := cryptoKey.Encrypt(in)
if err != nil {
return nil, managerError(ErrCrypto, "failed to encrypt", err)
}
return encrypted, nil
} | go | func (m *Manager) Encrypt(keyType CryptoKeyType, in []byte) ([]byte, error) {
// Encryption must be performed under the manager mutex since the
// keys are cleared when the manager is locked.
m.mtx.Lock()
defer m.mtx.Unlock()
cryptoKey, err := m.selectCryptoKey(keyType)
if err != nil {
return nil, err
}
encrypted, err := cryptoKey.Encrypt(in)
if err != nil {
return nil, managerError(ErrCrypto, "failed to encrypt", err)
}
return encrypted, nil
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"Encrypt",
"(",
"keyType",
"CryptoKeyType",
",",
"in",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"m",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"mtx",
".",
"... | // Encrypt in using the crypto key type specified by keyType. | [
"Encrypt",
"in",
"using",
"the",
"crypto",
"key",
"type",
"specified",
"by",
"keyType",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1214-L1230 | train |
btcsuite/btcwallet | waddrmgr/manager.go | newManager | func newManager(chainParams *chaincfg.Params, masterKeyPub *snacl.SecretKey,
masterKeyPriv *snacl.SecretKey, cryptoKeyPub EncryptorDecryptor,
cryptoKeyPrivEncrypted, cryptoKeyScriptEncrypted []byte, syncInfo *syncState,
birthday time.Time, privPassphraseSalt [saltSize]byte,
scopedManagers map[KeyScope]*ScopedKeyManager) *Manager {
m := &Manager{
chainParams: chainParams,
syncState: *syncInfo,
locked: true,
birthday: birthday,
masterKeyPub: masterKeyPub,
masterKeyPriv: masterKeyPriv,
cryptoKeyPub: cryptoKeyPub,
cryptoKeyPrivEncrypted: cryptoKeyPrivEncrypted,
cryptoKeyPriv: &cryptoKey{},
cryptoKeyScriptEncrypted: cryptoKeyScriptEncrypted,
cryptoKeyScript: &cryptoKey{},
privPassphraseSalt: privPassphraseSalt,
scopedManagers: scopedManagers,
externalAddrSchemas: make(map[AddressType][]KeyScope),
internalAddrSchemas: make(map[AddressType][]KeyScope),
}
for _, sMgr := range m.scopedManagers {
externalType := sMgr.AddrSchema().ExternalAddrType
internalType := sMgr.AddrSchema().InternalAddrType
scope := sMgr.Scope()
m.externalAddrSchemas[externalType] = append(
m.externalAddrSchemas[externalType], scope,
)
m.internalAddrSchemas[internalType] = append(
m.internalAddrSchemas[internalType], scope,
)
}
return m
} | go | func newManager(chainParams *chaincfg.Params, masterKeyPub *snacl.SecretKey,
masterKeyPriv *snacl.SecretKey, cryptoKeyPub EncryptorDecryptor,
cryptoKeyPrivEncrypted, cryptoKeyScriptEncrypted []byte, syncInfo *syncState,
birthday time.Time, privPassphraseSalt [saltSize]byte,
scopedManagers map[KeyScope]*ScopedKeyManager) *Manager {
m := &Manager{
chainParams: chainParams,
syncState: *syncInfo,
locked: true,
birthday: birthday,
masterKeyPub: masterKeyPub,
masterKeyPriv: masterKeyPriv,
cryptoKeyPub: cryptoKeyPub,
cryptoKeyPrivEncrypted: cryptoKeyPrivEncrypted,
cryptoKeyPriv: &cryptoKey{},
cryptoKeyScriptEncrypted: cryptoKeyScriptEncrypted,
cryptoKeyScript: &cryptoKey{},
privPassphraseSalt: privPassphraseSalt,
scopedManagers: scopedManagers,
externalAddrSchemas: make(map[AddressType][]KeyScope),
internalAddrSchemas: make(map[AddressType][]KeyScope),
}
for _, sMgr := range m.scopedManagers {
externalType := sMgr.AddrSchema().ExternalAddrType
internalType := sMgr.AddrSchema().InternalAddrType
scope := sMgr.Scope()
m.externalAddrSchemas[externalType] = append(
m.externalAddrSchemas[externalType], scope,
)
m.internalAddrSchemas[internalType] = append(
m.internalAddrSchemas[internalType], scope,
)
}
return m
} | [
"func",
"newManager",
"(",
"chainParams",
"*",
"chaincfg",
".",
"Params",
",",
"masterKeyPub",
"*",
"snacl",
".",
"SecretKey",
",",
"masterKeyPriv",
"*",
"snacl",
".",
"SecretKey",
",",
"cryptoKeyPub",
"EncryptorDecryptor",
",",
"cryptoKeyPrivEncrypted",
",",
"cry... | // newManager returns a new locked address manager with the given parameters. | [
"newManager",
"returns",
"a",
"new",
"locked",
"address",
"manager",
"with",
"the",
"given",
"parameters",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1252-L1290 | train |
btcsuite/btcwallet | waddrmgr/manager.go | Open | func Open(ns walletdb.ReadBucket, pubPassphrase []byte,
chainParams *chaincfg.Params) (*Manager, error) {
// Return an error if the manager has NOT already been created in the
// given database namespace.
exists := managerExists(ns)
if !exists {
str := "the specified address manager does not exist"
return nil, managerError(ErrNoExist, str, nil)
}
return loadManager(ns, pubPassphrase, chainParams)
} | go | func Open(ns walletdb.ReadBucket, pubPassphrase []byte,
chainParams *chaincfg.Params) (*Manager, error) {
// Return an error if the manager has NOT already been created in the
// given database namespace.
exists := managerExists(ns)
if !exists {
str := "the specified address manager does not exist"
return nil, managerError(ErrNoExist, str, nil)
}
return loadManager(ns, pubPassphrase, chainParams)
} | [
"func",
"Open",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"pubPassphrase",
"[",
"]",
"byte",
",",
"chainParams",
"*",
"chaincfg",
".",
"Params",
")",
"(",
"*",
"Manager",
",",
"error",
")",
"{",
"exists",
":=",
"managerExists",
"(",
"ns",
")",
"\n... | // Open loads an existing address manager from the given namespace. The public
// passphrase is required to decrypt the public keys used to protect the public
// information such as addresses. This is important since access to BIP0032
// extended keys means it is possible to generate all future addresses.
//
// If a config structure is passed to the function, that configuration will
// override the defaults.
//
// A ManagerError with an error code of ErrNoExist will be returned if the
// passed manager does not exist in the specified namespace. | [
"Open",
"loads",
"an",
"existing",
"address",
"manager",
"from",
"the",
"given",
"namespace",
".",
"The",
"public",
"passphrase",
"is",
"required",
"to",
"decrypt",
"the",
"public",
"keys",
"used",
"to",
"protect",
"the",
"public",
"information",
"such",
"as",... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1519-L1531 | train |
btcsuite/btcwallet | waddrmgr/manager.go | createManagerKeyScope | func createManagerKeyScope(ns walletdb.ReadWriteBucket,
scope KeyScope, root *hdkeychain.ExtendedKey,
cryptoKeyPub, cryptoKeyPriv EncryptorDecryptor) error {
// Derive the cointype key according to the passed scope.
coinTypeKeyPriv, err := deriveCoinTypeKey(root, scope)
if err != nil {
str := "failed to derive cointype extended key"
return managerError(ErrKeyChain, str, err)
}
defer coinTypeKeyPriv.Zero()
// Derive the account key for the first account according our
// BIP0044-like derivation.
acctKeyPriv, err := deriveAccountKey(coinTypeKeyPriv, 0)
if err != nil {
// The seed is unusable if the any of the children in the
// required hierarchy can't be derived due to invalid child.
if err == hdkeychain.ErrInvalidChild {
str := "the provided seed is unusable"
return managerError(ErrKeyChain, str,
hdkeychain.ErrUnusableSeed)
}
return err
}
// Ensure the branch keys can be derived for the provided seed according
// to our BIP0044-like derivation.
if err := checkBranchKeys(acctKeyPriv); err != nil {
// The seed is unusable if the any of the children in the
// required hierarchy can't be derived due to invalid child.
if err == hdkeychain.ErrInvalidChild {
str := "the provided seed is unusable"
return managerError(ErrKeyChain, str,
hdkeychain.ErrUnusableSeed)
}
return err
}
// The address manager needs the public extended key for the account.
acctKeyPub, err := acctKeyPriv.Neuter()
if err != nil {
str := "failed to convert private key for account 0"
return managerError(ErrKeyChain, str, err)
}
// Encrypt the cointype keys with the associated crypto keys.
coinTypeKeyPub, err := coinTypeKeyPriv.Neuter()
if err != nil {
str := "failed to convert cointype private key"
return managerError(ErrKeyChain, str, err)
}
coinTypePubEnc, err := cryptoKeyPub.Encrypt([]byte(coinTypeKeyPub.String()))
if err != nil {
str := "failed to encrypt cointype public key"
return managerError(ErrCrypto, str, err)
}
coinTypePrivEnc, err := cryptoKeyPriv.Encrypt([]byte(coinTypeKeyPriv.String()))
if err != nil {
str := "failed to encrypt cointype private key"
return managerError(ErrCrypto, str, err)
}
// Encrypt the default account keys with the associated crypto keys.
acctPubEnc, err := cryptoKeyPub.Encrypt([]byte(acctKeyPub.String()))
if err != nil {
str := "failed to encrypt public key for account 0"
return managerError(ErrCrypto, str, err)
}
acctPrivEnc, err := cryptoKeyPriv.Encrypt([]byte(acctKeyPriv.String()))
if err != nil {
str := "failed to encrypt private key for account 0"
return managerError(ErrCrypto, str, err)
}
// Save the encrypted cointype keys to the database.
err = putCoinTypeKeys(ns, &scope, coinTypePubEnc, coinTypePrivEnc)
if err != nil {
return err
}
// Save the information for the default account to the database.
err = putAccountInfo(
ns, &scope, DefaultAccountNum, acctPubEnc, acctPrivEnc, 0, 0,
defaultAccountName,
)
if err != nil {
return err
}
return putAccountInfo(
ns, &scope, ImportedAddrAccount, nil, nil, 0, 0,
ImportedAddrAccountName,
)
} | go | func createManagerKeyScope(ns walletdb.ReadWriteBucket,
scope KeyScope, root *hdkeychain.ExtendedKey,
cryptoKeyPub, cryptoKeyPriv EncryptorDecryptor) error {
// Derive the cointype key according to the passed scope.
coinTypeKeyPriv, err := deriveCoinTypeKey(root, scope)
if err != nil {
str := "failed to derive cointype extended key"
return managerError(ErrKeyChain, str, err)
}
defer coinTypeKeyPriv.Zero()
// Derive the account key for the first account according our
// BIP0044-like derivation.
acctKeyPriv, err := deriveAccountKey(coinTypeKeyPriv, 0)
if err != nil {
// The seed is unusable if the any of the children in the
// required hierarchy can't be derived due to invalid child.
if err == hdkeychain.ErrInvalidChild {
str := "the provided seed is unusable"
return managerError(ErrKeyChain, str,
hdkeychain.ErrUnusableSeed)
}
return err
}
// Ensure the branch keys can be derived for the provided seed according
// to our BIP0044-like derivation.
if err := checkBranchKeys(acctKeyPriv); err != nil {
// The seed is unusable if the any of the children in the
// required hierarchy can't be derived due to invalid child.
if err == hdkeychain.ErrInvalidChild {
str := "the provided seed is unusable"
return managerError(ErrKeyChain, str,
hdkeychain.ErrUnusableSeed)
}
return err
}
// The address manager needs the public extended key for the account.
acctKeyPub, err := acctKeyPriv.Neuter()
if err != nil {
str := "failed to convert private key for account 0"
return managerError(ErrKeyChain, str, err)
}
// Encrypt the cointype keys with the associated crypto keys.
coinTypeKeyPub, err := coinTypeKeyPriv.Neuter()
if err != nil {
str := "failed to convert cointype private key"
return managerError(ErrKeyChain, str, err)
}
coinTypePubEnc, err := cryptoKeyPub.Encrypt([]byte(coinTypeKeyPub.String()))
if err != nil {
str := "failed to encrypt cointype public key"
return managerError(ErrCrypto, str, err)
}
coinTypePrivEnc, err := cryptoKeyPriv.Encrypt([]byte(coinTypeKeyPriv.String()))
if err != nil {
str := "failed to encrypt cointype private key"
return managerError(ErrCrypto, str, err)
}
// Encrypt the default account keys with the associated crypto keys.
acctPubEnc, err := cryptoKeyPub.Encrypt([]byte(acctKeyPub.String()))
if err != nil {
str := "failed to encrypt public key for account 0"
return managerError(ErrCrypto, str, err)
}
acctPrivEnc, err := cryptoKeyPriv.Encrypt([]byte(acctKeyPriv.String()))
if err != nil {
str := "failed to encrypt private key for account 0"
return managerError(ErrCrypto, str, err)
}
// Save the encrypted cointype keys to the database.
err = putCoinTypeKeys(ns, &scope, coinTypePubEnc, coinTypePrivEnc)
if err != nil {
return err
}
// Save the information for the default account to the database.
err = putAccountInfo(
ns, &scope, DefaultAccountNum, acctPubEnc, acctPrivEnc, 0, 0,
defaultAccountName,
)
if err != nil {
return err
}
return putAccountInfo(
ns, &scope, ImportedAddrAccount, nil, nil, 0, 0,
ImportedAddrAccountName,
)
} | [
"func",
"createManagerKeyScope",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"scope",
"KeyScope",
",",
"root",
"*",
"hdkeychain",
".",
"ExtendedKey",
",",
"cryptoKeyPub",
",",
"cryptoKeyPriv",
"EncryptorDecryptor",
")",
"error",
"{",
"coinTypeKeyPriv",
",",
... | // createManagerKeyScope creates a new key scoped for a target manager's scope.
// This partitions key derivation for a particular purpose+coin tuple, allowing
// multiple address derivation schems to be maintained concurrently. | [
"createManagerKeyScope",
"creates",
"a",
"new",
"key",
"scoped",
"for",
"a",
"target",
"manager",
"s",
"scope",
".",
"This",
"partitions",
"key",
"derivation",
"for",
"a",
"particular",
"purpose",
"+",
"coin",
"tuple",
"allowing",
"multiple",
"address",
"derivat... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1536-L1632 | train |
btcsuite/btcwallet | walletsetup.go | networkDir | func networkDir(dataDir string, chainParams *chaincfg.Params) string {
netname := chainParams.Name
// For now, we must always name the testnet data directory as "testnet"
// and not "testnet3" or any other version, as the chaincfg testnet3
// paramaters will likely be switched to being named "testnet3" in the
// future. This is done to future proof that change, and an upgrade
// plan to move the testnet3 data directory can be worked out later.
if chainParams.Net == wire.TestNet3 {
netname = "testnet"
}
return filepath.Join(dataDir, netname)
} | go | func networkDir(dataDir string, chainParams *chaincfg.Params) string {
netname := chainParams.Name
// For now, we must always name the testnet data directory as "testnet"
// and not "testnet3" or any other version, as the chaincfg testnet3
// paramaters will likely be switched to being named "testnet3" in the
// future. This is done to future proof that change, and an upgrade
// plan to move the testnet3 data directory can be worked out later.
if chainParams.Net == wire.TestNet3 {
netname = "testnet"
}
return filepath.Join(dataDir, netname)
} | [
"func",
"networkDir",
"(",
"dataDir",
"string",
",",
"chainParams",
"*",
"chaincfg",
".",
"Params",
")",
"string",
"{",
"netname",
":=",
"chainParams",
".",
"Name",
"\n",
"if",
"chainParams",
".",
"Net",
"==",
"wire",
".",
"TestNet3",
"{",
"netname",
"=",
... | // networkDir returns the directory name of a network directory to hold wallet
// files. | [
"networkDir",
"returns",
"the",
"directory",
"name",
"of",
"a",
"network",
"directory",
"to",
"hold",
"wallet",
"files",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletsetup.go#L28-L41 | train |
btcsuite/btcwallet | walletsetup.go | convertLegacyKeystore | func convertLegacyKeystore(legacyKeyStore *keystore.Store, w *wallet.Wallet) error {
netParams := legacyKeyStore.Net()
blockStamp := waddrmgr.BlockStamp{
Height: 0,
Hash: *netParams.GenesisHash,
}
for _, walletAddr := range legacyKeyStore.ActiveAddresses() {
switch addr := walletAddr.(type) {
case keystore.PubKeyAddress:
privKey, err := addr.PrivKey()
if err != nil {
fmt.Printf("WARN: Failed to obtain private key "+
"for address %v: %v\n", addr.Address(),
err)
continue
}
wif, err := btcutil.NewWIF((*btcec.PrivateKey)(privKey),
netParams, addr.Compressed())
if err != nil {
fmt.Printf("WARN: Failed to create wallet "+
"import format for address %v: %v\n",
addr.Address(), err)
continue
}
_, err = w.ImportPrivateKey(waddrmgr.KeyScopeBIP0044,
wif, &blockStamp, false)
if err != nil {
fmt.Printf("WARN: Failed to import private "+
"key for address %v: %v\n",
addr.Address(), err)
continue
}
case keystore.ScriptAddress:
_, err := w.ImportP2SHRedeemScript(addr.Script())
if err != nil {
fmt.Printf("WARN: Failed to import "+
"pay-to-script-hash script for "+
"address %v: %v\n", addr.Address(), err)
continue
}
default:
fmt.Printf("WARN: Skipping unrecognized legacy "+
"keystore type: %T\n", addr)
continue
}
}
return nil
} | go | func convertLegacyKeystore(legacyKeyStore *keystore.Store, w *wallet.Wallet) error {
netParams := legacyKeyStore.Net()
blockStamp := waddrmgr.BlockStamp{
Height: 0,
Hash: *netParams.GenesisHash,
}
for _, walletAddr := range legacyKeyStore.ActiveAddresses() {
switch addr := walletAddr.(type) {
case keystore.PubKeyAddress:
privKey, err := addr.PrivKey()
if err != nil {
fmt.Printf("WARN: Failed to obtain private key "+
"for address %v: %v\n", addr.Address(),
err)
continue
}
wif, err := btcutil.NewWIF((*btcec.PrivateKey)(privKey),
netParams, addr.Compressed())
if err != nil {
fmt.Printf("WARN: Failed to create wallet "+
"import format for address %v: %v\n",
addr.Address(), err)
continue
}
_, err = w.ImportPrivateKey(waddrmgr.KeyScopeBIP0044,
wif, &blockStamp, false)
if err != nil {
fmt.Printf("WARN: Failed to import private "+
"key for address %v: %v\n",
addr.Address(), err)
continue
}
case keystore.ScriptAddress:
_, err := w.ImportP2SHRedeemScript(addr.Script())
if err != nil {
fmt.Printf("WARN: Failed to import "+
"pay-to-script-hash script for "+
"address %v: %v\n", addr.Address(), err)
continue
}
default:
fmt.Printf("WARN: Skipping unrecognized legacy "+
"keystore type: %T\n", addr)
continue
}
}
return nil
} | [
"func",
"convertLegacyKeystore",
"(",
"legacyKeyStore",
"*",
"keystore",
".",
"Store",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"error",
"{",
"netParams",
":=",
"legacyKeyStore",
".",
"Net",
"(",
")",
"\n",
"blockStamp",
":=",
"waddrmgr",
".",
"BlockStam... | // convertLegacyKeystore converts all of the addresses in the passed legacy
// key store to the new waddrmgr.Manager format. Both the legacy keystore and
// the new manager must be unlocked. | [
"convertLegacyKeystore",
"converts",
"all",
"of",
"the",
"addresses",
"in",
"the",
"passed",
"legacy",
"key",
"store",
"to",
"the",
"new",
"waddrmgr",
".",
"Manager",
"format",
".",
"Both",
"the",
"legacy",
"keystore",
"and",
"the",
"new",
"manager",
"must",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletsetup.go#L46-L98 | train |
btcsuite/btcwallet | walletsetup.go | createWallet | func createWallet(cfg *config) error {
dbDir := networkDir(cfg.AppDataDir.Value, activeNet.Params)
loader := wallet.NewLoader(activeNet.Params, dbDir, 250)
// When there is a legacy keystore, open it now to ensure any errors
// don't end up exiting the process after the user has spent time
// entering a bunch of information.
netDir := networkDir(cfg.AppDataDir.Value, activeNet.Params)
keystorePath := filepath.Join(netDir, keystore.Filename)
var legacyKeyStore *keystore.Store
_, err := os.Stat(keystorePath)
if err != nil && !os.IsNotExist(err) {
// A stat error not due to a non-existant file should be
// returned to the caller.
return err
} else if err == nil {
// Keystore file exists.
legacyKeyStore, err = keystore.OpenDir(netDir)
if err != nil {
return err
}
}
// Start by prompting for the private passphrase. When there is an
// existing keystore, the user will be promped for that passphrase,
// otherwise they will be prompted for a new one.
reader := bufio.NewReader(os.Stdin)
privPass, err := prompt.PrivatePass(reader, legacyKeyStore)
if err != nil {
return err
}
// When there exists a legacy keystore, unlock it now and set up a
// callback to import all keystore keys into the new walletdb
// wallet
if legacyKeyStore != nil {
err = legacyKeyStore.Unlock(privPass)
if err != nil {
return err
}
// Import the addresses in the legacy keystore to the new wallet if
// any exist, locking each wallet again when finished.
loader.RunAfterLoad(func(w *wallet.Wallet) {
defer legacyKeyStore.Lock()
fmt.Println("Importing addresses from existing wallet...")
lockChan := make(chan time.Time, 1)
defer func() {
lockChan <- time.Time{}
}()
err := w.Unlock(privPass, lockChan)
if err != nil {
fmt.Printf("ERR: Failed to unlock new wallet "+
"during old wallet key import: %v", err)
return
}
err = convertLegacyKeystore(legacyKeyStore, w)
if err != nil {
fmt.Printf("ERR: Failed to import keys from old "+
"wallet format: %v", err)
return
}
// Remove the legacy key store.
err = os.Remove(keystorePath)
if err != nil {
fmt.Printf("WARN: Failed to remove legacy wallet "+
"from'%s'\n", keystorePath)
}
})
}
// Ascertain the public passphrase. This will either be a value
// specified by the user or the default hard-coded public passphrase if
// the user does not want the additional public data encryption.
pubPass, err := prompt.PublicPass(reader, privPass,
[]byte(wallet.InsecurePubPassphrase), []byte(cfg.WalletPass))
if err != nil {
return err
}
// Ascertain the wallet generation seed. This will either be an
// automatically generated value the user has already confirmed or a
// value the user has entered which has already been validated.
seed, err := prompt.Seed(reader)
if err != nil {
return err
}
fmt.Println("Creating the wallet...")
w, err := loader.CreateNewWallet(pubPass, privPass, seed, time.Now())
if err != nil {
return err
}
w.Manager.Close()
fmt.Println("The wallet has been created successfully.")
return nil
} | go | func createWallet(cfg *config) error {
dbDir := networkDir(cfg.AppDataDir.Value, activeNet.Params)
loader := wallet.NewLoader(activeNet.Params, dbDir, 250)
// When there is a legacy keystore, open it now to ensure any errors
// don't end up exiting the process after the user has spent time
// entering a bunch of information.
netDir := networkDir(cfg.AppDataDir.Value, activeNet.Params)
keystorePath := filepath.Join(netDir, keystore.Filename)
var legacyKeyStore *keystore.Store
_, err := os.Stat(keystorePath)
if err != nil && !os.IsNotExist(err) {
// A stat error not due to a non-existant file should be
// returned to the caller.
return err
} else if err == nil {
// Keystore file exists.
legacyKeyStore, err = keystore.OpenDir(netDir)
if err != nil {
return err
}
}
// Start by prompting for the private passphrase. When there is an
// existing keystore, the user will be promped for that passphrase,
// otherwise they will be prompted for a new one.
reader := bufio.NewReader(os.Stdin)
privPass, err := prompt.PrivatePass(reader, legacyKeyStore)
if err != nil {
return err
}
// When there exists a legacy keystore, unlock it now and set up a
// callback to import all keystore keys into the new walletdb
// wallet
if legacyKeyStore != nil {
err = legacyKeyStore.Unlock(privPass)
if err != nil {
return err
}
// Import the addresses in the legacy keystore to the new wallet if
// any exist, locking each wallet again when finished.
loader.RunAfterLoad(func(w *wallet.Wallet) {
defer legacyKeyStore.Lock()
fmt.Println("Importing addresses from existing wallet...")
lockChan := make(chan time.Time, 1)
defer func() {
lockChan <- time.Time{}
}()
err := w.Unlock(privPass, lockChan)
if err != nil {
fmt.Printf("ERR: Failed to unlock new wallet "+
"during old wallet key import: %v", err)
return
}
err = convertLegacyKeystore(legacyKeyStore, w)
if err != nil {
fmt.Printf("ERR: Failed to import keys from old "+
"wallet format: %v", err)
return
}
// Remove the legacy key store.
err = os.Remove(keystorePath)
if err != nil {
fmt.Printf("WARN: Failed to remove legacy wallet "+
"from'%s'\n", keystorePath)
}
})
}
// Ascertain the public passphrase. This will either be a value
// specified by the user or the default hard-coded public passphrase if
// the user does not want the additional public data encryption.
pubPass, err := prompt.PublicPass(reader, privPass,
[]byte(wallet.InsecurePubPassphrase), []byte(cfg.WalletPass))
if err != nil {
return err
}
// Ascertain the wallet generation seed. This will either be an
// automatically generated value the user has already confirmed or a
// value the user has entered which has already been validated.
seed, err := prompt.Seed(reader)
if err != nil {
return err
}
fmt.Println("Creating the wallet...")
w, err := loader.CreateNewWallet(pubPass, privPass, seed, time.Now())
if err != nil {
return err
}
w.Manager.Close()
fmt.Println("The wallet has been created successfully.")
return nil
} | [
"func",
"createWallet",
"(",
"cfg",
"*",
"config",
")",
"error",
"{",
"dbDir",
":=",
"networkDir",
"(",
"cfg",
".",
"AppDataDir",
".",
"Value",
",",
"activeNet",
".",
"Params",
")",
"\n",
"loader",
":=",
"wallet",
".",
"NewLoader",
"(",
"activeNet",
".",... | // createWallet prompts the user for information needed to generate a new wallet
// and generates the wallet accordingly. The new wallet will reside at the
// provided path. | [
"createWallet",
"prompts",
"the",
"user",
"for",
"information",
"needed",
"to",
"generate",
"a",
"new",
"wallet",
"and",
"generates",
"the",
"wallet",
"accordingly",
".",
"The",
"new",
"wallet",
"will",
"reside",
"at",
"the",
"provided",
"path",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletsetup.go#L103-L204 | train |
btcsuite/btcwallet | walletsetup.go | createSimulationWallet | func createSimulationWallet(cfg *config) error {
// Simulation wallet password is 'password'.
privPass := []byte("password")
// Public passphrase is the default.
pubPass := []byte(wallet.InsecurePubPassphrase)
netDir := networkDir(cfg.AppDataDir.Value, activeNet.Params)
// Create the wallet.
dbPath := filepath.Join(netDir, walletDbName)
fmt.Println("Creating the wallet...")
// Create the wallet database backed by bolt db.
db, err := walletdb.Create("bdb", dbPath)
if err != nil {
return err
}
defer db.Close()
// Create the wallet.
err = wallet.Create(db, pubPass, privPass, nil, activeNet.Params, time.Now())
if err != nil {
return err
}
fmt.Println("The wallet has been created successfully.")
return nil
} | go | func createSimulationWallet(cfg *config) error {
// Simulation wallet password is 'password'.
privPass := []byte("password")
// Public passphrase is the default.
pubPass := []byte(wallet.InsecurePubPassphrase)
netDir := networkDir(cfg.AppDataDir.Value, activeNet.Params)
// Create the wallet.
dbPath := filepath.Join(netDir, walletDbName)
fmt.Println("Creating the wallet...")
// Create the wallet database backed by bolt db.
db, err := walletdb.Create("bdb", dbPath)
if err != nil {
return err
}
defer db.Close()
// Create the wallet.
err = wallet.Create(db, pubPass, privPass, nil, activeNet.Params, time.Now())
if err != nil {
return err
}
fmt.Println("The wallet has been created successfully.")
return nil
} | [
"func",
"createSimulationWallet",
"(",
"cfg",
"*",
"config",
")",
"error",
"{",
"privPass",
":=",
"[",
"]",
"byte",
"(",
"\"password\"",
")",
"\n",
"pubPass",
":=",
"[",
"]",
"byte",
"(",
"wallet",
".",
"InsecurePubPassphrase",
")",
"\n",
"netDir",
":=",
... | // createSimulationWallet is intended to be called from the rpcclient
// and used to create a wallet for actors involved in simulations. | [
"createSimulationWallet",
"is",
"intended",
"to",
"be",
"called",
"from",
"the",
"rpcclient",
"and",
"used",
"to",
"create",
"a",
"wallet",
"for",
"actors",
"involved",
"in",
"simulations",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletsetup.go#L208-L236 | train |
btcsuite/btcwallet | walletsetup.go | checkCreateDir | func checkCreateDir(path string) error {
if fi, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
// Attempt data directory creation
if err = os.MkdirAll(path, 0700); err != nil {
return fmt.Errorf("cannot create directory: %s", err)
}
} else {
return fmt.Errorf("error checking directory: %s", err)
}
} else {
if !fi.IsDir() {
return fmt.Errorf("path '%s' is not a directory", path)
}
}
return nil
} | go | func checkCreateDir(path string) error {
if fi, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
// Attempt data directory creation
if err = os.MkdirAll(path, 0700); err != nil {
return fmt.Errorf("cannot create directory: %s", err)
}
} else {
return fmt.Errorf("error checking directory: %s", err)
}
} else {
if !fi.IsDir() {
return fmt.Errorf("path '%s' is not a directory", path)
}
}
return nil
} | [
"func",
"checkCreateDir",
"(",
"path",
"string",
")",
"error",
"{",
"if",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"path",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"if",
"err",
"=",
"os",
".... | // checkCreateDir checks that the path exists and is a directory.
// If path does not exist, it is created. | [
"checkCreateDir",
"checks",
"that",
"the",
"path",
"exists",
"and",
"is",
"a",
"directory",
".",
"If",
"path",
"does",
"not",
"exist",
"it",
"is",
"created",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletsetup.go#L240-L257 | train |
btcsuite/btcwallet | waddrmgr/db.go | maybeConvertDbError | func maybeConvertDbError(err error) error {
// When the error is already a ManagerError, just return it.
if _, ok := err.(ManagerError); ok {
return err
}
return managerError(ErrDatabase, err.Error(), err)
} | go | func maybeConvertDbError(err error) error {
// When the error is already a ManagerError, just return it.
if _, ok := err.(ManagerError); ok {
return err
}
return managerError(ErrDatabase, err.Error(), err)
} | [
"func",
"maybeConvertDbError",
"(",
"err",
"error",
")",
"error",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"ManagerError",
")",
";",
"ok",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"err",
".",
... | // maybeConvertDbError converts the passed error to a ManagerError with an
// error code of ErrDatabase if it is not already a ManagerError. This is
// useful for potential errors returned from managed transaction an other parts
// of the walletdb database. | [
"maybeConvertDbError",
"converts",
"the",
"passed",
"error",
"to",
"a",
"ManagerError",
"with",
"an",
"error",
"code",
"of",
"ErrDatabase",
"if",
"it",
"is",
"not",
"already",
"a",
"ManagerError",
".",
"This",
"is",
"useful",
"for",
"potential",
"errors",
"ret... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L37-L44 | train |
btcsuite/btcwallet | waddrmgr/db.go | scopeToBytes | func scopeToBytes(scope *KeyScope) [scopeKeySize]byte {
var scopeBytes [scopeKeySize]byte
binary.LittleEndian.PutUint32(scopeBytes[:], scope.Purpose)
binary.LittleEndian.PutUint32(scopeBytes[4:], scope.Coin)
return scopeBytes
} | go | func scopeToBytes(scope *KeyScope) [scopeKeySize]byte {
var scopeBytes [scopeKeySize]byte
binary.LittleEndian.PutUint32(scopeBytes[:], scope.Purpose)
binary.LittleEndian.PutUint32(scopeBytes[4:], scope.Coin)
return scopeBytes
} | [
"func",
"scopeToBytes",
"(",
"scope",
"*",
"KeyScope",
")",
"[",
"scopeKeySize",
"]",
"byte",
"{",
"var",
"scopeBytes",
"[",
"scopeKeySize",
"]",
"byte",
"\n",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"scopeBytes",
"[",
":",
"]",
",",
"scope",... | // scopeToBytes transforms a manager's scope into the form that will be used to
// retrieve the bucket that all information for a particular scope is stored
// under | [
"scopeToBytes",
"transforms",
"a",
"manager",
"s",
"scope",
"into",
"the",
"form",
"that",
"will",
"be",
"used",
"to",
"retrieve",
"the",
"bucket",
"that",
"all",
"information",
"for",
"a",
"particular",
"scope",
"is",
"stored",
"under"
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L299-L305 | train |
btcsuite/btcwallet | waddrmgr/db.go | scopeFromBytes | func scopeFromBytes(scopeBytes []byte) KeyScope {
return KeyScope{
Purpose: binary.LittleEndian.Uint32(scopeBytes[:]),
Coin: binary.LittleEndian.Uint32(scopeBytes[4:]),
}
} | go | func scopeFromBytes(scopeBytes []byte) KeyScope {
return KeyScope{
Purpose: binary.LittleEndian.Uint32(scopeBytes[:]),
Coin: binary.LittleEndian.Uint32(scopeBytes[4:]),
}
} | [
"func",
"scopeFromBytes",
"(",
"scopeBytes",
"[",
"]",
"byte",
")",
"KeyScope",
"{",
"return",
"KeyScope",
"{",
"Purpose",
":",
"binary",
".",
"LittleEndian",
".",
"Uint32",
"(",
"scopeBytes",
"[",
":",
"]",
")",
",",
"Coin",
":",
"binary",
".",
"LittleE... | // scopeFromBytes decodes a serializes manager scope into its concrete manager
// scope struct. | [
"scopeFromBytes",
"decodes",
"a",
"serializes",
"manager",
"scope",
"into",
"its",
"concrete",
"manager",
"scope",
"struct",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L309-L314 | train |
btcsuite/btcwallet | waddrmgr/db.go | scopeSchemaToBytes | func scopeSchemaToBytes(schema *ScopeAddrSchema) []byte {
var schemaBytes [2]byte
schemaBytes[0] = byte(schema.InternalAddrType)
schemaBytes[1] = byte(schema.ExternalAddrType)
return schemaBytes[:]
} | go | func scopeSchemaToBytes(schema *ScopeAddrSchema) []byte {
var schemaBytes [2]byte
schemaBytes[0] = byte(schema.InternalAddrType)
schemaBytes[1] = byte(schema.ExternalAddrType)
return schemaBytes[:]
} | [
"func",
"scopeSchemaToBytes",
"(",
"schema",
"*",
"ScopeAddrSchema",
")",
"[",
"]",
"byte",
"{",
"var",
"schemaBytes",
"[",
"2",
"]",
"byte",
"\n",
"schemaBytes",
"[",
"0",
"]",
"=",
"byte",
"(",
"schema",
".",
"InternalAddrType",
")",
"\n",
"schemaBytes",... | // scopeSchemaToBytes encodes the passed scope schema as a set of bytes
// suitable for storage within the database. | [
"scopeSchemaToBytes",
"encodes",
"the",
"passed",
"scope",
"schema",
"as",
"a",
"set",
"of",
"bytes",
"suitable",
"for",
"storage",
"within",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L318-L324 | train |
btcsuite/btcwallet | waddrmgr/db.go | scopeSchemaFromBytes | func scopeSchemaFromBytes(schemaBytes []byte) *ScopeAddrSchema {
return &ScopeAddrSchema{
InternalAddrType: AddressType(schemaBytes[0]),
ExternalAddrType: AddressType(schemaBytes[1]),
}
} | go | func scopeSchemaFromBytes(schemaBytes []byte) *ScopeAddrSchema {
return &ScopeAddrSchema{
InternalAddrType: AddressType(schemaBytes[0]),
ExternalAddrType: AddressType(schemaBytes[1]),
}
} | [
"func",
"scopeSchemaFromBytes",
"(",
"schemaBytes",
"[",
"]",
"byte",
")",
"*",
"ScopeAddrSchema",
"{",
"return",
"&",
"ScopeAddrSchema",
"{",
"InternalAddrType",
":",
"AddressType",
"(",
"schemaBytes",
"[",
"0",
"]",
")",
",",
"ExternalAddrType",
":",
"AddressT... | // scopeSchemaFromBytes decodes a new scope schema instance from the set of
// serialized bytes. | [
"scopeSchemaFromBytes",
"decodes",
"a",
"new",
"scope",
"schema",
"instance",
"from",
"the",
"set",
"of",
"serialized",
"bytes",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L328-L333 | train |
btcsuite/btcwallet | waddrmgr/db.go | fetchScopeAddrSchema | func fetchScopeAddrSchema(ns walletdb.ReadBucket,
scope *KeyScope) (*ScopeAddrSchema, error) {
schemaBucket := ns.NestedReadBucket(scopeSchemaBucketName)
if schemaBucket == nil {
str := fmt.Sprintf("unable to find scope schema bucket")
return nil, managerError(ErrScopeNotFound, str, nil)
}
scopeKey := scopeToBytes(scope)
schemaBytes := schemaBucket.Get(scopeKey[:])
if schemaBytes == nil {
str := fmt.Sprintf("unable to find scope %v", scope)
return nil, managerError(ErrScopeNotFound, str, nil)
}
return scopeSchemaFromBytes(schemaBytes), nil
} | go | func fetchScopeAddrSchema(ns walletdb.ReadBucket,
scope *KeyScope) (*ScopeAddrSchema, error) {
schemaBucket := ns.NestedReadBucket(scopeSchemaBucketName)
if schemaBucket == nil {
str := fmt.Sprintf("unable to find scope schema bucket")
return nil, managerError(ErrScopeNotFound, str, nil)
}
scopeKey := scopeToBytes(scope)
schemaBytes := schemaBucket.Get(scopeKey[:])
if schemaBytes == nil {
str := fmt.Sprintf("unable to find scope %v", scope)
return nil, managerError(ErrScopeNotFound, str, nil)
}
return scopeSchemaFromBytes(schemaBytes), nil
} | [
"func",
"fetchScopeAddrSchema",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"scope",
"*",
"KeyScope",
")",
"(",
"*",
"ScopeAddrSchema",
",",
"error",
")",
"{",
"schemaBucket",
":=",
"ns",
".",
"NestedReadBucket",
"(",
"scopeSchemaBucketName",
")",
"\n",
"if... | // fetchScopeAddrSchema will attempt to retrieve the address schema for a
// particular manager scope stored within the database. These are used in order
// to properly type each address generated by the scope address manager. | [
"fetchScopeAddrSchema",
"will",
"attempt",
"to",
"retrieve",
"the",
"address",
"schema",
"for",
"a",
"particular",
"manager",
"scope",
"stored",
"within",
"the",
"database",
".",
"These",
"are",
"used",
"in",
"order",
"to",
"properly",
"type",
"each",
"address",... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L338-L355 | train |
btcsuite/btcwallet | waddrmgr/db.go | putScopeAddrTypes | func putScopeAddrTypes(ns walletdb.ReadWriteBucket, scope *KeyScope,
schema *ScopeAddrSchema) error {
scopeSchemaBucket := ns.NestedReadWriteBucket(scopeSchemaBucketName)
if scopeSchemaBucket == nil {
str := fmt.Sprintf("unable to find scope schema bucket")
return managerError(ErrScopeNotFound, str, nil)
}
scopeKey := scopeToBytes(scope)
schemaBytes := scopeSchemaToBytes(schema)
return scopeSchemaBucket.Put(scopeKey[:], schemaBytes)
} | go | func putScopeAddrTypes(ns walletdb.ReadWriteBucket, scope *KeyScope,
schema *ScopeAddrSchema) error {
scopeSchemaBucket := ns.NestedReadWriteBucket(scopeSchemaBucketName)
if scopeSchemaBucket == nil {
str := fmt.Sprintf("unable to find scope schema bucket")
return managerError(ErrScopeNotFound, str, nil)
}
scopeKey := scopeToBytes(scope)
schemaBytes := scopeSchemaToBytes(schema)
return scopeSchemaBucket.Put(scopeKey[:], schemaBytes)
} | [
"func",
"putScopeAddrTypes",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"scope",
"*",
"KeyScope",
",",
"schema",
"*",
"ScopeAddrSchema",
")",
"error",
"{",
"scopeSchemaBucket",
":=",
"ns",
".",
"NestedReadWriteBucket",
"(",
"scopeSchemaBucketName",
")",
"... | // putScopeAddrSchema attempts to store the passed addr scehma for the given
// manager scope. | [
"putScopeAddrSchema",
"attempts",
"to",
"store",
"the",
"passed",
"addr",
"scehma",
"for",
"the",
"given",
"manager",
"scope",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L359-L371 | train |
btcsuite/btcwallet | waddrmgr/db.go | fetchManagerVersion | func fetchManagerVersion(ns walletdb.ReadBucket) (uint32, error) {
mainBucket := ns.NestedReadBucket(mainBucketName)
verBytes := mainBucket.Get(mgrVersionName)
if verBytes == nil {
str := "required version number not stored in database"
return 0, managerError(ErrDatabase, str, nil)
}
version := binary.LittleEndian.Uint32(verBytes)
return version, nil
} | go | func fetchManagerVersion(ns walletdb.ReadBucket) (uint32, error) {
mainBucket := ns.NestedReadBucket(mainBucketName)
verBytes := mainBucket.Get(mgrVersionName)
if verBytes == nil {
str := "required version number not stored in database"
return 0, managerError(ErrDatabase, str, nil)
}
version := binary.LittleEndian.Uint32(verBytes)
return version, nil
} | [
"func",
"fetchManagerVersion",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"mainBucket",
":=",
"ns",
".",
"NestedReadBucket",
"(",
"mainBucketName",
")",
"\n",
"verBytes",
":=",
"mainBucket",
".",
"Get",
"(",
"mgrVer... | // fetchManagerVersion fetches the current manager version from the database. | [
"fetchManagerVersion",
"fetches",
"the",
"current",
"manager",
"version",
"from",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L402-L411 | train |
btcsuite/btcwallet | waddrmgr/db.go | putManagerVersion | func putManagerVersion(ns walletdb.ReadWriteBucket, version uint32) error {
bucket := ns.NestedReadWriteBucket(mainBucketName)
verBytes := uint32ToBytes(version)
err := bucket.Put(mgrVersionName, verBytes)
if err != nil {
str := "failed to store version"
return managerError(ErrDatabase, str, err)
}
return nil
} | go | func putManagerVersion(ns walletdb.ReadWriteBucket, version uint32) error {
bucket := ns.NestedReadWriteBucket(mainBucketName)
verBytes := uint32ToBytes(version)
err := bucket.Put(mgrVersionName, verBytes)
if err != nil {
str := "failed to store version"
return managerError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"putManagerVersion",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"version",
"uint32",
")",
"error",
"{",
"bucket",
":=",
"ns",
".",
"NestedReadWriteBucket",
"(",
"mainBucketName",
")",
"\n",
"verBytes",
":=",
"uint32ToBytes",
"(",
"version",
")",... | // putManagerVersion stores the provided version to the database. | [
"putManagerVersion",
"stores",
"the",
"provided",
"version",
"to",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L414-L424 | train |
btcsuite/btcwallet | waddrmgr/db.go | putMasterKeyParams | func putMasterKeyParams(ns walletdb.ReadWriteBucket, pubParams, privParams []byte) error {
bucket := ns.NestedReadWriteBucket(mainBucketName)
if privParams != nil {
err := bucket.Put(masterPrivKeyName, privParams)
if err != nil {
str := "failed to store master private key parameters"
return managerError(ErrDatabase, str, err)
}
}
if pubParams != nil {
err := bucket.Put(masterPubKeyName, pubParams)
if err != nil {
str := "failed to store master public key parameters"
return managerError(ErrDatabase, str, err)
}
}
return nil
} | go | func putMasterKeyParams(ns walletdb.ReadWriteBucket, pubParams, privParams []byte) error {
bucket := ns.NestedReadWriteBucket(mainBucketName)
if privParams != nil {
err := bucket.Put(masterPrivKeyName, privParams)
if err != nil {
str := "failed to store master private key parameters"
return managerError(ErrDatabase, str, err)
}
}
if pubParams != nil {
err := bucket.Put(masterPubKeyName, pubParams)
if err != nil {
str := "failed to store master public key parameters"
return managerError(ErrDatabase, str, err)
}
}
return nil
} | [
"func",
"putMasterKeyParams",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"pubParams",
",",
"privParams",
"[",
"]",
"byte",
")",
"error",
"{",
"bucket",
":=",
"ns",
".",
"NestedReadWriteBucket",
"(",
"mainBucketName",
")",
"\n",
"if",
"privParams",
"!=... | // putMasterKeyParams stores the master key parameters needed to derive them to
// the database. Either parameter can be nil in which case no value is
// written for the parameter. | [
"putMasterKeyParams",
"stores",
"the",
"master",
"key",
"parameters",
"needed",
"to",
"derive",
"them",
"to",
"the",
"database",
".",
"Either",
"parameter",
"can",
"be",
"nil",
"in",
"which",
"case",
"no",
"value",
"is",
"written",
"for",
"the",
"parameter",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L457-L477 | train |
btcsuite/btcwallet | waddrmgr/db.go | fetchCoinTypeKeys | func fetchCoinTypeKeys(ns walletdb.ReadBucket, scope *KeyScope) ([]byte, []byte, error) {
scopedBucket, err := fetchReadScopeBucket(ns, scope)
if err != nil {
return nil, nil, err
}
coinTypePubKeyEnc := scopedBucket.Get(coinTypePubKeyName)
if coinTypePubKeyEnc == nil {
str := "required encrypted cointype public key not stored in database"
return nil, nil, managerError(ErrDatabase, str, nil)
}
coinTypePrivKeyEnc := scopedBucket.Get(coinTypePrivKeyName)
if coinTypePrivKeyEnc == nil {
str := "required encrypted cointype private key not stored in database"
return nil, nil, managerError(ErrDatabase, str, nil)
}
return coinTypePubKeyEnc, coinTypePrivKeyEnc, nil
} | go | func fetchCoinTypeKeys(ns walletdb.ReadBucket, scope *KeyScope) ([]byte, []byte, error) {
scopedBucket, err := fetchReadScopeBucket(ns, scope)
if err != nil {
return nil, nil, err
}
coinTypePubKeyEnc := scopedBucket.Get(coinTypePubKeyName)
if coinTypePubKeyEnc == nil {
str := "required encrypted cointype public key not stored in database"
return nil, nil, managerError(ErrDatabase, str, nil)
}
coinTypePrivKeyEnc := scopedBucket.Get(coinTypePrivKeyName)
if coinTypePrivKeyEnc == nil {
str := "required encrypted cointype private key not stored in database"
return nil, nil, managerError(ErrDatabase, str, nil)
}
return coinTypePubKeyEnc, coinTypePrivKeyEnc, nil
} | [
"func",
"fetchCoinTypeKeys",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"scope",
"*",
"KeyScope",
")",
"(",
"[",
"]",
"byte",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"scopedBucket",
",",
"err",
":=",
"fetchReadScopeBucket",
"(",
"ns",
",",
"... | // fetchCoinTypeKeys loads the encrypted cointype keys which are in turn used
// to derive the extended keys for all accounts. Each cointype key is
// associated with a particular manager scoped. | [
"fetchCoinTypeKeys",
"loads",
"the",
"encrypted",
"cointype",
"keys",
"which",
"are",
"in",
"turn",
"used",
"to",
"derive",
"the",
"extended",
"keys",
"for",
"all",
"accounts",
".",
"Each",
"cointype",
"key",
"is",
"associated",
"with",
"a",
"particular",
"man... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L482-L501 | train |
btcsuite/btcwallet | waddrmgr/db.go | putCoinTypeKeys | func putCoinTypeKeys(ns walletdb.ReadWriteBucket, scope *KeyScope,
coinTypePubKeyEnc []byte, coinTypePrivKeyEnc []byte) error {
scopedBucket, err := fetchWriteScopeBucket(ns, scope)
if err != nil {
return err
}
if coinTypePubKeyEnc != nil {
err := scopedBucket.Put(coinTypePubKeyName, coinTypePubKeyEnc)
if err != nil {
str := "failed to store encrypted cointype public key"
return managerError(ErrDatabase, str, err)
}
}
if coinTypePrivKeyEnc != nil {
err := scopedBucket.Put(coinTypePrivKeyName, coinTypePrivKeyEnc)
if err != nil {
str := "failed to store encrypted cointype private key"
return managerError(ErrDatabase, str, err)
}
}
return nil
} | go | func putCoinTypeKeys(ns walletdb.ReadWriteBucket, scope *KeyScope,
coinTypePubKeyEnc []byte, coinTypePrivKeyEnc []byte) error {
scopedBucket, err := fetchWriteScopeBucket(ns, scope)
if err != nil {
return err
}
if coinTypePubKeyEnc != nil {
err := scopedBucket.Put(coinTypePubKeyName, coinTypePubKeyEnc)
if err != nil {
str := "failed to store encrypted cointype public key"
return managerError(ErrDatabase, str, err)
}
}
if coinTypePrivKeyEnc != nil {
err := scopedBucket.Put(coinTypePrivKeyName, coinTypePrivKeyEnc)
if err != nil {
str := "failed to store encrypted cointype private key"
return managerError(ErrDatabase, str, err)
}
}
return nil
} | [
"func",
"putCoinTypeKeys",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"scope",
"*",
"KeyScope",
",",
"coinTypePubKeyEnc",
"[",
"]",
"byte",
",",
"coinTypePrivKeyEnc",
"[",
"]",
"byte",
")",
"error",
"{",
"scopedBucket",
",",
"err",
":=",
"fetchWriteSc... | // putCoinTypeKeys stores the encrypted cointype keys which are in turn used to
// derive the extended keys for all accounts. Either parameter can be nil in
// which case no value is written for the parameter. Each cointype key is
// associated with a particular manager scope. | [
"putCoinTypeKeys",
"stores",
"the",
"encrypted",
"cointype",
"keys",
"which",
"are",
"in",
"turn",
"used",
"to",
"derive",
"the",
"extended",
"keys",
"for",
"all",
"accounts",
".",
"Either",
"parameter",
"can",
"be",
"nil",
"in",
"which",
"case",
"no",
"valu... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L507-L532 | train |
btcsuite/btcwallet | waddrmgr/db.go | putMasterHDKeys | func putMasterHDKeys(ns walletdb.ReadWriteBucket, masterHDPrivEnc, masterHDPubEnc []byte) error {
// As this is the key for the root manager, we don't need to fetch any
// particular scope, and can insert directly within the main bucket.
bucket := ns.NestedReadWriteBucket(mainBucketName)
// Now that we have the main bucket, we can directly store each of the
// relevant keys. If we're in watch only mode, then some or all of
// these keys might not be available.
if masterHDPrivEnc != nil {
err := bucket.Put(masterHDPrivName, masterHDPrivEnc)
if err != nil {
str := "failed to store encrypted master HD private key"
return managerError(ErrDatabase, str, err)
}
}
if masterHDPubEnc != nil {
err := bucket.Put(masterHDPubName, masterHDPubEnc)
if err != nil {
str := "failed to store encrypted master HD public key"
return managerError(ErrDatabase, str, err)
}
}
return nil
} | go | func putMasterHDKeys(ns walletdb.ReadWriteBucket, masterHDPrivEnc, masterHDPubEnc []byte) error {
// As this is the key for the root manager, we don't need to fetch any
// particular scope, and can insert directly within the main bucket.
bucket := ns.NestedReadWriteBucket(mainBucketName)
// Now that we have the main bucket, we can directly store each of the
// relevant keys. If we're in watch only mode, then some or all of
// these keys might not be available.
if masterHDPrivEnc != nil {
err := bucket.Put(masterHDPrivName, masterHDPrivEnc)
if err != nil {
str := "failed to store encrypted master HD private key"
return managerError(ErrDatabase, str, err)
}
}
if masterHDPubEnc != nil {
err := bucket.Put(masterHDPubName, masterHDPubEnc)
if err != nil {
str := "failed to store encrypted master HD public key"
return managerError(ErrDatabase, str, err)
}
}
return nil
} | [
"func",
"putMasterHDKeys",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"masterHDPrivEnc",
",",
"masterHDPubEnc",
"[",
"]",
"byte",
")",
"error",
"{",
"bucket",
":=",
"ns",
".",
"NestedReadWriteBucket",
"(",
"mainBucketName",
")",
"\n",
"if",
"masterHDPri... | // putMasterHDKeys stores the encrypted master HD keys in the top level main
// bucket. These are required in order to create any new manager scopes, as
// those are created via hardened derivation of the children of this key. | [
"putMasterHDKeys",
"stores",
"the",
"encrypted",
"master",
"HD",
"keys",
"in",
"the",
"top",
"level",
"main",
"bucket",
".",
"These",
"are",
"required",
"in",
"order",
"to",
"create",
"any",
"new",
"manager",
"scopes",
"as",
"those",
"are",
"created",
"via",... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L537-L562 | train |
btcsuite/btcwallet | waddrmgr/db.go | fetchMasterHDKeys | func fetchMasterHDKeys(ns walletdb.ReadBucket) ([]byte, []byte, error) {
bucket := ns.NestedReadBucket(mainBucketName)
var masterHDPrivEnc, masterHDPubEnc []byte
// First, we'll try to fetch the master private key. If this database
// is watch only, or the master has been neutered, then this won't be
// found on disk.
key := bucket.Get(masterHDPrivName)
if key != nil {
masterHDPrivEnc = make([]byte, len(key))
copy(masterHDPrivEnc[:], key)
}
key = bucket.Get(masterHDPubName)
if key != nil {
masterHDPubEnc = make([]byte, len(key))
copy(masterHDPubEnc[:], key)
}
return masterHDPrivEnc, masterHDPubEnc, nil
} | go | func fetchMasterHDKeys(ns walletdb.ReadBucket) ([]byte, []byte, error) {
bucket := ns.NestedReadBucket(mainBucketName)
var masterHDPrivEnc, masterHDPubEnc []byte
// First, we'll try to fetch the master private key. If this database
// is watch only, or the master has been neutered, then this won't be
// found on disk.
key := bucket.Get(masterHDPrivName)
if key != nil {
masterHDPrivEnc = make([]byte, len(key))
copy(masterHDPrivEnc[:], key)
}
key = bucket.Get(masterHDPubName)
if key != nil {
masterHDPubEnc = make([]byte, len(key))
copy(masterHDPubEnc[:], key)
}
return masterHDPrivEnc, masterHDPubEnc, nil
} | [
"func",
"fetchMasterHDKeys",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
")",
"(",
"[",
"]",
"byte",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"bucket",
":=",
"ns",
".",
"NestedReadBucket",
"(",
"mainBucketName",
")",
"\n",
"var",
"masterHDPrivEnc",
"... | // fetchMasterHDKeys attempts to fetch both the master HD private and public
// keys from the database. If this is a watch only wallet, then it's possible
// that the master private key isn't stored. | [
"fetchMasterHDKeys",
"attempts",
"to",
"fetch",
"both",
"the",
"master",
"HD",
"private",
"and",
"public",
"keys",
"from",
"the",
"database",
".",
"If",
"this",
"is",
"a",
"watch",
"only",
"wallet",
"then",
"it",
"s",
"possible",
"that",
"the",
"master",
"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L567-L588 | train |
btcsuite/btcwallet | waddrmgr/db.go | fetchCryptoKeys | func fetchCryptoKeys(ns walletdb.ReadBucket) ([]byte, []byte, []byte, error) {
bucket := ns.NestedReadBucket(mainBucketName)
// Load the crypto public key parameters. Required.
val := bucket.Get(cryptoPubKeyName)
if val == nil {
str := "required encrypted crypto public not stored in database"
return nil, nil, nil, managerError(ErrDatabase, str, nil)
}
pubKey := make([]byte, len(val))
copy(pubKey, val)
// Load the crypto private key parameters if they were stored.
var privKey []byte
val = bucket.Get(cryptoPrivKeyName)
if val != nil {
privKey = make([]byte, len(val))
copy(privKey, val)
}
// Load the crypto script key parameters if they were stored.
var scriptKey []byte
val = bucket.Get(cryptoScriptKeyName)
if val != nil {
scriptKey = make([]byte, len(val))
copy(scriptKey, val)
}
return pubKey, privKey, scriptKey, nil
} | go | func fetchCryptoKeys(ns walletdb.ReadBucket) ([]byte, []byte, []byte, error) {
bucket := ns.NestedReadBucket(mainBucketName)
// Load the crypto public key parameters. Required.
val := bucket.Get(cryptoPubKeyName)
if val == nil {
str := "required encrypted crypto public not stored in database"
return nil, nil, nil, managerError(ErrDatabase, str, nil)
}
pubKey := make([]byte, len(val))
copy(pubKey, val)
// Load the crypto private key parameters if they were stored.
var privKey []byte
val = bucket.Get(cryptoPrivKeyName)
if val != nil {
privKey = make([]byte, len(val))
copy(privKey, val)
}
// Load the crypto script key parameters if they were stored.
var scriptKey []byte
val = bucket.Get(cryptoScriptKeyName)
if val != nil {
scriptKey = make([]byte, len(val))
copy(scriptKey, val)
}
return pubKey, privKey, scriptKey, nil
} | [
"func",
"fetchCryptoKeys",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
")",
"(",
"[",
"]",
"byte",
",",
"[",
"]",
"byte",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"bucket",
":=",
"ns",
".",
"NestedReadBucket",
"(",
"mainBucketName",
")",
"\n",
"v... | // fetchCryptoKeys loads the encrypted crypto keys which are in turn used to
// protect the extended keys, imported keys, and scripts. Any of the returned
// values can be nil, but in practice only the crypto private and script keys
// will be nil for a watching-only database. | [
"fetchCryptoKeys",
"loads",
"the",
"encrypted",
"crypto",
"keys",
"which",
"are",
"in",
"turn",
"used",
"to",
"protect",
"the",
"extended",
"keys",
"imported",
"keys",
"and",
"scripts",
".",
"Any",
"of",
"the",
"returned",
"values",
"can",
"be",
"nil",
"but"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L594-L623 | train |
btcsuite/btcwallet | waddrmgr/db.go | putCryptoKeys | func putCryptoKeys(ns walletdb.ReadWriteBucket, pubKeyEncrypted, privKeyEncrypted,
scriptKeyEncrypted []byte) error {
bucket := ns.NestedReadWriteBucket(mainBucketName)
if pubKeyEncrypted != nil {
err := bucket.Put(cryptoPubKeyName, pubKeyEncrypted)
if err != nil {
str := "failed to store encrypted crypto public key"
return managerError(ErrDatabase, str, err)
}
}
if privKeyEncrypted != nil {
err := bucket.Put(cryptoPrivKeyName, privKeyEncrypted)
if err != nil {
str := "failed to store encrypted crypto private key"
return managerError(ErrDatabase, str, err)
}
}
if scriptKeyEncrypted != nil {
err := bucket.Put(cryptoScriptKeyName, scriptKeyEncrypted)
if err != nil {
str := "failed to store encrypted crypto script key"
return managerError(ErrDatabase, str, err)
}
}
return nil
} | go | func putCryptoKeys(ns walletdb.ReadWriteBucket, pubKeyEncrypted, privKeyEncrypted,
scriptKeyEncrypted []byte) error {
bucket := ns.NestedReadWriteBucket(mainBucketName)
if pubKeyEncrypted != nil {
err := bucket.Put(cryptoPubKeyName, pubKeyEncrypted)
if err != nil {
str := "failed to store encrypted crypto public key"
return managerError(ErrDatabase, str, err)
}
}
if privKeyEncrypted != nil {
err := bucket.Put(cryptoPrivKeyName, privKeyEncrypted)
if err != nil {
str := "failed to store encrypted crypto private key"
return managerError(ErrDatabase, str, err)
}
}
if scriptKeyEncrypted != nil {
err := bucket.Put(cryptoScriptKeyName, scriptKeyEncrypted)
if err != nil {
str := "failed to store encrypted crypto script key"
return managerError(ErrDatabase, str, err)
}
}
return nil
} | [
"func",
"putCryptoKeys",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"pubKeyEncrypted",
",",
"privKeyEncrypted",
",",
"scriptKeyEncrypted",
"[",
"]",
"byte",
")",
"error",
"{",
"bucket",
":=",
"ns",
".",
"NestedReadWriteBucket",
"(",
"mainBucketName",
")",... | // putCryptoKeys stores the encrypted crypto keys which are in turn used to
// protect the extended and imported keys. Either parameter can be nil in
// which case no value is written for the parameter. | [
"putCryptoKeys",
"stores",
"the",
"encrypted",
"crypto",
"keys",
"which",
"are",
"in",
"turn",
"used",
"to",
"protect",
"the",
"extended",
"and",
"imported",
"keys",
".",
"Either",
"parameter",
"can",
"be",
"nil",
"in",
"which",
"case",
"no",
"value",
"is",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L628-L658 | train |
btcsuite/btcwallet | waddrmgr/db.go | fetchWatchingOnly | func fetchWatchingOnly(ns walletdb.ReadBucket) (bool, error) {
bucket := ns.NestedReadBucket(mainBucketName)
buf := bucket.Get(watchingOnlyName)
if len(buf) != 1 {
str := "malformed watching-only flag stored in database"
return false, managerError(ErrDatabase, str, nil)
}
return buf[0] != 0, nil
} | go | func fetchWatchingOnly(ns walletdb.ReadBucket) (bool, error) {
bucket := ns.NestedReadBucket(mainBucketName)
buf := bucket.Get(watchingOnlyName)
if len(buf) != 1 {
str := "malformed watching-only flag stored in database"
return false, managerError(ErrDatabase, str, nil)
}
return buf[0] != 0, nil
} | [
"func",
"fetchWatchingOnly",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
")",
"(",
"bool",
",",
"error",
")",
"{",
"bucket",
":=",
"ns",
".",
"NestedReadBucket",
"(",
"mainBucketName",
")",
"\n",
"buf",
":=",
"bucket",
".",
"Get",
"(",
"watchingOnlyName",
")... | // fetchWatchingOnly loads the watching-only flag from the database. | [
"fetchWatchingOnly",
"loads",
"the",
"watching",
"-",
"only",
"flag",
"from",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L661-L671 | train |
btcsuite/btcwallet | waddrmgr/db.go | putWatchingOnly | func putWatchingOnly(ns walletdb.ReadWriteBucket, watchingOnly bool) error {
bucket := ns.NestedReadWriteBucket(mainBucketName)
var encoded byte
if watchingOnly {
encoded = 1
}
if err := bucket.Put(watchingOnlyName, []byte{encoded}); err != nil {
str := "failed to store watching only flag"
return managerError(ErrDatabase, str, err)
}
return nil
} | go | func putWatchingOnly(ns walletdb.ReadWriteBucket, watchingOnly bool) error {
bucket := ns.NestedReadWriteBucket(mainBucketName)
var encoded byte
if watchingOnly {
encoded = 1
}
if err := bucket.Put(watchingOnlyName, []byte{encoded}); err != nil {
str := "failed to store watching only flag"
return managerError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"putWatchingOnly",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"watchingOnly",
"bool",
")",
"error",
"{",
"bucket",
":=",
"ns",
".",
"NestedReadWriteBucket",
"(",
"mainBucketName",
")",
"\n",
"var",
"encoded",
"byte",
"\n",
"if",
"watchingOnly",
... | // putWatchingOnly stores the watching-only flag to the database. | [
"putWatchingOnly",
"stores",
"the",
"watching",
"-",
"only",
"flag",
"to",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L674-L687 | train |
btcsuite/btcwallet | waddrmgr/db.go | deserializeAccountRow | func deserializeAccountRow(accountID []byte, serializedAccount []byte) (*dbAccountRow, error) {
// The serialized account format is:
// <acctType><rdlen><rawdata>
//
// 1 byte acctType + 4 bytes raw data length + raw data
// Given the above, the length of the entry must be at a minimum
// the constant value sizes.
if len(serializedAccount) < 5 {
str := fmt.Sprintf("malformed serialized account for key %x",
accountID)
return nil, managerError(ErrDatabase, str, nil)
}
row := dbAccountRow{}
row.acctType = accountType(serializedAccount[0])
rdlen := binary.LittleEndian.Uint32(serializedAccount[1:5])
row.rawData = make([]byte, rdlen)
copy(row.rawData, serializedAccount[5:5+rdlen])
return &row, nil
} | go | func deserializeAccountRow(accountID []byte, serializedAccount []byte) (*dbAccountRow, error) {
// The serialized account format is:
// <acctType><rdlen><rawdata>
//
// 1 byte acctType + 4 bytes raw data length + raw data
// Given the above, the length of the entry must be at a minimum
// the constant value sizes.
if len(serializedAccount) < 5 {
str := fmt.Sprintf("malformed serialized account for key %x",
accountID)
return nil, managerError(ErrDatabase, str, nil)
}
row := dbAccountRow{}
row.acctType = accountType(serializedAccount[0])
rdlen := binary.LittleEndian.Uint32(serializedAccount[1:5])
row.rawData = make([]byte, rdlen)
copy(row.rawData, serializedAccount[5:5+rdlen])
return &row, nil
} | [
"func",
"deserializeAccountRow",
"(",
"accountID",
"[",
"]",
"byte",
",",
"serializedAccount",
"[",
"]",
"byte",
")",
"(",
"*",
"dbAccountRow",
",",
"error",
")",
"{",
"if",
"len",
"(",
"serializedAccount",
")",
"<",
"5",
"{",
"str",
":=",
"fmt",
".",
... | // deserializeAccountRow deserializes the passed serialized account information.
// This is used as a common base for the various account types to deserialize
// the common parts. | [
"deserializeAccountRow",
"deserializes",
"the",
"passed",
"serialized",
"account",
"information",
".",
"This",
"is",
"used",
"as",
"a",
"common",
"base",
"for",
"the",
"various",
"account",
"types",
"to",
"deserialize",
"the",
"common",
"parts",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L692-L713 | train |
btcsuite/btcwallet | waddrmgr/db.go | serializeAccountRow | func serializeAccountRow(row *dbAccountRow) []byte {
// The serialized account format is:
// <acctType><rdlen><rawdata>
//
// 1 byte acctType + 4 bytes raw data length + raw data
rdlen := len(row.rawData)
buf := make([]byte, 5+rdlen)
buf[0] = byte(row.acctType)
binary.LittleEndian.PutUint32(buf[1:5], uint32(rdlen))
copy(buf[5:5+rdlen], row.rawData)
return buf
} | go | func serializeAccountRow(row *dbAccountRow) []byte {
// The serialized account format is:
// <acctType><rdlen><rawdata>
//
// 1 byte acctType + 4 bytes raw data length + raw data
rdlen := len(row.rawData)
buf := make([]byte, 5+rdlen)
buf[0] = byte(row.acctType)
binary.LittleEndian.PutUint32(buf[1:5], uint32(rdlen))
copy(buf[5:5+rdlen], row.rawData)
return buf
} | [
"func",
"serializeAccountRow",
"(",
"row",
"*",
"dbAccountRow",
")",
"[",
"]",
"byte",
"{",
"rdlen",
":=",
"len",
"(",
"row",
".",
"rawData",
")",
"\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"5",
"+",
"rdlen",
")",
"\n",
"buf",
"[",
"0... | // serializeAccountRow returns the serialization of the passed account row. | [
"serializeAccountRow",
"returns",
"the",
"serialization",
"of",
"the",
"passed",
"account",
"row",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L716-L727 | train |
btcsuite/btcwallet | waddrmgr/db.go | deserializeDefaultAccountRow | func deserializeDefaultAccountRow(accountID []byte, row *dbAccountRow) (*dbDefaultAccountRow, error) {
// The serialized BIP0044 account raw data format is:
// <encpubkeylen><encpubkey><encprivkeylen><encprivkey><nextextidx>
// <nextintidx><namelen><name>
//
// 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted
// privkey len + encrypted privkey + 4 bytes next external index +
// 4 bytes next internal index + 4 bytes name len + name
// Given the above, the length of the entry must be at a minimum
// the constant value sizes.
if len(row.rawData) < 20 {
str := fmt.Sprintf("malformed serialized bip0044 account for "+
"key %x", accountID)
return nil, managerError(ErrDatabase, str, nil)
}
retRow := dbDefaultAccountRow{
dbAccountRow: *row,
}
pubLen := binary.LittleEndian.Uint32(row.rawData[0:4])
retRow.pubKeyEncrypted = make([]byte, pubLen)
copy(retRow.pubKeyEncrypted, row.rawData[4:4+pubLen])
offset := 4 + pubLen
privLen := binary.LittleEndian.Uint32(row.rawData[offset : offset+4])
offset += 4
retRow.privKeyEncrypted = make([]byte, privLen)
copy(retRow.privKeyEncrypted, row.rawData[offset:offset+privLen])
offset += privLen
retRow.nextExternalIndex = binary.LittleEndian.Uint32(row.rawData[offset : offset+4])
offset += 4
retRow.nextInternalIndex = binary.LittleEndian.Uint32(row.rawData[offset : offset+4])
offset += 4
nameLen := binary.LittleEndian.Uint32(row.rawData[offset : offset+4])
offset += 4
retRow.name = string(row.rawData[offset : offset+nameLen])
return &retRow, nil
} | go | func deserializeDefaultAccountRow(accountID []byte, row *dbAccountRow) (*dbDefaultAccountRow, error) {
// The serialized BIP0044 account raw data format is:
// <encpubkeylen><encpubkey><encprivkeylen><encprivkey><nextextidx>
// <nextintidx><namelen><name>
//
// 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted
// privkey len + encrypted privkey + 4 bytes next external index +
// 4 bytes next internal index + 4 bytes name len + name
// Given the above, the length of the entry must be at a minimum
// the constant value sizes.
if len(row.rawData) < 20 {
str := fmt.Sprintf("malformed serialized bip0044 account for "+
"key %x", accountID)
return nil, managerError(ErrDatabase, str, nil)
}
retRow := dbDefaultAccountRow{
dbAccountRow: *row,
}
pubLen := binary.LittleEndian.Uint32(row.rawData[0:4])
retRow.pubKeyEncrypted = make([]byte, pubLen)
copy(retRow.pubKeyEncrypted, row.rawData[4:4+pubLen])
offset := 4 + pubLen
privLen := binary.LittleEndian.Uint32(row.rawData[offset : offset+4])
offset += 4
retRow.privKeyEncrypted = make([]byte, privLen)
copy(retRow.privKeyEncrypted, row.rawData[offset:offset+privLen])
offset += privLen
retRow.nextExternalIndex = binary.LittleEndian.Uint32(row.rawData[offset : offset+4])
offset += 4
retRow.nextInternalIndex = binary.LittleEndian.Uint32(row.rawData[offset : offset+4])
offset += 4
nameLen := binary.LittleEndian.Uint32(row.rawData[offset : offset+4])
offset += 4
retRow.name = string(row.rawData[offset : offset+nameLen])
return &retRow, nil
} | [
"func",
"deserializeDefaultAccountRow",
"(",
"accountID",
"[",
"]",
"byte",
",",
"row",
"*",
"dbAccountRow",
")",
"(",
"*",
"dbDefaultAccountRow",
",",
"error",
")",
"{",
"if",
"len",
"(",
"row",
".",
"rawData",
")",
"<",
"20",
"{",
"str",
":=",
"fmt",
... | // deserializeDefaultAccountRow deserializes the raw data from the passed
// account row as a BIP0044-like account. | [
"deserializeDefaultAccountRow",
"deserializes",
"the",
"raw",
"data",
"from",
"the",
"passed",
"account",
"row",
"as",
"a",
"BIP0044",
"-",
"like",
"account",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L731-L770 | train |
btcsuite/btcwallet | waddrmgr/db.go | serializeDefaultAccountRow | func serializeDefaultAccountRow(encryptedPubKey, encryptedPrivKey []byte,
nextExternalIndex, nextInternalIndex uint32, name string) []byte {
// The serialized BIP0044 account raw data format is:
// <encpubkeylen><encpubkey><encprivkeylen><encprivkey><nextextidx>
// <nextintidx><namelen><name>
//
// 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted
// privkey len + encrypted privkey + 4 bytes next external index +
// 4 bytes next internal index + 4 bytes name len + name
pubLen := uint32(len(encryptedPubKey))
privLen := uint32(len(encryptedPrivKey))
nameLen := uint32(len(name))
rawData := make([]byte, 20+pubLen+privLen+nameLen)
binary.LittleEndian.PutUint32(rawData[0:4], pubLen)
copy(rawData[4:4+pubLen], encryptedPubKey)
offset := 4 + pubLen
binary.LittleEndian.PutUint32(rawData[offset:offset+4], privLen)
offset += 4
copy(rawData[offset:offset+privLen], encryptedPrivKey)
offset += privLen
binary.LittleEndian.PutUint32(rawData[offset:offset+4], nextExternalIndex)
offset += 4
binary.LittleEndian.PutUint32(rawData[offset:offset+4], nextInternalIndex)
offset += 4
binary.LittleEndian.PutUint32(rawData[offset:offset+4], nameLen)
offset += 4
copy(rawData[offset:offset+nameLen], name)
return rawData
} | go | func serializeDefaultAccountRow(encryptedPubKey, encryptedPrivKey []byte,
nextExternalIndex, nextInternalIndex uint32, name string) []byte {
// The serialized BIP0044 account raw data format is:
// <encpubkeylen><encpubkey><encprivkeylen><encprivkey><nextextidx>
// <nextintidx><namelen><name>
//
// 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted
// privkey len + encrypted privkey + 4 bytes next external index +
// 4 bytes next internal index + 4 bytes name len + name
pubLen := uint32(len(encryptedPubKey))
privLen := uint32(len(encryptedPrivKey))
nameLen := uint32(len(name))
rawData := make([]byte, 20+pubLen+privLen+nameLen)
binary.LittleEndian.PutUint32(rawData[0:4], pubLen)
copy(rawData[4:4+pubLen], encryptedPubKey)
offset := 4 + pubLen
binary.LittleEndian.PutUint32(rawData[offset:offset+4], privLen)
offset += 4
copy(rawData[offset:offset+privLen], encryptedPrivKey)
offset += privLen
binary.LittleEndian.PutUint32(rawData[offset:offset+4], nextExternalIndex)
offset += 4
binary.LittleEndian.PutUint32(rawData[offset:offset+4], nextInternalIndex)
offset += 4
binary.LittleEndian.PutUint32(rawData[offset:offset+4], nameLen)
offset += 4
copy(rawData[offset:offset+nameLen], name)
return rawData
} | [
"func",
"serializeDefaultAccountRow",
"(",
"encryptedPubKey",
",",
"encryptedPrivKey",
"[",
"]",
"byte",
",",
"nextExternalIndex",
",",
"nextInternalIndex",
"uint32",
",",
"name",
"string",
")",
"[",
"]",
"byte",
"{",
"pubLen",
":=",
"uint32",
"(",
"len",
"(",
... | // serializeDefaultAccountRow returns the serialization of the raw data field
// for a BIP0044-like account. | [
"serializeDefaultAccountRow",
"returns",
"the",
"serialization",
"of",
"the",
"raw",
"data",
"field",
"for",
"a",
"BIP0044",
"-",
"like",
"account",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L774-L803 | train |
btcsuite/btcwallet | waddrmgr/db.go | forEachKeyScope | func forEachKeyScope(ns walletdb.ReadBucket, fn func(KeyScope) error) error {
bucket := ns.NestedReadBucket(scopeBucketName)
return bucket.ForEach(func(k, v []byte) error {
// skip non-bucket
if len(k) != 8 {
return nil
}
scope := KeyScope{
Purpose: binary.LittleEndian.Uint32(k[:]),
Coin: binary.LittleEndian.Uint32(k[4:]),
}
return fn(scope)
})
} | go | func forEachKeyScope(ns walletdb.ReadBucket, fn func(KeyScope) error) error {
bucket := ns.NestedReadBucket(scopeBucketName)
return bucket.ForEach(func(k, v []byte) error {
// skip non-bucket
if len(k) != 8 {
return nil
}
scope := KeyScope{
Purpose: binary.LittleEndian.Uint32(k[:]),
Coin: binary.LittleEndian.Uint32(k[4:]),
}
return fn(scope)
})
} | [
"func",
"forEachKeyScope",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"fn",
"func",
"(",
"KeyScope",
")",
"error",
")",
"error",
"{",
"bucket",
":=",
"ns",
".",
"NestedReadBucket",
"(",
"scopeBucketName",
")",
"\n",
"return",
"bucket",
".",
"ForEach",
... | // forEachKeyScope calls the given function for each known manager scope
// within the set of scopes known by the root manager. | [
"forEachKeyScope",
"calls",
"the",
"given",
"function",
"for",
"each",
"known",
"manager",
"scope",
"within",
"the",
"set",
"of",
"scopes",
"known",
"by",
"the",
"root",
"manager",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L807-L823 | train |
btcsuite/btcwallet | waddrmgr/db.go | forEachAccount | func forEachAccount(ns walletdb.ReadBucket, scope *KeyScope,
fn func(account uint32) error) error {
scopedBucket, err := fetchReadScopeBucket(ns, scope)
if err != nil {
return err
}
acctBucket := scopedBucket.NestedReadBucket(acctBucketName)
return acctBucket.ForEach(func(k, v []byte) error {
// Skip buckets.
if v == nil {
return nil
}
return fn(binary.LittleEndian.Uint32(k))
})
} | go | func forEachAccount(ns walletdb.ReadBucket, scope *KeyScope,
fn func(account uint32) error) error {
scopedBucket, err := fetchReadScopeBucket(ns, scope)
if err != nil {
return err
}
acctBucket := scopedBucket.NestedReadBucket(acctBucketName)
return acctBucket.ForEach(func(k, v []byte) error {
// Skip buckets.
if v == nil {
return nil
}
return fn(binary.LittleEndian.Uint32(k))
})
} | [
"func",
"forEachAccount",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"scope",
"*",
"KeyScope",
",",
"fn",
"func",
"(",
"account",
"uint32",
")",
"error",
")",
"error",
"{",
"scopedBucket",
",",
"err",
":=",
"fetchReadScopeBucket",
"(",
"ns",
",",
"scop... | // forEachAccount calls the given function with each account stored in the
// manager, breaking early on error. | [
"forEachAccount",
"calls",
"the",
"given",
"function",
"with",
"each",
"account",
"stored",
"in",
"the",
"manager",
"breaking",
"early",
"on",
"error",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L827-L843 | train |
btcsuite/btcwallet | waddrmgr/db.go | fetchLastAccount | func fetchLastAccount(ns walletdb.ReadBucket, scope *KeyScope) (uint32, error) {
scopedBucket, err := fetchReadScopeBucket(ns, scope)
if err != nil {
return 0, err
}
metaBucket := scopedBucket.NestedReadBucket(metaBucketName)
val := metaBucket.Get(lastAccountName)
if len(val) != 4 {
str := fmt.Sprintf("malformed metadata '%s' stored in database",
lastAccountName)
return 0, managerError(ErrDatabase, str, nil)
}
account := binary.LittleEndian.Uint32(val[0:4])
return account, nil
} | go | func fetchLastAccount(ns walletdb.ReadBucket, scope *KeyScope) (uint32, error) {
scopedBucket, err := fetchReadScopeBucket(ns, scope)
if err != nil {
return 0, err
}
metaBucket := scopedBucket.NestedReadBucket(metaBucketName)
val := metaBucket.Get(lastAccountName)
if len(val) != 4 {
str := fmt.Sprintf("malformed metadata '%s' stored in database",
lastAccountName)
return 0, managerError(ErrDatabase, str, nil)
}
account := binary.LittleEndian.Uint32(val[0:4])
return account, nil
} | [
"func",
"fetchLastAccount",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"scope",
"*",
"KeyScope",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"scopedBucket",
",",
"err",
":=",
"fetchReadScopeBucket",
"(",
"ns",
",",
"scope",
")",
"\n",
"if",
"err",
"!... | // fetchLastAccount retrieves the last account from the database. | [
"fetchLastAccount",
"retrieves",
"the",
"last",
"account",
"from",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L846-L863 | train |
btcsuite/btcwallet | waddrmgr/db.go | fetchAccountName | func fetchAccountName(ns walletdb.ReadBucket, scope *KeyScope,
account uint32) (string, error) {
scopedBucket, err := fetchReadScopeBucket(ns, scope)
if err != nil {
return "", err
}
acctIDxBucket := scopedBucket.NestedReadBucket(acctIDIdxBucketName)
val := acctIDxBucket.Get(uint32ToBytes(account))
if val == nil {
str := fmt.Sprintf("account %d not found", account)
return "", managerError(ErrAccountNotFound, str, nil)
}
offset := uint32(0)
nameLen := binary.LittleEndian.Uint32(val[offset : offset+4])
offset += 4
acctName := string(val[offset : offset+nameLen])
return acctName, nil
} | go | func fetchAccountName(ns walletdb.ReadBucket, scope *KeyScope,
account uint32) (string, error) {
scopedBucket, err := fetchReadScopeBucket(ns, scope)
if err != nil {
return "", err
}
acctIDxBucket := scopedBucket.NestedReadBucket(acctIDIdxBucketName)
val := acctIDxBucket.Get(uint32ToBytes(account))
if val == nil {
str := fmt.Sprintf("account %d not found", account)
return "", managerError(ErrAccountNotFound, str, nil)
}
offset := uint32(0)
nameLen := binary.LittleEndian.Uint32(val[offset : offset+4])
offset += 4
acctName := string(val[offset : offset+nameLen])
return acctName, nil
} | [
"func",
"fetchAccountName",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"scope",
"*",
"KeyScope",
",",
"account",
"uint32",
")",
"(",
"string",
",",
"error",
")",
"{",
"scopedBucket",
",",
"err",
":=",
"fetchReadScopeBucket",
"(",
"ns",
",",
"scope",
")... | // fetchAccountName retrieves the account name given an account number from the
// database. | [
"fetchAccountName",
"retrieves",
"the",
"account",
"name",
"given",
"an",
"account",
"number",
"from",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L867-L889 | train |
btcsuite/btcwallet | waddrmgr/db.go | fetchAccountByName | func fetchAccountByName(ns walletdb.ReadBucket, scope *KeyScope,
name string) (uint32, error) {
scopedBucket, err := fetchReadScopeBucket(ns, scope)
if err != nil {
return 0, err
}
idxBucket := scopedBucket.NestedReadBucket(acctNameIdxBucketName)
val := idxBucket.Get(stringToBytes(name))
if val == nil {
str := fmt.Sprintf("account name '%s' not found", name)
return 0, managerError(ErrAccountNotFound, str, nil)
}
return binary.LittleEndian.Uint32(val), nil
} | go | func fetchAccountByName(ns walletdb.ReadBucket, scope *KeyScope,
name string) (uint32, error) {
scopedBucket, err := fetchReadScopeBucket(ns, scope)
if err != nil {
return 0, err
}
idxBucket := scopedBucket.NestedReadBucket(acctNameIdxBucketName)
val := idxBucket.Get(stringToBytes(name))
if val == nil {
str := fmt.Sprintf("account name '%s' not found", name)
return 0, managerError(ErrAccountNotFound, str, nil)
}
return binary.LittleEndian.Uint32(val), nil
} | [
"func",
"fetchAccountByName",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"scope",
"*",
"KeyScope",
",",
"name",
"string",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"scopedBucket",
",",
"err",
":=",
"fetchReadScopeBucket",
"(",
"ns",
",",
"scope",
")"... | // fetchAccountByName retrieves the account number given an account name from
// the database. | [
"fetchAccountByName",
"retrieves",
"the",
"account",
"number",
"given",
"an",
"account",
"name",
"from",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L893-L910 | train |
btcsuite/btcwallet | waddrmgr/db.go | fetchAccountInfo | func fetchAccountInfo(ns walletdb.ReadBucket, scope *KeyScope,
account uint32) (interface{}, error) {
scopedBucket, err := fetchReadScopeBucket(ns, scope)
if err != nil {
return nil, err
}
acctBucket := scopedBucket.NestedReadBucket(acctBucketName)
accountID := uint32ToBytes(account)
serializedRow := acctBucket.Get(accountID)
if serializedRow == nil {
str := fmt.Sprintf("account %d not found", account)
return nil, managerError(ErrAccountNotFound, str, nil)
}
row, err := deserializeAccountRow(accountID, serializedRow)
if err != nil {
return nil, err
}
switch row.acctType {
case accountDefault:
return deserializeDefaultAccountRow(accountID, row)
}
str := fmt.Sprintf("unsupported account type '%d'", row.acctType)
return nil, managerError(ErrDatabase, str, nil)
} | go | func fetchAccountInfo(ns walletdb.ReadBucket, scope *KeyScope,
account uint32) (interface{}, error) {
scopedBucket, err := fetchReadScopeBucket(ns, scope)
if err != nil {
return nil, err
}
acctBucket := scopedBucket.NestedReadBucket(acctBucketName)
accountID := uint32ToBytes(account)
serializedRow := acctBucket.Get(accountID)
if serializedRow == nil {
str := fmt.Sprintf("account %d not found", account)
return nil, managerError(ErrAccountNotFound, str, nil)
}
row, err := deserializeAccountRow(accountID, serializedRow)
if err != nil {
return nil, err
}
switch row.acctType {
case accountDefault:
return deserializeDefaultAccountRow(accountID, row)
}
str := fmt.Sprintf("unsupported account type '%d'", row.acctType)
return nil, managerError(ErrDatabase, str, nil)
} | [
"func",
"fetchAccountInfo",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"scope",
"*",
"KeyScope",
",",
"account",
"uint32",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"scopedBucket",
",",
"err",
":=",
"fetchReadScopeBucket",
"(",
"ns",
","... | // fetchAccountInfo loads information about the passed account from the
// database. | [
"fetchAccountInfo",
"loads",
"information",
"about",
"the",
"passed",
"account",
"from",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L914-L943 | train |
btcsuite/btcwallet | waddrmgr/db.go | deleteAccountNameIndex | func deleteAccountNameIndex(ns walletdb.ReadWriteBucket, scope *KeyScope,
name string) error {
scopedBucket, err := fetchWriteScopeBucket(ns, scope)
if err != nil {
return err
}
bucket := scopedBucket.NestedReadWriteBucket(acctNameIdxBucketName)
// Delete the account name key
err = bucket.Delete(stringToBytes(name))
if err != nil {
str := fmt.Sprintf("failed to delete account name index key %s", name)
return managerError(ErrDatabase, str, err)
}
return nil
} | go | func deleteAccountNameIndex(ns walletdb.ReadWriteBucket, scope *KeyScope,
name string) error {
scopedBucket, err := fetchWriteScopeBucket(ns, scope)
if err != nil {
return err
}
bucket := scopedBucket.NestedReadWriteBucket(acctNameIdxBucketName)
// Delete the account name key
err = bucket.Delete(stringToBytes(name))
if err != nil {
str := fmt.Sprintf("failed to delete account name index key %s", name)
return managerError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"deleteAccountNameIndex",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"scope",
"*",
"KeyScope",
",",
"name",
"string",
")",
"error",
"{",
"scopedBucket",
",",
"err",
":=",
"fetchWriteScopeBucket",
"(",
"ns",
",",
"scope",
")",
"\n",
"if",
"er... | // deleteAccountNameIndex deletes the given key from the account name index of the database. | [
"deleteAccountNameIndex",
"deletes",
"the",
"given",
"key",
"from",
"the",
"account",
"name",
"index",
"of",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L946-L963 | train |
btcsuite/btcwallet | waddrmgr/db.go | deleteAccountIDIndex | func deleteAccountIDIndex(ns walletdb.ReadWriteBucket, scope *KeyScope,
account uint32) error {
scopedBucket, err := fetchWriteScopeBucket(ns, scope)
if err != nil {
return err
}
bucket := scopedBucket.NestedReadWriteBucket(acctIDIdxBucketName)
// Delete the account id key
err = bucket.Delete(uint32ToBytes(account))
if err != nil {
str := fmt.Sprintf("failed to delete account id index key %d", account)
return managerError(ErrDatabase, str, err)
}
return nil
} | go | func deleteAccountIDIndex(ns walletdb.ReadWriteBucket, scope *KeyScope,
account uint32) error {
scopedBucket, err := fetchWriteScopeBucket(ns, scope)
if err != nil {
return err
}
bucket := scopedBucket.NestedReadWriteBucket(acctIDIdxBucketName)
// Delete the account id key
err = bucket.Delete(uint32ToBytes(account))
if err != nil {
str := fmt.Sprintf("failed to delete account id index key %d", account)
return managerError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"deleteAccountIDIndex",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"scope",
"*",
"KeyScope",
",",
"account",
"uint32",
")",
"error",
"{",
"scopedBucket",
",",
"err",
":=",
"fetchWriteScopeBucket",
"(",
"ns",
",",
"scope",
")",
"\n",
"if",
"e... | // deleteAccounIdIndex deletes the given key from the account id index of the database. | [
"deleteAccounIdIndex",
"deletes",
"the",
"given",
"key",
"from",
"the",
"account",
"id",
"index",
"of",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L966-L983 | train |
btcsuite/btcwallet | waddrmgr/db.go | putAccountNameIndex | func putAccountNameIndex(ns walletdb.ReadWriteBucket, scope *KeyScope,
account uint32, name string) error {
scopedBucket, err := fetchWriteScopeBucket(ns, scope)
if err != nil {
return err
}
bucket := scopedBucket.NestedReadWriteBucket(acctNameIdxBucketName)
// Write the account number keyed by the account name.
err = bucket.Put(stringToBytes(name), uint32ToBytes(account))
if err != nil {
str := fmt.Sprintf("failed to store account name index key %s", name)
return managerError(ErrDatabase, str, err)
}
return nil
} | go | func putAccountNameIndex(ns walletdb.ReadWriteBucket, scope *KeyScope,
account uint32, name string) error {
scopedBucket, err := fetchWriteScopeBucket(ns, scope)
if err != nil {
return err
}
bucket := scopedBucket.NestedReadWriteBucket(acctNameIdxBucketName)
// Write the account number keyed by the account name.
err = bucket.Put(stringToBytes(name), uint32ToBytes(account))
if err != nil {
str := fmt.Sprintf("failed to store account name index key %s", name)
return managerError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"putAccountNameIndex",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"scope",
"*",
"KeyScope",
",",
"account",
"uint32",
",",
"name",
"string",
")",
"error",
"{",
"scopedBucket",
",",
"err",
":=",
"fetchWriteScopeBucket",
"(",
"ns",
",",
"scope",... | // putAccountNameIndex stores the given key to the account name index of the
// database. | [
"putAccountNameIndex",
"stores",
"the",
"given",
"key",
"to",
"the",
"account",
"name",
"index",
"of",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L987-L1004 | train |
btcsuite/btcwallet | waddrmgr/db.go | putAddrAccountIndex | func putAddrAccountIndex(ns walletdb.ReadWriteBucket, scope *KeyScope,
account uint32, addrHash []byte) error {
scopedBucket, err := fetchWriteScopeBucket(ns, scope)
if err != nil {
return err
}
bucket := scopedBucket.NestedReadWriteBucket(addrAcctIdxBucketName)
// Write account keyed by address hash
err = bucket.Put(addrHash, uint32ToBytes(account))
if err != nil {
return nil
}
bucket, err = bucket.CreateBucketIfNotExists(uint32ToBytes(account))
if err != nil {
return err
}
// In account bucket, write a null value keyed by the address hash
err = bucket.Put(addrHash, nullVal)
if err != nil {
str := fmt.Sprintf("failed to store address account index key %s", addrHash)
return managerError(ErrDatabase, str, err)
}
return nil
} | go | func putAddrAccountIndex(ns walletdb.ReadWriteBucket, scope *KeyScope,
account uint32, addrHash []byte) error {
scopedBucket, err := fetchWriteScopeBucket(ns, scope)
if err != nil {
return err
}
bucket := scopedBucket.NestedReadWriteBucket(addrAcctIdxBucketName)
// Write account keyed by address hash
err = bucket.Put(addrHash, uint32ToBytes(account))
if err != nil {
return nil
}
bucket, err = bucket.CreateBucketIfNotExists(uint32ToBytes(account))
if err != nil {
return err
}
// In account bucket, write a null value keyed by the address hash
err = bucket.Put(addrHash, nullVal)
if err != nil {
str := fmt.Sprintf("failed to store address account index key %s", addrHash)
return managerError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"putAddrAccountIndex",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"scope",
"*",
"KeyScope",
",",
"account",
"uint32",
",",
"addrHash",
"[",
"]",
"byte",
")",
"error",
"{",
"scopedBucket",
",",
"err",
":=",
"fetchWriteScopeBucket",
"(",
"ns",
... | // putAddrAccountIndex stores the given key to the address account index of the
// database. | [
"putAddrAccountIndex",
"stores",
"the",
"given",
"key",
"to",
"the",
"address",
"account",
"index",
"of",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1028-L1056 | train |
btcsuite/btcwallet | waddrmgr/db.go | putAccountRow | func putAccountRow(ns walletdb.ReadWriteBucket, scope *KeyScope,
account uint32, row *dbAccountRow) error {
scopedBucket, err := fetchWriteScopeBucket(ns, scope)
if err != nil {
return err
}
bucket := scopedBucket.NestedReadWriteBucket(acctBucketName)
// Write the serialized value keyed by the account number.
err = bucket.Put(uint32ToBytes(account), serializeAccountRow(row))
if err != nil {
str := fmt.Sprintf("failed to store account %d", account)
return managerError(ErrDatabase, str, err)
}
return nil
} | go | func putAccountRow(ns walletdb.ReadWriteBucket, scope *KeyScope,
account uint32, row *dbAccountRow) error {
scopedBucket, err := fetchWriteScopeBucket(ns, scope)
if err != nil {
return err
}
bucket := scopedBucket.NestedReadWriteBucket(acctBucketName)
// Write the serialized value keyed by the account number.
err = bucket.Put(uint32ToBytes(account), serializeAccountRow(row))
if err != nil {
str := fmt.Sprintf("failed to store account %d", account)
return managerError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"putAccountRow",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"scope",
"*",
"KeyScope",
",",
"account",
"uint32",
",",
"row",
"*",
"dbAccountRow",
")",
"error",
"{",
"scopedBucket",
",",
"err",
":=",
"fetchWriteScopeBucket",
"(",
"ns",
",",
"s... | // putAccountRow stores the provided account information to the database. This
// is used a common base for storing the various account types. | [
"putAccountRow",
"stores",
"the",
"provided",
"account",
"information",
"to",
"the",
"database",
".",
"This",
"is",
"used",
"a",
"common",
"base",
"for",
"storing",
"the",
"various",
"account",
"types",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1060-L1077 | train |
btcsuite/btcwallet | waddrmgr/db.go | putAccountInfo | func putAccountInfo(ns walletdb.ReadWriteBucket, scope *KeyScope,
account uint32, encryptedPubKey, encryptedPrivKey []byte,
nextExternalIndex, nextInternalIndex uint32, name string) error {
rawData := serializeDefaultAccountRow(
encryptedPubKey, encryptedPrivKey, nextExternalIndex,
nextInternalIndex, name,
)
// TODO(roasbeef): pass scope bucket directly??
acctRow := dbAccountRow{
acctType: accountDefault,
rawData: rawData,
}
if err := putAccountRow(ns, scope, account, &acctRow); err != nil {
return err
}
// Update account id index.
if err := putAccountIDIndex(ns, scope, account, name); err != nil {
return err
}
// Update account name index.
if err := putAccountNameIndex(ns, scope, account, name); err != nil {
return err
}
return nil
} | go | func putAccountInfo(ns walletdb.ReadWriteBucket, scope *KeyScope,
account uint32, encryptedPubKey, encryptedPrivKey []byte,
nextExternalIndex, nextInternalIndex uint32, name string) error {
rawData := serializeDefaultAccountRow(
encryptedPubKey, encryptedPrivKey, nextExternalIndex,
nextInternalIndex, name,
)
// TODO(roasbeef): pass scope bucket directly??
acctRow := dbAccountRow{
acctType: accountDefault,
rawData: rawData,
}
if err := putAccountRow(ns, scope, account, &acctRow); err != nil {
return err
}
// Update account id index.
if err := putAccountIDIndex(ns, scope, account, name); err != nil {
return err
}
// Update account name index.
if err := putAccountNameIndex(ns, scope, account, name); err != nil {
return err
}
return nil
} | [
"func",
"putAccountInfo",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"scope",
"*",
"KeyScope",
",",
"account",
"uint32",
",",
"encryptedPubKey",
",",
"encryptedPrivKey",
"[",
"]",
"byte",
",",
"nextExternalIndex",
",",
"nextInternalIndex",
"uint32",
",",
... | // putAccountInfo stores the provided account information to the database. | [
"putAccountInfo",
"stores",
"the",
"provided",
"account",
"information",
"to",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1080-L1110 | train |
btcsuite/btcwallet | waddrmgr/db.go | putLastAccount | func putLastAccount(ns walletdb.ReadWriteBucket, scope *KeyScope,
account uint32) error {
scopedBucket, err := fetchWriteScopeBucket(ns, scope)
if err != nil {
return err
}
bucket := scopedBucket.NestedReadWriteBucket(metaBucketName)
err = bucket.Put(lastAccountName, uint32ToBytes(account))
if err != nil {
str := fmt.Sprintf("failed to update metadata '%s'", lastAccountName)
return managerError(ErrDatabase, str, err)
}
return nil
} | go | func putLastAccount(ns walletdb.ReadWriteBucket, scope *KeyScope,
account uint32) error {
scopedBucket, err := fetchWriteScopeBucket(ns, scope)
if err != nil {
return err
}
bucket := scopedBucket.NestedReadWriteBucket(metaBucketName)
err = bucket.Put(lastAccountName, uint32ToBytes(account))
if err != nil {
str := fmt.Sprintf("failed to update metadata '%s'", lastAccountName)
return managerError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"putLastAccount",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"scope",
"*",
"KeyScope",
",",
"account",
"uint32",
")",
"error",
"{",
"scopedBucket",
",",
"err",
":=",
"fetchWriteScopeBucket",
"(",
"ns",
",",
"scope",
")",
"\n",
"if",
"err",
... | // putLastAccount stores the provided metadata - last account - to the
// database. | [
"putLastAccount",
"stores",
"the",
"provided",
"metadata",
"-",
"last",
"account",
"-",
"to",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1114-L1130 | train |
btcsuite/btcwallet | waddrmgr/db.go | deserializeAddressRow | func deserializeAddressRow(serializedAddress []byte) (*dbAddressRow, error) {
// The serialized address format is:
// <addrType><account><addedTime><syncStatus><rawdata>
//
// 1 byte addrType + 4 bytes account + 8 bytes addTime + 1 byte
// syncStatus + 4 bytes raw data length + raw data
// Given the above, the length of the entry must be at a minimum
// the constant value sizes.
if len(serializedAddress) < 18 {
str := "malformed serialized address"
return nil, managerError(ErrDatabase, str, nil)
}
row := dbAddressRow{}
row.addrType = addressType(serializedAddress[0])
row.account = binary.LittleEndian.Uint32(serializedAddress[1:5])
row.addTime = binary.LittleEndian.Uint64(serializedAddress[5:13])
row.syncStatus = syncStatus(serializedAddress[13])
rdlen := binary.LittleEndian.Uint32(serializedAddress[14:18])
row.rawData = make([]byte, rdlen)
copy(row.rawData, serializedAddress[18:18+rdlen])
return &row, nil
} | go | func deserializeAddressRow(serializedAddress []byte) (*dbAddressRow, error) {
// The serialized address format is:
// <addrType><account><addedTime><syncStatus><rawdata>
//
// 1 byte addrType + 4 bytes account + 8 bytes addTime + 1 byte
// syncStatus + 4 bytes raw data length + raw data
// Given the above, the length of the entry must be at a minimum
// the constant value sizes.
if len(serializedAddress) < 18 {
str := "malformed serialized address"
return nil, managerError(ErrDatabase, str, nil)
}
row := dbAddressRow{}
row.addrType = addressType(serializedAddress[0])
row.account = binary.LittleEndian.Uint32(serializedAddress[1:5])
row.addTime = binary.LittleEndian.Uint64(serializedAddress[5:13])
row.syncStatus = syncStatus(serializedAddress[13])
rdlen := binary.LittleEndian.Uint32(serializedAddress[14:18])
row.rawData = make([]byte, rdlen)
copy(row.rawData, serializedAddress[18:18+rdlen])
return &row, nil
} | [
"func",
"deserializeAddressRow",
"(",
"serializedAddress",
"[",
"]",
"byte",
")",
"(",
"*",
"dbAddressRow",
",",
"error",
")",
"{",
"if",
"len",
"(",
"serializedAddress",
")",
"<",
"18",
"{",
"str",
":=",
"\"malformed serialized address\"",
"\n",
"return",
"ni... | // deserializeAddressRow deserializes the passed serialized address
// information. This is used as a common base for the various address types to
// deserialize the common parts. | [
"deserializeAddressRow",
"deserializes",
"the",
"passed",
"serialized",
"address",
"information",
".",
"This",
"is",
"used",
"as",
"a",
"common",
"base",
"for",
"the",
"various",
"address",
"types",
"to",
"deserialize",
"the",
"common",
"parts",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1135-L1159 | train |
btcsuite/btcwallet | waddrmgr/db.go | serializeAddressRow | func serializeAddressRow(row *dbAddressRow) []byte {
// The serialized address format is:
// <addrType><account><addedTime><syncStatus><commentlen><comment>
// <rawdata>
//
// 1 byte addrType + 4 bytes account + 8 bytes addTime + 1 byte
// syncStatus + 4 bytes raw data length + raw data
rdlen := len(row.rawData)
buf := make([]byte, 18+rdlen)
buf[0] = byte(row.addrType)
binary.LittleEndian.PutUint32(buf[1:5], row.account)
binary.LittleEndian.PutUint64(buf[5:13], row.addTime)
buf[13] = byte(row.syncStatus)
binary.LittleEndian.PutUint32(buf[14:18], uint32(rdlen))
copy(buf[18:18+rdlen], row.rawData)
return buf
} | go | func serializeAddressRow(row *dbAddressRow) []byte {
// The serialized address format is:
// <addrType><account><addedTime><syncStatus><commentlen><comment>
// <rawdata>
//
// 1 byte addrType + 4 bytes account + 8 bytes addTime + 1 byte
// syncStatus + 4 bytes raw data length + raw data
rdlen := len(row.rawData)
buf := make([]byte, 18+rdlen)
buf[0] = byte(row.addrType)
binary.LittleEndian.PutUint32(buf[1:5], row.account)
binary.LittleEndian.PutUint64(buf[5:13], row.addTime)
buf[13] = byte(row.syncStatus)
binary.LittleEndian.PutUint32(buf[14:18], uint32(rdlen))
copy(buf[18:18+rdlen], row.rawData)
return buf
} | [
"func",
"serializeAddressRow",
"(",
"row",
"*",
"dbAddressRow",
")",
"[",
"]",
"byte",
"{",
"rdlen",
":=",
"len",
"(",
"row",
".",
"rawData",
")",
"\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"18",
"+",
"rdlen",
")",
"\n",
"buf",
"[",
"... | // serializeAddressRow returns the serialization of the passed address row. | [
"serializeAddressRow",
"returns",
"the",
"serialization",
"of",
"the",
"passed",
"address",
"row",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1162-L1178 | train |
btcsuite/btcwallet | waddrmgr/db.go | deserializeChainedAddress | func deserializeChainedAddress(row *dbAddressRow) (*dbChainAddressRow, error) {
// The serialized chain address raw data format is:
// <branch><index>
//
// 4 bytes branch + 4 bytes address index
if len(row.rawData) != 8 {
str := "malformed serialized chained address"
return nil, managerError(ErrDatabase, str, nil)
}
retRow := dbChainAddressRow{
dbAddressRow: *row,
}
retRow.branch = binary.LittleEndian.Uint32(row.rawData[0:4])
retRow.index = binary.LittleEndian.Uint32(row.rawData[4:8])
return &retRow, nil
} | go | func deserializeChainedAddress(row *dbAddressRow) (*dbChainAddressRow, error) {
// The serialized chain address raw data format is:
// <branch><index>
//
// 4 bytes branch + 4 bytes address index
if len(row.rawData) != 8 {
str := "malformed serialized chained address"
return nil, managerError(ErrDatabase, str, nil)
}
retRow := dbChainAddressRow{
dbAddressRow: *row,
}
retRow.branch = binary.LittleEndian.Uint32(row.rawData[0:4])
retRow.index = binary.LittleEndian.Uint32(row.rawData[4:8])
return &retRow, nil
} | [
"func",
"deserializeChainedAddress",
"(",
"row",
"*",
"dbAddressRow",
")",
"(",
"*",
"dbChainAddressRow",
",",
"error",
")",
"{",
"if",
"len",
"(",
"row",
".",
"rawData",
")",
"!=",
"8",
"{",
"str",
":=",
"\"malformed serialized chained address\"",
"\n",
"retu... | // deserializeChainedAddress deserializes the raw data from the passed address
// row as a chained address. | [
"deserializeChainedAddress",
"deserializes",
"the",
"raw",
"data",
"from",
"the",
"passed",
"address",
"row",
"as",
"a",
"chained",
"address",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1182-L1200 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.