repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
btcsuite/btcwallet | snacl/snacl.go | NewSecretKey | func NewSecretKey(password *[]byte, N, r, p int) (*SecretKey, error) {
sk := SecretKey{
Key: (*CryptoKey)(&[KeySize]byte{}),
}
// setup parameters
sk.Parameters.N = N
sk.Parameters.R = r
sk.Parameters.P = p
_, err := io.ReadFull(prng, sk.Parameters.Salt[:])
if err != nil {
return nil, err
}
// derive key
err = sk.deriveKey(password)
if err != nil {
return nil, err
}
// store digest
sk.Parameters.Digest = sha256.Sum256(sk.Key[:])
return &sk, nil
} | go | func NewSecretKey(password *[]byte, N, r, p int) (*SecretKey, error) {
sk := SecretKey{
Key: (*CryptoKey)(&[KeySize]byte{}),
}
// setup parameters
sk.Parameters.N = N
sk.Parameters.R = r
sk.Parameters.P = p
_, err := io.ReadFull(prng, sk.Parameters.Salt[:])
if err != nil {
return nil, err
}
// derive key
err = sk.deriveKey(password)
if err != nil {
return nil, err
}
// store digest
sk.Parameters.Digest = sha256.Sum256(sk.Key[:])
return &sk, nil
} | [
"func",
"NewSecretKey",
"(",
"password",
"*",
"[",
"]",
"byte",
",",
"N",
",",
"r",
",",
"p",
"int",
")",
"(",
"*",
"SecretKey",
",",
"error",
")",
"{",
"sk",
":=",
"SecretKey",
"{",
"Key",
":",
"(",
"*",
"CryptoKey",
")",
"(",
"&",
"[",
"KeySize",
"]",
"byte",
"{",
"}",
")",
",",
"}",
"\n",
"// setup parameters",
"sk",
".",
"Parameters",
".",
"N",
"=",
"N",
"\n",
"sk",
".",
"Parameters",
".",
"R",
"=",
"r",
"\n",
"sk",
".",
"Parameters",
".",
"P",
"=",
"p",
"\n",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"prng",
",",
"sk",
".",
"Parameters",
".",
"Salt",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// derive key",
"err",
"=",
"sk",
".",
"deriveKey",
"(",
"password",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// store digest",
"sk",
".",
"Parameters",
".",
"Digest",
"=",
"sha256",
".",
"Sum256",
"(",
"sk",
".",
"Key",
"[",
":",
"]",
")",
"\n\n",
"return",
"&",
"sk",
",",
"nil",
"\n",
"}"
] | // NewSecretKey returns a SecretKey structure based on the passed parameters. | [
"NewSecretKey",
"returns",
"a",
"SecretKey",
"structure",
"based",
"on",
"the",
"passed",
"parameters",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L225-L248 | train |
btcsuite/btcwallet | wallet/txrules/rules.go | GetDustThreshold | func GetDustThreshold(scriptSize int, relayFeePerKb btcutil.Amount) btcutil.Amount {
// Calculate the total (estimated) cost to the network. This is
// calculated using the serialize size of the output plus the serial
// size of a transaction input which redeems it. The output is assumed
// to be compressed P2PKH as this is the most common script type. Use
// the average size of a compressed P2PKH redeem input (148) rather than
// the largest possible (txsizes.RedeemP2PKHInputSize).
totalSize := 8 + wire.VarIntSerializeSize(uint64(scriptSize)) +
scriptSize + 148
byteFee := relayFeePerKb / 1000
relayFee := btcutil.Amount(totalSize) * byteFee
return 3 * relayFee
} | go | func GetDustThreshold(scriptSize int, relayFeePerKb btcutil.Amount) btcutil.Amount {
// Calculate the total (estimated) cost to the network. This is
// calculated using the serialize size of the output plus the serial
// size of a transaction input which redeems it. The output is assumed
// to be compressed P2PKH as this is the most common script type. Use
// the average size of a compressed P2PKH redeem input (148) rather than
// the largest possible (txsizes.RedeemP2PKHInputSize).
totalSize := 8 + wire.VarIntSerializeSize(uint64(scriptSize)) +
scriptSize + 148
byteFee := relayFeePerKb / 1000
relayFee := btcutil.Amount(totalSize) * byteFee
return 3 * relayFee
} | [
"func",
"GetDustThreshold",
"(",
"scriptSize",
"int",
",",
"relayFeePerKb",
"btcutil",
".",
"Amount",
")",
"btcutil",
".",
"Amount",
"{",
"// Calculate the total (estimated) cost to the network. This is",
"// calculated using the serialize size of the output plus the serial",
"// size of a transaction input which redeems it. The output is assumed",
"// to be compressed P2PKH as this is the most common script type. Use",
"// the average size of a compressed P2PKH redeem input (148) rather than",
"// the largest possible (txsizes.RedeemP2PKHInputSize).",
"totalSize",
":=",
"8",
"+",
"wire",
".",
"VarIntSerializeSize",
"(",
"uint64",
"(",
"scriptSize",
")",
")",
"+",
"scriptSize",
"+",
"148",
"\n\n",
"byteFee",
":=",
"relayFeePerKb",
"/",
"1000",
"\n",
"relayFee",
":=",
"btcutil",
".",
"Amount",
"(",
"totalSize",
")",
"*",
"byteFee",
"\n",
"return",
"3",
"*",
"relayFee",
"\n",
"}"
] | // GetDustThreshold is used to define the amount below which output will be
// determined as dust. Threshold is determined as 3 times the relay fee. | [
"GetDustThreshold",
"is",
"used",
"to",
"define",
"the",
"amount",
"below",
"which",
"output",
"will",
"be",
"determined",
"as",
"dust",
".",
"Threshold",
"is",
"determined",
"as",
"3",
"times",
"the",
"relay",
"fee",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/txrules/rules.go#L22-L35 | train |
btcsuite/btcwallet | wallet/txrules/rules.go | IsDustAmount | func IsDustAmount(amount btcutil.Amount, scriptSize int, relayFeePerKb btcutil.Amount) bool {
return amount < GetDustThreshold(scriptSize, relayFeePerKb)
} | go | func IsDustAmount(amount btcutil.Amount, scriptSize int, relayFeePerKb btcutil.Amount) bool {
return amount < GetDustThreshold(scriptSize, relayFeePerKb)
} | [
"func",
"IsDustAmount",
"(",
"amount",
"btcutil",
".",
"Amount",
",",
"scriptSize",
"int",
",",
"relayFeePerKb",
"btcutil",
".",
"Amount",
")",
"bool",
"{",
"return",
"amount",
"<",
"GetDustThreshold",
"(",
"scriptSize",
",",
"relayFeePerKb",
")",
"\n",
"}"
] | // IsDustAmount determines whether a transaction output value and script length would
// cause the output to be considered dust. Transactions with dust outputs are
// not standard and are rejected by mempools with default policies. | [
"IsDustAmount",
"determines",
"whether",
"a",
"transaction",
"output",
"value",
"and",
"script",
"length",
"would",
"cause",
"the",
"output",
"to",
"be",
"considered",
"dust",
".",
"Transactions",
"with",
"dust",
"outputs",
"are",
"not",
"standard",
"and",
"are",
"rejected",
"by",
"mempools",
"with",
"default",
"policies",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/txrules/rules.go#L40-L42 | train |
btcsuite/btcwallet | wallet/txrules/rules.go | IsDustOutput | func IsDustOutput(output *wire.TxOut, relayFeePerKb btcutil.Amount) bool {
// Unspendable outputs which solely carry data are not checked for dust.
if txscript.GetScriptClass(output.PkScript) == txscript.NullDataTy {
return false
}
// All other unspendable outputs are considered dust.
if txscript.IsUnspendable(output.PkScript) {
return true
}
return IsDustAmount(btcutil.Amount(output.Value), len(output.PkScript),
relayFeePerKb)
} | go | func IsDustOutput(output *wire.TxOut, relayFeePerKb btcutil.Amount) bool {
// Unspendable outputs which solely carry data are not checked for dust.
if txscript.GetScriptClass(output.PkScript) == txscript.NullDataTy {
return false
}
// All other unspendable outputs are considered dust.
if txscript.IsUnspendable(output.PkScript) {
return true
}
return IsDustAmount(btcutil.Amount(output.Value), len(output.PkScript),
relayFeePerKb)
} | [
"func",
"IsDustOutput",
"(",
"output",
"*",
"wire",
".",
"TxOut",
",",
"relayFeePerKb",
"btcutil",
".",
"Amount",
")",
"bool",
"{",
"// Unspendable outputs which solely carry data are not checked for dust.",
"if",
"txscript",
".",
"GetScriptClass",
"(",
"output",
".",
"PkScript",
")",
"==",
"txscript",
".",
"NullDataTy",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// All other unspendable outputs are considered dust.",
"if",
"txscript",
".",
"IsUnspendable",
"(",
"output",
".",
"PkScript",
")",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"return",
"IsDustAmount",
"(",
"btcutil",
".",
"Amount",
"(",
"output",
".",
"Value",
")",
",",
"len",
"(",
"output",
".",
"PkScript",
")",
",",
"relayFeePerKb",
")",
"\n",
"}"
] | // IsDustOutput determines whether a transaction output is considered dust.
// Transactions with dust outputs are not standard and are rejected by mempools
// with default policies. | [
"IsDustOutput",
"determines",
"whether",
"a",
"transaction",
"output",
"is",
"considered",
"dust",
".",
"Transactions",
"with",
"dust",
"outputs",
"are",
"not",
"standard",
"and",
"are",
"rejected",
"by",
"mempools",
"with",
"default",
"policies",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/txrules/rules.go#L47-L60 | train |
btcsuite/btcwallet | wallet/txrules/rules.go | CheckOutput | func CheckOutput(output *wire.TxOut, relayFeePerKb btcutil.Amount) error {
if output.Value < 0 {
return ErrAmountNegative
}
if output.Value > btcutil.MaxSatoshi {
return ErrAmountExceedsMax
}
if IsDustOutput(output, relayFeePerKb) {
return ErrOutputIsDust
}
return nil
} | go | func CheckOutput(output *wire.TxOut, relayFeePerKb btcutil.Amount) error {
if output.Value < 0 {
return ErrAmountNegative
}
if output.Value > btcutil.MaxSatoshi {
return ErrAmountExceedsMax
}
if IsDustOutput(output, relayFeePerKb) {
return ErrOutputIsDust
}
return nil
} | [
"func",
"CheckOutput",
"(",
"output",
"*",
"wire",
".",
"TxOut",
",",
"relayFeePerKb",
"btcutil",
".",
"Amount",
")",
"error",
"{",
"if",
"output",
".",
"Value",
"<",
"0",
"{",
"return",
"ErrAmountNegative",
"\n",
"}",
"\n",
"if",
"output",
".",
"Value",
">",
"btcutil",
".",
"MaxSatoshi",
"{",
"return",
"ErrAmountExceedsMax",
"\n",
"}",
"\n",
"if",
"IsDustOutput",
"(",
"output",
",",
"relayFeePerKb",
")",
"{",
"return",
"ErrOutputIsDust",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CheckOutput performs simple consensus and policy tests on a transaction
// output. | [
"CheckOutput",
"performs",
"simple",
"consensus",
"and",
"policy",
"tests",
"on",
"a",
"transaction",
"output",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/txrules/rules.go#L71-L82 | train |
btcsuite/btcwallet | wallet/txrules/rules.go | FeeForSerializeSize | func FeeForSerializeSize(relayFeePerKb btcutil.Amount, txSerializeSize int) btcutil.Amount {
fee := relayFeePerKb * btcutil.Amount(txSerializeSize) / 1000
if fee == 0 && relayFeePerKb > 0 {
fee = relayFeePerKb
}
if fee < 0 || fee > btcutil.MaxSatoshi {
fee = btcutil.MaxSatoshi
}
return fee
} | go | func FeeForSerializeSize(relayFeePerKb btcutil.Amount, txSerializeSize int) btcutil.Amount {
fee := relayFeePerKb * btcutil.Amount(txSerializeSize) / 1000
if fee == 0 && relayFeePerKb > 0 {
fee = relayFeePerKb
}
if fee < 0 || fee > btcutil.MaxSatoshi {
fee = btcutil.MaxSatoshi
}
return fee
} | [
"func",
"FeeForSerializeSize",
"(",
"relayFeePerKb",
"btcutil",
".",
"Amount",
",",
"txSerializeSize",
"int",
")",
"btcutil",
".",
"Amount",
"{",
"fee",
":=",
"relayFeePerKb",
"*",
"btcutil",
".",
"Amount",
"(",
"txSerializeSize",
")",
"/",
"1000",
"\n\n",
"if",
"fee",
"==",
"0",
"&&",
"relayFeePerKb",
">",
"0",
"{",
"fee",
"=",
"relayFeePerKb",
"\n",
"}",
"\n\n",
"if",
"fee",
"<",
"0",
"||",
"fee",
">",
"btcutil",
".",
"MaxSatoshi",
"{",
"fee",
"=",
"btcutil",
".",
"MaxSatoshi",
"\n",
"}",
"\n\n",
"return",
"fee",
"\n",
"}"
] | // FeeForSerializeSize calculates the required fee for a transaction of some
// arbitrary size given a mempool's relay fee policy. | [
"FeeForSerializeSize",
"calculates",
"the",
"required",
"fee",
"for",
"a",
"transaction",
"of",
"some",
"arbitrary",
"size",
"given",
"a",
"mempool",
"s",
"relay",
"fee",
"policy",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/txrules/rules.go#L86-L98 | train |
btcsuite/btcwallet | wtxmgr/kahnsort.go | graphRoots | func graphRoots(graph hashGraph) []*wire.MsgTx {
roots := make([]*wire.MsgTx, 0, len(graph))
for _, node := range graph {
if node.inDegree == 0 {
roots = append(roots, node.value)
}
}
return roots
} | go | func graphRoots(graph hashGraph) []*wire.MsgTx {
roots := make([]*wire.MsgTx, 0, len(graph))
for _, node := range graph {
if node.inDegree == 0 {
roots = append(roots, node.value)
}
}
return roots
} | [
"func",
"graphRoots",
"(",
"graph",
"hashGraph",
")",
"[",
"]",
"*",
"wire",
".",
"MsgTx",
"{",
"roots",
":=",
"make",
"(",
"[",
"]",
"*",
"wire",
".",
"MsgTx",
",",
"0",
",",
"len",
"(",
"graph",
")",
")",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"graph",
"{",
"if",
"node",
".",
"inDegree",
"==",
"0",
"{",
"roots",
"=",
"append",
"(",
"roots",
",",
"node",
".",
"value",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"roots",
"\n",
"}"
] | // graphRoots returns the roots of the graph. That is, it returns the node's
// values for all nodes which contain an input degree of 0. | [
"graphRoots",
"returns",
"the",
"roots",
"of",
"the",
"graph",
".",
"That",
"is",
"it",
"returns",
"the",
"node",
"s",
"values",
"for",
"all",
"nodes",
"which",
"contain",
"an",
"input",
"degree",
"of",
"0",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/kahnsort.go#L76-L84 | train |
btcsuite/btcwallet | wtxmgr/kahnsort.go | DependencySort | func DependencySort(txs map[chainhash.Hash]*wire.MsgTx) []*wire.MsgTx {
graph := makeGraph(txs)
s := graphRoots(graph)
// If there are no edges (no transactions from the map reference each
// other), then Kahn's algorithm is unnecessary.
if len(s) == len(txs) {
return s
}
sorted := make([]*wire.MsgTx, 0, len(txs))
for len(s) != 0 {
tx := s[0]
s = s[1:]
sorted = append(sorted, tx)
n := graph[tx.TxHash()]
for _, mHash := range n.outEdges {
m := graph[*mHash]
if m.inDegree != 0 {
m.inDegree--
graph[*mHash] = m
if m.inDegree == 0 {
s = append(s, m.value)
}
}
}
}
return sorted
} | go | func DependencySort(txs map[chainhash.Hash]*wire.MsgTx) []*wire.MsgTx {
graph := makeGraph(txs)
s := graphRoots(graph)
// If there are no edges (no transactions from the map reference each
// other), then Kahn's algorithm is unnecessary.
if len(s) == len(txs) {
return s
}
sorted := make([]*wire.MsgTx, 0, len(txs))
for len(s) != 0 {
tx := s[0]
s = s[1:]
sorted = append(sorted, tx)
n := graph[tx.TxHash()]
for _, mHash := range n.outEdges {
m := graph[*mHash]
if m.inDegree != 0 {
m.inDegree--
graph[*mHash] = m
if m.inDegree == 0 {
s = append(s, m.value)
}
}
}
}
return sorted
} | [
"func",
"DependencySort",
"(",
"txs",
"map",
"[",
"chainhash",
".",
"Hash",
"]",
"*",
"wire",
".",
"MsgTx",
")",
"[",
"]",
"*",
"wire",
".",
"MsgTx",
"{",
"graph",
":=",
"makeGraph",
"(",
"txs",
")",
"\n",
"s",
":=",
"graphRoots",
"(",
"graph",
")",
"\n\n",
"// If there are no edges (no transactions from the map reference each",
"// other), then Kahn's algorithm is unnecessary.",
"if",
"len",
"(",
"s",
")",
"==",
"len",
"(",
"txs",
")",
"{",
"return",
"s",
"\n",
"}",
"\n\n",
"sorted",
":=",
"make",
"(",
"[",
"]",
"*",
"wire",
".",
"MsgTx",
",",
"0",
",",
"len",
"(",
"txs",
")",
")",
"\n",
"for",
"len",
"(",
"s",
")",
"!=",
"0",
"{",
"tx",
":=",
"s",
"[",
"0",
"]",
"\n",
"s",
"=",
"s",
"[",
"1",
":",
"]",
"\n",
"sorted",
"=",
"append",
"(",
"sorted",
",",
"tx",
")",
"\n\n",
"n",
":=",
"graph",
"[",
"tx",
".",
"TxHash",
"(",
")",
"]",
"\n",
"for",
"_",
",",
"mHash",
":=",
"range",
"n",
".",
"outEdges",
"{",
"m",
":=",
"graph",
"[",
"*",
"mHash",
"]",
"\n",
"if",
"m",
".",
"inDegree",
"!=",
"0",
"{",
"m",
".",
"inDegree",
"--",
"\n",
"graph",
"[",
"*",
"mHash",
"]",
"=",
"m",
"\n",
"if",
"m",
".",
"inDegree",
"==",
"0",
"{",
"s",
"=",
"append",
"(",
"s",
",",
"m",
".",
"value",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"sorted",
"\n",
"}"
] | // DependencySort topologically sorts a set of transactions by their dependency
// order. It is implemented using Kahn's algorithm. | [
"DependencySort",
"topologically",
"sorts",
"a",
"set",
"of",
"transactions",
"by",
"their",
"dependency",
"order",
".",
"It",
"is",
"implemented",
"using",
"Kahn",
"s",
"algorithm",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/kahnsort.go#L88-L117 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | String | func (k *KeyScope) String() string {
return fmt.Sprintf("m/%v'/%v'", k.Purpose, k.Coin)
} | go | func (k *KeyScope) String() string {
return fmt.Sprintf("m/%v'/%v'", k.Purpose, k.Coin)
} | [
"func",
"(",
"k",
"*",
"KeyScope",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"k",
".",
"Purpose",
",",
"k",
".",
"Coin",
")",
"\n",
"}"
] | // String returns a human readable version describing the keypath encapsulated
// by the target key scope. | [
"String",
"returns",
"a",
"human",
"readable",
"version",
"describing",
"the",
"keypath",
"encapsulated",
"by",
"the",
"target",
"key",
"scope",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L69-L71 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | zeroSensitivePublicData | func (s *ScopedKeyManager) zeroSensitivePublicData() {
// Clear all of the account private keys.
for _, acctInfo := range s.acctInfo {
acctInfo.acctKeyPub.Zero()
acctInfo.acctKeyPub = nil
}
} | go | func (s *ScopedKeyManager) zeroSensitivePublicData() {
// Clear all of the account private keys.
for _, acctInfo := range s.acctInfo {
acctInfo.acctKeyPub.Zero()
acctInfo.acctKeyPub = nil
}
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"zeroSensitivePublicData",
"(",
")",
"{",
"// Clear all of the account private keys.",
"for",
"_",
",",
"acctInfo",
":=",
"range",
"s",
".",
"acctInfo",
"{",
"acctInfo",
".",
"acctKeyPub",
".",
"Zero",
"(",
")",
"\n",
"acctInfo",
".",
"acctKeyPub",
"=",
"nil",
"\n",
"}",
"\n",
"}"
] | // zeroSensitivePublicData performs a best try effort to remove and zero all
// sensitive public data associated with the address manager such as
// hierarchical deterministic extended public keys and the crypto public keys. | [
"zeroSensitivePublicData",
"performs",
"a",
"best",
"try",
"effort",
"to",
"remove",
"and",
"zero",
"all",
"sensitive",
"public",
"data",
"associated",
"with",
"the",
"address",
"manager",
"such",
"as",
"hierarchical",
"deterministic",
"extended",
"public",
"keys",
"and",
"the",
"crypto",
"public",
"keys",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L188-L194 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | keyToManaged | func (s *ScopedKeyManager) keyToManaged(derivedKey *hdkeychain.ExtendedKey,
account, branch, index uint32) (ManagedAddress, error) {
var addrType AddressType
if branch == InternalBranch {
addrType = s.addrSchema.InternalAddrType
} else {
addrType = s.addrSchema.ExternalAddrType
}
derivationPath := DerivationPath{
Account: account,
Branch: branch,
Index: index,
}
// Create a new managed address based on the public or private key
// depending on whether the passed key is private. Also, zero the key
// after creating the managed address from it.
ma, err := newManagedAddressFromExtKey(
s, derivationPath, derivedKey, addrType,
)
defer derivedKey.Zero()
if err != nil {
return nil, err
}
if !derivedKey.IsPrivate() {
// Add the managed address to the list of addresses that need
// their private keys derived when the address manager is next
// unlocked.
info := unlockDeriveInfo{
managedAddr: ma,
branch: branch,
index: index,
}
s.deriveOnUnlock = append(s.deriveOnUnlock, &info)
}
if branch == InternalBranch {
ma.internal = true
}
return ma, nil
} | go | func (s *ScopedKeyManager) keyToManaged(derivedKey *hdkeychain.ExtendedKey,
account, branch, index uint32) (ManagedAddress, error) {
var addrType AddressType
if branch == InternalBranch {
addrType = s.addrSchema.InternalAddrType
} else {
addrType = s.addrSchema.ExternalAddrType
}
derivationPath := DerivationPath{
Account: account,
Branch: branch,
Index: index,
}
// Create a new managed address based on the public or private key
// depending on whether the passed key is private. Also, zero the key
// after creating the managed address from it.
ma, err := newManagedAddressFromExtKey(
s, derivationPath, derivedKey, addrType,
)
defer derivedKey.Zero()
if err != nil {
return nil, err
}
if !derivedKey.IsPrivate() {
// Add the managed address to the list of addresses that need
// their private keys derived when the address manager is next
// unlocked.
info := unlockDeriveInfo{
managedAddr: ma,
branch: branch,
index: index,
}
s.deriveOnUnlock = append(s.deriveOnUnlock, &info)
}
if branch == InternalBranch {
ma.internal = true
}
return ma, nil
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"keyToManaged",
"(",
"derivedKey",
"*",
"hdkeychain",
".",
"ExtendedKey",
",",
"account",
",",
"branch",
",",
"index",
"uint32",
")",
"(",
"ManagedAddress",
",",
"error",
")",
"{",
"var",
"addrType",
"AddressType",
"\n",
"if",
"branch",
"==",
"InternalBranch",
"{",
"addrType",
"=",
"s",
".",
"addrSchema",
".",
"InternalAddrType",
"\n",
"}",
"else",
"{",
"addrType",
"=",
"s",
".",
"addrSchema",
".",
"ExternalAddrType",
"\n",
"}",
"\n\n",
"derivationPath",
":=",
"DerivationPath",
"{",
"Account",
":",
"account",
",",
"Branch",
":",
"branch",
",",
"Index",
":",
"index",
",",
"}",
"\n\n",
"// Create a new managed address based on the public or private key",
"// depending on whether the passed key is private. Also, zero the key",
"// after creating the managed address from it.",
"ma",
",",
"err",
":=",
"newManagedAddressFromExtKey",
"(",
"s",
",",
"derivationPath",
",",
"derivedKey",
",",
"addrType",
",",
")",
"\n",
"defer",
"derivedKey",
".",
"Zero",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"derivedKey",
".",
"IsPrivate",
"(",
")",
"{",
"// Add the managed address to the list of addresses that need",
"// their private keys derived when the address manager is next",
"// unlocked.",
"info",
":=",
"unlockDeriveInfo",
"{",
"managedAddr",
":",
"ma",
",",
"branch",
":",
"branch",
",",
"index",
":",
"index",
",",
"}",
"\n",
"s",
".",
"deriveOnUnlock",
"=",
"append",
"(",
"s",
".",
"deriveOnUnlock",
",",
"&",
"info",
")",
"\n",
"}",
"\n\n",
"if",
"branch",
"==",
"InternalBranch",
"{",
"ma",
".",
"internal",
"=",
"true",
"\n",
"}",
"\n\n",
"return",
"ma",
",",
"nil",
"\n",
"}"
] | // keyToManaged returns a new managed address for the provided derived key and
// its derivation path which consists of the account, branch, and index.
//
// The passed derivedKey is zeroed after the new address is created.
//
// This function MUST be called with the manager lock held for writes. | [
"keyToManaged",
"returns",
"a",
"new",
"managed",
"address",
"for",
"the",
"provided",
"derived",
"key",
"and",
"its",
"derivation",
"path",
"which",
"consists",
"of",
"the",
"account",
"branch",
"and",
"index",
".",
"The",
"passed",
"derivedKey",
"is",
"zeroed",
"after",
"the",
"new",
"address",
"is",
"created",
".",
"This",
"function",
"MUST",
"be",
"called",
"with",
"the",
"manager",
"lock",
"held",
"for",
"writes",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L214-L258 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | deriveKey | func (s *ScopedKeyManager) deriveKey(acctInfo *accountInfo, branch,
index uint32, private bool) (*hdkeychain.ExtendedKey, error) {
// Choose the public or private extended key based on whether or not
// the private flag was specified. This, in turn, allows for public or
// private child derivation.
acctKey := acctInfo.acctKeyPub
if private {
acctKey = acctInfo.acctKeyPriv
}
// Derive and return the key.
branchKey, err := acctKey.Child(branch)
if err != nil {
str := fmt.Sprintf("failed to derive extended key branch %d",
branch)
return nil, managerError(ErrKeyChain, str, err)
}
addressKey, err := branchKey.Child(index)
branchKey.Zero() // Zero branch key after it's used.
if err != nil {
str := fmt.Sprintf("failed to derive child extended key -- "+
"branch %d, child %d",
branch, index)
return nil, managerError(ErrKeyChain, str, err)
}
return addressKey, nil
} | go | func (s *ScopedKeyManager) deriveKey(acctInfo *accountInfo, branch,
index uint32, private bool) (*hdkeychain.ExtendedKey, error) {
// Choose the public or private extended key based on whether or not
// the private flag was specified. This, in turn, allows for public or
// private child derivation.
acctKey := acctInfo.acctKeyPub
if private {
acctKey = acctInfo.acctKeyPriv
}
// Derive and return the key.
branchKey, err := acctKey.Child(branch)
if err != nil {
str := fmt.Sprintf("failed to derive extended key branch %d",
branch)
return nil, managerError(ErrKeyChain, str, err)
}
addressKey, err := branchKey.Child(index)
branchKey.Zero() // Zero branch key after it's used.
if err != nil {
str := fmt.Sprintf("failed to derive child extended key -- "+
"branch %d, child %d",
branch, index)
return nil, managerError(ErrKeyChain, str, err)
}
return addressKey, nil
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"deriveKey",
"(",
"acctInfo",
"*",
"accountInfo",
",",
"branch",
",",
"index",
"uint32",
",",
"private",
"bool",
")",
"(",
"*",
"hdkeychain",
".",
"ExtendedKey",
",",
"error",
")",
"{",
"// Choose the public or private extended key based on whether or not",
"// the private flag was specified. This, in turn, allows for public or",
"// private child derivation.",
"acctKey",
":=",
"acctInfo",
".",
"acctKeyPub",
"\n",
"if",
"private",
"{",
"acctKey",
"=",
"acctInfo",
".",
"acctKeyPriv",
"\n",
"}",
"\n\n",
"// Derive and return the key.",
"branchKey",
",",
"err",
":=",
"acctKey",
".",
"Child",
"(",
"branch",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"branch",
")",
"\n",
"return",
"nil",
",",
"managerError",
"(",
"ErrKeyChain",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"addressKey",
",",
"err",
":=",
"branchKey",
".",
"Child",
"(",
"index",
")",
"\n",
"branchKey",
".",
"Zero",
"(",
")",
"// Zero branch key after it's used.",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"branch",
",",
"index",
")",
"\n",
"return",
"nil",
",",
"managerError",
"(",
"ErrKeyChain",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"addressKey",
",",
"nil",
"\n",
"}"
] | // deriveKey returns either a public or private derived extended key based on
// the private flag for the given an account info, branch, and index. | [
"deriveKey",
"returns",
"either",
"a",
"public",
"or",
"private",
"derived",
"extended",
"key",
"based",
"on",
"the",
"private",
"flag",
"for",
"the",
"given",
"an",
"account",
"info",
"branch",
"and",
"index",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L262-L291 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | AccountProperties | func (s *ScopedKeyManager) AccountProperties(ns walletdb.ReadBucket,
account uint32) (*AccountProperties, error) {
defer s.mtx.RUnlock()
s.mtx.RLock()
props := &AccountProperties{AccountNumber: account}
// Until keys can be imported into any account, special handling is
// required for the imported account.
//
// loadAccountInfo errors when using it on the imported account since
// the accountInfo struct is filled with a BIP0044 account's extended
// keys, and the imported accounts has none.
//
// Since only the imported account allows imports currently, the number
// of imported keys for any other account is zero, and since the
// imported account cannot contain non-imported keys, the external and
// internal key counts for it are zero.
if account != ImportedAddrAccount {
acctInfo, err := s.loadAccountInfo(ns, account)
if err != nil {
return nil, err
}
props.AccountName = acctInfo.acctName
props.ExternalKeyCount = acctInfo.nextExternalIndex
props.InternalKeyCount = acctInfo.nextInternalIndex
} else {
props.AccountName = ImportedAddrAccountName // reserved, nonchangable
// Could be more efficient if this was tracked by the db.
var importedKeyCount uint32
count := func(interface{}) error {
importedKeyCount++
return nil
}
err := forEachAccountAddress(ns, &s.scope, ImportedAddrAccount, count)
if err != nil {
return nil, err
}
props.ImportedKeyCount = importedKeyCount
}
return props, nil
} | go | func (s *ScopedKeyManager) AccountProperties(ns walletdb.ReadBucket,
account uint32) (*AccountProperties, error) {
defer s.mtx.RUnlock()
s.mtx.RLock()
props := &AccountProperties{AccountNumber: account}
// Until keys can be imported into any account, special handling is
// required for the imported account.
//
// loadAccountInfo errors when using it on the imported account since
// the accountInfo struct is filled with a BIP0044 account's extended
// keys, and the imported accounts has none.
//
// Since only the imported account allows imports currently, the number
// of imported keys for any other account is zero, and since the
// imported account cannot contain non-imported keys, the external and
// internal key counts for it are zero.
if account != ImportedAddrAccount {
acctInfo, err := s.loadAccountInfo(ns, account)
if err != nil {
return nil, err
}
props.AccountName = acctInfo.acctName
props.ExternalKeyCount = acctInfo.nextExternalIndex
props.InternalKeyCount = acctInfo.nextInternalIndex
} else {
props.AccountName = ImportedAddrAccountName // reserved, nonchangable
// Could be more efficient if this was tracked by the db.
var importedKeyCount uint32
count := func(interface{}) error {
importedKeyCount++
return nil
}
err := forEachAccountAddress(ns, &s.scope, ImportedAddrAccount, count)
if err != nil {
return nil, err
}
props.ImportedKeyCount = importedKeyCount
}
return props, nil
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"AccountProperties",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"account",
"uint32",
")",
"(",
"*",
"AccountProperties",
",",
"error",
")",
"{",
"defer",
"s",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"s",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n\n",
"props",
":=",
"&",
"AccountProperties",
"{",
"AccountNumber",
":",
"account",
"}",
"\n\n",
"// Until keys can be imported into any account, special handling is",
"// required for the imported account.",
"//",
"// loadAccountInfo errors when using it on the imported account since",
"// the accountInfo struct is filled with a BIP0044 account's extended",
"// keys, and the imported accounts has none.",
"//",
"// Since only the imported account allows imports currently, the number",
"// of imported keys for any other account is zero, and since the",
"// imported account cannot contain non-imported keys, the external and",
"// internal key counts for it are zero.",
"if",
"account",
"!=",
"ImportedAddrAccount",
"{",
"acctInfo",
",",
"err",
":=",
"s",
".",
"loadAccountInfo",
"(",
"ns",
",",
"account",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"props",
".",
"AccountName",
"=",
"acctInfo",
".",
"acctName",
"\n",
"props",
".",
"ExternalKeyCount",
"=",
"acctInfo",
".",
"nextExternalIndex",
"\n",
"props",
".",
"InternalKeyCount",
"=",
"acctInfo",
".",
"nextInternalIndex",
"\n",
"}",
"else",
"{",
"props",
".",
"AccountName",
"=",
"ImportedAddrAccountName",
"// reserved, nonchangable",
"\n\n",
"// Could be more efficient if this was tracked by the db.",
"var",
"importedKeyCount",
"uint32",
"\n",
"count",
":=",
"func",
"(",
"interface",
"{",
"}",
")",
"error",
"{",
"importedKeyCount",
"++",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"err",
":=",
"forEachAccountAddress",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
",",
"ImportedAddrAccount",
",",
"count",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"props",
".",
"ImportedKeyCount",
"=",
"importedKeyCount",
"\n",
"}",
"\n\n",
"return",
"props",
",",
"nil",
"\n",
"}"
] | // AccountProperties returns properties associated with the account, such as
// the account number, name, and the number of derived and imported keys. | [
"AccountProperties",
"returns",
"properties",
"associated",
"with",
"the",
"account",
"such",
"as",
"the",
"account",
"number",
"name",
"and",
"the",
"number",
"of",
"derived",
"and",
"imported",
"keys",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L405-L449 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | deriveKeyFromPath | func (s *ScopedKeyManager) deriveKeyFromPath(ns walletdb.ReadBucket, account, branch,
index uint32, private bool) (*hdkeychain.ExtendedKey, error) {
// Look up the account key information.
acctInfo, err := s.loadAccountInfo(ns, account)
if err != nil {
return nil, err
}
return s.deriveKey(acctInfo, branch, index, private)
} | go | func (s *ScopedKeyManager) deriveKeyFromPath(ns walletdb.ReadBucket, account, branch,
index uint32, private bool) (*hdkeychain.ExtendedKey, error) {
// Look up the account key information.
acctInfo, err := s.loadAccountInfo(ns, account)
if err != nil {
return nil, err
}
return s.deriveKey(acctInfo, branch, index, private)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"deriveKeyFromPath",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"account",
",",
"branch",
",",
"index",
"uint32",
",",
"private",
"bool",
")",
"(",
"*",
"hdkeychain",
".",
"ExtendedKey",
",",
"error",
")",
"{",
"// Look up the account key information.",
"acctInfo",
",",
"err",
":=",
"s",
".",
"loadAccountInfo",
"(",
"ns",
",",
"account",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"s",
".",
"deriveKey",
"(",
"acctInfo",
",",
"branch",
",",
"index",
",",
"private",
")",
"\n",
"}"
] | // deriveKeyFromPath returns either a public or private derived extended key
// based on the private flag for the given an account, branch, and index.
//
// This function MUST be called with the manager lock held for writes. | [
"deriveKeyFromPath",
"returns",
"either",
"a",
"public",
"or",
"private",
"derived",
"extended",
"key",
"based",
"on",
"the",
"private",
"flag",
"for",
"the",
"given",
"an",
"account",
"branch",
"and",
"index",
".",
"This",
"function",
"MUST",
"be",
"called",
"with",
"the",
"manager",
"lock",
"held",
"for",
"writes",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L474-L484 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | chainAddressRowToManaged | func (s *ScopedKeyManager) chainAddressRowToManaged(ns walletdb.ReadBucket,
row *dbChainAddressRow) (ManagedAddress, error) {
// Since the manger's mutex is assumed to held when invoking this
// function, we use the internal isLocked to avoid a deadlock.
isLocked := s.rootManager.isLocked()
addressKey, err := s.deriveKeyFromPath(
ns, row.account, row.branch, row.index, !isLocked,
)
if err != nil {
return nil, err
}
return s.keyToManaged(addressKey, row.account, row.branch, row.index)
} | go | func (s *ScopedKeyManager) chainAddressRowToManaged(ns walletdb.ReadBucket,
row *dbChainAddressRow) (ManagedAddress, error) {
// Since the manger's mutex is assumed to held when invoking this
// function, we use the internal isLocked to avoid a deadlock.
isLocked := s.rootManager.isLocked()
addressKey, err := s.deriveKeyFromPath(
ns, row.account, row.branch, row.index, !isLocked,
)
if err != nil {
return nil, err
}
return s.keyToManaged(addressKey, row.account, row.branch, row.index)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"chainAddressRowToManaged",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"row",
"*",
"dbChainAddressRow",
")",
"(",
"ManagedAddress",
",",
"error",
")",
"{",
"// Since the manger's mutex is assumed to held when invoking this",
"// function, we use the internal isLocked to avoid a deadlock.",
"isLocked",
":=",
"s",
".",
"rootManager",
".",
"isLocked",
"(",
")",
"\n\n",
"addressKey",
",",
"err",
":=",
"s",
".",
"deriveKeyFromPath",
"(",
"ns",
",",
"row",
".",
"account",
",",
"row",
".",
"branch",
",",
"row",
".",
"index",
",",
"!",
"isLocked",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"s",
".",
"keyToManaged",
"(",
"addressKey",
",",
"row",
".",
"account",
",",
"row",
".",
"branch",
",",
"row",
".",
"index",
")",
"\n",
"}"
] | // chainAddressRowToManaged returns a new managed address based on chained
// address data loaded from the database.
//
// This function MUST be called with the manager lock held for writes. | [
"chainAddressRowToManaged",
"returns",
"a",
"new",
"managed",
"address",
"based",
"on",
"chained",
"address",
"data",
"loaded",
"from",
"the",
"database",
".",
"This",
"function",
"MUST",
"be",
"called",
"with",
"the",
"manager",
"lock",
"held",
"for",
"writes",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L490-L505 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | importedAddressRowToManaged | func (s *ScopedKeyManager) importedAddressRowToManaged(row *dbImportedAddressRow) (ManagedAddress, error) {
// Use the crypto public key to decrypt the imported public key.
pubBytes, err := s.rootManager.cryptoKeyPub.Decrypt(row.encryptedPubKey)
if err != nil {
str := "failed to decrypt public key for imported address"
return nil, managerError(ErrCrypto, str, err)
}
pubKey, err := btcec.ParsePubKey(pubBytes, btcec.S256())
if err != nil {
str := "invalid public key for imported address"
return nil, managerError(ErrCrypto, str, err)
}
// Since this is an imported address, we won't populate the full
// derivation path, as we don't have enough information to do so.
derivationPath := DerivationPath{
Account: row.account,
}
compressed := len(pubBytes) == btcec.PubKeyBytesLenCompressed
ma, err := newManagedAddressWithoutPrivKey(
s, derivationPath, pubKey, compressed,
s.addrSchema.ExternalAddrType,
)
if err != nil {
return nil, err
}
ma.privKeyEncrypted = row.encryptedPrivKey
ma.imported = true
return ma, nil
} | go | func (s *ScopedKeyManager) importedAddressRowToManaged(row *dbImportedAddressRow) (ManagedAddress, error) {
// Use the crypto public key to decrypt the imported public key.
pubBytes, err := s.rootManager.cryptoKeyPub.Decrypt(row.encryptedPubKey)
if err != nil {
str := "failed to decrypt public key for imported address"
return nil, managerError(ErrCrypto, str, err)
}
pubKey, err := btcec.ParsePubKey(pubBytes, btcec.S256())
if err != nil {
str := "invalid public key for imported address"
return nil, managerError(ErrCrypto, str, err)
}
// Since this is an imported address, we won't populate the full
// derivation path, as we don't have enough information to do so.
derivationPath := DerivationPath{
Account: row.account,
}
compressed := len(pubBytes) == btcec.PubKeyBytesLenCompressed
ma, err := newManagedAddressWithoutPrivKey(
s, derivationPath, pubKey, compressed,
s.addrSchema.ExternalAddrType,
)
if err != nil {
return nil, err
}
ma.privKeyEncrypted = row.encryptedPrivKey
ma.imported = true
return ma, nil
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"importedAddressRowToManaged",
"(",
"row",
"*",
"dbImportedAddressRow",
")",
"(",
"ManagedAddress",
",",
"error",
")",
"{",
"// Use the crypto public key to decrypt the imported public key.",
"pubBytes",
",",
"err",
":=",
"s",
".",
"rootManager",
".",
"cryptoKeyPub",
".",
"Decrypt",
"(",
"row",
".",
"encryptedPubKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"nil",
",",
"managerError",
"(",
"ErrCrypto",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"pubKey",
",",
"err",
":=",
"btcec",
".",
"ParsePubKey",
"(",
"pubBytes",
",",
"btcec",
".",
"S256",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"nil",
",",
"managerError",
"(",
"ErrCrypto",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Since this is an imported address, we won't populate the full",
"// derivation path, as we don't have enough information to do so.",
"derivationPath",
":=",
"DerivationPath",
"{",
"Account",
":",
"row",
".",
"account",
",",
"}",
"\n\n",
"compressed",
":=",
"len",
"(",
"pubBytes",
")",
"==",
"btcec",
".",
"PubKeyBytesLenCompressed",
"\n",
"ma",
",",
"err",
":=",
"newManagedAddressWithoutPrivKey",
"(",
"s",
",",
"derivationPath",
",",
"pubKey",
",",
"compressed",
",",
"s",
".",
"addrSchema",
".",
"ExternalAddrType",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"ma",
".",
"privKeyEncrypted",
"=",
"row",
".",
"encryptedPrivKey",
"\n",
"ma",
".",
"imported",
"=",
"true",
"\n\n",
"return",
"ma",
",",
"nil",
"\n",
"}"
] | // importedAddressRowToManaged returns a new managed address based on imported
// address data loaded from the database. | [
"importedAddressRowToManaged",
"returns",
"a",
"new",
"managed",
"address",
"based",
"on",
"imported",
"address",
"data",
"loaded",
"from",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L509-L542 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | scriptAddressRowToManaged | func (s *ScopedKeyManager) scriptAddressRowToManaged(row *dbScriptAddressRow) (ManagedAddress, error) {
// Use the crypto public key to decrypt the imported script hash.
scriptHash, err := s.rootManager.cryptoKeyPub.Decrypt(row.encryptedHash)
if err != nil {
str := "failed to decrypt imported script hash"
return nil, managerError(ErrCrypto, str, err)
}
return newScriptAddress(s, row.account, scriptHash, row.encryptedScript)
} | go | func (s *ScopedKeyManager) scriptAddressRowToManaged(row *dbScriptAddressRow) (ManagedAddress, error) {
// Use the crypto public key to decrypt the imported script hash.
scriptHash, err := s.rootManager.cryptoKeyPub.Decrypt(row.encryptedHash)
if err != nil {
str := "failed to decrypt imported script hash"
return nil, managerError(ErrCrypto, str, err)
}
return newScriptAddress(s, row.account, scriptHash, row.encryptedScript)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"scriptAddressRowToManaged",
"(",
"row",
"*",
"dbScriptAddressRow",
")",
"(",
"ManagedAddress",
",",
"error",
")",
"{",
"// Use the crypto public key to decrypt the imported script hash.",
"scriptHash",
",",
"err",
":=",
"s",
".",
"rootManager",
".",
"cryptoKeyPub",
".",
"Decrypt",
"(",
"row",
".",
"encryptedHash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"nil",
",",
"managerError",
"(",
"ErrCrypto",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"newScriptAddress",
"(",
"s",
",",
"row",
".",
"account",
",",
"scriptHash",
",",
"row",
".",
"encryptedScript",
")",
"\n",
"}"
] | // scriptAddressRowToManaged returns a new managed address based on script
// address data loaded from the database. | [
"scriptAddressRowToManaged",
"returns",
"a",
"new",
"managed",
"address",
"based",
"on",
"script",
"address",
"data",
"loaded",
"from",
"the",
"database",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L546-L555 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | rowInterfaceToManaged | func (s *ScopedKeyManager) rowInterfaceToManaged(ns walletdb.ReadBucket,
rowInterface interface{}) (ManagedAddress, error) {
switch row := rowInterface.(type) {
case *dbChainAddressRow:
return s.chainAddressRowToManaged(ns, row)
case *dbImportedAddressRow:
return s.importedAddressRowToManaged(row)
case *dbScriptAddressRow:
return s.scriptAddressRowToManaged(row)
}
str := fmt.Sprintf("unsupported address type %T", rowInterface)
return nil, managerError(ErrDatabase, str, nil)
} | go | func (s *ScopedKeyManager) rowInterfaceToManaged(ns walletdb.ReadBucket,
rowInterface interface{}) (ManagedAddress, error) {
switch row := rowInterface.(type) {
case *dbChainAddressRow:
return s.chainAddressRowToManaged(ns, row)
case *dbImportedAddressRow:
return s.importedAddressRowToManaged(row)
case *dbScriptAddressRow:
return s.scriptAddressRowToManaged(row)
}
str := fmt.Sprintf("unsupported address type %T", rowInterface)
return nil, managerError(ErrDatabase, str, nil)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"rowInterfaceToManaged",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"rowInterface",
"interface",
"{",
"}",
")",
"(",
"ManagedAddress",
",",
"error",
")",
"{",
"switch",
"row",
":=",
"rowInterface",
".",
"(",
"type",
")",
"{",
"case",
"*",
"dbChainAddressRow",
":",
"return",
"s",
".",
"chainAddressRowToManaged",
"(",
"ns",
",",
"row",
")",
"\n\n",
"case",
"*",
"dbImportedAddressRow",
":",
"return",
"s",
".",
"importedAddressRowToManaged",
"(",
"row",
")",
"\n\n",
"case",
"*",
"dbScriptAddressRow",
":",
"return",
"s",
".",
"scriptAddressRowToManaged",
"(",
"row",
")",
"\n",
"}",
"\n\n",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"rowInterface",
")",
"\n",
"return",
"nil",
",",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"nil",
")",
"\n",
"}"
] | // rowInterfaceToManaged returns a new managed address based on the given
// address data loaded from the database. It will automatically select the
// appropriate type.
//
// This function MUST be called with the manager lock held for writes. | [
"rowInterfaceToManaged",
"returns",
"a",
"new",
"managed",
"address",
"based",
"on",
"the",
"given",
"address",
"data",
"loaded",
"from",
"the",
"database",
".",
"It",
"will",
"automatically",
"select",
"the",
"appropriate",
"type",
".",
"This",
"function",
"MUST",
"be",
"called",
"with",
"the",
"manager",
"lock",
"held",
"for",
"writes",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L562-L578 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | loadAndCacheAddress | func (s *ScopedKeyManager) loadAndCacheAddress(ns walletdb.ReadBucket,
address btcutil.Address) (ManagedAddress, error) {
// Attempt to load the raw address information from the database.
rowInterface, err := fetchAddress(ns, &s.scope, address.ScriptAddress())
if err != nil {
if merr, ok := err.(*ManagerError); ok {
desc := fmt.Sprintf("failed to fetch address '%s': %v",
address.ScriptAddress(), merr.Description)
merr.Description = desc
return nil, merr
}
return nil, maybeConvertDbError(err)
}
// Create a new managed address for the specific type of address based
// on type.
managedAddr, err := s.rowInterfaceToManaged(ns, rowInterface)
if err != nil {
return nil, err
}
// Cache and return the new managed address.
s.addrs[addrKey(managedAddr.Address().ScriptAddress())] = managedAddr
return managedAddr, nil
} | go | func (s *ScopedKeyManager) loadAndCacheAddress(ns walletdb.ReadBucket,
address btcutil.Address) (ManagedAddress, error) {
// Attempt to load the raw address information from the database.
rowInterface, err := fetchAddress(ns, &s.scope, address.ScriptAddress())
if err != nil {
if merr, ok := err.(*ManagerError); ok {
desc := fmt.Sprintf("failed to fetch address '%s': %v",
address.ScriptAddress(), merr.Description)
merr.Description = desc
return nil, merr
}
return nil, maybeConvertDbError(err)
}
// Create a new managed address for the specific type of address based
// on type.
managedAddr, err := s.rowInterfaceToManaged(ns, rowInterface)
if err != nil {
return nil, err
}
// Cache and return the new managed address.
s.addrs[addrKey(managedAddr.Address().ScriptAddress())] = managedAddr
return managedAddr, nil
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"loadAndCacheAddress",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"address",
"btcutil",
".",
"Address",
")",
"(",
"ManagedAddress",
",",
"error",
")",
"{",
"// Attempt to load the raw address information from the database.",
"rowInterface",
",",
"err",
":=",
"fetchAddress",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
",",
"address",
".",
"ScriptAddress",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"merr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"ManagerError",
")",
";",
"ok",
"{",
"desc",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"address",
".",
"ScriptAddress",
"(",
")",
",",
"merr",
".",
"Description",
")",
"\n",
"merr",
".",
"Description",
"=",
"desc",
"\n",
"return",
"nil",
",",
"merr",
"\n",
"}",
"\n",
"return",
"nil",
",",
"maybeConvertDbError",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Create a new managed address for the specific type of address based",
"// on type.",
"managedAddr",
",",
"err",
":=",
"s",
".",
"rowInterfaceToManaged",
"(",
"ns",
",",
"rowInterface",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Cache and return the new managed address.",
"s",
".",
"addrs",
"[",
"addrKey",
"(",
"managedAddr",
".",
"Address",
"(",
")",
".",
"ScriptAddress",
"(",
")",
")",
"]",
"=",
"managedAddr",
"\n\n",
"return",
"managedAddr",
",",
"nil",
"\n",
"}"
] | // loadAndCacheAddress attempts to load the passed address from the database
// and caches the associated managed address.
//
// This function MUST be called with the manager lock held for writes. | [
"loadAndCacheAddress",
"attempts",
"to",
"load",
"the",
"passed",
"address",
"from",
"the",
"database",
"and",
"caches",
"the",
"associated",
"managed",
"address",
".",
"This",
"function",
"MUST",
"be",
"called",
"with",
"the",
"manager",
"lock",
"held",
"for",
"writes",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L584-L610 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | existsAddress | func (s *ScopedKeyManager) existsAddress(ns walletdb.ReadBucket, addressID []byte) bool {
// Check the in-memory map first since it's faster than a db access.
if _, ok := s.addrs[addrKey(addressID)]; ok {
return true
}
// Check the database if not already found above.
return existsAddress(ns, &s.scope, addressID)
} | go | func (s *ScopedKeyManager) existsAddress(ns walletdb.ReadBucket, addressID []byte) bool {
// Check the in-memory map first since it's faster than a db access.
if _, ok := s.addrs[addrKey(addressID)]; ok {
return true
}
// Check the database if not already found above.
return existsAddress(ns, &s.scope, addressID)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"existsAddress",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"addressID",
"[",
"]",
"byte",
")",
"bool",
"{",
"// Check the in-memory map first since it's faster than a db access.",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"addrs",
"[",
"addrKey",
"(",
"addressID",
")",
"]",
";",
"ok",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"// Check the database if not already found above.",
"return",
"existsAddress",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
",",
"addressID",
")",
"\n",
"}"
] | // existsAddress returns whether or not the passed address is known to the
// address manager.
//
// This function MUST be called with the manager lock held for reads. | [
"existsAddress",
"returns",
"whether",
"or",
"not",
"the",
"passed",
"address",
"is",
"known",
"to",
"the",
"address",
"manager",
".",
"This",
"function",
"MUST",
"be",
"called",
"with",
"the",
"manager",
"lock",
"held",
"for",
"reads",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L616-L624 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | Address | func (s *ScopedKeyManager) Address(ns walletdb.ReadBucket,
address btcutil.Address) (ManagedAddress, error) {
// ScriptAddress will only return a script hash if we're accessing an
// address that is either PKH or SH. In the event we're passed a PK
// address, convert the PK to PKH address so that we can access it from
// the addrs map and database.
if pka, ok := address.(*btcutil.AddressPubKey); ok {
address = pka.AddressPubKeyHash()
}
// Return the address from cache if it's available.
//
// NOTE: Not using a defer on the lock here since a write lock is
// needed if the lookup fails.
s.mtx.RLock()
if ma, ok := s.addrs[addrKey(address.ScriptAddress())]; ok {
s.mtx.RUnlock()
return ma, nil
}
s.mtx.RUnlock()
s.mtx.Lock()
defer s.mtx.Unlock()
// Attempt to load the address from the database.
return s.loadAndCacheAddress(ns, address)
} | go | func (s *ScopedKeyManager) Address(ns walletdb.ReadBucket,
address btcutil.Address) (ManagedAddress, error) {
// ScriptAddress will only return a script hash if we're accessing an
// address that is either PKH or SH. In the event we're passed a PK
// address, convert the PK to PKH address so that we can access it from
// the addrs map and database.
if pka, ok := address.(*btcutil.AddressPubKey); ok {
address = pka.AddressPubKeyHash()
}
// Return the address from cache if it's available.
//
// NOTE: Not using a defer on the lock here since a write lock is
// needed if the lookup fails.
s.mtx.RLock()
if ma, ok := s.addrs[addrKey(address.ScriptAddress())]; ok {
s.mtx.RUnlock()
return ma, nil
}
s.mtx.RUnlock()
s.mtx.Lock()
defer s.mtx.Unlock()
// Attempt to load the address from the database.
return s.loadAndCacheAddress(ns, address)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"Address",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"address",
"btcutil",
".",
"Address",
")",
"(",
"ManagedAddress",
",",
"error",
")",
"{",
"// ScriptAddress will only return a script hash if we're accessing an",
"// address that is either PKH or SH. In the event we're passed a PK",
"// address, convert the PK to PKH address so that we can access it from",
"// the addrs map and database.",
"if",
"pka",
",",
"ok",
":=",
"address",
".",
"(",
"*",
"btcutil",
".",
"AddressPubKey",
")",
";",
"ok",
"{",
"address",
"=",
"pka",
".",
"AddressPubKeyHash",
"(",
")",
"\n",
"}",
"\n\n",
"// Return the address from cache if it's available.",
"//",
"// NOTE: Not using a defer on the lock here since a write lock is",
"// needed if the lookup fails.",
"s",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"if",
"ma",
",",
"ok",
":=",
"s",
".",
"addrs",
"[",
"addrKey",
"(",
"address",
".",
"ScriptAddress",
"(",
")",
")",
"]",
";",
"ok",
"{",
"s",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"ma",
",",
"nil",
"\n",
"}",
"\n",
"s",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"// Attempt to load the address from the database.",
"return",
"s",
".",
"loadAndCacheAddress",
"(",
"ns",
",",
"address",
")",
"\n",
"}"
] | // Address returns a managed address given the passed address if it is known to
// the address manager. A managed address differs from the passed address in
// that it also potentially contains extra information needed to sign
// transactions such as the associated private key for pay-to-pubkey and
// pay-to-pubkey-hash addresses and the script associated with
// pay-to-script-hash addresses. | [
"Address",
"returns",
"a",
"managed",
"address",
"given",
"the",
"passed",
"address",
"if",
"it",
"is",
"known",
"to",
"the",
"address",
"manager",
".",
"A",
"managed",
"address",
"differs",
"from",
"the",
"passed",
"address",
"in",
"that",
"it",
"also",
"potentially",
"contains",
"extra",
"information",
"needed",
"to",
"sign",
"transactions",
"such",
"as",
"the",
"associated",
"private",
"key",
"for",
"pay",
"-",
"to",
"-",
"pubkey",
"and",
"pay",
"-",
"to",
"-",
"pubkey",
"-",
"hash",
"addresses",
"and",
"the",
"script",
"associated",
"with",
"pay",
"-",
"to",
"-",
"script",
"-",
"hash",
"addresses",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L632-L659 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | AddrAccount | func (s *ScopedKeyManager) AddrAccount(ns walletdb.ReadBucket,
address btcutil.Address) (uint32, error) {
account, err := fetchAddrAccount(ns, &s.scope, address.ScriptAddress())
if err != nil {
return 0, maybeConvertDbError(err)
}
return account, nil
} | go | func (s *ScopedKeyManager) AddrAccount(ns walletdb.ReadBucket,
address btcutil.Address) (uint32, error) {
account, err := fetchAddrAccount(ns, &s.scope, address.ScriptAddress())
if err != nil {
return 0, maybeConvertDbError(err)
}
return account, nil
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"AddrAccount",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"address",
"btcutil",
".",
"Address",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"account",
",",
"err",
":=",
"fetchAddrAccount",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
",",
"address",
".",
"ScriptAddress",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"maybeConvertDbError",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"account",
",",
"nil",
"\n",
"}"
] | // AddrAccount returns the account to which the given address belongs. | [
"AddrAccount",
"returns",
"the",
"account",
"to",
"which",
"the",
"given",
"address",
"belongs",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L662-L671 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | NextExternalAddresses | func (s *ScopedKeyManager) NextExternalAddresses(ns walletdb.ReadWriteBucket,
account uint32, numAddresses uint32) ([]ManagedAddress, error) {
// Enforce maximum account number.
if account > MaxAccountNum {
err := managerError(ErrAccountNumTooHigh, errAcctTooHigh, nil)
return nil, err
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.nextAddresses(ns, account, numAddresses, false)
} | go | func (s *ScopedKeyManager) NextExternalAddresses(ns walletdb.ReadWriteBucket,
account uint32, numAddresses uint32) ([]ManagedAddress, error) {
// Enforce maximum account number.
if account > MaxAccountNum {
err := managerError(ErrAccountNumTooHigh, errAcctTooHigh, nil)
return nil, err
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.nextAddresses(ns, account, numAddresses, false)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"NextExternalAddresses",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"account",
"uint32",
",",
"numAddresses",
"uint32",
")",
"(",
"[",
"]",
"ManagedAddress",
",",
"error",
")",
"{",
"// Enforce maximum account number.",
"if",
"account",
">",
"MaxAccountNum",
"{",
"err",
":=",
"managerError",
"(",
"ErrAccountNumTooHigh",
",",
"errAcctTooHigh",
",",
"nil",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"s",
".",
"nextAddresses",
"(",
"ns",
",",
"account",
",",
"numAddresses",
",",
"false",
")",
"\n",
"}"
] | // NextExternalAddresses returns the specified number of next chained addresses
// that are intended for external use from the address manager. | [
"NextExternalAddresses",
"returns",
"the",
"specified",
"number",
"of",
"next",
"chained",
"addresses",
"that",
"are",
"intended",
"for",
"external",
"use",
"from",
"the",
"address",
"manager",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L1053-L1066 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | ExtendExternalAddresses | func (s *ScopedKeyManager) ExtendExternalAddresses(ns walletdb.ReadWriteBucket,
account uint32, lastIndex uint32) error {
if account > MaxAccountNum {
err := managerError(ErrAccountNumTooHigh, errAcctTooHigh, nil)
return err
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.extendAddresses(ns, account, lastIndex, false)
} | go | func (s *ScopedKeyManager) ExtendExternalAddresses(ns walletdb.ReadWriteBucket,
account uint32, lastIndex uint32) error {
if account > MaxAccountNum {
err := managerError(ErrAccountNumTooHigh, errAcctTooHigh, nil)
return err
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.extendAddresses(ns, account, lastIndex, false)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"ExtendExternalAddresses",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"account",
"uint32",
",",
"lastIndex",
"uint32",
")",
"error",
"{",
"if",
"account",
">",
"MaxAccountNum",
"{",
"err",
":=",
"managerError",
"(",
"ErrAccountNumTooHigh",
",",
"errAcctTooHigh",
",",
"nil",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"s",
".",
"extendAddresses",
"(",
"ns",
",",
"account",
",",
"lastIndex",
",",
"false",
")",
"\n",
"}"
] | // ExtendExternalAddresses ensures that all valid external keys through
// lastIndex are derived and stored in the wallet. This is used to ensure that
// wallet's persistent state catches up to a external child that was found
// during recovery. | [
"ExtendExternalAddresses",
"ensures",
"that",
"all",
"valid",
"external",
"keys",
"through",
"lastIndex",
"are",
"derived",
"and",
"stored",
"in",
"the",
"wallet",
".",
"This",
"is",
"used",
"to",
"ensure",
"that",
"wallet",
"s",
"persistent",
"state",
"catches",
"up",
"to",
"a",
"external",
"child",
"that",
"was",
"found",
"during",
"recovery",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L1089-L1101 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | LastExternalAddress | func (s *ScopedKeyManager) LastExternalAddress(ns walletdb.ReadBucket,
account uint32) (ManagedAddress, error) {
// Enforce maximum account number.
if account > MaxAccountNum {
err := managerError(ErrAccountNumTooHigh, errAcctTooHigh, nil)
return nil, err
}
s.mtx.Lock()
defer s.mtx.Unlock()
// Load account information for the passed account. It is typically
// cached, but if not it will be loaded from the database.
acctInfo, err := s.loadAccountInfo(ns, account)
if err != nil {
return nil, err
}
if acctInfo.nextExternalIndex > 0 {
return acctInfo.lastExternalAddr, nil
}
return nil, managerError(ErrAddressNotFound, "no previous external address", nil)
} | go | func (s *ScopedKeyManager) LastExternalAddress(ns walletdb.ReadBucket,
account uint32) (ManagedAddress, error) {
// Enforce maximum account number.
if account > MaxAccountNum {
err := managerError(ErrAccountNumTooHigh, errAcctTooHigh, nil)
return nil, err
}
s.mtx.Lock()
defer s.mtx.Unlock()
// Load account information for the passed account. It is typically
// cached, but if not it will be loaded from the database.
acctInfo, err := s.loadAccountInfo(ns, account)
if err != nil {
return nil, err
}
if acctInfo.nextExternalIndex > 0 {
return acctInfo.lastExternalAddr, nil
}
return nil, managerError(ErrAddressNotFound, "no previous external address", nil)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"LastExternalAddress",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"account",
"uint32",
")",
"(",
"ManagedAddress",
",",
"error",
")",
"{",
"// Enforce maximum account number.",
"if",
"account",
">",
"MaxAccountNum",
"{",
"err",
":=",
"managerError",
"(",
"ErrAccountNumTooHigh",
",",
"errAcctTooHigh",
",",
"nil",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"// Load account information for the passed account. It is typically",
"// cached, but if not it will be loaded from the database.",
"acctInfo",
",",
"err",
":=",
"s",
".",
"loadAccountInfo",
"(",
"ns",
",",
"account",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"acctInfo",
".",
"nextExternalIndex",
">",
"0",
"{",
"return",
"acctInfo",
".",
"lastExternalAddr",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"managerError",
"(",
"ErrAddressNotFound",
",",
"\"",
"\"",
",",
"nil",
")",
"\n",
"}"
] | // LastExternalAddress returns the most recently requested chained external
// address from calling NextExternalAddress for the given account. The first
// external address for the account will be returned if none have been
// previously requested.
//
// This function will return an error if the provided account number is greater
// than the MaxAccountNum constant or there is no account information for the
// passed account. Any other errors returned are generally unexpected. | [
"LastExternalAddress",
"returns",
"the",
"most",
"recently",
"requested",
"chained",
"external",
"address",
"from",
"calling",
"NextExternalAddress",
"for",
"the",
"given",
"account",
".",
"The",
"first",
"external",
"address",
"for",
"the",
"account",
"will",
"be",
"returned",
"if",
"none",
"have",
"been",
"previously",
"requested",
".",
"This",
"function",
"will",
"return",
"an",
"error",
"if",
"the",
"provided",
"account",
"number",
"is",
"greater",
"than",
"the",
"MaxAccountNum",
"constant",
"or",
"there",
"is",
"no",
"account",
"information",
"for",
"the",
"passed",
"account",
".",
"Any",
"other",
"errors",
"returned",
"are",
"generally",
"unexpected",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L1129-L1153 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | LastInternalAddress | func (s *ScopedKeyManager) LastInternalAddress(ns walletdb.ReadBucket,
account uint32) (ManagedAddress, error) {
// Enforce maximum account number.
if account > MaxAccountNum {
err := managerError(ErrAccountNumTooHigh, errAcctTooHigh, nil)
return nil, err
}
s.mtx.Lock()
defer s.mtx.Unlock()
// Load account information for the passed account. It is typically
// cached, but if not it will be loaded from the database.
acctInfo, err := s.loadAccountInfo(ns, account)
if err != nil {
return nil, err
}
if acctInfo.nextInternalIndex > 0 {
return acctInfo.lastInternalAddr, nil
}
return nil, managerError(ErrAddressNotFound, "no previous internal address", nil)
} | go | func (s *ScopedKeyManager) LastInternalAddress(ns walletdb.ReadBucket,
account uint32) (ManagedAddress, error) {
// Enforce maximum account number.
if account > MaxAccountNum {
err := managerError(ErrAccountNumTooHigh, errAcctTooHigh, nil)
return nil, err
}
s.mtx.Lock()
defer s.mtx.Unlock()
// Load account information for the passed account. It is typically
// cached, but if not it will be loaded from the database.
acctInfo, err := s.loadAccountInfo(ns, account)
if err != nil {
return nil, err
}
if acctInfo.nextInternalIndex > 0 {
return acctInfo.lastInternalAddr, nil
}
return nil, managerError(ErrAddressNotFound, "no previous internal address", nil)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"LastInternalAddress",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"account",
"uint32",
")",
"(",
"ManagedAddress",
",",
"error",
")",
"{",
"// Enforce maximum account number.",
"if",
"account",
">",
"MaxAccountNum",
"{",
"err",
":=",
"managerError",
"(",
"ErrAccountNumTooHigh",
",",
"errAcctTooHigh",
",",
"nil",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"// Load account information for the passed account. It is typically",
"// cached, but if not it will be loaded from the database.",
"acctInfo",
",",
"err",
":=",
"s",
".",
"loadAccountInfo",
"(",
"ns",
",",
"account",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"acctInfo",
".",
"nextInternalIndex",
">",
"0",
"{",
"return",
"acctInfo",
".",
"lastInternalAddr",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"managerError",
"(",
"ErrAddressNotFound",
",",
"\"",
"\"",
",",
"nil",
")",
"\n",
"}"
] | // LastInternalAddress returns the most recently requested chained internal
// address from calling NextInternalAddress for the given account. The first
// internal address for the account will be returned if none have been
// previously requested.
//
// This function will return an error if the provided account number is greater
// than the MaxAccountNum constant or there is no account information for the
// passed account. Any other errors returned are generally unexpected. | [
"LastInternalAddress",
"returns",
"the",
"most",
"recently",
"requested",
"chained",
"internal",
"address",
"from",
"calling",
"NextInternalAddress",
"for",
"the",
"given",
"account",
".",
"The",
"first",
"internal",
"address",
"for",
"the",
"account",
"will",
"be",
"returned",
"if",
"none",
"have",
"been",
"previously",
"requested",
".",
"This",
"function",
"will",
"return",
"an",
"error",
"if",
"the",
"provided",
"account",
"number",
"is",
"greater",
"than",
"the",
"MaxAccountNum",
"constant",
"or",
"there",
"is",
"no",
"account",
"information",
"for",
"the",
"passed",
"account",
".",
"Any",
"other",
"errors",
"returned",
"are",
"generally",
"unexpected",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L1163-L1187 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | RenameAccount | func (s *ScopedKeyManager) RenameAccount(ns walletdb.ReadWriteBucket,
account uint32, name string) error {
s.mtx.Lock()
defer s.mtx.Unlock()
// Ensure that a reserved account is not being renamed.
if isReservedAccountNum(account) {
str := "reserved account cannot be renamed"
return managerError(ErrInvalidAccount, str, nil)
}
// Check that account with the new name does not exist
_, err := s.lookupAccount(ns, name)
if err == nil {
str := fmt.Sprintf("account with the same name already exists")
return managerError(ErrDuplicateAccount, str, err)
}
// Validate account name
if err := ValidateAccountName(name); err != nil {
return err
}
rowInterface, err := fetchAccountInfo(ns, &s.scope, account)
if err != nil {
return err
}
// Ensure the account type is a default account.
row, ok := rowInterface.(*dbDefaultAccountRow)
if !ok {
str := fmt.Sprintf("unsupported account type %T", row)
err = managerError(ErrDatabase, str, nil)
}
// Remove the old name key from the account id index.
if err = deleteAccountIDIndex(ns, &s.scope, account); err != nil {
return err
}
// Remove the old name key from the account name index.
if err = deleteAccountNameIndex(ns, &s.scope, row.name); err != nil {
return err
}
err = putAccountInfo(
ns, &s.scope, account, row.pubKeyEncrypted,
row.privKeyEncrypted, row.nextExternalIndex,
row.nextInternalIndex, name,
)
if err != nil {
return err
}
// Update in-memory account info with new name if cached and the db
// write was successful.
if err == nil {
if acctInfo, ok := s.acctInfo[account]; ok {
acctInfo.acctName = name
}
}
return err
} | go | func (s *ScopedKeyManager) RenameAccount(ns walletdb.ReadWriteBucket,
account uint32, name string) error {
s.mtx.Lock()
defer s.mtx.Unlock()
// Ensure that a reserved account is not being renamed.
if isReservedAccountNum(account) {
str := "reserved account cannot be renamed"
return managerError(ErrInvalidAccount, str, nil)
}
// Check that account with the new name does not exist
_, err := s.lookupAccount(ns, name)
if err == nil {
str := fmt.Sprintf("account with the same name already exists")
return managerError(ErrDuplicateAccount, str, err)
}
// Validate account name
if err := ValidateAccountName(name); err != nil {
return err
}
rowInterface, err := fetchAccountInfo(ns, &s.scope, account)
if err != nil {
return err
}
// Ensure the account type is a default account.
row, ok := rowInterface.(*dbDefaultAccountRow)
if !ok {
str := fmt.Sprintf("unsupported account type %T", row)
err = managerError(ErrDatabase, str, nil)
}
// Remove the old name key from the account id index.
if err = deleteAccountIDIndex(ns, &s.scope, account); err != nil {
return err
}
// Remove the old name key from the account name index.
if err = deleteAccountNameIndex(ns, &s.scope, row.name); err != nil {
return err
}
err = putAccountInfo(
ns, &s.scope, account, row.pubKeyEncrypted,
row.privKeyEncrypted, row.nextExternalIndex,
row.nextInternalIndex, name,
)
if err != nil {
return err
}
// Update in-memory account info with new name if cached and the db
// write was successful.
if err == nil {
if acctInfo, ok := s.acctInfo[account]; ok {
acctInfo.acctName = name
}
}
return err
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"RenameAccount",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"account",
"uint32",
",",
"name",
"string",
")",
"error",
"{",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"// Ensure that a reserved account is not being renamed.",
"if",
"isReservedAccountNum",
"(",
"account",
")",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrInvalidAccount",
",",
"str",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"// Check that account with the new name does not exist",
"_",
",",
"err",
":=",
"s",
".",
"lookupAccount",
"(",
"ns",
",",
"name",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"managerError",
"(",
"ErrDuplicateAccount",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Validate account name",
"if",
"err",
":=",
"ValidateAccountName",
"(",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"rowInterface",
",",
"err",
":=",
"fetchAccountInfo",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
",",
"account",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Ensure the account type is a default account.",
"row",
",",
"ok",
":=",
"rowInterface",
".",
"(",
"*",
"dbDefaultAccountRow",
")",
"\n",
"if",
"!",
"ok",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"row",
")",
"\n",
"err",
"=",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"// Remove the old name key from the account id index.",
"if",
"err",
"=",
"deleteAccountIDIndex",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
",",
"account",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Remove the old name key from the account name index.",
"if",
"err",
"=",
"deleteAccountNameIndex",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
",",
"row",
".",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"putAccountInfo",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
",",
"account",
",",
"row",
".",
"pubKeyEncrypted",
",",
"row",
".",
"privKeyEncrypted",
",",
"row",
".",
"nextExternalIndex",
",",
"row",
".",
"nextInternalIndex",
",",
"name",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Update in-memory account info with new name if cached and the db",
"// write was successful.",
"if",
"err",
"==",
"nil",
"{",
"if",
"acctInfo",
",",
"ok",
":=",
"s",
".",
"acctInfo",
"[",
"account",
"]",
";",
"ok",
"{",
"acctInfo",
".",
"acctName",
"=",
"name",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
] | // RenameAccount renames an account stored in the manager based on the given
// account number with the given name. If an account with the same name
// already exists, ErrDuplicateAccount will be returned. | [
"RenameAccount",
"renames",
"an",
"account",
"stored",
"in",
"the",
"manager",
"based",
"on",
"the",
"given",
"account",
"number",
"with",
"the",
"given",
"name",
".",
"If",
"an",
"account",
"with",
"the",
"same",
"name",
"already",
"exists",
"ErrDuplicateAccount",
"will",
"be",
"returned",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L1332-L1395 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | ImportScript | func (s *ScopedKeyManager) ImportScript(ns walletdb.ReadWriteBucket,
script []byte, bs *BlockStamp) (ManagedScriptAddress, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
// The manager must be unlocked to encrypt the imported script.
if s.rootManager.IsLocked() && !s.rootManager.WatchOnly() {
return nil, managerError(ErrLocked, errLocked, nil)
}
// Prevent duplicates.
scriptHash := btcutil.Hash160(script)
alreadyExists := s.existsAddress(ns, scriptHash)
if alreadyExists {
str := fmt.Sprintf("address for script hash %x already exists",
scriptHash)
return nil, managerError(ErrDuplicateAddress, str, nil)
}
// Encrypt the script hash using the crypto public key so it is
// accessible when the address manager is locked or watching-only.
encryptedHash, err := s.rootManager.cryptoKeyPub.Encrypt(scriptHash)
if err != nil {
str := fmt.Sprintf("failed to encrypt script hash %x",
scriptHash)
return nil, managerError(ErrCrypto, str, err)
}
// Encrypt the script for storage in database using the crypto script
// key when not a watching-only address manager.
var encryptedScript []byte
if !s.rootManager.WatchOnly() {
encryptedScript, err = s.rootManager.cryptoKeyScript.Encrypt(
script,
)
if err != nil {
str := fmt.Sprintf("failed to encrypt script for %x",
scriptHash)
return nil, managerError(ErrCrypto, str, err)
}
}
// The start block needs to be updated when the newly imported address
// is before the current one.
updateStartBlock := false
s.rootManager.mtx.Lock()
if bs.Height < s.rootManager.syncState.startBlock.Height {
updateStartBlock = true
}
s.rootManager.mtx.Unlock()
// Save the new imported address to the db and update start block (if
// needed) in a single transaction.
err = putScriptAddress(
ns, &s.scope, scriptHash, ImportedAddrAccount, ssNone,
encryptedHash, encryptedScript,
)
if err != nil {
return nil, maybeConvertDbError(err)
}
if updateStartBlock {
err := putStartBlock(ns, bs)
if err != nil {
return nil, maybeConvertDbError(err)
}
}
// Now that the database has been updated, update the start block in
// memory too if needed.
if updateStartBlock {
s.rootManager.mtx.Lock()
s.rootManager.syncState.startBlock = *bs
s.rootManager.mtx.Unlock()
}
// Create a new managed address based on the imported script. Also,
// when not a watching-only address manager, make a copy of the script
// since it will be cleared on lock and the script the caller passed
// should not be cleared out from under the caller.
scriptAddr, err := newScriptAddress(
s, ImportedAddrAccount, scriptHash, encryptedScript,
)
if err != nil {
return nil, err
}
if !s.rootManager.WatchOnly() {
scriptAddr.scriptCT = make([]byte, len(script))
copy(scriptAddr.scriptCT, script)
}
// Add the new managed address to the cache of recent addresses and
// return it.
s.addrs[addrKey(scriptHash)] = scriptAddr
return scriptAddr, nil
} | go | func (s *ScopedKeyManager) ImportScript(ns walletdb.ReadWriteBucket,
script []byte, bs *BlockStamp) (ManagedScriptAddress, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
// The manager must be unlocked to encrypt the imported script.
if s.rootManager.IsLocked() && !s.rootManager.WatchOnly() {
return nil, managerError(ErrLocked, errLocked, nil)
}
// Prevent duplicates.
scriptHash := btcutil.Hash160(script)
alreadyExists := s.existsAddress(ns, scriptHash)
if alreadyExists {
str := fmt.Sprintf("address for script hash %x already exists",
scriptHash)
return nil, managerError(ErrDuplicateAddress, str, nil)
}
// Encrypt the script hash using the crypto public key so it is
// accessible when the address manager is locked or watching-only.
encryptedHash, err := s.rootManager.cryptoKeyPub.Encrypt(scriptHash)
if err != nil {
str := fmt.Sprintf("failed to encrypt script hash %x",
scriptHash)
return nil, managerError(ErrCrypto, str, err)
}
// Encrypt the script for storage in database using the crypto script
// key when not a watching-only address manager.
var encryptedScript []byte
if !s.rootManager.WatchOnly() {
encryptedScript, err = s.rootManager.cryptoKeyScript.Encrypt(
script,
)
if err != nil {
str := fmt.Sprintf("failed to encrypt script for %x",
scriptHash)
return nil, managerError(ErrCrypto, str, err)
}
}
// The start block needs to be updated when the newly imported address
// is before the current one.
updateStartBlock := false
s.rootManager.mtx.Lock()
if bs.Height < s.rootManager.syncState.startBlock.Height {
updateStartBlock = true
}
s.rootManager.mtx.Unlock()
// Save the new imported address to the db and update start block (if
// needed) in a single transaction.
err = putScriptAddress(
ns, &s.scope, scriptHash, ImportedAddrAccount, ssNone,
encryptedHash, encryptedScript,
)
if err != nil {
return nil, maybeConvertDbError(err)
}
if updateStartBlock {
err := putStartBlock(ns, bs)
if err != nil {
return nil, maybeConvertDbError(err)
}
}
// Now that the database has been updated, update the start block in
// memory too if needed.
if updateStartBlock {
s.rootManager.mtx.Lock()
s.rootManager.syncState.startBlock = *bs
s.rootManager.mtx.Unlock()
}
// Create a new managed address based on the imported script. Also,
// when not a watching-only address manager, make a copy of the script
// since it will be cleared on lock and the script the caller passed
// should not be cleared out from under the caller.
scriptAddr, err := newScriptAddress(
s, ImportedAddrAccount, scriptHash, encryptedScript,
)
if err != nil {
return nil, err
}
if !s.rootManager.WatchOnly() {
scriptAddr.scriptCT = make([]byte, len(script))
copy(scriptAddr.scriptCT, script)
}
// Add the new managed address to the cache of recent addresses and
// return it.
s.addrs[addrKey(scriptHash)] = scriptAddr
return scriptAddr, nil
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"ImportScript",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"script",
"[",
"]",
"byte",
",",
"bs",
"*",
"BlockStamp",
")",
"(",
"ManagedScriptAddress",
",",
"error",
")",
"{",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"// The manager must be unlocked to encrypt the imported script.",
"if",
"s",
".",
"rootManager",
".",
"IsLocked",
"(",
")",
"&&",
"!",
"s",
".",
"rootManager",
".",
"WatchOnly",
"(",
")",
"{",
"return",
"nil",
",",
"managerError",
"(",
"ErrLocked",
",",
"errLocked",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"// Prevent duplicates.",
"scriptHash",
":=",
"btcutil",
".",
"Hash160",
"(",
"script",
")",
"\n",
"alreadyExists",
":=",
"s",
".",
"existsAddress",
"(",
"ns",
",",
"scriptHash",
")",
"\n",
"if",
"alreadyExists",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"scriptHash",
")",
"\n",
"return",
"nil",
",",
"managerError",
"(",
"ErrDuplicateAddress",
",",
"str",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"// Encrypt the script hash using the crypto public key so it is",
"// accessible when the address manager is locked or watching-only.",
"encryptedHash",
",",
"err",
":=",
"s",
".",
"rootManager",
".",
"cryptoKeyPub",
".",
"Encrypt",
"(",
"scriptHash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"scriptHash",
")",
"\n",
"return",
"nil",
",",
"managerError",
"(",
"ErrCrypto",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Encrypt the script for storage in database using the crypto script",
"// key when not a watching-only address manager.",
"var",
"encryptedScript",
"[",
"]",
"byte",
"\n",
"if",
"!",
"s",
".",
"rootManager",
".",
"WatchOnly",
"(",
")",
"{",
"encryptedScript",
",",
"err",
"=",
"s",
".",
"rootManager",
".",
"cryptoKeyScript",
".",
"Encrypt",
"(",
"script",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"scriptHash",
")",
"\n",
"return",
"nil",
",",
"managerError",
"(",
"ErrCrypto",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// The start block needs to be updated when the newly imported address",
"// is before the current one.",
"updateStartBlock",
":=",
"false",
"\n",
"s",
".",
"rootManager",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"if",
"bs",
".",
"Height",
"<",
"s",
".",
"rootManager",
".",
"syncState",
".",
"startBlock",
".",
"Height",
"{",
"updateStartBlock",
"=",
"true",
"\n",
"}",
"\n",
"s",
".",
"rootManager",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"// Save the new imported address to the db and update start block (if",
"// needed) in a single transaction.",
"err",
"=",
"putScriptAddress",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
",",
"scriptHash",
",",
"ImportedAddrAccount",
",",
"ssNone",
",",
"encryptedHash",
",",
"encryptedScript",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"maybeConvertDbError",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"updateStartBlock",
"{",
"err",
":=",
"putStartBlock",
"(",
"ns",
",",
"bs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"maybeConvertDbError",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Now that the database has been updated, update the start block in",
"// memory too if needed.",
"if",
"updateStartBlock",
"{",
"s",
".",
"rootManager",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"rootManager",
".",
"syncState",
".",
"startBlock",
"=",
"*",
"bs",
"\n",
"s",
".",
"rootManager",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n\n",
"// Create a new managed address based on the imported script. Also,",
"// when not a watching-only address manager, make a copy of the script",
"// since it will be cleared on lock and the script the caller passed",
"// should not be cleared out from under the caller.",
"scriptAddr",
",",
"err",
":=",
"newScriptAddress",
"(",
"s",
",",
"ImportedAddrAccount",
",",
"scriptHash",
",",
"encryptedScript",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"s",
".",
"rootManager",
".",
"WatchOnly",
"(",
")",
"{",
"scriptAddr",
".",
"scriptCT",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"script",
")",
")",
"\n",
"copy",
"(",
"scriptAddr",
".",
"scriptCT",
",",
"script",
")",
"\n",
"}",
"\n\n",
"// Add the new managed address to the cache of recent addresses and",
"// return it.",
"s",
".",
"addrs",
"[",
"addrKey",
"(",
"scriptHash",
")",
"]",
"=",
"scriptAddr",
"\n",
"return",
"scriptAddr",
",",
"nil",
"\n",
"}"
] | // ImportScript imports a user-provided script into the address manager. The
// imported script will act as a pay-to-script-hash address.
//
// All imported script addresses will be part of the account defined by the
// ImportedAddrAccount constant.
//
// When the address manager is watching-only, the script itself will not be
// stored or available since it is considered private data.
//
// This function will return an error if the address manager is locked and not
// watching-only, or the address already exists. Any other errors returned are
// generally unexpected. | [
"ImportScript",
"imports",
"a",
"user",
"-",
"provided",
"script",
"into",
"the",
"address",
"manager",
".",
"The",
"imported",
"script",
"will",
"act",
"as",
"a",
"pay",
"-",
"to",
"-",
"script",
"-",
"hash",
"address",
".",
"All",
"imported",
"script",
"addresses",
"will",
"be",
"part",
"of",
"the",
"account",
"defined",
"by",
"the",
"ImportedAddrAccount",
"constant",
".",
"When",
"the",
"address",
"manager",
"is",
"watching",
"-",
"only",
"the",
"script",
"itself",
"will",
"not",
"be",
"stored",
"or",
"available",
"since",
"it",
"is",
"considered",
"private",
"data",
".",
"This",
"function",
"will",
"return",
"an",
"error",
"if",
"the",
"address",
"manager",
"is",
"locked",
"and",
"not",
"watching",
"-",
"only",
"or",
"the",
"address",
"already",
"exists",
".",
"Any",
"other",
"errors",
"returned",
"are",
"generally",
"unexpected",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L1541-L1637 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | lookupAccount | func (s *ScopedKeyManager) lookupAccount(ns walletdb.ReadBucket, name string) (uint32, error) {
return fetchAccountByName(ns, &s.scope, name)
} | go | func (s *ScopedKeyManager) lookupAccount(ns walletdb.ReadBucket, name string) (uint32, error) {
return fetchAccountByName(ns, &s.scope, name)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"lookupAccount",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"name",
"string",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"return",
"fetchAccountByName",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
",",
"name",
")",
"\n",
"}"
] | // lookupAccount loads account number stored in the manager for the given
// account name
//
// This function MUST be called with the manager lock held for reads. | [
"lookupAccount",
"loads",
"account",
"number",
"stored",
"in",
"the",
"manager",
"for",
"the",
"given",
"account",
"name",
"This",
"function",
"MUST",
"be",
"called",
"with",
"the",
"manager",
"lock",
"held",
"for",
"reads",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L1643-L1645 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | LookupAccount | func (s *ScopedKeyManager) LookupAccount(ns walletdb.ReadBucket, name string) (uint32, error) {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.lookupAccount(ns, name)
} | go | func (s *ScopedKeyManager) LookupAccount(ns walletdb.ReadBucket, name string) (uint32, error) {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.lookupAccount(ns, name)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"LookupAccount",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"name",
"string",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"s",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"s",
".",
"lookupAccount",
"(",
"ns",
",",
"name",
")",
"\n",
"}"
] | // LookupAccount loads account number stored in the manager for the given
// account name | [
"LookupAccount",
"loads",
"account",
"number",
"stored",
"in",
"the",
"manager",
"for",
"the",
"given",
"account",
"name"
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L1649-L1654 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | fetchUsed | func (s *ScopedKeyManager) fetchUsed(ns walletdb.ReadBucket,
addressID []byte) bool {
return fetchAddressUsed(ns, &s.scope, addressID)
} | go | func (s *ScopedKeyManager) fetchUsed(ns walletdb.ReadBucket,
addressID []byte) bool {
return fetchAddressUsed(ns, &s.scope, addressID)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"fetchUsed",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"addressID",
"[",
"]",
"byte",
")",
"bool",
"{",
"return",
"fetchAddressUsed",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
",",
"addressID",
")",
"\n",
"}"
] | // fetchUsed returns true if the provided address id was flagged used. | [
"fetchUsed",
"returns",
"true",
"if",
"the",
"provided",
"address",
"id",
"was",
"flagged",
"used",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L1657-L1661 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | AccountName | func (s *ScopedKeyManager) AccountName(ns walletdb.ReadBucket, account uint32) (string, error) {
return fetchAccountName(ns, &s.scope, account)
} | go | func (s *ScopedKeyManager) AccountName(ns walletdb.ReadBucket, account uint32) (string, error) {
return fetchAccountName(ns, &s.scope, account)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"AccountName",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"account",
"uint32",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"fetchAccountName",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
",",
"account",
")",
"\n",
"}"
] | // AccountName returns the account name for the given account number stored in
// the manager. | [
"AccountName",
"returns",
"the",
"account",
"name",
"for",
"the",
"given",
"account",
"number",
"stored",
"in",
"the",
"manager",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L1690-L1692 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | ForEachAccount | func (s *ScopedKeyManager) ForEachAccount(ns walletdb.ReadBucket,
fn func(account uint32) error) error {
return forEachAccount(ns, &s.scope, fn)
} | go | func (s *ScopedKeyManager) ForEachAccount(ns walletdb.ReadBucket,
fn func(account uint32) error) error {
return forEachAccount(ns, &s.scope, fn)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"ForEachAccount",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"fn",
"func",
"(",
"account",
"uint32",
")",
"error",
")",
"error",
"{",
"return",
"forEachAccount",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
",",
"fn",
")",
"\n",
"}"
] | // 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/scoped_manager.go#L1696-L1700 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | LastAccount | func (s *ScopedKeyManager) LastAccount(ns walletdb.ReadBucket) (uint32, error) {
return fetchLastAccount(ns, &s.scope)
} | go | func (s *ScopedKeyManager) LastAccount(ns walletdb.ReadBucket) (uint32, error) {
return fetchLastAccount(ns, &s.scope)
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"LastAccount",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"return",
"fetchLastAccount",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
")",
"\n",
"}"
] | // LastAccount returns the last account stored in the manager. | [
"LastAccount",
"returns",
"the",
"last",
"account",
"stored",
"in",
"the",
"manager",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L1703-L1705 | train |
btcsuite/btcwallet | waddrmgr/scoped_manager.go | ForEachAccountAddress | func (s *ScopedKeyManager) ForEachAccountAddress(ns walletdb.ReadBucket,
account uint32, fn func(maddr ManagedAddress) error) error {
s.mtx.Lock()
defer s.mtx.Unlock()
addrFn := func(rowInterface interface{}) error {
managedAddr, err := s.rowInterfaceToManaged(ns, rowInterface)
if err != nil {
return err
}
return fn(managedAddr)
}
err := forEachAccountAddress(ns, &s.scope, account, addrFn)
if err != nil {
return maybeConvertDbError(err)
}
return nil
} | go | func (s *ScopedKeyManager) ForEachAccountAddress(ns walletdb.ReadBucket,
account uint32, fn func(maddr ManagedAddress) error) error {
s.mtx.Lock()
defer s.mtx.Unlock()
addrFn := func(rowInterface interface{}) error {
managedAddr, err := s.rowInterfaceToManaged(ns, rowInterface)
if err != nil {
return err
}
return fn(managedAddr)
}
err := forEachAccountAddress(ns, &s.scope, account, addrFn)
if err != nil {
return maybeConvertDbError(err)
}
return nil
} | [
"func",
"(",
"s",
"*",
"ScopedKeyManager",
")",
"ForEachAccountAddress",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"account",
"uint32",
",",
"fn",
"func",
"(",
"maddr",
"ManagedAddress",
")",
"error",
")",
"error",
"{",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"addrFn",
":=",
"func",
"(",
"rowInterface",
"interface",
"{",
"}",
")",
"error",
"{",
"managedAddr",
",",
"err",
":=",
"s",
".",
"rowInterfaceToManaged",
"(",
"ns",
",",
"rowInterface",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"fn",
"(",
"managedAddr",
")",
"\n",
"}",
"\n",
"err",
":=",
"forEachAccountAddress",
"(",
"ns",
",",
"&",
"s",
".",
"scope",
",",
"account",
",",
"addrFn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"maybeConvertDbError",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // ForEachAccountAddress calls the given function with each address of the
// given account stored in the manager, breaking early on error. | [
"ForEachAccountAddress",
"calls",
"the",
"given",
"function",
"with",
"each",
"address",
"of",
"the",
"given",
"account",
"stored",
"in",
"the",
"manager",
"breaking",
"early",
"on",
"error",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/scoped_manager.go#L1709-L1728 | train |
btcsuite/btcwallet | wtxmgr/tx.go | NewTxRecord | func NewTxRecord(serializedTx []byte, received time.Time) (*TxRecord, error) {
rec := &TxRecord{
Received: received,
SerializedTx: serializedTx,
}
err := rec.MsgTx.Deserialize(bytes.NewReader(serializedTx))
if err != nil {
str := "failed to deserialize transaction"
return nil, storeError(ErrInput, str, err)
}
copy(rec.Hash[:], chainhash.DoubleHashB(serializedTx))
return rec, nil
} | go | func NewTxRecord(serializedTx []byte, received time.Time) (*TxRecord, error) {
rec := &TxRecord{
Received: received,
SerializedTx: serializedTx,
}
err := rec.MsgTx.Deserialize(bytes.NewReader(serializedTx))
if err != nil {
str := "failed to deserialize transaction"
return nil, storeError(ErrInput, str, err)
}
copy(rec.Hash[:], chainhash.DoubleHashB(serializedTx))
return rec, nil
} | [
"func",
"NewTxRecord",
"(",
"serializedTx",
"[",
"]",
"byte",
",",
"received",
"time",
".",
"Time",
")",
"(",
"*",
"TxRecord",
",",
"error",
")",
"{",
"rec",
":=",
"&",
"TxRecord",
"{",
"Received",
":",
"received",
",",
"SerializedTx",
":",
"serializedTx",
",",
"}",
"\n",
"err",
":=",
"rec",
".",
"MsgTx",
".",
"Deserialize",
"(",
"bytes",
".",
"NewReader",
"(",
"serializedTx",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"nil",
",",
"storeError",
"(",
"ErrInput",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n",
"copy",
"(",
"rec",
".",
"Hash",
"[",
":",
"]",
",",
"chainhash",
".",
"DoubleHashB",
"(",
"serializedTx",
")",
")",
"\n",
"return",
"rec",
",",
"nil",
"\n",
"}"
] | // NewTxRecord creates a new transaction record that may be inserted into the
// store. It uses memoization to save the transaction hash and the serialized
// transaction. | [
"NewTxRecord",
"creates",
"a",
"new",
"transaction",
"record",
"that",
"may",
"be",
"inserted",
"into",
"the",
"store",
".",
"It",
"uses",
"memoization",
"to",
"save",
"the",
"transaction",
"hash",
"and",
"the",
"serialized",
"transaction",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/tx.go#L88-L100 | train |
btcsuite/btcwallet | wtxmgr/tx.go | NewTxRecordFromMsgTx | func NewTxRecordFromMsgTx(msgTx *wire.MsgTx, received time.Time) (*TxRecord, error) {
buf := bytes.NewBuffer(make([]byte, 0, msgTx.SerializeSize()))
err := msgTx.Serialize(buf)
if err != nil {
str := "failed to serialize transaction"
return nil, storeError(ErrInput, str, err)
}
rec := &TxRecord{
MsgTx: *msgTx,
Received: received,
SerializedTx: buf.Bytes(),
Hash: msgTx.TxHash(),
}
return rec, nil
} | go | func NewTxRecordFromMsgTx(msgTx *wire.MsgTx, received time.Time) (*TxRecord, error) {
buf := bytes.NewBuffer(make([]byte, 0, msgTx.SerializeSize()))
err := msgTx.Serialize(buf)
if err != nil {
str := "failed to serialize transaction"
return nil, storeError(ErrInput, str, err)
}
rec := &TxRecord{
MsgTx: *msgTx,
Received: received,
SerializedTx: buf.Bytes(),
Hash: msgTx.TxHash(),
}
return rec, nil
} | [
"func",
"NewTxRecordFromMsgTx",
"(",
"msgTx",
"*",
"wire",
".",
"MsgTx",
",",
"received",
"time",
".",
"Time",
")",
"(",
"*",
"TxRecord",
",",
"error",
")",
"{",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"msgTx",
".",
"SerializeSize",
"(",
")",
")",
")",
"\n",
"err",
":=",
"msgTx",
".",
"Serialize",
"(",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"nil",
",",
"storeError",
"(",
"ErrInput",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n",
"rec",
":=",
"&",
"TxRecord",
"{",
"MsgTx",
":",
"*",
"msgTx",
",",
"Received",
":",
"received",
",",
"SerializedTx",
":",
"buf",
".",
"Bytes",
"(",
")",
",",
"Hash",
":",
"msgTx",
".",
"TxHash",
"(",
")",
",",
"}",
"\n\n",
"return",
"rec",
",",
"nil",
"\n",
"}"
] | // NewTxRecordFromMsgTx creates a new transaction record that may be inserted
// into the store. | [
"NewTxRecordFromMsgTx",
"creates",
"a",
"new",
"transaction",
"record",
"that",
"may",
"be",
"inserted",
"into",
"the",
"store",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/tx.go#L104-L119 | train |
btcsuite/btcwallet | wtxmgr/tx.go | Open | func Open(ns walletdb.ReadBucket, chainParams *chaincfg.Params) (*Store, error) {
// Open the store.
err := openStore(ns)
if err != nil {
return nil, err
}
s := &Store{chainParams, nil} // TODO: set callbacks
return s, nil
} | go | func Open(ns walletdb.ReadBucket, chainParams *chaincfg.Params) (*Store, error) {
// Open the store.
err := openStore(ns)
if err != nil {
return nil, err
}
s := &Store{chainParams, nil} // TODO: set callbacks
return s, nil
} | [
"func",
"Open",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"chainParams",
"*",
"chaincfg",
".",
"Params",
")",
"(",
"*",
"Store",
",",
"error",
")",
"{",
"// Open the store.",
"err",
":=",
"openStore",
"(",
"ns",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"s",
":=",
"&",
"Store",
"{",
"chainParams",
",",
"nil",
"}",
"// TODO: set callbacks",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // Open opens the wallet transaction store from a walletdb namespace. If the
// store does not exist, ErrNoExist is returned. | [
"Open",
"opens",
"the",
"wallet",
"transaction",
"store",
"from",
"a",
"walletdb",
"namespace",
".",
"If",
"the",
"store",
"does",
"not",
"exist",
"ErrNoExist",
"is",
"returned",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/tx.go#L145-L153 | train |
btcsuite/btcwallet | wtxmgr/tx.go | updateMinedBalance | func (s *Store) updateMinedBalance(ns walletdb.ReadWriteBucket, rec *TxRecord,
block *BlockMeta) error {
// Fetch the mined balance in case we need to update it.
minedBalance, err := fetchMinedBalance(ns)
if err != nil {
return err
}
// Add a debit record for each unspent credit spent by this transaction.
// The index is set in each iteration below.
spender := indexedIncidence{
incidence: incidence{
txHash: rec.Hash,
block: block.Block,
},
}
newMinedBalance := minedBalance
for i, input := range rec.MsgTx.TxIn {
unspentKey, credKey := existsUnspent(ns, &input.PreviousOutPoint)
if credKey == nil {
// Debits for unmined transactions are not explicitly
// tracked. Instead, all previous outputs spent by any
// unmined transaction are added to a map for quick
// lookups when it must be checked whether a mined
// output is unspent or not.
//
// Tracking individual debits for unmined transactions
// could be added later to simplify (and increase
// performance of) determining some details that need
// the previous outputs (e.g. determining a fee), but at
// the moment that is not done (and a db lookup is used
// for those cases instead). There is also a good
// chance that all unmined transaction handling will
// move entirely to the db rather than being handled in
// memory for atomicity reasons, so the simplist
// implementation is currently used.
continue
}
// If this output is relevant to us, we'll mark the it as spent
// and remove its amount from the store.
spender.index = uint32(i)
amt, err := spendCredit(ns, credKey, &spender)
if err != nil {
return err
}
err = putDebit(
ns, &rec.Hash, uint32(i), amt, &block.Block, credKey,
)
if err != nil {
return err
}
if err := deleteRawUnspent(ns, unspentKey); err != nil {
return err
}
newMinedBalance -= amt
}
// For each output of the record that is marked as a credit, if the
// output is marked as a credit by the unconfirmed store, remove the
// marker and mark the output as a credit in the db.
//
// Moved credits are added as unspents, even if there is another
// unconfirmed transaction which spends them.
cred := credit{
outPoint: wire.OutPoint{Hash: rec.Hash},
block: block.Block,
spentBy: indexedIncidence{index: ^uint32(0)},
}
it := makeUnminedCreditIterator(ns, &rec.Hash)
for it.next() {
// TODO: This should use the raw apis. The credit value (it.cv)
// can be moved from unmined directly to the credits bucket.
// The key needs a modification to include the block
// height/hash.
index, err := fetchRawUnminedCreditIndex(it.ck)
if err != nil {
return err
}
amount, change, err := fetchRawUnminedCreditAmountChange(it.cv)
if err != nil {
return err
}
cred.outPoint.Index = index
cred.amount = amount
cred.change = change
if err := putUnspentCredit(ns, &cred); err != nil {
return err
}
err = putUnspent(ns, &cred.outPoint, &block.Block)
if err != nil {
return err
}
newMinedBalance += amount
}
if it.err != nil {
return it.err
}
// Update the balance if it has changed.
if newMinedBalance != minedBalance {
return putMinedBalance(ns, newMinedBalance)
}
return nil
} | go | func (s *Store) updateMinedBalance(ns walletdb.ReadWriteBucket, rec *TxRecord,
block *BlockMeta) error {
// Fetch the mined balance in case we need to update it.
minedBalance, err := fetchMinedBalance(ns)
if err != nil {
return err
}
// Add a debit record for each unspent credit spent by this transaction.
// The index is set in each iteration below.
spender := indexedIncidence{
incidence: incidence{
txHash: rec.Hash,
block: block.Block,
},
}
newMinedBalance := minedBalance
for i, input := range rec.MsgTx.TxIn {
unspentKey, credKey := existsUnspent(ns, &input.PreviousOutPoint)
if credKey == nil {
// Debits for unmined transactions are not explicitly
// tracked. Instead, all previous outputs spent by any
// unmined transaction are added to a map for quick
// lookups when it must be checked whether a mined
// output is unspent or not.
//
// Tracking individual debits for unmined transactions
// could be added later to simplify (and increase
// performance of) determining some details that need
// the previous outputs (e.g. determining a fee), but at
// the moment that is not done (and a db lookup is used
// for those cases instead). There is also a good
// chance that all unmined transaction handling will
// move entirely to the db rather than being handled in
// memory for atomicity reasons, so the simplist
// implementation is currently used.
continue
}
// If this output is relevant to us, we'll mark the it as spent
// and remove its amount from the store.
spender.index = uint32(i)
amt, err := spendCredit(ns, credKey, &spender)
if err != nil {
return err
}
err = putDebit(
ns, &rec.Hash, uint32(i), amt, &block.Block, credKey,
)
if err != nil {
return err
}
if err := deleteRawUnspent(ns, unspentKey); err != nil {
return err
}
newMinedBalance -= amt
}
// For each output of the record that is marked as a credit, if the
// output is marked as a credit by the unconfirmed store, remove the
// marker and mark the output as a credit in the db.
//
// Moved credits are added as unspents, even if there is another
// unconfirmed transaction which spends them.
cred := credit{
outPoint: wire.OutPoint{Hash: rec.Hash},
block: block.Block,
spentBy: indexedIncidence{index: ^uint32(0)},
}
it := makeUnminedCreditIterator(ns, &rec.Hash)
for it.next() {
// TODO: This should use the raw apis. The credit value (it.cv)
// can be moved from unmined directly to the credits bucket.
// The key needs a modification to include the block
// height/hash.
index, err := fetchRawUnminedCreditIndex(it.ck)
if err != nil {
return err
}
amount, change, err := fetchRawUnminedCreditAmountChange(it.cv)
if err != nil {
return err
}
cred.outPoint.Index = index
cred.amount = amount
cred.change = change
if err := putUnspentCredit(ns, &cred); err != nil {
return err
}
err = putUnspent(ns, &cred.outPoint, &block.Block)
if err != nil {
return err
}
newMinedBalance += amount
}
if it.err != nil {
return it.err
}
// Update the balance if it has changed.
if newMinedBalance != minedBalance {
return putMinedBalance(ns, newMinedBalance)
}
return nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"updateMinedBalance",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"rec",
"*",
"TxRecord",
",",
"block",
"*",
"BlockMeta",
")",
"error",
"{",
"// Fetch the mined balance in case we need to update it.",
"minedBalance",
",",
"err",
":=",
"fetchMinedBalance",
"(",
"ns",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Add a debit record for each unspent credit spent by this transaction.",
"// The index is set in each iteration below.",
"spender",
":=",
"indexedIncidence",
"{",
"incidence",
":",
"incidence",
"{",
"txHash",
":",
"rec",
".",
"Hash",
",",
"block",
":",
"block",
".",
"Block",
",",
"}",
",",
"}",
"\n\n",
"newMinedBalance",
":=",
"minedBalance",
"\n",
"for",
"i",
",",
"input",
":=",
"range",
"rec",
".",
"MsgTx",
".",
"TxIn",
"{",
"unspentKey",
",",
"credKey",
":=",
"existsUnspent",
"(",
"ns",
",",
"&",
"input",
".",
"PreviousOutPoint",
")",
"\n",
"if",
"credKey",
"==",
"nil",
"{",
"// Debits for unmined transactions are not explicitly",
"// tracked. Instead, all previous outputs spent by any",
"// unmined transaction are added to a map for quick",
"// lookups when it must be checked whether a mined",
"// output is unspent or not.",
"//",
"// Tracking individual debits for unmined transactions",
"// could be added later to simplify (and increase",
"// performance of) determining some details that need",
"// the previous outputs (e.g. determining a fee), but at",
"// the moment that is not done (and a db lookup is used",
"// for those cases instead). There is also a good",
"// chance that all unmined transaction handling will",
"// move entirely to the db rather than being handled in",
"// memory for atomicity reasons, so the simplist",
"// implementation is currently used.",
"continue",
"\n",
"}",
"\n\n",
"// If this output is relevant to us, we'll mark the it as spent",
"// and remove its amount from the store.",
"spender",
".",
"index",
"=",
"uint32",
"(",
"i",
")",
"\n",
"amt",
",",
"err",
":=",
"spendCredit",
"(",
"ns",
",",
"credKey",
",",
"&",
"spender",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"putDebit",
"(",
"ns",
",",
"&",
"rec",
".",
"Hash",
",",
"uint32",
"(",
"i",
")",
",",
"amt",
",",
"&",
"block",
".",
"Block",
",",
"credKey",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"deleteRawUnspent",
"(",
"ns",
",",
"unspentKey",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"newMinedBalance",
"-=",
"amt",
"\n",
"}",
"\n\n",
"// For each output of the record that is marked as a credit, if the",
"// output is marked as a credit by the unconfirmed store, remove the",
"// marker and mark the output as a credit in the db.",
"//",
"// Moved credits are added as unspents, even if there is another",
"// unconfirmed transaction which spends them.",
"cred",
":=",
"credit",
"{",
"outPoint",
":",
"wire",
".",
"OutPoint",
"{",
"Hash",
":",
"rec",
".",
"Hash",
"}",
",",
"block",
":",
"block",
".",
"Block",
",",
"spentBy",
":",
"indexedIncidence",
"{",
"index",
":",
"^",
"uint32",
"(",
"0",
")",
"}",
",",
"}",
"\n\n",
"it",
":=",
"makeUnminedCreditIterator",
"(",
"ns",
",",
"&",
"rec",
".",
"Hash",
")",
"\n",
"for",
"it",
".",
"next",
"(",
")",
"{",
"// TODO: This should use the raw apis. The credit value (it.cv)",
"// can be moved from unmined directly to the credits bucket.",
"// The key needs a modification to include the block",
"// height/hash.",
"index",
",",
"err",
":=",
"fetchRawUnminedCreditIndex",
"(",
"it",
".",
"ck",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"amount",
",",
"change",
",",
"err",
":=",
"fetchRawUnminedCreditAmountChange",
"(",
"it",
".",
"cv",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"cred",
".",
"outPoint",
".",
"Index",
"=",
"index",
"\n",
"cred",
".",
"amount",
"=",
"amount",
"\n",
"cred",
".",
"change",
"=",
"change",
"\n\n",
"if",
"err",
":=",
"putUnspentCredit",
"(",
"ns",
",",
"&",
"cred",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"putUnspent",
"(",
"ns",
",",
"&",
"cred",
".",
"outPoint",
",",
"&",
"block",
".",
"Block",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"newMinedBalance",
"+=",
"amount",
"\n",
"}",
"\n",
"if",
"it",
".",
"err",
"!=",
"nil",
"{",
"return",
"it",
".",
"err",
"\n",
"}",
"\n\n",
"// Update the balance if it has changed.",
"if",
"newMinedBalance",
"!=",
"minedBalance",
"{",
"return",
"putMinedBalance",
"(",
"ns",
",",
"newMinedBalance",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // updateMinedBalance updates the mined balance within the store, if changed,
// after processing the given transaction record. | [
"updateMinedBalance",
"updates",
"the",
"mined",
"balance",
"within",
"the",
"store",
"if",
"changed",
"after",
"processing",
"the",
"given",
"transaction",
"record",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/tx.go#L164-L276 | train |
btcsuite/btcwallet | wtxmgr/tx.go | InsertTx | func (s *Store) InsertTx(ns walletdb.ReadWriteBucket, rec *TxRecord, block *BlockMeta) error {
if block == nil {
return s.insertMemPoolTx(ns, rec)
}
return s.insertMinedTx(ns, rec, block)
} | go | func (s *Store) InsertTx(ns walletdb.ReadWriteBucket, rec *TxRecord, block *BlockMeta) error {
if block == nil {
return s.insertMemPoolTx(ns, rec)
}
return s.insertMinedTx(ns, rec, block)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"InsertTx",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"rec",
"*",
"TxRecord",
",",
"block",
"*",
"BlockMeta",
")",
"error",
"{",
"if",
"block",
"==",
"nil",
"{",
"return",
"s",
".",
"insertMemPoolTx",
"(",
"ns",
",",
"rec",
")",
"\n",
"}",
"\n",
"return",
"s",
".",
"insertMinedTx",
"(",
"ns",
",",
"rec",
",",
"block",
")",
"\n",
"}"
] | // InsertTx records a transaction as belonging to a wallet's transaction
// history. If block is nil, the transaction is considered unspent, and the
// transaction's index must be unset. | [
"InsertTx",
"records",
"a",
"transaction",
"as",
"belonging",
"to",
"a",
"wallet",
"s",
"transaction",
"history",
".",
"If",
"block",
"is",
"nil",
"the",
"transaction",
"is",
"considered",
"unspent",
"and",
"the",
"transaction",
"s",
"index",
"must",
"be",
"unset",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/tx.go#L295-L300 | train |
btcsuite/btcwallet | wtxmgr/tx.go | RemoveUnminedTx | func (s *Store) RemoveUnminedTx(ns walletdb.ReadWriteBucket, rec *TxRecord) error {
// As we already have a tx record, we can directly call the
// removeConflict method. This will do the job of recursively removing
// this unmined transaction, and any transactions that depend on it.
return s.removeConflict(ns, rec)
} | go | func (s *Store) RemoveUnminedTx(ns walletdb.ReadWriteBucket, rec *TxRecord) error {
// As we already have a tx record, we can directly call the
// removeConflict method. This will do the job of recursively removing
// this unmined transaction, and any transactions that depend on it.
return s.removeConflict(ns, rec)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"RemoveUnminedTx",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"rec",
"*",
"TxRecord",
")",
"error",
"{",
"// As we already have a tx record, we can directly call the",
"// removeConflict method. This will do the job of recursively removing",
"// this unmined transaction, and any transactions that depend on it.",
"return",
"s",
".",
"removeConflict",
"(",
"ns",
",",
"rec",
")",
"\n",
"}"
] | // RemoveUnminedTx attempts to remove an unmined transaction from the
// transaction store. This is to be used in the scenario that a transaction
// that we attempt to rebroadcast, turns out to double spend one of our
// existing inputs. This function we remove the conflicting transaction
// identified by the tx record, and also recursively remove all transactions
// that depend on it. | [
"RemoveUnminedTx",
"attempts",
"to",
"remove",
"an",
"unmined",
"transaction",
"from",
"the",
"transaction",
"store",
".",
"This",
"is",
"to",
"be",
"used",
"in",
"the",
"scenario",
"that",
"a",
"transaction",
"that",
"we",
"attempt",
"to",
"rebroadcast",
"turns",
"out",
"to",
"double",
"spend",
"one",
"of",
"our",
"existing",
"inputs",
".",
"This",
"function",
"we",
"remove",
"the",
"conflicting",
"transaction",
"identified",
"by",
"the",
"tx",
"record",
"and",
"also",
"recursively",
"remove",
"all",
"transactions",
"that",
"depend",
"on",
"it",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/tx.go#L308-L313 | train |
btcsuite/btcwallet | wtxmgr/tx.go | insertMinedTx | func (s *Store) insertMinedTx(ns walletdb.ReadWriteBucket, rec *TxRecord,
block *BlockMeta) error {
// If a transaction record for this hash and block already exists, we
// can exit early.
if _, v := existsTxRecord(ns, &rec.Hash, &block.Block); v != nil {
return nil
}
// If a block record does not yet exist for any transactions from this
// block, insert a block record first. Otherwise, update it by adding
// the transaction hash to the set of transactions from this block.
var err error
blockKey, blockValue := existsBlockRecord(ns, block.Height)
if blockValue == nil {
err = putBlockRecord(ns, block, &rec.Hash)
} else {
blockValue, err = appendRawBlockRecord(blockValue, &rec.Hash)
if err != nil {
return err
}
err = putRawBlockRecord(ns, blockKey, blockValue)
}
if err != nil {
return err
}
if err := putTxRecord(ns, rec, &block.Block); err != nil {
return err
}
// Determine if this transaction has affected our balance, and if so,
// update it.
if err := s.updateMinedBalance(ns, rec, block); err != nil {
return err
}
// If this transaction previously existed within the store as unmined,
// we'll need to remove it from the unmined bucket.
if v := existsRawUnmined(ns, rec.Hash[:]); v != nil {
log.Infof("Marking unconfirmed transaction %v mined in block %d",
&rec.Hash, block.Height)
if err := s.deleteUnminedTx(ns, rec); err != nil {
return err
}
}
// As there may be unconfirmed transactions that are invalidated by this
// transaction (either being duplicates, or double spends), remove them
// from the unconfirmed set. This also handles removing unconfirmed
// transaction spend chains if any other unconfirmed transactions spend
// outputs of the removed double spend.
return s.removeDoubleSpends(ns, rec)
} | go | func (s *Store) insertMinedTx(ns walletdb.ReadWriteBucket, rec *TxRecord,
block *BlockMeta) error {
// If a transaction record for this hash and block already exists, we
// can exit early.
if _, v := existsTxRecord(ns, &rec.Hash, &block.Block); v != nil {
return nil
}
// If a block record does not yet exist for any transactions from this
// block, insert a block record first. Otherwise, update it by adding
// the transaction hash to the set of transactions from this block.
var err error
blockKey, blockValue := existsBlockRecord(ns, block.Height)
if blockValue == nil {
err = putBlockRecord(ns, block, &rec.Hash)
} else {
blockValue, err = appendRawBlockRecord(blockValue, &rec.Hash)
if err != nil {
return err
}
err = putRawBlockRecord(ns, blockKey, blockValue)
}
if err != nil {
return err
}
if err := putTxRecord(ns, rec, &block.Block); err != nil {
return err
}
// Determine if this transaction has affected our balance, and if so,
// update it.
if err := s.updateMinedBalance(ns, rec, block); err != nil {
return err
}
// If this transaction previously existed within the store as unmined,
// we'll need to remove it from the unmined bucket.
if v := existsRawUnmined(ns, rec.Hash[:]); v != nil {
log.Infof("Marking unconfirmed transaction %v mined in block %d",
&rec.Hash, block.Height)
if err := s.deleteUnminedTx(ns, rec); err != nil {
return err
}
}
// As there may be unconfirmed transactions that are invalidated by this
// transaction (either being duplicates, or double spends), remove them
// from the unconfirmed set. This also handles removing unconfirmed
// transaction spend chains if any other unconfirmed transactions spend
// outputs of the removed double spend.
return s.removeDoubleSpends(ns, rec)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"insertMinedTx",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"rec",
"*",
"TxRecord",
",",
"block",
"*",
"BlockMeta",
")",
"error",
"{",
"// If a transaction record for this hash and block already exists, we",
"// can exit early.",
"if",
"_",
",",
"v",
":=",
"existsTxRecord",
"(",
"ns",
",",
"&",
"rec",
".",
"Hash",
",",
"&",
"block",
".",
"Block",
")",
";",
"v",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// If a block record does not yet exist for any transactions from this",
"// block, insert a block record first. Otherwise, update it by adding",
"// the transaction hash to the set of transactions from this block.",
"var",
"err",
"error",
"\n",
"blockKey",
",",
"blockValue",
":=",
"existsBlockRecord",
"(",
"ns",
",",
"block",
".",
"Height",
")",
"\n",
"if",
"blockValue",
"==",
"nil",
"{",
"err",
"=",
"putBlockRecord",
"(",
"ns",
",",
"block",
",",
"&",
"rec",
".",
"Hash",
")",
"\n",
"}",
"else",
"{",
"blockValue",
",",
"err",
"=",
"appendRawBlockRecord",
"(",
"blockValue",
",",
"&",
"rec",
".",
"Hash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"putRawBlockRecord",
"(",
"ns",
",",
"blockKey",
",",
"blockValue",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"putTxRecord",
"(",
"ns",
",",
"rec",
",",
"&",
"block",
".",
"Block",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Determine if this transaction has affected our balance, and if so,",
"// update it.",
"if",
"err",
":=",
"s",
".",
"updateMinedBalance",
"(",
"ns",
",",
"rec",
",",
"block",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// If this transaction previously existed within the store as unmined,",
"// we'll need to remove it from the unmined bucket.",
"if",
"v",
":=",
"existsRawUnmined",
"(",
"ns",
",",
"rec",
".",
"Hash",
"[",
":",
"]",
")",
";",
"v",
"!=",
"nil",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"&",
"rec",
".",
"Hash",
",",
"block",
".",
"Height",
")",
"\n\n",
"if",
"err",
":=",
"s",
".",
"deleteUnminedTx",
"(",
"ns",
",",
"rec",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// As there may be unconfirmed transactions that are invalidated by this",
"// transaction (either being duplicates, or double spends), remove them",
"// from the unconfirmed set. This also handles removing unconfirmed",
"// transaction spend chains if any other unconfirmed transactions spend",
"// outputs of the removed double spend.",
"return",
"s",
".",
"removeDoubleSpends",
"(",
"ns",
",",
"rec",
")",
"\n",
"}"
] | // insertMinedTx inserts a new transaction record for a mined transaction into
// the database under the confirmed bucket. It guarantees that, if the
// tranasction was previously unconfirmed, then it will take care of cleaning up
// the unconfirmed state. All other unconfirmed double spend attempts will be
// removed as well. | [
"insertMinedTx",
"inserts",
"a",
"new",
"transaction",
"record",
"for",
"a",
"mined",
"transaction",
"into",
"the",
"database",
"under",
"the",
"confirmed",
"bucket",
".",
"It",
"guarantees",
"that",
"if",
"the",
"tranasction",
"was",
"previously",
"unconfirmed",
"then",
"it",
"will",
"take",
"care",
"of",
"cleaning",
"up",
"the",
"unconfirmed",
"state",
".",
"All",
"other",
"unconfirmed",
"double",
"spend",
"attempts",
"will",
"be",
"removed",
"as",
"well",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/tx.go#L320-L373 | train |
btcsuite/btcwallet | wtxmgr/tx.go | Rollback | func (s *Store) Rollback(ns walletdb.ReadWriteBucket, height int32) error {
return s.rollback(ns, height)
} | go | func (s *Store) Rollback(ns walletdb.ReadWriteBucket, height int32) error {
return s.rollback(ns, height)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Rollback",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"height",
"int32",
")",
"error",
"{",
"return",
"s",
".",
"rollback",
"(",
"ns",
",",
"height",
")",
"\n",
"}"
] | // Rollback removes all blocks at height onwards, moving any transactions within
// each block to the unconfirmed pool. | [
"Rollback",
"removes",
"all",
"blocks",
"at",
"height",
"onwards",
"moving",
"any",
"transactions",
"within",
"each",
"block",
"to",
"the",
"unconfirmed",
"pool",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/tx.go#L453-L455 | train |
btcsuite/btcwallet | internal/zero/slice.go | BigInt | func BigInt(x *big.Int) {
b := x.Bits()
for i := range b {
b[i] = 0
}
x.SetInt64(0)
} | go | func BigInt(x *big.Int) {
b := x.Bits()
for i := range b {
b[i] = 0
}
x.SetInt64(0)
} | [
"func",
"BigInt",
"(",
"x",
"*",
"big",
".",
"Int",
")",
"{",
"b",
":=",
"x",
".",
"Bits",
"(",
")",
"\n",
"for",
"i",
":=",
"range",
"b",
"{",
"b",
"[",
"i",
"]",
"=",
"0",
"\n",
"}",
"\n",
"x",
".",
"SetInt64",
"(",
"0",
")",
"\n",
"}"
] | // BigInt sets all bytes in the passed big int to zero and then sets the
// value to 0. This differs from simply setting the value in that it
// specifically clears the underlying bytes whereas simply setting the value
// does not. This is mostly useful to forcefully clear private keys. | [
"BigInt",
"sets",
"all",
"bytes",
"in",
"the",
"passed",
"big",
"int",
"to",
"zero",
"and",
"then",
"sets",
"the",
"value",
"to",
"0",
".",
"This",
"differs",
"from",
"simply",
"setting",
"the",
"value",
"in",
"that",
"it",
"specifically",
"clears",
"the",
"underlying",
"bytes",
"whereas",
"simply",
"setting",
"the",
"value",
"does",
"not",
".",
"This",
"is",
"mostly",
"useful",
"to",
"forcefully",
"clear",
"private",
"keys",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/zero/slice.go#L28-L34 | train |
btcsuite/btcwallet | rpc/rpcserver/log.go | stripGrpcPrefixArgs | func stripGrpcPrefixArgs(args ...interface{}) []interface{} {
if len(args) == 0 {
return args
}
firstArgStr, ok := args[0].(string)
if ok {
args[0] = stripGrpcPrefix(firstArgStr)
}
return args
} | go | func stripGrpcPrefixArgs(args ...interface{}) []interface{} {
if len(args) == 0 {
return args
}
firstArgStr, ok := args[0].(string)
if ok {
args[0] = stripGrpcPrefix(firstArgStr)
}
return args
} | [
"func",
"stripGrpcPrefixArgs",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"if",
"len",
"(",
"args",
")",
"==",
"0",
"{",
"return",
"args",
"\n",
"}",
"\n",
"firstArgStr",
",",
"ok",
":=",
"args",
"[",
"0",
"]",
".",
"(",
"string",
")",
"\n",
"if",
"ok",
"{",
"args",
"[",
"0",
"]",
"=",
"stripGrpcPrefix",
"(",
"firstArgStr",
")",
"\n",
"}",
"\n",
"return",
"args",
"\n",
"}"
] | // stripGrpcPrefixArgs removes the package prefix from the first argument, if it
// exists and is a string, returning the same arg slice after reassigning the
// first arg. | [
"stripGrpcPrefixArgs",
"removes",
"the",
"package",
"prefix",
"from",
"the",
"first",
"argument",
"if",
"it",
"exists",
"and",
"is",
"a",
"string",
"returning",
"the",
"same",
"arg",
"slice",
"after",
"reassigning",
"the",
"first",
"arg",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/rpcserver/log.go#L45-L54 | train |
btcsuite/btcwallet | internal/cfgutil/amount.go | UnmarshalFlag | func (a *AmountFlag) UnmarshalFlag(value string) error {
value = strings.TrimSuffix(value, " BTC")
valueF64, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
}
amount, err := btcutil.NewAmount(valueF64)
if err != nil {
return err
}
a.Amount = amount
return nil
} | go | func (a *AmountFlag) UnmarshalFlag(value string) error {
value = strings.TrimSuffix(value, " BTC")
valueF64, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
}
amount, err := btcutil.NewAmount(valueF64)
if err != nil {
return err
}
a.Amount = amount
return nil
} | [
"func",
"(",
"a",
"*",
"AmountFlag",
")",
"UnmarshalFlag",
"(",
"value",
"string",
")",
"error",
"{",
"value",
"=",
"strings",
".",
"TrimSuffix",
"(",
"value",
",",
"\"",
"\"",
")",
"\n",
"valueF64",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"value",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"amount",
",",
"err",
":=",
"btcutil",
".",
"NewAmount",
"(",
"valueF64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"a",
".",
"Amount",
"=",
"amount",
"\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalFlag satisifes the flags.Unmarshaler interface. | [
"UnmarshalFlag",
"satisifes",
"the",
"flags",
".",
"Unmarshaler",
"interface",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/cfgutil/amount.go#L31-L43 | train |
btcsuite/btcwallet | wtxmgr/unconfirmed.go | insertMemPoolTx | func (s *Store) insertMemPoolTx(ns walletdb.ReadWriteBucket, rec *TxRecord) error {
// Check whether the transaction has already been added to the
// unconfirmed bucket.
if existsRawUnmined(ns, rec.Hash[:]) != nil {
// TODO: compare serialized txs to ensure this isn't a hash
// collision?
return nil
}
// Since transaction records within the store are keyed by their
// transaction _and_ block confirmation, we'll iterate through the
// transaction's outputs to determine if we've already seen them to
// prevent from adding this transaction to the unconfirmed bucket.
for i := range rec.MsgTx.TxOut {
k := canonicalOutPoint(&rec.Hash, uint32(i))
if existsRawUnspent(ns, k) != nil {
return nil
}
}
log.Infof("Inserting unconfirmed transaction %v", rec.Hash)
v, err := valueTxRecord(rec)
if err != nil {
return err
}
err = putRawUnmined(ns, rec.Hash[:], v)
if err != nil {
return err
}
for _, input := range rec.MsgTx.TxIn {
prevOut := &input.PreviousOutPoint
k := canonicalOutPoint(&prevOut.Hash, prevOut.Index)
err = putRawUnminedInput(ns, k, rec.Hash[:])
if err != nil {
return err
}
}
// TODO: increment credit amount for each credit (but those are unknown
// here currently).
return nil
} | go | func (s *Store) insertMemPoolTx(ns walletdb.ReadWriteBucket, rec *TxRecord) error {
// Check whether the transaction has already been added to the
// unconfirmed bucket.
if existsRawUnmined(ns, rec.Hash[:]) != nil {
// TODO: compare serialized txs to ensure this isn't a hash
// collision?
return nil
}
// Since transaction records within the store are keyed by their
// transaction _and_ block confirmation, we'll iterate through the
// transaction's outputs to determine if we've already seen them to
// prevent from adding this transaction to the unconfirmed bucket.
for i := range rec.MsgTx.TxOut {
k := canonicalOutPoint(&rec.Hash, uint32(i))
if existsRawUnspent(ns, k) != nil {
return nil
}
}
log.Infof("Inserting unconfirmed transaction %v", rec.Hash)
v, err := valueTxRecord(rec)
if err != nil {
return err
}
err = putRawUnmined(ns, rec.Hash[:], v)
if err != nil {
return err
}
for _, input := range rec.MsgTx.TxIn {
prevOut := &input.PreviousOutPoint
k := canonicalOutPoint(&prevOut.Hash, prevOut.Index)
err = putRawUnminedInput(ns, k, rec.Hash[:])
if err != nil {
return err
}
}
// TODO: increment credit amount for each credit (but those are unknown
// here currently).
return nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"insertMemPoolTx",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"rec",
"*",
"TxRecord",
")",
"error",
"{",
"// Check whether the transaction has already been added to the",
"// unconfirmed bucket.",
"if",
"existsRawUnmined",
"(",
"ns",
",",
"rec",
".",
"Hash",
"[",
":",
"]",
")",
"!=",
"nil",
"{",
"// TODO: compare serialized txs to ensure this isn't a hash",
"// collision?",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Since transaction records within the store are keyed by their",
"// transaction _and_ block confirmation, we'll iterate through the",
"// transaction's outputs to determine if we've already seen them to",
"// prevent from adding this transaction to the unconfirmed bucket.",
"for",
"i",
":=",
"range",
"rec",
".",
"MsgTx",
".",
"TxOut",
"{",
"k",
":=",
"canonicalOutPoint",
"(",
"&",
"rec",
".",
"Hash",
",",
"uint32",
"(",
"i",
")",
")",
"\n",
"if",
"existsRawUnspent",
"(",
"ns",
",",
"k",
")",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"rec",
".",
"Hash",
")",
"\n",
"v",
",",
"err",
":=",
"valueTxRecord",
"(",
"rec",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"putRawUnmined",
"(",
"ns",
",",
"rec",
".",
"Hash",
"[",
":",
"]",
",",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"input",
":=",
"range",
"rec",
".",
"MsgTx",
".",
"TxIn",
"{",
"prevOut",
":=",
"&",
"input",
".",
"PreviousOutPoint",
"\n",
"k",
":=",
"canonicalOutPoint",
"(",
"&",
"prevOut",
".",
"Hash",
",",
"prevOut",
".",
"Index",
")",
"\n",
"err",
"=",
"putRawUnminedInput",
"(",
"ns",
",",
"k",
",",
"rec",
".",
"Hash",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// TODO: increment credit amount for each credit (but those are unknown",
"// here currently).",
"return",
"nil",
"\n",
"}"
] | // insertMemPoolTx inserts the unmined transaction record. It also marks
// previous outputs referenced by the inputs as spent. | [
"insertMemPoolTx",
"inserts",
"the",
"unmined",
"transaction",
"record",
".",
"It",
"also",
"marks",
"previous",
"outputs",
"referenced",
"by",
"the",
"inputs",
"as",
"spent",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/unconfirmed.go#L16-L59 | train |
btcsuite/btcwallet | wtxmgr/unconfirmed.go | removeConflict | func (s *Store) removeConflict(ns walletdb.ReadWriteBucket, rec *TxRecord) error {
// For each potential credit for this record, each spender (if any) must
// be recursively removed as well. Once the spenders are removed, the
// credit is deleted.
for i := range rec.MsgTx.TxOut {
k := canonicalOutPoint(&rec.Hash, uint32(i))
spenderHashes := fetchUnminedInputSpendTxHashes(ns, k)
for _, spenderHash := range spenderHashes {
// If the spending transaction spends multiple outputs
// from the same transaction, we'll find duplicate
// entries within the store, so it's possible we're
// unable to find it if the conflicts have already been
// removed in a previous iteration.
spenderVal := existsRawUnmined(ns, spenderHash[:])
if spenderVal == nil {
continue
}
var spender TxRecord
spender.Hash = spenderHash
err := readRawTxRecord(&spender.Hash, spenderVal, &spender)
if err != nil {
return err
}
log.Debugf("Transaction %v is part of a removed conflict "+
"chain -- removing as well", spender.Hash)
if err := s.removeConflict(ns, &spender); err != nil {
return err
}
}
if err := deleteRawUnminedCredit(ns, k); err != nil {
return err
}
}
// If this tx spends any previous credits (either mined or unmined), set
// each unspent. Mined transactions are only marked spent by having the
// output in the unmined inputs bucket.
for _, input := range rec.MsgTx.TxIn {
prevOut := &input.PreviousOutPoint
k := canonicalOutPoint(&prevOut.Hash, prevOut.Index)
err := deleteRawUnminedInput(ns, k, rec.Hash)
if err != nil {
return err
}
}
return deleteRawUnmined(ns, rec.Hash[:])
} | go | func (s *Store) removeConflict(ns walletdb.ReadWriteBucket, rec *TxRecord) error {
// For each potential credit for this record, each spender (if any) must
// be recursively removed as well. Once the spenders are removed, the
// credit is deleted.
for i := range rec.MsgTx.TxOut {
k := canonicalOutPoint(&rec.Hash, uint32(i))
spenderHashes := fetchUnminedInputSpendTxHashes(ns, k)
for _, spenderHash := range spenderHashes {
// If the spending transaction spends multiple outputs
// from the same transaction, we'll find duplicate
// entries within the store, so it's possible we're
// unable to find it if the conflicts have already been
// removed in a previous iteration.
spenderVal := existsRawUnmined(ns, spenderHash[:])
if spenderVal == nil {
continue
}
var spender TxRecord
spender.Hash = spenderHash
err := readRawTxRecord(&spender.Hash, spenderVal, &spender)
if err != nil {
return err
}
log.Debugf("Transaction %v is part of a removed conflict "+
"chain -- removing as well", spender.Hash)
if err := s.removeConflict(ns, &spender); err != nil {
return err
}
}
if err := deleteRawUnminedCredit(ns, k); err != nil {
return err
}
}
// If this tx spends any previous credits (either mined or unmined), set
// each unspent. Mined transactions are only marked spent by having the
// output in the unmined inputs bucket.
for _, input := range rec.MsgTx.TxIn {
prevOut := &input.PreviousOutPoint
k := canonicalOutPoint(&prevOut.Hash, prevOut.Index)
err := deleteRawUnminedInput(ns, k, rec.Hash)
if err != nil {
return err
}
}
return deleteRawUnmined(ns, rec.Hash[:])
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"removeConflict",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"rec",
"*",
"TxRecord",
")",
"error",
"{",
"// For each potential credit for this record, each spender (if any) must",
"// be recursively removed as well. Once the spenders are removed, the",
"// credit is deleted.",
"for",
"i",
":=",
"range",
"rec",
".",
"MsgTx",
".",
"TxOut",
"{",
"k",
":=",
"canonicalOutPoint",
"(",
"&",
"rec",
".",
"Hash",
",",
"uint32",
"(",
"i",
")",
")",
"\n",
"spenderHashes",
":=",
"fetchUnminedInputSpendTxHashes",
"(",
"ns",
",",
"k",
")",
"\n",
"for",
"_",
",",
"spenderHash",
":=",
"range",
"spenderHashes",
"{",
"// If the spending transaction spends multiple outputs",
"// from the same transaction, we'll find duplicate",
"// entries within the store, so it's possible we're",
"// unable to find it if the conflicts have already been",
"// removed in a previous iteration.",
"spenderVal",
":=",
"existsRawUnmined",
"(",
"ns",
",",
"spenderHash",
"[",
":",
"]",
")",
"\n",
"if",
"spenderVal",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"var",
"spender",
"TxRecord",
"\n",
"spender",
".",
"Hash",
"=",
"spenderHash",
"\n",
"err",
":=",
"readRawTxRecord",
"(",
"&",
"spender",
".",
"Hash",
",",
"spenderVal",
",",
"&",
"spender",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"spender",
".",
"Hash",
")",
"\n",
"if",
"err",
":=",
"s",
".",
"removeConflict",
"(",
"ns",
",",
"&",
"spender",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"deleteRawUnminedCredit",
"(",
"ns",
",",
"k",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If this tx spends any previous credits (either mined or unmined), set",
"// each unspent. Mined transactions are only marked spent by having the",
"// output in the unmined inputs bucket.",
"for",
"_",
",",
"input",
":=",
"range",
"rec",
".",
"MsgTx",
".",
"TxIn",
"{",
"prevOut",
":=",
"&",
"input",
".",
"PreviousOutPoint",
"\n",
"k",
":=",
"canonicalOutPoint",
"(",
"&",
"prevOut",
".",
"Hash",
",",
"prevOut",
".",
"Index",
")",
"\n",
"err",
":=",
"deleteRawUnminedInput",
"(",
"ns",
",",
"k",
",",
"rec",
".",
"Hash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"deleteRawUnmined",
"(",
"ns",
",",
"rec",
".",
"Hash",
"[",
":",
"]",
")",
"\n",
"}"
] | // removeConflict removes an unmined transaction record and all spend chains
// deriving from it from the store. This is designed to remove transactions
// that would otherwise result in double spend conflicts if left in the store,
// and to remove transactions that spend coinbase transactions on reorgs. | [
"removeConflict",
"removes",
"an",
"unmined",
"transaction",
"record",
"and",
"all",
"spend",
"chains",
"deriving",
"from",
"it",
"from",
"the",
"store",
".",
"This",
"is",
"designed",
"to",
"remove",
"transactions",
"that",
"would",
"otherwise",
"result",
"in",
"double",
"spend",
"conflicts",
"if",
"left",
"in",
"the",
"store",
"and",
"to",
"remove",
"transactions",
"that",
"spend",
"coinbase",
"transactions",
"on",
"reorgs",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/unconfirmed.go#L114-L163 | train |
btcsuite/btcwallet | wtxmgr/unconfirmed.go | UnminedTxs | func (s *Store) UnminedTxs(ns walletdb.ReadBucket) ([]*wire.MsgTx, error) {
recSet, err := s.unminedTxRecords(ns)
if err != nil {
return nil, err
}
txSet := make(map[chainhash.Hash]*wire.MsgTx, len(recSet))
for txHash, txRec := range recSet {
txSet[txHash] = &txRec.MsgTx
}
return DependencySort(txSet), nil
} | go | func (s *Store) UnminedTxs(ns walletdb.ReadBucket) ([]*wire.MsgTx, error) {
recSet, err := s.unminedTxRecords(ns)
if err != nil {
return nil, err
}
txSet := make(map[chainhash.Hash]*wire.MsgTx, len(recSet))
for txHash, txRec := range recSet {
txSet[txHash] = &txRec.MsgTx
}
return DependencySort(txSet), nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"UnminedTxs",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
")",
"(",
"[",
"]",
"*",
"wire",
".",
"MsgTx",
",",
"error",
")",
"{",
"recSet",
",",
"err",
":=",
"s",
".",
"unminedTxRecords",
"(",
"ns",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"txSet",
":=",
"make",
"(",
"map",
"[",
"chainhash",
".",
"Hash",
"]",
"*",
"wire",
".",
"MsgTx",
",",
"len",
"(",
"recSet",
")",
")",
"\n",
"for",
"txHash",
",",
"txRec",
":=",
"range",
"recSet",
"{",
"txSet",
"[",
"txHash",
"]",
"=",
"&",
"txRec",
".",
"MsgTx",
"\n",
"}",
"\n\n",
"return",
"DependencySort",
"(",
"txSet",
")",
",",
"nil",
"\n",
"}"
] | // UnminedTxs returns the underlying transactions for all unmined transactions
// which are not known to have been mined in a block. Transactions are
// guaranteed to be sorted by their dependency order. | [
"UnminedTxs",
"returns",
"the",
"underlying",
"transactions",
"for",
"all",
"unmined",
"transactions",
"which",
"are",
"not",
"known",
"to",
"have",
"been",
"mined",
"in",
"a",
"block",
".",
"Transactions",
"are",
"guaranteed",
"to",
"be",
"sorted",
"by",
"their",
"dependency",
"order",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/unconfirmed.go#L168-L180 | train |
btcsuite/btcwallet | wtxmgr/unconfirmed.go | UnminedTxHashes | func (s *Store) UnminedTxHashes(ns walletdb.ReadBucket) ([]*chainhash.Hash, error) {
return s.unminedTxHashes(ns)
} | go | func (s *Store) UnminedTxHashes(ns walletdb.ReadBucket) ([]*chainhash.Hash, error) {
return s.unminedTxHashes(ns)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"UnminedTxHashes",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
")",
"(",
"[",
"]",
"*",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"return",
"s",
".",
"unminedTxHashes",
"(",
"ns",
")",
"\n",
"}"
] | // UnminedTxHashes returns the hashes of all transactions not known to have been
// mined in a block. | [
"UnminedTxHashes",
"returns",
"the",
"hashes",
"of",
"all",
"transactions",
"not",
"known",
"to",
"have",
"been",
"mined",
"in",
"a",
"block",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/unconfirmed.go#L204-L206 | train |
btcsuite/btcwallet | wallet/wallet.go | Start | func (w *Wallet) Start() {
w.quitMu.Lock()
select {
case <-w.quit:
// Restart the wallet goroutines after shutdown finishes.
w.WaitForShutdown()
w.quit = make(chan struct{})
default:
// Ignore when the wallet is still running.
if w.started {
w.quitMu.Unlock()
return
}
w.started = true
}
w.quitMu.Unlock()
w.wg.Add(2)
go w.txCreator()
go w.walletLocker()
} | go | func (w *Wallet) Start() {
w.quitMu.Lock()
select {
case <-w.quit:
// Restart the wallet goroutines after shutdown finishes.
w.WaitForShutdown()
w.quit = make(chan struct{})
default:
// Ignore when the wallet is still running.
if w.started {
w.quitMu.Unlock()
return
}
w.started = true
}
w.quitMu.Unlock()
w.wg.Add(2)
go w.txCreator()
go w.walletLocker()
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"Start",
"(",
")",
"{",
"w",
".",
"quitMu",
".",
"Lock",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"w",
".",
"quit",
":",
"// Restart the wallet goroutines after shutdown finishes.",
"w",
".",
"WaitForShutdown",
"(",
")",
"\n",
"w",
".",
"quit",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"default",
":",
"// Ignore when the wallet is still running.",
"if",
"w",
".",
"started",
"{",
"w",
".",
"quitMu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"started",
"=",
"true",
"\n",
"}",
"\n",
"w",
".",
"quitMu",
".",
"Unlock",
"(",
")",
"\n\n",
"w",
".",
"wg",
".",
"Add",
"(",
"2",
")",
"\n",
"go",
"w",
".",
"txCreator",
"(",
")",
"\n",
"go",
"w",
".",
"walletLocker",
"(",
")",
"\n",
"}"
] | // Start starts the goroutines necessary to manage a wallet. | [
"Start",
"starts",
"the",
"goroutines",
"necessary",
"to",
"manage",
"a",
"wallet",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L124-L144 | train |
btcsuite/btcwallet | wallet/wallet.go | SynchronizeRPC | func (w *Wallet) SynchronizeRPC(chainClient chain.Interface) {
w.quitMu.Lock()
select {
case <-w.quit:
w.quitMu.Unlock()
return
default:
}
w.quitMu.Unlock()
// TODO: Ignoring the new client when one is already set breaks callers
// who are replacing the client, perhaps after a disconnect.
w.chainClientLock.Lock()
if w.chainClient != nil {
w.chainClientLock.Unlock()
return
}
w.chainClient = chainClient
// If the chain client is a NeutrinoClient instance, set a birthday so
// we don't download all the filters as we go.
switch cc := chainClient.(type) {
case *chain.NeutrinoClient:
cc.SetStartTime(w.Manager.Birthday())
case *chain.BitcoindClient:
cc.SetBirthday(w.Manager.Birthday())
}
w.chainClientLock.Unlock()
// TODO: It would be preferable to either run these goroutines
// separately from the wallet (use wallet mutator functions to
// make changes from the RPC client) and not have to stop and
// restart them each time the client disconnects and reconnets.
w.wg.Add(4)
go w.handleChainNotifications()
go w.rescanBatchHandler()
go w.rescanProgressHandler()
go w.rescanRPCHandler()
} | go | func (w *Wallet) SynchronizeRPC(chainClient chain.Interface) {
w.quitMu.Lock()
select {
case <-w.quit:
w.quitMu.Unlock()
return
default:
}
w.quitMu.Unlock()
// TODO: Ignoring the new client when one is already set breaks callers
// who are replacing the client, perhaps after a disconnect.
w.chainClientLock.Lock()
if w.chainClient != nil {
w.chainClientLock.Unlock()
return
}
w.chainClient = chainClient
// If the chain client is a NeutrinoClient instance, set a birthday so
// we don't download all the filters as we go.
switch cc := chainClient.(type) {
case *chain.NeutrinoClient:
cc.SetStartTime(w.Manager.Birthday())
case *chain.BitcoindClient:
cc.SetBirthday(w.Manager.Birthday())
}
w.chainClientLock.Unlock()
// TODO: It would be preferable to either run these goroutines
// separately from the wallet (use wallet mutator functions to
// make changes from the RPC client) and not have to stop and
// restart them each time the client disconnects and reconnets.
w.wg.Add(4)
go w.handleChainNotifications()
go w.rescanBatchHandler()
go w.rescanProgressHandler()
go w.rescanRPCHandler()
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"SynchronizeRPC",
"(",
"chainClient",
"chain",
".",
"Interface",
")",
"{",
"w",
".",
"quitMu",
".",
"Lock",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"w",
".",
"quit",
":",
"w",
".",
"quitMu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"default",
":",
"}",
"\n",
"w",
".",
"quitMu",
".",
"Unlock",
"(",
")",
"\n\n",
"// TODO: Ignoring the new client when one is already set breaks callers",
"// who are replacing the client, perhaps after a disconnect.",
"w",
".",
"chainClientLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"w",
".",
"chainClient",
"!=",
"nil",
"{",
"w",
".",
"chainClientLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"chainClient",
"=",
"chainClient",
"\n\n",
"// If the chain client is a NeutrinoClient instance, set a birthday so",
"// we don't download all the filters as we go.",
"switch",
"cc",
":=",
"chainClient",
".",
"(",
"type",
")",
"{",
"case",
"*",
"chain",
".",
"NeutrinoClient",
":",
"cc",
".",
"SetStartTime",
"(",
"w",
".",
"Manager",
".",
"Birthday",
"(",
")",
")",
"\n",
"case",
"*",
"chain",
".",
"BitcoindClient",
":",
"cc",
".",
"SetBirthday",
"(",
"w",
".",
"Manager",
".",
"Birthday",
"(",
")",
")",
"\n",
"}",
"\n",
"w",
".",
"chainClientLock",
".",
"Unlock",
"(",
")",
"\n\n",
"// TODO: It would be preferable to either run these goroutines",
"// separately from the wallet (use wallet mutator functions to",
"// make changes from the RPC client) and not have to stop and",
"// restart them each time the client disconnects and reconnets.",
"w",
".",
"wg",
".",
"Add",
"(",
"4",
")",
"\n",
"go",
"w",
".",
"handleChainNotifications",
"(",
")",
"\n",
"go",
"w",
".",
"rescanBatchHandler",
"(",
")",
"\n",
"go",
"w",
".",
"rescanProgressHandler",
"(",
")",
"\n",
"go",
"w",
".",
"rescanRPCHandler",
"(",
")",
"\n",
"}"
] | // SynchronizeRPC associates the wallet with the consensus RPC client,
// synchronizes the wallet with the latest changes to the blockchain, and
// continuously updates the wallet through RPC notifications.
//
// This method is unstable and will be removed when all syncing logic is moved
// outside of the wallet package. | [
"SynchronizeRPC",
"associates",
"the",
"wallet",
"with",
"the",
"consensus",
"RPC",
"client",
"synchronizes",
"the",
"wallet",
"with",
"the",
"latest",
"changes",
"to",
"the",
"blockchain",
"and",
"continuously",
"updates",
"the",
"wallet",
"through",
"RPC",
"notifications",
".",
"This",
"method",
"is",
"unstable",
"and",
"will",
"be",
"removed",
"when",
"all",
"syncing",
"logic",
"is",
"moved",
"outside",
"of",
"the",
"wallet",
"package",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L152-L190 | train |
btcsuite/btcwallet | wallet/wallet.go | requireChainClient | func (w *Wallet) requireChainClient() (chain.Interface, error) {
w.chainClientLock.Lock()
chainClient := w.chainClient
w.chainClientLock.Unlock()
if chainClient == nil {
return nil, errors.New("blockchain RPC is inactive")
}
return chainClient, nil
} | go | func (w *Wallet) requireChainClient() (chain.Interface, error) {
w.chainClientLock.Lock()
chainClient := w.chainClient
w.chainClientLock.Unlock()
if chainClient == nil {
return nil, errors.New("blockchain RPC is inactive")
}
return chainClient, nil
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"requireChainClient",
"(",
")",
"(",
"chain",
".",
"Interface",
",",
"error",
")",
"{",
"w",
".",
"chainClientLock",
".",
"Lock",
"(",
")",
"\n",
"chainClient",
":=",
"w",
".",
"chainClient",
"\n",
"w",
".",
"chainClientLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"chainClient",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"chainClient",
",",
"nil",
"\n",
"}"
] | // requireChainClient marks that a wallet method can only be completed when the
// consensus RPC server is set. This function and all functions that call it
// are unstable and will need to be moved when the syncing code is moved out of
// the wallet. | [
"requireChainClient",
"marks",
"that",
"a",
"wallet",
"method",
"can",
"only",
"be",
"completed",
"when",
"the",
"consensus",
"RPC",
"server",
"is",
"set",
".",
"This",
"function",
"and",
"all",
"functions",
"that",
"call",
"it",
"are",
"unstable",
"and",
"will",
"need",
"to",
"be",
"moved",
"when",
"the",
"syncing",
"code",
"is",
"moved",
"out",
"of",
"the",
"wallet",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L196-L204 | train |
btcsuite/btcwallet | wallet/wallet.go | ChainClient | func (w *Wallet) ChainClient() chain.Interface {
w.chainClientLock.Lock()
chainClient := w.chainClient
w.chainClientLock.Unlock()
return chainClient
} | go | func (w *Wallet) ChainClient() chain.Interface {
w.chainClientLock.Lock()
chainClient := w.chainClient
w.chainClientLock.Unlock()
return chainClient
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"ChainClient",
"(",
")",
"chain",
".",
"Interface",
"{",
"w",
".",
"chainClientLock",
".",
"Lock",
"(",
")",
"\n",
"chainClient",
":=",
"w",
".",
"chainClient",
"\n",
"w",
".",
"chainClientLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"chainClient",
"\n",
"}"
] | // ChainClient returns the optional consensus RPC client associated with the
// wallet.
//
// This function is unstable and will be removed once sync logic is moved out of
// the wallet. | [
"ChainClient",
"returns",
"the",
"optional",
"consensus",
"RPC",
"client",
"associated",
"with",
"the",
"wallet",
".",
"This",
"function",
"is",
"unstable",
"and",
"will",
"be",
"removed",
"once",
"sync",
"logic",
"is",
"moved",
"out",
"of",
"the",
"wallet",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L211-L216 | train |
btcsuite/btcwallet | wallet/wallet.go | quitChan | func (w *Wallet) quitChan() <-chan struct{} {
w.quitMu.Lock()
c := w.quit
w.quitMu.Unlock()
return c
} | go | func (w *Wallet) quitChan() <-chan struct{} {
w.quitMu.Lock()
c := w.quit
w.quitMu.Unlock()
return c
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"quitChan",
"(",
")",
"<-",
"chan",
"struct",
"{",
"}",
"{",
"w",
".",
"quitMu",
".",
"Lock",
"(",
")",
"\n",
"c",
":=",
"w",
".",
"quit",
"\n",
"w",
".",
"quitMu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"c",
"\n",
"}"
] | // quitChan atomically reads the quit channel. | [
"quitChan",
"atomically",
"reads",
"the",
"quit",
"channel",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L219-L224 | train |
btcsuite/btcwallet | wallet/wallet.go | Stop | func (w *Wallet) Stop() {
w.quitMu.Lock()
quit := w.quit
w.quitMu.Unlock()
select {
case <-quit:
default:
close(quit)
w.chainClientLock.Lock()
if w.chainClient != nil {
w.chainClient.Stop()
w.chainClient = nil
}
w.chainClientLock.Unlock()
}
} | go | func (w *Wallet) Stop() {
w.quitMu.Lock()
quit := w.quit
w.quitMu.Unlock()
select {
case <-quit:
default:
close(quit)
w.chainClientLock.Lock()
if w.chainClient != nil {
w.chainClient.Stop()
w.chainClient = nil
}
w.chainClientLock.Unlock()
}
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"Stop",
"(",
")",
"{",
"w",
".",
"quitMu",
".",
"Lock",
"(",
")",
"\n",
"quit",
":=",
"w",
".",
"quit",
"\n",
"w",
".",
"quitMu",
".",
"Unlock",
"(",
")",
"\n\n",
"select",
"{",
"case",
"<-",
"quit",
":",
"default",
":",
"close",
"(",
"quit",
")",
"\n",
"w",
".",
"chainClientLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"w",
".",
"chainClient",
"!=",
"nil",
"{",
"w",
".",
"chainClient",
".",
"Stop",
"(",
")",
"\n",
"w",
".",
"chainClient",
"=",
"nil",
"\n",
"}",
"\n",
"w",
".",
"chainClientLock",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Stop signals all wallet goroutines to shutdown. | [
"Stop",
"signals",
"all",
"wallet",
"goroutines",
"to",
"shutdown",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L227-L243 | train |
btcsuite/btcwallet | wallet/wallet.go | WaitForShutdown | func (w *Wallet) WaitForShutdown() {
w.chainClientLock.Lock()
if w.chainClient != nil {
w.chainClient.WaitForShutdown()
}
w.chainClientLock.Unlock()
w.wg.Wait()
} | go | func (w *Wallet) WaitForShutdown() {
w.chainClientLock.Lock()
if w.chainClient != nil {
w.chainClient.WaitForShutdown()
}
w.chainClientLock.Unlock()
w.wg.Wait()
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"WaitForShutdown",
"(",
")",
"{",
"w",
".",
"chainClientLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"w",
".",
"chainClient",
"!=",
"nil",
"{",
"w",
".",
"chainClient",
".",
"WaitForShutdown",
"(",
")",
"\n",
"}",
"\n",
"w",
".",
"chainClientLock",
".",
"Unlock",
"(",
")",
"\n",
"w",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"}"
] | // WaitForShutdown blocks until all wallet goroutines have finished executing. | [
"WaitForShutdown",
"blocks",
"until",
"all",
"wallet",
"goroutines",
"have",
"finished",
"executing",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L257-L264 | train |
btcsuite/btcwallet | wallet/wallet.go | SynchronizingToNetwork | func (w *Wallet) SynchronizingToNetwork() bool {
// At the moment, RPC is the only synchronization method. In the
// future, when SPV is added, a separate check will also be needed, or
// SPV could always be enabled if RPC was not explicitly specified when
// creating the wallet.
w.chainClientSyncMtx.Lock()
syncing := w.chainClient != nil
w.chainClientSyncMtx.Unlock()
return syncing
} | go | func (w *Wallet) SynchronizingToNetwork() bool {
// At the moment, RPC is the only synchronization method. In the
// future, when SPV is added, a separate check will also be needed, or
// SPV could always be enabled if RPC was not explicitly specified when
// creating the wallet.
w.chainClientSyncMtx.Lock()
syncing := w.chainClient != nil
w.chainClientSyncMtx.Unlock()
return syncing
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"SynchronizingToNetwork",
"(",
")",
"bool",
"{",
"// At the moment, RPC is the only synchronization method. In the",
"// future, when SPV is added, a separate check will also be needed, or",
"// SPV could always be enabled if RPC was not explicitly specified when",
"// creating the wallet.",
"w",
".",
"chainClientSyncMtx",
".",
"Lock",
"(",
")",
"\n",
"syncing",
":=",
"w",
".",
"chainClient",
"!=",
"nil",
"\n",
"w",
".",
"chainClientSyncMtx",
".",
"Unlock",
"(",
")",
"\n",
"return",
"syncing",
"\n",
"}"
] | // SynchronizingToNetwork returns whether the wallet is currently synchronizing
// with the Bitcoin network. | [
"SynchronizingToNetwork",
"returns",
"whether",
"the",
"wallet",
"is",
"currently",
"synchronizing",
"with",
"the",
"Bitcoin",
"network",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L268-L277 | train |
btcsuite/btcwallet | wallet/wallet.go | ChainSynced | func (w *Wallet) ChainSynced() bool {
w.chainClientSyncMtx.Lock()
synced := w.chainClientSynced
w.chainClientSyncMtx.Unlock()
return synced
} | go | func (w *Wallet) ChainSynced() bool {
w.chainClientSyncMtx.Lock()
synced := w.chainClientSynced
w.chainClientSyncMtx.Unlock()
return synced
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"ChainSynced",
"(",
")",
"bool",
"{",
"w",
".",
"chainClientSyncMtx",
".",
"Lock",
"(",
")",
"\n",
"synced",
":=",
"w",
".",
"chainClientSynced",
"\n",
"w",
".",
"chainClientSyncMtx",
".",
"Unlock",
"(",
")",
"\n",
"return",
"synced",
"\n",
"}"
] | // ChainSynced returns whether the wallet has been attached to a chain server
// and synced up to the best block on the main chain. | [
"ChainSynced",
"returns",
"whether",
"the",
"wallet",
"has",
"been",
"attached",
"to",
"a",
"chain",
"server",
"and",
"synced",
"up",
"to",
"the",
"best",
"block",
"on",
"the",
"main",
"chain",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L281-L286 | train |
btcsuite/btcwallet | wallet/wallet.go | activeData | func (w *Wallet) activeData(dbtx walletdb.ReadTx) ([]btcutil.Address, []wtxmgr.Credit, error) {
addrmgrNs := dbtx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
var addrs []btcutil.Address
err := w.Manager.ForEachActiveAddress(addrmgrNs, func(addr btcutil.Address) error {
addrs = append(addrs, addr)
return nil
})
if err != nil {
return nil, nil, err
}
unspent, err := w.TxStore.UnspentOutputs(txmgrNs)
return addrs, unspent, err
} | go | func (w *Wallet) activeData(dbtx walletdb.ReadTx) ([]btcutil.Address, []wtxmgr.Credit, error) {
addrmgrNs := dbtx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
var addrs []btcutil.Address
err := w.Manager.ForEachActiveAddress(addrmgrNs, func(addr btcutil.Address) error {
addrs = append(addrs, addr)
return nil
})
if err != nil {
return nil, nil, err
}
unspent, err := w.TxStore.UnspentOutputs(txmgrNs)
return addrs, unspent, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"activeData",
"(",
"dbtx",
"walletdb",
".",
"ReadTx",
")",
"(",
"[",
"]",
"btcutil",
".",
"Address",
",",
"[",
"]",
"wtxmgr",
".",
"Credit",
",",
"error",
")",
"{",
"addrmgrNs",
":=",
"dbtx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"txmgrNs",
":=",
"dbtx",
".",
"ReadBucket",
"(",
"wtxmgrNamespaceKey",
")",
"\n\n",
"var",
"addrs",
"[",
"]",
"btcutil",
".",
"Address",
"\n",
"err",
":=",
"w",
".",
"Manager",
".",
"ForEachActiveAddress",
"(",
"addrmgrNs",
",",
"func",
"(",
"addr",
"btcutil",
".",
"Address",
")",
"error",
"{",
"addrs",
"=",
"append",
"(",
"addrs",
",",
"addr",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"unspent",
",",
"err",
":=",
"w",
".",
"TxStore",
".",
"UnspentOutputs",
"(",
"txmgrNs",
")",
"\n",
"return",
"addrs",
",",
"unspent",
",",
"err",
"\n",
"}"
] | // activeData returns the currently-active receiving addresses and all unspent
// outputs. This is primarely intended to provide the parameters for a
// rescan request. | [
"activeData",
"returns",
"the",
"currently",
"-",
"active",
"receiving",
"addresses",
"and",
"all",
"unspent",
"outputs",
".",
"This",
"is",
"primarely",
"intended",
"to",
"provide",
"the",
"parameters",
"for",
"a",
"rescan",
"request",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L304-L318 | train |
btcsuite/btcwallet | wallet/wallet.go | syncWithChain | func (w *Wallet) syncWithChain(birthdayStamp *waddrmgr.BlockStamp) error {
// To start, if we've yet to find our birthday stamp, we'll do so now.
if birthdayStamp == nil {
var err error
birthdayStamp, err = w.syncToBirthday()
if err != nil {
return err
}
}
// If the wallet requested an on-chain recovery of its funds, we'll do
// so now.
if w.recoveryWindow > 0 {
// We'll start the recovery from our birthday unless we were
// in the middle of a previous recovery attempt. If that's the
// case, we'll resume from that point.
startHeight := birthdayStamp.Height
walletHeight := w.Manager.SyncedTo().Height
if walletHeight > startHeight {
startHeight = walletHeight
}
if err := w.recovery(startHeight); err != nil {
return err
}
}
// Compare previously-seen blocks against the current chain. If any of
// these blocks no longer exist, rollback all of the missing blocks
// before catching up with the rescan.
rollback := false
rollbackStamp := w.Manager.SyncedTo()
chainClient, err := w.requireChainClient()
if err != nil {
return err
}
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
txmgrNs := tx.ReadWriteBucket(wtxmgrNamespaceKey)
for height := rollbackStamp.Height; true; height-- {
hash, err := w.Manager.BlockHash(addrmgrNs, height)
if err != nil {
return err
}
chainHash, err := chainClient.GetBlockHash(int64(height))
if err != nil {
return err
}
header, err := chainClient.GetBlockHeader(chainHash)
if err != nil {
return err
}
rollbackStamp.Hash = *chainHash
rollbackStamp.Height = height
rollbackStamp.Timestamp = header.Timestamp
if bytes.Equal(hash[:], chainHash[:]) {
break
}
rollback = true
}
// If a rollback did not happen, we can proceed safely.
if !rollback {
return nil
}
// Otherwise, we'll mark this as our new synced height.
err := w.Manager.SetSyncedTo(addrmgrNs, &rollbackStamp)
if err != nil {
return err
}
// If the rollback happened to go beyond our birthday stamp,
// we'll need to find a new one by syncing with the chain again
// until finding one.
if rollbackStamp.Height <= birthdayStamp.Height &&
rollbackStamp.Hash != birthdayStamp.Hash {
err := w.Manager.SetBirthdayBlock(
addrmgrNs, rollbackStamp, true,
)
if err != nil {
return err
}
}
// Finally, we'll roll back our transaction store to reflect the
// stale state. `Rollback` unconfirms transactions at and beyond
// the passed height, so add one to the new synced-to height to
// prevent unconfirming transactions in the synced-to block.
return w.TxStore.Rollback(txmgrNs, rollbackStamp.Height+1)
})
if err != nil {
return err
}
// Request notifications for connected and disconnected blocks.
//
// TODO(jrick): Either request this notification only once, or when
// rpcclient is modified to allow some notification request to not
// automatically resent on reconnect, include the notifyblocks request
// as well. I am leaning towards allowing off all rpcclient
// notification re-registrations, in which case the code here should be
// left as is.
if err := chainClient.NotifyBlocks(); err != nil {
return err
}
// Finally, we'll trigger a wallet rescan from the currently synced tip
// and request notifications for transactions sending to all wallet
// addresses and spending all wallet UTXOs.
var (
addrs []btcutil.Address
unspent []wtxmgr.Credit
)
err = walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
addrs, unspent, err = w.activeData(dbtx)
return err
})
if err != nil {
return err
}
return w.rescanWithTarget(addrs, unspent, nil)
} | go | func (w *Wallet) syncWithChain(birthdayStamp *waddrmgr.BlockStamp) error {
// To start, if we've yet to find our birthday stamp, we'll do so now.
if birthdayStamp == nil {
var err error
birthdayStamp, err = w.syncToBirthday()
if err != nil {
return err
}
}
// If the wallet requested an on-chain recovery of its funds, we'll do
// so now.
if w.recoveryWindow > 0 {
// We'll start the recovery from our birthday unless we were
// in the middle of a previous recovery attempt. If that's the
// case, we'll resume from that point.
startHeight := birthdayStamp.Height
walletHeight := w.Manager.SyncedTo().Height
if walletHeight > startHeight {
startHeight = walletHeight
}
if err := w.recovery(startHeight); err != nil {
return err
}
}
// Compare previously-seen blocks against the current chain. If any of
// these blocks no longer exist, rollback all of the missing blocks
// before catching up with the rescan.
rollback := false
rollbackStamp := w.Manager.SyncedTo()
chainClient, err := w.requireChainClient()
if err != nil {
return err
}
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
txmgrNs := tx.ReadWriteBucket(wtxmgrNamespaceKey)
for height := rollbackStamp.Height; true; height-- {
hash, err := w.Manager.BlockHash(addrmgrNs, height)
if err != nil {
return err
}
chainHash, err := chainClient.GetBlockHash(int64(height))
if err != nil {
return err
}
header, err := chainClient.GetBlockHeader(chainHash)
if err != nil {
return err
}
rollbackStamp.Hash = *chainHash
rollbackStamp.Height = height
rollbackStamp.Timestamp = header.Timestamp
if bytes.Equal(hash[:], chainHash[:]) {
break
}
rollback = true
}
// If a rollback did not happen, we can proceed safely.
if !rollback {
return nil
}
// Otherwise, we'll mark this as our new synced height.
err := w.Manager.SetSyncedTo(addrmgrNs, &rollbackStamp)
if err != nil {
return err
}
// If the rollback happened to go beyond our birthday stamp,
// we'll need to find a new one by syncing with the chain again
// until finding one.
if rollbackStamp.Height <= birthdayStamp.Height &&
rollbackStamp.Hash != birthdayStamp.Hash {
err := w.Manager.SetBirthdayBlock(
addrmgrNs, rollbackStamp, true,
)
if err != nil {
return err
}
}
// Finally, we'll roll back our transaction store to reflect the
// stale state. `Rollback` unconfirms transactions at and beyond
// the passed height, so add one to the new synced-to height to
// prevent unconfirming transactions in the synced-to block.
return w.TxStore.Rollback(txmgrNs, rollbackStamp.Height+1)
})
if err != nil {
return err
}
// Request notifications for connected and disconnected blocks.
//
// TODO(jrick): Either request this notification only once, or when
// rpcclient is modified to allow some notification request to not
// automatically resent on reconnect, include the notifyblocks request
// as well. I am leaning towards allowing off all rpcclient
// notification re-registrations, in which case the code here should be
// left as is.
if err := chainClient.NotifyBlocks(); err != nil {
return err
}
// Finally, we'll trigger a wallet rescan from the currently synced tip
// and request notifications for transactions sending to all wallet
// addresses and spending all wallet UTXOs.
var (
addrs []btcutil.Address
unspent []wtxmgr.Credit
)
err = walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
addrs, unspent, err = w.activeData(dbtx)
return err
})
if err != nil {
return err
}
return w.rescanWithTarget(addrs, unspent, nil)
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"syncWithChain",
"(",
"birthdayStamp",
"*",
"waddrmgr",
".",
"BlockStamp",
")",
"error",
"{",
"// To start, if we've yet to find our birthday stamp, we'll do so now.",
"if",
"birthdayStamp",
"==",
"nil",
"{",
"var",
"err",
"error",
"\n",
"birthdayStamp",
",",
"err",
"=",
"w",
".",
"syncToBirthday",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If the wallet requested an on-chain recovery of its funds, we'll do",
"// so now.",
"if",
"w",
".",
"recoveryWindow",
">",
"0",
"{",
"// We'll start the recovery from our birthday unless we were",
"// in the middle of a previous recovery attempt. If that's the",
"// case, we'll resume from that point.",
"startHeight",
":=",
"birthdayStamp",
".",
"Height",
"\n",
"walletHeight",
":=",
"w",
".",
"Manager",
".",
"SyncedTo",
"(",
")",
".",
"Height",
"\n",
"if",
"walletHeight",
">",
"startHeight",
"{",
"startHeight",
"=",
"walletHeight",
"\n",
"}",
"\n",
"if",
"err",
":=",
"w",
".",
"recovery",
"(",
"startHeight",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Compare previously-seen blocks against the current chain. If any of",
"// these blocks no longer exist, rollback all of the missing blocks",
"// before catching up with the rescan.",
"rollback",
":=",
"false",
"\n",
"rollbackStamp",
":=",
"w",
".",
"Manager",
".",
"SyncedTo",
"(",
")",
"\n",
"chainClient",
",",
"err",
":=",
"w",
".",
"requireChainClient",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"walletdb",
".",
"Update",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadWriteTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadWriteBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"txmgrNs",
":=",
"tx",
".",
"ReadWriteBucket",
"(",
"wtxmgrNamespaceKey",
")",
"\n\n",
"for",
"height",
":=",
"rollbackStamp",
".",
"Height",
";",
"true",
";",
"height",
"--",
"{",
"hash",
",",
"err",
":=",
"w",
".",
"Manager",
".",
"BlockHash",
"(",
"addrmgrNs",
",",
"height",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"chainHash",
",",
"err",
":=",
"chainClient",
".",
"GetBlockHash",
"(",
"int64",
"(",
"height",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"header",
",",
"err",
":=",
"chainClient",
".",
"GetBlockHeader",
"(",
"chainHash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"rollbackStamp",
".",
"Hash",
"=",
"*",
"chainHash",
"\n",
"rollbackStamp",
".",
"Height",
"=",
"height",
"\n",
"rollbackStamp",
".",
"Timestamp",
"=",
"header",
".",
"Timestamp",
"\n\n",
"if",
"bytes",
".",
"Equal",
"(",
"hash",
"[",
":",
"]",
",",
"chainHash",
"[",
":",
"]",
")",
"{",
"break",
"\n",
"}",
"\n",
"rollback",
"=",
"true",
"\n",
"}",
"\n\n",
"// If a rollback did not happen, we can proceed safely.",
"if",
"!",
"rollback",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Otherwise, we'll mark this as our new synced height.",
"err",
":=",
"w",
".",
"Manager",
".",
"SetSyncedTo",
"(",
"addrmgrNs",
",",
"&",
"rollbackStamp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// If the rollback happened to go beyond our birthday stamp,",
"// we'll need to find a new one by syncing with the chain again",
"// until finding one.",
"if",
"rollbackStamp",
".",
"Height",
"<=",
"birthdayStamp",
".",
"Height",
"&&",
"rollbackStamp",
".",
"Hash",
"!=",
"birthdayStamp",
".",
"Hash",
"{",
"err",
":=",
"w",
".",
"Manager",
".",
"SetBirthdayBlock",
"(",
"addrmgrNs",
",",
"rollbackStamp",
",",
"true",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Finally, we'll roll back our transaction store to reflect the",
"// stale state. `Rollback` unconfirms transactions at and beyond",
"// the passed height, so add one to the new synced-to height to",
"// prevent unconfirming transactions in the synced-to block.",
"return",
"w",
".",
"TxStore",
".",
"Rollback",
"(",
"txmgrNs",
",",
"rollbackStamp",
".",
"Height",
"+",
"1",
")",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Request notifications for connected and disconnected blocks.",
"//",
"// TODO(jrick): Either request this notification only once, or when",
"// rpcclient is modified to allow some notification request to not",
"// automatically resent on reconnect, include the notifyblocks request",
"// as well. I am leaning towards allowing off all rpcclient",
"// notification re-registrations, in which case the code here should be",
"// left as is.",
"if",
"err",
":=",
"chainClient",
".",
"NotifyBlocks",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Finally, we'll trigger a wallet rescan from the currently synced tip",
"// and request notifications for transactions sending to all wallet",
"// addresses and spending all wallet UTXOs.",
"var",
"(",
"addrs",
"[",
"]",
"btcutil",
".",
"Address",
"\n",
"unspent",
"[",
"]",
"wtxmgr",
".",
"Credit",
"\n",
")",
"\n",
"err",
"=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"dbtx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"addrs",
",",
"unspent",
",",
"err",
"=",
"w",
".",
"activeData",
"(",
"dbtx",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"w",
".",
"rescanWithTarget",
"(",
"addrs",
",",
"unspent",
",",
"nil",
")",
"\n",
"}"
] | // syncWithChain brings the wallet up to date with the current chain server
// connection. It creates a rescan request and blocks until the rescan has
// finished. The birthday block can be passed in, if set, to ensure we can
// properly detect if it gets rolled back. | [
"syncWithChain",
"brings",
"the",
"wallet",
"up",
"to",
"date",
"with",
"the",
"current",
"chain",
"server",
"connection",
".",
"It",
"creates",
"a",
"rescan",
"request",
"and",
"blocks",
"until",
"the",
"rescan",
"has",
"finished",
".",
"The",
"birthday",
"block",
"can",
"be",
"passed",
"in",
"if",
"set",
"to",
"ensure",
"we",
"can",
"properly",
"detect",
"if",
"it",
"gets",
"rolled",
"back",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L324-L451 | train |
btcsuite/btcwallet | wallet/wallet.go | scanChain | func (w *Wallet) scanChain(startHeight int32,
onBlock func(int32, *chainhash.Hash, *wire.BlockHeader) error) error {
chainClient, err := w.requireChainClient()
if err != nil {
return err
}
// isCurrent is a helper function that we'll use to determine if the
// chain backend is currently synced. When running with a btcd or
// bitcoind backend, it will use the height of the latest checkpoint as
// its lower bound.
var latestCheckptHeight int32
if len(w.chainParams.Checkpoints) > 0 {
latestCheckptHeight = w.chainParams.
Checkpoints[len(w.chainParams.Checkpoints)-1].Height
}
isCurrent := func(bestHeight int32) bool {
// If the best height is zero, we assume the chain backend is
// still looking for peers to sync to in the case of a global
// network, e.g., testnet and mainnet.
if bestHeight == 0 && !w.isDevEnv() {
return false
}
switch c := chainClient.(type) {
case *chain.NeutrinoClient:
return c.CS.IsCurrent()
}
return bestHeight >= latestCheckptHeight
}
// Determine the latest height known to the chain backend and begin
// scanning the chain from the start height up until this point.
_, bestHeight, err := chainClient.GetBestBlock()
if err != nil {
return err
}
for height := startHeight; height <= bestHeight; height++ {
hash, err := chainClient.GetBlockHash(int64(height))
if err != nil {
return err
}
header, err := chainClient.GetBlockHeader(hash)
if err != nil {
return err
}
if err := onBlock(height, hash, header); err != nil {
return err
}
// If we've reached our best height, we'll wait for blocks at
// tip to ensure we go through all existent blocks in the chain.
// We'll update our bestHeight before checking if we're current
// with the chain to ensure we process any additional blocks
// that came in while we were scanning from our starting point.
for height == bestHeight {
time.Sleep(100 * time.Millisecond)
_, bestHeight, err = chainClient.GetBestBlock()
if err != nil {
return err
}
if isCurrent(bestHeight) {
break
}
}
}
return nil
} | go | func (w *Wallet) scanChain(startHeight int32,
onBlock func(int32, *chainhash.Hash, *wire.BlockHeader) error) error {
chainClient, err := w.requireChainClient()
if err != nil {
return err
}
// isCurrent is a helper function that we'll use to determine if the
// chain backend is currently synced. When running with a btcd or
// bitcoind backend, it will use the height of the latest checkpoint as
// its lower bound.
var latestCheckptHeight int32
if len(w.chainParams.Checkpoints) > 0 {
latestCheckptHeight = w.chainParams.
Checkpoints[len(w.chainParams.Checkpoints)-1].Height
}
isCurrent := func(bestHeight int32) bool {
// If the best height is zero, we assume the chain backend is
// still looking for peers to sync to in the case of a global
// network, e.g., testnet and mainnet.
if bestHeight == 0 && !w.isDevEnv() {
return false
}
switch c := chainClient.(type) {
case *chain.NeutrinoClient:
return c.CS.IsCurrent()
}
return bestHeight >= latestCheckptHeight
}
// Determine the latest height known to the chain backend and begin
// scanning the chain from the start height up until this point.
_, bestHeight, err := chainClient.GetBestBlock()
if err != nil {
return err
}
for height := startHeight; height <= bestHeight; height++ {
hash, err := chainClient.GetBlockHash(int64(height))
if err != nil {
return err
}
header, err := chainClient.GetBlockHeader(hash)
if err != nil {
return err
}
if err := onBlock(height, hash, header); err != nil {
return err
}
// If we've reached our best height, we'll wait for blocks at
// tip to ensure we go through all existent blocks in the chain.
// We'll update our bestHeight before checking if we're current
// with the chain to ensure we process any additional blocks
// that came in while we were scanning from our starting point.
for height == bestHeight {
time.Sleep(100 * time.Millisecond)
_, bestHeight, err = chainClient.GetBestBlock()
if err != nil {
return err
}
if isCurrent(bestHeight) {
break
}
}
}
return nil
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"scanChain",
"(",
"startHeight",
"int32",
",",
"onBlock",
"func",
"(",
"int32",
",",
"*",
"chainhash",
".",
"Hash",
",",
"*",
"wire",
".",
"BlockHeader",
")",
"error",
")",
"error",
"{",
"chainClient",
",",
"err",
":=",
"w",
".",
"requireChainClient",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// isCurrent is a helper function that we'll use to determine if the",
"// chain backend is currently synced. When running with a btcd or",
"// bitcoind backend, it will use the height of the latest checkpoint as",
"// its lower bound.",
"var",
"latestCheckptHeight",
"int32",
"\n",
"if",
"len",
"(",
"w",
".",
"chainParams",
".",
"Checkpoints",
")",
">",
"0",
"{",
"latestCheckptHeight",
"=",
"w",
".",
"chainParams",
".",
"Checkpoints",
"[",
"len",
"(",
"w",
".",
"chainParams",
".",
"Checkpoints",
")",
"-",
"1",
"]",
".",
"Height",
"\n",
"}",
"\n",
"isCurrent",
":=",
"func",
"(",
"bestHeight",
"int32",
")",
"bool",
"{",
"// If the best height is zero, we assume the chain backend is",
"// still looking for peers to sync to in the case of a global",
"// network, e.g., testnet and mainnet.",
"if",
"bestHeight",
"==",
"0",
"&&",
"!",
"w",
".",
"isDevEnv",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"switch",
"c",
":=",
"chainClient",
".",
"(",
"type",
")",
"{",
"case",
"*",
"chain",
".",
"NeutrinoClient",
":",
"return",
"c",
".",
"CS",
".",
"IsCurrent",
"(",
")",
"\n",
"}",
"\n",
"return",
"bestHeight",
">=",
"latestCheckptHeight",
"\n",
"}",
"\n\n",
"// Determine the latest height known to the chain backend and begin",
"// scanning the chain from the start height up until this point.",
"_",
",",
"bestHeight",
",",
"err",
":=",
"chainClient",
".",
"GetBestBlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"height",
":=",
"startHeight",
";",
"height",
"<=",
"bestHeight",
";",
"height",
"++",
"{",
"hash",
",",
"err",
":=",
"chainClient",
".",
"GetBlockHash",
"(",
"int64",
"(",
"height",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"header",
",",
"err",
":=",
"chainClient",
".",
"GetBlockHeader",
"(",
"hash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"onBlock",
"(",
"height",
",",
"hash",
",",
"header",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// If we've reached our best height, we'll wait for blocks at",
"// tip to ensure we go through all existent blocks in the chain.",
"// We'll update our bestHeight before checking if we're current",
"// with the chain to ensure we process any additional blocks",
"// that came in while we were scanning from our starting point.",
"for",
"height",
"==",
"bestHeight",
"{",
"time",
".",
"Sleep",
"(",
"100",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"_",
",",
"bestHeight",
",",
"err",
"=",
"chainClient",
".",
"GetBestBlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"isCurrent",
"(",
"bestHeight",
")",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // scanChain is a helper method that scans the chain from the starting height
// until the tip of the chain. The onBlock callback can be used to perform
// certain operations for every block that we process as we scan the chain. | [
"scanChain",
"is",
"a",
"helper",
"method",
"that",
"scans",
"the",
"chain",
"from",
"the",
"starting",
"height",
"until",
"the",
"tip",
"of",
"the",
"chain",
".",
"The",
"onBlock",
"callback",
"can",
"be",
"used",
"to",
"perform",
"certain",
"operations",
"for",
"every",
"block",
"that",
"we",
"process",
"as",
"we",
"scan",
"the",
"chain",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L468-L539 | train |
btcsuite/btcwallet | wallet/wallet.go | syncToBirthday | func (w *Wallet) syncToBirthday() (*waddrmgr.BlockStamp, error) {
var birthdayStamp *waddrmgr.BlockStamp
birthday := w.Manager.Birthday()
tx, err := w.db.BeginReadWriteTx()
if err != nil {
return nil, err
}
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
// We'll begin scanning the chain from our last sync point until finding
// the first block with a timestamp greater than our birthday. We'll use
// this block to represent our birthday stamp. errDone is an error we'll
// use to signal that we've found it and no longer need to keep scanning
// the chain.
errDone := errors.New("done")
err = w.scanChain(w.Manager.SyncedTo().Height, func(height int32,
hash *chainhash.Hash, header *wire.BlockHeader) error {
if header.Timestamp.After(birthday) {
log.Debugf("Found birthday block: height=%d, hash=%v",
height, hash)
birthdayStamp = &waddrmgr.BlockStamp{
Hash: *hash,
Height: height,
Timestamp: header.Timestamp,
}
err := w.Manager.SetBirthdayBlock(
ns, *birthdayStamp, true,
)
if err != nil {
return err
}
}
err = w.Manager.SetSyncedTo(ns, &waddrmgr.BlockStamp{
Hash: *hash,
Height: height,
Timestamp: header.Timestamp,
})
if err != nil {
return err
}
// Checkpoint our state every 10K blocks.
if height%10000 == 0 {
if err := tx.Commit(); err != nil {
return err
}
log.Infof("Caught up to height %d", height)
tx, err = w.db.BeginReadWriteTx()
if err != nil {
return err
}
ns = tx.ReadWriteBucket(waddrmgrNamespaceKey)
}
// If we've found our birthday, we can return errDone to signal
// that we should stop scanning the chain and persist our state.
if birthdayStamp != nil {
return errDone
}
return nil
})
if err != nil && err != errDone {
tx.Rollback()
return nil, err
}
// If a birthday stamp has yet to be found, we'll return an error
// indicating so, but only if this is a live chain like it is the case
// with testnet and mainnet.
if birthdayStamp == nil && !w.isDevEnv() {
tx.Rollback()
return nil, fmt.Errorf("did not find a suitable birthday "+
"block with a timestamp greater than %v", birthday)
}
// Otherwise, if we're in a development environment and we've yet to
// find a birthday block due to the chain not being current, we'll
// use the last block we've synced to as our birthday to proceed.
if birthdayStamp == nil {
syncedTo := w.Manager.SyncedTo()
err := w.Manager.SetBirthdayBlock(ns, syncedTo, true)
if err != nil {
return nil, err
}
birthdayStamp = &syncedTo
}
if err := tx.Commit(); err != nil {
tx.Rollback()
return nil, err
}
return birthdayStamp, nil
} | go | func (w *Wallet) syncToBirthday() (*waddrmgr.BlockStamp, error) {
var birthdayStamp *waddrmgr.BlockStamp
birthday := w.Manager.Birthday()
tx, err := w.db.BeginReadWriteTx()
if err != nil {
return nil, err
}
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
// We'll begin scanning the chain from our last sync point until finding
// the first block with a timestamp greater than our birthday. We'll use
// this block to represent our birthday stamp. errDone is an error we'll
// use to signal that we've found it and no longer need to keep scanning
// the chain.
errDone := errors.New("done")
err = w.scanChain(w.Manager.SyncedTo().Height, func(height int32,
hash *chainhash.Hash, header *wire.BlockHeader) error {
if header.Timestamp.After(birthday) {
log.Debugf("Found birthday block: height=%d, hash=%v",
height, hash)
birthdayStamp = &waddrmgr.BlockStamp{
Hash: *hash,
Height: height,
Timestamp: header.Timestamp,
}
err := w.Manager.SetBirthdayBlock(
ns, *birthdayStamp, true,
)
if err != nil {
return err
}
}
err = w.Manager.SetSyncedTo(ns, &waddrmgr.BlockStamp{
Hash: *hash,
Height: height,
Timestamp: header.Timestamp,
})
if err != nil {
return err
}
// Checkpoint our state every 10K blocks.
if height%10000 == 0 {
if err := tx.Commit(); err != nil {
return err
}
log.Infof("Caught up to height %d", height)
tx, err = w.db.BeginReadWriteTx()
if err != nil {
return err
}
ns = tx.ReadWriteBucket(waddrmgrNamespaceKey)
}
// If we've found our birthday, we can return errDone to signal
// that we should stop scanning the chain and persist our state.
if birthdayStamp != nil {
return errDone
}
return nil
})
if err != nil && err != errDone {
tx.Rollback()
return nil, err
}
// If a birthday stamp has yet to be found, we'll return an error
// indicating so, but only if this is a live chain like it is the case
// with testnet and mainnet.
if birthdayStamp == nil && !w.isDevEnv() {
tx.Rollback()
return nil, fmt.Errorf("did not find a suitable birthday "+
"block with a timestamp greater than %v", birthday)
}
// Otherwise, if we're in a development environment and we've yet to
// find a birthday block due to the chain not being current, we'll
// use the last block we've synced to as our birthday to proceed.
if birthdayStamp == nil {
syncedTo := w.Manager.SyncedTo()
err := w.Manager.SetBirthdayBlock(ns, syncedTo, true)
if err != nil {
return nil, err
}
birthdayStamp = &syncedTo
}
if err := tx.Commit(); err != nil {
tx.Rollback()
return nil, err
}
return birthdayStamp, nil
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"syncToBirthday",
"(",
")",
"(",
"*",
"waddrmgr",
".",
"BlockStamp",
",",
"error",
")",
"{",
"var",
"birthdayStamp",
"*",
"waddrmgr",
".",
"BlockStamp",
"\n",
"birthday",
":=",
"w",
".",
"Manager",
".",
"Birthday",
"(",
")",
"\n\n",
"tx",
",",
"err",
":=",
"w",
".",
"db",
".",
"BeginReadWriteTx",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"ns",
":=",
"tx",
".",
"ReadWriteBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n\n",
"// We'll begin scanning the chain from our last sync point until finding",
"// the first block with a timestamp greater than our birthday. We'll use",
"// this block to represent our birthday stamp. errDone is an error we'll",
"// use to signal that we've found it and no longer need to keep scanning",
"// the chain.",
"errDone",
":=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"err",
"=",
"w",
".",
"scanChain",
"(",
"w",
".",
"Manager",
".",
"SyncedTo",
"(",
")",
".",
"Height",
",",
"func",
"(",
"height",
"int32",
",",
"hash",
"*",
"chainhash",
".",
"Hash",
",",
"header",
"*",
"wire",
".",
"BlockHeader",
")",
"error",
"{",
"if",
"header",
".",
"Timestamp",
".",
"After",
"(",
"birthday",
")",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"height",
",",
"hash",
")",
"\n\n",
"birthdayStamp",
"=",
"&",
"waddrmgr",
".",
"BlockStamp",
"{",
"Hash",
":",
"*",
"hash",
",",
"Height",
":",
"height",
",",
"Timestamp",
":",
"header",
".",
"Timestamp",
",",
"}",
"\n\n",
"err",
":=",
"w",
".",
"Manager",
".",
"SetBirthdayBlock",
"(",
"ns",
",",
"*",
"birthdayStamp",
",",
"true",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"err",
"=",
"w",
".",
"Manager",
".",
"SetSyncedTo",
"(",
"ns",
",",
"&",
"waddrmgr",
".",
"BlockStamp",
"{",
"Hash",
":",
"*",
"hash",
",",
"Height",
":",
"height",
",",
"Timestamp",
":",
"header",
".",
"Timestamp",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Checkpoint our state every 10K blocks.",
"if",
"height",
"%",
"10000",
"==",
"0",
"{",
"if",
"err",
":=",
"tx",
".",
"Commit",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"height",
")",
"\n\n",
"tx",
",",
"err",
"=",
"w",
".",
"db",
".",
"BeginReadWriteTx",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ns",
"=",
"tx",
".",
"ReadWriteBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"}",
"\n\n",
"// If we've found our birthday, we can return errDone to signal",
"// that we should stop scanning the chain and persist our state.",
"if",
"birthdayStamp",
"!=",
"nil",
"{",
"return",
"errDone",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"errDone",
"{",
"tx",
".",
"Rollback",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// If a birthday stamp has yet to be found, we'll return an error",
"// indicating so, but only if this is a live chain like it is the case",
"// with testnet and mainnet.",
"if",
"birthdayStamp",
"==",
"nil",
"&&",
"!",
"w",
".",
"isDevEnv",
"(",
")",
"{",
"tx",
".",
"Rollback",
"(",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"birthday",
")",
"\n",
"}",
"\n\n",
"// Otherwise, if we're in a development environment and we've yet to",
"// find a birthday block due to the chain not being current, we'll",
"// use the last block we've synced to as our birthday to proceed.",
"if",
"birthdayStamp",
"==",
"nil",
"{",
"syncedTo",
":=",
"w",
".",
"Manager",
".",
"SyncedTo",
"(",
")",
"\n",
"err",
":=",
"w",
".",
"Manager",
".",
"SetBirthdayBlock",
"(",
"ns",
",",
"syncedTo",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"birthdayStamp",
"=",
"&",
"syncedTo",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"tx",
".",
"Commit",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"tx",
".",
"Rollback",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"birthdayStamp",
",",
"nil",
"\n",
"}"
] | // syncToBirthday attempts to sync the wallet's point of view of the chain until
// it finds the first block whose timestamp is above the wallet's birthday. The
// wallet's birthday is already two days in the past of its actual birthday, so
// this is relatively safe to do. | [
"syncToBirthday",
"attempts",
"to",
"sync",
"the",
"wallet",
"s",
"point",
"of",
"view",
"of",
"the",
"chain",
"until",
"it",
"finds",
"the",
"first",
"block",
"whose",
"timestamp",
"is",
"above",
"the",
"wallet",
"s",
"birthday",
".",
"The",
"wallet",
"s",
"birthday",
"is",
"already",
"two",
"days",
"in",
"the",
"past",
"of",
"its",
"actual",
"birthday",
"so",
"this",
"is",
"relatively",
"safe",
"to",
"do",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L545-L646 | train |
btcsuite/btcwallet | wallet/wallet.go | defaultScopeManagers | func (w *Wallet) defaultScopeManagers() (
map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager, error) {
scopedMgrs := make(map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager)
for _, scope := range waddrmgr.DefaultKeyScopes {
scopedMgr, err := w.Manager.FetchScopedKeyManager(scope)
if err != nil {
return nil, err
}
scopedMgrs[scope] = scopedMgr
}
return scopedMgrs, nil
} | go | func (w *Wallet) defaultScopeManagers() (
map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager, error) {
scopedMgrs := make(map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager)
for _, scope := range waddrmgr.DefaultKeyScopes {
scopedMgr, err := w.Manager.FetchScopedKeyManager(scope)
if err != nil {
return nil, err
}
scopedMgrs[scope] = scopedMgr
}
return scopedMgrs, nil
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"defaultScopeManagers",
"(",
")",
"(",
"map",
"[",
"waddrmgr",
".",
"KeyScope",
"]",
"*",
"waddrmgr",
".",
"ScopedKeyManager",
",",
"error",
")",
"{",
"scopedMgrs",
":=",
"make",
"(",
"map",
"[",
"waddrmgr",
".",
"KeyScope",
"]",
"*",
"waddrmgr",
".",
"ScopedKeyManager",
")",
"\n",
"for",
"_",
",",
"scope",
":=",
"range",
"waddrmgr",
".",
"DefaultKeyScopes",
"{",
"scopedMgr",
",",
"err",
":=",
"w",
".",
"Manager",
".",
"FetchScopedKeyManager",
"(",
"scope",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"scopedMgrs",
"[",
"scope",
"]",
"=",
"scopedMgr",
"\n",
"}",
"\n\n",
"return",
"scopedMgrs",
",",
"nil",
"\n",
"}"
] | // defaultScopeManagers fetches the ScopedKeyManagers from the wallet using the
// default set of key scopes. | [
"defaultScopeManagers",
"fetches",
"the",
"ScopedKeyManagers",
"from",
"the",
"wallet",
"using",
"the",
"default",
"set",
"of",
"key",
"scopes",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L776-L790 | train |
btcsuite/btcwallet | wallet/wallet.go | expandScopeHorizons | func expandScopeHorizons(ns walletdb.ReadWriteBucket,
scopedMgr *waddrmgr.ScopedKeyManager,
scopeState *ScopeRecoveryState) error {
// Compute the current external horizon and the number of addresses we
// must derive to ensure we maintain a sufficient recovery window for
// the external branch.
exHorizon, exWindow := scopeState.ExternalBranch.ExtendHorizon()
count, childIndex := uint32(0), exHorizon
for count < exWindow {
keyPath := externalKeyPath(childIndex)
addr, err := scopedMgr.DeriveFromKeyPath(ns, keyPath)
switch {
case err == hdkeychain.ErrInvalidChild:
// Record the existence of an invalid child with the
// external branch's recovery state. This also
// increments the branch's horizon so that it accounts
// for this skipped child index.
scopeState.ExternalBranch.MarkInvalidChild(childIndex)
childIndex++
continue
case err != nil:
return err
}
// Register the newly generated external address and child index
// with the external branch recovery state.
scopeState.ExternalBranch.AddAddr(childIndex, addr.Address())
childIndex++
count++
}
// Compute the current internal horizon and the number of addresses we
// must derive to ensure we maintain a sufficient recovery window for
// the internal branch.
inHorizon, inWindow := scopeState.InternalBranch.ExtendHorizon()
count, childIndex = 0, inHorizon
for count < inWindow {
keyPath := internalKeyPath(childIndex)
addr, err := scopedMgr.DeriveFromKeyPath(ns, keyPath)
switch {
case err == hdkeychain.ErrInvalidChild:
// Record the existence of an invalid child with the
// internal branch's recovery state. This also
// increments the branch's horizon so that it accounts
// for this skipped child index.
scopeState.InternalBranch.MarkInvalidChild(childIndex)
childIndex++
continue
case err != nil:
return err
}
// Register the newly generated internal address and child index
// with the internal branch recovery state.
scopeState.InternalBranch.AddAddr(childIndex, addr.Address())
childIndex++
count++
}
return nil
} | go | func expandScopeHorizons(ns walletdb.ReadWriteBucket,
scopedMgr *waddrmgr.ScopedKeyManager,
scopeState *ScopeRecoveryState) error {
// Compute the current external horizon and the number of addresses we
// must derive to ensure we maintain a sufficient recovery window for
// the external branch.
exHorizon, exWindow := scopeState.ExternalBranch.ExtendHorizon()
count, childIndex := uint32(0), exHorizon
for count < exWindow {
keyPath := externalKeyPath(childIndex)
addr, err := scopedMgr.DeriveFromKeyPath(ns, keyPath)
switch {
case err == hdkeychain.ErrInvalidChild:
// Record the existence of an invalid child with the
// external branch's recovery state. This also
// increments the branch's horizon so that it accounts
// for this skipped child index.
scopeState.ExternalBranch.MarkInvalidChild(childIndex)
childIndex++
continue
case err != nil:
return err
}
// Register the newly generated external address and child index
// with the external branch recovery state.
scopeState.ExternalBranch.AddAddr(childIndex, addr.Address())
childIndex++
count++
}
// Compute the current internal horizon and the number of addresses we
// must derive to ensure we maintain a sufficient recovery window for
// the internal branch.
inHorizon, inWindow := scopeState.InternalBranch.ExtendHorizon()
count, childIndex = 0, inHorizon
for count < inWindow {
keyPath := internalKeyPath(childIndex)
addr, err := scopedMgr.DeriveFromKeyPath(ns, keyPath)
switch {
case err == hdkeychain.ErrInvalidChild:
// Record the existence of an invalid child with the
// internal branch's recovery state. This also
// increments the branch's horizon so that it accounts
// for this skipped child index.
scopeState.InternalBranch.MarkInvalidChild(childIndex)
childIndex++
continue
case err != nil:
return err
}
// Register the newly generated internal address and child index
// with the internal branch recovery state.
scopeState.InternalBranch.AddAddr(childIndex, addr.Address())
childIndex++
count++
}
return nil
} | [
"func",
"expandScopeHorizons",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"scopedMgr",
"*",
"waddrmgr",
".",
"ScopedKeyManager",
",",
"scopeState",
"*",
"ScopeRecoveryState",
")",
"error",
"{",
"// Compute the current external horizon and the number of addresses we",
"// must derive to ensure we maintain a sufficient recovery window for",
"// the external branch.",
"exHorizon",
",",
"exWindow",
":=",
"scopeState",
".",
"ExternalBranch",
".",
"ExtendHorizon",
"(",
")",
"\n",
"count",
",",
"childIndex",
":=",
"uint32",
"(",
"0",
")",
",",
"exHorizon",
"\n",
"for",
"count",
"<",
"exWindow",
"{",
"keyPath",
":=",
"externalKeyPath",
"(",
"childIndex",
")",
"\n",
"addr",
",",
"err",
":=",
"scopedMgr",
".",
"DeriveFromKeyPath",
"(",
"ns",
",",
"keyPath",
")",
"\n",
"switch",
"{",
"case",
"err",
"==",
"hdkeychain",
".",
"ErrInvalidChild",
":",
"// Record the existence of an invalid child with the",
"// external branch's recovery state. This also",
"// increments the branch's horizon so that it accounts",
"// for this skipped child index.",
"scopeState",
".",
"ExternalBranch",
".",
"MarkInvalidChild",
"(",
"childIndex",
")",
"\n",
"childIndex",
"++",
"\n",
"continue",
"\n\n",
"case",
"err",
"!=",
"nil",
":",
"return",
"err",
"\n",
"}",
"\n\n",
"// Register the newly generated external address and child index",
"// with the external branch recovery state.",
"scopeState",
".",
"ExternalBranch",
".",
"AddAddr",
"(",
"childIndex",
",",
"addr",
".",
"Address",
"(",
")",
")",
"\n\n",
"childIndex",
"++",
"\n",
"count",
"++",
"\n",
"}",
"\n\n",
"// Compute the current internal horizon and the number of addresses we",
"// must derive to ensure we maintain a sufficient recovery window for",
"// the internal branch.",
"inHorizon",
",",
"inWindow",
":=",
"scopeState",
".",
"InternalBranch",
".",
"ExtendHorizon",
"(",
")",
"\n",
"count",
",",
"childIndex",
"=",
"0",
",",
"inHorizon",
"\n",
"for",
"count",
"<",
"inWindow",
"{",
"keyPath",
":=",
"internalKeyPath",
"(",
"childIndex",
")",
"\n",
"addr",
",",
"err",
":=",
"scopedMgr",
".",
"DeriveFromKeyPath",
"(",
"ns",
",",
"keyPath",
")",
"\n",
"switch",
"{",
"case",
"err",
"==",
"hdkeychain",
".",
"ErrInvalidChild",
":",
"// Record the existence of an invalid child with the",
"// internal branch's recovery state. This also",
"// increments the branch's horizon so that it accounts",
"// for this skipped child index.",
"scopeState",
".",
"InternalBranch",
".",
"MarkInvalidChild",
"(",
"childIndex",
")",
"\n",
"childIndex",
"++",
"\n",
"continue",
"\n\n",
"case",
"err",
"!=",
"nil",
":",
"return",
"err",
"\n",
"}",
"\n\n",
"// Register the newly generated internal address and child index",
"// with the internal branch recovery state.",
"scopeState",
".",
"InternalBranch",
".",
"AddAddr",
"(",
"childIndex",
",",
"addr",
".",
"Address",
"(",
")",
")",
"\n\n",
"childIndex",
"++",
"\n",
"count",
"++",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // expandScopeHorizons ensures that the ScopeRecoveryState has an adequately
// sized look ahead for both its internal and external branches. The keys
// derived here are added to the scope's recovery state, but do not affect the
// persistent state of the wallet. If any invalid child keys are detected, the
// horizon will be properly extended such that our lookahead always includes the
// proper number of valid child keys. | [
"expandScopeHorizons",
"ensures",
"that",
"the",
"ScopeRecoveryState",
"has",
"an",
"adequately",
"sized",
"look",
"ahead",
"for",
"both",
"its",
"internal",
"and",
"external",
"branches",
".",
"The",
"keys",
"derived",
"here",
"are",
"added",
"to",
"the",
"scope",
"s",
"recovery",
"state",
"but",
"do",
"not",
"affect",
"the",
"persistent",
"state",
"of",
"the",
"wallet",
".",
"If",
"any",
"invalid",
"child",
"keys",
"are",
"detected",
"the",
"horizon",
"will",
"be",
"properly",
"extended",
"such",
"that",
"our",
"lookahead",
"always",
"includes",
"the",
"proper",
"number",
"of",
"valid",
"child",
"keys",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L927-L992 | train |
btcsuite/btcwallet | wallet/wallet.go | newFilterBlocksRequest | func newFilterBlocksRequest(batch []wtxmgr.BlockMeta,
scopedMgrs map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager,
recoveryState *RecoveryState) *chain.FilterBlocksRequest {
filterReq := &chain.FilterBlocksRequest{
Blocks: batch,
ExternalAddrs: make(map[waddrmgr.ScopedIndex]btcutil.Address),
InternalAddrs: make(map[waddrmgr.ScopedIndex]btcutil.Address),
WatchedOutPoints: recoveryState.WatchedOutPoints(),
}
// Populate the external and internal addresses by merging the addresses
// sets belong to all currently tracked scopes.
for scope := range scopedMgrs {
scopeState := recoveryState.StateForScope(scope)
for index, addr := range scopeState.ExternalBranch.Addrs() {
scopedIndex := waddrmgr.ScopedIndex{
Scope: scope,
Index: index,
}
filterReq.ExternalAddrs[scopedIndex] = addr
}
for index, addr := range scopeState.InternalBranch.Addrs() {
scopedIndex := waddrmgr.ScopedIndex{
Scope: scope,
Index: index,
}
filterReq.InternalAddrs[scopedIndex] = addr
}
}
return filterReq
} | go | func newFilterBlocksRequest(batch []wtxmgr.BlockMeta,
scopedMgrs map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager,
recoveryState *RecoveryState) *chain.FilterBlocksRequest {
filterReq := &chain.FilterBlocksRequest{
Blocks: batch,
ExternalAddrs: make(map[waddrmgr.ScopedIndex]btcutil.Address),
InternalAddrs: make(map[waddrmgr.ScopedIndex]btcutil.Address),
WatchedOutPoints: recoveryState.WatchedOutPoints(),
}
// Populate the external and internal addresses by merging the addresses
// sets belong to all currently tracked scopes.
for scope := range scopedMgrs {
scopeState := recoveryState.StateForScope(scope)
for index, addr := range scopeState.ExternalBranch.Addrs() {
scopedIndex := waddrmgr.ScopedIndex{
Scope: scope,
Index: index,
}
filterReq.ExternalAddrs[scopedIndex] = addr
}
for index, addr := range scopeState.InternalBranch.Addrs() {
scopedIndex := waddrmgr.ScopedIndex{
Scope: scope,
Index: index,
}
filterReq.InternalAddrs[scopedIndex] = addr
}
}
return filterReq
} | [
"func",
"newFilterBlocksRequest",
"(",
"batch",
"[",
"]",
"wtxmgr",
".",
"BlockMeta",
",",
"scopedMgrs",
"map",
"[",
"waddrmgr",
".",
"KeyScope",
"]",
"*",
"waddrmgr",
".",
"ScopedKeyManager",
",",
"recoveryState",
"*",
"RecoveryState",
")",
"*",
"chain",
".",
"FilterBlocksRequest",
"{",
"filterReq",
":=",
"&",
"chain",
".",
"FilterBlocksRequest",
"{",
"Blocks",
":",
"batch",
",",
"ExternalAddrs",
":",
"make",
"(",
"map",
"[",
"waddrmgr",
".",
"ScopedIndex",
"]",
"btcutil",
".",
"Address",
")",
",",
"InternalAddrs",
":",
"make",
"(",
"map",
"[",
"waddrmgr",
".",
"ScopedIndex",
"]",
"btcutil",
".",
"Address",
")",
",",
"WatchedOutPoints",
":",
"recoveryState",
".",
"WatchedOutPoints",
"(",
")",
",",
"}",
"\n\n",
"// Populate the external and internal addresses by merging the addresses",
"// sets belong to all currently tracked scopes.",
"for",
"scope",
":=",
"range",
"scopedMgrs",
"{",
"scopeState",
":=",
"recoveryState",
".",
"StateForScope",
"(",
"scope",
")",
"\n",
"for",
"index",
",",
"addr",
":=",
"range",
"scopeState",
".",
"ExternalBranch",
".",
"Addrs",
"(",
")",
"{",
"scopedIndex",
":=",
"waddrmgr",
".",
"ScopedIndex",
"{",
"Scope",
":",
"scope",
",",
"Index",
":",
"index",
",",
"}",
"\n",
"filterReq",
".",
"ExternalAddrs",
"[",
"scopedIndex",
"]",
"=",
"addr",
"\n",
"}",
"\n",
"for",
"index",
",",
"addr",
":=",
"range",
"scopeState",
".",
"InternalBranch",
".",
"Addrs",
"(",
")",
"{",
"scopedIndex",
":=",
"waddrmgr",
".",
"ScopedIndex",
"{",
"Scope",
":",
"scope",
",",
"Index",
":",
"index",
",",
"}",
"\n",
"filterReq",
".",
"InternalAddrs",
"[",
"scopedIndex",
"]",
"=",
"addr",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"filterReq",
"\n",
"}"
] | // newFilterBlocksRequest constructs FilterBlocksRequests using our current
// block range, scoped managers, and recovery state. | [
"newFilterBlocksRequest",
"constructs",
"FilterBlocksRequests",
"using",
"our",
"current",
"block",
"range",
"scoped",
"managers",
"and",
"recovery",
"state",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1014-L1046 | train |
btcsuite/btcwallet | wallet/wallet.go | extendFoundAddresses | func extendFoundAddresses(ns walletdb.ReadWriteBucket,
filterResp *chain.FilterBlocksResponse,
scopedMgrs map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager,
recoveryState *RecoveryState) error {
// Mark all recovered external addresses as used. This will be done only
// for scopes that reported a non-zero number of external addresses in
// this block.
for scope, indexes := range filterResp.FoundExternalAddrs {
// First, report all external child indexes found for this
// scope. This ensures that the external last-found index will
// be updated to include the maximum child index seen thus far.
scopeState := recoveryState.StateForScope(scope)
for index := range indexes {
scopeState.ExternalBranch.ReportFound(index)
}
scopedMgr := scopedMgrs[scope]
// Now, with all found addresses reported, derive and extend all
// external addresses up to and including the current last found
// index for this scope.
exNextUnfound := scopeState.ExternalBranch.NextUnfound()
exLastFound := exNextUnfound
if exLastFound > 0 {
exLastFound--
}
err := scopedMgr.ExtendExternalAddresses(
ns, waddrmgr.DefaultAccountNum, exLastFound,
)
if err != nil {
return err
}
// Finally, with the scope's addresses extended, we mark used
// the external addresses that were found in the block and
// belong to this scope.
for index := range indexes {
addr := scopeState.ExternalBranch.GetAddr(index)
err := scopedMgr.MarkUsed(ns, addr)
if err != nil {
return err
}
}
}
// Mark all recovered internal addresses as used. This will be done only
// for scopes that reported a non-zero number of internal addresses in
// this block.
for scope, indexes := range filterResp.FoundInternalAddrs {
// First, report all internal child indexes found for this
// scope. This ensures that the internal last-found index will
// be updated to include the maximum child index seen thus far.
scopeState := recoveryState.StateForScope(scope)
for index := range indexes {
scopeState.InternalBranch.ReportFound(index)
}
scopedMgr := scopedMgrs[scope]
// Now, with all found addresses reported, derive and extend all
// internal addresses up to and including the current last found
// index for this scope.
inNextUnfound := scopeState.InternalBranch.NextUnfound()
inLastFound := inNextUnfound
if inLastFound > 0 {
inLastFound--
}
err := scopedMgr.ExtendInternalAddresses(
ns, waddrmgr.DefaultAccountNum, inLastFound,
)
if err != nil {
return err
}
// Finally, with the scope's addresses extended, we mark used
// the internal addresses that were found in the blockand belong
// to this scope.
for index := range indexes {
addr := scopeState.InternalBranch.GetAddr(index)
err := scopedMgr.MarkUsed(ns, addr)
if err != nil {
return err
}
}
}
return nil
} | go | func extendFoundAddresses(ns walletdb.ReadWriteBucket,
filterResp *chain.FilterBlocksResponse,
scopedMgrs map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager,
recoveryState *RecoveryState) error {
// Mark all recovered external addresses as used. This will be done only
// for scopes that reported a non-zero number of external addresses in
// this block.
for scope, indexes := range filterResp.FoundExternalAddrs {
// First, report all external child indexes found for this
// scope. This ensures that the external last-found index will
// be updated to include the maximum child index seen thus far.
scopeState := recoveryState.StateForScope(scope)
for index := range indexes {
scopeState.ExternalBranch.ReportFound(index)
}
scopedMgr := scopedMgrs[scope]
// Now, with all found addresses reported, derive and extend all
// external addresses up to and including the current last found
// index for this scope.
exNextUnfound := scopeState.ExternalBranch.NextUnfound()
exLastFound := exNextUnfound
if exLastFound > 0 {
exLastFound--
}
err := scopedMgr.ExtendExternalAddresses(
ns, waddrmgr.DefaultAccountNum, exLastFound,
)
if err != nil {
return err
}
// Finally, with the scope's addresses extended, we mark used
// the external addresses that were found in the block and
// belong to this scope.
for index := range indexes {
addr := scopeState.ExternalBranch.GetAddr(index)
err := scopedMgr.MarkUsed(ns, addr)
if err != nil {
return err
}
}
}
// Mark all recovered internal addresses as used. This will be done only
// for scopes that reported a non-zero number of internal addresses in
// this block.
for scope, indexes := range filterResp.FoundInternalAddrs {
// First, report all internal child indexes found for this
// scope. This ensures that the internal last-found index will
// be updated to include the maximum child index seen thus far.
scopeState := recoveryState.StateForScope(scope)
for index := range indexes {
scopeState.InternalBranch.ReportFound(index)
}
scopedMgr := scopedMgrs[scope]
// Now, with all found addresses reported, derive and extend all
// internal addresses up to and including the current last found
// index for this scope.
inNextUnfound := scopeState.InternalBranch.NextUnfound()
inLastFound := inNextUnfound
if inLastFound > 0 {
inLastFound--
}
err := scopedMgr.ExtendInternalAddresses(
ns, waddrmgr.DefaultAccountNum, inLastFound,
)
if err != nil {
return err
}
// Finally, with the scope's addresses extended, we mark used
// the internal addresses that were found in the blockand belong
// to this scope.
for index := range indexes {
addr := scopeState.InternalBranch.GetAddr(index)
err := scopedMgr.MarkUsed(ns, addr)
if err != nil {
return err
}
}
}
return nil
} | [
"func",
"extendFoundAddresses",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"filterResp",
"*",
"chain",
".",
"FilterBlocksResponse",
",",
"scopedMgrs",
"map",
"[",
"waddrmgr",
".",
"KeyScope",
"]",
"*",
"waddrmgr",
".",
"ScopedKeyManager",
",",
"recoveryState",
"*",
"RecoveryState",
")",
"error",
"{",
"// Mark all recovered external addresses as used. This will be done only",
"// for scopes that reported a non-zero number of external addresses in",
"// this block.",
"for",
"scope",
",",
"indexes",
":=",
"range",
"filterResp",
".",
"FoundExternalAddrs",
"{",
"// First, report all external child indexes found for this",
"// scope. This ensures that the external last-found index will",
"// be updated to include the maximum child index seen thus far.",
"scopeState",
":=",
"recoveryState",
".",
"StateForScope",
"(",
"scope",
")",
"\n",
"for",
"index",
":=",
"range",
"indexes",
"{",
"scopeState",
".",
"ExternalBranch",
".",
"ReportFound",
"(",
"index",
")",
"\n",
"}",
"\n\n",
"scopedMgr",
":=",
"scopedMgrs",
"[",
"scope",
"]",
"\n\n",
"// Now, with all found addresses reported, derive and extend all",
"// external addresses up to and including the current last found",
"// index for this scope.",
"exNextUnfound",
":=",
"scopeState",
".",
"ExternalBranch",
".",
"NextUnfound",
"(",
")",
"\n\n",
"exLastFound",
":=",
"exNextUnfound",
"\n",
"if",
"exLastFound",
">",
"0",
"{",
"exLastFound",
"--",
"\n",
"}",
"\n\n",
"err",
":=",
"scopedMgr",
".",
"ExtendExternalAddresses",
"(",
"ns",
",",
"waddrmgr",
".",
"DefaultAccountNum",
",",
"exLastFound",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Finally, with the scope's addresses extended, we mark used",
"// the external addresses that were found in the block and",
"// belong to this scope.",
"for",
"index",
":=",
"range",
"indexes",
"{",
"addr",
":=",
"scopeState",
".",
"ExternalBranch",
".",
"GetAddr",
"(",
"index",
")",
"\n",
"err",
":=",
"scopedMgr",
".",
"MarkUsed",
"(",
"ns",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Mark all recovered internal addresses as used. This will be done only",
"// for scopes that reported a non-zero number of internal addresses in",
"// this block.",
"for",
"scope",
",",
"indexes",
":=",
"range",
"filterResp",
".",
"FoundInternalAddrs",
"{",
"// First, report all internal child indexes found for this",
"// scope. This ensures that the internal last-found index will",
"// be updated to include the maximum child index seen thus far.",
"scopeState",
":=",
"recoveryState",
".",
"StateForScope",
"(",
"scope",
")",
"\n",
"for",
"index",
":=",
"range",
"indexes",
"{",
"scopeState",
".",
"InternalBranch",
".",
"ReportFound",
"(",
"index",
")",
"\n",
"}",
"\n\n",
"scopedMgr",
":=",
"scopedMgrs",
"[",
"scope",
"]",
"\n\n",
"// Now, with all found addresses reported, derive and extend all",
"// internal addresses up to and including the current last found",
"// index for this scope.",
"inNextUnfound",
":=",
"scopeState",
".",
"InternalBranch",
".",
"NextUnfound",
"(",
")",
"\n\n",
"inLastFound",
":=",
"inNextUnfound",
"\n",
"if",
"inLastFound",
">",
"0",
"{",
"inLastFound",
"--",
"\n",
"}",
"\n",
"err",
":=",
"scopedMgr",
".",
"ExtendInternalAddresses",
"(",
"ns",
",",
"waddrmgr",
".",
"DefaultAccountNum",
",",
"inLastFound",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Finally, with the scope's addresses extended, we mark used",
"// the internal addresses that were found in the blockand belong",
"// to this scope.",
"for",
"index",
":=",
"range",
"indexes",
"{",
"addr",
":=",
"scopeState",
".",
"InternalBranch",
".",
"GetAddr",
"(",
"index",
")",
"\n",
"err",
":=",
"scopedMgr",
".",
"MarkUsed",
"(",
"ns",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // extendFoundAddresses accepts a filter blocks response that contains addresses
// found on chain, and advances the state of all relevant derivation paths to
// match the highest found child index for each branch. | [
"extendFoundAddresses",
"accepts",
"a",
"filter",
"blocks",
"response",
"that",
"contains",
"addresses",
"found",
"on",
"chain",
"and",
"advances",
"the",
"state",
"of",
"all",
"relevant",
"derivation",
"paths",
"to",
"match",
"the",
"highest",
"found",
"child",
"index",
"for",
"each",
"branch",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1051-L1142 | train |
btcsuite/btcwallet | wallet/wallet.go | logFilterBlocksResp | func logFilterBlocksResp(block wtxmgr.BlockMeta,
resp *chain.FilterBlocksResponse) {
// Log the number of external addresses found in this block.
var nFoundExternal int
for _, indexes := range resp.FoundExternalAddrs {
nFoundExternal += len(indexes)
}
if nFoundExternal > 0 {
log.Infof("Recovered %d external addrs at height=%d hash=%v",
nFoundExternal, block.Height, block.Hash)
}
// Log the number of internal addresses found in this block.
var nFoundInternal int
for _, indexes := range resp.FoundInternalAddrs {
nFoundInternal += len(indexes)
}
if nFoundInternal > 0 {
log.Infof("Recovered %d internal addrs at height=%d hash=%v",
nFoundInternal, block.Height, block.Hash)
}
// Log the number of outpoints found in this block.
nFoundOutPoints := len(resp.FoundOutPoints)
if nFoundOutPoints > 0 {
log.Infof("Found %d spends from watched outpoints at "+
"height=%d hash=%v",
nFoundOutPoints, block.Height, block.Hash)
}
} | go | func logFilterBlocksResp(block wtxmgr.BlockMeta,
resp *chain.FilterBlocksResponse) {
// Log the number of external addresses found in this block.
var nFoundExternal int
for _, indexes := range resp.FoundExternalAddrs {
nFoundExternal += len(indexes)
}
if nFoundExternal > 0 {
log.Infof("Recovered %d external addrs at height=%d hash=%v",
nFoundExternal, block.Height, block.Hash)
}
// Log the number of internal addresses found in this block.
var nFoundInternal int
for _, indexes := range resp.FoundInternalAddrs {
nFoundInternal += len(indexes)
}
if nFoundInternal > 0 {
log.Infof("Recovered %d internal addrs at height=%d hash=%v",
nFoundInternal, block.Height, block.Hash)
}
// Log the number of outpoints found in this block.
nFoundOutPoints := len(resp.FoundOutPoints)
if nFoundOutPoints > 0 {
log.Infof("Found %d spends from watched outpoints at "+
"height=%d hash=%v",
nFoundOutPoints, block.Height, block.Hash)
}
} | [
"func",
"logFilterBlocksResp",
"(",
"block",
"wtxmgr",
".",
"BlockMeta",
",",
"resp",
"*",
"chain",
".",
"FilterBlocksResponse",
")",
"{",
"// Log the number of external addresses found in this block.",
"var",
"nFoundExternal",
"int",
"\n",
"for",
"_",
",",
"indexes",
":=",
"range",
"resp",
".",
"FoundExternalAddrs",
"{",
"nFoundExternal",
"+=",
"len",
"(",
"indexes",
")",
"\n",
"}",
"\n",
"if",
"nFoundExternal",
">",
"0",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"nFoundExternal",
",",
"block",
".",
"Height",
",",
"block",
".",
"Hash",
")",
"\n",
"}",
"\n\n",
"// Log the number of internal addresses found in this block.",
"var",
"nFoundInternal",
"int",
"\n",
"for",
"_",
",",
"indexes",
":=",
"range",
"resp",
".",
"FoundInternalAddrs",
"{",
"nFoundInternal",
"+=",
"len",
"(",
"indexes",
")",
"\n",
"}",
"\n",
"if",
"nFoundInternal",
">",
"0",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"nFoundInternal",
",",
"block",
".",
"Height",
",",
"block",
".",
"Hash",
")",
"\n",
"}",
"\n\n",
"// Log the number of outpoints found in this block.",
"nFoundOutPoints",
":=",
"len",
"(",
"resp",
".",
"FoundOutPoints",
")",
"\n",
"if",
"nFoundOutPoints",
">",
"0",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"nFoundOutPoints",
",",
"block",
".",
"Height",
",",
"block",
".",
"Hash",
")",
"\n",
"}",
"\n",
"}"
] | // logFilterBlocksResp provides useful logging information when filtering
// succeeded in finding relevant transactions. | [
"logFilterBlocksResp",
"provides",
"useful",
"logging",
"information",
"when",
"filtering",
"succeeded",
"in",
"finding",
"relevant",
"transactions",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1146-L1176 | train |
btcsuite/btcwallet | wallet/wallet.go | Unlock | func (w *Wallet) Unlock(passphrase []byte, lock <-chan time.Time) error {
err := make(chan error, 1)
w.unlockRequests <- unlockRequest{
passphrase: passphrase,
lockAfter: lock,
err: err,
}
return <-err
} | go | func (w *Wallet) Unlock(passphrase []byte, lock <-chan time.Time) error {
err := make(chan error, 1)
w.unlockRequests <- unlockRequest{
passphrase: passphrase,
lockAfter: lock,
err: err,
}
return <-err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"Unlock",
"(",
"passphrase",
"[",
"]",
"byte",
",",
"lock",
"<-",
"chan",
"time",
".",
"Time",
")",
"error",
"{",
"err",
":=",
"make",
"(",
"chan",
"error",
",",
"1",
")",
"\n",
"w",
".",
"unlockRequests",
"<-",
"unlockRequest",
"{",
"passphrase",
":",
"passphrase",
",",
"lockAfter",
":",
"lock",
",",
"err",
":",
"err",
",",
"}",
"\n",
"return",
"<-",
"err",
"\n",
"}"
] | // Unlock unlocks the wallet's address manager and relocks it after timeout has
// expired. If the wallet is already unlocked and the new passphrase is
// correct, the current timeout is replaced with the new one. The wallet will
// be locked if the passphrase is incorrect or any other error occurs during the
// unlock. | [
"Unlock",
"unlocks",
"the",
"wallet",
"s",
"address",
"manager",
"and",
"relocks",
"it",
"after",
"timeout",
"has",
"expired",
".",
"If",
"the",
"wallet",
"is",
"already",
"unlocked",
"and",
"the",
"new",
"passphrase",
"is",
"correct",
"the",
"current",
"timeout",
"is",
"replaced",
"with",
"the",
"new",
"one",
".",
"The",
"wallet",
"will",
"be",
"locked",
"if",
"the",
"passphrase",
"is",
"incorrect",
"or",
"any",
"other",
"error",
"occurs",
"during",
"the",
"unlock",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1383-L1391 | train |
btcsuite/btcwallet | wallet/wallet.go | ChangePrivatePassphrase | func (w *Wallet) ChangePrivatePassphrase(old, new []byte) error {
err := make(chan error, 1)
w.changePassphrase <- changePassphraseRequest{
old: old,
new: new,
private: true,
err: err,
}
return <-err
} | go | func (w *Wallet) ChangePrivatePassphrase(old, new []byte) error {
err := make(chan error, 1)
w.changePassphrase <- changePassphraseRequest{
old: old,
new: new,
private: true,
err: err,
}
return <-err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"ChangePrivatePassphrase",
"(",
"old",
",",
"new",
"[",
"]",
"byte",
")",
"error",
"{",
"err",
":=",
"make",
"(",
"chan",
"error",
",",
"1",
")",
"\n",
"w",
".",
"changePassphrase",
"<-",
"changePassphraseRequest",
"{",
"old",
":",
"old",
",",
"new",
":",
"new",
",",
"private",
":",
"true",
",",
"err",
":",
"err",
",",
"}",
"\n",
"return",
"<-",
"err",
"\n",
"}"
] | // ChangePrivatePassphrase attempts to change the passphrase for a wallet from
// old to new. Changing the passphrase is synchronized with all other address
// manager locking and unlocking. The lock state will be the same as it was
// before the password change. | [
"ChangePrivatePassphrase",
"attempts",
"to",
"change",
"the",
"passphrase",
"for",
"a",
"wallet",
"from",
"old",
"to",
"new",
".",
"Changing",
"the",
"passphrase",
"is",
"synchronized",
"with",
"all",
"other",
"address",
"manager",
"locking",
"and",
"unlocking",
".",
"The",
"lock",
"state",
"will",
"be",
"the",
"same",
"as",
"it",
"was",
"before",
"the",
"password",
"change",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1435-L1444 | train |
btcsuite/btcwallet | wallet/wallet.go | ChangePublicPassphrase | func (w *Wallet) ChangePublicPassphrase(old, new []byte) error {
err := make(chan error, 1)
w.changePassphrase <- changePassphraseRequest{
old: old,
new: new,
private: false,
err: err,
}
return <-err
} | go | func (w *Wallet) ChangePublicPassphrase(old, new []byte) error {
err := make(chan error, 1)
w.changePassphrase <- changePassphraseRequest{
old: old,
new: new,
private: false,
err: err,
}
return <-err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"ChangePublicPassphrase",
"(",
"old",
",",
"new",
"[",
"]",
"byte",
")",
"error",
"{",
"err",
":=",
"make",
"(",
"chan",
"error",
",",
"1",
")",
"\n",
"w",
".",
"changePassphrase",
"<-",
"changePassphraseRequest",
"{",
"old",
":",
"old",
",",
"new",
":",
"new",
",",
"private",
":",
"false",
",",
"err",
":",
"err",
",",
"}",
"\n",
"return",
"<-",
"err",
"\n",
"}"
] | // ChangePublicPassphrase modifies the public passphrase of the wallet. | [
"ChangePublicPassphrase",
"modifies",
"the",
"public",
"passphrase",
"of",
"the",
"wallet",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1447-L1456 | train |
btcsuite/btcwallet | wallet/wallet.go | ChangePassphrases | func (w *Wallet) ChangePassphrases(publicOld, publicNew, privateOld,
privateNew []byte) error {
err := make(chan error, 1)
w.changePassphrases <- changePassphrasesRequest{
publicOld: publicOld,
publicNew: publicNew,
privateOld: privateOld,
privateNew: privateNew,
err: err,
}
return <-err
} | go | func (w *Wallet) ChangePassphrases(publicOld, publicNew, privateOld,
privateNew []byte) error {
err := make(chan error, 1)
w.changePassphrases <- changePassphrasesRequest{
publicOld: publicOld,
publicNew: publicNew,
privateOld: privateOld,
privateNew: privateNew,
err: err,
}
return <-err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"ChangePassphrases",
"(",
"publicOld",
",",
"publicNew",
",",
"privateOld",
",",
"privateNew",
"[",
"]",
"byte",
")",
"error",
"{",
"err",
":=",
"make",
"(",
"chan",
"error",
",",
"1",
")",
"\n",
"w",
".",
"changePassphrases",
"<-",
"changePassphrasesRequest",
"{",
"publicOld",
":",
"publicOld",
",",
"publicNew",
":",
"publicNew",
",",
"privateOld",
":",
"privateOld",
",",
"privateNew",
":",
"privateNew",
",",
"err",
":",
"err",
",",
"}",
"\n",
"return",
"<-",
"err",
"\n",
"}"
] | // ChangePassphrases modifies the public and private passphrase of the wallet
// atomically. | [
"ChangePassphrases",
"modifies",
"the",
"public",
"and",
"private",
"passphrase",
"of",
"the",
"wallet",
"atomically",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1460-L1472 | train |
btcsuite/btcwallet | wallet/wallet.go | accountUsed | func (w *Wallet) accountUsed(addrmgrNs walletdb.ReadWriteBucket, account uint32) (bool, error) {
var used bool
err := w.Manager.ForEachAccountAddress(addrmgrNs, account,
func(maddr waddrmgr.ManagedAddress) error {
used = maddr.Used(addrmgrNs)
if used {
return waddrmgr.Break
}
return nil
})
if err == waddrmgr.Break {
err = nil
}
return used, err
} | go | func (w *Wallet) accountUsed(addrmgrNs walletdb.ReadWriteBucket, account uint32) (bool, error) {
var used bool
err := w.Manager.ForEachAccountAddress(addrmgrNs, account,
func(maddr waddrmgr.ManagedAddress) error {
used = maddr.Used(addrmgrNs)
if used {
return waddrmgr.Break
}
return nil
})
if err == waddrmgr.Break {
err = nil
}
return used, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"accountUsed",
"(",
"addrmgrNs",
"walletdb",
".",
"ReadWriteBucket",
",",
"account",
"uint32",
")",
"(",
"bool",
",",
"error",
")",
"{",
"var",
"used",
"bool",
"\n",
"err",
":=",
"w",
".",
"Manager",
".",
"ForEachAccountAddress",
"(",
"addrmgrNs",
",",
"account",
",",
"func",
"(",
"maddr",
"waddrmgr",
".",
"ManagedAddress",
")",
"error",
"{",
"used",
"=",
"maddr",
".",
"Used",
"(",
"addrmgrNs",
")",
"\n",
"if",
"used",
"{",
"return",
"waddrmgr",
".",
"Break",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"==",
"waddrmgr",
".",
"Break",
"{",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"used",
",",
"err",
"\n",
"}"
] | // accountUsed returns whether there are any recorded transactions spending to
// a given account. It returns true if atleast one address in the account was
// used and false if no address in the account was used. | [
"accountUsed",
"returns",
"whether",
"there",
"are",
"any",
"recorded",
"transactions",
"spending",
"to",
"a",
"given",
"account",
".",
"It",
"returns",
"true",
"if",
"atleast",
"one",
"address",
"in",
"the",
"account",
"was",
"used",
"and",
"false",
"if",
"no",
"address",
"in",
"the",
"account",
"was",
"used",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1477-L1491 | train |
btcsuite/btcwallet | wallet/wallet.go | AccountAddresses | func (w *Wallet) AccountAddresses(account uint32) (addrs []btcutil.Address, err error) {
err = walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
return w.Manager.ForEachAccountAddress(addrmgrNs, account, func(maddr waddrmgr.ManagedAddress) error {
addrs = append(addrs, maddr.Address())
return nil
})
})
return
} | go | func (w *Wallet) AccountAddresses(account uint32) (addrs []btcutil.Address, err error) {
err = walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
return w.Manager.ForEachAccountAddress(addrmgrNs, account, func(maddr waddrmgr.ManagedAddress) error {
addrs = append(addrs, maddr.Address())
return nil
})
})
return
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"AccountAddresses",
"(",
"account",
"uint32",
")",
"(",
"addrs",
"[",
"]",
"btcutil",
".",
"Address",
",",
"err",
"error",
")",
"{",
"err",
"=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"return",
"w",
".",
"Manager",
".",
"ForEachAccountAddress",
"(",
"addrmgrNs",
",",
"account",
",",
"func",
"(",
"maddr",
"waddrmgr",
".",
"ManagedAddress",
")",
"error",
"{",
"addrs",
"=",
"append",
"(",
"addrs",
",",
"maddr",
".",
"Address",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}",
")",
"\n",
"return",
"\n",
"}"
] | // AccountAddresses returns the addresses for every created address for an
// account. | [
"AccountAddresses",
"returns",
"the",
"addresses",
"for",
"every",
"created",
"address",
"for",
"an",
"account",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1495-L1504 | train |
btcsuite/btcwallet | wallet/wallet.go | CalculateAccountBalances | func (w *Wallet) CalculateAccountBalances(account uint32, confirms int32) (Balances, error) {
var bals Balances
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
// Get current block. The block height used for calculating
// the number of tx confirmations.
syncBlock := w.Manager.SyncedTo()
unspent, err := w.TxStore.UnspentOutputs(txmgrNs)
if err != nil {
return err
}
for i := range unspent {
output := &unspent[i]
var outputAcct uint32
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
output.PkScript, w.chainParams)
if err == nil && len(addrs) > 0 {
_, outputAcct, err = w.Manager.AddrAccount(addrmgrNs, addrs[0])
}
if err != nil || outputAcct != account {
continue
}
bals.Total += output.Amount
if output.FromCoinBase && !confirmed(int32(w.chainParams.CoinbaseMaturity),
output.Height, syncBlock.Height) {
bals.ImmatureReward += output.Amount
} else if confirmed(confirms, output.Height, syncBlock.Height) {
bals.Spendable += output.Amount
}
}
return nil
})
return bals, err
} | go | func (w *Wallet) CalculateAccountBalances(account uint32, confirms int32) (Balances, error) {
var bals Balances
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
// Get current block. The block height used for calculating
// the number of tx confirmations.
syncBlock := w.Manager.SyncedTo()
unspent, err := w.TxStore.UnspentOutputs(txmgrNs)
if err != nil {
return err
}
for i := range unspent {
output := &unspent[i]
var outputAcct uint32
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
output.PkScript, w.chainParams)
if err == nil && len(addrs) > 0 {
_, outputAcct, err = w.Manager.AddrAccount(addrmgrNs, addrs[0])
}
if err != nil || outputAcct != account {
continue
}
bals.Total += output.Amount
if output.FromCoinBase && !confirmed(int32(w.chainParams.CoinbaseMaturity),
output.Height, syncBlock.Height) {
bals.ImmatureReward += output.Amount
} else if confirmed(confirms, output.Height, syncBlock.Height) {
bals.Spendable += output.Amount
}
}
return nil
})
return bals, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"CalculateAccountBalances",
"(",
"account",
"uint32",
",",
"confirms",
"int32",
")",
"(",
"Balances",
",",
"error",
")",
"{",
"var",
"bals",
"Balances",
"\n",
"err",
":=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"txmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"wtxmgrNamespaceKey",
")",
"\n\n",
"// Get current block. The block height used for calculating",
"// the number of tx confirmations.",
"syncBlock",
":=",
"w",
".",
"Manager",
".",
"SyncedTo",
"(",
")",
"\n\n",
"unspent",
",",
"err",
":=",
"w",
".",
"TxStore",
".",
"UnspentOutputs",
"(",
"txmgrNs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"i",
":=",
"range",
"unspent",
"{",
"output",
":=",
"&",
"unspent",
"[",
"i",
"]",
"\n\n",
"var",
"outputAcct",
"uint32",
"\n",
"_",
",",
"addrs",
",",
"_",
",",
"err",
":=",
"txscript",
".",
"ExtractPkScriptAddrs",
"(",
"output",
".",
"PkScript",
",",
"w",
".",
"chainParams",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"len",
"(",
"addrs",
")",
">",
"0",
"{",
"_",
",",
"outputAcct",
",",
"err",
"=",
"w",
".",
"Manager",
".",
"AddrAccount",
"(",
"addrmgrNs",
",",
"addrs",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"outputAcct",
"!=",
"account",
"{",
"continue",
"\n",
"}",
"\n\n",
"bals",
".",
"Total",
"+=",
"output",
".",
"Amount",
"\n",
"if",
"output",
".",
"FromCoinBase",
"&&",
"!",
"confirmed",
"(",
"int32",
"(",
"w",
".",
"chainParams",
".",
"CoinbaseMaturity",
")",
",",
"output",
".",
"Height",
",",
"syncBlock",
".",
"Height",
")",
"{",
"bals",
".",
"ImmatureReward",
"+=",
"output",
".",
"Amount",
"\n",
"}",
"else",
"if",
"confirmed",
"(",
"confirms",
",",
"output",
".",
"Height",
",",
"syncBlock",
".",
"Height",
")",
"{",
"bals",
".",
"Spendable",
"+=",
"output",
".",
"Amount",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"bals",
",",
"err",
"\n",
"}"
] | // CalculateAccountBalances sums the amounts of all unspent transaction
// outputs to the given account of a wallet and returns the balance.
//
// This function is much slower than it needs to be since transactions outputs
// are not indexed by the accounts they credit to, and all unspent transaction
// outputs must be iterated. | [
"CalculateAccountBalances",
"sums",
"the",
"amounts",
"of",
"all",
"unspent",
"transaction",
"outputs",
"to",
"the",
"given",
"account",
"of",
"a",
"wallet",
"and",
"returns",
"the",
"balance",
".",
"This",
"function",
"is",
"much",
"slower",
"than",
"it",
"needs",
"to",
"be",
"since",
"transactions",
"outputs",
"are",
"not",
"indexed",
"by",
"the",
"accounts",
"they",
"credit",
"to",
"and",
"all",
"unspent",
"transaction",
"outputs",
"must",
"be",
"iterated",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1540-L1578 | train |
btcsuite/btcwallet | wallet/wallet.go | PubKeyForAddress | func (w *Wallet) PubKeyForAddress(a btcutil.Address) (*btcec.PublicKey, error) {
var pubKey *btcec.PublicKey
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
managedAddr, err := w.Manager.Address(addrmgrNs, a)
if err != nil {
return err
}
managedPubKeyAddr, ok := managedAddr.(waddrmgr.ManagedPubKeyAddress)
if !ok {
return errors.New("address does not have an associated public key")
}
pubKey = managedPubKeyAddr.PubKey()
return nil
})
return pubKey, err
} | go | func (w *Wallet) PubKeyForAddress(a btcutil.Address) (*btcec.PublicKey, error) {
var pubKey *btcec.PublicKey
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
managedAddr, err := w.Manager.Address(addrmgrNs, a)
if err != nil {
return err
}
managedPubKeyAddr, ok := managedAddr.(waddrmgr.ManagedPubKeyAddress)
if !ok {
return errors.New("address does not have an associated public key")
}
pubKey = managedPubKeyAddr.PubKey()
return nil
})
return pubKey, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"PubKeyForAddress",
"(",
"a",
"btcutil",
".",
"Address",
")",
"(",
"*",
"btcec",
".",
"PublicKey",
",",
"error",
")",
"{",
"var",
"pubKey",
"*",
"btcec",
".",
"PublicKey",
"\n",
"err",
":=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"managedAddr",
",",
"err",
":=",
"w",
".",
"Manager",
".",
"Address",
"(",
"addrmgrNs",
",",
"a",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"managedPubKeyAddr",
",",
"ok",
":=",
"managedAddr",
".",
"(",
"waddrmgr",
".",
"ManagedPubKeyAddress",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"pubKey",
"=",
"managedPubKeyAddr",
".",
"PubKey",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"pubKey",
",",
"err",
"\n",
"}"
] | // PubKeyForAddress looks up the associated public key for a P2PKH address. | [
"PubKeyForAddress",
"looks",
"up",
"the",
"associated",
"public",
"key",
"for",
"a",
"P2PKH",
"address",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1644-L1660 | train |
btcsuite/btcwallet | wallet/wallet.go | PrivKeyForAddress | func (w *Wallet) PrivKeyForAddress(a btcutil.Address) (*btcec.PrivateKey, error) {
var privKey *btcec.PrivateKey
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
managedAddr, err := w.Manager.Address(addrmgrNs, a)
if err != nil {
return err
}
managedPubKeyAddr, ok := managedAddr.(waddrmgr.ManagedPubKeyAddress)
if !ok {
return errors.New("address does not have an associated private key")
}
privKey, err = managedPubKeyAddr.PrivKey()
return err
})
return privKey, err
} | go | func (w *Wallet) PrivKeyForAddress(a btcutil.Address) (*btcec.PrivateKey, error) {
var privKey *btcec.PrivateKey
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
managedAddr, err := w.Manager.Address(addrmgrNs, a)
if err != nil {
return err
}
managedPubKeyAddr, ok := managedAddr.(waddrmgr.ManagedPubKeyAddress)
if !ok {
return errors.New("address does not have an associated private key")
}
privKey, err = managedPubKeyAddr.PrivKey()
return err
})
return privKey, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"PrivKeyForAddress",
"(",
"a",
"btcutil",
".",
"Address",
")",
"(",
"*",
"btcec",
".",
"PrivateKey",
",",
"error",
")",
"{",
"var",
"privKey",
"*",
"btcec",
".",
"PrivateKey",
"\n",
"err",
":=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"managedAddr",
",",
"err",
":=",
"w",
".",
"Manager",
".",
"Address",
"(",
"addrmgrNs",
",",
"a",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"managedPubKeyAddr",
",",
"ok",
":=",
"managedAddr",
".",
"(",
"waddrmgr",
".",
"ManagedPubKeyAddress",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"privKey",
",",
"err",
"=",
"managedPubKeyAddr",
".",
"PrivKey",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"return",
"privKey",
",",
"err",
"\n",
"}"
] | // PrivKeyForAddress looks up the associated private key for a P2PKH or P2PK
// address. | [
"PrivKeyForAddress",
"looks",
"up",
"the",
"associated",
"private",
"key",
"for",
"a",
"P2PKH",
"or",
"P2PK",
"address",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1664-L1680 | train |
btcsuite/btcwallet | wallet/wallet.go | HaveAddress | func (w *Wallet) HaveAddress(a btcutil.Address) (bool, error) {
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
_, err := w.Manager.Address(addrmgrNs, a)
return err
})
if err == nil {
return true, nil
}
if waddrmgr.IsError(err, waddrmgr.ErrAddressNotFound) {
return false, nil
}
return false, err
} | go | func (w *Wallet) HaveAddress(a btcutil.Address) (bool, error) {
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
_, err := w.Manager.Address(addrmgrNs, a)
return err
})
if err == nil {
return true, nil
}
if waddrmgr.IsError(err, waddrmgr.ErrAddressNotFound) {
return false, nil
}
return false, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"HaveAddress",
"(",
"a",
"btcutil",
".",
"Address",
")",
"(",
"bool",
",",
"error",
")",
"{",
"err",
":=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"_",
",",
"err",
":=",
"w",
".",
"Manager",
".",
"Address",
"(",
"addrmgrNs",
",",
"a",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"if",
"waddrmgr",
".",
"IsError",
"(",
"err",
",",
"waddrmgr",
".",
"ErrAddressNotFound",
")",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"return",
"false",
",",
"err",
"\n",
"}"
] | // HaveAddress returns whether the wallet is the owner of the address a. | [
"HaveAddress",
"returns",
"whether",
"the",
"wallet",
"is",
"the",
"owner",
"of",
"the",
"address",
"a",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L1683-L1696 | train |
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",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"var",
"err",
"error",
"\n",
"_",
",",
"account",
",",
"err",
"=",
"w",
".",
"Manager",
".",
"AddrAccount",
"(",
"addrmgrNs",
",",
"a",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"return",
"account",
",",
"err",
"\n",
"}"
] | // 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",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"var",
"err",
"error",
"\n",
"managedAddress",
",",
"err",
"=",
"w",
".",
"Manager",
".",
"Address",
"(",
"addrmgrNs",
",",
"a",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"return",
"managedAddress",
",",
"err",
"\n",
"}"
] | // 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",
"(",
"scope",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"account",
"uint32",
"\n",
"err",
"=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"var",
"err",
"error",
"\n",
"account",
",",
"err",
"=",
"manager",
".",
"LookupAccount",
"(",
"addrmgrNs",
",",
"accountName",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"return",
"account",
",",
"err",
"\n",
"}"
] | // 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",
".",
"FetchScopedKeyManager",
"(",
"scope",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"props",
"*",
"waddrmgr",
".",
"AccountProperties",
"\n",
"err",
"=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"waddrmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"var",
"err",
"error",
"\n",
"props",
",",
"err",
"=",
"manager",
".",
"AccountProperties",
"(",
"waddrmgrNs",
",",
"acct",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"return",
"props",
",",
"err",
"\n",
"}"
] | // 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",
"based",
"on",
"the",
"address",
"pools",
"."
] | 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",
"(",
"scope",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"var",
"props",
"*",
"waddrmgr",
".",
"AccountProperties",
"\n",
"err",
"=",
"walletdb",
".",
"Update",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadWriteTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadWriteBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"err",
":=",
"manager",
".",
"RenameAccount",
"(",
"addrmgrNs",
",",
"account",
",",
"newName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"props",
",",
"err",
"=",
"manager",
".",
"AccountProperties",
"(",
"addrmgrNs",
",",
"account",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"w",
".",
"NtfnServer",
".",
"notifyAccountProperties",
"(",
"props",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // 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",
".",
"ListTransactionsResult",
"{",
"}",
"\n",
"err",
":=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"txmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"wtxmgrNamespaceKey",
")",
"\n\n",
"rangeFn",
":=",
"func",
"(",
"details",
"[",
"]",
"wtxmgr",
".",
"TxDetails",
")",
"(",
"bool",
",",
"error",
")",
"{",
"for",
"_",
",",
"detail",
":=",
"range",
"details",
"{",
"jsonResults",
":=",
"listTransactions",
"(",
"tx",
",",
"&",
"detail",
",",
"w",
".",
"Manager",
",",
"syncHeight",
",",
"w",
".",
"chainParams",
")",
"\n",
"txList",
"=",
"append",
"(",
"txList",
",",
"jsonResults",
"...",
")",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"w",
".",
"TxStore",
".",
"RangeTransactions",
"(",
"txmgrNs",
",",
"start",
",",
"end",
",",
"rangeFn",
")",
"\n",
"}",
")",
"\n",
"return",
"txList",
",",
"err",
"\n",
"}"
] | // 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",
"intended",
"to",
"be",
"used",
"for",
"listsinceblock",
"RPC",
"replies",
"."
] | 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",
"{",
"}",
"\n\n",
"err",
":=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"txmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"wtxmgrNamespaceKey",
")",
"\n\n",
"// Get current block. The block height used for calculating",
"// the number of tx confirmations.",
"syncBlock",
":=",
"w",
".",
"Manager",
".",
"SyncedTo",
"(",
")",
"\n\n",
"// Need to skip the first from transactions, and after those, only",
"// include the next count transactions.",
"skipped",
":=",
"0",
"\n",
"n",
":=",
"0",
"\n\n",
"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",
"++",
"\n",
"continue",
"\n",
"}",
"\n\n",
"n",
"++",
"\n",
"if",
"n",
">",
"count",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n\n",
"jsonResults",
":=",
"listTransactions",
"(",
"tx",
",",
"&",
"details",
"[",
"i",
"]",
",",
"w",
".",
"Manager",
",",
"syncBlock",
".",
"Height",
",",
"w",
".",
"chainParams",
")",
"\n",
"txList",
"=",
"append",
"(",
"txList",
",",
"jsonResults",
"...",
")",
"\n\n",
"if",
"len",
"(",
"jsonResults",
")",
">",
"0",
"{",
"n",
"++",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"// Return newer results first by starting at mempool height and working",
"// down to the genesis block.",
"return",
"w",
".",
"TxStore",
".",
"RangeTransactions",
"(",
"txmgrNs",
",",
"-",
"1",
",",
"0",
",",
"rangeFn",
")",
"\n",
"}",
")",
"\n",
"return",
"txList",
",",
"err",
"\n",
"}"
] | // 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",
".",
"ListTransactionsResult",
"{",
"}",
"\n",
"err",
":=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"txmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"wtxmgrNamespaceKey",
")",
"\n\n",
"// Get current block. The block height used for calculating",
"// the number of tx confirmations.",
"syncBlock",
":=",
"w",
".",
"Manager",
".",
"SyncedTo",
"(",
")",
"\n",
"rangeFn",
":=",
"func",
"(",
"details",
"[",
"]",
"wtxmgr",
".",
"TxDetails",
")",
"(",
"bool",
",",
"error",
")",
"{",
"loopDetails",
":",
"for",
"i",
":=",
"range",
"details",
"{",
"detail",
":=",
"&",
"details",
"[",
"i",
"]",
"\n\n",
"for",
"_",
",",
"cred",
":=",
"range",
"detail",
".",
"Credits",
"{",
"pkScript",
":=",
"detail",
".",
"MsgTx",
".",
"TxOut",
"[",
"cred",
".",
"Index",
"]",
".",
"PkScript",
"\n",
"_",
",",
"addrs",
",",
"_",
",",
"err",
":=",
"txscript",
".",
"ExtractPkScriptAddrs",
"(",
"pkScript",
",",
"w",
".",
"chainParams",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"len",
"(",
"addrs",
")",
"!=",
"1",
"{",
"continue",
"\n",
"}",
"\n",
"apkh",
",",
"ok",
":=",
"addrs",
"[",
"0",
"]",
".",
"(",
"*",
"btcutil",
".",
"AddressPubKeyHash",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"_",
",",
"ok",
"=",
"pkHashes",
"[",
"string",
"(",
"apkh",
".",
"ScriptAddress",
"(",
")",
")",
"]",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n\n",
"jsonResults",
":=",
"listTransactions",
"(",
"tx",
",",
"detail",
",",
"w",
".",
"Manager",
",",
"syncBlock",
".",
"Height",
",",
"w",
".",
"chainParams",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"txList",
"=",
"append",
"(",
"txList",
",",
"jsonResults",
"...",
")",
"\n",
"continue",
"loopDetails",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"w",
".",
"TxStore",
".",
"RangeTransactions",
"(",
"txmgrNs",
",",
"0",
",",
"-",
"1",
",",
"rangeFn",
")",
"\n",
"}",
")",
"\n",
"return",
"txList",
",",
"err",
"\n",
"}"
] | // 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",
"listaddresstransactions",
"RPC",
"replies",
"."
] | 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",
".",
"FetchScopedKeyManager",
"(",
"scope",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"results",
"[",
"]",
"AccountBalanceResult",
"\n",
"err",
"=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"txmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"wtxmgrNamespaceKey",
")",
"\n\n",
"syncBlock",
":=",
"w",
".",
"Manager",
".",
"SyncedTo",
"(",
")",
"\n\n",
"// Fill out all account info except for the balances.",
"lastAcct",
",",
"err",
":=",
"manager",
".",
"LastAccount",
"(",
"addrmgrNs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"results",
"=",
"make",
"(",
"[",
"]",
"AccountBalanceResult",
",",
"lastAcct",
"+",
"2",
")",
"\n",
"for",
"i",
":=",
"range",
"results",
"[",
":",
"len",
"(",
"results",
")",
"-",
"1",
"]",
"{",
"accountName",
",",
"err",
":=",
"manager",
".",
"AccountName",
"(",
"addrmgrNs",
",",
"uint32",
"(",
"i",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"results",
"[",
"i",
"]",
".",
"AccountNumber",
"=",
"uint32",
"(",
"i",
")",
"\n",
"results",
"[",
"i",
"]",
".",
"AccountName",
"=",
"accountName",
"\n",
"}",
"\n",
"results",
"[",
"len",
"(",
"results",
")",
"-",
"1",
"]",
".",
"AccountNumber",
"=",
"waddrmgr",
".",
"ImportedAddrAccount",
"\n",
"results",
"[",
"len",
"(",
"results",
")",
"-",
"1",
"]",
".",
"AccountName",
"=",
"waddrmgr",
".",
"ImportedAddrAccountName",
"\n\n",
"// 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",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"i",
":=",
"range",
"unspentOutputs",
"{",
"output",
":=",
"&",
"unspentOutputs",
"[",
"i",
"]",
"\n",
"if",
"!",
"confirmed",
"(",
"requiredConfs",
",",
"output",
".",
"Height",
",",
"syncBlock",
".",
"Height",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"output",
".",
"FromCoinBase",
"&&",
"!",
"confirmed",
"(",
"int32",
"(",
"w",
".",
"ChainParams",
"(",
")",
".",
"CoinbaseMaturity",
")",
",",
"output",
".",
"Height",
",",
"syncBlock",
".",
"Height",
")",
"{",
"continue",
"\n",
"}",
"\n",
"_",
",",
"addrs",
",",
"_",
",",
"err",
":=",
"txscript",
".",
"ExtractPkScriptAddrs",
"(",
"output",
".",
"PkScript",
",",
"w",
".",
"chainParams",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"len",
"(",
"addrs",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"outputAcct",
",",
"err",
":=",
"manager",
".",
"AddrAccount",
"(",
"addrmgrNs",
",",
"addrs",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"switch",
"{",
"case",
"outputAcct",
"==",
"waddrmgr",
".",
"ImportedAddrAccount",
":",
"results",
"[",
"len",
"(",
"results",
")",
"-",
"1",
"]",
".",
"AccountBalance",
"+=",
"output",
".",
"Amount",
"\n",
"case",
"outputAcct",
">",
"lastAcct",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"default",
":",
"results",
"[",
"outputAcct",
"]",
".",
"AccountBalance",
"+=",
"output",
".",
"Amount",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"results",
",",
"err",
"\n",
"}"
] | // 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",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"// 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",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Only those addresses with keys needed.",
"pka",
",",
"ok",
":=",
"ma",
".",
"(",
"waddrmgr",
".",
"ManagedPubKeyAddress",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"wif",
",",
"err",
":=",
"pka",
".",
"ExportPrivKey",
"(",
")",
"\n",
"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",
"\n",
"}",
"\n",
"privkeys",
"=",
"append",
"(",
"privkeys",
",",
"wif",
".",
"String",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}",
")",
"\n",
"return",
"privkeys",
",",
"err",
"\n",
"}"
] | // 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",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"waddrmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"// Get private key from wallet if it exists.",
"var",
"err",
"error",
"\n",
"maddr",
",",
"err",
"=",
"w",
".",
"Manager",
".",
"Address",
"(",
"waddrmgrNs",
",",
"addr",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"pka",
",",
"ok",
":=",
"maddr",
".",
"(",
"waddrmgr",
".",
"ManagedPubKeyAddress",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"}",
"\n\n",
"wif",
",",
"err",
":=",
"pka",
".",
"ExportPrivKey",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"wif",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}"
] | // 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",
"i",
":=",
"0",
"\n",
"for",
"op",
":=",
"range",
"w",
".",
"lockedOutpoints",
"{",
"locked",
"[",
"i",
"]",
"=",
"btcjson",
".",
"TransactionInput",
"{",
"Txid",
":",
"op",
".",
"Hash",
".",
"String",
"(",
")",
",",
"Vout",
":",
"op",
".",
"Index",
",",
"}",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"return",
"locked",
"\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",
")",
"error",
"{",
"txmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"wtxmgrNamespaceKey",
")",
"\n",
"var",
"err",
"error",
"\n",
"txs",
",",
"err",
"=",
"w",
".",
"TxStore",
".",
"UnminedTxs",
"(",
"txmgrNs",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"tx",
":=",
"range",
"txs",
"{",
"txHash",
",",
"err",
":=",
"w",
".",
"publishTransaction",
"(",
"tx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"tx",
".",
"TxHash",
"(",
")",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"txHash",
")",
"\n",
"}",
"\n",
"}"
] | // 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",
"server",
"for",
"relay",
"."
] | 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",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"return",
"w",
".",
"Manager",
".",
"ForEachActiveAddress",
"(",
"addrmgrNs",
",",
"func",
"(",
"addr",
"btcutil",
".",
"Address",
")",
"error",
"{",
"addrStrs",
"=",
"append",
"(",
"addrStrs",
",",
"addr",
".",
"EncodeAddress",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"sort",
".",
"Sort",
"(",
"sort",
".",
"StringSlice",
"(",
"addrStrs",
")",
")",
"\n",
"return",
"addrStrs",
",",
"nil",
"\n",
"}"
] | // 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",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"(",
"addr",
"btcutil",
".",
"Address",
"\n",
"props",
"*",
"waddrmgr",
".",
"AccountProperties",
"\n",
")",
"\n",
"err",
"=",
"walletdb",
".",
"Update",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadWriteTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadWriteBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"var",
"err",
"error",
"\n",
"addr",
",",
"props",
",",
"err",
"=",
"w",
".",
"newAddress",
"(",
"addrmgrNs",
",",
"account",
",",
"scope",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Notify the rpc server about the newly created address.",
"err",
"=",
"chainClient",
".",
"NotifyReceived",
"(",
"[",
"]",
"btcutil",
".",
"Address",
"{",
"addr",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"w",
".",
"NtfnServer",
".",
"notifyAccountProperties",
"(",
"props",
")",
"\n\n",
"return",
"addr",
",",
"nil",
"\n",
"}"
] | // 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",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"addr",
"btcutil",
".",
"Address",
"\n",
"err",
"=",
"walletdb",
".",
"Update",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadWriteTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadWriteBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"var",
"err",
"error",
"\n",
"addr",
",",
"err",
"=",
"w",
".",
"newChangeAddress",
"(",
"addrmgrNs",
",",
"account",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Notify the rpc server about the newly created address.",
"err",
"=",
"chainClient",
".",
"NotifyReceived",
"(",
"[",
"]",
"btcutil",
".",
"Address",
"{",
"addr",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"addr",
",",
"nil",
"\n",
"}"
] | // 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",
".",
"FetchScopedKeyManager",
"(",
"scope",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"results",
"[",
"]",
"AccountTotalReceivedResult",
"\n",
"err",
"=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"txmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"wtxmgrNamespaceKey",
")",
"\n\n",
"syncBlock",
":=",
"w",
".",
"Manager",
".",
"SyncedTo",
"(",
")",
"\n\n",
"err",
":=",
"manager",
".",
"ForEachAccount",
"(",
"addrmgrNs",
",",
"func",
"(",
"account",
"uint32",
")",
"error",
"{",
"accountName",
",",
"err",
":=",
"manager",
".",
"AccountName",
"(",
"addrmgrNs",
",",
"account",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"results",
"=",
"append",
"(",
"results",
",",
"AccountTotalReceivedResult",
"{",
"AccountNumber",
":",
"account",
",",
"AccountName",
":",
"accountName",
",",
"}",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"var",
"stopHeight",
"int32",
"\n\n",
"if",
"minConf",
">",
"0",
"{",
"stopHeight",
"=",
"syncBlock",
".",
"Height",
"-",
"minConf",
"+",
"1",
"\n",
"}",
"else",
"{",
"stopHeight",
"=",
"-",
"1",
"\n",
"}",
"\n\n",
"rangeFn",
":=",
"func",
"(",
"details",
"[",
"]",
"wtxmgr",
".",
"TxDetails",
")",
"(",
"bool",
",",
"error",
")",
"{",
"for",
"i",
":=",
"range",
"details",
"{",
"detail",
":=",
"&",
"details",
"[",
"i",
"]",
"\n",
"for",
"_",
",",
"cred",
":=",
"range",
"detail",
".",
"Credits",
"{",
"pkScript",
":=",
"detail",
".",
"MsgTx",
".",
"TxOut",
"[",
"cred",
".",
"Index",
"]",
".",
"PkScript",
"\n",
"var",
"outputAcct",
"uint32",
"\n",
"_",
",",
"addrs",
",",
"_",
",",
"err",
":=",
"txscript",
".",
"ExtractPkScriptAddrs",
"(",
"pkScript",
",",
"w",
".",
"chainParams",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"len",
"(",
"addrs",
")",
">",
"0",
"{",
"_",
",",
"outputAcct",
",",
"err",
"=",
"w",
".",
"Manager",
".",
"AddrAccount",
"(",
"addrmgrNs",
",",
"addrs",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"{",
"acctIndex",
":=",
"int",
"(",
"outputAcct",
")",
"\n",
"if",
"outputAcct",
"==",
"waddrmgr",
".",
"ImportedAddrAccount",
"{",
"acctIndex",
"=",
"len",
"(",
"results",
")",
"-",
"1",
"\n",
"}",
"\n",
"res",
":=",
"&",
"results",
"[",
"acctIndex",
"]",
"\n",
"res",
".",
"TotalReceived",
"+=",
"cred",
".",
"Amount",
"\n",
"res",
".",
"LastConfirmation",
"=",
"confirms",
"(",
"detail",
".",
"Block",
".",
"Height",
",",
"syncBlock",
".",
"Height",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"return",
"w",
".",
"TxStore",
".",
"RangeTransactions",
"(",
"txmgrNs",
",",
"0",
",",
"stopHeight",
",",
"rangeFn",
")",
"\n",
"}",
")",
"\n",
"return",
"results",
",",
"err",
"\n",
"}"
] | // 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",
":=",
"walletdb",
".",
"View",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadTx",
")",
"error",
"{",
"txmgrNs",
":=",
"tx",
".",
"ReadBucket",
"(",
"wtxmgrNamespaceKey",
")",
"\n\n",
"syncBlock",
":=",
"w",
".",
"Manager",
".",
"SyncedTo",
"(",
")",
"\n\n",
"var",
"(",
"addrStr",
"=",
"addr",
".",
"EncodeAddress",
"(",
")",
"\n",
"stopHeight",
"int32",
"\n",
")",
"\n\n",
"if",
"minConf",
">",
"0",
"{",
"stopHeight",
"=",
"syncBlock",
".",
"Height",
"-",
"minConf",
"+",
"1",
"\n",
"}",
"else",
"{",
"stopHeight",
"=",
"-",
"1",
"\n",
"}",
"\n",
"rangeFn",
":=",
"func",
"(",
"details",
"[",
"]",
"wtxmgr",
".",
"TxDetails",
")",
"(",
"bool",
",",
"error",
")",
"{",
"for",
"i",
":=",
"range",
"details",
"{",
"detail",
":=",
"&",
"details",
"[",
"i",
"]",
"\n",
"for",
"_",
",",
"cred",
":=",
"range",
"detail",
".",
"Credits",
"{",
"pkScript",
":=",
"detail",
".",
"MsgTx",
".",
"TxOut",
"[",
"cred",
".",
"Index",
"]",
".",
"PkScript",
"\n",
"_",
",",
"addrs",
",",
"_",
",",
"err",
":=",
"txscript",
".",
"ExtractPkScriptAddrs",
"(",
"pkScript",
",",
"w",
".",
"chainParams",
")",
"\n",
"// An error creating addresses from the output script only",
"// indicates a non-standard script, so ignore this credit.",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"addrs",
"{",
"if",
"addrStr",
"==",
"a",
".",
"EncodeAddress",
"(",
")",
"{",
"amount",
"+=",
"cred",
".",
"Amount",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"return",
"w",
".",
"TxStore",
".",
"RangeTransactions",
"(",
"txmgrNs",
",",
"0",
",",
"stopHeight",
",",
"rangeFn",
")",
"\n",
"}",
")",
"\n",
"return",
"amount",
",",
"err",
"\n",
"}"
] | // 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",
")",
"{",
"// 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",
"\n",
"}",
"\n",
"}",
"\n\n",
"// 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",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"txHash",
",",
"err",
":=",
"w",
".",
"reliablyPublishTransaction",
"(",
"createdTx",
".",
"Tx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Sanity check on the returned tx hash.",
"if",
"*",
"txHash",
"!=",
"createdTx",
".",
"Tx",
".",
"TxHash",
"(",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"createdTx",
".",
"Tx",
",",
"nil",
"\n",
"}"
] | // 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 |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.