repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
btcsuite/btcwallet | chain/neutrino.go | Rescan | func (s *NeutrinoClient) Rescan(startHash *chainhash.Hash, addrs []btcutil.Address,
outPoints map[wire.OutPoint]btcutil.Address) error {
s.clientMtx.Lock()
defer s.clientMtx.Unlock()
if !s.started {
return fmt.Errorf("can't do a rescan when the chain client " +
"is not started")
}
if s.scanning {
// Restart the rescan by killing the existing rescan.
close(s.rescanQuit)
s.clientMtx.Unlock()
s.rescan.WaitForShutdown()
s.clientMtx.Lock()
s.rescan = nil
s.rescanErr = nil
}
s.rescanQuit = make(chan struct{})
s.scanning = true
s.finished = false
s.lastProgressSent = false
s.lastFilteredBlockHeader = nil
s.isRescan = true
bestBlock, err := s.CS.BestBlock()
if err != nil {
return fmt.Errorf("Can't get chain service's best block: %s", err)
}
header, err := s.CS.GetBlockHeader(&bestBlock.Hash)
if err != nil {
return fmt.Errorf("Can't get block header for hash %v: %s",
bestBlock.Hash, err)
}
// If the wallet is already fully caught up, or the rescan has started
// with state that indicates a "fresh" wallet, we'll send a
// notification indicating the rescan has "finished".
if header.BlockHash() == *startHash {
s.finished = true
select {
case s.enqueueNotification <- &RescanFinished{
Hash: startHash,
Height: int32(bestBlock.Height),
Time: header.Timestamp,
}:
case <-s.quit:
return nil
case <-s.rescanQuit:
return nil
}
}
var inputsToWatch []neutrino.InputWithScript
for op, addr := range outPoints {
addrScript, err := txscript.PayToAddrScript(addr)
if err != nil {
}
inputsToWatch = append(inputsToWatch, neutrino.InputWithScript{
OutPoint: op,
PkScript: addrScript,
})
}
newRescan := neutrino.NewRescan(
&neutrino.RescanChainSource{
ChainService: s.CS,
},
neutrino.NotificationHandlers(rpcclient.NotificationHandlers{
OnBlockConnected: s.onBlockConnected,
OnFilteredBlockConnected: s.onFilteredBlockConnected,
OnBlockDisconnected: s.onBlockDisconnected,
}),
neutrino.StartBlock(&waddrmgr.BlockStamp{Hash: *startHash}),
neutrino.StartTime(s.startTime),
neutrino.QuitChan(s.rescanQuit),
neutrino.WatchAddrs(addrs...),
neutrino.WatchInputs(inputsToWatch...),
)
s.rescan = newRescan
s.rescanErr = s.rescan.Start()
return nil
} | go | func (s *NeutrinoClient) Rescan(startHash *chainhash.Hash, addrs []btcutil.Address,
outPoints map[wire.OutPoint]btcutil.Address) error {
s.clientMtx.Lock()
defer s.clientMtx.Unlock()
if !s.started {
return fmt.Errorf("can't do a rescan when the chain client " +
"is not started")
}
if s.scanning {
// Restart the rescan by killing the existing rescan.
close(s.rescanQuit)
s.clientMtx.Unlock()
s.rescan.WaitForShutdown()
s.clientMtx.Lock()
s.rescan = nil
s.rescanErr = nil
}
s.rescanQuit = make(chan struct{})
s.scanning = true
s.finished = false
s.lastProgressSent = false
s.lastFilteredBlockHeader = nil
s.isRescan = true
bestBlock, err := s.CS.BestBlock()
if err != nil {
return fmt.Errorf("Can't get chain service's best block: %s", err)
}
header, err := s.CS.GetBlockHeader(&bestBlock.Hash)
if err != nil {
return fmt.Errorf("Can't get block header for hash %v: %s",
bestBlock.Hash, err)
}
// If the wallet is already fully caught up, or the rescan has started
// with state that indicates a "fresh" wallet, we'll send a
// notification indicating the rescan has "finished".
if header.BlockHash() == *startHash {
s.finished = true
select {
case s.enqueueNotification <- &RescanFinished{
Hash: startHash,
Height: int32(bestBlock.Height),
Time: header.Timestamp,
}:
case <-s.quit:
return nil
case <-s.rescanQuit:
return nil
}
}
var inputsToWatch []neutrino.InputWithScript
for op, addr := range outPoints {
addrScript, err := txscript.PayToAddrScript(addr)
if err != nil {
}
inputsToWatch = append(inputsToWatch, neutrino.InputWithScript{
OutPoint: op,
PkScript: addrScript,
})
}
newRescan := neutrino.NewRescan(
&neutrino.RescanChainSource{
ChainService: s.CS,
},
neutrino.NotificationHandlers(rpcclient.NotificationHandlers{
OnBlockConnected: s.onBlockConnected,
OnFilteredBlockConnected: s.onFilteredBlockConnected,
OnBlockDisconnected: s.onBlockDisconnected,
}),
neutrino.StartBlock(&waddrmgr.BlockStamp{Hash: *startHash}),
neutrino.StartTime(s.startTime),
neutrino.QuitChan(s.rescanQuit),
neutrino.WatchAddrs(addrs...),
neutrino.WatchInputs(inputsToWatch...),
)
s.rescan = newRescan
s.rescanErr = s.rescan.Start()
return nil
} | [
"func",
"(",
"s",
"*",
"NeutrinoClient",
")",
"Rescan",
"(",
"startHash",
"*",
"chainhash",
".",
"Hash",
",",
"addrs",
"[",
"]",
"btcutil",
".",
"Address",
",",
"outPoints",
"map",
"[",
"wire",
".",
"OutPoint",
"]",
"btcutil",
".",
"Address",
")",
"err... | // Rescan replicates the RPC client's Rescan command. | [
"Rescan",
"replicates",
"the",
"RPC",
"client",
"s",
"Rescan",
"command",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L321-L405 | train |
btcsuite/btcwallet | chain/neutrino.go | NotifyBlocks | func (s *NeutrinoClient) NotifyBlocks() error {
s.clientMtx.Lock()
// If we're scanning, we're already notifying on blocks. Otherwise,
// start a rescan without watching any addresses.
if !s.scanning {
s.clientMtx.Unlock()
return s.NotifyReceived([]btcutil.Address{})
}
s.clientMtx.Unlock()
return nil
} | go | func (s *NeutrinoClient) NotifyBlocks() error {
s.clientMtx.Lock()
// If we're scanning, we're already notifying on blocks. Otherwise,
// start a rescan without watching any addresses.
if !s.scanning {
s.clientMtx.Unlock()
return s.NotifyReceived([]btcutil.Address{})
}
s.clientMtx.Unlock()
return nil
} | [
"func",
"(",
"s",
"*",
"NeutrinoClient",
")",
"NotifyBlocks",
"(",
")",
"error",
"{",
"s",
".",
"clientMtx",
".",
"Lock",
"(",
")",
"\n",
"if",
"!",
"s",
".",
"scanning",
"{",
"s",
".",
"clientMtx",
".",
"Unlock",
"(",
")",
"\n",
"return",
"s",
"... | // NotifyBlocks replicates the RPC client's NotifyBlocks command. | [
"NotifyBlocks",
"replicates",
"the",
"RPC",
"client",
"s",
"NotifyBlocks",
"command",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L408-L418 | train |
btcsuite/btcwallet | chain/neutrino.go | NotifyReceived | func (s *NeutrinoClient) NotifyReceived(addrs []btcutil.Address) error {
s.clientMtx.Lock()
// If we have a rescan running, we just need to add the appropriate
// addresses to the watch list.
if s.scanning {
s.clientMtx.Unlock()
return s.rescan.Update(neutrino.AddAddrs(addrs...))
}
s.rescanQuit = make(chan struct{})
s.scanning = true
// Don't need RescanFinished or RescanProgress notifications.
s.finished = true
s.lastProgressSent = true
s.lastFilteredBlockHeader = nil
// Rescan with just the specified addresses.
newRescan := neutrino.NewRescan(
&neutrino.RescanChainSource{
ChainService: s.CS,
},
neutrino.NotificationHandlers(rpcclient.NotificationHandlers{
OnBlockConnected: s.onBlockConnected,
OnFilteredBlockConnected: s.onFilteredBlockConnected,
OnBlockDisconnected: s.onBlockDisconnected,
}),
neutrino.StartTime(s.startTime),
neutrino.QuitChan(s.rescanQuit),
neutrino.WatchAddrs(addrs...),
)
s.rescan = newRescan
s.rescanErr = s.rescan.Start()
s.clientMtx.Unlock()
return nil
} | go | func (s *NeutrinoClient) NotifyReceived(addrs []btcutil.Address) error {
s.clientMtx.Lock()
// If we have a rescan running, we just need to add the appropriate
// addresses to the watch list.
if s.scanning {
s.clientMtx.Unlock()
return s.rescan.Update(neutrino.AddAddrs(addrs...))
}
s.rescanQuit = make(chan struct{})
s.scanning = true
// Don't need RescanFinished or RescanProgress notifications.
s.finished = true
s.lastProgressSent = true
s.lastFilteredBlockHeader = nil
// Rescan with just the specified addresses.
newRescan := neutrino.NewRescan(
&neutrino.RescanChainSource{
ChainService: s.CS,
},
neutrino.NotificationHandlers(rpcclient.NotificationHandlers{
OnBlockConnected: s.onBlockConnected,
OnFilteredBlockConnected: s.onFilteredBlockConnected,
OnBlockDisconnected: s.onBlockDisconnected,
}),
neutrino.StartTime(s.startTime),
neutrino.QuitChan(s.rescanQuit),
neutrino.WatchAddrs(addrs...),
)
s.rescan = newRescan
s.rescanErr = s.rescan.Start()
s.clientMtx.Unlock()
return nil
} | [
"func",
"(",
"s",
"*",
"NeutrinoClient",
")",
"NotifyReceived",
"(",
"addrs",
"[",
"]",
"btcutil",
".",
"Address",
")",
"error",
"{",
"s",
".",
"clientMtx",
".",
"Lock",
"(",
")",
"\n",
"if",
"s",
".",
"scanning",
"{",
"s",
".",
"clientMtx",
".",
"... | // NotifyReceived replicates the RPC client's NotifyReceived command. | [
"NotifyReceived",
"replicates",
"the",
"RPC",
"client",
"s",
"NotifyReceived",
"command",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L421-L457 | train |
btcsuite/btcwallet | chain/neutrino.go | onFilteredBlockConnected | func (s *NeutrinoClient) onFilteredBlockConnected(height int32,
header *wire.BlockHeader, relevantTxs []*btcutil.Tx) {
ntfn := FilteredBlockConnected{
Block: &wtxmgr.BlockMeta{
Block: wtxmgr.Block{
Hash: header.BlockHash(),
Height: height,
},
Time: header.Timestamp,
},
}
for _, tx := range relevantTxs {
rec, err := wtxmgr.NewTxRecordFromMsgTx(tx.MsgTx(),
header.Timestamp)
if err != nil {
log.Errorf("Cannot create transaction record for "+
"relevant tx: %s", err)
// TODO(aakselrod): Return?
continue
}
ntfn.RelevantTxs = append(ntfn.RelevantTxs, rec)
}
select {
case s.enqueueNotification <- ntfn:
case <-s.quit:
return
case <-s.rescanQuit:
return
}
s.clientMtx.Lock()
s.lastFilteredBlockHeader = header
s.clientMtx.Unlock()
// Handle RescanFinished notification if required.
s.dispatchRescanFinished()
} | go | func (s *NeutrinoClient) onFilteredBlockConnected(height int32,
header *wire.BlockHeader, relevantTxs []*btcutil.Tx) {
ntfn := FilteredBlockConnected{
Block: &wtxmgr.BlockMeta{
Block: wtxmgr.Block{
Hash: header.BlockHash(),
Height: height,
},
Time: header.Timestamp,
},
}
for _, tx := range relevantTxs {
rec, err := wtxmgr.NewTxRecordFromMsgTx(tx.MsgTx(),
header.Timestamp)
if err != nil {
log.Errorf("Cannot create transaction record for "+
"relevant tx: %s", err)
// TODO(aakselrod): Return?
continue
}
ntfn.RelevantTxs = append(ntfn.RelevantTxs, rec)
}
select {
case s.enqueueNotification <- ntfn:
case <-s.quit:
return
case <-s.rescanQuit:
return
}
s.clientMtx.Lock()
s.lastFilteredBlockHeader = header
s.clientMtx.Unlock()
// Handle RescanFinished notification if required.
s.dispatchRescanFinished()
} | [
"func",
"(",
"s",
"*",
"NeutrinoClient",
")",
"onFilteredBlockConnected",
"(",
"height",
"int32",
",",
"header",
"*",
"wire",
".",
"BlockHeader",
",",
"relevantTxs",
"[",
"]",
"*",
"btcutil",
".",
"Tx",
")",
"{",
"ntfn",
":=",
"FilteredBlockConnected",
"{",
... | // onFilteredBlockConnected sends appropriate notifications to the notification
// channel. | [
"onFilteredBlockConnected",
"sends",
"appropriate",
"notifications",
"to",
"the",
"notification",
"channel",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L479-L516 | train |
btcsuite/btcwallet | chain/neutrino.go | onBlockDisconnected | func (s *NeutrinoClient) onBlockDisconnected(hash *chainhash.Hash, height int32,
t time.Time) {
select {
case s.enqueueNotification <- BlockDisconnected{
Block: wtxmgr.Block{
Hash: *hash,
Height: height,
},
Time: t,
}:
case <-s.quit:
case <-s.rescanQuit:
}
} | go | func (s *NeutrinoClient) onBlockDisconnected(hash *chainhash.Hash, height int32,
t time.Time) {
select {
case s.enqueueNotification <- BlockDisconnected{
Block: wtxmgr.Block{
Hash: *hash,
Height: height,
},
Time: t,
}:
case <-s.quit:
case <-s.rescanQuit:
}
} | [
"func",
"(",
"s",
"*",
"NeutrinoClient",
")",
"onBlockDisconnected",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
",",
"height",
"int32",
",",
"t",
"time",
".",
"Time",
")",
"{",
"select",
"{",
"case",
"s",
".",
"enqueueNotification",
"<-",
"BlockDisconnect... | // onBlockDisconnected sends appropriate notifications to the notification
// channel. | [
"onBlockDisconnected",
"sends",
"appropriate",
"notifications",
"to",
"the",
"notification",
"channel",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L520-L533 | train |
btcsuite/btcwallet | chain/neutrino.go | dispatchRescanFinished | func (s *NeutrinoClient) dispatchRescanFinished() {
bs, err := s.CS.BestBlock()
if err != nil {
log.Errorf("Can't get chain service's best block: %s", err)
return
}
s.clientMtx.Lock()
// Only send the RescanFinished notification once.
if s.lastFilteredBlockHeader == nil || s.finished {
s.clientMtx.Unlock()
return
}
// Only send the RescanFinished notification once the underlying chain
// service sees itself as current.
if bs.Hash != s.lastFilteredBlockHeader.BlockHash() {
s.clientMtx.Unlock()
return
}
s.finished = s.CS.IsCurrent() && s.lastProgressSent
if !s.finished {
s.clientMtx.Unlock()
return
}
header := s.lastFilteredBlockHeader
s.clientMtx.Unlock()
select {
case s.enqueueNotification <- &RescanFinished{
Hash: &bs.Hash,
Height: bs.Height,
Time: header.Timestamp,
}:
case <-s.quit:
return
case <-s.rescanQuit:
return
}
} | go | func (s *NeutrinoClient) dispatchRescanFinished() {
bs, err := s.CS.BestBlock()
if err != nil {
log.Errorf("Can't get chain service's best block: %s", err)
return
}
s.clientMtx.Lock()
// Only send the RescanFinished notification once.
if s.lastFilteredBlockHeader == nil || s.finished {
s.clientMtx.Unlock()
return
}
// Only send the RescanFinished notification once the underlying chain
// service sees itself as current.
if bs.Hash != s.lastFilteredBlockHeader.BlockHash() {
s.clientMtx.Unlock()
return
}
s.finished = s.CS.IsCurrent() && s.lastProgressSent
if !s.finished {
s.clientMtx.Unlock()
return
}
header := s.lastFilteredBlockHeader
s.clientMtx.Unlock()
select {
case s.enqueueNotification <- &RescanFinished{
Hash: &bs.Hash,
Height: bs.Height,
Time: header.Timestamp,
}:
case <-s.quit:
return
case <-s.rescanQuit:
return
}
} | [
"func",
"(",
"s",
"*",
"NeutrinoClient",
")",
"dispatchRescanFinished",
"(",
")",
"{",
"bs",
",",
"err",
":=",
"s",
".",
"CS",
".",
"BestBlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"Can't get chain service's best b... | // dispatchRescanFinished determines whether we're able to dispatch our final
// RescanFinished notification in order to mark the wallet as synced with the
// chain. If the notification has already been dispatched, then it won't be done
// again. | [
"dispatchRescanFinished",
"determines",
"whether",
"we",
"re",
"able",
"to",
"dispatch",
"our",
"final",
"RescanFinished",
"notification",
"in",
"order",
"to",
"mark",
"the",
"wallet",
"as",
"synced",
"with",
"the",
"chain",
".",
"If",
"the",
"notification",
"ha... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L600-L641 | train |
btcsuite/btcwallet | chain/neutrino.go | notificationHandler | func (s *NeutrinoClient) notificationHandler() {
hash, height, err := s.GetBestBlock()
if err != nil {
log.Errorf("Failed to get best block from chain service: %s",
err)
s.Stop()
s.wg.Done()
return
}
bs := &waddrmgr.BlockStamp{Hash: *hash, Height: height}
// TODO: Rather than leaving this as an unbounded queue for all types of
// notifications, try dropping ones where a later enqueued notification
// can fully invalidate one waiting to be processed. For example,
// blockconnected notifications for greater block heights can remove the
// need to process earlier blockconnected notifications still waiting
// here.
var notifications []interface{}
enqueue := s.enqueueNotification
var dequeue chan interface{}
var next interface{}
out:
for {
s.clientMtx.Lock()
rescanErr := s.rescanErr
s.clientMtx.Unlock()
select {
case n, ok := <-enqueue:
if !ok {
// If no notifications are queued for handling,
// the queue is finished.
if len(notifications) == 0 {
break out
}
// nil channel so no more reads can occur.
enqueue = nil
continue
}
if len(notifications) == 0 {
next = n
dequeue = s.dequeueNotification
}
notifications = append(notifications, n)
case dequeue <- next:
if n, ok := next.(BlockConnected); ok {
bs = &waddrmgr.BlockStamp{
Height: n.Height,
Hash: n.Hash,
}
}
notifications[0] = nil
notifications = notifications[1:]
if len(notifications) != 0 {
next = notifications[0]
} else {
// If no more notifications can be enqueued, the
// queue is finished.
if enqueue == nil {
break out
}
dequeue = nil
}
case err := <-rescanErr:
if err != nil {
log.Errorf("Neutrino rescan ended with error: %s", err)
}
case s.currentBlock <- bs:
case <-s.quit:
break out
}
}
s.Stop()
close(s.dequeueNotification)
s.wg.Done()
} | go | func (s *NeutrinoClient) notificationHandler() {
hash, height, err := s.GetBestBlock()
if err != nil {
log.Errorf("Failed to get best block from chain service: %s",
err)
s.Stop()
s.wg.Done()
return
}
bs := &waddrmgr.BlockStamp{Hash: *hash, Height: height}
// TODO: Rather than leaving this as an unbounded queue for all types of
// notifications, try dropping ones where a later enqueued notification
// can fully invalidate one waiting to be processed. For example,
// blockconnected notifications for greater block heights can remove the
// need to process earlier blockconnected notifications still waiting
// here.
var notifications []interface{}
enqueue := s.enqueueNotification
var dequeue chan interface{}
var next interface{}
out:
for {
s.clientMtx.Lock()
rescanErr := s.rescanErr
s.clientMtx.Unlock()
select {
case n, ok := <-enqueue:
if !ok {
// If no notifications are queued for handling,
// the queue is finished.
if len(notifications) == 0 {
break out
}
// nil channel so no more reads can occur.
enqueue = nil
continue
}
if len(notifications) == 0 {
next = n
dequeue = s.dequeueNotification
}
notifications = append(notifications, n)
case dequeue <- next:
if n, ok := next.(BlockConnected); ok {
bs = &waddrmgr.BlockStamp{
Height: n.Height,
Hash: n.Hash,
}
}
notifications[0] = nil
notifications = notifications[1:]
if len(notifications) != 0 {
next = notifications[0]
} else {
// If no more notifications can be enqueued, the
// queue is finished.
if enqueue == nil {
break out
}
dequeue = nil
}
case err := <-rescanErr:
if err != nil {
log.Errorf("Neutrino rescan ended with error: %s", err)
}
case s.currentBlock <- bs:
case <-s.quit:
break out
}
}
s.Stop()
close(s.dequeueNotification)
s.wg.Done()
} | [
"func",
"(",
"s",
"*",
"NeutrinoClient",
")",
"notificationHandler",
"(",
")",
"{",
"hash",
",",
"height",
",",
"err",
":=",
"s",
".",
"GetBestBlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"Failed to get best block f... | // notificationHandler queues and dequeues notifications. There are currently
// no bounds on the queue, so the dequeue channel should be read continually to
// avoid running out of memory. | [
"notificationHandler",
"queues",
"and",
"dequeues",
"notifications",
".",
"There",
"are",
"currently",
"no",
"bounds",
"on",
"the",
"queue",
"so",
"the",
"dequeue",
"channel",
"should",
"be",
"read",
"continually",
"to",
"avoid",
"running",
"out",
"of",
"memory"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L646-L728 | train |
btcsuite/btcwallet | chain/rpc.go | NewRPCClient | func NewRPCClient(chainParams *chaincfg.Params, connect, user, pass string, certs []byte,
disableTLS bool, reconnectAttempts int) (*RPCClient, error) {
if reconnectAttempts < 0 {
return nil, errors.New("reconnectAttempts must be positive")
}
client := &RPCClient{
connConfig: &rpcclient.ConnConfig{
Host: connect,
Endpoint: "ws",
User: user,
Pass: pass,
Certificates: certs,
DisableAutoReconnect: false,
DisableConnectOnNew: true,
DisableTLS: disableTLS,
},
chainParams: chainParams,
reconnectAttempts: reconnectAttempts,
enqueueNotification: make(chan interface{}),
dequeueNotification: make(chan interface{}),
currentBlock: make(chan *waddrmgr.BlockStamp),
quit: make(chan struct{}),
}
ntfnCallbacks := &rpcclient.NotificationHandlers{
OnClientConnected: client.onClientConnect,
OnBlockConnected: client.onBlockConnected,
OnBlockDisconnected: client.onBlockDisconnected,
OnRecvTx: client.onRecvTx,
OnRedeemingTx: client.onRedeemingTx,
OnRescanFinished: client.onRescanFinished,
OnRescanProgress: client.onRescanProgress,
}
rpcClient, err := rpcclient.New(client.connConfig, ntfnCallbacks)
if err != nil {
return nil, err
}
client.Client = rpcClient
return client, nil
} | go | func NewRPCClient(chainParams *chaincfg.Params, connect, user, pass string, certs []byte,
disableTLS bool, reconnectAttempts int) (*RPCClient, error) {
if reconnectAttempts < 0 {
return nil, errors.New("reconnectAttempts must be positive")
}
client := &RPCClient{
connConfig: &rpcclient.ConnConfig{
Host: connect,
Endpoint: "ws",
User: user,
Pass: pass,
Certificates: certs,
DisableAutoReconnect: false,
DisableConnectOnNew: true,
DisableTLS: disableTLS,
},
chainParams: chainParams,
reconnectAttempts: reconnectAttempts,
enqueueNotification: make(chan interface{}),
dequeueNotification: make(chan interface{}),
currentBlock: make(chan *waddrmgr.BlockStamp),
quit: make(chan struct{}),
}
ntfnCallbacks := &rpcclient.NotificationHandlers{
OnClientConnected: client.onClientConnect,
OnBlockConnected: client.onBlockConnected,
OnBlockDisconnected: client.onBlockDisconnected,
OnRecvTx: client.onRecvTx,
OnRedeemingTx: client.onRedeemingTx,
OnRescanFinished: client.onRescanFinished,
OnRescanProgress: client.onRescanProgress,
}
rpcClient, err := rpcclient.New(client.connConfig, ntfnCallbacks)
if err != nil {
return nil, err
}
client.Client = rpcClient
return client, nil
} | [
"func",
"NewRPCClient",
"(",
"chainParams",
"*",
"chaincfg",
".",
"Params",
",",
"connect",
",",
"user",
",",
"pass",
"string",
",",
"certs",
"[",
"]",
"byte",
",",
"disableTLS",
"bool",
",",
"reconnectAttempts",
"int",
")",
"(",
"*",
"RPCClient",
",",
"... | // NewRPCClient creates a client connection to the server described by the
// connect string. If disableTLS is false, the remote RPC certificate must be
// provided in the certs slice. The connection is not established immediately,
// but must be done using the Start method. If the remote server does not
// operate on the same bitcoin network as described by the passed chain
// parameters, the connection will be disconnected. | [
"NewRPCClient",
"creates",
"a",
"client",
"connection",
"to",
"the",
"server",
"described",
"by",
"the",
"connect",
"string",
".",
"If",
"disableTLS",
"is",
"false",
"the",
"remote",
"RPC",
"certificate",
"must",
"be",
"provided",
"in",
"the",
"certs",
"slice"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/rpc.go#L48-L88 | train |
btcsuite/btcwallet | chain/rpc.go | Start | func (c *RPCClient) Start() error {
err := c.Connect(c.reconnectAttempts)
if err != nil {
return err
}
// Verify that the server is running on the expected network.
net, err := c.GetCurrentNet()
if err != nil {
c.Disconnect()
return err
}
if net != c.chainParams.Net {
c.Disconnect()
return errors.New("mismatched networks")
}
c.quitMtx.Lock()
c.started = true
c.quitMtx.Unlock()
c.wg.Add(1)
go c.handler()
return nil
} | go | func (c *RPCClient) Start() error {
err := c.Connect(c.reconnectAttempts)
if err != nil {
return err
}
// Verify that the server is running on the expected network.
net, err := c.GetCurrentNet()
if err != nil {
c.Disconnect()
return err
}
if net != c.chainParams.Net {
c.Disconnect()
return errors.New("mismatched networks")
}
c.quitMtx.Lock()
c.started = true
c.quitMtx.Unlock()
c.wg.Add(1)
go c.handler()
return nil
} | [
"func",
"(",
"c",
"*",
"RPCClient",
")",
"Start",
"(",
")",
"error",
"{",
"err",
":=",
"c",
".",
"Connect",
"(",
"c",
".",
"reconnectAttempts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"net",
",",
"err",
":=",
... | // Start attempts to establish a client connection with the remote server.
// If successful, handler goroutines are started to process notifications
// sent by the server. After a limited number of connection attempts, this
// function gives up, and therefore will not block forever waiting for the
// connection to be established to a server that may not exist. | [
"Start",
"attempts",
"to",
"establish",
"a",
"client",
"connection",
"with",
"the",
"remote",
"server",
".",
"If",
"successful",
"handler",
"goroutines",
"are",
"started",
"to",
"process",
"notifications",
"sent",
"by",
"the",
"server",
".",
"After",
"a",
"lim... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/rpc.go#L100-L124 | train |
btcsuite/btcwallet | chain/rpc.go | Stop | func (c *RPCClient) Stop() {
c.quitMtx.Lock()
select {
case <-c.quit:
default:
close(c.quit)
c.Client.Shutdown()
if !c.started {
close(c.dequeueNotification)
}
}
c.quitMtx.Unlock()
} | go | func (c *RPCClient) Stop() {
c.quitMtx.Lock()
select {
case <-c.quit:
default:
close(c.quit)
c.Client.Shutdown()
if !c.started {
close(c.dequeueNotification)
}
}
c.quitMtx.Unlock()
} | [
"func",
"(",
"c",
"*",
"RPCClient",
")",
"Stop",
"(",
")",
"{",
"c",
".",
"quitMtx",
".",
"Lock",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"c",
".",
"quit",
":",
"default",
":",
"close",
"(",
"c",
".",
"quit",
")",
"\n",
"c",
".",
"Client... | // Stop disconnects the client and signals the shutdown of all goroutines
// started by Start. | [
"Stop",
"disconnects",
"the",
"client",
"and",
"signals",
"the",
"shutdown",
"of",
"all",
"goroutines",
"started",
"by",
"Start",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/rpc.go#L128-L141 | train |
btcsuite/btcwallet | chain/rpc.go | Rescan | func (c *RPCClient) Rescan(startHash *chainhash.Hash, addrs []btcutil.Address,
outPoints map[wire.OutPoint]btcutil.Address) error {
flatOutpoints := make([]*wire.OutPoint, 0, len(outPoints))
for ops := range outPoints {
flatOutpoints = append(flatOutpoints, &ops)
}
return c.Client.Rescan(startHash, addrs, flatOutpoints)
} | go | func (c *RPCClient) Rescan(startHash *chainhash.Hash, addrs []btcutil.Address,
outPoints map[wire.OutPoint]btcutil.Address) error {
flatOutpoints := make([]*wire.OutPoint, 0, len(outPoints))
for ops := range outPoints {
flatOutpoints = append(flatOutpoints, &ops)
}
return c.Client.Rescan(startHash, addrs, flatOutpoints)
} | [
"func",
"(",
"c",
"*",
"RPCClient",
")",
"Rescan",
"(",
"startHash",
"*",
"chainhash",
".",
"Hash",
",",
"addrs",
"[",
"]",
"btcutil",
".",
"Address",
",",
"outPoints",
"map",
"[",
"wire",
".",
"OutPoint",
"]",
"btcutil",
".",
"Address",
")",
"error",
... | // Rescan wraps the normal Rescan command with an additional paramter that
// allows us to map an oupoint to the address in the chain that it pays to.
// This is useful when using BIP 158 filters as they include the prev pkScript
// rather than the full outpoint. | [
"Rescan",
"wraps",
"the",
"normal",
"Rescan",
"command",
"with",
"an",
"additional",
"paramter",
"that",
"allows",
"us",
"to",
"map",
"an",
"oupoint",
"to",
"the",
"address",
"in",
"the",
"chain",
"that",
"it",
"pays",
"to",
".",
"This",
"is",
"useful",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/rpc.go#L147-L156 | train |
btcsuite/btcwallet | chain/rpc.go | parseBlock | func parseBlock(block *btcjson.BlockDetails) (*wtxmgr.BlockMeta, error) {
if block == nil {
return nil, nil
}
blkHash, err := chainhash.NewHashFromStr(block.Hash)
if err != nil {
return nil, err
}
blk := &wtxmgr.BlockMeta{
Block: wtxmgr.Block{
Height: block.Height,
Hash: *blkHash,
},
Time: time.Unix(block.Time, 0),
}
return blk, nil
} | go | func parseBlock(block *btcjson.BlockDetails) (*wtxmgr.BlockMeta, error) {
if block == nil {
return nil, nil
}
blkHash, err := chainhash.NewHashFromStr(block.Hash)
if err != nil {
return nil, err
}
blk := &wtxmgr.BlockMeta{
Block: wtxmgr.Block{
Height: block.Height,
Hash: *blkHash,
},
Time: time.Unix(block.Time, 0),
}
return blk, nil
} | [
"func",
"parseBlock",
"(",
"block",
"*",
"btcjson",
".",
"BlockDetails",
")",
"(",
"*",
"wtxmgr",
".",
"BlockMeta",
",",
"error",
")",
"{",
"if",
"block",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"blkHash",
",",
"err",
":=",
... | // parseBlock parses a btcws definition of the block a tx is mined it to the
// Block structure of the wtxmgr package, and the block index. This is done
// here since rpcclient doesn't parse this nicely for us. | [
"parseBlock",
"parses",
"a",
"btcws",
"definition",
"of",
"the",
"block",
"a",
"tx",
"is",
"mined",
"it",
"to",
"the",
"Block",
"structure",
"of",
"the",
"wtxmgr",
"package",
"and",
"the",
"block",
"index",
".",
"This",
"is",
"done",
"here",
"since",
"rp... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/rpc.go#L274-L290 | train |
btcsuite/btcwallet | chain/rpc.go | POSTClient | func (c *RPCClient) POSTClient() (*rpcclient.Client, error) {
configCopy := *c.connConfig
configCopy.HTTPPostMode = true
return rpcclient.New(&configCopy, nil)
} | go | func (c *RPCClient) POSTClient() (*rpcclient.Client, error) {
configCopy := *c.connConfig
configCopy.HTTPPostMode = true
return rpcclient.New(&configCopy, nil)
} | [
"func",
"(",
"c",
"*",
"RPCClient",
")",
"POSTClient",
"(",
")",
"(",
"*",
"rpcclient",
".",
"Client",
",",
"error",
")",
"{",
"configCopy",
":=",
"*",
"c",
".",
"connConfig",
"\n",
"configCopy",
".",
"HTTPPostMode",
"=",
"true",
"\n",
"return",
"rpccl... | // POSTClient creates the equivalent HTTP POST rpcclient.Client. | [
"POSTClient",
"creates",
"the",
"equivalent",
"HTTP",
"POST",
"rpcclient",
".",
"Client",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/rpc.go#L443-L447 | train |
btcsuite/btcwallet | snacl/snacl.go | Encrypt | func (ck *CryptoKey) Encrypt(in []byte) ([]byte, error) {
var nonce [NonceSize]byte
_, err := io.ReadFull(prng, nonce[:])
if err != nil {
return nil, err
}
blob := secretbox.Seal(nil, in, &nonce, (*[KeySize]byte)(ck))
return append(nonce[:], blob...), nil
} | go | func (ck *CryptoKey) Encrypt(in []byte) ([]byte, error) {
var nonce [NonceSize]byte
_, err := io.ReadFull(prng, nonce[:])
if err != nil {
return nil, err
}
blob := secretbox.Seal(nil, in, &nonce, (*[KeySize]byte)(ck))
return append(nonce[:], blob...), nil
} | [
"func",
"(",
"ck",
"*",
"CryptoKey",
")",
"Encrypt",
"(",
"in",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"nonce",
"[",
"NonceSize",
"]",
"byte",
"\n",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"prng"... | // Encrypt encrypts the passed data. | [
"Encrypt",
"encrypts",
"the",
"passed",
"data",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L48-L56 | train |
btcsuite/btcwallet | snacl/snacl.go | Decrypt | func (ck *CryptoKey) Decrypt(in []byte) ([]byte, error) {
if len(in) < NonceSize {
return nil, ErrMalformed
}
var nonce [NonceSize]byte
copy(nonce[:], in[:NonceSize])
blob := in[NonceSize:]
opened, ok := secretbox.Open(nil, blob, &nonce, (*[KeySize]byte)(ck))
if !ok {
return nil, ErrDecryptFailed
}
return opened, nil
} | go | func (ck *CryptoKey) Decrypt(in []byte) ([]byte, error) {
if len(in) < NonceSize {
return nil, ErrMalformed
}
var nonce [NonceSize]byte
copy(nonce[:], in[:NonceSize])
blob := in[NonceSize:]
opened, ok := secretbox.Open(nil, blob, &nonce, (*[KeySize]byte)(ck))
if !ok {
return nil, ErrDecryptFailed
}
return opened, nil
} | [
"func",
"(",
"ck",
"*",
"CryptoKey",
")",
"Decrypt",
"(",
"in",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"in",
")",
"<",
"NonceSize",
"{",
"return",
"nil",
",",
"ErrMalformed",
"\n",
"}",
"\n",
"va... | // Decrypt decrypts the passed data. The must be the output of the Encrypt
// function. | [
"Decrypt",
"decrypts",
"the",
"passed",
"data",
".",
"The",
"must",
"be",
"the",
"output",
"of",
"the",
"Encrypt",
"function",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L60-L75 | train |
btcsuite/btcwallet | snacl/snacl.go | GenerateCryptoKey | func GenerateCryptoKey() (*CryptoKey, error) {
var key CryptoKey
_, err := io.ReadFull(prng, key[:])
if err != nil {
return nil, err
}
return &key, nil
} | go | func GenerateCryptoKey() (*CryptoKey, error) {
var key CryptoKey
_, err := io.ReadFull(prng, key[:])
if err != nil {
return nil, err
}
return &key, nil
} | [
"func",
"GenerateCryptoKey",
"(",
")",
"(",
"*",
"CryptoKey",
",",
"error",
")",
"{",
"var",
"key",
"CryptoKey",
"\n",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"prng",
",",
"key",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",... | // GenerateCryptoKey generates a new crypotgraphically random key. | [
"GenerateCryptoKey",
"generates",
"a",
"new",
"crypotgraphically",
"random",
"key",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L86-L94 | train |
btcsuite/btcwallet | snacl/snacl.go | deriveKey | func (sk *SecretKey) deriveKey(password *[]byte) error {
key, err := scrypt.Key(*password, sk.Parameters.Salt[:],
sk.Parameters.N,
sk.Parameters.R,
sk.Parameters.P,
len(sk.Key))
if err != nil {
return err
}
copy(sk.Key[:], key)
zero.Bytes(key)
// I'm not a fan of forced garbage collections, but scrypt allocates a
// ton of memory and calling it back to back without a GC cycle in
// between means you end up needing twice the amount of memory. For
// example, if your scrypt parameters are such that you require 1GB and
// you call it twice in a row, without this you end up allocating 2GB
// since the first GB probably hasn't been released yet.
debug.FreeOSMemory()
return nil
} | go | func (sk *SecretKey) deriveKey(password *[]byte) error {
key, err := scrypt.Key(*password, sk.Parameters.Salt[:],
sk.Parameters.N,
sk.Parameters.R,
sk.Parameters.P,
len(sk.Key))
if err != nil {
return err
}
copy(sk.Key[:], key)
zero.Bytes(key)
// I'm not a fan of forced garbage collections, but scrypt allocates a
// ton of memory and calling it back to back without a GC cycle in
// between means you end up needing twice the amount of memory. For
// example, if your scrypt parameters are such that you require 1GB and
// you call it twice in a row, without this you end up allocating 2GB
// since the first GB probably hasn't been released yet.
debug.FreeOSMemory()
return nil
} | [
"func",
"(",
"sk",
"*",
"SecretKey",
")",
"deriveKey",
"(",
"password",
"*",
"[",
"]",
"byte",
")",
"error",
"{",
"key",
",",
"err",
":=",
"scrypt",
".",
"Key",
"(",
"*",
"password",
",",
"sk",
".",
"Parameters",
".",
"Salt",
"[",
":",
"]",
",",
... | // deriveKey fills out the Key field. | [
"deriveKey",
"fills",
"out",
"the",
"Key",
"field",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L113-L134 | train |
btcsuite/btcwallet | snacl/snacl.go | Marshal | func (sk *SecretKey) Marshal() []byte {
params := &sk.Parameters
// The marshalled format for the the params is as follows:
// <salt><digest><N><R><P>
//
// KeySize + sha256.Size + N (8 bytes) + R (8 bytes) + P (8 bytes)
marshalled := make([]byte, KeySize+sha256.Size+24)
b := marshalled
copy(b[:KeySize], params.Salt[:])
b = b[KeySize:]
copy(b[:sha256.Size], params.Digest[:])
b = b[sha256.Size:]
binary.LittleEndian.PutUint64(b[:8], uint64(params.N))
b = b[8:]
binary.LittleEndian.PutUint64(b[:8], uint64(params.R))
b = b[8:]
binary.LittleEndian.PutUint64(b[:8], uint64(params.P))
return marshalled
} | go | func (sk *SecretKey) Marshal() []byte {
params := &sk.Parameters
// The marshalled format for the the params is as follows:
// <salt><digest><N><R><P>
//
// KeySize + sha256.Size + N (8 bytes) + R (8 bytes) + P (8 bytes)
marshalled := make([]byte, KeySize+sha256.Size+24)
b := marshalled
copy(b[:KeySize], params.Salt[:])
b = b[KeySize:]
copy(b[:sha256.Size], params.Digest[:])
b = b[sha256.Size:]
binary.LittleEndian.PutUint64(b[:8], uint64(params.N))
b = b[8:]
binary.LittleEndian.PutUint64(b[:8], uint64(params.R))
b = b[8:]
binary.LittleEndian.PutUint64(b[:8], uint64(params.P))
return marshalled
} | [
"func",
"(",
"sk",
"*",
"SecretKey",
")",
"Marshal",
"(",
")",
"[",
"]",
"byte",
"{",
"params",
":=",
"&",
"sk",
".",
"Parameters",
"\n",
"marshalled",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"KeySize",
"+",
"sha256",
".",
"Size",
"+",
"24",
")... | // Marshal returns the Parameters field marshalled into a format suitable for
// storage. This result of this can be stored in clear text. | [
"Marshal",
"returns",
"the",
"Parameters",
"field",
"marshalled",
"into",
"a",
"format",
"suitable",
"for",
"storage",
".",
"This",
"result",
"of",
"this",
"can",
"be",
"stored",
"in",
"clear",
"text",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L138-L159 | train |
btcsuite/btcwallet | snacl/snacl.go | Unmarshal | func (sk *SecretKey) Unmarshal(marshalled []byte) error {
if sk.Key == nil {
sk.Key = (*CryptoKey)(&[KeySize]byte{})
}
// The marshalled format for the the params is as follows:
// <salt><digest><N><R><P>
//
// KeySize + sha256.Size + N (8 bytes) + R (8 bytes) + P (8 bytes)
if len(marshalled) != KeySize+sha256.Size+24 {
return ErrMalformed
}
params := &sk.Parameters
copy(params.Salt[:], marshalled[:KeySize])
marshalled = marshalled[KeySize:]
copy(params.Digest[:], marshalled[:sha256.Size])
marshalled = marshalled[sha256.Size:]
params.N = int(binary.LittleEndian.Uint64(marshalled[:8]))
marshalled = marshalled[8:]
params.R = int(binary.LittleEndian.Uint64(marshalled[:8]))
marshalled = marshalled[8:]
params.P = int(binary.LittleEndian.Uint64(marshalled[:8]))
return nil
} | go | func (sk *SecretKey) Unmarshal(marshalled []byte) error {
if sk.Key == nil {
sk.Key = (*CryptoKey)(&[KeySize]byte{})
}
// The marshalled format for the the params is as follows:
// <salt><digest><N><R><P>
//
// KeySize + sha256.Size + N (8 bytes) + R (8 bytes) + P (8 bytes)
if len(marshalled) != KeySize+sha256.Size+24 {
return ErrMalformed
}
params := &sk.Parameters
copy(params.Salt[:], marshalled[:KeySize])
marshalled = marshalled[KeySize:]
copy(params.Digest[:], marshalled[:sha256.Size])
marshalled = marshalled[sha256.Size:]
params.N = int(binary.LittleEndian.Uint64(marshalled[:8]))
marshalled = marshalled[8:]
params.R = int(binary.LittleEndian.Uint64(marshalled[:8]))
marshalled = marshalled[8:]
params.P = int(binary.LittleEndian.Uint64(marshalled[:8]))
return nil
} | [
"func",
"(",
"sk",
"*",
"SecretKey",
")",
"Unmarshal",
"(",
"marshalled",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"sk",
".",
"Key",
"==",
"nil",
"{",
"sk",
".",
"Key",
"=",
"(",
"*",
"CryptoKey",
")",
"(",
"&",
"[",
"KeySize",
"]",
"byte",
"... | // Unmarshal unmarshalls the parameters needed to derive the secret key from a
// passphrase into sk. | [
"Unmarshal",
"unmarshalls",
"the",
"parameters",
"needed",
"to",
"derive",
"the",
"secret",
"key",
"from",
"a",
"passphrase",
"into",
"sk",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L163-L188 | train |
btcsuite/btcwallet | snacl/snacl.go | DeriveKey | func (sk *SecretKey) DeriveKey(password *[]byte) error {
if err := sk.deriveKey(password); err != nil {
return err
}
// verify password
digest := sha256.Sum256(sk.Key[:])
if subtle.ConstantTimeCompare(digest[:], sk.Parameters.Digest[:]) != 1 {
return ErrInvalidPassword
}
return nil
} | go | func (sk *SecretKey) DeriveKey(password *[]byte) error {
if err := sk.deriveKey(password); err != nil {
return err
}
// verify password
digest := sha256.Sum256(sk.Key[:])
if subtle.ConstantTimeCompare(digest[:], sk.Parameters.Digest[:]) != 1 {
return ErrInvalidPassword
}
return nil
} | [
"func",
"(",
"sk",
"*",
"SecretKey",
")",
"DeriveKey",
"(",
"password",
"*",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"err",
":=",
"sk",
".",
"deriveKey",
"(",
"password",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"di... | // DeriveKey derives the underlying secret key and ensures it matches the
// expected digest. This should only be called after previously calling the
// Zero function or on an initial Unmarshal. | [
"DeriveKey",
"derives",
"the",
"underlying",
"secret",
"key",
"and",
"ensures",
"it",
"matches",
"the",
"expected",
"digest",
".",
"This",
"should",
"only",
"be",
"called",
"after",
"previously",
"calling",
"the",
"Zero",
"function",
"or",
"on",
"an",
"initial... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L200-L212 | train |
btcsuite/btcwallet | snacl/snacl.go | Encrypt | func (sk *SecretKey) Encrypt(in []byte) ([]byte, error) {
return sk.Key.Encrypt(in)
} | go | func (sk *SecretKey) Encrypt(in []byte) ([]byte, error) {
return sk.Key.Encrypt(in)
} | [
"func",
"(",
"sk",
"*",
"SecretKey",
")",
"Encrypt",
"(",
"in",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"sk",
".",
"Key",
".",
"Encrypt",
"(",
"in",
")",
"\n",
"}"
] | // Encrypt encrypts in bytes and returns a JSON blob. | [
"Encrypt",
"encrypts",
"in",
"bytes",
"and",
"returns",
"a",
"JSON",
"blob",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L215-L217 | train |
btcsuite/btcwallet | snacl/snacl.go | Decrypt | func (sk *SecretKey) Decrypt(in []byte) ([]byte, error) {
return sk.Key.Decrypt(in)
} | go | func (sk *SecretKey) Decrypt(in []byte) ([]byte, error) {
return sk.Key.Decrypt(in)
} | [
"func",
"(",
"sk",
"*",
"SecretKey",
")",
"Decrypt",
"(",
"in",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"sk",
".",
"Key",
".",
"Decrypt",
"(",
"in",
")",
"\n",
"}"
] | // Decrypt takes in a JSON blob and returns it's decrypted form. | [
"Decrypt",
"takes",
"in",
"a",
"JSON",
"blob",
"and",
"returns",
"it",
"s",
"decrypted",
"form",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L220-L222 | train |
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",
")",
"(",
"&",
"[",
"KeySi... | // 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",
"{",
"totalSize",
":=",
"8",
"+",
"wire",
".",
"VarIntSerializeSize",
"(",
"uint64",
"(",
"scriptSize",
")",
")",
"+",
"scrip... | // 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"... | 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",
"{",
"if",
"txscript",
".",
"GetScriptClass",
"(",
"output",
".",
"PkScript",
")",
"==",
"txscript",
".",
"NullDataTy",
"{",
"ret... | // 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",... | // 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",
"if",... | // 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",
":=",
... | // 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",
")"... | // 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",
"(",
"\"m/%v'/%v'\"",
",",
"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",
"(",
")",
"{",
"for",
"_",
",",
"acctInfo",
":=",
"range",
"s",
".",
"acctInfo",
"{",
"acctInfo",
".",
"acctKeyPub",
".",
"Zero",
"(",
")",
"\n",
"acctInfo",
".",
"acctKeyPub",
"=... | // 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",
... | 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",
"AddressTy... | // 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",
"zeroe... | 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",
")",
"{",
"acctKey",
":=",
"ac... | // 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",... | // 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",
")"... | // 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",
... | 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",
")",
"{",
"isLocked",
":=",
"s",
".",
"rootManager",
".",
"i... | // 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",
")",
"{",
"pubBytes",
",",
"err",
":=",
"s",
".",
"rootManager",
".",
"cryptoKeyPub",
".",
"Decryp... | // 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",
")",
"{",
"scriptHash",
",",
"err",
":=",
"s",
".",
"rootManager",
".",
"cryptoKeyPub",
".",
"Decrypt"... | // 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",
".",
"("... | // 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",
"MUS... | 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",
")",
"{",
"rowInterface",
",",
"err",
":=",
"fetchAddress",
... | // 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",
... | 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",
"{",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"addrs",
"[",
"addrKey",
"(",
"addressID",
")",
"]"... | // 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",
")",
"{",
"if",
"pka",
",",
"ok",
":=",
"address",
".",
"(",
"*",
... | // 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",
"... | 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",
",... | // 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",
")",
"{",
"if",
"account",
">... | // 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",
":=",
"manager... | // 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"... | 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",
")",
"{",
"if",
"account",
">",
"MaxAccountNum",
"{",
"err",
":=",
"managerEr... | // 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",... | 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",
")",
"{",
"if",
"account",
">",
"MaxAccountNum",
"{",
"err",
":=",
"managerEr... | // 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",... | 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",
... | // 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",
"ErrDuplicateAcco... | 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",
".",
... | // 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",
... | 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",
",",
"... | // 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",
"... | // 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",
")",
"\... | // 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",
",",
"a... | // 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",
... | // 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",
... | // 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... | // 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",
... | // 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",
")",
"{",
"err",
":=",
"openStore",
"(",
"ns",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"... | // 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",
"{",
"minedBalance",
",",
"err",
":=",
"fetchMinedBalance",
"(",
"ns",
")",... | // 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",
"(",... | // 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",
"... | 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",
"{",
"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",
"tur... | 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",
"_",
",",
"v",
":=",
"existsTxRecord",
"(",
"ns",
",",
"&",
"re... | // 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",
... | 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... | 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",... | // 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",
",",
"\" BTC\"",
")",
"\n",
"valueF64",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
... | // 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",
"{",
"if",
"existsRawUnmined",
"(",
"ns",
",",
"rec",
".",
"Hash",
"[",
":",
"]",
")",
"!=",
"nil",
"{",... | // 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",
"i",
":=",
"range",
"rec",
".",
"MsgTx",
".",
"TxOut",
"{",
"k",
":=",
"canonicalOutPoint",
"("... | // 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",... | 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",
"i... | // 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",
"the... | 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",
":",
"w",
".",
"WaitForShutdown",
"(",
")",
"\n",
"w",
".",
"quit",
"=",
"make",
"("... | // 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",... | // 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",
"noti... | 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",
".",
"cha... | // 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",
"w... | 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",
"("... | // 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"... | // 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",
"select",
"{",
"case",
"<-",
"quit",
":",
... | // 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",
"}",
... | // 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",
"{",
"w",
".",
"chainClientSyncMtx",
".",
"Lock",
"(",
")",
"\n",
"syncing",
":=",
"w",
".",
"chainClient",
"!=",
"nil",
"\n",
"w",
".",
"chainClientSyncMtx",
".",
"Unlock"... | // 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",... | // 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",
... | // 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",
"{",
"if",
"birthdayStamp",
"==",
"nil",
"{",
"var",
"err",
"error",
"\n",
"birthdayStamp",
",",
"err",
"=",
"w",
".",
"syncToB... | // 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",
"... | 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",
... | // 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",
... | 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",
... | // 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"... | 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",
".",
"... | // 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",
"{",
"exHorizon",
",",
"exWindow",
":=",
"scopeState",
".",
"Exter... | // 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",
"scop... | 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",
".",... | // 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",
",",
"recoverySt... | // 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",
... | 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",
")",
"{",
"var",
"nFoundExternal",
"int",
"\n",
"for",
"_",
",",
"indexes",
":=",
"range",
"resp",
".",
"FoundExternalAddrs",
"{",
... | // 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",
"<... | // 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",
"tim... | 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",
... | // 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",
... | 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",
... | // 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",
".",
"chang... | // 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",
".",
"ForEachA... | // 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",
"... | 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",
"(",
... | // 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",
".",
"d... | // 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",
"ne... | 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",
".",
"Vie... | // 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",
".",
... | // 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",
")",... | // 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.