repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
lightninglabs/neutrino
blockntfns/notification.go
String
func (n *Connected) String() string { return fmt.Sprintf("block connected (height=%d, hash=%v)", n.height, n.header.BlockHash()) }
go
func (n *Connected) String() string { return fmt.Sprintf("block connected (height=%d, hash=%v)", n.height, n.header.BlockHash()) }
[ "func", "(", "n", "*", "Connected", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "n", ".", "height", ",", "n", ".", "header", ".", "BlockHash", "(", ")", ")", "\n", "}" ]
// String returns the string representation of a Connected notification.
[ "String", "returns", "the", "string", "representation", "of", "a", "Connected", "notification", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockntfns/notification.go#L57-L60
train
lightninglabs/neutrino
blockntfns/notification.go
NewBlockDisconnected
func NewBlockDisconnected(headerDisconnected wire.BlockHeader, heightDisconnected uint32, chainTip wire.BlockHeader) *Disconnected { return &Disconnected{ headerDisconnected: headerDisconnected, heightDisconnected: heightDisconnected, chainTip: chainTip, } }
go
func NewBlockDisconnected(headerDisconnected wire.BlockHeader, heightDisconnected uint32, chainTip wire.BlockHeader) *Disconnected { return &Disconnected{ headerDisconnected: headerDisconnected, heightDisconnected: heightDisconnected, chainTip: chainTip, } }
[ "func", "NewBlockDisconnected", "(", "headerDisconnected", "wire", ".", "BlockHeader", ",", "heightDisconnected", "uint32", ",", "chainTip", "wire", ".", "BlockHeader", ")", "*", "Disconnected", "{", "return", "&", "Disconnected", "{", "headerDisconnected", ":", "headerDisconnected", ",", "heightDisconnected", ":", "heightDisconnected", ",", "chainTip", ":", "chainTip", ",", "}", "\n", "}" ]
// NewBlockDisconnected creates a Disconnected notification for the given block.
[ "NewBlockDisconnected", "creates", "a", "Disconnected", "notification", "for", "the", "given", "block", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockntfns/notification.go#L75-L83
train
lightninglabs/neutrino
blockntfns/notification.go
String
func (n *Disconnected) String() string { return fmt.Sprintf("block disconnected (height=%d, hash=%v)", n.heightDisconnected, n.headerDisconnected.BlockHash()) }
go
func (n *Disconnected) String() string { return fmt.Sprintf("block disconnected (height=%d, hash=%v)", n.heightDisconnected, n.headerDisconnected.BlockHash()) }
[ "func", "(", "n", "*", "Disconnected", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "n", ".", "heightDisconnected", ",", "n", ".", "headerDisconnected", ".", "BlockHash", "(", ")", ")", "\n", "}" ]
// String returns the string representation of a Disconnected notification.
[ "String", "returns", "the", "string", "representation", "of", "a", "Disconnected", "notification", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockntfns/notification.go#L102-L105
train
lightninglabs/neutrino
query.go
defaultQueryOptions
func defaultQueryOptions() *queryOptions { return &queryOptions{ timeout: QueryTimeout, numRetries: uint8(QueryNumRetries), peerConnectTimeout: QueryPeerConnectTimeout, encoding: QueryEncoding, optimisticBatch: noBatch, } }
go
func defaultQueryOptions() *queryOptions { return &queryOptions{ timeout: QueryTimeout, numRetries: uint8(QueryNumRetries), peerConnectTimeout: QueryPeerConnectTimeout, encoding: QueryEncoding, optimisticBatch: noBatch, } }
[ "func", "defaultQueryOptions", "(", ")", "*", "queryOptions", "{", "return", "&", "queryOptions", "{", "timeout", ":", "QueryTimeout", ",", "numRetries", ":", "uint8", "(", "QueryNumRetries", ")", ",", "peerConnectTimeout", ":", "QueryPeerConnectTimeout", ",", "encoding", ":", "QueryEncoding", ",", "optimisticBatch", ":", "noBatch", ",", "}", "\n", "}" ]
// defaultQueryOptions returns a queryOptions set to package-level defaults.
[ "defaultQueryOptions", "returns", "a", "queryOptions", "set", "to", "package", "-", "level", "defaults", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/query.go#L112-L120
train
lightninglabs/neutrino
query.go
applyQueryOptions
func (qo *queryOptions) applyQueryOptions(options ...QueryOption) { for _, option := range options { option(qo) } }
go
func (qo *queryOptions) applyQueryOptions(options ...QueryOption) { for _, option := range options { option(qo) } }
[ "func", "(", "qo", "*", "queryOptions", ")", "applyQueryOptions", "(", "options", "...", "QueryOption", ")", "{", "for", "_", ",", "option", ":=", "range", "options", "{", "option", "(", "qo", ")", "\n", "}", "\n", "}" ]
// applyQueryOptions updates a queryOptions set with functional options.
[ "applyQueryOptions", "updates", "a", "queryOptions", "set", "with", "functional", "options", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/query.go#L123-L127
train
lightninglabs/neutrino
query.go
Timeout
func Timeout(timeout time.Duration) QueryOption { return func(qo *queryOptions) { qo.timeout = timeout } }
go
func Timeout(timeout time.Duration) QueryOption { return func(qo *queryOptions) { qo.timeout = timeout } }
[ "func", "Timeout", "(", "timeout", "time", ".", "Duration", ")", "QueryOption", "{", "return", "func", "(", "qo", "*", "queryOptions", ")", "{", "qo", ".", "timeout", "=", "timeout", "\n", "}", "\n", "}" ]
// Timeout is a query option that lets the query know how long to wait for each // peer we ask the query to answer it before moving on.
[ "Timeout", "is", "a", "query", "option", "that", "lets", "the", "query", "know", "how", "long", "to", "wait", "for", "each", "peer", "we", "ask", "the", "query", "to", "answer", "it", "before", "moving", "on", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/query.go#L131-L135
train
lightninglabs/neutrino
query.go
PeerConnectTimeout
func PeerConnectTimeout(timeout time.Duration) QueryOption { return func(qo *queryOptions) { qo.peerConnectTimeout = timeout } }
go
func PeerConnectTimeout(timeout time.Duration) QueryOption { return func(qo *queryOptions) { qo.peerConnectTimeout = timeout } }
[ "func", "PeerConnectTimeout", "(", "timeout", "time", ".", "Duration", ")", "QueryOption", "{", "return", "func", "(", "qo", "*", "queryOptions", ")", "{", "qo", ".", "peerConnectTimeout", "=", "timeout", "\n", "}", "\n", "}" ]
// PeerConnectTimeout is a query option that lets the query know how long to // wait for the underlying chain service to connect to a peer before giving up // on a query in case we don't have any peers.
[ "PeerConnectTimeout", "is", "a", "query", "option", "that", "lets", "the", "query", "know", "how", "long", "to", "wait", "for", "the", "underlying", "chain", "service", "to", "connect", "to", "a", "peer", "before", "giving", "up", "on", "a", "query", "in", "case", "we", "don", "t", "have", "any", "peers", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/query.go#L148-L152
train
lightninglabs/neutrino
query.go
Encoding
func Encoding(encoding wire.MessageEncoding) QueryOption { return func(qo *queryOptions) { qo.encoding = encoding } }
go
func Encoding(encoding wire.MessageEncoding) QueryOption { return func(qo *queryOptions) { qo.encoding = encoding } }
[ "func", "Encoding", "(", "encoding", "wire", ".", "MessageEncoding", ")", "QueryOption", "{", "return", "func", "(", "qo", "*", "queryOptions", ")", "{", "qo", ".", "encoding", "=", "encoding", "\n", "}", "\n", "}" ]
// Encoding is a query option that allows the caller to set a message encoding // for the query messages.
[ "Encoding", "is", "a", "query", "option", "that", "allows", "the", "caller", "to", "set", "a", "message", "encoding", "for", "the", "query", "messages", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/query.go#L156-L160
train
lightninglabs/neutrino
query.go
queryAllPeers
func (s *ChainService) queryAllPeers( // queryMsg is the message to broadcast to all peers. queryMsg wire.Message, // checkResponse is called for every message within the timeout period. // The quit channel lets the query know to terminate because the // required response has been found. This is done by closing the // channel. The peerQuit lets the query know to terminate the query for // the peer which sent the response, allowing releasing resources for // peers which respond quickly while continuing to wait for slower // peers to respond and nonresponsive peers to time out. checkResponse func(sp *ServerPeer, resp wire.Message, quit chan<- struct{}, peerQuit chan<- struct{}), // options takes functional options for executing the query. options ...QueryOption) { // Starting with the set of default options, we'll apply any specified // functional options to the query. qo := defaultQueryOptions() qo.numRetries = 1 qo.applyQueryOptions(options...) // This is done in a single-threaded query because the peerState is // held in a single thread. This is the only part of the query // framework that requires access to peerState, so it's done once per // query. peers := s.Peers() // This will be shared state between the per-peer goroutines. queryQuit := make(chan struct{}) allQuit := make(chan struct{}) var wg sync.WaitGroup msgChan := make(chan spMsg) subscription := spMsgSubscription{ msgChan: msgChan, quitChan: allQuit, } // Now we start a goroutine for each peer which manages the peer's // message subscription. peerQuits := make(map[string]chan struct{}) for _, sp := range peers { sp.subscribeRecvMsg(subscription) wg.Add(1) peerQuits[sp.Addr()] = make(chan struct{}) go func(sp *ServerPeer, peerQuit <-chan struct{}) { defer wg.Done() defer sp.unsubscribeRecvMsgs(subscription) for i := uint8(0); i < qo.numRetries; i++ { timeout := time.After(qo.timeout) sp.QueueMessageWithEncoding(queryMsg, nil, qo.encoding) select { case <-queryQuit: return case <-s.quit: return case <-peerQuit: return case <-timeout: } } }(sp, peerQuits[sp.Addr()]) } // This goroutine will wait until all of the peer-query goroutines have // terminated, and then initiate a query shutdown. go func() { wg.Wait() // Make sure our main goroutine and the subscription know to // quit. close(allQuit) // Close the done channel, if any. if qo.doneChan != nil { close(qo.doneChan) } }() // Loop for any messages sent to us via our subscription channel and // check them for whether they satisfy the query. Break the loop when // allQuit is closed. checkResponses: for { select { case <-queryQuit: break checkResponses case <-s.quit: break checkResponses case <-allQuit: break checkResponses // A message has arrived over the subscription channel, so we // execute the checkResponses callback to see if this ends our // query session. case sm := <-msgChan: // TODO: This will get stuck if checkResponse gets // stuck. This is a caveat for callers that should be // fixed before exposing this function for public use. select { case <-peerQuits[sm.sp.Addr()]: default: checkResponse(sm.sp, sm.msg, queryQuit, peerQuits[sm.sp.Addr()]) } } } }
go
func (s *ChainService) queryAllPeers( // queryMsg is the message to broadcast to all peers. queryMsg wire.Message, // checkResponse is called for every message within the timeout period. // The quit channel lets the query know to terminate because the // required response has been found. This is done by closing the // channel. The peerQuit lets the query know to terminate the query for // the peer which sent the response, allowing releasing resources for // peers which respond quickly while continuing to wait for slower // peers to respond and nonresponsive peers to time out. checkResponse func(sp *ServerPeer, resp wire.Message, quit chan<- struct{}, peerQuit chan<- struct{}), // options takes functional options for executing the query. options ...QueryOption) { // Starting with the set of default options, we'll apply any specified // functional options to the query. qo := defaultQueryOptions() qo.numRetries = 1 qo.applyQueryOptions(options...) // This is done in a single-threaded query because the peerState is // held in a single thread. This is the only part of the query // framework that requires access to peerState, so it's done once per // query. peers := s.Peers() // This will be shared state between the per-peer goroutines. queryQuit := make(chan struct{}) allQuit := make(chan struct{}) var wg sync.WaitGroup msgChan := make(chan spMsg) subscription := spMsgSubscription{ msgChan: msgChan, quitChan: allQuit, } // Now we start a goroutine for each peer which manages the peer's // message subscription. peerQuits := make(map[string]chan struct{}) for _, sp := range peers { sp.subscribeRecvMsg(subscription) wg.Add(1) peerQuits[sp.Addr()] = make(chan struct{}) go func(sp *ServerPeer, peerQuit <-chan struct{}) { defer wg.Done() defer sp.unsubscribeRecvMsgs(subscription) for i := uint8(0); i < qo.numRetries; i++ { timeout := time.After(qo.timeout) sp.QueueMessageWithEncoding(queryMsg, nil, qo.encoding) select { case <-queryQuit: return case <-s.quit: return case <-peerQuit: return case <-timeout: } } }(sp, peerQuits[sp.Addr()]) } // This goroutine will wait until all of the peer-query goroutines have // terminated, and then initiate a query shutdown. go func() { wg.Wait() // Make sure our main goroutine and the subscription know to // quit. close(allQuit) // Close the done channel, if any. if qo.doneChan != nil { close(qo.doneChan) } }() // Loop for any messages sent to us via our subscription channel and // check them for whether they satisfy the query. Break the loop when // allQuit is closed. checkResponses: for { select { case <-queryQuit: break checkResponses case <-s.quit: break checkResponses case <-allQuit: break checkResponses // A message has arrived over the subscription channel, so we // execute the checkResponses callback to see if this ends our // query session. case sm := <-msgChan: // TODO: This will get stuck if checkResponse gets // stuck. This is a caveat for callers that should be // fixed before exposing this function for public use. select { case <-peerQuits[sm.sp.Addr()]: default: checkResponse(sm.sp, sm.msg, queryQuit, peerQuits[sm.sp.Addr()]) } } } }
[ "func", "(", "s", "*", "ChainService", ")", "queryAllPeers", "(", "// queryMsg is the message to broadcast to all peers.", "queryMsg", "wire", ".", "Message", ",", "// checkResponse is called for every message within the timeout period.", "// The quit channel lets the query know to terminate because the", "// required response has been found. This is done by closing the", "// channel. The peerQuit lets the query know to terminate the query for", "// the peer which sent the response, allowing releasing resources for", "// peers which respond quickly while continuing to wait for slower", "// peers to respond and nonresponsive peers to time out.", "checkResponse", "func", "(", "sp", "*", "ServerPeer", ",", "resp", "wire", ".", "Message", ",", "quit", "chan", "<-", "struct", "{", "}", ",", "peerQuit", "chan", "<-", "struct", "{", "}", ")", ",", "// options takes functional options for executing the query.", "options", "...", "QueryOption", ")", "{", "// Starting with the set of default options, we'll apply any specified", "// functional options to the query.", "qo", ":=", "defaultQueryOptions", "(", ")", "\n", "qo", ".", "numRetries", "=", "1", "\n", "qo", ".", "applyQueryOptions", "(", "options", "...", ")", "\n\n", "// This is done in a single-threaded query because the peerState is", "// held in a single thread. This is the only part of the query", "// framework that requires access to peerState, so it's done once per", "// query.", "peers", ":=", "s", ".", "Peers", "(", ")", "\n\n", "// This will be shared state between the per-peer goroutines.", "queryQuit", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "allQuit", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "var", "wg", "sync", ".", "WaitGroup", "\n", "msgChan", ":=", "make", "(", "chan", "spMsg", ")", "\n", "subscription", ":=", "spMsgSubscription", "{", "msgChan", ":", "msgChan", ",", "quitChan", ":", "allQuit", ",", "}", "\n\n", "// Now we start a goroutine for each peer which manages the peer's", "// message subscription.", "peerQuits", ":=", "make", "(", "map", "[", "string", "]", "chan", "struct", "{", "}", ")", "\n", "for", "_", ",", "sp", ":=", "range", "peers", "{", "sp", ".", "subscribeRecvMsg", "(", "subscription", ")", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "peerQuits", "[", "sp", ".", "Addr", "(", ")", "]", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", "sp", "*", "ServerPeer", ",", "peerQuit", "<-", "chan", "struct", "{", "}", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n\n", "defer", "sp", ".", "unsubscribeRecvMsgs", "(", "subscription", ")", "\n\n", "for", "i", ":=", "uint8", "(", "0", ")", ";", "i", "<", "qo", ".", "numRetries", ";", "i", "++", "{", "timeout", ":=", "time", ".", "After", "(", "qo", ".", "timeout", ")", "\n", "sp", ".", "QueueMessageWithEncoding", "(", "queryMsg", ",", "nil", ",", "qo", ".", "encoding", ")", "\n", "select", "{", "case", "<-", "queryQuit", ":", "return", "\n", "case", "<-", "s", ".", "quit", ":", "return", "\n", "case", "<-", "peerQuit", ":", "return", "\n", "case", "<-", "timeout", ":", "}", "\n", "}", "\n", "}", "(", "sp", ",", "peerQuits", "[", "sp", ".", "Addr", "(", ")", "]", ")", "\n", "}", "\n\n", "// This goroutine will wait until all of the peer-query goroutines have", "// terminated, and then initiate a query shutdown.", "go", "func", "(", ")", "{", "wg", ".", "Wait", "(", ")", "\n\n", "// Make sure our main goroutine and the subscription know to", "// quit.", "close", "(", "allQuit", ")", "\n\n", "// Close the done channel, if any.", "if", "qo", ".", "doneChan", "!=", "nil", "{", "close", "(", "qo", ".", "doneChan", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// Loop for any messages sent to us via our subscription channel and", "// check them for whether they satisfy the query. Break the loop when", "// allQuit is closed.", "checkResponses", ":", "for", "{", "select", "{", "case", "<-", "queryQuit", ":", "break", "checkResponses", "\n\n", "case", "<-", "s", ".", "quit", ":", "break", "checkResponses", "\n\n", "case", "<-", "allQuit", ":", "break", "checkResponses", "\n\n", "// A message has arrived over the subscription channel, so we", "// execute the checkResponses callback to see if this ends our", "// query session.", "case", "sm", ":=", "<-", "msgChan", ":", "// TODO: This will get stuck if checkResponse gets", "// stuck. This is a caveat for callers that should be", "// fixed before exposing this function for public use.", "select", "{", "case", "<-", "peerQuits", "[", "sm", ".", "sp", ".", "Addr", "(", ")", "]", ":", "default", ":", "checkResponse", "(", "sm", ".", "sp", ",", "sm", ".", "msg", ",", "queryQuit", ",", "peerQuits", "[", "sm", ".", "sp", ".", "Addr", "(", ")", "]", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// queryAllPeers is a helper function that sends a query to all peers and waits // for a timeout specified by the QueryTimeout package-level variable or the // Timeout functional option. The NumRetries option is set to 1 by default // unless overridden by the caller.
[ "queryAllPeers", "is", "a", "helper", "function", "that", "sends", "a", "query", "to", "all", "peers", "and", "waits", "for", "a", "timeout", "specified", "by", "the", "QueryTimeout", "package", "-", "level", "variable", "or", "the", "Timeout", "functional", "option", ".", "The", "NumRetries", "option", "is", "set", "to", "1", "by", "default", "unless", "overridden", "by", "the", "caller", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/query.go#L496-L609
train
lightninglabs/neutrino
query.go
queryChainServicePeers
func queryChainServicePeers( // s is the ChainService to use. s *ChainService, // queryMsg is the message to send to each peer selected by selectPeer. queryMsg wire.Message, // checkResponse is called for every message within the timeout period. // The quit channel lets the query know to terminate because the // required response has been found. This is done by closing the // channel. checkResponse func(sp *ServerPeer, resp wire.Message, quit chan<- struct{}), // options takes functional options for executing the query. options ...QueryOption) { // Starting with the set of default options, we'll apply any specified // functional options to the query. qo := defaultQueryOptions() qo.applyQueryOptions(options...) // We get an initial view of our peers, to be updated each time a peer // query times out. queryPeer := s.blockManager.SyncPeer() peerTries := make(map[string]uint8) // This will be state used by the peer query goroutine. queryQuit := make(chan struct{}) subQuit := make(chan struct{}) // Increase this number to be able to handle more queries at once as // each channel gets results for all queries, otherwise messages can // get mixed and there's a vicious cycle of retries causing a bigger // message flood, more of which get missed. msgChan := make(chan spMsg) subscription := spMsgSubscription{ msgChan: msgChan, quitChan: subQuit, } // Loop for any messages sent to us via our subscription channel and // check them for whether they satisfy the query. Break the loop if // it's time to quit. peerTimeout := time.NewTicker(qo.timeout) timeout := time.After(qo.peerConnectTimeout) if queryPeer != nil { peerTries[queryPeer.Addr()]++ queryPeer.subscribeRecvMsg(subscription) queryPeer.QueueMessageWithEncoding(queryMsg, nil, qo.encoding) } checkResponses: for { select { case <-timeout: // When we time out, we're done. if queryPeer != nil { queryPeer.unsubscribeRecvMsgs(subscription) } break checkResponses case <-queryQuit: // Same when we get a quit signal. if queryPeer != nil { queryPeer.unsubscribeRecvMsgs(subscription) } break checkResponses case <-s.quit: // Same when chain server's quit is signaled. if queryPeer != nil { queryPeer.unsubscribeRecvMsgs(subscription) } break checkResponses // A message has arrived over the subscription channel, so we // execute the checkResponses callback to see if this ends our // query session. case sm := <-msgChan: // TODO: This will get stuck if checkResponse gets // stuck. This is a caveat for callers that should be // fixed before exposing this function for public use. checkResponse(sm.sp, sm.msg, queryQuit) // The current peer we're querying has failed to answer the // query. Time to select a new peer and query it. case <-peerTimeout.C: if queryPeer != nil { queryPeer.unsubscribeRecvMsgs(subscription) } queryPeer = nil for _, peer := range s.Peers() { // If the peer is no longer connected, we'll // skip them. if !peer.Connected() { continue } // If we've yet to try this peer, we'll make // sure to do so. If we've exceeded the number // of tries we should retry this peer, then // we'll skip them. numTries, ok := peerTries[peer.Addr()] if ok && numTries >= qo.numRetries { continue } queryPeer = peer // Found a peer we can query. peerTries[queryPeer.Addr()]++ queryPeer.subscribeRecvMsg(subscription) queryPeer.QueueMessageWithEncoding( queryMsg, nil, qo.encoding, ) break } // If at this point, we don't yet have a query peer, // then we'll exit now as all the peers are exhausted. if queryPeer == nil { break checkResponses } } } // Close the subscription quit channel and the done channel, if any. close(subQuit) peerTimeout.Stop() if qo.doneChan != nil { close(qo.doneChan) } }
go
func queryChainServicePeers( // s is the ChainService to use. s *ChainService, // queryMsg is the message to send to each peer selected by selectPeer. queryMsg wire.Message, // checkResponse is called for every message within the timeout period. // The quit channel lets the query know to terminate because the // required response has been found. This is done by closing the // channel. checkResponse func(sp *ServerPeer, resp wire.Message, quit chan<- struct{}), // options takes functional options for executing the query. options ...QueryOption) { // Starting with the set of default options, we'll apply any specified // functional options to the query. qo := defaultQueryOptions() qo.applyQueryOptions(options...) // We get an initial view of our peers, to be updated each time a peer // query times out. queryPeer := s.blockManager.SyncPeer() peerTries := make(map[string]uint8) // This will be state used by the peer query goroutine. queryQuit := make(chan struct{}) subQuit := make(chan struct{}) // Increase this number to be able to handle more queries at once as // each channel gets results for all queries, otherwise messages can // get mixed and there's a vicious cycle of retries causing a bigger // message flood, more of which get missed. msgChan := make(chan spMsg) subscription := spMsgSubscription{ msgChan: msgChan, quitChan: subQuit, } // Loop for any messages sent to us via our subscription channel and // check them for whether they satisfy the query. Break the loop if // it's time to quit. peerTimeout := time.NewTicker(qo.timeout) timeout := time.After(qo.peerConnectTimeout) if queryPeer != nil { peerTries[queryPeer.Addr()]++ queryPeer.subscribeRecvMsg(subscription) queryPeer.QueueMessageWithEncoding(queryMsg, nil, qo.encoding) } checkResponses: for { select { case <-timeout: // When we time out, we're done. if queryPeer != nil { queryPeer.unsubscribeRecvMsgs(subscription) } break checkResponses case <-queryQuit: // Same when we get a quit signal. if queryPeer != nil { queryPeer.unsubscribeRecvMsgs(subscription) } break checkResponses case <-s.quit: // Same when chain server's quit is signaled. if queryPeer != nil { queryPeer.unsubscribeRecvMsgs(subscription) } break checkResponses // A message has arrived over the subscription channel, so we // execute the checkResponses callback to see if this ends our // query session. case sm := <-msgChan: // TODO: This will get stuck if checkResponse gets // stuck. This is a caveat for callers that should be // fixed before exposing this function for public use. checkResponse(sm.sp, sm.msg, queryQuit) // The current peer we're querying has failed to answer the // query. Time to select a new peer and query it. case <-peerTimeout.C: if queryPeer != nil { queryPeer.unsubscribeRecvMsgs(subscription) } queryPeer = nil for _, peer := range s.Peers() { // If the peer is no longer connected, we'll // skip them. if !peer.Connected() { continue } // If we've yet to try this peer, we'll make // sure to do so. If we've exceeded the number // of tries we should retry this peer, then // we'll skip them. numTries, ok := peerTries[peer.Addr()] if ok && numTries >= qo.numRetries { continue } queryPeer = peer // Found a peer we can query. peerTries[queryPeer.Addr()]++ queryPeer.subscribeRecvMsg(subscription) queryPeer.QueueMessageWithEncoding( queryMsg, nil, qo.encoding, ) break } // If at this point, we don't yet have a query peer, // then we'll exit now as all the peers are exhausted. if queryPeer == nil { break checkResponses } } } // Close the subscription quit channel and the done channel, if any. close(subQuit) peerTimeout.Stop() if qo.doneChan != nil { close(qo.doneChan) } }
[ "func", "queryChainServicePeers", "(", "// s is the ChainService to use.", "s", "*", "ChainService", ",", "// queryMsg is the message to send to each peer selected by selectPeer.", "queryMsg", "wire", ".", "Message", ",", "// checkResponse is called for every message within the timeout period.", "// The quit channel lets the query know to terminate because the", "// required response has been found. This is done by closing the", "// channel.", "checkResponse", "func", "(", "sp", "*", "ServerPeer", ",", "resp", "wire", ".", "Message", ",", "quit", "chan", "<-", "struct", "{", "}", ")", ",", "// options takes functional options for executing the query.", "options", "...", "QueryOption", ")", "{", "// Starting with the set of default options, we'll apply any specified", "// functional options to the query.", "qo", ":=", "defaultQueryOptions", "(", ")", "\n", "qo", ".", "applyQueryOptions", "(", "options", "...", ")", "\n\n", "// We get an initial view of our peers, to be updated each time a peer", "// query times out.", "queryPeer", ":=", "s", ".", "blockManager", ".", "SyncPeer", "(", ")", "\n", "peerTries", ":=", "make", "(", "map", "[", "string", "]", "uint8", ")", "\n\n", "// This will be state used by the peer query goroutine.", "queryQuit", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "subQuit", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n\n", "// Increase this number to be able to handle more queries at once as", "// each channel gets results for all queries, otherwise messages can", "// get mixed and there's a vicious cycle of retries causing a bigger", "// message flood, more of which get missed.", "msgChan", ":=", "make", "(", "chan", "spMsg", ")", "\n", "subscription", ":=", "spMsgSubscription", "{", "msgChan", ":", "msgChan", ",", "quitChan", ":", "subQuit", ",", "}", "\n\n", "// Loop for any messages sent to us via our subscription channel and", "// check them for whether they satisfy the query. Break the loop if", "// it's time to quit.", "peerTimeout", ":=", "time", ".", "NewTicker", "(", "qo", ".", "timeout", ")", "\n", "timeout", ":=", "time", ".", "After", "(", "qo", ".", "peerConnectTimeout", ")", "\n", "if", "queryPeer", "!=", "nil", "{", "peerTries", "[", "queryPeer", ".", "Addr", "(", ")", "]", "++", "\n", "queryPeer", ".", "subscribeRecvMsg", "(", "subscription", ")", "\n", "queryPeer", ".", "QueueMessageWithEncoding", "(", "queryMsg", ",", "nil", ",", "qo", ".", "encoding", ")", "\n", "}", "\n", "checkResponses", ":", "for", "{", "select", "{", "case", "<-", "timeout", ":", "// When we time out, we're done.", "if", "queryPeer", "!=", "nil", "{", "queryPeer", ".", "unsubscribeRecvMsgs", "(", "subscription", ")", "\n", "}", "\n", "break", "checkResponses", "\n\n", "case", "<-", "queryQuit", ":", "// Same when we get a quit signal.", "if", "queryPeer", "!=", "nil", "{", "queryPeer", ".", "unsubscribeRecvMsgs", "(", "subscription", ")", "\n", "}", "\n", "break", "checkResponses", "\n\n", "case", "<-", "s", ".", "quit", ":", "// Same when chain server's quit is signaled.", "if", "queryPeer", "!=", "nil", "{", "queryPeer", ".", "unsubscribeRecvMsgs", "(", "subscription", ")", "\n", "}", "\n", "break", "checkResponses", "\n\n", "// A message has arrived over the subscription channel, so we", "// execute the checkResponses callback to see if this ends our", "// query session.", "case", "sm", ":=", "<-", "msgChan", ":", "// TODO: This will get stuck if checkResponse gets", "// stuck. This is a caveat for callers that should be", "// fixed before exposing this function for public use.", "checkResponse", "(", "sm", ".", "sp", ",", "sm", ".", "msg", ",", "queryQuit", ")", "\n\n", "// The current peer we're querying has failed to answer the", "// query. Time to select a new peer and query it.", "case", "<-", "peerTimeout", ".", "C", ":", "if", "queryPeer", "!=", "nil", "{", "queryPeer", ".", "unsubscribeRecvMsgs", "(", "subscription", ")", "\n", "}", "\n\n", "queryPeer", "=", "nil", "\n", "for", "_", ",", "peer", ":=", "range", "s", ".", "Peers", "(", ")", "{", "// If the peer is no longer connected, we'll", "// skip them.", "if", "!", "peer", ".", "Connected", "(", ")", "{", "continue", "\n", "}", "\n\n", "// If we've yet to try this peer, we'll make", "// sure to do so. If we've exceeded the number", "// of tries we should retry this peer, then", "// we'll skip them.", "numTries", ",", "ok", ":=", "peerTries", "[", "peer", ".", "Addr", "(", ")", "]", "\n", "if", "ok", "&&", "numTries", ">=", "qo", ".", "numRetries", "{", "continue", "\n", "}", "\n\n", "queryPeer", "=", "peer", "\n\n", "// Found a peer we can query.", "peerTries", "[", "queryPeer", ".", "Addr", "(", ")", "]", "++", "\n", "queryPeer", ".", "subscribeRecvMsg", "(", "subscription", ")", "\n", "queryPeer", ".", "QueueMessageWithEncoding", "(", "queryMsg", ",", "nil", ",", "qo", ".", "encoding", ",", ")", "\n", "break", "\n", "}", "\n\n", "// If at this point, we don't yet have a query peer,", "// then we'll exit now as all the peers are exhausted.", "if", "queryPeer", "==", "nil", "{", "break", "checkResponses", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Close the subscription quit channel and the done channel, if any.", "close", "(", "subQuit", ")", "\n", "peerTimeout", ".", "Stop", "(", ")", "\n", "if", "qo", ".", "doneChan", "!=", "nil", "{", "close", "(", "qo", ".", "doneChan", ")", "\n", "}", "\n", "}" ]
// queryChainServicePeers is a helper function that sends a query to one or // more peers of the given ChainService, and waits for an answer. The timeout // for queries is set by the QueryTimeout package-level variable or the Timeout // functional option.
[ "queryChainServicePeers", "is", "a", "helper", "function", "that", "sends", "a", "query", "to", "one", "or", "more", "peers", "of", "the", "given", "ChainService", "and", "waits", "for", "an", "answer", ".", "The", "timeout", "for", "queries", "is", "set", "by", "the", "QueryTimeout", "package", "-", "level", "variable", "or", "the", "Timeout", "functional", "option", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/query.go#L615-L748
train
lightninglabs/neutrino
query.go
getFilterFromCache
func (s *ChainService) getFilterFromCache(blockHash *chainhash.Hash, filterType filterdb.FilterType) (*gcs.Filter, error) { cacheKey := cache.FilterCacheKey{*blockHash, filterType} filterValue, err := s.FilterCache.Get(cacheKey) if err != nil { return nil, err } return filterValue.(*cache.CacheableFilter).Filter, nil }
go
func (s *ChainService) getFilterFromCache(blockHash *chainhash.Hash, filterType filterdb.FilterType) (*gcs.Filter, error) { cacheKey := cache.FilterCacheKey{*blockHash, filterType} filterValue, err := s.FilterCache.Get(cacheKey) if err != nil { return nil, err } return filterValue.(*cache.CacheableFilter).Filter, nil }
[ "func", "(", "s", "*", "ChainService", ")", "getFilterFromCache", "(", "blockHash", "*", "chainhash", ".", "Hash", ",", "filterType", "filterdb", ".", "FilterType", ")", "(", "*", "gcs", ".", "Filter", ",", "error", ")", "{", "cacheKey", ":=", "cache", ".", "FilterCacheKey", "{", "*", "blockHash", ",", "filterType", "}", "\n\n", "filterValue", ",", "err", ":=", "s", ".", "FilterCache", ".", "Get", "(", "cacheKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "filterValue", ".", "(", "*", "cache", ".", "CacheableFilter", ")", ".", "Filter", ",", "nil", "\n", "}" ]
// getFilterFromCache returns a filter from ChainService's FilterCache if it // exists, returning nil and error if it doesn't.
[ "getFilterFromCache", "returns", "a", "filter", "from", "ChainService", "s", "FilterCache", "if", "it", "exists", "returning", "nil", "and", "error", "if", "it", "doesn", "t", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/query.go#L752-L763
train
lightninglabs/neutrino
query.go
putFilterToCache
func (s *ChainService) putFilterToCache(blockHash *chainhash.Hash, filterType filterdb.FilterType, filter *gcs.Filter) (bool, error) { cacheKey := cache.FilterCacheKey{*blockHash, filterType} return s.FilterCache.Put(cacheKey, &cache.CacheableFilter{Filter: filter}) }
go
func (s *ChainService) putFilterToCache(blockHash *chainhash.Hash, filterType filterdb.FilterType, filter *gcs.Filter) (bool, error) { cacheKey := cache.FilterCacheKey{*blockHash, filterType} return s.FilterCache.Put(cacheKey, &cache.CacheableFilter{Filter: filter}) }
[ "func", "(", "s", "*", "ChainService", ")", "putFilterToCache", "(", "blockHash", "*", "chainhash", ".", "Hash", ",", "filterType", "filterdb", ".", "FilterType", ",", "filter", "*", "gcs", ".", "Filter", ")", "(", "bool", ",", "error", ")", "{", "cacheKey", ":=", "cache", ".", "FilterCacheKey", "{", "*", "blockHash", ",", "filterType", "}", "\n", "return", "s", ".", "FilterCache", ".", "Put", "(", "cacheKey", ",", "&", "cache", ".", "CacheableFilter", "{", "Filter", ":", "filter", "}", ")", "\n", "}" ]
// putFilterToCache inserts a given filter in ChainService's FilterCache.
[ "putFilterToCache", "inserts", "a", "given", "filter", "in", "ChainService", "s", "FilterCache", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/query.go#L766-L771
train
lightninglabs/neutrino
query.go
queryMsg
func (q *cfiltersQuery) queryMsg() wire.Message { return wire.NewMsgGetCFilters( q.filterType, uint32(q.startHeight), q.stopHash, ) }
go
func (q *cfiltersQuery) queryMsg() wire.Message { return wire.NewMsgGetCFilters( q.filterType, uint32(q.startHeight), q.stopHash, ) }
[ "func", "(", "q", "*", "cfiltersQuery", ")", "queryMsg", "(", ")", "wire", ".", "Message", "{", "return", "wire", ".", "NewMsgGetCFilters", "(", "q", ".", "filterType", ",", "uint32", "(", "q", ".", "startHeight", ")", ",", "q", ".", "stopHash", ",", ")", "\n", "}" ]
// queryMsg returns the wire message to perform this query.
[ "queryMsg", "returns", "the", "wire", "message", "to", "perform", "this", "query", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/query.go#L788-L792
train
lightninglabs/neutrino
query.go
handleCFiltersResponse
func (s *ChainService) handleCFiltersResponse(q *cfiltersQuery, resp wire.Message, quit chan<- struct{}) { // We're only interested in "cfilter" messages. response, ok := resp.(*wire.MsgCFilter) if !ok { return } // If the response doesn't match our request, ignore this message. if q.filterType != response.FilterType { return } // If this filter is for a block not in our index, we can ignore it, as // we either already got it, or it is out of our queried range. i, ok := q.headerIndex[response.BlockHash] if !ok { return } gotFilter, err := gcs.FromNBytes( builder.DefaultP, builder.DefaultM, response.Data, ) if err != nil { // Malformed filter data. We can ignore this message. return } // Now that we have a proper filter, ensure that re-calculating the // filter header hash for the header _after_ the filter in the chain // checks out. If not, we can ignore this response. curHeader := q.filterHeaders[i] prevHeader := q.filterHeaders[i-1] gotHeader, err := builder.MakeHeaderForFilter( gotFilter, prevHeader, ) if err != nil { return } if gotHeader != curHeader { return } // At this point, the filter matches what we know about it and we // declare it sane. If this is the filter requested initially, send it // to the caller immediately. if response.BlockHash == q.targetHash { q.filterChan <- gotFilter } // Put the filter in the cache and persistToDisk if the caller // requested it. // TODO(halseth): for an LRU we could take care to insert the next // height filter last. dbFilterType := filterdb.RegularFilter evict, err := s.putFilterToCache( &response.BlockHash, dbFilterType, gotFilter, ) if err != nil { log.Warnf("Couldn't write filter to cache: %v", err) } // TODO(halseth): dynamically increase/decrease the batch size to match // our cache capacity. numFilters := q.stopHeight - q.startHeight + 1 if evict && s.FilterCache.Len() < int(numFilters) { log.Debugf("Items evicted from the cache with less "+ "than %d elements. Consider increasing the "+ "cache size...", numFilters) } qo := defaultQueryOptions() qo.applyQueryOptions(q.options...) if qo.persistToDisk { err = s.FilterDB.PutFilter( &response.BlockHash, gotFilter, dbFilterType, ) if err != nil { log.Warnf("Couldn't write filter to filterDB: "+ "%v", err) } log.Tracef("Wrote filter for block %s, type %d", &response.BlockHash, dbFilterType) } // Finally, we can delete it from the headerIndex. delete(q.headerIndex, response.BlockHash) // If the headerIndex is empty, we got everything we wanted, and can // exit. if len(q.headerIndex) == 0 { close(quit) } }
go
func (s *ChainService) handleCFiltersResponse(q *cfiltersQuery, resp wire.Message, quit chan<- struct{}) { // We're only interested in "cfilter" messages. response, ok := resp.(*wire.MsgCFilter) if !ok { return } // If the response doesn't match our request, ignore this message. if q.filterType != response.FilterType { return } // If this filter is for a block not in our index, we can ignore it, as // we either already got it, or it is out of our queried range. i, ok := q.headerIndex[response.BlockHash] if !ok { return } gotFilter, err := gcs.FromNBytes( builder.DefaultP, builder.DefaultM, response.Data, ) if err != nil { // Malformed filter data. We can ignore this message. return } // Now that we have a proper filter, ensure that re-calculating the // filter header hash for the header _after_ the filter in the chain // checks out. If not, we can ignore this response. curHeader := q.filterHeaders[i] prevHeader := q.filterHeaders[i-1] gotHeader, err := builder.MakeHeaderForFilter( gotFilter, prevHeader, ) if err != nil { return } if gotHeader != curHeader { return } // At this point, the filter matches what we know about it and we // declare it sane. If this is the filter requested initially, send it // to the caller immediately. if response.BlockHash == q.targetHash { q.filterChan <- gotFilter } // Put the filter in the cache and persistToDisk if the caller // requested it. // TODO(halseth): for an LRU we could take care to insert the next // height filter last. dbFilterType := filterdb.RegularFilter evict, err := s.putFilterToCache( &response.BlockHash, dbFilterType, gotFilter, ) if err != nil { log.Warnf("Couldn't write filter to cache: %v", err) } // TODO(halseth): dynamically increase/decrease the batch size to match // our cache capacity. numFilters := q.stopHeight - q.startHeight + 1 if evict && s.FilterCache.Len() < int(numFilters) { log.Debugf("Items evicted from the cache with less "+ "than %d elements. Consider increasing the "+ "cache size...", numFilters) } qo := defaultQueryOptions() qo.applyQueryOptions(q.options...) if qo.persistToDisk { err = s.FilterDB.PutFilter( &response.BlockHash, gotFilter, dbFilterType, ) if err != nil { log.Warnf("Couldn't write filter to filterDB: "+ "%v", err) } log.Tracef("Wrote filter for block %s, type %d", &response.BlockHash, dbFilterType) } // Finally, we can delete it from the headerIndex. delete(q.headerIndex, response.BlockHash) // If the headerIndex is empty, we got everything we wanted, and can // exit. if len(q.headerIndex) == 0 { close(quit) } }
[ "func", "(", "s", "*", "ChainService", ")", "handleCFiltersResponse", "(", "q", "*", "cfiltersQuery", ",", "resp", "wire", ".", "Message", ",", "quit", "chan", "<-", "struct", "{", "}", ")", "{", "// We're only interested in \"cfilter\" messages.", "response", ",", "ok", ":=", "resp", ".", "(", "*", "wire", ".", "MsgCFilter", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n\n", "// If the response doesn't match our request, ignore this message.", "if", "q", ".", "filterType", "!=", "response", ".", "FilterType", "{", "return", "\n", "}", "\n\n", "// If this filter is for a block not in our index, we can ignore it, as", "// we either already got it, or it is out of our queried range.", "i", ",", "ok", ":=", "q", ".", "headerIndex", "[", "response", ".", "BlockHash", "]", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n\n", "gotFilter", ",", "err", ":=", "gcs", ".", "FromNBytes", "(", "builder", ".", "DefaultP", ",", "builder", ".", "DefaultM", ",", "response", ".", "Data", ",", ")", "\n", "if", "err", "!=", "nil", "{", "// Malformed filter data. We can ignore this message.", "return", "\n", "}", "\n\n", "// Now that we have a proper filter, ensure that re-calculating the", "// filter header hash for the header _after_ the filter in the chain", "// checks out. If not, we can ignore this response.", "curHeader", ":=", "q", ".", "filterHeaders", "[", "i", "]", "\n", "prevHeader", ":=", "q", ".", "filterHeaders", "[", "i", "-", "1", "]", "\n", "gotHeader", ",", "err", ":=", "builder", ".", "MakeHeaderForFilter", "(", "gotFilter", ",", "prevHeader", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "if", "gotHeader", "!=", "curHeader", "{", "return", "\n", "}", "\n\n", "// At this point, the filter matches what we know about it and we", "// declare it sane. If this is the filter requested initially, send it", "// to the caller immediately.", "if", "response", ".", "BlockHash", "==", "q", ".", "targetHash", "{", "q", ".", "filterChan", "<-", "gotFilter", "\n", "}", "\n\n", "// Put the filter in the cache and persistToDisk if the caller", "// requested it.", "// TODO(halseth): for an LRU we could take care to insert the next", "// height filter last.", "dbFilterType", ":=", "filterdb", ".", "RegularFilter", "\n", "evict", ",", "err", ":=", "s", ".", "putFilterToCache", "(", "&", "response", ".", "BlockHash", ",", "dbFilterType", ",", "gotFilter", ",", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// TODO(halseth): dynamically increase/decrease the batch size to match", "// our cache capacity.", "numFilters", ":=", "q", ".", "stopHeight", "-", "q", ".", "startHeight", "+", "1", "\n", "if", "evict", "&&", "s", ".", "FilterCache", ".", "Len", "(", ")", "<", "int", "(", "numFilters", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "numFilters", ")", "\n", "}", "\n\n", "qo", ":=", "defaultQueryOptions", "(", ")", "\n", "qo", ".", "applyQueryOptions", "(", "q", ".", "options", "...", ")", "\n", "if", "qo", ".", "persistToDisk", "{", "err", "=", "s", ".", "FilterDB", ".", "PutFilter", "(", "&", "response", ".", "BlockHash", ",", "gotFilter", ",", "dbFilterType", ",", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "&", "response", ".", "BlockHash", ",", "dbFilterType", ")", "\n", "}", "\n\n", "// Finally, we can delete it from the headerIndex.", "delete", "(", "q", ".", "headerIndex", ",", "response", ".", "BlockHash", ")", "\n\n", "// If the headerIndex is empty, we got everything we wanted, and can", "// exit.", "if", "len", "(", "q", ".", "headerIndex", ")", "==", "0", "{", "close", "(", "quit", ")", "\n", "}", "\n", "}" ]
// handleCFiltersRespons is called every time we receive a response for the // GetCFilters request.
[ "handleCFiltersRespons", "is", "called", "every", "time", "we", "receive", "a", "response", "for", "the", "GetCFilters", "request", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/query.go#L928-L1024
train
lightninglabs/neutrino
query.go
GetCFilter
func (s *ChainService) GetCFilter(blockHash chainhash.Hash, filterType wire.FilterType, options ...QueryOption) (*gcs.Filter, error) { // The only supported filter atm is the regular filter, so we'll reject // all other filters. if filterType != wire.GCSFilterRegular { return nil, fmt.Errorf("unknown filter type: %v", filterType) } // Based on if extended is true or not, we'll set up our set of // querying, and db-write functions. dbFilterType := filterdb.RegularFilter // First check the cache to see if we already have this filter. If // so, then we can return it an exit early. filter, err := s.getFilterFromCache(&blockHash, dbFilterType) if err == nil && filter != nil { return filter, nil } if err != nil && err != cache.ErrElementNotFound { return nil, err } // If not in cache, check if it's in database, returning early if yes. filter, err = s.FilterDB.FetchFilter(&blockHash, dbFilterType) if err == nil && filter != nil { return filter, nil } if err != nil && err != filterdb.ErrFilterNotFound { return nil, err } // We acquire the mutex ensuring we don't have several redundant // CFilter queries running in parallel. s.mtxCFilter.Lock() // Since another request might have added the filter to the cache while // we were waiting for the mutex, we do a final lookup before starting // our own query. filter, err = s.getFilterFromCache(&blockHash, dbFilterType) if err == nil && filter != nil { s.mtxCFilter.Unlock() return filter, nil } if err != nil && err != cache.ErrElementNotFound { s.mtxCFilter.Unlock() return nil, err } // We didn't get the filter from the DB, so we'll try to get it from // the network. query, err := s.prepareCFiltersQuery(blockHash, filterType, options...) if err != nil { s.mtxCFilter.Unlock() return nil, err } // With all the necessary items retrieved, we'll launch our concurrent // query to the set of connected peers. log.Debugf("Fetching filters for heights=[%v, %v], stophash=%v", query.startHeight, query.stopHeight, query.stopHash) go func() { defer s.mtxCFilter.Unlock() defer close(query.filterChan) s.queryPeers( // Send a wire.MsgGetCFilters query.queryMsg(), // Check responses and if we get one that matches, end // the query early. func(_ *ServerPeer, resp wire.Message, quit chan<- struct{}) { s.handleCFiltersResponse(query, resp, quit) }, query.options..., ) // If there are elements left to receive, the query failed. if len(query.headerIndex) > 0 { numFilters := query.stopHeight - query.startHeight + 1 log.Errorf("Query failed with %d out of %d filters "+ "received", len(query.headerIndex), numFilters) return } }() var ok bool select { // We'll return immediately to the caller when the filter arrives. case filter, ok = <-query.filterChan: if !ok { // TODO(halseth): return error? return nil, nil } return filter, nil case <-s.quit: // TODO(halseth): return error? return nil, nil } }
go
func (s *ChainService) GetCFilter(blockHash chainhash.Hash, filterType wire.FilterType, options ...QueryOption) (*gcs.Filter, error) { // The only supported filter atm is the regular filter, so we'll reject // all other filters. if filterType != wire.GCSFilterRegular { return nil, fmt.Errorf("unknown filter type: %v", filterType) } // Based on if extended is true or not, we'll set up our set of // querying, and db-write functions. dbFilterType := filterdb.RegularFilter // First check the cache to see if we already have this filter. If // so, then we can return it an exit early. filter, err := s.getFilterFromCache(&blockHash, dbFilterType) if err == nil && filter != nil { return filter, nil } if err != nil && err != cache.ErrElementNotFound { return nil, err } // If not in cache, check if it's in database, returning early if yes. filter, err = s.FilterDB.FetchFilter(&blockHash, dbFilterType) if err == nil && filter != nil { return filter, nil } if err != nil && err != filterdb.ErrFilterNotFound { return nil, err } // We acquire the mutex ensuring we don't have several redundant // CFilter queries running in parallel. s.mtxCFilter.Lock() // Since another request might have added the filter to the cache while // we were waiting for the mutex, we do a final lookup before starting // our own query. filter, err = s.getFilterFromCache(&blockHash, dbFilterType) if err == nil && filter != nil { s.mtxCFilter.Unlock() return filter, nil } if err != nil && err != cache.ErrElementNotFound { s.mtxCFilter.Unlock() return nil, err } // We didn't get the filter from the DB, so we'll try to get it from // the network. query, err := s.prepareCFiltersQuery(blockHash, filterType, options...) if err != nil { s.mtxCFilter.Unlock() return nil, err } // With all the necessary items retrieved, we'll launch our concurrent // query to the set of connected peers. log.Debugf("Fetching filters for heights=[%v, %v], stophash=%v", query.startHeight, query.stopHeight, query.stopHash) go func() { defer s.mtxCFilter.Unlock() defer close(query.filterChan) s.queryPeers( // Send a wire.MsgGetCFilters query.queryMsg(), // Check responses and if we get one that matches, end // the query early. func(_ *ServerPeer, resp wire.Message, quit chan<- struct{}) { s.handleCFiltersResponse(query, resp, quit) }, query.options..., ) // If there are elements left to receive, the query failed. if len(query.headerIndex) > 0 { numFilters := query.stopHeight - query.startHeight + 1 log.Errorf("Query failed with %d out of %d filters "+ "received", len(query.headerIndex), numFilters) return } }() var ok bool select { // We'll return immediately to the caller when the filter arrives. case filter, ok = <-query.filterChan: if !ok { // TODO(halseth): return error? return nil, nil } return filter, nil case <-s.quit: // TODO(halseth): return error? return nil, nil } }
[ "func", "(", "s", "*", "ChainService", ")", "GetCFilter", "(", "blockHash", "chainhash", ".", "Hash", ",", "filterType", "wire", ".", "FilterType", ",", "options", "...", "QueryOption", ")", "(", "*", "gcs", ".", "Filter", ",", "error", ")", "{", "// The only supported filter atm is the regular filter, so we'll reject", "// all other filters.", "if", "filterType", "!=", "wire", ".", "GCSFilterRegular", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "filterType", ")", "\n", "}", "\n\n", "// Based on if extended is true or not, we'll set up our set of", "// querying, and db-write functions.", "dbFilterType", ":=", "filterdb", ".", "RegularFilter", "\n\n", "// First check the cache to see if we already have this filter. If", "// so, then we can return it an exit early.", "filter", ",", "err", ":=", "s", ".", "getFilterFromCache", "(", "&", "blockHash", ",", "dbFilterType", ")", "\n", "if", "err", "==", "nil", "&&", "filter", "!=", "nil", "{", "return", "filter", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "cache", ".", "ErrElementNotFound", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// If not in cache, check if it's in database, returning early if yes.", "filter", ",", "err", "=", "s", ".", "FilterDB", ".", "FetchFilter", "(", "&", "blockHash", ",", "dbFilterType", ")", "\n", "if", "err", "==", "nil", "&&", "filter", "!=", "nil", "{", "return", "filter", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "filterdb", ".", "ErrFilterNotFound", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// We acquire the mutex ensuring we don't have several redundant", "// CFilter queries running in parallel.", "s", ".", "mtxCFilter", ".", "Lock", "(", ")", "\n\n", "// Since another request might have added the filter to the cache while", "// we were waiting for the mutex, we do a final lookup before starting", "// our own query.", "filter", ",", "err", "=", "s", ".", "getFilterFromCache", "(", "&", "blockHash", ",", "dbFilterType", ")", "\n", "if", "err", "==", "nil", "&&", "filter", "!=", "nil", "{", "s", ".", "mtxCFilter", ".", "Unlock", "(", ")", "\n", "return", "filter", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "cache", ".", "ErrElementNotFound", "{", "s", ".", "mtxCFilter", ".", "Unlock", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// We didn't get the filter from the DB, so we'll try to get it from", "// the network.", "query", ",", "err", ":=", "s", ".", "prepareCFiltersQuery", "(", "blockHash", ",", "filterType", ",", "options", "...", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "mtxCFilter", ".", "Unlock", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// With all the necessary items retrieved, we'll launch our concurrent", "// query to the set of connected peers.", "log", ".", "Debugf", "(", "\"", "\"", ",", "query", ".", "startHeight", ",", "query", ".", "stopHeight", ",", "query", ".", "stopHash", ")", "\n\n", "go", "func", "(", ")", "{", "defer", "s", ".", "mtxCFilter", ".", "Unlock", "(", ")", "\n", "defer", "close", "(", "query", ".", "filterChan", ")", "\n\n", "s", ".", "queryPeers", "(", "// Send a wire.MsgGetCFilters", "query", ".", "queryMsg", "(", ")", ",", "// Check responses and if we get one that matches, end", "// the query early.", "func", "(", "_", "*", "ServerPeer", ",", "resp", "wire", ".", "Message", ",", "quit", "chan", "<-", "struct", "{", "}", ")", "{", "s", ".", "handleCFiltersResponse", "(", "query", ",", "resp", ",", "quit", ")", "\n", "}", ",", "query", ".", "options", "...", ",", ")", "\n\n", "// If there are elements left to receive, the query failed.", "if", "len", "(", "query", ".", "headerIndex", ")", ">", "0", "{", "numFilters", ":=", "query", ".", "stopHeight", "-", "query", ".", "startHeight", "+", "1", "\n", "log", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "len", "(", "query", ".", "headerIndex", ")", ",", "numFilters", ")", "\n", "return", "\n", "}", "\n", "}", "(", ")", "\n\n", "var", "ok", "bool", "\n", "select", "{", "// We'll return immediately to the caller when the filter arrives.", "case", "filter", ",", "ok", "=", "<-", "query", ".", "filterChan", ":", "if", "!", "ok", "{", "// TODO(halseth): return error?", "return", "nil", ",", "nil", "\n", "}", "\n\n", "return", "filter", ",", "nil", "\n\n", "case", "<-", "s", ".", "quit", ":", "// TODO(halseth): return error?", "return", "nil", ",", "nil", "\n", "}", "\n\n", "}" ]
// GetCFilter gets a cfilter from the database. Failing that, it requests the // cfilter from the network and writes it to the database. If extended is true, // an extended filter will be queried for. Otherwise, we'll fetch the regular // filter.
[ "GetCFilter", "gets", "a", "cfilter", "from", "the", "database", ".", "Failing", "that", "it", "requests", "the", "cfilter", "from", "the", "network", "and", "writes", "it", "to", "the", "database", ".", "If", "extended", "is", "true", "an", "extended", "filter", "will", "be", "queried", "for", ".", "Otherwise", "we", "ll", "fetch", "the", "regular", "filter", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/query.go#L1030-L1134
train
lightninglabs/neutrino
query.go
GetBlock
func (s *ChainService) GetBlock(blockHash chainhash.Hash, options ...QueryOption) (*btcutil.Block, error) { // Fetch the corresponding block header from the database. If this // isn't found, then we don't have the header for this block so we // can't request it. blockHeader, height, err := s.BlockHeaders.FetchHeader(&blockHash) if err != nil || blockHeader.BlockHash() != blockHash { return nil, fmt.Errorf("Couldn't get header for block %s "+ "from database", blockHash) } // Starting with the set of default options, we'll apply any specified // functional options to the query so that we can check what inv type // to use. qo := defaultQueryOptions() qo.applyQueryOptions(options...) invType := wire.InvTypeWitnessBlock if qo.encoding == wire.BaseEncoding { invType = wire.InvTypeBlock } // Create an inv vector for getting this block. inv := wire.NewInvVect(invType, &blockHash) // If the block is already in the cache, we can return it immediately. blockValue, err := s.BlockCache.Get(*inv) if err == nil && blockValue != nil { return blockValue.(*cache.CacheableBlock).Block, err } if err != nil && err != cache.ErrElementNotFound { return nil, err } // Construct the appropriate getdata message to fetch the target block. getData := wire.NewMsgGetData() getData.AddInvVect(inv) // The block is only updated from the checkResponse function argument, // which is always called single-threadedly. We don't check the block // until after the query is finished, so we can just write to it // naively. var foundBlock *btcutil.Block s.queryPeers( // Send a wire.GetDataMsg getData, // Check responses and if we get one that matches, end the // query early. func(sp *ServerPeer, resp wire.Message, quit chan<- struct{}) { switch response := resp.(type) { // We're only interested in "block" messages. case *wire.MsgBlock: // Only keep this going if we haven't already // found a block, or we risk closing an already // closed channel. if foundBlock != nil { return } // If this isn't our block, ignore it. if response.BlockHash() != blockHash { return } block := btcutil.NewBlock(response) // Only set height if btcutil hasn't // automagically put one in. if block.Height() == btcutil.BlockHeightUnknown { block.SetHeight(int32(height)) } // If this claims our block but doesn't pass // the sanity check, the peer is trying to // bamboozle us. Disconnect it. if err := blockchain.CheckBlockSanity( block, // We don't need to check PoW because // by the time we get here, it's been // checked during header // synchronization s.chainParams.PowLimit, s.timeSource, ); err != nil { log.Warnf("Invalid block for %s "+ "received from %s -- "+ "disconnecting peer", blockHash, sp.Addr()) sp.Disconnect() return } // TODO(roasbeef): modify CheckBlockSanity to // also check witness commitment // At this point, the block matches what we // know about it and we declare it sane. We can // kill the query and pass the response back to // the caller. foundBlock = block close(quit) default: } }, options..., ) if foundBlock == nil { return nil, fmt.Errorf("Couldn't retrieve block %s from "+ "network", blockHash) } // Add block to the cache before returning it. _, err = s.BlockCache.Put(*inv, &cache.CacheableBlock{foundBlock}) if err != nil { log.Warnf("couldn't write block to cache: %v", err) } return foundBlock, nil }
go
func (s *ChainService) GetBlock(blockHash chainhash.Hash, options ...QueryOption) (*btcutil.Block, error) { // Fetch the corresponding block header from the database. If this // isn't found, then we don't have the header for this block so we // can't request it. blockHeader, height, err := s.BlockHeaders.FetchHeader(&blockHash) if err != nil || blockHeader.BlockHash() != blockHash { return nil, fmt.Errorf("Couldn't get header for block %s "+ "from database", blockHash) } // Starting with the set of default options, we'll apply any specified // functional options to the query so that we can check what inv type // to use. qo := defaultQueryOptions() qo.applyQueryOptions(options...) invType := wire.InvTypeWitnessBlock if qo.encoding == wire.BaseEncoding { invType = wire.InvTypeBlock } // Create an inv vector for getting this block. inv := wire.NewInvVect(invType, &blockHash) // If the block is already in the cache, we can return it immediately. blockValue, err := s.BlockCache.Get(*inv) if err == nil && blockValue != nil { return blockValue.(*cache.CacheableBlock).Block, err } if err != nil && err != cache.ErrElementNotFound { return nil, err } // Construct the appropriate getdata message to fetch the target block. getData := wire.NewMsgGetData() getData.AddInvVect(inv) // The block is only updated from the checkResponse function argument, // which is always called single-threadedly. We don't check the block // until after the query is finished, so we can just write to it // naively. var foundBlock *btcutil.Block s.queryPeers( // Send a wire.GetDataMsg getData, // Check responses and if we get one that matches, end the // query early. func(sp *ServerPeer, resp wire.Message, quit chan<- struct{}) { switch response := resp.(type) { // We're only interested in "block" messages. case *wire.MsgBlock: // Only keep this going if we haven't already // found a block, or we risk closing an already // closed channel. if foundBlock != nil { return } // If this isn't our block, ignore it. if response.BlockHash() != blockHash { return } block := btcutil.NewBlock(response) // Only set height if btcutil hasn't // automagically put one in. if block.Height() == btcutil.BlockHeightUnknown { block.SetHeight(int32(height)) } // If this claims our block but doesn't pass // the sanity check, the peer is trying to // bamboozle us. Disconnect it. if err := blockchain.CheckBlockSanity( block, // We don't need to check PoW because // by the time we get here, it's been // checked during header // synchronization s.chainParams.PowLimit, s.timeSource, ); err != nil { log.Warnf("Invalid block for %s "+ "received from %s -- "+ "disconnecting peer", blockHash, sp.Addr()) sp.Disconnect() return } // TODO(roasbeef): modify CheckBlockSanity to // also check witness commitment // At this point, the block matches what we // know about it and we declare it sane. We can // kill the query and pass the response back to // the caller. foundBlock = block close(quit) default: } }, options..., ) if foundBlock == nil { return nil, fmt.Errorf("Couldn't retrieve block %s from "+ "network", blockHash) } // Add block to the cache before returning it. _, err = s.BlockCache.Put(*inv, &cache.CacheableBlock{foundBlock}) if err != nil { log.Warnf("couldn't write block to cache: %v", err) } return foundBlock, nil }
[ "func", "(", "s", "*", "ChainService", ")", "GetBlock", "(", "blockHash", "chainhash", ".", "Hash", ",", "options", "...", "QueryOption", ")", "(", "*", "btcutil", ".", "Block", ",", "error", ")", "{", "// Fetch the corresponding block header from the database. If this", "// isn't found, then we don't have the header for this block so we", "// can't request it.", "blockHeader", ",", "height", ",", "err", ":=", "s", ".", "BlockHeaders", ".", "FetchHeader", "(", "&", "blockHash", ")", "\n", "if", "err", "!=", "nil", "||", "blockHeader", ".", "BlockHash", "(", ")", "!=", "blockHash", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "blockHash", ")", "\n", "}", "\n\n", "// Starting with the set of default options, we'll apply any specified", "// functional options to the query so that we can check what inv type", "// to use.", "qo", ":=", "defaultQueryOptions", "(", ")", "\n", "qo", ".", "applyQueryOptions", "(", "options", "...", ")", "\n", "invType", ":=", "wire", ".", "InvTypeWitnessBlock", "\n", "if", "qo", ".", "encoding", "==", "wire", ".", "BaseEncoding", "{", "invType", "=", "wire", ".", "InvTypeBlock", "\n", "}", "\n\n", "// Create an inv vector for getting this block.", "inv", ":=", "wire", ".", "NewInvVect", "(", "invType", ",", "&", "blockHash", ")", "\n\n", "// If the block is already in the cache, we can return it immediately.", "blockValue", ",", "err", ":=", "s", ".", "BlockCache", ".", "Get", "(", "*", "inv", ")", "\n", "if", "err", "==", "nil", "&&", "blockValue", "!=", "nil", "{", "return", "blockValue", ".", "(", "*", "cache", ".", "CacheableBlock", ")", ".", "Block", ",", "err", "\n", "}", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "cache", ".", "ErrElementNotFound", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Construct the appropriate getdata message to fetch the target block.", "getData", ":=", "wire", ".", "NewMsgGetData", "(", ")", "\n", "getData", ".", "AddInvVect", "(", "inv", ")", "\n\n", "// The block is only updated from the checkResponse function argument,", "// which is always called single-threadedly. We don't check the block", "// until after the query is finished, so we can just write to it", "// naively.", "var", "foundBlock", "*", "btcutil", ".", "Block", "\n", "s", ".", "queryPeers", "(", "// Send a wire.GetDataMsg", "getData", ",", "// Check responses and if we get one that matches, end the", "// query early.", "func", "(", "sp", "*", "ServerPeer", ",", "resp", "wire", ".", "Message", ",", "quit", "chan", "<-", "struct", "{", "}", ")", "{", "switch", "response", ":=", "resp", ".", "(", "type", ")", "{", "// We're only interested in \"block\" messages.", "case", "*", "wire", ".", "MsgBlock", ":", "// Only keep this going if we haven't already", "// found a block, or we risk closing an already", "// closed channel.", "if", "foundBlock", "!=", "nil", "{", "return", "\n", "}", "\n\n", "// If this isn't our block, ignore it.", "if", "response", ".", "BlockHash", "(", ")", "!=", "blockHash", "{", "return", "\n", "}", "\n", "block", ":=", "btcutil", ".", "NewBlock", "(", "response", ")", "\n\n", "// Only set height if btcutil hasn't", "// automagically put one in.", "if", "block", ".", "Height", "(", ")", "==", "btcutil", ".", "BlockHeightUnknown", "{", "block", ".", "SetHeight", "(", "int32", "(", "height", ")", ")", "\n", "}", "\n\n", "// If this claims our block but doesn't pass", "// the sanity check, the peer is trying to", "// bamboozle us. Disconnect it.", "if", "err", ":=", "blockchain", ".", "CheckBlockSanity", "(", "block", ",", "// We don't need to check PoW because", "// by the time we get here, it's been", "// checked during header", "// synchronization", "s", ".", "chainParams", ".", "PowLimit", ",", "s", ".", "timeSource", ",", ")", ";", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "blockHash", ",", "sp", ".", "Addr", "(", ")", ")", "\n", "sp", ".", "Disconnect", "(", ")", "\n", "return", "\n", "}", "\n\n", "// TODO(roasbeef): modify CheckBlockSanity to", "// also check witness commitment", "// At this point, the block matches what we", "// know about it and we declare it sane. We can", "// kill the query and pass the response back to", "// the caller.", "foundBlock", "=", "block", "\n", "close", "(", "quit", ")", "\n", "default", ":", "}", "\n", "}", ",", "options", "...", ",", ")", "\n", "if", "foundBlock", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "blockHash", ")", "\n", "}", "\n\n", "// Add block to the cache before returning it.", "_", ",", "err", "=", "s", ".", "BlockCache", ".", "Put", "(", "*", "inv", ",", "&", "cache", ".", "CacheableBlock", "{", "foundBlock", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "foundBlock", ",", "nil", "\n", "}" ]
// GetBlock gets a block by requesting it from the network, one peer at a // time, until one answers. If the block is found in the cache, it will be // returned immediately.
[ "GetBlock", "gets", "a", "block", "by", "requesting", "it", "from", "the", "network", "one", "peer", "at", "a", "time", "until", "one", "answers", ".", "If", "the", "block", "is", "found", "in", "the", "cache", "it", "will", "be", "returned", "immediately", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/query.go#L1139-L1258
train
lightninglabs/neutrino
notifications.go
Peers
func (s *ChainService) Peers() []*ServerPeer { replyChan := make(chan []*ServerPeer) select { case s.query <- getPeersMsg{reply: replyChan}: return <-replyChan case <-s.quit: return nil } }
go
func (s *ChainService) Peers() []*ServerPeer { replyChan := make(chan []*ServerPeer) select { case s.query <- getPeersMsg{reply: replyChan}: return <-replyChan case <-s.quit: return nil } }
[ "func", "(", "s", "*", "ChainService", ")", "Peers", "(", ")", "[", "]", "*", "ServerPeer", "{", "replyChan", ":=", "make", "(", "chan", "[", "]", "*", "ServerPeer", ")", "\n\n", "select", "{", "case", "s", ".", "query", "<-", "getPeersMsg", "{", "reply", ":", "replyChan", "}", ":", "return", "<-", "replyChan", "\n", "case", "<-", "s", ".", "quit", ":", "return", "nil", "\n", "}", "\n", "}" ]
// Peers returns an array of all connected peers.
[ "Peers", "returns", "an", "array", "of", "all", "connected", "peers", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/notifications.go#L223-L232
train
lightninglabs/neutrino
notifications.go
DisconnectNodeByAddr
func (s *ChainService) DisconnectNodeByAddr(addr string) error { replyChan := make(chan error) select { case s.query <- disconnectNodeMsg{ cmp: func(sp *ServerPeer) bool { return sp.Addr() == addr }, reply: replyChan, }: return <-replyChan case <-s.quit: return nil } }
go
func (s *ChainService) DisconnectNodeByAddr(addr string) error { replyChan := make(chan error) select { case s.query <- disconnectNodeMsg{ cmp: func(sp *ServerPeer) bool { return sp.Addr() == addr }, reply: replyChan, }: return <-replyChan case <-s.quit: return nil } }
[ "func", "(", "s", "*", "ChainService", ")", "DisconnectNodeByAddr", "(", "addr", "string", ")", "error", "{", "replyChan", ":=", "make", "(", "chan", "error", ")", "\n\n", "select", "{", "case", "s", ".", "query", "<-", "disconnectNodeMsg", "{", "cmp", ":", "func", "(", "sp", "*", "ServerPeer", ")", "bool", "{", "return", "sp", ".", "Addr", "(", ")", "==", "addr", "}", ",", "reply", ":", "replyChan", ",", "}", ":", "return", "<-", "replyChan", "\n", "case", "<-", "s", ".", "quit", ":", "return", "nil", "\n", "}", "\n", "}" ]
// DisconnectNodeByAddr disconnects a peer by target address. Both outbound and // inbound nodes will be searched for the target node. An error message will // be returned if the peer was not found.
[ "DisconnectNodeByAddr", "disconnects", "a", "peer", "by", "target", "address", ".", "Both", "outbound", "and", "inbound", "nodes", "will", "be", "searched", "for", "the", "target", "node", ".", "An", "error", "message", "will", "be", "returned", "if", "the", "peer", "was", "not", "found", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/notifications.go#L237-L249
train
lightninglabs/neutrino
notifications.go
DisconnectNodeByID
func (s *ChainService) DisconnectNodeByID(id int32) error { replyChan := make(chan error) select { case s.query <- disconnectNodeMsg{ cmp: func(sp *ServerPeer) bool { return sp.ID() == id }, reply: replyChan, }: return <-replyChan case <-s.quit: return nil } }
go
func (s *ChainService) DisconnectNodeByID(id int32) error { replyChan := make(chan error) select { case s.query <- disconnectNodeMsg{ cmp: func(sp *ServerPeer) bool { return sp.ID() == id }, reply: replyChan, }: return <-replyChan case <-s.quit: return nil } }
[ "func", "(", "s", "*", "ChainService", ")", "DisconnectNodeByID", "(", "id", "int32", ")", "error", "{", "replyChan", ":=", "make", "(", "chan", "error", ")", "\n\n", "select", "{", "case", "s", ".", "query", "<-", "disconnectNodeMsg", "{", "cmp", ":", "func", "(", "sp", "*", "ServerPeer", ")", "bool", "{", "return", "sp", ".", "ID", "(", ")", "==", "id", "}", ",", "reply", ":", "replyChan", ",", "}", ":", "return", "<-", "replyChan", "\n", "case", "<-", "s", ".", "quit", ":", "return", "nil", "\n", "}", "\n", "}" ]
// DisconnectNodeByID disconnects a peer by target node id. Both outbound and // inbound nodes will be searched for the target node. An error message will be // returned if the peer was not found.
[ "DisconnectNodeByID", "disconnects", "a", "peer", "by", "target", "node", "id", ".", "Both", "outbound", "and", "inbound", "nodes", "will", "be", "searched", "for", "the", "target", "node", ".", "An", "error", "message", "will", "be", "returned", "if", "the", "peer", "was", "not", "found", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/notifications.go#L254-L266
train
lightninglabs/neutrino
notifications.go
ConnectNode
func (s *ChainService) ConnectNode(addr string, permanent bool) error { replyChan := make(chan error) select { case s.query <- connectNodeMsg{ addr: addr, permanent: permanent, reply: replyChan, }: return <-replyChan case <-s.quit: return nil } }
go
func (s *ChainService) ConnectNode(addr string, permanent bool) error { replyChan := make(chan error) select { case s.query <- connectNodeMsg{ addr: addr, permanent: permanent, reply: replyChan, }: return <-replyChan case <-s.quit: return nil } }
[ "func", "(", "s", "*", "ChainService", ")", "ConnectNode", "(", "addr", "string", ",", "permanent", "bool", ")", "error", "{", "replyChan", ":=", "make", "(", "chan", "error", ")", "\n\n", "select", "{", "case", "s", ".", "query", "<-", "connectNodeMsg", "{", "addr", ":", "addr", ",", "permanent", ":", "permanent", ",", "reply", ":", "replyChan", ",", "}", ":", "return", "<-", "replyChan", "\n", "case", "<-", "s", ".", "quit", ":", "return", "nil", "\n", "}", "\n", "}" ]
// ConnectNode adds `addr' as a new outbound peer. If permanent is true then the // peer will be persistent and reconnect if the connection is lost. // It is an error to call this with an already existing peer.
[ "ConnectNode", "adds", "addr", "as", "a", "new", "outbound", "peer", ".", "If", "permanent", "is", "true", "then", "the", "peer", "will", "be", "persistent", "and", "reconnect", "if", "the", "connection", "is", "lost", ".", "It", "is", "an", "error", "to", "call", "this", "with", "an", "already", "existing", "peer", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/notifications.go#L303-L316
train
lightninglabs/neutrino
notifications.go
IsBanned
func (s *ChainService) IsBanned(addr string) bool { replyChan := make(chan bool, 1) select { case s.query <- banQueryMsg{ addr: addr, reply: replyChan, }: return <-replyChan case <-s.quit: return false } }
go
func (s *ChainService) IsBanned(addr string) bool { replyChan := make(chan bool, 1) select { case s.query <- banQueryMsg{ addr: addr, reply: replyChan, }: return <-replyChan case <-s.quit: return false } }
[ "func", "(", "s", "*", "ChainService", ")", "IsBanned", "(", "addr", "string", ")", "bool", "{", "replyChan", ":=", "make", "(", "chan", "bool", ",", "1", ")", "\n\n", "select", "{", "case", "s", ".", "query", "<-", "banQueryMsg", "{", "addr", ":", "addr", ",", "reply", ":", "replyChan", ",", "}", ":", "return", "<-", "replyChan", "\n", "case", "<-", "s", ".", "quit", ":", "return", "false", "\n", "}", "\n", "}" ]
// IsBanned retursn true if the peer is banned, and false otherwise.
[ "IsBanned", "retursn", "true", "if", "the", "peer", "is", "banned", "and", "false", "otherwise", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/notifications.go#L330-L342
train
lightninglabs/neutrino
rescan.go
NotificationHandlers
func NotificationHandlers(ntfn rpcclient.NotificationHandlers) RescanOption { return func(ro *rescanOptions) { ro.ntfn = ntfn } }
go
func NotificationHandlers(ntfn rpcclient.NotificationHandlers) RescanOption { return func(ro *rescanOptions) { ro.ntfn = ntfn } }
[ "func", "NotificationHandlers", "(", "ntfn", "rpcclient", ".", "NotificationHandlers", ")", "RescanOption", "{", "return", "func", "(", "ro", "*", "rescanOptions", ")", "{", "ro", ".", "ntfn", "=", "ntfn", "\n", "}", "\n", "}" ]
// NotificationHandlers specifies notification handlers for the rescan. These // will always run in the same goroutine as the caller.
[ "NotificationHandlers", "specifies", "notification", "handlers", "for", "the", "rescan", ".", "These", "will", "always", "run", "in", "the", "same", "goroutine", "as", "the", "caller", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L114-L118
train
lightninglabs/neutrino
rescan.go
StartTime
func StartTime(startTime time.Time) RescanOption { return func(ro *rescanOptions) { ro.startTime = startTime } }
go
func StartTime(startTime time.Time) RescanOption { return func(ro *rescanOptions) { ro.startTime = startTime } }
[ "func", "StartTime", "(", "startTime", "time", ".", "Time", ")", "RescanOption", "{", "return", "func", "(", "ro", "*", "rescanOptions", ")", "{", "ro", ".", "startTime", "=", "startTime", "\n", "}", "\n", "}" ]
// StartTime specifies the start time. The time is compared to the timestamp of // each block, and the rescan only begins once the first block crosses that // timestamp. When using this, it is advisable to use a margin of error and // start rescans slightly earlier than required. The rescan uses the latter of // StartBlock and StartTime.
[ "StartTime", "specifies", "the", "start", "time", ".", "The", "time", "is", "compared", "to", "the", "timestamp", "of", "each", "block", "and", "the", "rescan", "only", "begins", "once", "the", "first", "block", "crosses", "that", "timestamp", ".", "When", "using", "this", "it", "is", "advisable", "to", "use", "a", "margin", "of", "error", "and", "start", "rescans", "slightly", "earlier", "than", "required", ".", "The", "rescan", "uses", "the", "latter", "of", "StartBlock", "and", "StartTime", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L137-L141
train
lightninglabs/neutrino
rescan.go
WatchInputs
func WatchInputs(watchInputs ...InputWithScript) RescanOption { return func(ro *rescanOptions) { ro.watchInputs = append(ro.watchInputs, watchInputs...) } }
go
func WatchInputs(watchInputs ...InputWithScript) RescanOption { return func(ro *rescanOptions) { ro.watchInputs = append(ro.watchInputs, watchInputs...) } }
[ "func", "WatchInputs", "(", "watchInputs", "...", "InputWithScript", ")", "RescanOption", "{", "return", "func", "(", "ro", "*", "rescanOptions", ")", "{", "ro", ".", "watchInputs", "=", "append", "(", "ro", ".", "watchInputs", ",", "watchInputs", "...", ")", "\n", "}", "\n", "}" ]
// WatchInputs specifies the outpoints to watch for on-chain spends. We also // require the script as we'll match on the script, but then notify based on // the outpoint. Each call to this function adds to the list of outpoints being // watched rather than replacing the list.
[ "WatchInputs", "specifies", "the", "outpoints", "to", "watch", "for", "on", "-", "chain", "spends", ".", "We", "also", "require", "the", "script", "as", "we", "ll", "match", "on", "the", "script", "but", "then", "notify", "based", "on", "the", "outpoint", ".", "Each", "call", "to", "this", "function", "adds", "to", "the", "list", "of", "outpoints", "being", "watched", "rather", "than", "replacing", "the", "list", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L180-L184
train
lightninglabs/neutrino
rescan.go
notifyBlock
func notifyBlock(chain ChainSource, ro *rescanOptions, curHeader wire.BlockHeader, curStamp waddrmgr.BlockStamp, scanning bool) error { // Find relevant transactions based on watch list. If scanning is // false, we can safely assume this block has no relevant transactions. var relevantTxs []*btcutil.Tx if len(ro.watchList) != 0 && scanning { // If we have a non-empty watch list, then we need to see if it // matches the rescan's filters, so we get the basic filter // from the DB or network. matched, err := blockFilterMatches(chain, ro, &curStamp.Hash) if err != nil { return err } if matched { relevantTxs, err = extractBlockMatches( chain, ro, &curStamp, ) if err != nil { return err } } } if ro.ntfn.OnFilteredBlockConnected != nil { ro.ntfn.OnFilteredBlockConnected(curStamp.Height, &curHeader, relevantTxs) } if ro.ntfn.OnBlockConnected != nil { ro.ntfn.OnBlockConnected(&curStamp.Hash, curStamp.Height, curHeader.Timestamp) } return nil }
go
func notifyBlock(chain ChainSource, ro *rescanOptions, curHeader wire.BlockHeader, curStamp waddrmgr.BlockStamp, scanning bool) error { // Find relevant transactions based on watch list. If scanning is // false, we can safely assume this block has no relevant transactions. var relevantTxs []*btcutil.Tx if len(ro.watchList) != 0 && scanning { // If we have a non-empty watch list, then we need to see if it // matches the rescan's filters, so we get the basic filter // from the DB or network. matched, err := blockFilterMatches(chain, ro, &curStamp.Hash) if err != nil { return err } if matched { relevantTxs, err = extractBlockMatches( chain, ro, &curStamp, ) if err != nil { return err } } } if ro.ntfn.OnFilteredBlockConnected != nil { ro.ntfn.OnFilteredBlockConnected(curStamp.Height, &curHeader, relevantTxs) } if ro.ntfn.OnBlockConnected != nil { ro.ntfn.OnBlockConnected(&curStamp.Hash, curStamp.Height, curHeader.Timestamp) } return nil }
[ "func", "notifyBlock", "(", "chain", "ChainSource", ",", "ro", "*", "rescanOptions", ",", "curHeader", "wire", ".", "BlockHeader", ",", "curStamp", "waddrmgr", ".", "BlockStamp", ",", "scanning", "bool", ")", "error", "{", "// Find relevant transactions based on watch list. If scanning is", "// false, we can safely assume this block has no relevant transactions.", "var", "relevantTxs", "[", "]", "*", "btcutil", ".", "Tx", "\n", "if", "len", "(", "ro", ".", "watchList", ")", "!=", "0", "&&", "scanning", "{", "// If we have a non-empty watch list, then we need to see if it", "// matches the rescan's filters, so we get the basic filter", "// from the DB or network.", "matched", ",", "err", ":=", "blockFilterMatches", "(", "chain", ",", "ro", ",", "&", "curStamp", ".", "Hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "matched", "{", "relevantTxs", ",", "err", "=", "extractBlockMatches", "(", "chain", ",", "ro", ",", "&", "curStamp", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "ro", ".", "ntfn", ".", "OnFilteredBlockConnected", "!=", "nil", "{", "ro", ".", "ntfn", ".", "OnFilteredBlockConnected", "(", "curStamp", ".", "Height", ",", "&", "curHeader", ",", "relevantTxs", ")", "\n", "}", "\n\n", "if", "ro", ".", "ntfn", ".", "OnBlockConnected", "!=", "nil", "{", "ro", ".", "ntfn", ".", "OnBlockConnected", "(", "&", "curStamp", ".", "Hash", ",", "curStamp", ".", "Height", ",", "curHeader", ".", "Timestamp", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// notifyBlock calls appropriate listeners based on the block filter.
[ "notifyBlock", "calls", "appropriate", "listeners", "based", "on", "the", "block", "filter", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L813-L850
train
lightninglabs/neutrino
rescan.go
extractBlockMatches
func extractBlockMatches(chain ChainSource, ro *rescanOptions, curStamp *waddrmgr.BlockStamp) ([]*btcutil.Tx, error) { // We've matched. Now we actually get the block and cycle through the // transactions to see which ones are relevant. block, err := chain.GetBlock(curStamp.Hash, ro.queryOptions...) if err != nil { return nil, err } if block == nil { return nil, fmt.Errorf("Couldn't get block %d (%s) from "+ "network", curStamp.Height, curStamp.Hash) } blockHeader := block.MsgBlock().Header blockDetails := btcjson.BlockDetails{ Height: block.Height(), Hash: block.Hash().String(), Time: blockHeader.Timestamp.Unix(), } relevantTxs := make([]*btcutil.Tx, 0, len(block.Transactions())) for txIdx, tx := range block.Transactions() { txDetails := blockDetails txDetails.Index = txIdx var relevant bool if ro.spendsWatchedInput(tx) { relevant = true if ro.ntfn.OnRedeemingTx != nil { ro.ntfn.OnRedeemingTx(tx, &txDetails) } } // Even though the transaction may already be known as relevant // and there might not be a notification callback, we need to // call paysWatchedAddr anyway as it updates the rescan // options. pays, err := ro.paysWatchedAddr(tx) if err != nil { return nil, err } if pays { relevant = true if ro.ntfn.OnRecvTx != nil { ro.ntfn.OnRecvTx(tx, &txDetails) } } if relevant { relevantTxs = append(relevantTxs, tx) } } return relevantTxs, nil }
go
func extractBlockMatches(chain ChainSource, ro *rescanOptions, curStamp *waddrmgr.BlockStamp) ([]*btcutil.Tx, error) { // We've matched. Now we actually get the block and cycle through the // transactions to see which ones are relevant. block, err := chain.GetBlock(curStamp.Hash, ro.queryOptions...) if err != nil { return nil, err } if block == nil { return nil, fmt.Errorf("Couldn't get block %d (%s) from "+ "network", curStamp.Height, curStamp.Hash) } blockHeader := block.MsgBlock().Header blockDetails := btcjson.BlockDetails{ Height: block.Height(), Hash: block.Hash().String(), Time: blockHeader.Timestamp.Unix(), } relevantTxs := make([]*btcutil.Tx, 0, len(block.Transactions())) for txIdx, tx := range block.Transactions() { txDetails := blockDetails txDetails.Index = txIdx var relevant bool if ro.spendsWatchedInput(tx) { relevant = true if ro.ntfn.OnRedeemingTx != nil { ro.ntfn.OnRedeemingTx(tx, &txDetails) } } // Even though the transaction may already be known as relevant // and there might not be a notification callback, we need to // call paysWatchedAddr anyway as it updates the rescan // options. pays, err := ro.paysWatchedAddr(tx) if err != nil { return nil, err } if pays { relevant = true if ro.ntfn.OnRecvTx != nil { ro.ntfn.OnRecvTx(tx, &txDetails) } } if relevant { relevantTxs = append(relevantTxs, tx) } } return relevantTxs, nil }
[ "func", "extractBlockMatches", "(", "chain", "ChainSource", ",", "ro", "*", "rescanOptions", ",", "curStamp", "*", "waddrmgr", ".", "BlockStamp", ")", "(", "[", "]", "*", "btcutil", ".", "Tx", ",", "error", ")", "{", "// We've matched. Now we actually get the block and cycle through the", "// transactions to see which ones are relevant.", "block", ",", "err", ":=", "chain", ".", "GetBlock", "(", "curStamp", ".", "Hash", ",", "ro", ".", "queryOptions", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "block", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "curStamp", ".", "Height", ",", "curStamp", ".", "Hash", ")", "\n", "}", "\n\n", "blockHeader", ":=", "block", ".", "MsgBlock", "(", ")", ".", "Header", "\n", "blockDetails", ":=", "btcjson", ".", "BlockDetails", "{", "Height", ":", "block", ".", "Height", "(", ")", ",", "Hash", ":", "block", ".", "Hash", "(", ")", ".", "String", "(", ")", ",", "Time", ":", "blockHeader", ".", "Timestamp", ".", "Unix", "(", ")", ",", "}", "\n\n", "relevantTxs", ":=", "make", "(", "[", "]", "*", "btcutil", ".", "Tx", ",", "0", ",", "len", "(", "block", ".", "Transactions", "(", ")", ")", ")", "\n", "for", "txIdx", ",", "tx", ":=", "range", "block", ".", "Transactions", "(", ")", "{", "txDetails", ":=", "blockDetails", "\n", "txDetails", ".", "Index", "=", "txIdx", "\n\n", "var", "relevant", "bool", "\n\n", "if", "ro", ".", "spendsWatchedInput", "(", "tx", ")", "{", "relevant", "=", "true", "\n", "if", "ro", ".", "ntfn", ".", "OnRedeemingTx", "!=", "nil", "{", "ro", ".", "ntfn", ".", "OnRedeemingTx", "(", "tx", ",", "&", "txDetails", ")", "\n", "}", "\n", "}", "\n\n", "// Even though the transaction may already be known as relevant", "// and there might not be a notification callback, we need to", "// call paysWatchedAddr anyway as it updates the rescan", "// options.", "pays", ",", "err", ":=", "ro", ".", "paysWatchedAddr", "(", "tx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "pays", "{", "relevant", "=", "true", "\n", "if", "ro", ".", "ntfn", ".", "OnRecvTx", "!=", "nil", "{", "ro", ".", "ntfn", ".", "OnRecvTx", "(", "tx", ",", "&", "txDetails", ")", "\n", "}", "\n", "}", "\n\n", "if", "relevant", "{", "relevantTxs", "=", "append", "(", "relevantTxs", ",", "tx", ")", "\n", "}", "\n", "}", "\n\n", "return", "relevantTxs", ",", "nil", "\n", "}" ]
// extractBlockMatches fetches the target block from the network, and filters // out any relevant transactions found within the block.
[ "extractBlockMatches", "fetches", "the", "target", "block", "from", "the", "network", "and", "filters", "out", "any", "relevant", "transactions", "found", "within", "the", "block", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L854-L911
train
lightninglabs/neutrino
rescan.go
notifyBlockWithFilter
func notifyBlockWithFilter(chain ChainSource, ro *rescanOptions, curHeader *wire.BlockHeader, curStamp *waddrmgr.BlockStamp, filter *gcs.Filter) error { // Based on what we find within the block or the filter, we'll be // sending out a set of notifications with transactions that are // relevant to the rescan. var relevantTxs []*btcutil.Tx // If we actually have a filter, then we'll go ahead an attempt to // match the items within the filter to ensure we create any relevant // notifications. if filter != nil { matched, err := matchBlockFilter(ro, filter, &curStamp.Hash) if err != nil { return err } if matched { relevantTxs, err = extractBlockMatches( chain, ro, curStamp, ) if err != nil { return err } } } if ro.ntfn.OnFilteredBlockConnected != nil { ro.ntfn.OnFilteredBlockConnected(curStamp.Height, curHeader, relevantTxs) } if ro.ntfn.OnBlockConnected != nil { ro.ntfn.OnBlockConnected(&curStamp.Hash, curStamp.Height, curHeader.Timestamp) } return nil }
go
func notifyBlockWithFilter(chain ChainSource, ro *rescanOptions, curHeader *wire.BlockHeader, curStamp *waddrmgr.BlockStamp, filter *gcs.Filter) error { // Based on what we find within the block or the filter, we'll be // sending out a set of notifications with transactions that are // relevant to the rescan. var relevantTxs []*btcutil.Tx // If we actually have a filter, then we'll go ahead an attempt to // match the items within the filter to ensure we create any relevant // notifications. if filter != nil { matched, err := matchBlockFilter(ro, filter, &curStamp.Hash) if err != nil { return err } if matched { relevantTxs, err = extractBlockMatches( chain, ro, curStamp, ) if err != nil { return err } } } if ro.ntfn.OnFilteredBlockConnected != nil { ro.ntfn.OnFilteredBlockConnected(curStamp.Height, curHeader, relevantTxs) } if ro.ntfn.OnBlockConnected != nil { ro.ntfn.OnBlockConnected(&curStamp.Hash, curStamp.Height, curHeader.Timestamp) } return nil }
[ "func", "notifyBlockWithFilter", "(", "chain", "ChainSource", ",", "ro", "*", "rescanOptions", ",", "curHeader", "*", "wire", ".", "BlockHeader", ",", "curStamp", "*", "waddrmgr", ".", "BlockStamp", ",", "filter", "*", "gcs", ".", "Filter", ")", "error", "{", "// Based on what we find within the block or the filter, we'll be", "// sending out a set of notifications with transactions that are", "// relevant to the rescan.", "var", "relevantTxs", "[", "]", "*", "btcutil", ".", "Tx", "\n\n", "// If we actually have a filter, then we'll go ahead an attempt to", "// match the items within the filter to ensure we create any relevant", "// notifications.", "if", "filter", "!=", "nil", "{", "matched", ",", "err", ":=", "matchBlockFilter", "(", "ro", ",", "filter", ",", "&", "curStamp", ".", "Hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "matched", "{", "relevantTxs", ",", "err", "=", "extractBlockMatches", "(", "chain", ",", "ro", ",", "curStamp", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "ro", ".", "ntfn", ".", "OnFilteredBlockConnected", "!=", "nil", "{", "ro", ".", "ntfn", ".", "OnFilteredBlockConnected", "(", "curStamp", ".", "Height", ",", "curHeader", ",", "relevantTxs", ")", "\n", "}", "\n\n", "if", "ro", ".", "ntfn", ".", "OnBlockConnected", "!=", "nil", "{", "ro", ".", "ntfn", ".", "OnBlockConnected", "(", "&", "curStamp", ".", "Hash", ",", "curStamp", ".", "Height", ",", "curHeader", ".", "Timestamp", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// notifyBlockWithFilter calls appropriate listeners based on the block filter. // This differs from notifyBlock in that is expects the caller to already have // obtained the target filter.
[ "notifyBlockWithFilter", "calls", "appropriate", "listeners", "based", "on", "the", "block", "filter", ".", "This", "differs", "from", "notifyBlock", "in", "that", "is", "expects", "the", "caller", "to", "already", "have", "obtained", "the", "target", "filter", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L916-L955
train
lightninglabs/neutrino
rescan.go
matchBlockFilter
func matchBlockFilter(ro *rescanOptions, filter *gcs.Filter, blockHash *chainhash.Hash) (bool, error) { // Now that we have the filter as well as the block hash of the block // used to construct the filter, we'll check to see if the block // matches any items in our watch list. key := builder.DeriveKey(blockHash) matched, err := filter.MatchAny(key, ro.watchList) if err != nil { return false, err } return matched, nil }
go
func matchBlockFilter(ro *rescanOptions, filter *gcs.Filter, blockHash *chainhash.Hash) (bool, error) { // Now that we have the filter as well as the block hash of the block // used to construct the filter, we'll check to see if the block // matches any items in our watch list. key := builder.DeriveKey(blockHash) matched, err := filter.MatchAny(key, ro.watchList) if err != nil { return false, err } return matched, nil }
[ "func", "matchBlockFilter", "(", "ro", "*", "rescanOptions", ",", "filter", "*", "gcs", ".", "Filter", ",", "blockHash", "*", "chainhash", ".", "Hash", ")", "(", "bool", ",", "error", ")", "{", "// Now that we have the filter as well as the block hash of the block", "// used to construct the filter, we'll check to see if the block", "// matches any items in our watch list.", "key", ":=", "builder", ".", "DeriveKey", "(", "blockHash", ")", "\n", "matched", ",", "err", ":=", "filter", ".", "MatchAny", "(", "key", ",", "ro", ".", "watchList", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "return", "matched", ",", "nil", "\n", "}" ]
// matchBlockFilter returns whether the block filter matches the watched items. // If this returns false, it means the block is certainly not interesting to // us. This method differs from blockFilterMatches in that it expects the // filter to already be obtained, rather than fetching the filter from the // network.
[ "matchBlockFilter", "returns", "whether", "the", "block", "filter", "matches", "the", "watched", "items", ".", "If", "this", "returns", "false", "it", "means", "the", "block", "is", "certainly", "not", "interesting", "to", "us", ".", "This", "method", "differs", "from", "blockFilterMatches", "in", "that", "it", "expects", "the", "filter", "to", "already", "be", "obtained", "rather", "than", "fetching", "the", "filter", "from", "the", "network", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L962-L975
train
lightninglabs/neutrino
rescan.go
blockFilterMatches
func blockFilterMatches(chain ChainSource, ro *rescanOptions, blockHash *chainhash.Hash) (bool, error) { // TODO(roasbeef): need to ENSURE always get filter // Since this method is called when we are not current, and from the // utxoscanner, we expect more calls to follow for the subsequent // filters. To speed up the fetching, we make an optimistic batch // query. filter, err := chain.GetCFilter( *blockHash, wire.GCSFilterRegular, OptimisticBatch(), ) if err != nil { if err == headerfs.ErrHashNotFound { // Block has been reorged out from under us. return false, nil } return false, err } // If we found the filter, then we'll check the items in the watch list // against it. if filter != nil && filter.N() != 0 { return matchBlockFilter(ro, filter, blockHash) } return false, nil }
go
func blockFilterMatches(chain ChainSource, ro *rescanOptions, blockHash *chainhash.Hash) (bool, error) { // TODO(roasbeef): need to ENSURE always get filter // Since this method is called when we are not current, and from the // utxoscanner, we expect more calls to follow for the subsequent // filters. To speed up the fetching, we make an optimistic batch // query. filter, err := chain.GetCFilter( *blockHash, wire.GCSFilterRegular, OptimisticBatch(), ) if err != nil { if err == headerfs.ErrHashNotFound { // Block has been reorged out from under us. return false, nil } return false, err } // If we found the filter, then we'll check the items in the watch list // against it. if filter != nil && filter.N() != 0 { return matchBlockFilter(ro, filter, blockHash) } return false, nil }
[ "func", "blockFilterMatches", "(", "chain", "ChainSource", ",", "ro", "*", "rescanOptions", ",", "blockHash", "*", "chainhash", ".", "Hash", ")", "(", "bool", ",", "error", ")", "{", "// TODO(roasbeef): need to ENSURE always get filter", "// Since this method is called when we are not current, and from the", "// utxoscanner, we expect more calls to follow for the subsequent", "// filters. To speed up the fetching, we make an optimistic batch", "// query.", "filter", ",", "err", ":=", "chain", ".", "GetCFilter", "(", "*", "blockHash", ",", "wire", ".", "GCSFilterRegular", ",", "OptimisticBatch", "(", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "headerfs", ".", "ErrHashNotFound", "{", "// Block has been reorged out from under us.", "return", "false", ",", "nil", "\n", "}", "\n", "return", "false", ",", "err", "\n", "}", "\n\n", "// If we found the filter, then we'll check the items in the watch list", "// against it.", "if", "filter", "!=", "nil", "&&", "filter", ".", "N", "(", ")", "!=", "0", "{", "return", "matchBlockFilter", "(", "ro", ",", "filter", ",", "blockHash", ")", "\n", "}", "\n\n", "return", "false", ",", "nil", "\n", "}" ]
// blockFilterMatches returns whether the block filter matches the watched // items. If this returns false, it means the block is certainly not interesting // to us.
[ "blockFilterMatches", "returns", "whether", "the", "block", "filter", "matches", "the", "watched", "items", ".", "If", "this", "returns", "false", "it", "means", "the", "block", "is", "certainly", "not", "interesting", "to", "us", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L980-L1007
train
lightninglabs/neutrino
rescan.go
updateFilter
func (ro *rescanOptions) updateFilter(chain ChainSource, update *updateOptions, curStamp *waddrmgr.BlockStamp, curHeader *wire.BlockHeader) (bool, error) { ro.watchAddrs = append(ro.watchAddrs, update.addrs...) ro.watchInputs = append(ro.watchInputs, update.inputs...) for _, addr := range update.addrs { script, err := txscript.PayToAddrScript(addr) if err != nil { return false, err } ro.watchList = append(ro.watchList, script) } for _, input := range update.inputs { ro.watchList = append(ro.watchList, input.PkScript) } for _, txid := range update.txIDs { ro.watchList = append(ro.watchList, txid[:]) } // If we don't need to rewind, then we can exit early. if update.rewind == 0 { return false, nil } var ( header *wire.BlockHeader height uint32 rewound bool err error ) // If we need to rewind, then we'll walk backwards in the chain until // we arrive at the block _just_ before the rewind. for curStamp.Height > int32(update.rewind) { if ro.ntfn.OnBlockDisconnected != nil && !update.disableDisconnectedNtfns { ro.ntfn.OnBlockDisconnected(&curStamp.Hash, curStamp.Height, curHeader.Timestamp) } if ro.ntfn.OnFilteredBlockDisconnected != nil && !update.disableDisconnectedNtfns { ro.ntfn.OnFilteredBlockDisconnected(curStamp.Height, curHeader) } // We just disconnected a block above, so we're now in rewind // mode. We set this to true here so we properly send // notifications even if it was just a 1 block rewind. rewound = true // Rewind and continue. header, height, err = chain.GetBlockHeader(&curHeader.PrevBlock) if err != nil { return rewound, err } *curHeader = *header curStamp.Height = int32(height) curStamp.Hash = curHeader.BlockHash() } return rewound, nil }
go
func (ro *rescanOptions) updateFilter(chain ChainSource, update *updateOptions, curStamp *waddrmgr.BlockStamp, curHeader *wire.BlockHeader) (bool, error) { ro.watchAddrs = append(ro.watchAddrs, update.addrs...) ro.watchInputs = append(ro.watchInputs, update.inputs...) for _, addr := range update.addrs { script, err := txscript.PayToAddrScript(addr) if err != nil { return false, err } ro.watchList = append(ro.watchList, script) } for _, input := range update.inputs { ro.watchList = append(ro.watchList, input.PkScript) } for _, txid := range update.txIDs { ro.watchList = append(ro.watchList, txid[:]) } // If we don't need to rewind, then we can exit early. if update.rewind == 0 { return false, nil } var ( header *wire.BlockHeader height uint32 rewound bool err error ) // If we need to rewind, then we'll walk backwards in the chain until // we arrive at the block _just_ before the rewind. for curStamp.Height > int32(update.rewind) { if ro.ntfn.OnBlockDisconnected != nil && !update.disableDisconnectedNtfns { ro.ntfn.OnBlockDisconnected(&curStamp.Hash, curStamp.Height, curHeader.Timestamp) } if ro.ntfn.OnFilteredBlockDisconnected != nil && !update.disableDisconnectedNtfns { ro.ntfn.OnFilteredBlockDisconnected(curStamp.Height, curHeader) } // We just disconnected a block above, so we're now in rewind // mode. We set this to true here so we properly send // notifications even if it was just a 1 block rewind. rewound = true // Rewind and continue. header, height, err = chain.GetBlockHeader(&curHeader.PrevBlock) if err != nil { return rewound, err } *curHeader = *header curStamp.Height = int32(height) curStamp.Hash = curHeader.BlockHash() } return rewound, nil }
[ "func", "(", "ro", "*", "rescanOptions", ")", "updateFilter", "(", "chain", "ChainSource", ",", "update", "*", "updateOptions", ",", "curStamp", "*", "waddrmgr", ".", "BlockStamp", ",", "curHeader", "*", "wire", ".", "BlockHeader", ")", "(", "bool", ",", "error", ")", "{", "ro", ".", "watchAddrs", "=", "append", "(", "ro", ".", "watchAddrs", ",", "update", ".", "addrs", "...", ")", "\n", "ro", ".", "watchInputs", "=", "append", "(", "ro", ".", "watchInputs", ",", "update", ".", "inputs", "...", ")", "\n\n", "for", "_", ",", "addr", ":=", "range", "update", ".", "addrs", "{", "script", ",", "err", ":=", "txscript", ".", "PayToAddrScript", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "ro", ".", "watchList", "=", "append", "(", "ro", ".", "watchList", ",", "script", ")", "\n", "}", "\n", "for", "_", ",", "input", ":=", "range", "update", ".", "inputs", "{", "ro", ".", "watchList", "=", "append", "(", "ro", ".", "watchList", ",", "input", ".", "PkScript", ")", "\n", "}", "\n", "for", "_", ",", "txid", ":=", "range", "update", ".", "txIDs", "{", "ro", ".", "watchList", "=", "append", "(", "ro", ".", "watchList", ",", "txid", "[", ":", "]", ")", "\n", "}", "\n\n", "// If we don't need to rewind, then we can exit early.", "if", "update", ".", "rewind", "==", "0", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "var", "(", "header", "*", "wire", ".", "BlockHeader", "\n", "height", "uint32", "\n", "rewound", "bool", "\n", "err", "error", "\n", ")", "\n\n", "// If we need to rewind, then we'll walk backwards in the chain until", "// we arrive at the block _just_ before the rewind.", "for", "curStamp", ".", "Height", ">", "int32", "(", "update", ".", "rewind", ")", "{", "if", "ro", ".", "ntfn", ".", "OnBlockDisconnected", "!=", "nil", "&&", "!", "update", ".", "disableDisconnectedNtfns", "{", "ro", ".", "ntfn", ".", "OnBlockDisconnected", "(", "&", "curStamp", ".", "Hash", ",", "curStamp", ".", "Height", ",", "curHeader", ".", "Timestamp", ")", "\n", "}", "\n", "if", "ro", ".", "ntfn", ".", "OnFilteredBlockDisconnected", "!=", "nil", "&&", "!", "update", ".", "disableDisconnectedNtfns", "{", "ro", ".", "ntfn", ".", "OnFilteredBlockDisconnected", "(", "curStamp", ".", "Height", ",", "curHeader", ")", "\n", "}", "\n\n", "// We just disconnected a block above, so we're now in rewind", "// mode. We set this to true here so we properly send", "// notifications even if it was just a 1 block rewind.", "rewound", "=", "true", "\n\n", "// Rewind and continue.", "header", ",", "height", ",", "err", "=", "chain", ".", "GetBlockHeader", "(", "&", "curHeader", ".", "PrevBlock", ")", "\n", "if", "err", "!=", "nil", "{", "return", "rewound", ",", "err", "\n", "}", "\n\n", "*", "curHeader", "=", "*", "header", "\n", "curStamp", ".", "Height", "=", "int32", "(", "height", ")", "\n", "curStamp", ".", "Hash", "=", "curHeader", ".", "BlockHash", "(", ")", "\n", "}", "\n\n", "return", "rewound", ",", "nil", "\n", "}" ]
// updateFilter atomically updates the filter and rewinds to the specified // height if not 0.
[ "updateFilter", "atomically", "updates", "the", "filter", "and", "rewinds", "to", "the", "specified", "height", "if", "not", "0", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L1011-L1075
train
lightninglabs/neutrino
rescan.go
spendsWatchedInput
func (ro *rescanOptions) spendsWatchedInput(tx *btcutil.Tx) bool { for _, in := range tx.MsgTx().TxIn { for _, input := range ro.watchInputs { switch { // If we're watching for a zero outpoint, then we should // match on the output script being spent instead. case input.OutPoint == zeroOutPoint: pkScript, err := txscript.ComputePkScript( in.SignatureScript, in.Witness, ) if err != nil { continue } if bytes.Equal(pkScript.Script(), input.PkScript) { return true } // Otherwise, we'll match on the outpoint being spent. case in.PreviousOutPoint == input.OutPoint: return true } } } return false }
go
func (ro *rescanOptions) spendsWatchedInput(tx *btcutil.Tx) bool { for _, in := range tx.MsgTx().TxIn { for _, input := range ro.watchInputs { switch { // If we're watching for a zero outpoint, then we should // match on the output script being spent instead. case input.OutPoint == zeroOutPoint: pkScript, err := txscript.ComputePkScript( in.SignatureScript, in.Witness, ) if err != nil { continue } if bytes.Equal(pkScript.Script(), input.PkScript) { return true } // Otherwise, we'll match on the outpoint being spent. case in.PreviousOutPoint == input.OutPoint: return true } } } return false }
[ "func", "(", "ro", "*", "rescanOptions", ")", "spendsWatchedInput", "(", "tx", "*", "btcutil", ".", "Tx", ")", "bool", "{", "for", "_", ",", "in", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxIn", "{", "for", "_", ",", "input", ":=", "range", "ro", ".", "watchInputs", "{", "switch", "{", "// If we're watching for a zero outpoint, then we should", "// match on the output script being spent instead.", "case", "input", ".", "OutPoint", "==", "zeroOutPoint", ":", "pkScript", ",", "err", ":=", "txscript", ".", "ComputePkScript", "(", "in", ".", "SignatureScript", ",", "in", ".", "Witness", ",", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n\n", "if", "bytes", ".", "Equal", "(", "pkScript", ".", "Script", "(", ")", ",", "input", ".", "PkScript", ")", "{", "return", "true", "\n", "}", "\n\n", "// Otherwise, we'll match on the outpoint being spent.", "case", "in", ".", "PreviousOutPoint", "==", "input", ".", "OutPoint", ":", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// spendsWatchedInput returns whether the transaction matches the filter by // spending a watched input.
[ "spendsWatchedInput", "returns", "whether", "the", "transaction", "matches", "the", "filter", "by", "spending", "a", "watched", "input", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L1079-L1104
train
lightninglabs/neutrino
rescan.go
paysWatchedAddr
func (ro *rescanOptions) paysWatchedAddr(tx *btcutil.Tx) (bool, error) { anyMatchingOutputs := false txOutLoop: for outIdx, out := range tx.MsgTx().TxOut { pkScript := out.PkScript for _, addr := range ro.watchAddrs { // We'll convert the address into its matching pkScript // to in order to check for a match. addrScript, err := txscript.PayToAddrScript(addr) if err != nil { return false, err } // If the script doesn't match, we'll move onto the // next one. if !bytes.Equal(pkScript, addrScript) { continue } // At this state, we have a matching output so we'll // mark this transaction as matching. anyMatchingOutputs = true // Update the filter by also watching this created // outpoint for the event in the future that it's // spent. hash := tx.Hash() outPoint := wire.OutPoint{ Hash: *hash, Index: uint32(outIdx), } ro.watchInputs = append(ro.watchInputs, InputWithScript{ PkScript: pkScript, OutPoint: outPoint, }) ro.watchList = append(ro.watchList, pkScript) continue txOutLoop } } return anyMatchingOutputs, nil }
go
func (ro *rescanOptions) paysWatchedAddr(tx *btcutil.Tx) (bool, error) { anyMatchingOutputs := false txOutLoop: for outIdx, out := range tx.MsgTx().TxOut { pkScript := out.PkScript for _, addr := range ro.watchAddrs { // We'll convert the address into its matching pkScript // to in order to check for a match. addrScript, err := txscript.PayToAddrScript(addr) if err != nil { return false, err } // If the script doesn't match, we'll move onto the // next one. if !bytes.Equal(pkScript, addrScript) { continue } // At this state, we have a matching output so we'll // mark this transaction as matching. anyMatchingOutputs = true // Update the filter by also watching this created // outpoint for the event in the future that it's // spent. hash := tx.Hash() outPoint := wire.OutPoint{ Hash: *hash, Index: uint32(outIdx), } ro.watchInputs = append(ro.watchInputs, InputWithScript{ PkScript: pkScript, OutPoint: outPoint, }) ro.watchList = append(ro.watchList, pkScript) continue txOutLoop } } return anyMatchingOutputs, nil }
[ "func", "(", "ro", "*", "rescanOptions", ")", "paysWatchedAddr", "(", "tx", "*", "btcutil", ".", "Tx", ")", "(", "bool", ",", "error", ")", "{", "anyMatchingOutputs", ":=", "false", "\n\n", "txOutLoop", ":", "for", "outIdx", ",", "out", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxOut", "{", "pkScript", ":=", "out", ".", "PkScript", "\n\n", "for", "_", ",", "addr", ":=", "range", "ro", ".", "watchAddrs", "{", "// We'll convert the address into its matching pkScript", "// to in order to check for a match.", "addrScript", ",", "err", ":=", "txscript", ".", "PayToAddrScript", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "// If the script doesn't match, we'll move onto the", "// next one.", "if", "!", "bytes", ".", "Equal", "(", "pkScript", ",", "addrScript", ")", "{", "continue", "\n", "}", "\n\n", "// At this state, we have a matching output so we'll", "// mark this transaction as matching.", "anyMatchingOutputs", "=", "true", "\n\n", "// Update the filter by also watching this created", "// outpoint for the event in the future that it's", "// spent.", "hash", ":=", "tx", ".", "Hash", "(", ")", "\n", "outPoint", ":=", "wire", ".", "OutPoint", "{", "Hash", ":", "*", "hash", ",", "Index", ":", "uint32", "(", "outIdx", ")", ",", "}", "\n", "ro", ".", "watchInputs", "=", "append", "(", "ro", ".", "watchInputs", ",", "InputWithScript", "{", "PkScript", ":", "pkScript", ",", "OutPoint", ":", "outPoint", ",", "}", ")", "\n", "ro", ".", "watchList", "=", "append", "(", "ro", ".", "watchList", ",", "pkScript", ")", "\n\n", "continue", "txOutLoop", "\n", "}", "\n", "}", "\n\n", "return", "anyMatchingOutputs", ",", "nil", "\n", "}" ]
// paysWatchedAddr returns whether the transaction matches the filter by having // an output paying to a watched address. If that is the case, this also // updates the filter to watch the newly created output going forward.
[ "paysWatchedAddr", "returns", "whether", "the", "transaction", "matches", "the", "filter", "by", "having", "an", "output", "paying", "to", "a", "watched", "address", ".", "If", "that", "is", "the", "case", "this", "also", "updates", "the", "filter", "to", "watch", "the", "newly", "created", "output", "going", "forward", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L1109-L1153
train
lightninglabs/neutrino
rescan.go
NewRescan
func NewRescan(chain ChainSource, options ...RescanOption) *Rescan { return &Rescan{ running: make(chan struct{}), options: options, updateChan: make(chan *updateOptions), chain: chain, } }
go
func NewRescan(chain ChainSource, options ...RescanOption) *Rescan { return &Rescan{ running: make(chan struct{}), options: options, updateChan: make(chan *updateOptions), chain: chain, } }
[ "func", "NewRescan", "(", "chain", "ChainSource", ",", "options", "...", "RescanOption", ")", "*", "Rescan", "{", "return", "&", "Rescan", "{", "running", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "options", ":", "options", ",", "updateChan", ":", "make", "(", "chan", "*", "updateOptions", ")", ",", "chain", ":", "chain", ",", "}", "\n", "}" ]
// NewRescan returns a rescan object that runs in another goroutine and has an // updatable filter. It returns the long-running rescan object, and a channel // which returns any error on termination of the rescan process.
[ "NewRescan", "returns", "a", "rescan", "object", "that", "runs", "in", "another", "goroutine", "and", "has", "an", "updatable", "filter", ".", "It", "returns", "the", "long", "-", "running", "rescan", "object", "and", "a", "channel", "which", "returns", "any", "error", "on", "termination", "of", "the", "rescan", "process", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L1178-L1185
train
lightninglabs/neutrino
rescan.go
Start
func (r *Rescan) Start() <-chan error { errChan := make(chan error, 1) if !atomic.CompareAndSwapUint32(&r.started, 0, 1) { errChan <- fmt.Errorf("Rescan already started") return errChan } r.wg.Add(1) go func() { defer r.wg.Done() rescanArgs := append(r.options, updateChan(r.updateChan)) err := rescan(r.chain, rescanArgs...) close(r.running) r.errMtx.Lock() r.err = err r.errMtx.Unlock() errChan <- err }() return errChan }
go
func (r *Rescan) Start() <-chan error { errChan := make(chan error, 1) if !atomic.CompareAndSwapUint32(&r.started, 0, 1) { errChan <- fmt.Errorf("Rescan already started") return errChan } r.wg.Add(1) go func() { defer r.wg.Done() rescanArgs := append(r.options, updateChan(r.updateChan)) err := rescan(r.chain, rescanArgs...) close(r.running) r.errMtx.Lock() r.err = err r.errMtx.Unlock() errChan <- err }() return errChan }
[ "func", "(", "r", "*", "Rescan", ")", "Start", "(", ")", "<-", "chan", "error", "{", "errChan", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n\n", "if", "!", "atomic", ".", "CompareAndSwapUint32", "(", "&", "r", ".", "started", ",", "0", ",", "1", ")", "{", "errChan", "<-", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "errChan", "\n", "}", "\n\n", "r", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "r", ".", "wg", ".", "Done", "(", ")", "\n\n", "rescanArgs", ":=", "append", "(", "r", ".", "options", ",", "updateChan", "(", "r", ".", "updateChan", ")", ")", "\n", "err", ":=", "rescan", "(", "r", ".", "chain", ",", "rescanArgs", "...", ")", "\n\n", "close", "(", "r", ".", "running", ")", "\n\n", "r", ".", "errMtx", ".", "Lock", "(", ")", "\n", "r", ".", "err", "=", "err", "\n", "r", ".", "errMtx", ".", "Unlock", "(", ")", "\n\n", "errChan", "<-", "err", "\n", "}", "(", ")", "\n\n", "return", "errChan", "\n", "}" ]
// Start kicks off the rescan goroutine, which will begin to scan the chain // according to the specified rescan options.
[ "Start", "kicks", "off", "the", "rescan", "goroutine", "which", "will", "begin", "to", "scan", "the", "chain", "according", "to", "the", "specified", "rescan", "options", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L1196-L1221
train
lightninglabs/neutrino
rescan.go
AddAddrs
func AddAddrs(addrs ...btcutil.Address) UpdateOption { return func(uo *updateOptions) { uo.addrs = append(uo.addrs, addrs...) } }
go
func AddAddrs(addrs ...btcutil.Address) UpdateOption { return func(uo *updateOptions) { uo.addrs = append(uo.addrs, addrs...) } }
[ "func", "AddAddrs", "(", "addrs", "...", "btcutil", ".", "Address", ")", "UpdateOption", "{", "return", "func", "(", "uo", "*", "updateOptions", ")", "{", "uo", ".", "addrs", "=", "append", "(", "uo", ".", "addrs", ",", "addrs", "...", ")", "\n", "}", "\n", "}" ]
// AddAddrs adds addresses to the filter.
[ "AddAddrs", "adds", "addresses", "to", "the", "filter", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L1240-L1244
train
lightninglabs/neutrino
rescan.go
AddInputs
func AddInputs(inputs ...InputWithScript) UpdateOption { return func(uo *updateOptions) { uo.inputs = append(uo.inputs, inputs...) } }
go
func AddInputs(inputs ...InputWithScript) UpdateOption { return func(uo *updateOptions) { uo.inputs = append(uo.inputs, inputs...) } }
[ "func", "AddInputs", "(", "inputs", "...", "InputWithScript", ")", "UpdateOption", "{", "return", "func", "(", "uo", "*", "updateOptions", ")", "{", "uo", ".", "inputs", "=", "append", "(", "uo", ".", "inputs", ",", "inputs", "...", ")", "\n", "}", "\n", "}" ]
// AddInputs adds inputs to watch to the filter.
[ "AddInputs", "adds", "inputs", "to", "watch", "to", "the", "filter", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/rescan.go#L1247-L1251
train
lightninglabs/neutrino
pushtx/broadcaster.go
NewBroadcaster
func NewBroadcaster(cfg *Config) *Broadcaster { b := &Broadcaster{ cfg: *cfg, broadcastReqs: make(chan *broadcastReq), transactions: make(map[chainhash.Hash]*wire.MsgTx), quit: make(chan struct{}), } return b }
go
func NewBroadcaster(cfg *Config) *Broadcaster { b := &Broadcaster{ cfg: *cfg, broadcastReqs: make(chan *broadcastReq), transactions: make(map[chainhash.Hash]*wire.MsgTx), quit: make(chan struct{}), } return b }
[ "func", "NewBroadcaster", "(", "cfg", "*", "Config", ")", "*", "Broadcaster", "{", "b", ":=", "&", "Broadcaster", "{", "cfg", ":", "*", "cfg", ",", "broadcastReqs", ":", "make", "(", "chan", "*", "broadcastReq", ")", ",", "transactions", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "*", "wire", ".", "MsgTx", ")", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n\n", "return", "b", "\n", "}" ]
// NewBroadcaster creates a new Broadcaster backed by the given config.
[ "NewBroadcaster", "creates", "a", "new", "Broadcaster", "backed", "by", "the", "given", "config", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/pushtx/broadcaster.go#L74-L83
train
lightninglabs/neutrino
pushtx/broadcaster.go
Start
func (b *Broadcaster) Start() error { var err error b.start.Do(func() { sub, err := b.cfg.SubscribeBlocks() if err != nil { err = fmt.Errorf("unable to subscribe for block "+ "notifications: %v", err) return } b.wg.Add(1) go b.broadcastHandler(sub) }) return err }
go
func (b *Broadcaster) Start() error { var err error b.start.Do(func() { sub, err := b.cfg.SubscribeBlocks() if err != nil { err = fmt.Errorf("unable to subscribe for block "+ "notifications: %v", err) return } b.wg.Add(1) go b.broadcastHandler(sub) }) return err }
[ "func", "(", "b", "*", "Broadcaster", ")", "Start", "(", ")", "error", "{", "var", "err", "error", "\n", "b", ".", "start", ".", "Do", "(", "func", "(", ")", "{", "sub", ",", "err", ":=", "b", ".", "cfg", ".", "SubscribeBlocks", "(", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "b", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "b", ".", "broadcastHandler", "(", "sub", ")", "\n", "}", ")", "\n", "return", "err", "\n", "}" ]
// Start starts all of the necessary steps for the Broadcaster to begin properly // carrying out its duties.
[ "Start", "starts", "all", "of", "the", "necessary", "steps", "for", "the", "Broadcaster", "to", "begin", "properly", "carrying", "out", "its", "duties", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/pushtx/broadcaster.go#L87-L101
train
lightninglabs/neutrino
pushtx/broadcaster.go
Stop
func (b *Broadcaster) Stop() { b.stop.Do(func() { close(b.quit) b.wg.Wait() }) }
go
func (b *Broadcaster) Stop() { b.stop.Do(func() { close(b.quit) b.wg.Wait() }) }
[ "func", "(", "b", "*", "Broadcaster", ")", "Stop", "(", ")", "{", "b", ".", "stop", ".", "Do", "(", "func", "(", ")", "{", "close", "(", "b", ".", "quit", ")", "\n", "b", ".", "wg", ".", "Wait", "(", ")", "\n", "}", ")", "\n", "}" ]
// Stop halts the Broadcaster from rebroadcasting pending transactions.
[ "Stop", "halts", "the", "Broadcaster", "from", "rebroadcasting", "pending", "transactions", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/pushtx/broadcaster.go#L104-L109
train
lightninglabs/neutrino
pushtx/broadcaster.go
handleBroadcastReq
func (b *Broadcaster) handleBroadcastReq(req *broadcastReq) error { err := b.cfg.Broadcast(req.tx) if err != nil && !IsBroadcastError(err, Mempool) { log.Errorf("Broadcast attempt failed: %v", err) return err } b.transactions[req.tx.TxHash()] = req.tx return nil }
go
func (b *Broadcaster) handleBroadcastReq(req *broadcastReq) error { err := b.cfg.Broadcast(req.tx) if err != nil && !IsBroadcastError(err, Mempool) { log.Errorf("Broadcast attempt failed: %v", err) return err } b.transactions[req.tx.TxHash()] = req.tx return nil }
[ "func", "(", "b", "*", "Broadcaster", ")", "handleBroadcastReq", "(", "req", "*", "broadcastReq", ")", "error", "{", "err", ":=", "b", ".", "cfg", ".", "Broadcast", "(", "req", ".", "tx", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "IsBroadcastError", "(", "err", ",", "Mempool", ")", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "b", ".", "transactions", "[", "req", ".", "tx", ".", "TxHash", "(", ")", "]", "=", "req", ".", "tx", "\n\n", "return", "nil", "\n", "}" ]
// handleBroadcastReq handles a new external request to reliably broadcast a // transaction to the network.
[ "handleBroadcastReq", "handles", "a", "new", "external", "request", "to", "reliably", "broadcast", "a", "transaction", "to", "the", "network", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/pushtx/broadcaster.go#L167-L177
train
lightninglabs/neutrino
pushtx/broadcaster.go
rebroadcast
func (b *Broadcaster) rebroadcast() { if len(b.transactions) == 0 { return } sortedTxs := wtxmgr.DependencySort(b.transactions) for _, tx := range sortedTxs { err := b.cfg.Broadcast(tx) switch { // If the transaction has already confirmed on-chain, we can // stop broadcasting it further. // // TODO(wilmer); This should ideally be implemented by checking // the chain ourselves rather than trusting our peers. case IsBroadcastError(err, Confirmed): log.Debugf("Re-broadcast of txid=%v, now confirmed!", tx.TxHash()) delete(b.transactions, tx.TxHash()) continue // If the transaction already exists within our peers' mempool, // we'll continue to rebroadcast it to ensure it actually // propagates throughout the network. // // TODO(wilmer): Rate limit peers that have already accepted our // transaction into their mempool to prevent resending to them // every time. case IsBroadcastError(err, Mempool): log.Debugf("Re-broadcast of txid=%v, still "+ "pending...", tx.TxHash()) continue case err != nil: log.Errorf("Unable to rebroadcast transaction %v: %v", tx.TxHash(), err) continue } } }
go
func (b *Broadcaster) rebroadcast() { if len(b.transactions) == 0 { return } sortedTxs := wtxmgr.DependencySort(b.transactions) for _, tx := range sortedTxs { err := b.cfg.Broadcast(tx) switch { // If the transaction has already confirmed on-chain, we can // stop broadcasting it further. // // TODO(wilmer); This should ideally be implemented by checking // the chain ourselves rather than trusting our peers. case IsBroadcastError(err, Confirmed): log.Debugf("Re-broadcast of txid=%v, now confirmed!", tx.TxHash()) delete(b.transactions, tx.TxHash()) continue // If the transaction already exists within our peers' mempool, // we'll continue to rebroadcast it to ensure it actually // propagates throughout the network. // // TODO(wilmer): Rate limit peers that have already accepted our // transaction into their mempool to prevent resending to them // every time. case IsBroadcastError(err, Mempool): log.Debugf("Re-broadcast of txid=%v, still "+ "pending...", tx.TxHash()) continue case err != nil: log.Errorf("Unable to rebroadcast transaction %v: %v", tx.TxHash(), err) continue } } }
[ "func", "(", "b", "*", "Broadcaster", ")", "rebroadcast", "(", ")", "{", "if", "len", "(", "b", ".", "transactions", ")", "==", "0", "{", "return", "\n", "}", "\n\n", "sortedTxs", ":=", "wtxmgr", ".", "DependencySort", "(", "b", ".", "transactions", ")", "\n", "for", "_", ",", "tx", ":=", "range", "sortedTxs", "{", "err", ":=", "b", ".", "cfg", ".", "Broadcast", "(", "tx", ")", "\n", "switch", "{", "// If the transaction has already confirmed on-chain, we can", "// stop broadcasting it further.", "//", "// TODO(wilmer); This should ideally be implemented by checking", "// the chain ourselves rather than trusting our peers.", "case", "IsBroadcastError", "(", "err", ",", "Confirmed", ")", ":", "log", ".", "Debugf", "(", "\"", "\"", ",", "tx", ".", "TxHash", "(", ")", ")", "\n\n", "delete", "(", "b", ".", "transactions", ",", "tx", ".", "TxHash", "(", ")", ")", "\n", "continue", "\n\n", "// If the transaction already exists within our peers' mempool,", "// we'll continue to rebroadcast it to ensure it actually", "// propagates throughout the network.", "//", "// TODO(wilmer): Rate limit peers that have already accepted our", "// transaction into their mempool to prevent resending to them", "// every time.", "case", "IsBroadcastError", "(", "err", ",", "Mempool", ")", ":", "log", ".", "Debugf", "(", "\"", "\"", "+", "\"", "\"", ",", "tx", ".", "TxHash", "(", ")", ")", "\n\n", "continue", "\n\n", "case", "err", "!=", "nil", ":", "log", ".", "Errorf", "(", "\"", "\"", ",", "tx", ".", "TxHash", "(", ")", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "}" ]
// rebroadcast rebroadcasts all of the currently pending transactions. Care has // been taken to ensure that the transactions are sorted in their dependency // order to prevent peers from deeming our transactions as invalid due to // broadcasting them before their pending dependencies.
[ "rebroadcast", "rebroadcasts", "all", "of", "the", "currently", "pending", "transactions", ".", "Care", "has", "been", "taken", "to", "ensure", "that", "the", "transactions", "are", "sorted", "in", "their", "dependency", "order", "to", "prevent", "peers", "from", "deeming", "our", "transactions", "as", "invalid", "due", "to", "broadcasting", "them", "before", "their", "pending", "dependencies", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/pushtx/broadcaster.go#L183-L223
train
lightninglabs/neutrino
pushtx/broadcaster.go
Broadcast
func (b *Broadcaster) Broadcast(tx *wire.MsgTx) error { errChan := make(chan error, 1) select { case b.broadcastReqs <- &broadcastReq{ tx: tx, errChan: errChan, }: case <-b.quit: return ErrBroadcasterStopped } select { case err := <-errChan: return err case <-b.quit: return ErrBroadcasterStopped } }
go
func (b *Broadcaster) Broadcast(tx *wire.MsgTx) error { errChan := make(chan error, 1) select { case b.broadcastReqs <- &broadcastReq{ tx: tx, errChan: errChan, }: case <-b.quit: return ErrBroadcasterStopped } select { case err := <-errChan: return err case <-b.quit: return ErrBroadcasterStopped } }
[ "func", "(", "b", "*", "Broadcaster", ")", "Broadcast", "(", "tx", "*", "wire", ".", "MsgTx", ")", "error", "{", "errChan", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n\n", "select", "{", "case", "b", ".", "broadcastReqs", "<-", "&", "broadcastReq", "{", "tx", ":", "tx", ",", "errChan", ":", "errChan", ",", "}", ":", "case", "<-", "b", ".", "quit", ":", "return", "ErrBroadcasterStopped", "\n", "}", "\n\n", "select", "{", "case", "err", ":=", "<-", "errChan", ":", "return", "err", "\n", "case", "<-", "b", ".", "quit", ":", "return", "ErrBroadcasterStopped", "\n", "}", "\n", "}" ]
// Broadcast submits a request to the Broadcaster to reliably broadcast the // given transaction. An error won't be returned if the transaction already // exists within the mempool. Any transaction broadcast through this method will // be rebroadcast upon every change of the tip of the chain.
[ "Broadcast", "submits", "a", "request", "to", "the", "Broadcaster", "to", "reliably", "broadcast", "the", "given", "transaction", ".", "An", "error", "won", "t", "be", "returned", "if", "the", "transaction", "already", "exists", "within", "the", "mempool", ".", "Any", "transaction", "broadcast", "through", "this", "method", "will", "be", "rebroadcast", "upon", "every", "change", "of", "the", "tip", "of", "the", "chain", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/pushtx/broadcaster.go#L229-L247
train
lightninglabs/neutrino
blockntfns/manager.go
NewSubscriptionManager
func NewSubscriptionManager(ntfnSource NotificationSource) *SubscriptionManager { return &SubscriptionManager{ subscribers: make(map[uint64]*newSubscription), newSubscriptions: make(chan *newSubscription), cancelSubscriptions: make(chan *cancelSubscription), ntfnSource: ntfnSource, quit: make(chan struct{}), } }
go
func NewSubscriptionManager(ntfnSource NotificationSource) *SubscriptionManager { return &SubscriptionManager{ subscribers: make(map[uint64]*newSubscription), newSubscriptions: make(chan *newSubscription), cancelSubscriptions: make(chan *cancelSubscription), ntfnSource: ntfnSource, quit: make(chan struct{}), } }
[ "func", "NewSubscriptionManager", "(", "ntfnSource", "NotificationSource", ")", "*", "SubscriptionManager", "{", "return", "&", "SubscriptionManager", "{", "subscribers", ":", "make", "(", "map", "[", "uint64", "]", "*", "newSubscription", ")", ",", "newSubscriptions", ":", "make", "(", "chan", "*", "newSubscription", ")", ",", "cancelSubscriptions", ":", "make", "(", "chan", "*", "cancelSubscription", ")", ",", "ntfnSource", ":", "ntfnSource", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "}" ]
// NewSubscriptionManager creates a subscription manager backed by a // NotificationSource.
[ "NewSubscriptionManager", "creates", "a", "subscription", "manager", "backed", "by", "a", "NotificationSource", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockntfns/manager.go#L104-L112
train
lightninglabs/neutrino
blockntfns/manager.go
Start
func (m *SubscriptionManager) Start() { if atomic.AddInt32(&m.started, 1) != 1 { return } log.Debug("Starting block notifications subscription manager") m.wg.Add(1) go m.subscriptionHandler() }
go
func (m *SubscriptionManager) Start() { if atomic.AddInt32(&m.started, 1) != 1 { return } log.Debug("Starting block notifications subscription manager") m.wg.Add(1) go m.subscriptionHandler() }
[ "func", "(", "m", "*", "SubscriptionManager", ")", "Start", "(", ")", "{", "if", "atomic", ".", "AddInt32", "(", "&", "m", ".", "started", ",", "1", ")", "!=", "1", "{", "return", "\n", "}", "\n\n", "log", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "m", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "m", ".", "subscriptionHandler", "(", ")", "\n", "}" ]
// Start starts all the goroutines required for the SubscriptionManager to carry // out its duties.
[ "Start", "starts", "all", "the", "goroutines", "required", "for", "the", "SubscriptionManager", "to", "carry", "out", "its", "duties", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockntfns/manager.go#L116-L125
train
lightninglabs/neutrino
blockntfns/manager.go
Stop
func (m *SubscriptionManager) Stop() { if atomic.AddInt32(&m.stopped, 1) != 1 { return } log.Debug("Stopping block notifications subscription manager") close(m.quit) m.wg.Wait() var wg sync.WaitGroup wg.Add(len(m.subscribers)) for _, subscriber := range m.subscribers { go func() { defer wg.Done() subscriber.cancel() }() } wg.Wait() }
go
func (m *SubscriptionManager) Stop() { if atomic.AddInt32(&m.stopped, 1) != 1 { return } log.Debug("Stopping block notifications subscription manager") close(m.quit) m.wg.Wait() var wg sync.WaitGroup wg.Add(len(m.subscribers)) for _, subscriber := range m.subscribers { go func() { defer wg.Done() subscriber.cancel() }() } wg.Wait() }
[ "func", "(", "m", "*", "SubscriptionManager", ")", "Stop", "(", ")", "{", "if", "atomic", ".", "AddInt32", "(", "&", "m", ".", "stopped", ",", "1", ")", "!=", "1", "{", "return", "\n", "}", "\n\n", "log", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "close", "(", "m", ".", "quit", ")", "\n", "m", ".", "wg", ".", "Wait", "(", ")", "\n\n", "var", "wg", "sync", ".", "WaitGroup", "\n", "wg", ".", "Add", "(", "len", "(", "m", ".", "subscribers", ")", ")", "\n", "for", "_", ",", "subscriber", ":=", "range", "m", ".", "subscribers", "{", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "subscriber", ".", "cancel", "(", ")", "\n", "}", "(", ")", "\n", "}", "\n\n", "wg", ".", "Wait", "(", ")", "\n", "}" ]
// Stop stops all active goroutines required for the SubscriptionManager to // carry out its duties.
[ "Stop", "stops", "all", "active", "goroutines", "required", "for", "the", "SubscriptionManager", "to", "carry", "out", "its", "duties", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockntfns/manager.go#L129-L149
train
lightninglabs/neutrino
blockntfns/manager.go
NewSubscription
func (m *SubscriptionManager) NewSubscription(bestHeight uint32) (*Subscription, error) { // We'll start by constructing the internal messages that the // subscription handler will use to register the new client. sub := &newSubscription{ id: atomic.AddUint64(&m.subscriberCounter, 1), ntfnChan: make(chan BlockNtfn, 20), ntfnQueue: queue.NewConcurrentQueue(20), bestHeight: bestHeight, errChan: make(chan error, 1), quit: make(chan struct{}), } // We'll start the notification queue now so that it is ready in the // event that a backlog of notifications is to be delivered. sub.ntfnQueue.Start() // We'll also start a goroutine that will attempt to consume // notifications from this queue by delivering them to the client // itself. sub.wg.Add(1) go func() { defer sub.wg.Done() for { select { case ntfn, ok := <-sub.ntfnQueue.ChanOut(): if !ok { return } select { case sub.ntfnChan <- ntfn.(BlockNtfn): case <-sub.quit: return case <-m.quit: return } case <-sub.quit: return case <-m.quit: return } } }() // Now, we can deliver the notification to the subscription handler. select { case m.newSubscriptions <- sub: case <-m.quit: sub.ntfnQueue.Stop() return nil, ErrSubscriptionManagerStopped } // It's possible that the registration failed if we were unable to // deliver the backlog of notifications, so we'll make sure to handle // the error. select { case err := <-sub.errChan: if err != nil { sub.ntfnQueue.Stop() return nil, err } case <-m.quit: sub.ntfnQueue.Stop() return nil, ErrSubscriptionManagerStopped } // Finally, we can return to the client with its new subscription // successfully registered. return &Subscription{ Notifications: sub.ntfnChan, Cancel: func() { m.cancelSubscription(sub) }, }, nil }
go
func (m *SubscriptionManager) NewSubscription(bestHeight uint32) (*Subscription, error) { // We'll start by constructing the internal messages that the // subscription handler will use to register the new client. sub := &newSubscription{ id: atomic.AddUint64(&m.subscriberCounter, 1), ntfnChan: make(chan BlockNtfn, 20), ntfnQueue: queue.NewConcurrentQueue(20), bestHeight: bestHeight, errChan: make(chan error, 1), quit: make(chan struct{}), } // We'll start the notification queue now so that it is ready in the // event that a backlog of notifications is to be delivered. sub.ntfnQueue.Start() // We'll also start a goroutine that will attempt to consume // notifications from this queue by delivering them to the client // itself. sub.wg.Add(1) go func() { defer sub.wg.Done() for { select { case ntfn, ok := <-sub.ntfnQueue.ChanOut(): if !ok { return } select { case sub.ntfnChan <- ntfn.(BlockNtfn): case <-sub.quit: return case <-m.quit: return } case <-sub.quit: return case <-m.quit: return } } }() // Now, we can deliver the notification to the subscription handler. select { case m.newSubscriptions <- sub: case <-m.quit: sub.ntfnQueue.Stop() return nil, ErrSubscriptionManagerStopped } // It's possible that the registration failed if we were unable to // deliver the backlog of notifications, so we'll make sure to handle // the error. select { case err := <-sub.errChan: if err != nil { sub.ntfnQueue.Stop() return nil, err } case <-m.quit: sub.ntfnQueue.Stop() return nil, ErrSubscriptionManagerStopped } // Finally, we can return to the client with its new subscription // successfully registered. return &Subscription{ Notifications: sub.ntfnChan, Cancel: func() { m.cancelSubscription(sub) }, }, nil }
[ "func", "(", "m", "*", "SubscriptionManager", ")", "NewSubscription", "(", "bestHeight", "uint32", ")", "(", "*", "Subscription", ",", "error", ")", "{", "// We'll start by constructing the internal messages that the", "// subscription handler will use to register the new client.", "sub", ":=", "&", "newSubscription", "{", "id", ":", "atomic", ".", "AddUint64", "(", "&", "m", ".", "subscriberCounter", ",", "1", ")", ",", "ntfnChan", ":", "make", "(", "chan", "BlockNtfn", ",", "20", ")", ",", "ntfnQueue", ":", "queue", ".", "NewConcurrentQueue", "(", "20", ")", ",", "bestHeight", ":", "bestHeight", ",", "errChan", ":", "make", "(", "chan", "error", ",", "1", ")", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n\n", "// We'll start the notification queue now so that it is ready in the", "// event that a backlog of notifications is to be delivered.", "sub", ".", "ntfnQueue", ".", "Start", "(", ")", "\n\n", "// We'll also start a goroutine that will attempt to consume", "// notifications from this queue by delivering them to the client", "// itself.", "sub", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "sub", ".", "wg", ".", "Done", "(", ")", "\n\n", "for", "{", "select", "{", "case", "ntfn", ",", "ok", ":=", "<-", "sub", ".", "ntfnQueue", ".", "ChanOut", "(", ")", ":", "if", "!", "ok", "{", "return", "\n", "}", "\n\n", "select", "{", "case", "sub", ".", "ntfnChan", "<-", "ntfn", ".", "(", "BlockNtfn", ")", ":", "case", "<-", "sub", ".", "quit", ":", "return", "\n", "case", "<-", "m", ".", "quit", ":", "return", "\n", "}", "\n", "case", "<-", "sub", ".", "quit", ":", "return", "\n", "case", "<-", "m", ".", "quit", ":", "return", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "// Now, we can deliver the notification to the subscription handler.", "select", "{", "case", "m", ".", "newSubscriptions", "<-", "sub", ":", "case", "<-", "m", ".", "quit", ":", "sub", ".", "ntfnQueue", ".", "Stop", "(", ")", "\n", "return", "nil", ",", "ErrSubscriptionManagerStopped", "\n", "}", "\n\n", "// It's possible that the registration failed if we were unable to", "// deliver the backlog of notifications, so we'll make sure to handle", "// the error.", "select", "{", "case", "err", ":=", "<-", "sub", ".", "errChan", ":", "if", "err", "!=", "nil", "{", "sub", ".", "ntfnQueue", ".", "Stop", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "case", "<-", "m", ".", "quit", ":", "sub", ".", "ntfnQueue", ".", "Stop", "(", ")", "\n", "return", "nil", ",", "ErrSubscriptionManagerStopped", "\n", "}", "\n\n", "// Finally, we can return to the client with its new subscription", "// successfully registered.", "return", "&", "Subscription", "{", "Notifications", ":", "sub", ".", "ntfnChan", ",", "Cancel", ":", "func", "(", ")", "{", "m", ".", "cancelSubscription", "(", "sub", ")", "\n", "}", ",", "}", ",", "nil", "\n", "}" ]
// NewSubscription creates a new block notification subscription for a client. // The bestHeight parameter can be used by the client to indicate its best known // state. A backlog of notifications from said point until the tip of the chain // will be delivered upon the client's successful registration. When providing a // bestHeight of 0, no backlog will be delivered. // // These notifications, along with the latest notifications of the chain, will // be delivered through the Notifications channel within the Subscription // returned. A Cancel closure is also provided, in the event that the client // wishes to no longer receive any notifications.
[ "NewSubscription", "creates", "a", "new", "block", "notification", "subscription", "for", "a", "client", ".", "The", "bestHeight", "parameter", "can", "be", "used", "by", "the", "client", "to", "indicate", "its", "best", "known", "state", ".", "A", "backlog", "of", "notifications", "from", "said", "point", "until", "the", "tip", "of", "the", "chain", "will", "be", "delivered", "upon", "the", "client", "s", "successful", "registration", ".", "When", "providing", "a", "bestHeight", "of", "0", "no", "backlog", "will", "be", "delivered", ".", "These", "notifications", "along", "with", "the", "latest", "notifications", "of", "the", "chain", "will", "be", "delivered", "through", "the", "Notifications", "channel", "within", "the", "Subscription", "returned", ".", "A", "Cancel", "closure", "is", "also", "provided", "in", "the", "event", "that", "the", "client", "wishes", "to", "no", "longer", "receive", "any", "notifications", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockntfns/manager.go#L197-L274
train
lightninglabs/neutrino
blockntfns/manager.go
handleNewSubscription
func (m *SubscriptionManager) handleNewSubscription(sub *newSubscription) error { log.Infof("Registering block subscription: id=%d", sub.id) // We'll start by retrieving a backlog of notifications from the // client's best height. blocks, currentHeight, err := m.ntfnSource.NotificationsSinceHeight( sub.bestHeight, ) if err != nil { return fmt.Errorf("unable to retrieve blocks since height=%d: "+ "%v", sub.bestHeight, err) } // We'll then attempt to deliver these notifications. log.Debugf("Delivering backlog of block notifications: id=%d, "+ "start_height=%d, end_height=%d", sub.id, sub.bestHeight, currentHeight) for _, block := range blocks { m.notifySubscriber(sub, block) } // With the notifications delivered, we can keep track of the new client // internally in order to deliver new block notifications about the // chain. m.subscribers[sub.id] = sub return nil }
go
func (m *SubscriptionManager) handleNewSubscription(sub *newSubscription) error { log.Infof("Registering block subscription: id=%d", sub.id) // We'll start by retrieving a backlog of notifications from the // client's best height. blocks, currentHeight, err := m.ntfnSource.NotificationsSinceHeight( sub.bestHeight, ) if err != nil { return fmt.Errorf("unable to retrieve blocks since height=%d: "+ "%v", sub.bestHeight, err) } // We'll then attempt to deliver these notifications. log.Debugf("Delivering backlog of block notifications: id=%d, "+ "start_height=%d, end_height=%d", sub.id, sub.bestHeight, currentHeight) for _, block := range blocks { m.notifySubscriber(sub, block) } // With the notifications delivered, we can keep track of the new client // internally in order to deliver new block notifications about the // chain. m.subscribers[sub.id] = sub return nil }
[ "func", "(", "m", "*", "SubscriptionManager", ")", "handleNewSubscription", "(", "sub", "*", "newSubscription", ")", "error", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "sub", ".", "id", ")", "\n\n", "// We'll start by retrieving a backlog of notifications from the", "// client's best height.", "blocks", ",", "currentHeight", ",", "err", ":=", "m", ".", "ntfnSource", ".", "NotificationsSinceHeight", "(", "sub", ".", "bestHeight", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "sub", ".", "bestHeight", ",", "err", ")", "\n", "}", "\n\n", "// We'll then attempt to deliver these notifications.", "log", ".", "Debugf", "(", "\"", "\"", "+", "\"", "\"", ",", "sub", ".", "id", ",", "sub", ".", "bestHeight", ",", "currentHeight", ")", "\n\n", "for", "_", ",", "block", ":=", "range", "blocks", "{", "m", ".", "notifySubscriber", "(", "sub", ",", "block", ")", "\n", "}", "\n\n", "// With the notifications delivered, we can keep track of the new client", "// internally in order to deliver new block notifications about the", "// chain.", "m", ".", "subscribers", "[", "sub", ".", "id", "]", "=", "sub", "\n\n", "return", "nil", "\n", "}" ]
// handleNewSubscription handles a request to create a new block subscription.
[ "handleNewSubscription", "handles", "a", "request", "to", "create", "a", "new", "block", "subscription", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockntfns/manager.go#L277-L305
train
lightninglabs/neutrino
blockntfns/manager.go
cancelSubscription
func (m *SubscriptionManager) cancelSubscription(sub *newSubscription) { select { case m.cancelSubscriptions <- &cancelSubscription{sub.id}: case <-m.quit: } }
go
func (m *SubscriptionManager) cancelSubscription(sub *newSubscription) { select { case m.cancelSubscriptions <- &cancelSubscription{sub.id}: case <-m.quit: } }
[ "func", "(", "m", "*", "SubscriptionManager", ")", "cancelSubscription", "(", "sub", "*", "newSubscription", ")", "{", "select", "{", "case", "m", ".", "cancelSubscriptions", "<-", "&", "cancelSubscription", "{", "sub", ".", "id", "}", ":", "case", "<-", "m", ".", "quit", ":", "}", "\n", "}" ]
// cancelSubscription sends a request to the subscription handler to cancel an // existing subscription.
[ "cancelSubscription", "sends", "a", "request", "to", "the", "subscription", "handler", "to", "cancel", "an", "existing", "subscription", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockntfns/manager.go#L309-L314
train
lightninglabs/neutrino
blockntfns/manager.go
handleCancelSubscription
func (m *SubscriptionManager) handleCancelSubscription(msg *cancelSubscription) { // First, we'll attempt to look up an existing susbcriber with the given // ID. sub, ok := m.subscribers[msg.id] if !ok { return } log.Infof("Canceling block subscription: id=%d", msg.id) // If there is one, we'll stop their internal queue to no longer deliver // notifications to them. delete(m.subscribers, msg.id) sub.cancel() }
go
func (m *SubscriptionManager) handleCancelSubscription(msg *cancelSubscription) { // First, we'll attempt to look up an existing susbcriber with the given // ID. sub, ok := m.subscribers[msg.id] if !ok { return } log.Infof("Canceling block subscription: id=%d", msg.id) // If there is one, we'll stop their internal queue to no longer deliver // notifications to them. delete(m.subscribers, msg.id) sub.cancel() }
[ "func", "(", "m", "*", "SubscriptionManager", ")", "handleCancelSubscription", "(", "msg", "*", "cancelSubscription", ")", "{", "// First, we'll attempt to look up an existing susbcriber with the given", "// ID.", "sub", ",", "ok", ":=", "m", ".", "subscribers", "[", "msg", ".", "id", "]", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "msg", ".", "id", ")", "\n\n", "// If there is one, we'll stop their internal queue to no longer deliver", "// notifications to them.", "delete", "(", "m", ".", "subscribers", ",", "msg", ".", "id", ")", "\n", "sub", ".", "cancel", "(", ")", "\n", "}" ]
// handleCancelSubscription handles a request to cancel an existing // subscription.
[ "handleCancelSubscription", "handles", "a", "request", "to", "cancel", "an", "existing", "subscription", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockntfns/manager.go#L318-L332
train
lightninglabs/neutrino
blockntfns/manager.go
notifySubscribers
func (m *SubscriptionManager) notifySubscribers(ntfn BlockNtfn) { log.Tracef("Notifying %v", ntfn) for _, subscriber := range m.subscribers { m.notifySubscriber(subscriber, ntfn) } }
go
func (m *SubscriptionManager) notifySubscribers(ntfn BlockNtfn) { log.Tracef("Notifying %v", ntfn) for _, subscriber := range m.subscribers { m.notifySubscriber(subscriber, ntfn) } }
[ "func", "(", "m", "*", "SubscriptionManager", ")", "notifySubscribers", "(", "ntfn", "BlockNtfn", ")", "{", "log", ".", "Tracef", "(", "\"", "\"", ",", "ntfn", ")", "\n\n", "for", "_", ",", "subscriber", ":=", "range", "m", ".", "subscribers", "{", "m", ".", "notifySubscriber", "(", "subscriber", ",", "ntfn", ")", "\n", "}", "\n", "}" ]
// notifySubscribers notifies all currently active subscribers about the block.
[ "notifySubscribers", "notifies", "all", "currently", "active", "subscribers", "about", "the", "block", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockntfns/manager.go#L335-L341
train
lightninglabs/neutrino
blockntfns/manager.go
notifySubscriber
func (m *SubscriptionManager) notifySubscriber(sub *newSubscription, block BlockNtfn) { select { case sub.ntfnQueue.ChanIn() <- block: case <-sub.quit: case <-m.quit: return } }
go
func (m *SubscriptionManager) notifySubscriber(sub *newSubscription, block BlockNtfn) { select { case sub.ntfnQueue.ChanIn() <- block: case <-sub.quit: case <-m.quit: return } }
[ "func", "(", "m", "*", "SubscriptionManager", ")", "notifySubscriber", "(", "sub", "*", "newSubscription", ",", "block", "BlockNtfn", ")", "{", "select", "{", "case", "sub", ".", "ntfnQueue", ".", "ChanIn", "(", ")", "<-", "block", ":", "case", "<-", "sub", ".", "quit", ":", "case", "<-", "m", ".", "quit", ":", "return", "\n", "}", "\n", "}" ]
// notifySubscriber notifies a single subscriber about the block.
[ "notifySubscriber", "notifies", "a", "single", "subscriber", "about", "the", "block", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockntfns/manager.go#L344-L353
train
lightninglabs/neutrino
utxoscanner.go
deliver
func (r *GetUtxoRequest) deliver(report *SpendReport, err error) { select { case r.resultChan <- &getUtxoResult{report, err}: default: log.Warnf("duplicate getutxo result delivered for "+ "outpoint=%v, spend=%v, err=%v", r.Input.OutPoint, report, err) } }
go
func (r *GetUtxoRequest) deliver(report *SpendReport, err error) { select { case r.resultChan <- &getUtxoResult{report, err}: default: log.Warnf("duplicate getutxo result delivered for "+ "outpoint=%v, spend=%v, err=%v", r.Input.OutPoint, report, err) } }
[ "func", "(", "r", "*", "GetUtxoRequest", ")", "deliver", "(", "report", "*", "SpendReport", ",", "err", "error", ")", "{", "select", "{", "case", "r", ".", "resultChan", "<-", "&", "getUtxoResult", "{", "report", ",", "err", "}", ":", "default", ":", "log", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", ",", "r", ".", "Input", ".", "OutPoint", ",", "report", ",", "err", ")", "\n", "}", "\n", "}" ]
// deliver tries to deliver the report or error to any subscribers. If // resultChan cannot accept a new update, this method will not block.
[ "deliver", "tries", "to", "deliver", "the", "report", "or", "error", "to", "any", "subscribers", ".", "If", "resultChan", "cannot", "accept", "a", "new", "update", "this", "method", "will", "not", "block", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/utxoscanner.go#L47-L55
train
lightninglabs/neutrino
utxoscanner.go
Result
func (r *GetUtxoRequest) Result(cancel <-chan struct{}) (*SpendReport, error) { r.mu.Lock() defer r.mu.Unlock() select { case result := <-r.resultChan: // Cache the first result returned, in case we have multiple // readers calling Result. if r.result == nil { r.result = result } return r.result.report, r.result.err case <-cancel: return nil, ErrGetUtxoCancelled case <-r.quit: return nil, ErrShuttingDown } }
go
func (r *GetUtxoRequest) Result(cancel <-chan struct{}) (*SpendReport, error) { r.mu.Lock() defer r.mu.Unlock() select { case result := <-r.resultChan: // Cache the first result returned, in case we have multiple // readers calling Result. if r.result == nil { r.result = result } return r.result.report, r.result.err case <-cancel: return nil, ErrGetUtxoCancelled case <-r.quit: return nil, ErrShuttingDown } }
[ "func", "(", "r", "*", "GetUtxoRequest", ")", "Result", "(", "cancel", "<-", "chan", "struct", "{", "}", ")", "(", "*", "SpendReport", ",", "error", ")", "{", "r", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "select", "{", "case", "result", ":=", "<-", "r", ".", "resultChan", ":", "// Cache the first result returned, in case we have multiple", "// readers calling Result.", "if", "r", ".", "result", "==", "nil", "{", "r", ".", "result", "=", "result", "\n", "}", "\n\n", "return", "r", ".", "result", ".", "report", ",", "r", ".", "result", ".", "err", "\n\n", "case", "<-", "cancel", ":", "return", "nil", ",", "ErrGetUtxoCancelled", "\n\n", "case", "<-", "r", ".", "quit", ":", "return", "nil", ",", "ErrShuttingDown", "\n", "}", "\n", "}" ]
// Result is callback returning either a spend report or an error.
[ "Result", "is", "callback", "returning", "either", "a", "spend", "report", "or", "an", "error", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/utxoscanner.go#L58-L78
train
lightninglabs/neutrino
utxoscanner.go
NewUtxoScanner
func NewUtxoScanner(cfg *UtxoScannerConfig) *UtxoScanner { scanner := &UtxoScanner{ cfg: cfg, quit: make(chan struct{}), shutdown: make(chan struct{}), } scanner.cv = sync.NewCond(&scanner.mu) return scanner }
go
func NewUtxoScanner(cfg *UtxoScannerConfig) *UtxoScanner { scanner := &UtxoScanner{ cfg: cfg, quit: make(chan struct{}), shutdown: make(chan struct{}), } scanner.cv = sync.NewCond(&scanner.mu) return scanner }
[ "func", "NewUtxoScanner", "(", "cfg", "*", "UtxoScannerConfig", ")", "*", "UtxoScanner", "{", "scanner", ":=", "&", "UtxoScanner", "{", "cfg", ":", "cfg", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "shutdown", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "scanner", ".", "cv", "=", "sync", ".", "NewCond", "(", "&", "scanner", ".", "mu", ")", "\n\n", "return", "scanner", "\n", "}" ]
// NewUtxoScanner creates a new instance of UtxoScanner using the given chain // interface.
[ "NewUtxoScanner", "creates", "a", "new", "instance", "of", "UtxoScanner", "using", "the", "given", "chain", "interface", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/utxoscanner.go#L119-L128
train
lightninglabs/neutrino
utxoscanner.go
Start
func (s *UtxoScanner) Start() error { if !atomic.CompareAndSwapUint32(&s.started, 0, 1) { return nil } s.wg.Add(1) go s.batchManager() return nil }
go
func (s *UtxoScanner) Start() error { if !atomic.CompareAndSwapUint32(&s.started, 0, 1) { return nil } s.wg.Add(1) go s.batchManager() return nil }
[ "func", "(", "s", "*", "UtxoScanner", ")", "Start", "(", ")", "error", "{", "if", "!", "atomic", ".", "CompareAndSwapUint32", "(", "&", "s", ".", "started", ",", "0", ",", "1", ")", "{", "return", "nil", "\n", "}", "\n\n", "s", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "s", ".", "batchManager", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Start begins running scan batches.
[ "Start", "begins", "running", "scan", "batches", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/utxoscanner.go#L131-L140
train
lightninglabs/neutrino
utxoscanner.go
Stop
func (s *UtxoScanner) Stop() error { if !atomic.CompareAndSwapUint32(&s.stopped, 0, 1) { return nil } close(s.quit) batchShutdown: for { select { case <-s.shutdown: break batchShutdown case <-time.After(50 * time.Millisecond): s.cv.Signal() } } // Cancel all pending get utxo requests that were not pulled into the // batchManager's main goroutine. for !s.pq.IsEmpty() { pendingReq := heap.Pop(&s.pq).(*GetUtxoRequest) pendingReq.deliver(nil, ErrShuttingDown) } return nil }
go
func (s *UtxoScanner) Stop() error { if !atomic.CompareAndSwapUint32(&s.stopped, 0, 1) { return nil } close(s.quit) batchShutdown: for { select { case <-s.shutdown: break batchShutdown case <-time.After(50 * time.Millisecond): s.cv.Signal() } } // Cancel all pending get utxo requests that were not pulled into the // batchManager's main goroutine. for !s.pq.IsEmpty() { pendingReq := heap.Pop(&s.pq).(*GetUtxoRequest) pendingReq.deliver(nil, ErrShuttingDown) } return nil }
[ "func", "(", "s", "*", "UtxoScanner", ")", "Stop", "(", ")", "error", "{", "if", "!", "atomic", ".", "CompareAndSwapUint32", "(", "&", "s", ".", "stopped", ",", "0", ",", "1", ")", "{", "return", "nil", "\n", "}", "\n\n", "close", "(", "s", ".", "quit", ")", "\n\n", "batchShutdown", ":", "for", "{", "select", "{", "case", "<-", "s", ".", "shutdown", ":", "break", "batchShutdown", "\n", "case", "<-", "time", ".", "After", "(", "50", "*", "time", ".", "Millisecond", ")", ":", "s", ".", "cv", ".", "Signal", "(", ")", "\n", "}", "\n", "}", "\n\n", "// Cancel all pending get utxo requests that were not pulled into the", "// batchManager's main goroutine.", "for", "!", "s", ".", "pq", ".", "IsEmpty", "(", ")", "{", "pendingReq", ":=", "heap", ".", "Pop", "(", "&", "s", ".", "pq", ")", ".", "(", "*", "GetUtxoRequest", ")", "\n", "pendingReq", ".", "deliver", "(", "nil", ",", "ErrShuttingDown", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Stop any in-progress scan.
[ "Stop", "any", "in", "-", "progress", "scan", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/utxoscanner.go#L143-L168
train
lightninglabs/neutrino
utxoscanner.go
Enqueue
func (s *UtxoScanner) Enqueue(input *InputWithScript, birthHeight uint32) (*GetUtxoRequest, error) { log.Debugf("Enqueuing request for %s with birth height %d", input.OutPoint.String(), birthHeight) req := &GetUtxoRequest{ Input: input, BirthHeight: birthHeight, resultChan: make(chan *getUtxoResult, 1), quit: s.quit, } s.cv.L.Lock() select { case <-s.quit: s.cv.L.Unlock() return nil, ErrShuttingDown default: } // Insert the request into the queue and signal any threads that might be // waiting for new elements. heap.Push(&s.pq, req) s.cv.L.Unlock() s.cv.Signal() return req, nil }
go
func (s *UtxoScanner) Enqueue(input *InputWithScript, birthHeight uint32) (*GetUtxoRequest, error) { log.Debugf("Enqueuing request for %s with birth height %d", input.OutPoint.String(), birthHeight) req := &GetUtxoRequest{ Input: input, BirthHeight: birthHeight, resultChan: make(chan *getUtxoResult, 1), quit: s.quit, } s.cv.L.Lock() select { case <-s.quit: s.cv.L.Unlock() return nil, ErrShuttingDown default: } // Insert the request into the queue and signal any threads that might be // waiting for new elements. heap.Push(&s.pq, req) s.cv.L.Unlock() s.cv.Signal() return req, nil }
[ "func", "(", "s", "*", "UtxoScanner", ")", "Enqueue", "(", "input", "*", "InputWithScript", ",", "birthHeight", "uint32", ")", "(", "*", "GetUtxoRequest", ",", "error", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "input", ".", "OutPoint", ".", "String", "(", ")", ",", "birthHeight", ")", "\n\n", "req", ":=", "&", "GetUtxoRequest", "{", "Input", ":", "input", ",", "BirthHeight", ":", "birthHeight", ",", "resultChan", ":", "make", "(", "chan", "*", "getUtxoResult", ",", "1", ")", ",", "quit", ":", "s", ".", "quit", ",", "}", "\n\n", "s", ".", "cv", ".", "L", ".", "Lock", "(", ")", "\n", "select", "{", "case", "<-", "s", ".", "quit", ":", "s", ".", "cv", ".", "L", ".", "Unlock", "(", ")", "\n", "return", "nil", ",", "ErrShuttingDown", "\n", "default", ":", "}", "\n\n", "// Insert the request into the queue and signal any threads that might be", "// waiting for new elements.", "heap", ".", "Push", "(", "&", "s", ".", "pq", ",", "req", ")", "\n\n", "s", ".", "cv", ".", "L", ".", "Unlock", "(", ")", "\n", "s", ".", "cv", ".", "Signal", "(", ")", "\n\n", "return", "req", ",", "nil", "\n", "}" ]
// Enqueue takes a GetUtxoRequest and adds it to the next applicable batch.
[ "Enqueue", "takes", "a", "GetUtxoRequest", "and", "adds", "it", "to", "the", "next", "applicable", "batch", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/utxoscanner.go#L171-L200
train
lightninglabs/neutrino
utxoscanner.go
dequeueAtHeight
func (s *UtxoScanner) dequeueAtHeight(height uint32) []*GetUtxoRequest { s.cv.L.Lock() defer s.cv.L.Unlock() // Take any requests that are too old to go in this batch and keep them for // the next batch. for !s.pq.IsEmpty() && s.pq.Peek().BirthHeight < height { item := heap.Pop(&s.pq).(*GetUtxoRequest) s.nextBatch = append(s.nextBatch, item) } var requests []*GetUtxoRequest for !s.pq.IsEmpty() && s.pq.Peek().BirthHeight == height { item := heap.Pop(&s.pq).(*GetUtxoRequest) requests = append(requests, item) } return requests }
go
func (s *UtxoScanner) dequeueAtHeight(height uint32) []*GetUtxoRequest { s.cv.L.Lock() defer s.cv.L.Unlock() // Take any requests that are too old to go in this batch and keep them for // the next batch. for !s.pq.IsEmpty() && s.pq.Peek().BirthHeight < height { item := heap.Pop(&s.pq).(*GetUtxoRequest) s.nextBatch = append(s.nextBatch, item) } var requests []*GetUtxoRequest for !s.pq.IsEmpty() && s.pq.Peek().BirthHeight == height { item := heap.Pop(&s.pq).(*GetUtxoRequest) requests = append(requests, item) } return requests }
[ "func", "(", "s", "*", "UtxoScanner", ")", "dequeueAtHeight", "(", "height", "uint32", ")", "[", "]", "*", "GetUtxoRequest", "{", "s", ".", "cv", ".", "L", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "cv", ".", "L", ".", "Unlock", "(", ")", "\n\n", "// Take any requests that are too old to go in this batch and keep them for", "// the next batch.", "for", "!", "s", ".", "pq", ".", "IsEmpty", "(", ")", "&&", "s", ".", "pq", ".", "Peek", "(", ")", ".", "BirthHeight", "<", "height", "{", "item", ":=", "heap", ".", "Pop", "(", "&", "s", ".", "pq", ")", ".", "(", "*", "GetUtxoRequest", ")", "\n", "s", ".", "nextBatch", "=", "append", "(", "s", ".", "nextBatch", ",", "item", ")", "\n", "}", "\n\n", "var", "requests", "[", "]", "*", "GetUtxoRequest", "\n", "for", "!", "s", ".", "pq", ".", "IsEmpty", "(", ")", "&&", "s", ".", "pq", ".", "Peek", "(", ")", ".", "BirthHeight", "==", "height", "{", "item", ":=", "heap", ".", "Pop", "(", "&", "s", ".", "pq", ")", ".", "(", "*", "GetUtxoRequest", ")", "\n", "requests", "=", "append", "(", "requests", ",", "item", ")", "\n", "}", "\n\n", "return", "requests", "\n", "}" ]
// dequeueAtHeight returns all GetUtxoRequests that have starting height of the // given height.
[ "dequeueAtHeight", "returns", "all", "GetUtxoRequests", "that", "have", "starting", "height", "of", "the", "given", "height", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/utxoscanner.go#L252-L270
train
lightninglabs/neutrino
utxoscanner.go
scanFromHeight
func (s *UtxoScanner) scanFromHeight(initHeight uint32) error { // Before beginning the scan, grab the best block stamp we know of, // which will serve as an initial estimate for the end height of the // scan. bestStamp, err := s.cfg.BestSnapshot() if err != nil { return err } var ( // startHeight and endHeight bound the range of the current // scan. If more blocks are found while a scan is running, // these values will be updated afterwards to scan for the new // blocks. startHeight = initHeight endHeight = uint32(bestStamp.Height) ) reporter := newBatchSpendReporter() scanToEnd: // Scan forward through the blockchain and look for any transactions that // might spend the given UTXOs. for height := startHeight; height <= endHeight; height++ { // Before beginning to scan this height, check to see if the // utxoscanner has been signaled to exit. select { case <-s.quit: return reporter.FailRemaining(ErrShuttingDown) default: } hash, err := s.cfg.GetBlockHash(int64(height)) if err != nil { return reporter.FailRemaining(err) } // If there are any new requests that can safely be added to this batch, // then try and fetch them. newReqs := s.dequeueAtHeight(height) // If an outpoint is created in this block, then fetch it regardless. // Otherwise check to see if the filter matches any of our watched // outpoints. fetch := len(newReqs) > 0 if !fetch { options := rescanOptions{ watchList: reporter.filterEntries, } match, err := s.cfg.BlockFilterMatches(&options, hash) if err != nil { return reporter.FailRemaining(err) } // If still no match is found, we have no reason to // fetch this block, and can continue to next height. if !match { continue } } // At this point, we've determined that we either (1) have new // requests which we need the block to scan for originating // UTXOs, or (2) the watchlist triggered a match against the // neutrino filter. Before fetching the block, check to see if // the utxoscanner has been signaled to exit so that we can exit // the rescan before performing an expensive operation. select { case <-s.quit: return reporter.FailRemaining(ErrShuttingDown) default: } log.Debugf("Fetching block height=%d hash=%s", height, hash) block, err := s.cfg.GetBlock(*hash) if err != nil { return reporter.FailRemaining(err) } // Check again to see if the utxoscanner has been signaled to exit. select { case <-s.quit: return reporter.FailRemaining(ErrShuttingDown) default: } log.Debugf("Processing block height=%d hash=%s", height, hash) reporter.ProcessBlock(block.MsgBlock(), newReqs, height) } // We've scanned up to the end height, now perform a check to see if we // still have any new blocks to process. If this is the first time // through, we might have a few blocks that were added since the // scan started. currStamp, err := s.cfg.BestSnapshot() if err != nil { return reporter.FailRemaining(err) } // If the returned height is higher, we still have more blocks to go. // Shift the start and end heights and continue scanning. if uint32(currStamp.Height) > endHeight { startHeight = endHeight + 1 endHeight = uint32(currStamp.Height) goto scanToEnd } reporter.NotifyUnspentAndUnfound() return nil }
go
func (s *UtxoScanner) scanFromHeight(initHeight uint32) error { // Before beginning the scan, grab the best block stamp we know of, // which will serve as an initial estimate for the end height of the // scan. bestStamp, err := s.cfg.BestSnapshot() if err != nil { return err } var ( // startHeight and endHeight bound the range of the current // scan. If more blocks are found while a scan is running, // these values will be updated afterwards to scan for the new // blocks. startHeight = initHeight endHeight = uint32(bestStamp.Height) ) reporter := newBatchSpendReporter() scanToEnd: // Scan forward through the blockchain and look for any transactions that // might spend the given UTXOs. for height := startHeight; height <= endHeight; height++ { // Before beginning to scan this height, check to see if the // utxoscanner has been signaled to exit. select { case <-s.quit: return reporter.FailRemaining(ErrShuttingDown) default: } hash, err := s.cfg.GetBlockHash(int64(height)) if err != nil { return reporter.FailRemaining(err) } // If there are any new requests that can safely be added to this batch, // then try and fetch them. newReqs := s.dequeueAtHeight(height) // If an outpoint is created in this block, then fetch it regardless. // Otherwise check to see if the filter matches any of our watched // outpoints. fetch := len(newReqs) > 0 if !fetch { options := rescanOptions{ watchList: reporter.filterEntries, } match, err := s.cfg.BlockFilterMatches(&options, hash) if err != nil { return reporter.FailRemaining(err) } // If still no match is found, we have no reason to // fetch this block, and can continue to next height. if !match { continue } } // At this point, we've determined that we either (1) have new // requests which we need the block to scan for originating // UTXOs, or (2) the watchlist triggered a match against the // neutrino filter. Before fetching the block, check to see if // the utxoscanner has been signaled to exit so that we can exit // the rescan before performing an expensive operation. select { case <-s.quit: return reporter.FailRemaining(ErrShuttingDown) default: } log.Debugf("Fetching block height=%d hash=%s", height, hash) block, err := s.cfg.GetBlock(*hash) if err != nil { return reporter.FailRemaining(err) } // Check again to see if the utxoscanner has been signaled to exit. select { case <-s.quit: return reporter.FailRemaining(ErrShuttingDown) default: } log.Debugf("Processing block height=%d hash=%s", height, hash) reporter.ProcessBlock(block.MsgBlock(), newReqs, height) } // We've scanned up to the end height, now perform a check to see if we // still have any new blocks to process. If this is the first time // through, we might have a few blocks that were added since the // scan started. currStamp, err := s.cfg.BestSnapshot() if err != nil { return reporter.FailRemaining(err) } // If the returned height is higher, we still have more blocks to go. // Shift the start and end heights and continue scanning. if uint32(currStamp.Height) > endHeight { startHeight = endHeight + 1 endHeight = uint32(currStamp.Height) goto scanToEnd } reporter.NotifyUnspentAndUnfound() return nil }
[ "func", "(", "s", "*", "UtxoScanner", ")", "scanFromHeight", "(", "initHeight", "uint32", ")", "error", "{", "// Before beginning the scan, grab the best block stamp we know of,", "// which will serve as an initial estimate for the end height of the", "// scan.", "bestStamp", ",", "err", ":=", "s", ".", "cfg", ".", "BestSnapshot", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "(", "// startHeight and endHeight bound the range of the current", "// scan. If more blocks are found while a scan is running,", "// these values will be updated afterwards to scan for the new", "// blocks.", "startHeight", "=", "initHeight", "\n", "endHeight", "=", "uint32", "(", "bestStamp", ".", "Height", ")", "\n", ")", "\n\n", "reporter", ":=", "newBatchSpendReporter", "(", ")", "\n\n", "scanToEnd", ":", "// Scan forward through the blockchain and look for any transactions that", "// might spend the given UTXOs.", "for", "height", ":=", "startHeight", ";", "height", "<=", "endHeight", ";", "height", "++", "{", "// Before beginning to scan this height, check to see if the", "// utxoscanner has been signaled to exit.", "select", "{", "case", "<-", "s", ".", "quit", ":", "return", "reporter", ".", "FailRemaining", "(", "ErrShuttingDown", ")", "\n", "default", ":", "}", "\n\n", "hash", ",", "err", ":=", "s", ".", "cfg", ".", "GetBlockHash", "(", "int64", "(", "height", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "reporter", ".", "FailRemaining", "(", "err", ")", "\n", "}", "\n\n", "// If there are any new requests that can safely be added to this batch,", "// then try and fetch them.", "newReqs", ":=", "s", ".", "dequeueAtHeight", "(", "height", ")", "\n\n", "// If an outpoint is created in this block, then fetch it regardless.", "// Otherwise check to see if the filter matches any of our watched", "// outpoints.", "fetch", ":=", "len", "(", "newReqs", ")", ">", "0", "\n", "if", "!", "fetch", "{", "options", ":=", "rescanOptions", "{", "watchList", ":", "reporter", ".", "filterEntries", ",", "}", "\n\n", "match", ",", "err", ":=", "s", ".", "cfg", ".", "BlockFilterMatches", "(", "&", "options", ",", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "reporter", ".", "FailRemaining", "(", "err", ")", "\n", "}", "\n\n", "// If still no match is found, we have no reason to", "// fetch this block, and can continue to next height.", "if", "!", "match", "{", "continue", "\n", "}", "\n", "}", "\n\n", "// At this point, we've determined that we either (1) have new", "// requests which we need the block to scan for originating", "// UTXOs, or (2) the watchlist triggered a match against the", "// neutrino filter. Before fetching the block, check to see if", "// the utxoscanner has been signaled to exit so that we can exit", "// the rescan before performing an expensive operation.", "select", "{", "case", "<-", "s", ".", "quit", ":", "return", "reporter", ".", "FailRemaining", "(", "ErrShuttingDown", ")", "\n", "default", ":", "}", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "height", ",", "hash", ")", "\n\n", "block", ",", "err", ":=", "s", ".", "cfg", ".", "GetBlock", "(", "*", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "reporter", ".", "FailRemaining", "(", "err", ")", "\n", "}", "\n\n", "// Check again to see if the utxoscanner has been signaled to exit.", "select", "{", "case", "<-", "s", ".", "quit", ":", "return", "reporter", ".", "FailRemaining", "(", "ErrShuttingDown", ")", "\n", "default", ":", "}", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "height", ",", "hash", ")", "\n\n", "reporter", ".", "ProcessBlock", "(", "block", ".", "MsgBlock", "(", ")", ",", "newReqs", ",", "height", ")", "\n", "}", "\n\n", "// We've scanned up to the end height, now perform a check to see if we", "// still have any new blocks to process. If this is the first time", "// through, we might have a few blocks that were added since the", "// scan started.", "currStamp", ",", "err", ":=", "s", ".", "cfg", ".", "BestSnapshot", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "reporter", ".", "FailRemaining", "(", "err", ")", "\n", "}", "\n\n", "// If the returned height is higher, we still have more blocks to go.", "// Shift the start and end heights and continue scanning.", "if", "uint32", "(", "currStamp", ".", "Height", ")", ">", "endHeight", "{", "startHeight", "=", "endHeight", "+", "1", "\n", "endHeight", "=", "uint32", "(", "currStamp", ".", "Height", ")", "\n", "goto", "scanToEnd", "\n", "}", "\n\n", "reporter", ".", "NotifyUnspentAndUnfound", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// scanFromHeight runs a single batch, pulling in any requests that get added // above the batch's last processed height. If there was an error, then return // the outstanding requests.
[ "scanFromHeight", "runs", "a", "single", "batch", "pulling", "in", "any", "requests", "that", "get", "added", "above", "the", "batch", "s", "last", "processed", "height", ".", "If", "there", "was", "an", "error", "then", "return", "the", "outstanding", "requests", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/utxoscanner.go#L275-L388
train
lightninglabs/neutrino
utxoscanner.go
Push
func (pq *GetUtxoRequestPQ) Push(x interface{}) { item := x.(*GetUtxoRequest) *pq = append(*pq, item) }
go
func (pq *GetUtxoRequestPQ) Push(x interface{}) { item := x.(*GetUtxoRequest) *pq = append(*pq, item) }
[ "func", "(", "pq", "*", "GetUtxoRequestPQ", ")", "Push", "(", "x", "interface", "{", "}", ")", "{", "item", ":=", "x", ".", "(", "*", "GetUtxoRequest", ")", "\n", "*", "pq", "=", "append", "(", "*", "pq", ",", "item", ")", "\n", "}" ]
// Push is called by the heap.Interface implementation to add an element to the // end of the backing store. The heap library will then maintain the heap // invariant.
[ "Push", "is", "called", "by", "the", "heap", ".", "Interface", "implementation", "to", "add", "an", "element", "to", "the", "end", "of", "the", "backing", "store", ".", "The", "heap", "library", "will", "then", "maintain", "the", "heap", "invariant", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/utxoscanner.go#L410-L413
train
lightninglabs/neutrino
utxoscanner.go
Pop
func (pq *GetUtxoRequestPQ) Pop() interface{} { old := *pq n := len(old) item := old[n-1] *pq = old[0 : n-1] return item }
go
func (pq *GetUtxoRequestPQ) Pop() interface{} { old := *pq n := len(old) item := old[n-1] *pq = old[0 : n-1] return item }
[ "func", "(", "pq", "*", "GetUtxoRequestPQ", ")", "Pop", "(", ")", "interface", "{", "}", "{", "old", ":=", "*", "pq", "\n", "n", ":=", "len", "(", "old", ")", "\n", "item", ":=", "old", "[", "n", "-", "1", "]", "\n", "*", "pq", "=", "old", "[", "0", ":", "n", "-", "1", "]", "\n", "return", "item", "\n", "}" ]
// Pop is called by the heap.Interface implementation to remove an element from // the end of the backing store. The heap library will then maintain the heap // invariant.
[ "Pop", "is", "called", "by", "the", "heap", ".", "Interface", "implementation", "to", "remove", "an", "element", "from", "the", "end", "of", "the", "backing", "store", ".", "The", "heap", "library", "will", "then", "maintain", "the", "heap", "invariant", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/utxoscanner.go#L423-L429
train
lightninglabs/neutrino
blockmanager.go
newBlockManager
func newBlockManager(s *ChainService, firstPeerSignal <-chan struct{}) (*blockManager, error) { targetTimespan := int64(s.chainParams.TargetTimespan / time.Second) targetTimePerBlock := int64(s.chainParams.TargetTimePerBlock / time.Second) adjustmentFactor := s.chainParams.RetargetAdjustmentFactor bm := blockManager{ server: s, peerChan: make(chan interface{}, MaxPeers*3), blockNtfnChan: make(chan blockntfns.BlockNtfn), blkHeaderProgressLogger: newBlockProgressLogger( "Processed", "block", log, ), fltrHeaderProgessLogger: newBlockProgressLogger( "Verified", "filter header", log, ), headerList: headerlist.NewBoundedMemoryChain( numMaxMemHeaders, ), reorgList: headerlist.NewBoundedMemoryChain( numMaxMemHeaders, ), quit: make(chan struct{}), blocksPerRetarget: int32(targetTimespan / targetTimePerBlock), minRetargetTimespan: targetTimespan / adjustmentFactor, maxRetargetTimespan: targetTimespan * adjustmentFactor, firstPeerSignal: firstPeerSignal, } // Next we'll create the two signals that goroutines will use to wait // on a particular header chain height before starting their normal // duties. bm.newHeadersSignal = sync.NewCond(&bm.newHeadersMtx) bm.newFilterHeadersSignal = sync.NewCond(&bm.newFilterHeadersMtx) // We fetch the genesis header to use for verifying the first received // interval. genesisHeader, err := s.RegFilterHeaders.FetchHeaderByHeight(0) if err != nil { return nil, err } bm.genesisHeader = *genesisHeader // Initialize the next checkpoint based on the current height. header, height, err := s.BlockHeaders.ChainTip() if err != nil { return nil, err } bm.nextCheckpoint = bm.findNextHeaderCheckpoint(int32(height)) bm.headerList.ResetHeaderState(headerlist.Node{ Header: *header, Height: int32(height), }) bm.headerTip = height bm.headerTipHash = header.BlockHash() // Finally, we'll set the filter header tip so any goroutines waiting // on the condition obtain the correct initial state. _, bm.filterHeaderTip, err = s.RegFilterHeaders.ChainTip() if err != nil { return nil, err } // We must also ensure the the filter header tip hash is set to the // block hash at the filter tip height. fh, err := s.BlockHeaders.FetchHeaderByHeight(bm.filterHeaderTip) if err != nil { return nil, err } bm.filterHeaderTipHash = fh.BlockHash() return &bm, nil }
go
func newBlockManager(s *ChainService, firstPeerSignal <-chan struct{}) (*blockManager, error) { targetTimespan := int64(s.chainParams.TargetTimespan / time.Second) targetTimePerBlock := int64(s.chainParams.TargetTimePerBlock / time.Second) adjustmentFactor := s.chainParams.RetargetAdjustmentFactor bm := blockManager{ server: s, peerChan: make(chan interface{}, MaxPeers*3), blockNtfnChan: make(chan blockntfns.BlockNtfn), blkHeaderProgressLogger: newBlockProgressLogger( "Processed", "block", log, ), fltrHeaderProgessLogger: newBlockProgressLogger( "Verified", "filter header", log, ), headerList: headerlist.NewBoundedMemoryChain( numMaxMemHeaders, ), reorgList: headerlist.NewBoundedMemoryChain( numMaxMemHeaders, ), quit: make(chan struct{}), blocksPerRetarget: int32(targetTimespan / targetTimePerBlock), minRetargetTimespan: targetTimespan / adjustmentFactor, maxRetargetTimespan: targetTimespan * adjustmentFactor, firstPeerSignal: firstPeerSignal, } // Next we'll create the two signals that goroutines will use to wait // on a particular header chain height before starting their normal // duties. bm.newHeadersSignal = sync.NewCond(&bm.newHeadersMtx) bm.newFilterHeadersSignal = sync.NewCond(&bm.newFilterHeadersMtx) // We fetch the genesis header to use for verifying the first received // interval. genesisHeader, err := s.RegFilterHeaders.FetchHeaderByHeight(0) if err != nil { return nil, err } bm.genesisHeader = *genesisHeader // Initialize the next checkpoint based on the current height. header, height, err := s.BlockHeaders.ChainTip() if err != nil { return nil, err } bm.nextCheckpoint = bm.findNextHeaderCheckpoint(int32(height)) bm.headerList.ResetHeaderState(headerlist.Node{ Header: *header, Height: int32(height), }) bm.headerTip = height bm.headerTipHash = header.BlockHash() // Finally, we'll set the filter header tip so any goroutines waiting // on the condition obtain the correct initial state. _, bm.filterHeaderTip, err = s.RegFilterHeaders.ChainTip() if err != nil { return nil, err } // We must also ensure the the filter header tip hash is set to the // block hash at the filter tip height. fh, err := s.BlockHeaders.FetchHeaderByHeight(bm.filterHeaderTip) if err != nil { return nil, err } bm.filterHeaderTipHash = fh.BlockHash() return &bm, nil }
[ "func", "newBlockManager", "(", "s", "*", "ChainService", ",", "firstPeerSignal", "<-", "chan", "struct", "{", "}", ")", "(", "*", "blockManager", ",", "error", ")", "{", "targetTimespan", ":=", "int64", "(", "s", ".", "chainParams", ".", "TargetTimespan", "/", "time", ".", "Second", ")", "\n", "targetTimePerBlock", ":=", "int64", "(", "s", ".", "chainParams", ".", "TargetTimePerBlock", "/", "time", ".", "Second", ")", "\n", "adjustmentFactor", ":=", "s", ".", "chainParams", ".", "RetargetAdjustmentFactor", "\n\n", "bm", ":=", "blockManager", "{", "server", ":", "s", ",", "peerChan", ":", "make", "(", "chan", "interface", "{", "}", ",", "MaxPeers", "*", "3", ")", ",", "blockNtfnChan", ":", "make", "(", "chan", "blockntfns", ".", "BlockNtfn", ")", ",", "blkHeaderProgressLogger", ":", "newBlockProgressLogger", "(", "\"", "\"", ",", "\"", "\"", ",", "log", ",", ")", ",", "fltrHeaderProgessLogger", ":", "newBlockProgressLogger", "(", "\"", "\"", ",", "\"", "\"", ",", "log", ",", ")", ",", "headerList", ":", "headerlist", ".", "NewBoundedMemoryChain", "(", "numMaxMemHeaders", ",", ")", ",", "reorgList", ":", "headerlist", ".", "NewBoundedMemoryChain", "(", "numMaxMemHeaders", ",", ")", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "blocksPerRetarget", ":", "int32", "(", "targetTimespan", "/", "targetTimePerBlock", ")", ",", "minRetargetTimespan", ":", "targetTimespan", "/", "adjustmentFactor", ",", "maxRetargetTimespan", ":", "targetTimespan", "*", "adjustmentFactor", ",", "firstPeerSignal", ":", "firstPeerSignal", ",", "}", "\n\n", "// Next we'll create the two signals that goroutines will use to wait", "// on a particular header chain height before starting their normal", "// duties.", "bm", ".", "newHeadersSignal", "=", "sync", ".", "NewCond", "(", "&", "bm", ".", "newHeadersMtx", ")", "\n", "bm", ".", "newFilterHeadersSignal", "=", "sync", ".", "NewCond", "(", "&", "bm", ".", "newFilterHeadersMtx", ")", "\n\n", "// We fetch the genesis header to use for verifying the first received", "// interval.", "genesisHeader", ",", "err", ":=", "s", ".", "RegFilterHeaders", ".", "FetchHeaderByHeight", "(", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "bm", ".", "genesisHeader", "=", "*", "genesisHeader", "\n\n", "// Initialize the next checkpoint based on the current height.", "header", ",", "height", ",", "err", ":=", "s", ".", "BlockHeaders", ".", "ChainTip", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "bm", ".", "nextCheckpoint", "=", "bm", ".", "findNextHeaderCheckpoint", "(", "int32", "(", "height", ")", ")", "\n", "bm", ".", "headerList", ".", "ResetHeaderState", "(", "headerlist", ".", "Node", "{", "Header", ":", "*", "header", ",", "Height", ":", "int32", "(", "height", ")", ",", "}", ")", "\n", "bm", ".", "headerTip", "=", "height", "\n", "bm", ".", "headerTipHash", "=", "header", ".", "BlockHash", "(", ")", "\n\n", "// Finally, we'll set the filter header tip so any goroutines waiting", "// on the condition obtain the correct initial state.", "_", ",", "bm", ".", "filterHeaderTip", ",", "err", "=", "s", ".", "RegFilterHeaders", ".", "ChainTip", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// We must also ensure the the filter header tip hash is set to the", "// block hash at the filter tip height.", "fh", ",", "err", ":=", "s", ".", "BlockHeaders", ".", "FetchHeaderByHeight", "(", "bm", ".", "filterHeaderTip", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "bm", ".", "filterHeaderTipHash", "=", "fh", ".", "BlockHash", "(", ")", "\n\n", "return", "&", "bm", ",", "nil", "\n", "}" ]
// newBlockManager returns a new bitcoin block manager. Use Start to begin // processing asynchronous block and inv updates.
[ "newBlockManager", "returns", "a", "new", "bitcoin", "block", "manager", ".", "Use", "Start", "to", "begin", "processing", "asynchronous", "block", "and", "inv", "updates", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L191-L264
train
lightninglabs/neutrino
blockmanager.go
Stop
func (b *blockManager) Stop() error { if atomic.AddInt32(&b.shutdown, 1) != 1 { log.Warnf("Block manager is already in the process of " + "shutting down") return nil } // We'll send out update signals before the quit to ensure that any // goroutines waiting on them will properly exit. done := make(chan struct{}) go func() { ticker := time.NewTicker(time.Millisecond * 50) defer ticker.Stop() for { select { case <-done: return case <-ticker.C: } b.newHeadersSignal.Broadcast() b.newFilterHeadersSignal.Broadcast() } }() log.Infof("Block manager shutting down") close(b.quit) b.wg.Wait() close(done) return nil }
go
func (b *blockManager) Stop() error { if atomic.AddInt32(&b.shutdown, 1) != 1 { log.Warnf("Block manager is already in the process of " + "shutting down") return nil } // We'll send out update signals before the quit to ensure that any // goroutines waiting on them will properly exit. done := make(chan struct{}) go func() { ticker := time.NewTicker(time.Millisecond * 50) defer ticker.Stop() for { select { case <-done: return case <-ticker.C: } b.newHeadersSignal.Broadcast() b.newFilterHeadersSignal.Broadcast() } }() log.Infof("Block manager shutting down") close(b.quit) b.wg.Wait() close(done) return nil }
[ "func", "(", "b", "*", "blockManager", ")", "Stop", "(", ")", "error", "{", "if", "atomic", ".", "AddInt32", "(", "&", "b", ".", "shutdown", ",", "1", ")", "!=", "1", "{", "log", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// We'll send out update signals before the quit to ensure that any", "// goroutines waiting on them will properly exit.", "done", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", ")", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "time", ".", "Millisecond", "*", "50", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "done", ":", "return", "\n", "case", "<-", "ticker", ".", "C", ":", "}", "\n\n", "b", ".", "newHeadersSignal", ".", "Broadcast", "(", ")", "\n", "b", ".", "newFilterHeadersSignal", ".", "Broadcast", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "close", "(", "b", ".", "quit", ")", "\n", "b", ".", "wg", ".", "Wait", "(", ")", "\n\n", "close", "(", "done", ")", "\n", "return", "nil", "\n", "}" ]
// Stop gracefully shuts down the block manager by stopping all asynchronous // handlers and waiting for them to finish.
[ "Stop", "gracefully", "shuts", "down", "the", "block", "manager", "by", "stopping", "all", "asynchronous", "handlers", "and", "waiting", "for", "them", "to", "finish", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L296-L328
train
lightninglabs/neutrino
blockmanager.go
NewPeer
func (b *blockManager) NewPeer(sp *ServerPeer) { // Ignore if we are shutting down. if atomic.LoadInt32(&b.shutdown) != 0 { return } select { case b.peerChan <- &newPeerMsg{peer: sp}: case <-b.quit: return } }
go
func (b *blockManager) NewPeer(sp *ServerPeer) { // Ignore if we are shutting down. if atomic.LoadInt32(&b.shutdown) != 0 { return } select { case b.peerChan <- &newPeerMsg{peer: sp}: case <-b.quit: return } }
[ "func", "(", "b", "*", "blockManager", ")", "NewPeer", "(", "sp", "*", "ServerPeer", ")", "{", "// Ignore if we are shutting down.", "if", "atomic", ".", "LoadInt32", "(", "&", "b", ".", "shutdown", ")", "!=", "0", "{", "return", "\n", "}", "\n\n", "select", "{", "case", "b", ".", "peerChan", "<-", "&", "newPeerMsg", "{", "peer", ":", "sp", "}", ":", "case", "<-", "b", ".", "quit", ":", "return", "\n", "}", "\n", "}" ]
// NewPeer informs the block manager of a newly active peer.
[ "NewPeer", "informs", "the", "block", "manager", "of", "a", "newly", "active", "peer", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L331-L342
train
lightninglabs/neutrino
blockmanager.go
writeCFHeadersMsg
func (b *blockManager) writeCFHeadersMsg(msg *wire.MsgCFHeaders, store *headerfs.FilterHeaderStore) (*chainhash.Hash, error) { b.newFilterHeadersMtx.Lock() defer b.newFilterHeadersMtx.Unlock() // Check that the PrevFilterHeader is the same as the last stored so we // can prevent misalignment. tip, tipHeight, err := store.ChainTip() if err != nil { return nil, err } if *tip != msg.PrevFilterHeader { return nil, fmt.Errorf("attempt to write cfheaders out of "+ "order! Tip=%v (height=%v), prev_hash=%v.", *tip, tipHeight, msg.PrevFilterHeader) } // Cycle through the headers and compute each header based on the prev // header and the filter hash from the cfheaders response entries. lastHeader := msg.PrevFilterHeader headerBatch := make([]headerfs.FilterHeader, 0, wire.CFCheckptInterval) for _, hash := range msg.FilterHashes { // header = dsha256(filterHash || prevHeader) lastHeader = chainhash.DoubleHashH( append(hash[:], lastHeader[:]...), ) headerBatch = append(headerBatch, headerfs.FilterHeader{ FilterHash: lastHeader, }) } numHeaders := len(headerBatch) // We'll now query for the set of block headers which match each of // these filters headers in their corresponding chains. Our query will // return the headers for the entire checkpoint interval ending at the // designated stop hash. blockHeaders := b.server.BlockHeaders matchingBlockHeaders, startHeight, err := blockHeaders.FetchHeaderAncestors( uint32(numHeaders-1), &msg.StopHash, ) if err != nil { return nil, err } // The final height in our range will be offset to the end of this // particular checkpoint interval. lastHeight := startHeight + uint32(numHeaders) - 1 lastBlockHeader := matchingBlockHeaders[numHeaders-1] lastHash := lastBlockHeader.BlockHash() // We only need to set the height and hash of the very last filter // header in the range to ensure that the index properly updates the // tip of the chain. headerBatch[numHeaders-1].HeaderHash = lastHash headerBatch[numHeaders-1].Height = lastHeight log.Debugf("Writing filter headers up to height=%v, hash=%v, "+ "new_tip=%v", lastHeight, lastHash, lastHeader) // Write the header batch. err = store.WriteHeaders(headerBatch...) if err != nil { return nil, err } // Notify subscribers, and also update the filter header progress // logger at the same time. for i, header := range matchingBlockHeaders { header := header headerHeight := startHeight + uint32(i) b.fltrHeaderProgessLogger.LogBlockHeight( header.Timestamp, int32(headerHeight), ) b.onBlockConnected(header, headerHeight) } // We'll also set the new header tip and notify any peers that the tip // has changed as well. Unlike the set of notifications above, this is // for sub-system that only need to know the height has changed rather // than know each new header that's been added to the tip. b.filterHeaderTip = lastHeight b.filterHeaderTipHash = lastHash b.newFilterHeadersSignal.Broadcast() return &lastHeader, nil }
go
func (b *blockManager) writeCFHeadersMsg(msg *wire.MsgCFHeaders, store *headerfs.FilterHeaderStore) (*chainhash.Hash, error) { b.newFilterHeadersMtx.Lock() defer b.newFilterHeadersMtx.Unlock() // Check that the PrevFilterHeader is the same as the last stored so we // can prevent misalignment. tip, tipHeight, err := store.ChainTip() if err != nil { return nil, err } if *tip != msg.PrevFilterHeader { return nil, fmt.Errorf("attempt to write cfheaders out of "+ "order! Tip=%v (height=%v), prev_hash=%v.", *tip, tipHeight, msg.PrevFilterHeader) } // Cycle through the headers and compute each header based on the prev // header and the filter hash from the cfheaders response entries. lastHeader := msg.PrevFilterHeader headerBatch := make([]headerfs.FilterHeader, 0, wire.CFCheckptInterval) for _, hash := range msg.FilterHashes { // header = dsha256(filterHash || prevHeader) lastHeader = chainhash.DoubleHashH( append(hash[:], lastHeader[:]...), ) headerBatch = append(headerBatch, headerfs.FilterHeader{ FilterHash: lastHeader, }) } numHeaders := len(headerBatch) // We'll now query for the set of block headers which match each of // these filters headers in their corresponding chains. Our query will // return the headers for the entire checkpoint interval ending at the // designated stop hash. blockHeaders := b.server.BlockHeaders matchingBlockHeaders, startHeight, err := blockHeaders.FetchHeaderAncestors( uint32(numHeaders-1), &msg.StopHash, ) if err != nil { return nil, err } // The final height in our range will be offset to the end of this // particular checkpoint interval. lastHeight := startHeight + uint32(numHeaders) - 1 lastBlockHeader := matchingBlockHeaders[numHeaders-1] lastHash := lastBlockHeader.BlockHash() // We only need to set the height and hash of the very last filter // header in the range to ensure that the index properly updates the // tip of the chain. headerBatch[numHeaders-1].HeaderHash = lastHash headerBatch[numHeaders-1].Height = lastHeight log.Debugf("Writing filter headers up to height=%v, hash=%v, "+ "new_tip=%v", lastHeight, lastHash, lastHeader) // Write the header batch. err = store.WriteHeaders(headerBatch...) if err != nil { return nil, err } // Notify subscribers, and also update the filter header progress // logger at the same time. for i, header := range matchingBlockHeaders { header := header headerHeight := startHeight + uint32(i) b.fltrHeaderProgessLogger.LogBlockHeight( header.Timestamp, int32(headerHeight), ) b.onBlockConnected(header, headerHeight) } // We'll also set the new header tip and notify any peers that the tip // has changed as well. Unlike the set of notifications above, this is // for sub-system that only need to know the height has changed rather // than know each new header that's been added to the tip. b.filterHeaderTip = lastHeight b.filterHeaderTipHash = lastHash b.newFilterHeadersSignal.Broadcast() return &lastHeader, nil }
[ "func", "(", "b", "*", "blockManager", ")", "writeCFHeadersMsg", "(", "msg", "*", "wire", ".", "MsgCFHeaders", ",", "store", "*", "headerfs", ".", "FilterHeaderStore", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "b", ".", "newFilterHeadersMtx", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "newFilterHeadersMtx", ".", "Unlock", "(", ")", "\n\n", "// Check that the PrevFilterHeader is the same as the last stored so we", "// can prevent misalignment.", "tip", ",", "tipHeight", ",", "err", ":=", "store", ".", "ChainTip", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "*", "tip", "!=", "msg", ".", "PrevFilterHeader", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "*", "tip", ",", "tipHeight", ",", "msg", ".", "PrevFilterHeader", ")", "\n", "}", "\n\n", "// Cycle through the headers and compute each header based on the prev", "// header and the filter hash from the cfheaders response entries.", "lastHeader", ":=", "msg", ".", "PrevFilterHeader", "\n", "headerBatch", ":=", "make", "(", "[", "]", "headerfs", ".", "FilterHeader", ",", "0", ",", "wire", ".", "CFCheckptInterval", ")", "\n", "for", "_", ",", "hash", ":=", "range", "msg", ".", "FilterHashes", "{", "// header = dsha256(filterHash || prevHeader)", "lastHeader", "=", "chainhash", ".", "DoubleHashH", "(", "append", "(", "hash", "[", ":", "]", ",", "lastHeader", "[", ":", "]", "...", ")", ",", ")", "\n\n", "headerBatch", "=", "append", "(", "headerBatch", ",", "headerfs", ".", "FilterHeader", "{", "FilterHash", ":", "lastHeader", ",", "}", ")", "\n", "}", "\n\n", "numHeaders", ":=", "len", "(", "headerBatch", ")", "\n\n", "// We'll now query for the set of block headers which match each of", "// these filters headers in their corresponding chains. Our query will", "// return the headers for the entire checkpoint interval ending at the", "// designated stop hash.", "blockHeaders", ":=", "b", ".", "server", ".", "BlockHeaders", "\n", "matchingBlockHeaders", ",", "startHeight", ",", "err", ":=", "blockHeaders", ".", "FetchHeaderAncestors", "(", "uint32", "(", "numHeaders", "-", "1", ")", ",", "&", "msg", ".", "StopHash", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// The final height in our range will be offset to the end of this", "// particular checkpoint interval.", "lastHeight", ":=", "startHeight", "+", "uint32", "(", "numHeaders", ")", "-", "1", "\n", "lastBlockHeader", ":=", "matchingBlockHeaders", "[", "numHeaders", "-", "1", "]", "\n", "lastHash", ":=", "lastBlockHeader", ".", "BlockHash", "(", ")", "\n\n", "// We only need to set the height and hash of the very last filter", "// header in the range to ensure that the index properly updates the", "// tip of the chain.", "headerBatch", "[", "numHeaders", "-", "1", "]", ".", "HeaderHash", "=", "lastHash", "\n", "headerBatch", "[", "numHeaders", "-", "1", "]", ".", "Height", "=", "lastHeight", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", "+", "\"", "\"", ",", "lastHeight", ",", "lastHash", ",", "lastHeader", ")", "\n\n", "// Write the header batch.", "err", "=", "store", ".", "WriteHeaders", "(", "headerBatch", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Notify subscribers, and also update the filter header progress", "// logger at the same time.", "for", "i", ",", "header", ":=", "range", "matchingBlockHeaders", "{", "header", ":=", "header", "\n\n", "headerHeight", ":=", "startHeight", "+", "uint32", "(", "i", ")", "\n", "b", ".", "fltrHeaderProgessLogger", ".", "LogBlockHeight", "(", "header", ".", "Timestamp", ",", "int32", "(", "headerHeight", ")", ",", ")", "\n\n", "b", ".", "onBlockConnected", "(", "header", ",", "headerHeight", ")", "\n", "}", "\n\n", "// We'll also set the new header tip and notify any peers that the tip", "// has changed as well. Unlike the set of notifications above, this is", "// for sub-system that only need to know the height has changed rather", "// than know each new header that's been added to the tip.", "b", ".", "filterHeaderTip", "=", "lastHeight", "\n", "b", ".", "filterHeaderTipHash", "=", "lastHash", "\n", "b", ".", "newFilterHeadersSignal", ".", "Broadcast", "(", ")", "\n\n", "return", "&", "lastHeader", ",", "nil", "\n", "}" ]
// writeCFHeadersMsg writes a cfheaders message to the specified store. It // assumes that everything is being written in order. The hints are required to // store the correct block heights for the filters. We also return final // constructed cfheader in this range as this lets callers populate the prev // filter header field in the next message range before writing to disk.
[ "writeCFHeadersMsg", "writes", "a", "cfheaders", "message", "to", "the", "specified", "store", ".", "It", "assumes", "that", "everything", "is", "being", "written", "in", "order", ".", "The", "hints", "are", "required", "to", "store", "the", "correct", "block", "heights", "for", "the", "filters", ".", "We", "also", "return", "final", "constructed", "cfheader", "in", "this", "range", "as", "this", "lets", "callers", "populate", "the", "prev", "filter", "header", "field", "in", "the", "next", "message", "range", "before", "writing", "to", "disk", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1079-L1169
train
lightninglabs/neutrino
blockmanager.go
minCheckpointHeight
func minCheckpointHeight(checkpoints map[string][]*chainhash.Hash) uint32 { // If the map is empty, return 0 immediately. if len(checkpoints) == 0 { return 0 } // Otherwise return the length of the shortest one. minHeight := uint32(math.MaxUint32) for _, cps := range checkpoints { height := uint32(len(cps) * wire.CFCheckptInterval) if height < minHeight { minHeight = height } } return minHeight }
go
func minCheckpointHeight(checkpoints map[string][]*chainhash.Hash) uint32 { // If the map is empty, return 0 immediately. if len(checkpoints) == 0 { return 0 } // Otherwise return the length of the shortest one. minHeight := uint32(math.MaxUint32) for _, cps := range checkpoints { height := uint32(len(cps) * wire.CFCheckptInterval) if height < minHeight { minHeight = height } } return minHeight }
[ "func", "minCheckpointHeight", "(", "checkpoints", "map", "[", "string", "]", "[", "]", "*", "chainhash", ".", "Hash", ")", "uint32", "{", "// If the map is empty, return 0 immediately.", "if", "len", "(", "checkpoints", ")", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "// Otherwise return the length of the shortest one.", "minHeight", ":=", "uint32", "(", "math", ".", "MaxUint32", ")", "\n", "for", "_", ",", "cps", ":=", "range", "checkpoints", "{", "height", ":=", "uint32", "(", "len", "(", "cps", ")", "*", "wire", ".", "CFCheckptInterval", ")", "\n", "if", "height", "<", "minHeight", "{", "minHeight", "=", "height", "\n", "}", "\n", "}", "\n", "return", "minHeight", "\n", "}" ]
// minCheckpointHeight returns the height of the last filter checkpoint for the // shortest checkpoint list among the given lists.
[ "minCheckpointHeight", "returns", "the", "height", "of", "the", "last", "filter", "checkpoint", "for", "the", "shortest", "checkpoint", "list", "among", "the", "given", "lists", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1173-L1188
train
lightninglabs/neutrino
blockmanager.go
verifyCheckpoint
func verifyCheckpoint(prevCheckpoint, nextCheckpoint *chainhash.Hash, cfheaders *wire.MsgCFHeaders) bool { if *prevCheckpoint != cfheaders.PrevFilterHeader { return false } lastHeader := cfheaders.PrevFilterHeader for _, hash := range cfheaders.FilterHashes { lastHeader = chainhash.DoubleHashH( append(hash[:], lastHeader[:]...), ) } return lastHeader == *nextCheckpoint }
go
func verifyCheckpoint(prevCheckpoint, nextCheckpoint *chainhash.Hash, cfheaders *wire.MsgCFHeaders) bool { if *prevCheckpoint != cfheaders.PrevFilterHeader { return false } lastHeader := cfheaders.PrevFilterHeader for _, hash := range cfheaders.FilterHashes { lastHeader = chainhash.DoubleHashH( append(hash[:], lastHeader[:]...), ) } return lastHeader == *nextCheckpoint }
[ "func", "verifyCheckpoint", "(", "prevCheckpoint", ",", "nextCheckpoint", "*", "chainhash", ".", "Hash", ",", "cfheaders", "*", "wire", ".", "MsgCFHeaders", ")", "bool", "{", "if", "*", "prevCheckpoint", "!=", "cfheaders", ".", "PrevFilterHeader", "{", "return", "false", "\n", "}", "\n\n", "lastHeader", ":=", "cfheaders", ".", "PrevFilterHeader", "\n", "for", "_", ",", "hash", ":=", "range", "cfheaders", ".", "FilterHashes", "{", "lastHeader", "=", "chainhash", ".", "DoubleHashH", "(", "append", "(", "hash", "[", ":", "]", ",", "lastHeader", "[", ":", "]", "...", ")", ",", ")", "\n", "}", "\n\n", "return", "lastHeader", "==", "*", "nextCheckpoint", "\n", "}" ]
// verifyHeaderCheckpoint verifies that a CFHeaders message matches the passed // checkpoints. It assumes everything else has been checked, including filter // type and stop hash matches, and returns true if matching and false if not.
[ "verifyHeaderCheckpoint", "verifies", "that", "a", "CFHeaders", "message", "matches", "the", "passed", "checkpoints", ".", "It", "assumes", "everything", "else", "has", "been", "checked", "including", "filter", "type", "and", "stop", "hash", "matches", "and", "returns", "true", "if", "matching", "and", "false", "if", "not", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1193-L1208
train
lightninglabs/neutrino
blockmanager.go
checkForCFHeaderMismatch
func checkForCFHeaderMismatch(headers map[string]*wire.MsgCFHeaders, idx int) bool { // First, see if we have a mismatch. hash := zeroHash for _, msg := range headers { if len(msg.FilterHashes) <= idx { continue } if hash == zeroHash { hash = *msg.FilterHashes[idx] continue } if hash != *msg.FilterHashes[idx] { // We've found a mismatch! return true } } return false }
go
func checkForCFHeaderMismatch(headers map[string]*wire.MsgCFHeaders, idx int) bool { // First, see if we have a mismatch. hash := zeroHash for _, msg := range headers { if len(msg.FilterHashes) <= idx { continue } if hash == zeroHash { hash = *msg.FilterHashes[idx] continue } if hash != *msg.FilterHashes[idx] { // We've found a mismatch! return true } } return false }
[ "func", "checkForCFHeaderMismatch", "(", "headers", "map", "[", "string", "]", "*", "wire", ".", "MsgCFHeaders", ",", "idx", "int", ")", "bool", "{", "// First, see if we have a mismatch.", "hash", ":=", "zeroHash", "\n", "for", "_", ",", "msg", ":=", "range", "headers", "{", "if", "len", "(", "msg", ".", "FilterHashes", ")", "<=", "idx", "{", "continue", "\n", "}", "\n\n", "if", "hash", "==", "zeroHash", "{", "hash", "=", "*", "msg", ".", "FilterHashes", "[", "idx", "]", "\n", "continue", "\n", "}", "\n\n", "if", "hash", "!=", "*", "msg", ".", "FilterHashes", "[", "idx", "]", "{", "// We've found a mismatch!", "return", "true", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// checkForCFHeaderMismatch checks all peers' responses at a specific position // and detects a mismatch. It returns true if a mismatch has occurred.
[ "checkForCFHeaderMismatch", "checks", "all", "peers", "responses", "at", "a", "specific", "position", "and", "detects", "a", "mismatch", ".", "It", "returns", "true", "if", "a", "mismatch", "has", "occurred", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1356-L1378
train
lightninglabs/neutrino
blockmanager.go
resolveCFHeaderMismatch
func resolveCFHeaderMismatch(block *wire.MsgBlock, fType wire.FilterType, filtersFromPeers map[string]*gcs.Filter) ([]string, error) { badPeers := make(map[string]struct{}) blockHash := block.BlockHash() filterKey := builder.DeriveKey(&blockHash) log.Infof("Attempting to pinpoint mismatch in cfheaders for block=%v", block.Header.BlockHash()) // Based on the type of filter, our verification algorithm will differ. switch fType { // With the current set of items that we can fetch from the p2p // network, we're forced to only verify what we can at this point. So // we'll just ensure that each of the filters returned // // TODO(roasbeef): update after BLOCK_WITH_PREV_OUTS is a thing case wire.GCSFilterRegular: // We'll now run through each peer and ensure that each output // script is included in the filter that they responded with to // our query. for peerAddr, filter := range filtersFromPeers { peerVerification: // We'll ensure that all the filters include every // output script within the block. // // TODO(roasbeef): eventually just do a comparison // against decompressed filters for _, tx := range block.Transactions { for _, txOut := range tx.TxOut { switch { // If the script itself is blank, then // we'll skip this as it doesn't // contain any useful information. case len(txOut.PkScript) == 0: continue // We'll also skip any OP_RETURN // scripts as well since we don't index // these in order to avoid a circular // dependency. case txOut.PkScript[0] == txscript.OP_RETURN: continue } match, err := filter.Match( filterKey, txOut.PkScript, ) if err != nil { // If we're unable to query // this filter, then we'll skip // this peer all together. continue peerVerification } if match { continue } // If this filter doesn't match, then // we'll mark this peer as bad and move // on to the next peer. badPeers[peerAddr] = struct{}{} continue peerVerification } } } default: return nil, fmt.Errorf("unknown filter: %v", fType) } // TODO: We can add an after-the-fact countermeasure here against // eclipse attacks. If the checkpoints don't match the store, we can // check whether the store or the checkpoints we got from the network // are correct. // With the set of bad peers known, we'll collect a slice of all the // faulty peers. invalidPeers := make([]string, 0, len(badPeers)) for peer := range badPeers { invalidPeers = append(invalidPeers, peer) } return invalidPeers, nil }
go
func resolveCFHeaderMismatch(block *wire.MsgBlock, fType wire.FilterType, filtersFromPeers map[string]*gcs.Filter) ([]string, error) { badPeers := make(map[string]struct{}) blockHash := block.BlockHash() filterKey := builder.DeriveKey(&blockHash) log.Infof("Attempting to pinpoint mismatch in cfheaders for block=%v", block.Header.BlockHash()) // Based on the type of filter, our verification algorithm will differ. switch fType { // With the current set of items that we can fetch from the p2p // network, we're forced to only verify what we can at this point. So // we'll just ensure that each of the filters returned // // TODO(roasbeef): update after BLOCK_WITH_PREV_OUTS is a thing case wire.GCSFilterRegular: // We'll now run through each peer and ensure that each output // script is included in the filter that they responded with to // our query. for peerAddr, filter := range filtersFromPeers { peerVerification: // We'll ensure that all the filters include every // output script within the block. // // TODO(roasbeef): eventually just do a comparison // against decompressed filters for _, tx := range block.Transactions { for _, txOut := range tx.TxOut { switch { // If the script itself is blank, then // we'll skip this as it doesn't // contain any useful information. case len(txOut.PkScript) == 0: continue // We'll also skip any OP_RETURN // scripts as well since we don't index // these in order to avoid a circular // dependency. case txOut.PkScript[0] == txscript.OP_RETURN: continue } match, err := filter.Match( filterKey, txOut.PkScript, ) if err != nil { // If we're unable to query // this filter, then we'll skip // this peer all together. continue peerVerification } if match { continue } // If this filter doesn't match, then // we'll mark this peer as bad and move // on to the next peer. badPeers[peerAddr] = struct{}{} continue peerVerification } } } default: return nil, fmt.Errorf("unknown filter: %v", fType) } // TODO: We can add an after-the-fact countermeasure here against // eclipse attacks. If the checkpoints don't match the store, we can // check whether the store or the checkpoints we got from the network // are correct. // With the set of bad peers known, we'll collect a slice of all the // faulty peers. invalidPeers := make([]string, 0, len(badPeers)) for peer := range badPeers { invalidPeers = append(invalidPeers, peer) } return invalidPeers, nil }
[ "func", "resolveCFHeaderMismatch", "(", "block", "*", "wire", ".", "MsgBlock", ",", "fType", "wire", ".", "FilterType", ",", "filtersFromPeers", "map", "[", "string", "]", "*", "gcs", ".", "Filter", ")", "(", "[", "]", "string", ",", "error", ")", "{", "badPeers", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n\n", "blockHash", ":=", "block", ".", "BlockHash", "(", ")", "\n", "filterKey", ":=", "builder", ".", "DeriveKey", "(", "&", "blockHash", ")", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "block", ".", "Header", ".", "BlockHash", "(", ")", ")", "\n\n", "// Based on the type of filter, our verification algorithm will differ.", "switch", "fType", "{", "// With the current set of items that we can fetch from the p2p", "// network, we're forced to only verify what we can at this point. So", "// we'll just ensure that each of the filters returned", "//", "// TODO(roasbeef): update after BLOCK_WITH_PREV_OUTS is a thing", "case", "wire", ".", "GCSFilterRegular", ":", "// We'll now run through each peer and ensure that each output", "// script is included in the filter that they responded with to", "// our query.", "for", "peerAddr", ",", "filter", ":=", "range", "filtersFromPeers", "{", "peerVerification", ":", "// We'll ensure that all the filters include every", "// output script within the block.", "//", "// TODO(roasbeef): eventually just do a comparison", "// against decompressed filters", "for", "_", ",", "tx", ":=", "range", "block", ".", "Transactions", "{", "for", "_", ",", "txOut", ":=", "range", "tx", ".", "TxOut", "{", "switch", "{", "// If the script itself is blank, then", "// we'll skip this as it doesn't", "// contain any useful information.", "case", "len", "(", "txOut", ".", "PkScript", ")", "==", "0", ":", "continue", "\n\n", "// We'll also skip any OP_RETURN", "// scripts as well since we don't index", "// these in order to avoid a circular", "// dependency.", "case", "txOut", ".", "PkScript", "[", "0", "]", "==", "txscript", ".", "OP_RETURN", ":", "continue", "\n", "}", "\n\n", "match", ",", "err", ":=", "filter", ".", "Match", "(", "filterKey", ",", "txOut", ".", "PkScript", ",", ")", "\n", "if", "err", "!=", "nil", "{", "// If we're unable to query", "// this filter, then we'll skip", "// this peer all together.", "continue", "peerVerification", "\n", "}", "\n\n", "if", "match", "{", "continue", "\n", "}", "\n\n", "// If this filter doesn't match, then", "// we'll mark this peer as bad and move", "// on to the next peer.", "badPeers", "[", "peerAddr", "]", "=", "struct", "{", "}", "{", "}", "\n", "continue", "peerVerification", "\n", "}", "\n", "}", "\n", "}", "\n\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fType", ")", "\n", "}", "\n\n", "// TODO: We can add an after-the-fact countermeasure here against", "// eclipse attacks. If the checkpoints don't match the store, we can", "// check whether the store or the checkpoints we got from the network", "// are correct.", "// With the set of bad peers known, we'll collect a slice of all the", "// faulty peers.", "invalidPeers", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "badPeers", ")", ")", "\n", "for", "peer", ":=", "range", "badPeers", "{", "invalidPeers", "=", "append", "(", "invalidPeers", ",", "peer", ")", "\n", "}", "\n\n", "return", "invalidPeers", ",", "nil", "\n", "}" ]
// resolveCFHeaderMismatch will attempt to cross-reference each filter received // by each peer based on what we can reconstruct and verify from the filter in // question. We'll return all the peers that returned what we believe to in // invalid filter.
[ "resolveCFHeaderMismatch", "will", "attempt", "to", "cross", "-", "reference", "each", "filter", "received", "by", "each", "peer", "based", "on", "what", "we", "can", "reconstruct", "and", "verify", "from", "the", "filter", "in", "question", ".", "We", "ll", "return", "all", "the", "peers", "that", "returned", "what", "we", "believe", "to", "in", "invalid", "filter", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1384-L1473
train
lightninglabs/neutrino
blockmanager.go
getCFHeadersForAllPeers
func (b *blockManager) getCFHeadersForAllPeers(height uint32, fType wire.FilterType) (map[string]*wire.MsgCFHeaders, int) { // Create the map we're returning. headers := make(map[string]*wire.MsgCFHeaders) // Get the header we expect at either the tip of the block header store // or at the end of the maximum-size response message, whichever is // larger. stopHeader, stopHeight, err := b.server.BlockHeaders.ChainTip() if stopHeight-height >= wire.MaxCFHeadersPerMsg { stopHeader, err = b.server.BlockHeaders.FetchHeaderByHeight( height + wire.MaxCFHeadersPerMsg - 1, ) if err != nil { return nil, 0 } // We'll make sure we also update our stopHeight so we know how // many headers to expect below. stopHeight = height + wire.MaxCFHeadersPerMsg - 1 } // Calculate the hash and use it to create the query message. stopHash := stopHeader.BlockHash() msg := wire.NewMsgGetCFHeaders(fType, height, &stopHash) numHeaders := int(stopHeight - height + 1) // Send the query to all peers and record their responses in the map. b.server.queryAllPeers( msg, func(sp *ServerPeer, resp wire.Message, quit chan<- struct{}, peerQuit chan<- struct{}) { switch m := resp.(type) { case *wire.MsgCFHeaders: if m.StopHash == stopHash && m.FilterType == fType && len(m.FilterHashes) == numHeaders { headers[sp.Addr()] = m // We got an answer from this peer so // that peer's goroutine can stop. close(peerQuit) } } }, ) return headers, numHeaders }
go
func (b *blockManager) getCFHeadersForAllPeers(height uint32, fType wire.FilterType) (map[string]*wire.MsgCFHeaders, int) { // Create the map we're returning. headers := make(map[string]*wire.MsgCFHeaders) // Get the header we expect at either the tip of the block header store // or at the end of the maximum-size response message, whichever is // larger. stopHeader, stopHeight, err := b.server.BlockHeaders.ChainTip() if stopHeight-height >= wire.MaxCFHeadersPerMsg { stopHeader, err = b.server.BlockHeaders.FetchHeaderByHeight( height + wire.MaxCFHeadersPerMsg - 1, ) if err != nil { return nil, 0 } // We'll make sure we also update our stopHeight so we know how // many headers to expect below. stopHeight = height + wire.MaxCFHeadersPerMsg - 1 } // Calculate the hash and use it to create the query message. stopHash := stopHeader.BlockHash() msg := wire.NewMsgGetCFHeaders(fType, height, &stopHash) numHeaders := int(stopHeight - height + 1) // Send the query to all peers and record their responses in the map. b.server.queryAllPeers( msg, func(sp *ServerPeer, resp wire.Message, quit chan<- struct{}, peerQuit chan<- struct{}) { switch m := resp.(type) { case *wire.MsgCFHeaders: if m.StopHash == stopHash && m.FilterType == fType && len(m.FilterHashes) == numHeaders { headers[sp.Addr()] = m // We got an answer from this peer so // that peer's goroutine can stop. close(peerQuit) } } }, ) return headers, numHeaders }
[ "func", "(", "b", "*", "blockManager", ")", "getCFHeadersForAllPeers", "(", "height", "uint32", ",", "fType", "wire", ".", "FilterType", ")", "(", "map", "[", "string", "]", "*", "wire", ".", "MsgCFHeaders", ",", "int", ")", "{", "// Create the map we're returning.", "headers", ":=", "make", "(", "map", "[", "string", "]", "*", "wire", ".", "MsgCFHeaders", ")", "\n\n", "// Get the header we expect at either the tip of the block header store", "// or at the end of the maximum-size response message, whichever is", "// larger.", "stopHeader", ",", "stopHeight", ",", "err", ":=", "b", ".", "server", ".", "BlockHeaders", ".", "ChainTip", "(", ")", "\n", "if", "stopHeight", "-", "height", ">=", "wire", ".", "MaxCFHeadersPerMsg", "{", "stopHeader", ",", "err", "=", "b", ".", "server", ".", "BlockHeaders", ".", "FetchHeaderByHeight", "(", "height", "+", "wire", ".", "MaxCFHeadersPerMsg", "-", "1", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", "\n", "}", "\n\n", "// We'll make sure we also update our stopHeight so we know how", "// many headers to expect below.", "stopHeight", "=", "height", "+", "wire", ".", "MaxCFHeadersPerMsg", "-", "1", "\n", "}", "\n\n", "// Calculate the hash and use it to create the query message.", "stopHash", ":=", "stopHeader", ".", "BlockHash", "(", ")", "\n", "msg", ":=", "wire", ".", "NewMsgGetCFHeaders", "(", "fType", ",", "height", ",", "&", "stopHash", ")", "\n", "numHeaders", ":=", "int", "(", "stopHeight", "-", "height", "+", "1", ")", "\n\n", "// Send the query to all peers and record their responses in the map.", "b", ".", "server", ".", "queryAllPeers", "(", "msg", ",", "func", "(", "sp", "*", "ServerPeer", ",", "resp", "wire", ".", "Message", ",", "quit", "chan", "<-", "struct", "{", "}", ",", "peerQuit", "chan", "<-", "struct", "{", "}", ")", "{", "switch", "m", ":=", "resp", ".", "(", "type", ")", "{", "case", "*", "wire", ".", "MsgCFHeaders", ":", "if", "m", ".", "StopHash", "==", "stopHash", "&&", "m", ".", "FilterType", "==", "fType", "&&", "len", "(", "m", ".", "FilterHashes", ")", "==", "numHeaders", "{", "headers", "[", "sp", ".", "Addr", "(", ")", "]", "=", "m", "\n\n", "// We got an answer from this peer so", "// that peer's goroutine can stop.", "close", "(", "peerQuit", ")", "\n", "}", "\n", "}", "\n", "}", ",", ")", "\n\n", "return", "headers", ",", "numHeaders", "\n", "}" ]
// getCFHeadersForAllPeers runs a query for cfheaders at a specific height and // returns a map of responses from all peers. The second return value is the // number for cfheaders in each response.
[ "getCFHeadersForAllPeers", "runs", "a", "query", "for", "cfheaders", "at", "a", "specific", "height", "and", "returns", "a", "map", "of", "responses", "from", "all", "peers", ".", "The", "second", "return", "value", "is", "the", "number", "for", "cfheaders", "in", "each", "response", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1478-L1528
train
lightninglabs/neutrino
blockmanager.go
fetchFilterFromAllPeers
func (b *blockManager) fetchFilterFromAllPeers( height uint32, blockHash chainhash.Hash, filterType wire.FilterType) map[string]*gcs.Filter { // We'll use this map to collate all responses we receive from each // peer. filterResponses := make(map[string]*gcs.Filter) // We'll now request the target filter from each peer, using a stop // hash at the target block hash to ensure we only get a single filter. fitlerReqMsg := wire.NewMsgGetCFilters(filterType, height, &blockHash) b.server.queryAllPeers( fitlerReqMsg, func(sp *ServerPeer, resp wire.Message, quit chan<- struct{}, peerQuit chan<- struct{}) { switch response := resp.(type) { // We're only interested in "cfilter" messages. case *wire.MsgCFilter: // If the response doesn't match our request. // Ignore this message. if blockHash != response.BlockHash || filterType != response.FilterType { return } // Now that we know we have the proper filter, // we'll decode it into an object the caller // can utilize. gcsFilter, err := gcs.FromNBytes( builder.DefaultP, builder.DefaultM, response.Data, ) if err != nil { // Malformed filter data. We can ignore // this message. return } // Now that we're able to properly parse this // filter, we'll assign it to its source peer, // and wait for the next response. filterResponses[sp.Addr()] = gcsFilter default: } }, ) return filterResponses }
go
func (b *blockManager) fetchFilterFromAllPeers( height uint32, blockHash chainhash.Hash, filterType wire.FilterType) map[string]*gcs.Filter { // We'll use this map to collate all responses we receive from each // peer. filterResponses := make(map[string]*gcs.Filter) // We'll now request the target filter from each peer, using a stop // hash at the target block hash to ensure we only get a single filter. fitlerReqMsg := wire.NewMsgGetCFilters(filterType, height, &blockHash) b.server.queryAllPeers( fitlerReqMsg, func(sp *ServerPeer, resp wire.Message, quit chan<- struct{}, peerQuit chan<- struct{}) { switch response := resp.(type) { // We're only interested in "cfilter" messages. case *wire.MsgCFilter: // If the response doesn't match our request. // Ignore this message. if blockHash != response.BlockHash || filterType != response.FilterType { return } // Now that we know we have the proper filter, // we'll decode it into an object the caller // can utilize. gcsFilter, err := gcs.FromNBytes( builder.DefaultP, builder.DefaultM, response.Data, ) if err != nil { // Malformed filter data. We can ignore // this message. return } // Now that we're able to properly parse this // filter, we'll assign it to its source peer, // and wait for the next response. filterResponses[sp.Addr()] = gcsFilter default: } }, ) return filterResponses }
[ "func", "(", "b", "*", "blockManager", ")", "fetchFilterFromAllPeers", "(", "height", "uint32", ",", "blockHash", "chainhash", ".", "Hash", ",", "filterType", "wire", ".", "FilterType", ")", "map", "[", "string", "]", "*", "gcs", ".", "Filter", "{", "// We'll use this map to collate all responses we receive from each", "// peer.", "filterResponses", ":=", "make", "(", "map", "[", "string", "]", "*", "gcs", ".", "Filter", ")", "\n\n", "// We'll now request the target filter from each peer, using a stop", "// hash at the target block hash to ensure we only get a single filter.", "fitlerReqMsg", ":=", "wire", ".", "NewMsgGetCFilters", "(", "filterType", ",", "height", ",", "&", "blockHash", ")", "\n", "b", ".", "server", ".", "queryAllPeers", "(", "fitlerReqMsg", ",", "func", "(", "sp", "*", "ServerPeer", ",", "resp", "wire", ".", "Message", ",", "quit", "chan", "<-", "struct", "{", "}", ",", "peerQuit", "chan", "<-", "struct", "{", "}", ")", "{", "switch", "response", ":=", "resp", ".", "(", "type", ")", "{", "// We're only interested in \"cfilter\" messages.", "case", "*", "wire", ".", "MsgCFilter", ":", "// If the response doesn't match our request.", "// Ignore this message.", "if", "blockHash", "!=", "response", ".", "BlockHash", "||", "filterType", "!=", "response", ".", "FilterType", "{", "return", "\n", "}", "\n\n", "// Now that we know we have the proper filter,", "// we'll decode it into an object the caller", "// can utilize.", "gcsFilter", ",", "err", ":=", "gcs", ".", "FromNBytes", "(", "builder", ".", "DefaultP", ",", "builder", ".", "DefaultM", ",", "response", ".", "Data", ",", ")", "\n", "if", "err", "!=", "nil", "{", "// Malformed filter data. We can ignore", "// this message.", "return", "\n", "}", "\n\n", "// Now that we're able to properly parse this", "// filter, we'll assign it to its source peer,", "// and wait for the next response.", "filterResponses", "[", "sp", ".", "Addr", "(", ")", "]", "=", "gcsFilter", "\n\n", "default", ":", "}", "\n", "}", ",", ")", "\n\n", "return", "filterResponses", "\n", "}" ]
// fetchFilterFromAllPeers attempts to fetch a filter for the target filter // type and blocks from all peers connected to the block manager. This method // returns a map which allows the caller to match a peer to the filter it // responded with.
[ "fetchFilterFromAllPeers", "attempts", "to", "fetch", "a", "filter", "for", "the", "target", "filter", "type", "and", "blocks", "from", "all", "peers", "connected", "to", "the", "block", "manager", ".", "This", "method", "returns", "a", "map", "which", "allows", "the", "caller", "to", "match", "a", "peer", "to", "the", "filter", "it", "responded", "with", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1534-L1584
train
lightninglabs/neutrino
blockmanager.go
getCheckpts
func (b *blockManager) getCheckpts(lastHash *chainhash.Hash, fType wire.FilterType) map[string][]*chainhash.Hash { checkpoints := make(map[string][]*chainhash.Hash) getCheckptMsg := wire.NewMsgGetCFCheckpt(fType, lastHash) b.server.queryAllPeers( getCheckptMsg, func(sp *ServerPeer, resp wire.Message, quit chan<- struct{}, peerQuit chan<- struct{}) { switch m := resp.(type) { case *wire.MsgCFCheckpt: if m.FilterType == fType && m.StopHash == *lastHash { checkpoints[sp.Addr()] = m.FilterHeaders close(peerQuit) } } }, ) return checkpoints }
go
func (b *blockManager) getCheckpts(lastHash *chainhash.Hash, fType wire.FilterType) map[string][]*chainhash.Hash { checkpoints := make(map[string][]*chainhash.Hash) getCheckptMsg := wire.NewMsgGetCFCheckpt(fType, lastHash) b.server.queryAllPeers( getCheckptMsg, func(sp *ServerPeer, resp wire.Message, quit chan<- struct{}, peerQuit chan<- struct{}) { switch m := resp.(type) { case *wire.MsgCFCheckpt: if m.FilterType == fType && m.StopHash == *lastHash { checkpoints[sp.Addr()] = m.FilterHeaders close(peerQuit) } } }, ) return checkpoints }
[ "func", "(", "b", "*", "blockManager", ")", "getCheckpts", "(", "lastHash", "*", "chainhash", ".", "Hash", ",", "fType", "wire", ".", "FilterType", ")", "map", "[", "string", "]", "[", "]", "*", "chainhash", ".", "Hash", "{", "checkpoints", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "chainhash", ".", "Hash", ")", "\n", "getCheckptMsg", ":=", "wire", ".", "NewMsgGetCFCheckpt", "(", "fType", ",", "lastHash", ")", "\n", "b", ".", "server", ".", "queryAllPeers", "(", "getCheckptMsg", ",", "func", "(", "sp", "*", "ServerPeer", ",", "resp", "wire", ".", "Message", ",", "quit", "chan", "<-", "struct", "{", "}", ",", "peerQuit", "chan", "<-", "struct", "{", "}", ")", "{", "switch", "m", ":=", "resp", ".", "(", "type", ")", "{", "case", "*", "wire", ".", "MsgCFCheckpt", ":", "if", "m", ".", "FilterType", "==", "fType", "&&", "m", ".", "StopHash", "==", "*", "lastHash", "{", "checkpoints", "[", "sp", ".", "Addr", "(", ")", "]", "=", "m", ".", "FilterHeaders", "\n", "close", "(", "peerQuit", ")", "\n", "}", "\n", "}", "\n", "}", ",", ")", "\n", "return", "checkpoints", "\n", "}" ]
// getCheckpts runs a query for cfcheckpts against all peers and returns a map // of responses.
[ "getCheckpts", "runs", "a", "query", "for", "cfcheckpts", "against", "all", "peers", "and", "returns", "a", "map", "of", "responses", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1588-L1608
train
lightninglabs/neutrino
blockmanager.go
checkCFCheckptSanity
func checkCFCheckptSanity(cp map[string][]*chainhash.Hash, headerStore *headerfs.FilterHeaderStore) (int, error) { // Get the known best header to compare against checkpoints. _, storeTip, err := headerStore.ChainTip() if err != nil { return 0, err } // Determine the maximum length of each peer's checkpoint list. If they // differ, we don't return yet because we want to make sure they match // up to the shortest one. maxLen := 0 for _, checkpoints := range cp { if len(checkpoints) > maxLen { maxLen = len(checkpoints) } } // Compare the actual checkpoints against each other and anything // stored in the header store. for i := 0; i < maxLen; i++ { var checkpoint chainhash.Hash for _, checkpoints := range cp { if i >= len(checkpoints) { continue } if checkpoint == zeroHash { checkpoint = *checkpoints[i] } if checkpoint != *checkpoints[i] { log.Warnf("mismatch at %v, expected %v got "+ "%v", i, checkpoint, checkpoints[i]) return i, nil } } ckptHeight := uint32((i + 1) * wire.CFCheckptInterval) if ckptHeight <= storeTip { header, err := headerStore.FetchHeaderByHeight( ckptHeight, ) if err != nil { return i, err } if *header != checkpoint { log.Warnf("mismatch at height %v, expected %v got "+ "%v", ckptHeight, header, checkpoint) return i, nil } } } return -1, nil }
go
func checkCFCheckptSanity(cp map[string][]*chainhash.Hash, headerStore *headerfs.FilterHeaderStore) (int, error) { // Get the known best header to compare against checkpoints. _, storeTip, err := headerStore.ChainTip() if err != nil { return 0, err } // Determine the maximum length of each peer's checkpoint list. If they // differ, we don't return yet because we want to make sure they match // up to the shortest one. maxLen := 0 for _, checkpoints := range cp { if len(checkpoints) > maxLen { maxLen = len(checkpoints) } } // Compare the actual checkpoints against each other and anything // stored in the header store. for i := 0; i < maxLen; i++ { var checkpoint chainhash.Hash for _, checkpoints := range cp { if i >= len(checkpoints) { continue } if checkpoint == zeroHash { checkpoint = *checkpoints[i] } if checkpoint != *checkpoints[i] { log.Warnf("mismatch at %v, expected %v got "+ "%v", i, checkpoint, checkpoints[i]) return i, nil } } ckptHeight := uint32((i + 1) * wire.CFCheckptInterval) if ckptHeight <= storeTip { header, err := headerStore.FetchHeaderByHeight( ckptHeight, ) if err != nil { return i, err } if *header != checkpoint { log.Warnf("mismatch at height %v, expected %v got "+ "%v", ckptHeight, header, checkpoint) return i, nil } } } return -1, nil }
[ "func", "checkCFCheckptSanity", "(", "cp", "map", "[", "string", "]", "[", "]", "*", "chainhash", ".", "Hash", ",", "headerStore", "*", "headerfs", ".", "FilterHeaderStore", ")", "(", "int", ",", "error", ")", "{", "// Get the known best header to compare against checkpoints.", "_", ",", "storeTip", ",", "err", ":=", "headerStore", ".", "ChainTip", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "// Determine the maximum length of each peer's checkpoint list. If they", "// differ, we don't return yet because we want to make sure they match", "// up to the shortest one.", "maxLen", ":=", "0", "\n", "for", "_", ",", "checkpoints", ":=", "range", "cp", "{", "if", "len", "(", "checkpoints", ")", ">", "maxLen", "{", "maxLen", "=", "len", "(", "checkpoints", ")", "\n", "}", "\n", "}", "\n\n", "// Compare the actual checkpoints against each other and anything", "// stored in the header store.", "for", "i", ":=", "0", ";", "i", "<", "maxLen", ";", "i", "++", "{", "var", "checkpoint", "chainhash", ".", "Hash", "\n", "for", "_", ",", "checkpoints", ":=", "range", "cp", "{", "if", "i", ">=", "len", "(", "checkpoints", ")", "{", "continue", "\n", "}", "\n", "if", "checkpoint", "==", "zeroHash", "{", "checkpoint", "=", "*", "checkpoints", "[", "i", "]", "\n", "}", "\n", "if", "checkpoint", "!=", "*", "checkpoints", "[", "i", "]", "{", "log", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", ",", "i", ",", "checkpoint", ",", "checkpoints", "[", "i", "]", ")", "\n", "return", "i", ",", "nil", "\n", "}", "\n", "}", "\n\n", "ckptHeight", ":=", "uint32", "(", "(", "i", "+", "1", ")", "*", "wire", ".", "CFCheckptInterval", ")", "\n\n", "if", "ckptHeight", "<=", "storeTip", "{", "header", ",", "err", ":=", "headerStore", ".", "FetchHeaderByHeight", "(", "ckptHeight", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "i", ",", "err", "\n", "}", "\n\n", "if", "*", "header", "!=", "checkpoint", "{", "log", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", ",", "ckptHeight", ",", "header", ",", "checkpoint", ")", "\n", "return", "i", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "-", "1", ",", "nil", "\n", "}" ]
// checkCFCheckptSanity checks whether all peers which have responded agree. // If so, it returns -1; otherwise, it returns the earliest index at which at // least one of the peers differs. The checkpoints are also checked against the // existing store up to the tip of the store. If all of the peers match but // the store doesn't, the height at which the mismatch occurs is returned.
[ "checkCFCheckptSanity", "checks", "whether", "all", "peers", "which", "have", "responded", "agree", ".", "If", "so", "it", "returns", "-", "1", ";", "otherwise", "it", "returns", "the", "earliest", "index", "at", "which", "at", "least", "one", "of", "the", "peers", "differs", ".", "The", "checkpoints", "are", "also", "checked", "against", "the", "existing", "store", "up", "to", "the", "tip", "of", "the", "store", ".", "If", "all", "of", "the", "peers", "match", "but", "the", "store", "doesn", "t", "the", "height", "at", "which", "the", "mismatch", "occurs", "is", "returned", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1615-L1671
train
lightninglabs/neutrino
blockmanager.go
SyncPeer
func (b *blockManager) SyncPeer() *ServerPeer { b.syncPeerMutex.Lock() defer b.syncPeerMutex.Unlock() return b.syncPeer }
go
func (b *blockManager) SyncPeer() *ServerPeer { b.syncPeerMutex.Lock() defer b.syncPeerMutex.Unlock() return b.syncPeer }
[ "func", "(", "b", "*", "blockManager", ")", "SyncPeer", "(", ")", "*", "ServerPeer", "{", "b", ".", "syncPeerMutex", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "syncPeerMutex", ".", "Unlock", "(", ")", "\n\n", "return", "b", ".", "syncPeer", "\n", "}" ]
// SyncPeer returns the current sync peer.
[ "SyncPeer", "returns", "the", "current", "sync", "peer", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1714-L1719
train
lightninglabs/neutrino
blockmanager.go
findNextHeaderCheckpoint
func (b *blockManager) findNextHeaderCheckpoint(height int32) *chaincfg.Checkpoint { // There is no next checkpoint if there are none for this current // network. checkpoints := b.server.chainParams.Checkpoints if len(checkpoints) == 0 { return nil } // There is no next checkpoint if the height is already after the final // checkpoint. finalCheckpoint := &checkpoints[len(checkpoints)-1] if height >= finalCheckpoint.Height { return nil } // Find the next checkpoint. nextCheckpoint := finalCheckpoint for i := len(checkpoints) - 2; i >= 0; i-- { if height >= checkpoints[i].Height { break } nextCheckpoint = &checkpoints[i] } return nextCheckpoint }
go
func (b *blockManager) findNextHeaderCheckpoint(height int32) *chaincfg.Checkpoint { // There is no next checkpoint if there are none for this current // network. checkpoints := b.server.chainParams.Checkpoints if len(checkpoints) == 0 { return nil } // There is no next checkpoint if the height is already after the final // checkpoint. finalCheckpoint := &checkpoints[len(checkpoints)-1] if height >= finalCheckpoint.Height { return nil } // Find the next checkpoint. nextCheckpoint := finalCheckpoint for i := len(checkpoints) - 2; i >= 0; i-- { if height >= checkpoints[i].Height { break } nextCheckpoint = &checkpoints[i] } return nextCheckpoint }
[ "func", "(", "b", "*", "blockManager", ")", "findNextHeaderCheckpoint", "(", "height", "int32", ")", "*", "chaincfg", ".", "Checkpoint", "{", "// There is no next checkpoint if there are none for this current", "// network.", "checkpoints", ":=", "b", ".", "server", ".", "chainParams", ".", "Checkpoints", "\n", "if", "len", "(", "checkpoints", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "// There is no next checkpoint if the height is already after the final", "// checkpoint.", "finalCheckpoint", ":=", "&", "checkpoints", "[", "len", "(", "checkpoints", ")", "-", "1", "]", "\n", "if", "height", ">=", "finalCheckpoint", ".", "Height", "{", "return", "nil", "\n", "}", "\n\n", "// Find the next checkpoint.", "nextCheckpoint", ":=", "finalCheckpoint", "\n", "for", "i", ":=", "len", "(", "checkpoints", ")", "-", "2", ";", "i", ">=", "0", ";", "i", "--", "{", "if", "height", ">=", "checkpoints", "[", "i", "]", ".", "Height", "{", "break", "\n", "}", "\n", "nextCheckpoint", "=", "&", "checkpoints", "[", "i", "]", "\n", "}", "\n", "return", "nextCheckpoint", "\n", "}" ]
// findNextHeaderCheckpoint returns the next checkpoint after the passed height. // It returns nil when there is not one either because the height is already // later than the final checkpoint or there are none for the current network.
[ "findNextHeaderCheckpoint", "returns", "the", "next", "checkpoint", "after", "the", "passed", "height", ".", "It", "returns", "nil", "when", "there", "is", "not", "one", "either", "because", "the", "height", "is", "already", "later", "than", "the", "final", "checkpoint", "or", "there", "are", "none", "for", "the", "current", "network", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1731-L1755
train
lightninglabs/neutrino
blockmanager.go
findPreviousHeaderCheckpoint
func (b *blockManager) findPreviousHeaderCheckpoint(height int32) *chaincfg.Checkpoint { // Start with the genesis block - earliest checkpoint to which our code // will want to reset prevCheckpoint := &chaincfg.Checkpoint{ Height: 0, Hash: b.server.chainParams.GenesisHash, } // Find the latest checkpoint lower than height or return genesis block // if there are none. checkpoints := b.server.chainParams.Checkpoints for i := 0; i < len(checkpoints); i++ { if height <= checkpoints[i].Height { break } prevCheckpoint = &checkpoints[i] } return prevCheckpoint }
go
func (b *blockManager) findPreviousHeaderCheckpoint(height int32) *chaincfg.Checkpoint { // Start with the genesis block - earliest checkpoint to which our code // will want to reset prevCheckpoint := &chaincfg.Checkpoint{ Height: 0, Hash: b.server.chainParams.GenesisHash, } // Find the latest checkpoint lower than height or return genesis block // if there are none. checkpoints := b.server.chainParams.Checkpoints for i := 0; i < len(checkpoints); i++ { if height <= checkpoints[i].Height { break } prevCheckpoint = &checkpoints[i] } return prevCheckpoint }
[ "func", "(", "b", "*", "blockManager", ")", "findPreviousHeaderCheckpoint", "(", "height", "int32", ")", "*", "chaincfg", ".", "Checkpoint", "{", "// Start with the genesis block - earliest checkpoint to which our code", "// will want to reset", "prevCheckpoint", ":=", "&", "chaincfg", ".", "Checkpoint", "{", "Height", ":", "0", ",", "Hash", ":", "b", ".", "server", ".", "chainParams", ".", "GenesisHash", ",", "}", "\n\n", "// Find the latest checkpoint lower than height or return genesis block", "// if there are none.", "checkpoints", ":=", "b", ".", "server", ".", "chainParams", ".", "Checkpoints", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "checkpoints", ")", ";", "i", "++", "{", "if", "height", "<=", "checkpoints", "[", "i", "]", ".", "Height", "{", "break", "\n", "}", "\n", "prevCheckpoint", "=", "&", "checkpoints", "[", "i", "]", "\n", "}", "\n\n", "return", "prevCheckpoint", "\n", "}" ]
// findPreviousHeaderCheckpoint returns the last checkpoint before the passed // height. It returns a checkpoint matching the genesis block when the height // is earlier than the first checkpoint or there are no checkpoints for the // current network. This is used for resetting state when a malicious peer // sends us headers that don't lead up to a known checkpoint.
[ "findPreviousHeaderCheckpoint", "returns", "the", "last", "checkpoint", "before", "the", "passed", "height", ".", "It", "returns", "a", "checkpoint", "matching", "the", "genesis", "block", "when", "the", "height", "is", "earlier", "than", "the", "first", "checkpoint", "or", "there", "are", "no", "checkpoints", "for", "the", "current", "network", ".", "This", "is", "used", "for", "resetting", "state", "when", "a", "malicious", "peer", "sends", "us", "headers", "that", "don", "t", "lead", "up", "to", "a", "known", "checkpoint", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1762-L1781
train
lightninglabs/neutrino
blockmanager.go
IsFullySynced
func (b *blockManager) IsFullySynced() bool { _, blockHeaderHeight, err := b.server.BlockHeaders.ChainTip() if err != nil { return false } _, filterHeaderHeight, err := b.server.RegFilterHeaders.ChainTip() if err != nil { return false } // If the block headers and filter headers are not at the same height, // we cannot be fully synced. if blockHeaderHeight != filterHeaderHeight { return false } // Block and filter headers being at the same height, return whether // our block headers are synced. return b.BlockHeadersSynced() }
go
func (b *blockManager) IsFullySynced() bool { _, blockHeaderHeight, err := b.server.BlockHeaders.ChainTip() if err != nil { return false } _, filterHeaderHeight, err := b.server.RegFilterHeaders.ChainTip() if err != nil { return false } // If the block headers and filter headers are not at the same height, // we cannot be fully synced. if blockHeaderHeight != filterHeaderHeight { return false } // Block and filter headers being at the same height, return whether // our block headers are synced. return b.BlockHeadersSynced() }
[ "func", "(", "b", "*", "blockManager", ")", "IsFullySynced", "(", ")", "bool", "{", "_", ",", "blockHeaderHeight", ",", "err", ":=", "b", ".", "server", ".", "BlockHeaders", ".", "ChainTip", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "_", ",", "filterHeaderHeight", ",", "err", ":=", "b", ".", "server", ".", "RegFilterHeaders", ".", "ChainTip", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "// If the block headers and filter headers are not at the same height,", "// we cannot be fully synced.", "if", "blockHeaderHeight", "!=", "filterHeaderHeight", "{", "return", "false", "\n", "}", "\n\n", "// Block and filter headers being at the same height, return whether", "// our block headers are synced.", "return", "b", ".", "BlockHeadersSynced", "(", ")", "\n", "}" ]
// IsFullySynced returns whether or not the block manager believed it is fully // synced to the connected peers, meaning both block headers and filter headers // are current.
[ "IsFullySynced", "returns", "whether", "or", "not", "the", "block", "manager", "believed", "it", "is", "fully", "synced", "to", "the", "connected", "peers", "meaning", "both", "block", "headers", "and", "filter", "headers", "are", "current", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1875-L1895
train
lightninglabs/neutrino
blockmanager.go
BlockHeadersSynced
func (b *blockManager) BlockHeadersSynced() bool { b.syncPeerMutex.RLock() defer b.syncPeerMutex.RUnlock() // Figure out the latest block we know. header, height, err := b.server.BlockHeaders.ChainTip() if err != nil { return false } // There is no last checkpoint if checkpoints are disabled or there are // none for this current network. checkpoints := b.server.chainParams.Checkpoints if len(checkpoints) != 0 { // We aren't current if the newest block we know of isn't ahead // of all checkpoints. if checkpoints[len(checkpoints)-1].Height >= int32(height) { return false } } // If we have a syncPeer and are below the block we are syncing to, we // are not current. if b.syncPeer != nil && int32(height) < b.syncPeer.LastBlock() { return false } // If our time source (median times of all the connected peers) is at // least 24 hours ahead of our best known block, we aren't current. minus24Hours := b.server.timeSource.AdjustedTime().Add(-24 * time.Hour) if header.Timestamp.Before(minus24Hours) { return false } // If we have no sync peer, we can assume we're current for now. if b.syncPeer == nil { return true } // If we have a syncPeer and the peer reported a higher known block // height on connect than we know the peer already has, we're probably // not current. If the peer is lying to us, other code will disconnect // it and then we'll re-check and notice that we're actually current. return b.syncPeer.LastBlock() >= b.syncPeer.StartingHeight() }
go
func (b *blockManager) BlockHeadersSynced() bool { b.syncPeerMutex.RLock() defer b.syncPeerMutex.RUnlock() // Figure out the latest block we know. header, height, err := b.server.BlockHeaders.ChainTip() if err != nil { return false } // There is no last checkpoint if checkpoints are disabled or there are // none for this current network. checkpoints := b.server.chainParams.Checkpoints if len(checkpoints) != 0 { // We aren't current if the newest block we know of isn't ahead // of all checkpoints. if checkpoints[len(checkpoints)-1].Height >= int32(height) { return false } } // If we have a syncPeer and are below the block we are syncing to, we // are not current. if b.syncPeer != nil && int32(height) < b.syncPeer.LastBlock() { return false } // If our time source (median times of all the connected peers) is at // least 24 hours ahead of our best known block, we aren't current. minus24Hours := b.server.timeSource.AdjustedTime().Add(-24 * time.Hour) if header.Timestamp.Before(minus24Hours) { return false } // If we have no sync peer, we can assume we're current for now. if b.syncPeer == nil { return true } // If we have a syncPeer and the peer reported a higher known block // height on connect than we know the peer already has, we're probably // not current. If the peer is lying to us, other code will disconnect // it and then we'll re-check and notice that we're actually current. return b.syncPeer.LastBlock() >= b.syncPeer.StartingHeight() }
[ "func", "(", "b", "*", "blockManager", ")", "BlockHeadersSynced", "(", ")", "bool", "{", "b", ".", "syncPeerMutex", ".", "RLock", "(", ")", "\n", "defer", "b", ".", "syncPeerMutex", ".", "RUnlock", "(", ")", "\n\n", "// Figure out the latest block we know.", "header", ",", "height", ",", "err", ":=", "b", ".", "server", ".", "BlockHeaders", ".", "ChainTip", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "// There is no last checkpoint if checkpoints are disabled or there are", "// none for this current network.", "checkpoints", ":=", "b", ".", "server", ".", "chainParams", ".", "Checkpoints", "\n", "if", "len", "(", "checkpoints", ")", "!=", "0", "{", "// We aren't current if the newest block we know of isn't ahead", "// of all checkpoints.", "if", "checkpoints", "[", "len", "(", "checkpoints", ")", "-", "1", "]", ".", "Height", ">=", "int32", "(", "height", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "// If we have a syncPeer and are below the block we are syncing to, we", "// are not current.", "if", "b", ".", "syncPeer", "!=", "nil", "&&", "int32", "(", "height", ")", "<", "b", ".", "syncPeer", ".", "LastBlock", "(", ")", "{", "return", "false", "\n", "}", "\n\n", "// If our time source (median times of all the connected peers) is at", "// least 24 hours ahead of our best known block, we aren't current.", "minus24Hours", ":=", "b", ".", "server", ".", "timeSource", ".", "AdjustedTime", "(", ")", ".", "Add", "(", "-", "24", "*", "time", ".", "Hour", ")", "\n", "if", "header", ".", "Timestamp", ".", "Before", "(", "minus24Hours", ")", "{", "return", "false", "\n", "}", "\n\n", "// If we have no sync peer, we can assume we're current for now.", "if", "b", ".", "syncPeer", "==", "nil", "{", "return", "true", "\n", "}", "\n\n", "// If we have a syncPeer and the peer reported a higher known block", "// height on connect than we know the peer already has, we're probably", "// not current. If the peer is lying to us, other code will disconnect", "// it and then we'll re-check and notice that we're actually current.", "return", "b", ".", "syncPeer", ".", "LastBlock", "(", ")", ">=", "b", ".", "syncPeer", ".", "StartingHeight", "(", ")", "\n", "}" ]
// BlockHeadersSynced returns whether or not the block manager believes its // block headers are synced with the connected peers.
[ "BlockHeadersSynced", "returns", "whether", "or", "not", "the", "block", "manager", "believes", "its", "block", "headers", "are", "synced", "with", "the", "connected", "peers", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1899-L1943
train
lightninglabs/neutrino
blockmanager.go
SynchronizeFilterHeaders
func (b *blockManager) SynchronizeFilterHeaders(f func(uint32) error) error { b.newFilterHeadersMtx.RLock() defer b.newFilterHeadersMtx.RUnlock() return f(b.filterHeaderTip) }
go
func (b *blockManager) SynchronizeFilterHeaders(f func(uint32) error) error { b.newFilterHeadersMtx.RLock() defer b.newFilterHeadersMtx.RUnlock() return f(b.filterHeaderTip) }
[ "func", "(", "b", "*", "blockManager", ")", "SynchronizeFilterHeaders", "(", "f", "func", "(", "uint32", ")", "error", ")", "error", "{", "b", ".", "newFilterHeadersMtx", ".", "RLock", "(", ")", "\n", "defer", "b", ".", "newFilterHeadersMtx", ".", "RUnlock", "(", ")", "\n\n", "return", "f", "(", "b", ".", "filterHeaderTip", ")", "\n", "}" ]
// SynchronizeFilterHeaders allows the caller to execute a function closure // that depends on synchronization with the current set of filter headers. This // allows the caller to execute an action that depends on the current filter // header state, thereby ensuring that the state would shift from underneath // them. Each execution of the closure will have the current filter header tip // passed in to ensue that the caller gets a consistent view.
[ "SynchronizeFilterHeaders", "allows", "the", "caller", "to", "execute", "a", "function", "closure", "that", "depends", "on", "synchronization", "with", "the", "current", "set", "of", "filter", "headers", ".", "This", "allows", "the", "caller", "to", "execute", "an", "action", "that", "depends", "on", "the", "current", "filter", "header", "state", "thereby", "ensuring", "that", "the", "state", "would", "shift", "from", "underneath", "them", ".", "Each", "execution", "of", "the", "closure", "will", "have", "the", "current", "filter", "header", "tip", "passed", "in", "to", "ensue", "that", "the", "caller", "gets", "a", "consistent", "view", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1951-L1956
train
lightninglabs/neutrino
blockmanager.go
checkHeaderSanity
func (b *blockManager) checkHeaderSanity(blockHeader *wire.BlockHeader, maxTimestamp time.Time, reorgAttempt bool) error { diff, err := b.calcNextRequiredDifficulty( blockHeader.Timestamp, reorgAttempt) if err != nil { return err } stubBlock := btcutil.NewBlock(&wire.MsgBlock{ Header: *blockHeader, }) err = blockchain.CheckProofOfWork(stubBlock, blockchain.CompactToBig(diff)) if err != nil { return err } // Ensure the block time is not too far in the future. if blockHeader.Timestamp.After(maxTimestamp) { return fmt.Errorf("block timestamp of %v is too far in the "+ "future", blockHeader.Timestamp) } return nil }
go
func (b *blockManager) checkHeaderSanity(blockHeader *wire.BlockHeader, maxTimestamp time.Time, reorgAttempt bool) error { diff, err := b.calcNextRequiredDifficulty( blockHeader.Timestamp, reorgAttempt) if err != nil { return err } stubBlock := btcutil.NewBlock(&wire.MsgBlock{ Header: *blockHeader, }) err = blockchain.CheckProofOfWork(stubBlock, blockchain.CompactToBig(diff)) if err != nil { return err } // Ensure the block time is not too far in the future. if blockHeader.Timestamp.After(maxTimestamp) { return fmt.Errorf("block timestamp of %v is too far in the "+ "future", blockHeader.Timestamp) } return nil }
[ "func", "(", "b", "*", "blockManager", ")", "checkHeaderSanity", "(", "blockHeader", "*", "wire", ".", "BlockHeader", ",", "maxTimestamp", "time", ".", "Time", ",", "reorgAttempt", "bool", ")", "error", "{", "diff", ",", "err", ":=", "b", ".", "calcNextRequiredDifficulty", "(", "blockHeader", ".", "Timestamp", ",", "reorgAttempt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "stubBlock", ":=", "btcutil", ".", "NewBlock", "(", "&", "wire", ".", "MsgBlock", "{", "Header", ":", "*", "blockHeader", ",", "}", ")", "\n", "err", "=", "blockchain", ".", "CheckProofOfWork", "(", "stubBlock", ",", "blockchain", ".", "CompactToBig", "(", "diff", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Ensure the block time is not too far in the future.", "if", "blockHeader", ".", "Timestamp", ".", "After", "(", "maxTimestamp", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "blockHeader", ".", "Timestamp", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkHeaderSanity checks the PoW, and timestamp of a block header.
[ "checkHeaderSanity", "checks", "the", "PoW", "and", "timestamp", "of", "a", "block", "header", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L2416-L2437
train
lightninglabs/neutrino
blockmanager.go
calcNextRequiredDifficulty
func (b *blockManager) calcNextRequiredDifficulty(newBlockTime time.Time, reorgAttempt bool) (uint32, error) { hList := b.headerList if reorgAttempt { hList = b.reorgList } lastNode := hList.Back() // Genesis block. if lastNode == nil { return b.server.chainParams.PowLimitBits, nil } // Return the previous block's difficulty requirements if this block // is not at a difficulty retarget interval. if (lastNode.Height+1)%b.blocksPerRetarget != 0 { // For networks that support it, allow special reduction of the // required difficulty once too much time has elapsed without // mining a block. if b.server.chainParams.ReduceMinDifficulty { // Return minimum difficulty when more than the desired // amount of time has elapsed without mining a block. reductionTime := int64( b.server.chainParams.MinDiffReductionTime / time.Second) allowMinTime := lastNode.Header.Timestamp.Unix() + reductionTime if newBlockTime.Unix() > allowMinTime { return b.server.chainParams.PowLimitBits, nil } // The block was mined within the desired timeframe, so // return the difficulty for the last block which did // not have the special minimum difficulty rule applied. prevBits, err := b.findPrevTestNetDifficulty(hList) if err != nil { return 0, err } return prevBits, nil } // For the main network (or any unrecognized networks), simply // return the previous block's difficulty requirements. return lastNode.Header.Bits, nil } // Get the block node at the previous retarget (targetTimespan days // worth of blocks). firstNode, err := b.server.BlockHeaders.FetchHeaderByHeight( uint32(lastNode.Height + 1 - b.blocksPerRetarget), ) if err != nil { return 0, err } // Limit the amount of adjustment that can occur to the previous // difficulty. actualTimespan := lastNode.Header.Timestamp.Unix() - firstNode.Timestamp.Unix() adjustedTimespan := actualTimespan if actualTimespan < b.minRetargetTimespan { adjustedTimespan = b.minRetargetTimespan } else if actualTimespan > b.maxRetargetTimespan { adjustedTimespan = b.maxRetargetTimespan } // Calculate new target difficulty as: // currentDifficulty * (adjustedTimespan / targetTimespan) // The result uses integer division which means it will be slightly // rounded down. Bitcoind also uses integer division to calculate this // result. oldTarget := blockchain.CompactToBig(lastNode.Header.Bits) newTarget := new(big.Int).Mul(oldTarget, big.NewInt(adjustedTimespan)) targetTimeSpan := int64(b.server.chainParams.TargetTimespan / time.Second) newTarget.Div(newTarget, big.NewInt(targetTimeSpan)) // Limit new value to the proof of work limit. if newTarget.Cmp(b.server.chainParams.PowLimit) > 0 { newTarget.Set(b.server.chainParams.PowLimit) } // Log new target difficulty and return it. The new target logging is // intentionally converting the bits back to a number instead of using // newTarget since conversion to the compact representation loses // precision. newTargetBits := blockchain.BigToCompact(newTarget) log.Debugf("Difficulty retarget at block height %d", lastNode.Height+1) log.Debugf("Old target %08x (%064x)", lastNode.Header.Bits, oldTarget) log.Debugf("New target %08x (%064x)", newTargetBits, blockchain.CompactToBig(newTargetBits)) log.Debugf("Actual timespan %v, adjusted timespan %v, target timespan %v", time.Duration(actualTimespan)*time.Second, time.Duration(adjustedTimespan)*time.Second, b.server.chainParams.TargetTimespan) return newTargetBits, nil }
go
func (b *blockManager) calcNextRequiredDifficulty(newBlockTime time.Time, reorgAttempt bool) (uint32, error) { hList := b.headerList if reorgAttempt { hList = b.reorgList } lastNode := hList.Back() // Genesis block. if lastNode == nil { return b.server.chainParams.PowLimitBits, nil } // Return the previous block's difficulty requirements if this block // is not at a difficulty retarget interval. if (lastNode.Height+1)%b.blocksPerRetarget != 0 { // For networks that support it, allow special reduction of the // required difficulty once too much time has elapsed without // mining a block. if b.server.chainParams.ReduceMinDifficulty { // Return minimum difficulty when more than the desired // amount of time has elapsed without mining a block. reductionTime := int64( b.server.chainParams.MinDiffReductionTime / time.Second) allowMinTime := lastNode.Header.Timestamp.Unix() + reductionTime if newBlockTime.Unix() > allowMinTime { return b.server.chainParams.PowLimitBits, nil } // The block was mined within the desired timeframe, so // return the difficulty for the last block which did // not have the special minimum difficulty rule applied. prevBits, err := b.findPrevTestNetDifficulty(hList) if err != nil { return 0, err } return prevBits, nil } // For the main network (or any unrecognized networks), simply // return the previous block's difficulty requirements. return lastNode.Header.Bits, nil } // Get the block node at the previous retarget (targetTimespan days // worth of blocks). firstNode, err := b.server.BlockHeaders.FetchHeaderByHeight( uint32(lastNode.Height + 1 - b.blocksPerRetarget), ) if err != nil { return 0, err } // Limit the amount of adjustment that can occur to the previous // difficulty. actualTimespan := lastNode.Header.Timestamp.Unix() - firstNode.Timestamp.Unix() adjustedTimespan := actualTimespan if actualTimespan < b.minRetargetTimespan { adjustedTimespan = b.minRetargetTimespan } else if actualTimespan > b.maxRetargetTimespan { adjustedTimespan = b.maxRetargetTimespan } // Calculate new target difficulty as: // currentDifficulty * (adjustedTimespan / targetTimespan) // The result uses integer division which means it will be slightly // rounded down. Bitcoind also uses integer division to calculate this // result. oldTarget := blockchain.CompactToBig(lastNode.Header.Bits) newTarget := new(big.Int).Mul(oldTarget, big.NewInt(adjustedTimespan)) targetTimeSpan := int64(b.server.chainParams.TargetTimespan / time.Second) newTarget.Div(newTarget, big.NewInt(targetTimeSpan)) // Limit new value to the proof of work limit. if newTarget.Cmp(b.server.chainParams.PowLimit) > 0 { newTarget.Set(b.server.chainParams.PowLimit) } // Log new target difficulty and return it. The new target logging is // intentionally converting the bits back to a number instead of using // newTarget since conversion to the compact representation loses // precision. newTargetBits := blockchain.BigToCompact(newTarget) log.Debugf("Difficulty retarget at block height %d", lastNode.Height+1) log.Debugf("Old target %08x (%064x)", lastNode.Header.Bits, oldTarget) log.Debugf("New target %08x (%064x)", newTargetBits, blockchain.CompactToBig(newTargetBits)) log.Debugf("Actual timespan %v, adjusted timespan %v, target timespan %v", time.Duration(actualTimespan)*time.Second, time.Duration(adjustedTimespan)*time.Second, b.server.chainParams.TargetTimespan) return newTargetBits, nil }
[ "func", "(", "b", "*", "blockManager", ")", "calcNextRequiredDifficulty", "(", "newBlockTime", "time", ".", "Time", ",", "reorgAttempt", "bool", ")", "(", "uint32", ",", "error", ")", "{", "hList", ":=", "b", ".", "headerList", "\n", "if", "reorgAttempt", "{", "hList", "=", "b", ".", "reorgList", "\n", "}", "\n\n", "lastNode", ":=", "hList", ".", "Back", "(", ")", "\n\n", "// Genesis block.", "if", "lastNode", "==", "nil", "{", "return", "b", ".", "server", ".", "chainParams", ".", "PowLimitBits", ",", "nil", "\n", "}", "\n\n", "// Return the previous block's difficulty requirements if this block", "// is not at a difficulty retarget interval.", "if", "(", "lastNode", ".", "Height", "+", "1", ")", "%", "b", ".", "blocksPerRetarget", "!=", "0", "{", "// For networks that support it, allow special reduction of the", "// required difficulty once too much time has elapsed without", "// mining a block.", "if", "b", ".", "server", ".", "chainParams", ".", "ReduceMinDifficulty", "{", "// Return minimum difficulty when more than the desired", "// amount of time has elapsed without mining a block.", "reductionTime", ":=", "int64", "(", "b", ".", "server", ".", "chainParams", ".", "MinDiffReductionTime", "/", "time", ".", "Second", ")", "\n", "allowMinTime", ":=", "lastNode", ".", "Header", ".", "Timestamp", ".", "Unix", "(", ")", "+", "reductionTime", "\n", "if", "newBlockTime", ".", "Unix", "(", ")", ">", "allowMinTime", "{", "return", "b", ".", "server", ".", "chainParams", ".", "PowLimitBits", ",", "nil", "\n", "}", "\n\n", "// The block was mined within the desired timeframe, so", "// return the difficulty for the last block which did", "// not have the special minimum difficulty rule applied.", "prevBits", ",", "err", ":=", "b", ".", "findPrevTestNetDifficulty", "(", "hList", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "prevBits", ",", "nil", "\n", "}", "\n\n", "// For the main network (or any unrecognized networks), simply", "// return the previous block's difficulty requirements.", "return", "lastNode", ".", "Header", ".", "Bits", ",", "nil", "\n", "}", "\n\n", "// Get the block node at the previous retarget (targetTimespan days", "// worth of blocks).", "firstNode", ",", "err", ":=", "b", ".", "server", ".", "BlockHeaders", ".", "FetchHeaderByHeight", "(", "uint32", "(", "lastNode", ".", "Height", "+", "1", "-", "b", ".", "blocksPerRetarget", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "// Limit the amount of adjustment that can occur to the previous", "// difficulty.", "actualTimespan", ":=", "lastNode", ".", "Header", ".", "Timestamp", ".", "Unix", "(", ")", "-", "firstNode", ".", "Timestamp", ".", "Unix", "(", ")", "\n", "adjustedTimespan", ":=", "actualTimespan", "\n", "if", "actualTimespan", "<", "b", ".", "minRetargetTimespan", "{", "adjustedTimespan", "=", "b", ".", "minRetargetTimespan", "\n", "}", "else", "if", "actualTimespan", ">", "b", ".", "maxRetargetTimespan", "{", "adjustedTimespan", "=", "b", ".", "maxRetargetTimespan", "\n", "}", "\n\n", "// Calculate new target difficulty as:", "// currentDifficulty * (adjustedTimespan / targetTimespan)", "// The result uses integer division which means it will be slightly", "// rounded down. Bitcoind also uses integer division to calculate this", "// result.", "oldTarget", ":=", "blockchain", ".", "CompactToBig", "(", "lastNode", ".", "Header", ".", "Bits", ")", "\n", "newTarget", ":=", "new", "(", "big", ".", "Int", ")", ".", "Mul", "(", "oldTarget", ",", "big", ".", "NewInt", "(", "adjustedTimespan", ")", ")", "\n", "targetTimeSpan", ":=", "int64", "(", "b", ".", "server", ".", "chainParams", ".", "TargetTimespan", "/", "time", ".", "Second", ")", "\n", "newTarget", ".", "Div", "(", "newTarget", ",", "big", ".", "NewInt", "(", "targetTimeSpan", ")", ")", "\n\n", "// Limit new value to the proof of work limit.", "if", "newTarget", ".", "Cmp", "(", "b", ".", "server", ".", "chainParams", ".", "PowLimit", ")", ">", "0", "{", "newTarget", ".", "Set", "(", "b", ".", "server", ".", "chainParams", ".", "PowLimit", ")", "\n", "}", "\n\n", "// Log new target difficulty and return it. The new target logging is", "// intentionally converting the bits back to a number instead of using", "// newTarget since conversion to the compact representation loses", "// precision.", "newTargetBits", ":=", "blockchain", ".", "BigToCompact", "(", "newTarget", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "lastNode", ".", "Height", "+", "1", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "lastNode", ".", "Header", ".", "Bits", ",", "oldTarget", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "newTargetBits", ",", "blockchain", ".", "CompactToBig", "(", "newTargetBits", ")", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "time", ".", "Duration", "(", "actualTimespan", ")", "*", "time", ".", "Second", ",", "time", ".", "Duration", "(", "adjustedTimespan", ")", "*", "time", ".", "Second", ",", "b", ".", "server", ".", "chainParams", ".", "TargetTimespan", ")", "\n\n", "return", "newTargetBits", ",", "nil", "\n", "}" ]
// calcNextRequiredDifficulty calculates the required difficulty for the block // after the passed previous block node based on the difficulty retarget rules.
[ "calcNextRequiredDifficulty", "calculates", "the", "required", "difficulty", "for", "the", "block", "after", "the", "passed", "previous", "block", "node", "based", "on", "the", "difficulty", "retarget", "rules", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L2441-L2540
train
lightninglabs/neutrino
blockmanager.go
onBlockConnected
func (b *blockManager) onBlockConnected(header wire.BlockHeader, height uint32) { select { case b.blockNtfnChan <- blockntfns.NewBlockConnected(header, height): case <-b.quit: } }
go
func (b *blockManager) onBlockConnected(header wire.BlockHeader, height uint32) { select { case b.blockNtfnChan <- blockntfns.NewBlockConnected(header, height): case <-b.quit: } }
[ "func", "(", "b", "*", "blockManager", ")", "onBlockConnected", "(", "header", "wire", ".", "BlockHeader", ",", "height", "uint32", ")", "{", "select", "{", "case", "b", ".", "blockNtfnChan", "<-", "blockntfns", ".", "NewBlockConnected", "(", "header", ",", "height", ")", ":", "case", "<-", "b", ".", "quit", ":", "}", "\n", "}" ]
// onBlockConnected queues a block notification that extends the current chain.
[ "onBlockConnected", "queues", "a", "block", "notification", "that", "extends", "the", "current", "chain", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L2591-L2596
train
lightninglabs/neutrino
blockmanager.go
onBlockDisconnected
func (b *blockManager) onBlockDisconnected(headerDisconnected wire.BlockHeader, heightDisconnected uint32, newChainTip wire.BlockHeader) { select { case b.blockNtfnChan <- blockntfns.NewBlockDisconnected( headerDisconnected, heightDisconnected, newChainTip, ): case <-b.quit: } }
go
func (b *blockManager) onBlockDisconnected(headerDisconnected wire.BlockHeader, heightDisconnected uint32, newChainTip wire.BlockHeader) { select { case b.blockNtfnChan <- blockntfns.NewBlockDisconnected( headerDisconnected, heightDisconnected, newChainTip, ): case <-b.quit: } }
[ "func", "(", "b", "*", "blockManager", ")", "onBlockDisconnected", "(", "headerDisconnected", "wire", ".", "BlockHeader", ",", "heightDisconnected", "uint32", ",", "newChainTip", "wire", ".", "BlockHeader", ")", "{", "select", "{", "case", "b", ".", "blockNtfnChan", "<-", "blockntfns", ".", "NewBlockDisconnected", "(", "headerDisconnected", ",", "heightDisconnected", ",", "newChainTip", ",", ")", ":", "case", "<-", "b", ".", "quit", ":", "}", "\n", "}" ]
// onBlockDisconnected queues a block notification that reorgs the current // chain.
[ "onBlockDisconnected", "queues", "a", "block", "notification", "that", "reorgs", "the", "current", "chain", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L2600-L2609
train
lightninglabs/neutrino
blockmanager.go
NotificationsSinceHeight
func (b *blockManager) NotificationsSinceHeight( height uint32) ([]blockntfns.BlockNtfn, uint32, error) { b.newFilterHeadersMtx.RLock() defer b.newFilterHeadersMtx.RUnlock() bestHeight := b.filterHeaderTip // If a height of 0 is provided by the caller, then a backlog of // notifications is not needed. if height == 0 { return nil, bestHeight, nil } // If the best height matches the filter header tip, then we're done and // don't need to proceed any further. if bestHeight == height { return nil, bestHeight, nil } // If the request has a height later than a height we've yet to come // across in the chain, we'll return an error to indicate so to the // caller. if height > bestHeight { return nil, 0, fmt.Errorf("request with height %d is greater "+ "than best height known %d", height, bestHeight) } // Otherwise, we need to read block headers from disk to deliver a // backlog to the caller before we proceed. blocks := make([]blockntfns.BlockNtfn, 0, bestHeight-height) for i := height + 1; i <= bestHeight; i++ { header, err := b.server.BlockHeaders.FetchHeaderByHeight(i) if err != nil { return nil, 0, err } blocks = append(blocks, blockntfns.NewBlockConnected(*header, i)) } return blocks, bestHeight, nil }
go
func (b *blockManager) NotificationsSinceHeight( height uint32) ([]blockntfns.BlockNtfn, uint32, error) { b.newFilterHeadersMtx.RLock() defer b.newFilterHeadersMtx.RUnlock() bestHeight := b.filterHeaderTip // If a height of 0 is provided by the caller, then a backlog of // notifications is not needed. if height == 0 { return nil, bestHeight, nil } // If the best height matches the filter header tip, then we're done and // don't need to proceed any further. if bestHeight == height { return nil, bestHeight, nil } // If the request has a height later than a height we've yet to come // across in the chain, we'll return an error to indicate so to the // caller. if height > bestHeight { return nil, 0, fmt.Errorf("request with height %d is greater "+ "than best height known %d", height, bestHeight) } // Otherwise, we need to read block headers from disk to deliver a // backlog to the caller before we proceed. blocks := make([]blockntfns.BlockNtfn, 0, bestHeight-height) for i := height + 1; i <= bestHeight; i++ { header, err := b.server.BlockHeaders.FetchHeaderByHeight(i) if err != nil { return nil, 0, err } blocks = append(blocks, blockntfns.NewBlockConnected(*header, i)) } return blocks, bestHeight, nil }
[ "func", "(", "b", "*", "blockManager", ")", "NotificationsSinceHeight", "(", "height", "uint32", ")", "(", "[", "]", "blockntfns", ".", "BlockNtfn", ",", "uint32", ",", "error", ")", "{", "b", ".", "newFilterHeadersMtx", ".", "RLock", "(", ")", "\n", "defer", "b", ".", "newFilterHeadersMtx", ".", "RUnlock", "(", ")", "\n\n", "bestHeight", ":=", "b", ".", "filterHeaderTip", "\n\n", "// If a height of 0 is provided by the caller, then a backlog of", "// notifications is not needed.", "if", "height", "==", "0", "{", "return", "nil", ",", "bestHeight", ",", "nil", "\n", "}", "\n\n", "// If the best height matches the filter header tip, then we're done and", "// don't need to proceed any further.", "if", "bestHeight", "==", "height", "{", "return", "nil", ",", "bestHeight", ",", "nil", "\n", "}", "\n\n", "// If the request has a height later than a height we've yet to come", "// across in the chain, we'll return an error to indicate so to the", "// caller.", "if", "height", ">", "bestHeight", "{", "return", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "height", ",", "bestHeight", ")", "\n", "}", "\n\n", "// Otherwise, we need to read block headers from disk to deliver a", "// backlog to the caller before we proceed.", "blocks", ":=", "make", "(", "[", "]", "blockntfns", ".", "BlockNtfn", ",", "0", ",", "bestHeight", "-", "height", ")", "\n", "for", "i", ":=", "height", "+", "1", ";", "i", "<=", "bestHeight", ";", "i", "++", "{", "header", ",", "err", ":=", "b", ".", "server", ".", "BlockHeaders", ".", "FetchHeaderByHeight", "(", "i", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n\n", "blocks", "=", "append", "(", "blocks", ",", "blockntfns", ".", "NewBlockConnected", "(", "*", "header", ",", "i", ")", ")", "\n", "}", "\n\n", "return", "blocks", ",", "bestHeight", ",", "nil", "\n", "}" ]
// NotificationsSinceHeight returns a backlog of block notifications starting // from the given height to the tip of the chain. When providing a height of 0, // a backlog will not be delivered.
[ "NotificationsSinceHeight", "returns", "a", "backlog", "of", "block", "notifications", "starting", "from", "the", "given", "height", "to", "the", "tip", "of", "the", "chain", ".", "When", "providing", "a", "height", "of", "0", "a", "backlog", "will", "not", "be", "delivered", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L2620-L2661
train
lightninglabs/neutrino
cache/cacheable_filter.go
Size
func (c *CacheableFilter) Size() (uint64, error) { f, err := c.Filter.NBytes() if err != nil { return 0, err } return uint64(len(f)), nil }
go
func (c *CacheableFilter) Size() (uint64, error) { f, err := c.Filter.NBytes() if err != nil { return 0, err } return uint64(len(f)), nil }
[ "func", "(", "c", "*", "CacheableFilter", ")", "Size", "(", ")", "(", "uint64", ",", "error", ")", "{", "f", ",", "err", ":=", "c", ".", "Filter", ".", "NBytes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "uint64", "(", "len", "(", "f", ")", ")", ",", "nil", "\n", "}" ]
// Size returns size of this filter in bytes.
[ "Size", "returns", "size", "of", "this", "filter", "in", "bytes", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/cache/cacheable_filter.go#L22-L28
train
lightninglabs/neutrino
cache/lru/lru.go
NewCache
func NewCache(capacity uint64) *Cache { return &Cache{ capacity: capacity, ll: list.New(), cache: make(elementMap), } }
go
func NewCache(capacity uint64) *Cache { return &Cache{ capacity: capacity, ll: list.New(), cache: make(elementMap), } }
[ "func", "NewCache", "(", "capacity", "uint64", ")", "*", "Cache", "{", "return", "&", "Cache", "{", "capacity", ":", "capacity", ",", "ll", ":", "list", ".", "New", "(", ")", ",", "cache", ":", "make", "(", "elementMap", ")", ",", "}", "\n", "}" ]
// NewCache return a cache with specified capacity, the cache's size can't // exceed that given capacity.
[ "NewCache", "return", "a", "cache", "with", "specified", "capacity", "the", "cache", "s", "size", "can", "t", "exceed", "that", "given", "capacity", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/cache/lru/lru.go#L45-L51
train
lightninglabs/neutrino
cache/lru/lru.go
evict
func (c *Cache) evict(needed uint64) (bool, error) { if needed > c.capacity { return false, fmt.Errorf("can't evict %v elements in size, "+ "since capacity is %v", needed, c.capacity) } evicted := false for c.capacity-c.size < needed { // We still need to evict some more elements. if c.ll.Len() == 0 { // We should never reach here. return false, fmt.Errorf("all elements got evicted, "+ "yet still need to evict %v, likelihood of "+ "error during size calculation", needed-(c.capacity-c.size)) } // Find the least recently used item. if elr := c.ll.Back(); elr != nil { // Determine lru item's size. ce := elr.Value.(*entry) es, err := ce.value.Size() if err != nil { return false, fmt.Errorf("couldn't determine "+ "size of existing cache value %v", err) } // Account for that element's removal in evicted and // cache size. c.size -= es // Remove the element from the cache. c.ll.Remove(elr) delete(c.cache, ce.key) evicted = true } } return evicted, nil }
go
func (c *Cache) evict(needed uint64) (bool, error) { if needed > c.capacity { return false, fmt.Errorf("can't evict %v elements in size, "+ "since capacity is %v", needed, c.capacity) } evicted := false for c.capacity-c.size < needed { // We still need to evict some more elements. if c.ll.Len() == 0 { // We should never reach here. return false, fmt.Errorf("all elements got evicted, "+ "yet still need to evict %v, likelihood of "+ "error during size calculation", needed-(c.capacity-c.size)) } // Find the least recently used item. if elr := c.ll.Back(); elr != nil { // Determine lru item's size. ce := elr.Value.(*entry) es, err := ce.value.Size() if err != nil { return false, fmt.Errorf("couldn't determine "+ "size of existing cache value %v", err) } // Account for that element's removal in evicted and // cache size. c.size -= es // Remove the element from the cache. c.ll.Remove(elr) delete(c.cache, ce.key) evicted = true } } return evicted, nil }
[ "func", "(", "c", "*", "Cache", ")", "evict", "(", "needed", "uint64", ")", "(", "bool", ",", "error", ")", "{", "if", "needed", ">", "c", ".", "capacity", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "needed", ",", "c", ".", "capacity", ")", "\n", "}", "\n\n", "evicted", ":=", "false", "\n", "for", "c", ".", "capacity", "-", "c", ".", "size", "<", "needed", "{", "// We still need to evict some more elements.", "if", "c", ".", "ll", ".", "Len", "(", ")", "==", "0", "{", "// We should never reach here.", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "needed", "-", "(", "c", ".", "capacity", "-", "c", ".", "size", ")", ")", "\n", "}", "\n\n", "// Find the least recently used item.", "if", "elr", ":=", "c", ".", "ll", ".", "Back", "(", ")", ";", "elr", "!=", "nil", "{", "// Determine lru item's size.", "ce", ":=", "elr", ".", "Value", ".", "(", "*", "entry", ")", "\n", "es", ",", "err", ":=", "ce", ".", "value", ".", "Size", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Account for that element's removal in evicted and", "// cache size.", "c", ".", "size", "-=", "es", "\n\n", "// Remove the element from the cache.", "c", ".", "ll", ".", "Remove", "(", "elr", ")", "\n", "delete", "(", "c", ".", "cache", ",", "ce", ".", "key", ")", "\n", "evicted", "=", "true", "\n", "}", "\n", "}", "\n\n", "return", "evicted", ",", "nil", "\n", "}" ]
// evict will evict as many elements as necessary to make enough space for a new // element with size needed to be inserted.
[ "evict", "will", "evict", "as", "many", "elements", "as", "necessary", "to", "make", "enough", "space", "for", "a", "new", "element", "with", "size", "needed", "to", "be", "inserted", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/cache/lru/lru.go#L55-L94
train
lightninglabs/neutrino
cache/lru/lru.go
Get
func (c *Cache) Get(key interface{}) (cache.Value, error) { c.mtx.Lock() defer c.mtx.Unlock() el, ok := c.cache[key] if !ok { // Element not found in the cache. return nil, cache.ErrElementNotFound } // When the cache needs to evict a element to make space for another // one, it starts eviction from the back, so by moving this element to // the front, it's eviction is delayed because it's recently accessed. c.ll.MoveToFront(el) return el.Value.(*entry).value, nil }
go
func (c *Cache) Get(key interface{}) (cache.Value, error) { c.mtx.Lock() defer c.mtx.Unlock() el, ok := c.cache[key] if !ok { // Element not found in the cache. return nil, cache.ErrElementNotFound } // When the cache needs to evict a element to make space for another // one, it starts eviction from the back, so by moving this element to // the front, it's eviction is delayed because it's recently accessed. c.ll.MoveToFront(el) return el.Value.(*entry).value, nil }
[ "func", "(", "c", "*", "Cache", ")", "Get", "(", "key", "interface", "{", "}", ")", "(", "cache", ".", "Value", ",", "error", ")", "{", "c", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "el", ",", "ok", ":=", "c", ".", "cache", "[", "key", "]", "\n", "if", "!", "ok", "{", "// Element not found in the cache.", "return", "nil", ",", "cache", ".", "ErrElementNotFound", "\n", "}", "\n\n", "// When the cache needs to evict a element to make space for another", "// one, it starts eviction from the back, so by moving this element to", "// the front, it's eviction is delayed because it's recently accessed.", "c", ".", "ll", ".", "MoveToFront", "(", "el", ")", "\n", "return", "el", ".", "Value", ".", "(", "*", "entry", ")", ".", "value", ",", "nil", "\n", "}" ]
// Get will return value for a given key, making the element the most recently // accessed item in the process. Will return nil if the key isn't found.
[ "Get", "will", "return", "value", "for", "a", "given", "key", "making", "the", "element", "the", "most", "recently", "accessed", "item", "in", "the", "process", ".", "Will", "return", "nil", "if", "the", "key", "isn", "t", "found", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/cache/lru/lru.go#L144-L159
train
lightninglabs/neutrino
cache/lru/lru.go
Len
func (c *Cache) Len() int { c.mtx.RLock() defer c.mtx.RUnlock() return c.ll.Len() }
go
func (c *Cache) Len() int { c.mtx.RLock() defer c.mtx.RUnlock() return c.ll.Len() }
[ "func", "(", "c", "*", "Cache", ")", "Len", "(", ")", "int", "{", "c", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "return", "c", ".", "ll", ".", "Len", "(", ")", "\n", "}" ]
// Len returns number of elements in the cache.
[ "Len", "returns", "number", "of", "elements", "in", "the", "cache", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/cache/lru/lru.go#L162-L167
train
lightninglabs/neutrino
headerlist/bounded_header_list.go
NewBoundedMemoryChain
func NewBoundedMemoryChain(maxNodes uint32) *BoundedMemoryChain { return &BoundedMemoryChain{ headPtr: -1, tailPtr: -1, maxSize: int32(maxNodes), chain: make([]Node, maxNodes), } }
go
func NewBoundedMemoryChain(maxNodes uint32) *BoundedMemoryChain { return &BoundedMemoryChain{ headPtr: -1, tailPtr: -1, maxSize: int32(maxNodes), chain: make([]Node, maxNodes), } }
[ "func", "NewBoundedMemoryChain", "(", "maxNodes", "uint32", ")", "*", "BoundedMemoryChain", "{", "return", "&", "BoundedMemoryChain", "{", "headPtr", ":", "-", "1", ",", "tailPtr", ":", "-", "1", ",", "maxSize", ":", "int32", "(", "maxNodes", ")", ",", "chain", ":", "make", "(", "[", "]", "Node", ",", "maxNodes", ")", ",", "}", "\n", "}" ]
// NewBoundedMemoryChain returns a new instance of the BoundedMemoryChain with // a target max number of nodes.
[ "NewBoundedMemoryChain", "returns", "a", "new", "instance", "of", "the", "BoundedMemoryChain", "with", "a", "target", "max", "number", "of", "nodes", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerlist/bounded_header_list.go#L35-L42
train
lightninglabs/neutrino
pushtx/error.go
IsBroadcastError
func IsBroadcastError(err error, codes ...BroadcastErrorCode) bool { broadcastErr, ok := err.(*BroadcastError) if !ok { return false } for _, code := range codes { if broadcastErr.Code == code { return true } } return false }
go
func IsBroadcastError(err error, codes ...BroadcastErrorCode) bool { broadcastErr, ok := err.(*BroadcastError) if !ok { return false } for _, code := range codes { if broadcastErr.Code == code { return true } } return false }
[ "func", "IsBroadcastError", "(", "err", "error", ",", "codes", "...", "BroadcastErrorCode", ")", "bool", "{", "broadcastErr", ",", "ok", ":=", "err", ".", "(", "*", "BroadcastError", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "for", "_", ",", "code", ":=", "range", "codes", "{", "if", "broadcastErr", ".", "Code", "==", "code", "{", "return", "true", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// IsBroadcastError is a helper function that can be used to determine whether // an error is a BroadcastError that matches any of the specified codes.
[ "IsBroadcastError", "is", "a", "helper", "function", "that", "can", "be", "used", "to", "determine", "whether", "an", "error", "is", "a", "BroadcastError", "that", "matches", "any", "of", "the", "specified", "codes", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/pushtx/error.go#L72-L85
train
lightninglabs/neutrino
pushtx/error.go
ParseBroadcastError
func ParseBroadcastError(msg *wire.MsgReject, peerAddr string) *BroadcastError { // We'll determine the appropriate broadcast error code by looking at // the reject's message code and reason. The only reject codes returned // from peers (bitcoind and btcd) when attempting to accept a // transaction into their mempool are: // RejectInvalid, RejectNonstandard, RejectInsufficientFee, // RejectDuplicate var code BroadcastErrorCode switch { // The cases below apply for reject messages sent from any kind of peer. case msg.Code == wire.RejectInvalid || msg.Code == wire.RejectNonstandard: code = Invalid case msg.Code == wire.RejectInsufficientFee: code = InsufficientFee // The cases below apply for reject messages sent from bitcoind peers. // // If the transaction double spends an unconfirmed transaction in the // peer's mempool, then we'll deem it as invalid. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "txn-mempool-conflict"): code = Invalid // If the transaction was rejected due to it already existing in the // peer's mempool, then return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "txn-already-in-mempool"): code = Mempool // If the transaction was rejected due to it already existing in the // chain according to our peer, then we'll return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "txn-already-known"): code = Confirmed // The cases below apply for reject messages sent from btcd peers. // // If the transaction double spends an unconfirmed transaction in the // peer's mempool, then we'll deem it as invalid. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "already spent"): code = Invalid // If the transaction was rejected due to it already existing in the // peer's mempool, then return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "already have transaction"): code = Mempool // If the transaction was rejected due to it already existing in the // chain according to our peer, then we'll return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "transaction already exists"): code = Confirmed // Any other reject messages will use the unknown code. default: code = Unknown } reason := fmt.Sprintf("rejected by %v: %v", peerAddr, msg.Reason) return &BroadcastError{Code: code, Reason: reason} }
go
func ParseBroadcastError(msg *wire.MsgReject, peerAddr string) *BroadcastError { // We'll determine the appropriate broadcast error code by looking at // the reject's message code and reason. The only reject codes returned // from peers (bitcoind and btcd) when attempting to accept a // transaction into their mempool are: // RejectInvalid, RejectNonstandard, RejectInsufficientFee, // RejectDuplicate var code BroadcastErrorCode switch { // The cases below apply for reject messages sent from any kind of peer. case msg.Code == wire.RejectInvalid || msg.Code == wire.RejectNonstandard: code = Invalid case msg.Code == wire.RejectInsufficientFee: code = InsufficientFee // The cases below apply for reject messages sent from bitcoind peers. // // If the transaction double spends an unconfirmed transaction in the // peer's mempool, then we'll deem it as invalid. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "txn-mempool-conflict"): code = Invalid // If the transaction was rejected due to it already existing in the // peer's mempool, then return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "txn-already-in-mempool"): code = Mempool // If the transaction was rejected due to it already existing in the // chain according to our peer, then we'll return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "txn-already-known"): code = Confirmed // The cases below apply for reject messages sent from btcd peers. // // If the transaction double spends an unconfirmed transaction in the // peer's mempool, then we'll deem it as invalid. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "already spent"): code = Invalid // If the transaction was rejected due to it already existing in the // peer's mempool, then return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "already have transaction"): code = Mempool // If the transaction was rejected due to it already existing in the // chain according to our peer, then we'll return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "transaction already exists"): code = Confirmed // Any other reject messages will use the unknown code. default: code = Unknown } reason := fmt.Sprintf("rejected by %v: %v", peerAddr, msg.Reason) return &BroadcastError{Code: code, Reason: reason} }
[ "func", "ParseBroadcastError", "(", "msg", "*", "wire", ".", "MsgReject", ",", "peerAddr", "string", ")", "*", "BroadcastError", "{", "// We'll determine the appropriate broadcast error code by looking at", "// the reject's message code and reason. The only reject codes returned", "// from peers (bitcoind and btcd) when attempting to accept a", "// transaction into their mempool are:", "// RejectInvalid, RejectNonstandard, RejectInsufficientFee,", "// RejectDuplicate", "var", "code", "BroadcastErrorCode", "\n", "switch", "{", "// The cases below apply for reject messages sent from any kind of peer.", "case", "msg", ".", "Code", "==", "wire", ".", "RejectInvalid", "||", "msg", ".", "Code", "==", "wire", ".", "RejectNonstandard", ":", "code", "=", "Invalid", "\n\n", "case", "msg", ".", "Code", "==", "wire", ".", "RejectInsufficientFee", ":", "code", "=", "InsufficientFee", "\n\n", "// The cases below apply for reject messages sent from bitcoind peers.", "//", "// If the transaction double spends an unconfirmed transaction in the", "// peer's mempool, then we'll deem it as invalid.", "case", "msg", ".", "Code", "==", "wire", ".", "RejectDuplicate", "&&", "strings", ".", "Contains", "(", "msg", ".", "Reason", ",", "\"", "\"", ")", ":", "code", "=", "Invalid", "\n\n", "// If the transaction was rejected due to it already existing in the", "// peer's mempool, then return an error signaling so.", "case", "msg", ".", "Code", "==", "wire", ".", "RejectDuplicate", "&&", "strings", ".", "Contains", "(", "msg", ".", "Reason", ",", "\"", "\"", ")", ":", "code", "=", "Mempool", "\n\n", "// If the transaction was rejected due to it already existing in the", "// chain according to our peer, then we'll return an error signaling so.", "case", "msg", ".", "Code", "==", "wire", ".", "RejectDuplicate", "&&", "strings", ".", "Contains", "(", "msg", ".", "Reason", ",", "\"", "\"", ")", ":", "code", "=", "Confirmed", "\n\n", "// The cases below apply for reject messages sent from btcd peers.", "//", "// If the transaction double spends an unconfirmed transaction in the", "// peer's mempool, then we'll deem it as invalid.", "case", "msg", ".", "Code", "==", "wire", ".", "RejectDuplicate", "&&", "strings", ".", "Contains", "(", "msg", ".", "Reason", ",", "\"", "\"", ")", ":", "code", "=", "Invalid", "\n\n", "// If the transaction was rejected due to it already existing in the", "// peer's mempool, then return an error signaling so.", "case", "msg", ".", "Code", "==", "wire", ".", "RejectDuplicate", "&&", "strings", ".", "Contains", "(", "msg", ".", "Reason", ",", "\"", "\"", ")", ":", "code", "=", "Mempool", "\n\n", "// If the transaction was rejected due to it already existing in the", "// chain according to our peer, then we'll return an error signaling so.", "case", "msg", ".", "Code", "==", "wire", ".", "RejectDuplicate", "&&", "strings", ".", "Contains", "(", "msg", ".", "Reason", ",", "\"", "\"", ")", ":", "code", "=", "Confirmed", "\n\n", "// Any other reject messages will use the unknown code.", "default", ":", "code", "=", "Unknown", "\n", "}", "\n\n", "reason", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "peerAddr", ",", "msg", ".", "Reason", ")", "\n", "return", "&", "BroadcastError", "{", "Code", ":", "code", ",", "Reason", ":", "reason", "}", "\n", "}" ]
// ParseBroadcastError maps a peer's reject message for a transaction to a // BroadcastError.
[ "ParseBroadcastError", "maps", "a", "peer", "s", "reject", "message", "for", "a", "transaction", "to", "a", "BroadcastError", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/pushtx/error.go#L89-L152
train
lightninglabs/neutrino
filterdb/db.go
New
func New(db walletdb.DB, params chaincfg.Params) (*FilterStore, error) { err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error { // As part of our initial setup, we'll try to create the top // level filter bucket. If this already exists, then we can // exit early. filters, err := tx.CreateTopLevelBucket(filterBucket) if err != nil { return err } // If the main bucket doesn't already exist, then we'll need to // create the sub-buckets, and also initialize them with the // genesis filters. genesisBlock := params.GenesisBlock genesisHash := params.GenesisHash // First we'll create the bucket for the regular filters. regFilters, err := filters.CreateBucketIfNotExists(regBucket) if err != nil { return err } // With the bucket created, we'll now construct the initial // basic genesis filter and store it within the database. basicFilter, err := builder.BuildBasicFilter(genesisBlock, nil) if err != nil { return err } return putFilter(regFilters, genesisHash, basicFilter) }) if err != nil && err != walletdb.ErrBucketExists { return nil, err } return &FilterStore{ db: db, }, nil }
go
func New(db walletdb.DB, params chaincfg.Params) (*FilterStore, error) { err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error { // As part of our initial setup, we'll try to create the top // level filter bucket. If this already exists, then we can // exit early. filters, err := tx.CreateTopLevelBucket(filterBucket) if err != nil { return err } // If the main bucket doesn't already exist, then we'll need to // create the sub-buckets, and also initialize them with the // genesis filters. genesisBlock := params.GenesisBlock genesisHash := params.GenesisHash // First we'll create the bucket for the regular filters. regFilters, err := filters.CreateBucketIfNotExists(regBucket) if err != nil { return err } // With the bucket created, we'll now construct the initial // basic genesis filter and store it within the database. basicFilter, err := builder.BuildBasicFilter(genesisBlock, nil) if err != nil { return err } return putFilter(regFilters, genesisHash, basicFilter) }) if err != nil && err != walletdb.ErrBucketExists { return nil, err } return &FilterStore{ db: db, }, nil }
[ "func", "New", "(", "db", "walletdb", ".", "DB", ",", "params", "chaincfg", ".", "Params", ")", "(", "*", "FilterStore", ",", "error", ")", "{", "err", ":=", "walletdb", ".", "Update", "(", "db", ",", "func", "(", "tx", "walletdb", ".", "ReadWriteTx", ")", "error", "{", "// As part of our initial setup, we'll try to create the top", "// level filter bucket. If this already exists, then we can", "// exit early.", "filters", ",", "err", ":=", "tx", ".", "CreateTopLevelBucket", "(", "filterBucket", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// If the main bucket doesn't already exist, then we'll need to", "// create the sub-buckets, and also initialize them with the", "// genesis filters.", "genesisBlock", ":=", "params", ".", "GenesisBlock", "\n", "genesisHash", ":=", "params", ".", "GenesisHash", "\n\n", "// First we'll create the bucket for the regular filters.", "regFilters", ",", "err", ":=", "filters", ".", "CreateBucketIfNotExists", "(", "regBucket", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// With the bucket created, we'll now construct the initial", "// basic genesis filter and store it within the database.", "basicFilter", ",", "err", ":=", "builder", ".", "BuildBasicFilter", "(", "genesisBlock", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "putFilter", "(", "regFilters", ",", "genesisHash", ",", "basicFilter", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "walletdb", ".", "ErrBucketExists", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "FilterStore", "{", "db", ":", "db", ",", "}", ",", "nil", "\n", "}" ]
// New creates a new instance of the FilterStore given an already open // database, and the target chain parameters.
[ "New", "creates", "a", "new", "instance", "of", "the", "FilterStore", "given", "an", "already", "open", "database", "and", "the", "target", "chain", "parameters", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/filterdb/db.go#L70-L108
train
lightninglabs/neutrino
filterdb/db.go
putFilter
func putFilter(bucket walletdb.ReadWriteBucket, hash *chainhash.Hash, filter *gcs.Filter) error { if filter == nil { return bucket.Put(hash[:], nil) } bytes, err := filter.NBytes() if err != nil { return err } return bucket.Put(hash[:], bytes) }
go
func putFilter(bucket walletdb.ReadWriteBucket, hash *chainhash.Hash, filter *gcs.Filter) error { if filter == nil { return bucket.Put(hash[:], nil) } bytes, err := filter.NBytes() if err != nil { return err } return bucket.Put(hash[:], bytes) }
[ "func", "putFilter", "(", "bucket", "walletdb", ".", "ReadWriteBucket", ",", "hash", "*", "chainhash", ".", "Hash", ",", "filter", "*", "gcs", ".", "Filter", ")", "error", "{", "if", "filter", "==", "nil", "{", "return", "bucket", ".", "Put", "(", "hash", "[", ":", "]", ",", "nil", ")", "\n", "}", "\n\n", "bytes", ",", "err", ":=", "filter", ".", "NBytes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "bucket", ".", "Put", "(", "hash", "[", ":", "]", ",", "bytes", ")", "\n", "}" ]
// putFilter stores a filter in the database according to the corresponding // block hash. The passed bucket is expected to be the proper bucket for the // passed filter type.
[ "putFilter", "stores", "a", "filter", "in", "the", "database", "according", "to", "the", "corresponding", "block", "hash", ".", "The", "passed", "bucket", "is", "expected", "to", "be", "the", "proper", "bucket", "for", "the", "passed", "filter", "type", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/filterdb/db.go#L113-L126
train
lightninglabs/neutrino
headerfs/store.go
newHeaderStore
func newHeaderStore(db walletdb.DB, filePath string, hType HeaderType) (*headerStore, error) { var flatFileName string switch hType { case Block: flatFileName = "block_headers.bin" case RegularFilter: flatFileName = "reg_filter_headers.bin" default: return nil, fmt.Errorf("unrecognized filter type: %v", hType) } flatFileName = filepath.Join(filePath, flatFileName) // We'll open the file, creating it if necessary and ensuring that all // writes are actually appends to the end of the file. fileFlags := os.O_RDWR | os.O_APPEND | os.O_CREATE headerFile, err := os.OpenFile(flatFileName, fileFlags, 0644) if err != nil { return nil, err } // With the file open, we'll then create the header index so we can // have random access into the flat files. index, err := newHeaderIndex(db, hType) if err != nil { return nil, err } return &headerStore{ filePath: filePath, file: headerFile, headerIndex: index, }, nil }
go
func newHeaderStore(db walletdb.DB, filePath string, hType HeaderType) (*headerStore, error) { var flatFileName string switch hType { case Block: flatFileName = "block_headers.bin" case RegularFilter: flatFileName = "reg_filter_headers.bin" default: return nil, fmt.Errorf("unrecognized filter type: %v", hType) } flatFileName = filepath.Join(filePath, flatFileName) // We'll open the file, creating it if necessary and ensuring that all // writes are actually appends to the end of the file. fileFlags := os.O_RDWR | os.O_APPEND | os.O_CREATE headerFile, err := os.OpenFile(flatFileName, fileFlags, 0644) if err != nil { return nil, err } // With the file open, we'll then create the header index so we can // have random access into the flat files. index, err := newHeaderIndex(db, hType) if err != nil { return nil, err } return &headerStore{ filePath: filePath, file: headerFile, headerIndex: index, }, nil }
[ "func", "newHeaderStore", "(", "db", "walletdb", ".", "DB", ",", "filePath", "string", ",", "hType", "HeaderType", ")", "(", "*", "headerStore", ",", "error", ")", "{", "var", "flatFileName", "string", "\n", "switch", "hType", "{", "case", "Block", ":", "flatFileName", "=", "\"", "\"", "\n", "case", "RegularFilter", ":", "flatFileName", "=", "\"", "\"", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hType", ")", "\n", "}", "\n\n", "flatFileName", "=", "filepath", ".", "Join", "(", "filePath", ",", "flatFileName", ")", "\n\n", "// We'll open the file, creating it if necessary and ensuring that all", "// writes are actually appends to the end of the file.", "fileFlags", ":=", "os", ".", "O_RDWR", "|", "os", ".", "O_APPEND", "|", "os", ".", "O_CREATE", "\n", "headerFile", ",", "err", ":=", "os", ".", "OpenFile", "(", "flatFileName", ",", "fileFlags", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// With the file open, we'll then create the header index so we can", "// have random access into the flat files.", "index", ",", "err", ":=", "newHeaderIndex", "(", "db", ",", "hType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "headerStore", "{", "filePath", ":", "filePath", ",", "file", ":", "headerFile", ",", "headerIndex", ":", "index", ",", "}", ",", "nil", "\n", "}" ]
// newHeaderStore creates a new headerStore given an already open database, a // target file path for the flat-file and a particular header type. The target // file will be created as necessary.
[ "newHeaderStore", "creates", "a", "new", "headerStore", "given", "an", "already", "open", "database", "a", "target", "file", "path", "for", "the", "flat", "-", "file", "and", "a", "particular", "header", "type", ".", "The", "target", "file", "will", "be", "created", "as", "necessary", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L94-L129
train
lightninglabs/neutrino
headerfs/store.go
NewBlockHeaderStore
func NewBlockHeaderStore(filePath string, db walletdb.DB, netParams *chaincfg.Params) (BlockHeaderStore, error) { hStore, err := newHeaderStore(db, filePath, Block) if err != nil { return nil, err } // With the header store created, we'll fetch the file size to see if // we need to initialize it with the first header or not. fileInfo, err := hStore.file.Stat() if err != nil { return nil, err } bhs := &blockHeaderStore{ headerStore: hStore, } // If the size of the file is zero, then this means that we haven't yet // written the initial genesis header to disk, so we'll do so now. if fileInfo.Size() == 0 { genesisHeader := BlockHeader{ BlockHeader: &netParams.GenesisBlock.Header, Height: 0, } if err := bhs.WriteHeaders(genesisHeader); err != nil { return nil, err } return bhs, nil } // As a final initialization step (if this isn't the first time), we'll // ensure that the header tip within the flat files, is in sync with // out database index. tipHash, tipHeight, err := bhs.chainTip() if err != nil { return nil, err } // First, we'll compute the size of the current file so we can // calculate the latest header written to disk. fileHeight := uint32(fileInfo.Size()/80) - 1 // Using the file's current height, fetch the latest on-disk header. latestFileHeader, err := bhs.readHeader(fileHeight) if err != nil { return nil, err } // If the index's tip hash, and the file on-disk match, then we're // done here. latestBlockHash := latestFileHeader.BlockHash() if tipHash.IsEqual(&latestBlockHash) { return bhs, nil } // TODO(roasbeef): below assumes index can never get ahead? // * we always update files _then_ indexes // * need to dual pointer walk back for max safety // Otherwise, we'll need to truncate the file until it matches the // current index tip. for fileHeight > tipHeight { if err := bhs.singleTruncate(); err != nil { return nil, err } fileHeight-- } return bhs, nil }
go
func NewBlockHeaderStore(filePath string, db walletdb.DB, netParams *chaincfg.Params) (BlockHeaderStore, error) { hStore, err := newHeaderStore(db, filePath, Block) if err != nil { return nil, err } // With the header store created, we'll fetch the file size to see if // we need to initialize it with the first header or not. fileInfo, err := hStore.file.Stat() if err != nil { return nil, err } bhs := &blockHeaderStore{ headerStore: hStore, } // If the size of the file is zero, then this means that we haven't yet // written the initial genesis header to disk, so we'll do so now. if fileInfo.Size() == 0 { genesisHeader := BlockHeader{ BlockHeader: &netParams.GenesisBlock.Header, Height: 0, } if err := bhs.WriteHeaders(genesisHeader); err != nil { return nil, err } return bhs, nil } // As a final initialization step (if this isn't the first time), we'll // ensure that the header tip within the flat files, is in sync with // out database index. tipHash, tipHeight, err := bhs.chainTip() if err != nil { return nil, err } // First, we'll compute the size of the current file so we can // calculate the latest header written to disk. fileHeight := uint32(fileInfo.Size()/80) - 1 // Using the file's current height, fetch the latest on-disk header. latestFileHeader, err := bhs.readHeader(fileHeight) if err != nil { return nil, err } // If the index's tip hash, and the file on-disk match, then we're // done here. latestBlockHash := latestFileHeader.BlockHash() if tipHash.IsEqual(&latestBlockHash) { return bhs, nil } // TODO(roasbeef): below assumes index can never get ahead? // * we always update files _then_ indexes // * need to dual pointer walk back for max safety // Otherwise, we'll need to truncate the file until it matches the // current index tip. for fileHeight > tipHeight { if err := bhs.singleTruncate(); err != nil { return nil, err } fileHeight-- } return bhs, nil }
[ "func", "NewBlockHeaderStore", "(", "filePath", "string", ",", "db", "walletdb", ".", "DB", ",", "netParams", "*", "chaincfg", ".", "Params", ")", "(", "BlockHeaderStore", ",", "error", ")", "{", "hStore", ",", "err", ":=", "newHeaderStore", "(", "db", ",", "filePath", ",", "Block", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// With the header store created, we'll fetch the file size to see if", "// we need to initialize it with the first header or not.", "fileInfo", ",", "err", ":=", "hStore", ".", "file", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "bhs", ":=", "&", "blockHeaderStore", "{", "headerStore", ":", "hStore", ",", "}", "\n\n", "// If the size of the file is zero, then this means that we haven't yet", "// written the initial genesis header to disk, so we'll do so now.", "if", "fileInfo", ".", "Size", "(", ")", "==", "0", "{", "genesisHeader", ":=", "BlockHeader", "{", "BlockHeader", ":", "&", "netParams", ".", "GenesisBlock", ".", "Header", ",", "Height", ":", "0", ",", "}", "\n", "if", "err", ":=", "bhs", ".", "WriteHeaders", "(", "genesisHeader", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "bhs", ",", "nil", "\n", "}", "\n\n", "// As a final initialization step (if this isn't the first time), we'll", "// ensure that the header tip within the flat files, is in sync with", "// out database index.", "tipHash", ",", "tipHeight", ",", "err", ":=", "bhs", ".", "chainTip", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// First, we'll compute the size of the current file so we can", "// calculate the latest header written to disk.", "fileHeight", ":=", "uint32", "(", "fileInfo", ".", "Size", "(", ")", "/", "80", ")", "-", "1", "\n\n", "// Using the file's current height, fetch the latest on-disk header.", "latestFileHeader", ",", "err", ":=", "bhs", ".", "readHeader", "(", "fileHeight", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// If the index's tip hash, and the file on-disk match, then we're", "// done here.", "latestBlockHash", ":=", "latestFileHeader", ".", "BlockHash", "(", ")", "\n", "if", "tipHash", ".", "IsEqual", "(", "&", "latestBlockHash", ")", "{", "return", "bhs", ",", "nil", "\n", "}", "\n\n", "// TODO(roasbeef): below assumes index can never get ahead?", "// * we always update files _then_ indexes", "// * need to dual pointer walk back for max safety", "// Otherwise, we'll need to truncate the file until it matches the", "// current index tip.", "for", "fileHeight", ">", "tipHeight", "{", "if", "err", ":=", "bhs", ".", "singleTruncate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "fileHeight", "--", "\n", "}", "\n\n", "return", "bhs", ",", "nil", "\n", "}" ]
// NewBlockHeaderStore creates a new instance of the blockHeaderStore based on // a target file path, an open database instance, and finally a set of // parameters for the target chain. These parameters are required as if this is // the initial start up of the blockHeaderStore, then the initial genesis // header will need to be inserted.
[ "NewBlockHeaderStore", "creates", "a", "new", "instance", "of", "the", "blockHeaderStore", "based", "on", "a", "target", "file", "path", "an", "open", "database", "instance", "and", "finally", "a", "set", "of", "parameters", "for", "the", "target", "chain", ".", "These", "parameters", "are", "required", "as", "if", "this", "is", "the", "initial", "start", "up", "of", "the", "blockHeaderStore", "then", "the", "initial", "genesis", "header", "will", "need", "to", "be", "inserted", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L148-L221
train
lightninglabs/neutrino
headerfs/store.go
toIndexEntry
func (b *BlockHeader) toIndexEntry() headerEntry { return headerEntry{ hash: b.BlockHash(), height: b.Height, } }
go
func (b *BlockHeader) toIndexEntry() headerEntry { return headerEntry{ hash: b.BlockHash(), height: b.Height, } }
[ "func", "(", "b", "*", "BlockHeader", ")", "toIndexEntry", "(", ")", "headerEntry", "{", "return", "headerEntry", "{", "hash", ":", "b", ".", "BlockHash", "(", ")", ",", "height", ":", "b", ".", "Height", ",", "}", "\n", "}" ]
// toIndexEntry converts the BlockHeader into a matching headerEntry. This // method is used when a header is to be written to disk.
[ "toIndexEntry", "converts", "the", "BlockHeader", "into", "a", "matching", "headerEntry", ".", "This", "method", "is", "used", "when", "a", "header", "is", "to", "be", "written", "to", "disk", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L356-L361
train
lightninglabs/neutrino
headerfs/store.go
BlockLocatorFromHash
func (h *blockHeaderStore) BlockLocatorFromHash(hash *chainhash.Hash) ( blockchain.BlockLocator, error) { // Lock store for read. h.mtx.RLock() defer h.mtx.RUnlock() return h.blockLocatorFromHash(hash) }
go
func (h *blockHeaderStore) BlockLocatorFromHash(hash *chainhash.Hash) ( blockchain.BlockLocator, error) { // Lock store for read. h.mtx.RLock() defer h.mtx.RUnlock() return h.blockLocatorFromHash(hash) }
[ "func", "(", "h", "*", "blockHeaderStore", ")", "BlockLocatorFromHash", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "blockchain", ".", "BlockLocator", ",", "error", ")", "{", "// Lock store for read.", "h", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "h", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "return", "h", ".", "blockLocatorFromHash", "(", "hash", ")", "\n", "}" ]
// BlockLocatorFromHash computes a block locator given a particular hash. The // standard Bitcoin algorithm to compute block locators are employed.
[ "BlockLocatorFromHash", "computes", "a", "block", "locator", "given", "a", "particular", "hash", ".", "The", "standard", "Bitcoin", "algorithm", "to", "compute", "block", "locators", "are", "employed", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L472-L480
train
lightninglabs/neutrino
headerfs/store.go
CheckConnectivity
func (h *blockHeaderStore) CheckConnectivity() error { // Lock store for read. h.mtx.RLock() defer h.mtx.RUnlock() return walletdb.View(h.db, func(tx walletdb.ReadTx) error { // First, we'll fetch the root bucket, in order to use that to // fetch the bucket that houses the header index. rootBucket := tx.ReadBucket(indexBucket) // With the header bucket retrieved, we'll now fetch the chain // tip so we can start our backwards scan. tipHash := rootBucket.Get(bitcoinTip) tipHeightBytes := rootBucket.Get(tipHash) // With the height extracted, we'll now read the _last_ block // header within the file before we kick off our connectivity // loop. tipHeight := binary.BigEndian.Uint32(tipHeightBytes) header, err := h.readHeader(tipHeight) if err != nil { return err } // We'll now cycle backwards, seeking backwards along the // header file to ensure each header connects properly and the // index entries are also accurate. To do this, we start from a // height of one before our current tip. var newHeader wire.BlockHeader for height := tipHeight - 1; height > 0; height-- { // First, read the block header for this block height, // and also compute the block hash for it. newHeader, err = h.readHeader(height) if err != nil { return fmt.Errorf("Couldn't retrieve header %s:"+ " %s", header.PrevBlock, err) } newHeaderHash := newHeader.BlockHash() // With the header retrieved, we'll now fetch the // height for this current header hash to ensure the // on-disk state and the index matches up properly. indexHeightBytes := rootBucket.Get(newHeaderHash[:]) if indexHeightBytes == nil { return fmt.Errorf("index and on-disk file out of sync "+ "at height: %v", height) } indexHeight := binary.BigEndian.Uint32(indexHeightBytes) // With the index entry retrieved, we'll now assert // that the height matches up with our current height // in this backwards walk. if indexHeight != height { return fmt.Errorf("index height isn't monotonically " + "increasing") } // Finally, we'll assert that this new header is // actually the prev header of the target header from // the last loop. This ensures connectivity. if newHeader.BlockHash() != header.PrevBlock { return fmt.Errorf("Block %s doesn't match "+ "block %s's PrevBlock (%s)", newHeader.BlockHash(), header.BlockHash(), header.PrevBlock) } // As all the checks have passed, we'll now reset our // header pointer to this current location, and // continue our backwards walk. header = newHeader } return nil }) }
go
func (h *blockHeaderStore) CheckConnectivity() error { // Lock store for read. h.mtx.RLock() defer h.mtx.RUnlock() return walletdb.View(h.db, func(tx walletdb.ReadTx) error { // First, we'll fetch the root bucket, in order to use that to // fetch the bucket that houses the header index. rootBucket := tx.ReadBucket(indexBucket) // With the header bucket retrieved, we'll now fetch the chain // tip so we can start our backwards scan. tipHash := rootBucket.Get(bitcoinTip) tipHeightBytes := rootBucket.Get(tipHash) // With the height extracted, we'll now read the _last_ block // header within the file before we kick off our connectivity // loop. tipHeight := binary.BigEndian.Uint32(tipHeightBytes) header, err := h.readHeader(tipHeight) if err != nil { return err } // We'll now cycle backwards, seeking backwards along the // header file to ensure each header connects properly and the // index entries are also accurate. To do this, we start from a // height of one before our current tip. var newHeader wire.BlockHeader for height := tipHeight - 1; height > 0; height-- { // First, read the block header for this block height, // and also compute the block hash for it. newHeader, err = h.readHeader(height) if err != nil { return fmt.Errorf("Couldn't retrieve header %s:"+ " %s", header.PrevBlock, err) } newHeaderHash := newHeader.BlockHash() // With the header retrieved, we'll now fetch the // height for this current header hash to ensure the // on-disk state and the index matches up properly. indexHeightBytes := rootBucket.Get(newHeaderHash[:]) if indexHeightBytes == nil { return fmt.Errorf("index and on-disk file out of sync "+ "at height: %v", height) } indexHeight := binary.BigEndian.Uint32(indexHeightBytes) // With the index entry retrieved, we'll now assert // that the height matches up with our current height // in this backwards walk. if indexHeight != height { return fmt.Errorf("index height isn't monotonically " + "increasing") } // Finally, we'll assert that this new header is // actually the prev header of the target header from // the last loop. This ensures connectivity. if newHeader.BlockHash() != header.PrevBlock { return fmt.Errorf("Block %s doesn't match "+ "block %s's PrevBlock (%s)", newHeader.BlockHash(), header.BlockHash(), header.PrevBlock) } // As all the checks have passed, we'll now reset our // header pointer to this current location, and // continue our backwards walk. header = newHeader } return nil }) }
[ "func", "(", "h", "*", "blockHeaderStore", ")", "CheckConnectivity", "(", ")", "error", "{", "// Lock store for read.", "h", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "h", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "return", "walletdb", ".", "View", "(", "h", ".", "db", ",", "func", "(", "tx", "walletdb", ".", "ReadTx", ")", "error", "{", "// First, we'll fetch the root bucket, in order to use that to", "// fetch the bucket that houses the header index.", "rootBucket", ":=", "tx", ".", "ReadBucket", "(", "indexBucket", ")", "\n\n", "// With the header bucket retrieved, we'll now fetch the chain", "// tip so we can start our backwards scan.", "tipHash", ":=", "rootBucket", ".", "Get", "(", "bitcoinTip", ")", "\n", "tipHeightBytes", ":=", "rootBucket", ".", "Get", "(", "tipHash", ")", "\n\n", "// With the height extracted, we'll now read the _last_ block", "// header within the file before we kick off our connectivity", "// loop.", "tipHeight", ":=", "binary", ".", "BigEndian", ".", "Uint32", "(", "tipHeightBytes", ")", "\n", "header", ",", "err", ":=", "h", ".", "readHeader", "(", "tipHeight", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// We'll now cycle backwards, seeking backwards along the", "// header file to ensure each header connects properly and the", "// index entries are also accurate. To do this, we start from a", "// height of one before our current tip.", "var", "newHeader", "wire", ".", "BlockHeader", "\n", "for", "height", ":=", "tipHeight", "-", "1", ";", "height", ">", "0", ";", "height", "--", "{", "// First, read the block header for this block height,", "// and also compute the block hash for it.", "newHeader", ",", "err", "=", "h", ".", "readHeader", "(", "height", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "header", ".", "PrevBlock", ",", "err", ")", "\n", "}", "\n", "newHeaderHash", ":=", "newHeader", ".", "BlockHash", "(", ")", "\n\n", "// With the header retrieved, we'll now fetch the", "// height for this current header hash to ensure the", "// on-disk state and the index matches up properly.", "indexHeightBytes", ":=", "rootBucket", ".", "Get", "(", "newHeaderHash", "[", ":", "]", ")", "\n", "if", "indexHeightBytes", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "height", ")", "\n", "}", "\n", "indexHeight", ":=", "binary", ".", "BigEndian", ".", "Uint32", "(", "indexHeightBytes", ")", "\n\n", "// With the index entry retrieved, we'll now assert", "// that the height matches up with our current height", "// in this backwards walk.", "if", "indexHeight", "!=", "height", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "// Finally, we'll assert that this new header is", "// actually the prev header of the target header from", "// the last loop. This ensures connectivity.", "if", "newHeader", ".", "BlockHash", "(", ")", "!=", "header", ".", "PrevBlock", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "newHeader", ".", "BlockHash", "(", ")", ",", "header", ".", "BlockHash", "(", ")", ",", "header", ".", "PrevBlock", ")", "\n", "}", "\n\n", "// As all the checks have passed, we'll now reset our", "// header pointer to this current location, and", "// continue our backwards walk.", "header", "=", "newHeader", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// CheckConnectivity cycles through all of the block headers on disk, from last // to first, and makes sure they all connect to each other. Additionally, at // each block header, we also ensure that the index entry for that height and // hash also match up properly.
[ "CheckConnectivity", "cycles", "through", "all", "of", "the", "block", "headers", "on", "disk", "from", "last", "to", "first", "and", "makes", "sure", "they", "all", "connect", "to", "each", "other", ".", "Additionally", "at", "each", "block", "header", "we", "also", "ensure", "that", "the", "index", "entry", "for", "that", "height", "and", "hash", "also", "match", "up", "properly", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L486-L561
train
lightninglabs/neutrino
headerfs/store.go
NewFilterHeaderStore
func NewFilterHeaderStore(filePath string, db walletdb.DB, filterType HeaderType, netParams *chaincfg.Params) (*FilterHeaderStore, error) { fStore, err := newHeaderStore(db, filePath, filterType) if err != nil { return nil, err } // With the header store created, we'll fetch the fiie size to see if // we need to initialize it with the first header or not. fileInfo, err := fStore.file.Stat() if err != nil { return nil, err } fhs := &FilterHeaderStore{ fStore, } // TODO(roasbeef): also reconsile with block header state due to way // roll back works atm // If the size of the file is zero, then this means that we haven't yet // written the initial genesis header to disk, so we'll do so now. if fileInfo.Size() == 0 { var genesisFilterHash chainhash.Hash switch filterType { case RegularFilter: basicFilter, err := builder.BuildBasicFilter( netParams.GenesisBlock, nil, ) if err != nil { return nil, err } genesisFilterHash, err = builder.MakeHeaderForFilter( basicFilter, netParams.GenesisBlock.Header.PrevBlock, ) if err != nil { return nil, err } default: return nil, fmt.Errorf("unknown filter type: %v", filterType) } genesisHeader := FilterHeader{ HeaderHash: *netParams.GenesisHash, FilterHash: genesisFilterHash, Height: 0, } if err := fhs.WriteHeaders(genesisHeader); err != nil { return nil, err } return fhs, nil } // As a final initialization step, we'll ensure that the header tip // within the flat files, is in sync with out database index. tipHash, tipHeight, err := fhs.chainTip() if err != nil { return nil, err } // First, we'll compute the size of the current file so we can // calculate the latest header written to disk. fileHeight := uint32(fileInfo.Size()/32) - 1 // Using the file's current height, fetch the latest on-disk header. latestFileHeader, err := fhs.readHeader(fileHeight) if err != nil { return nil, err } // If the index's tip hash, and the file on-disk match, then we're // doing here. if tipHash.IsEqual(latestFileHeader) { return fhs, nil } // Otherwise, we'll need to truncate the file until it matches the // current index tip. for fileHeight > tipHeight { if err := fhs.singleTruncate(); err != nil { return nil, err } fileHeight-- } // TODO(roasbeef): make above into func return fhs, nil }
go
func NewFilterHeaderStore(filePath string, db walletdb.DB, filterType HeaderType, netParams *chaincfg.Params) (*FilterHeaderStore, error) { fStore, err := newHeaderStore(db, filePath, filterType) if err != nil { return nil, err } // With the header store created, we'll fetch the fiie size to see if // we need to initialize it with the first header or not. fileInfo, err := fStore.file.Stat() if err != nil { return nil, err } fhs := &FilterHeaderStore{ fStore, } // TODO(roasbeef): also reconsile with block header state due to way // roll back works atm // If the size of the file is zero, then this means that we haven't yet // written the initial genesis header to disk, so we'll do so now. if fileInfo.Size() == 0 { var genesisFilterHash chainhash.Hash switch filterType { case RegularFilter: basicFilter, err := builder.BuildBasicFilter( netParams.GenesisBlock, nil, ) if err != nil { return nil, err } genesisFilterHash, err = builder.MakeHeaderForFilter( basicFilter, netParams.GenesisBlock.Header.PrevBlock, ) if err != nil { return nil, err } default: return nil, fmt.Errorf("unknown filter type: %v", filterType) } genesisHeader := FilterHeader{ HeaderHash: *netParams.GenesisHash, FilterHash: genesisFilterHash, Height: 0, } if err := fhs.WriteHeaders(genesisHeader); err != nil { return nil, err } return fhs, nil } // As a final initialization step, we'll ensure that the header tip // within the flat files, is in sync with out database index. tipHash, tipHeight, err := fhs.chainTip() if err != nil { return nil, err } // First, we'll compute the size of the current file so we can // calculate the latest header written to disk. fileHeight := uint32(fileInfo.Size()/32) - 1 // Using the file's current height, fetch the latest on-disk header. latestFileHeader, err := fhs.readHeader(fileHeight) if err != nil { return nil, err } // If the index's tip hash, and the file on-disk match, then we're // doing here. if tipHash.IsEqual(latestFileHeader) { return fhs, nil } // Otherwise, we'll need to truncate the file until it matches the // current index tip. for fileHeight > tipHeight { if err := fhs.singleTruncate(); err != nil { return nil, err } fileHeight-- } // TODO(roasbeef): make above into func return fhs, nil }
[ "func", "NewFilterHeaderStore", "(", "filePath", "string", ",", "db", "walletdb", ".", "DB", ",", "filterType", "HeaderType", ",", "netParams", "*", "chaincfg", ".", "Params", ")", "(", "*", "FilterHeaderStore", ",", "error", ")", "{", "fStore", ",", "err", ":=", "newHeaderStore", "(", "db", ",", "filePath", ",", "filterType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// With the header store created, we'll fetch the fiie size to see if", "// we need to initialize it with the first header or not.", "fileInfo", ",", "err", ":=", "fStore", ".", "file", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "fhs", ":=", "&", "FilterHeaderStore", "{", "fStore", ",", "}", "\n\n", "// TODO(roasbeef): also reconsile with block header state due to way", "// roll back works atm", "// If the size of the file is zero, then this means that we haven't yet", "// written the initial genesis header to disk, so we'll do so now.", "if", "fileInfo", ".", "Size", "(", ")", "==", "0", "{", "var", "genesisFilterHash", "chainhash", ".", "Hash", "\n", "switch", "filterType", "{", "case", "RegularFilter", ":", "basicFilter", ",", "err", ":=", "builder", ".", "BuildBasicFilter", "(", "netParams", ".", "GenesisBlock", ",", "nil", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "genesisFilterHash", ",", "err", "=", "builder", ".", "MakeHeaderForFilter", "(", "basicFilter", ",", "netParams", ".", "GenesisBlock", ".", "Header", ".", "PrevBlock", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "filterType", ")", "\n", "}", "\n\n", "genesisHeader", ":=", "FilterHeader", "{", "HeaderHash", ":", "*", "netParams", ".", "GenesisHash", ",", "FilterHash", ":", "genesisFilterHash", ",", "Height", ":", "0", ",", "}", "\n", "if", "err", ":=", "fhs", ".", "WriteHeaders", "(", "genesisHeader", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "fhs", ",", "nil", "\n", "}", "\n\n", "// As a final initialization step, we'll ensure that the header tip", "// within the flat files, is in sync with out database index.", "tipHash", ",", "tipHeight", ",", "err", ":=", "fhs", ".", "chainTip", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// First, we'll compute the size of the current file so we can", "// calculate the latest header written to disk.", "fileHeight", ":=", "uint32", "(", "fileInfo", ".", "Size", "(", ")", "/", "32", ")", "-", "1", "\n\n", "// Using the file's current height, fetch the latest on-disk header.", "latestFileHeader", ",", "err", ":=", "fhs", ".", "readHeader", "(", "fileHeight", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// If the index's tip hash, and the file on-disk match, then we're", "// doing here.", "if", "tipHash", ".", "IsEqual", "(", "latestFileHeader", ")", "{", "return", "fhs", ",", "nil", "\n", "}", "\n\n", "// Otherwise, we'll need to truncate the file until it matches the", "// current index tip.", "for", "fileHeight", ">", "tipHeight", "{", "if", "err", ":=", "fhs", ".", "singleTruncate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "fileHeight", "--", "\n", "}", "\n\n", "// TODO(roasbeef): make above into func", "return", "fhs", ",", "nil", "\n", "}" ]
// NewFilterHeaderStore returns a new instance of the FilterHeaderStore based // on a target file path, filter type, and target net parameters. These // parameters are required as if this is the initial start up of the // FilterHeaderStore, then the initial genesis filter header will need to be // inserted.
[ "NewFilterHeaderStore", "returns", "a", "new", "instance", "of", "the", "FilterHeaderStore", "based", "on", "a", "target", "file", "path", "filter", "type", "and", "target", "net", "parameters", ".", "These", "parameters", "are", "required", "as", "if", "this", "is", "the", "initial", "start", "up", "of", "the", "FilterHeaderStore", "then", "the", "initial", "genesis", "filter", "header", "will", "need", "to", "be", "inserted", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L598-L694
train