repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
lightninglabs/neutrino
neutrino.go
pushSendHeadersMsg
func (sp *ServerPeer) pushSendHeadersMsg() error { if sp.VersionKnown() { if sp.ProtocolVersion() > wire.SendHeadersVersion { sp.QueueMessage(wire.NewMsgSendHeaders(), nil) } } return nil }
go
func (sp *ServerPeer) pushSendHeadersMsg() error { if sp.VersionKnown() { if sp.ProtocolVersion() > wire.SendHeadersVersion { sp.QueueMessage(wire.NewMsgSendHeaders(), nil) } } return nil }
[ "func", "(", "sp", "*", "ServerPeer", ")", "pushSendHeadersMsg", "(", ")", "error", "{", "if", "sp", ".", "VersionKnown", "(", ")", "{", "if", "sp", ".", "ProtocolVersion", "(", ")", ">", "wire", ".", "SendHeadersVersion", "{", "sp", ".", "QueueMessage",...
// pushSendHeadersMsg sends a sendheaders message to the connected peer.
[ "pushSendHeadersMsg", "sends", "a", "sendheaders", "message", "to", "the", "connected", "peer", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L238-L245
train
lightninglabs/neutrino
neutrino.go
OnVerAck
func (sp *ServerPeer) OnVerAck(_ *peer.Peer, msg *wire.MsgVerAck) { sp.pushSendHeadersMsg() }
go
func (sp *ServerPeer) OnVerAck(_ *peer.Peer, msg *wire.MsgVerAck) { sp.pushSendHeadersMsg() }
[ "func", "(", "sp", "*", "ServerPeer", ")", "OnVerAck", "(", "_", "*", "peer", ".", "Peer", ",", "msg", "*", "wire", ".", "MsgVerAck", ")", "{", "sp", ".", "pushSendHeadersMsg", "(", ")", "\n", "}" ]
// OnVerAck is invoked when a peer receives a verack bitcoin message and is used // to send the "sendheaders" command to peers that are of a sufficienty new // protocol version.
[ "OnVerAck", "is", "invoked", "when", "a", "peer", "receives", "a", "verack", "bitcoin", "message", "and", "is", "used", "to", "send", "the", "sendheaders", "command", "to", "peers", "that", "are", "of", "a", "sufficienty", "new", "protocol", "version", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L250-L252
train
lightninglabs/neutrino
neutrino.go
OnHeaders
func (sp *ServerPeer) OnHeaders(p *peer.Peer, msg *wire.MsgHeaders) { log.Tracef("Got headers with %d items from %s", len(msg.Headers), p.Addr()) sp.server.blockManager.QueueHeaders(msg, sp) }
go
func (sp *ServerPeer) OnHeaders(p *peer.Peer, msg *wire.MsgHeaders) { log.Tracef("Got headers with %d items from %s", len(msg.Headers), p.Addr()) sp.server.blockManager.QueueHeaders(msg, sp) }
[ "func", "(", "sp", "*", "ServerPeer", ")", "OnHeaders", "(", "p", "*", "peer", ".", "Peer", ",", "msg", "*", "wire", ".", "MsgHeaders", ")", "{", "log", ".", "Tracef", "(", "\"Got headers with %d items from %s\"", ",", "len", "(", "msg", ".", "Headers", ...
// OnHeaders is invoked when a peer receives a headers bitcoin // message. The message is passed down to the block manager.
[ "OnHeaders", "is", "invoked", "when", "a", "peer", "receives", "a", "headers", "bitcoin", "message", ".", "The", "message", "is", "passed", "down", "to", "the", "block", "manager", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L357-L361
train
lightninglabs/neutrino
neutrino.go
subscribeRecvMsg
func (sp *ServerPeer) subscribeRecvMsg(subscription spMsgSubscription) { sp.mtxSubscribers.Lock() defer sp.mtxSubscribers.Unlock() sp.recvSubscribers[subscription] = struct{}{} }
go
func (sp *ServerPeer) subscribeRecvMsg(subscription spMsgSubscription) { sp.mtxSubscribers.Lock() defer sp.mtxSubscribers.Unlock() sp.recvSubscribers[subscription] = struct{}{} }
[ "func", "(", "sp", "*", "ServerPeer", ")", "subscribeRecvMsg", "(", "subscription", "spMsgSubscription", ")", "{", "sp", ".", "mtxSubscribers", ".", "Lock", "(", ")", "\n", "defer", "sp", ".", "mtxSubscribers", ".", "Unlock", "(", ")", "\n", "sp", ".", "...
// subscribeRecvMsg handles adding OnRead subscriptions to the server peer.
[ "subscribeRecvMsg", "handles", "adding", "OnRead", "subscriptions", "to", "the", "server", "peer", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L476-L480
train
lightninglabs/neutrino
neutrino.go
unsubscribeRecvMsgs
func (sp *ServerPeer) unsubscribeRecvMsgs(subscription spMsgSubscription) { sp.mtxSubscribers.Lock() defer sp.mtxSubscribers.Unlock() delete(sp.recvSubscribers, subscription) }
go
func (sp *ServerPeer) unsubscribeRecvMsgs(subscription spMsgSubscription) { sp.mtxSubscribers.Lock() defer sp.mtxSubscribers.Unlock() delete(sp.recvSubscribers, subscription) }
[ "func", "(", "sp", "*", "ServerPeer", ")", "unsubscribeRecvMsgs", "(", "subscription", "spMsgSubscription", ")", "{", "sp", ".", "mtxSubscribers", ".", "Lock", "(", ")", "\n", "defer", "sp", ".", "mtxSubscribers", ".", "Unlock", "(", ")", "\n", "delete", "...
// unsubscribeRecvMsgs handles removing OnRead subscriptions from the server // peer.
[ "unsubscribeRecvMsgs", "handles", "removing", "OnRead", "subscriptions", "from", "the", "server", "peer", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L484-L488
train
lightninglabs/neutrino
neutrino.go
BestBlock
func (s *ChainService) BestBlock() (*waddrmgr.BlockStamp, error) { bestHeader, bestHeight, err := s.BlockHeaders.ChainTip() if err != nil { return nil, err } _, filterHeight, err := s.RegFilterHeaders.ChainTip() if err != nil { return nil, err } // Filter headers might lag behind block headers, so we can can fetch a // previous block header if the filter headers are not caught up. if filterHeight < bestHeight { bestHeight = filterHeight bestHeader, err = s.BlockHeaders.FetchHeaderByHeight( bestHeight, ) if err != nil { return nil, err } } return &waddrmgr.BlockStamp{ Height: int32(bestHeight), Hash: bestHeader.BlockHash(), }, nil }
go
func (s *ChainService) BestBlock() (*waddrmgr.BlockStamp, error) { bestHeader, bestHeight, err := s.BlockHeaders.ChainTip() if err != nil { return nil, err } _, filterHeight, err := s.RegFilterHeaders.ChainTip() if err != nil { return nil, err } // Filter headers might lag behind block headers, so we can can fetch a // previous block header if the filter headers are not caught up. if filterHeight < bestHeight { bestHeight = filterHeight bestHeader, err = s.BlockHeaders.FetchHeaderByHeight( bestHeight, ) if err != nil { return nil, err } } return &waddrmgr.BlockStamp{ Height: int32(bestHeight), Hash: bestHeader.BlockHash(), }, nil }
[ "func", "(", "s", "*", "ChainService", ")", "BestBlock", "(", ")", "(", "*", "waddrmgr", ".", "BlockStamp", ",", "error", ")", "{", "bestHeader", ",", "bestHeight", ",", "err", ":=", "s", ".", "BlockHeaders", ".", "ChainTip", "(", ")", "\n", "if", "e...
// BestBlock retrieves the most recent block's height and hash where we // have both the header and filter header ready.
[ "BestBlock", "retrieves", "the", "most", "recent", "block", "s", "height", "and", "hash", "where", "we", "have", "both", "the", "header", "and", "filter", "header", "ready", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L838-L865
train
lightninglabs/neutrino
neutrino.go
GetBlockHash
func (s *ChainService) GetBlockHash(height int64) (*chainhash.Hash, error) { header, err := s.BlockHeaders.FetchHeaderByHeight(uint32(height)) if err != nil { return nil, err } hash := header.BlockHash() return &hash, err }
go
func (s *ChainService) GetBlockHash(height int64) (*chainhash.Hash, error) { header, err := s.BlockHeaders.FetchHeaderByHeight(uint32(height)) if err != nil { return nil, err } hash := header.BlockHash() return &hash, err }
[ "func", "(", "s", "*", "ChainService", ")", "GetBlockHash", "(", "height", "int64", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "header", ",", "err", ":=", "s", ".", "BlockHeaders", ".", "FetchHeaderByHeight", "(", "uint32", "(", "...
// GetBlockHash returns the block hash at the given height.
[ "GetBlockHash", "returns", "the", "block", "hash", "at", "the", "given", "height", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L868-L875
train
lightninglabs/neutrino
neutrino.go
GetBlockHeader
func (s *ChainService) GetBlockHeader( blockHash *chainhash.Hash) (*wire.BlockHeader, error) { header, _, err := s.BlockHeaders.FetchHeader(blockHash) return header, err }
go
func (s *ChainService) GetBlockHeader( blockHash *chainhash.Hash) (*wire.BlockHeader, error) { header, _, err := s.BlockHeaders.FetchHeader(blockHash) return header, err }
[ "func", "(", "s", "*", "ChainService", ")", "GetBlockHeader", "(", "blockHash", "*", "chainhash", ".", "Hash", ")", "(", "*", "wire", ".", "BlockHeader", ",", "error", ")", "{", "header", ",", "_", ",", "err", ":=", "s", ".", "BlockHeaders", ".", "Fe...
// GetBlockHeader returns the block header for the given block hash, or an // error if the hash doesn't exist or is unknown.
[ "GetBlockHeader", "returns", "the", "block", "header", "for", "the", "given", "block", "hash", "or", "an", "error", "if", "the", "hash", "doesn", "t", "exist", "or", "is", "unknown", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L879-L883
train
lightninglabs/neutrino
neutrino.go
GetBlockHeight
func (s *ChainService) GetBlockHeight(hash *chainhash.Hash) (int32, error) { _, height, err := s.BlockHeaders.FetchHeader(hash) if err != nil { return 0, err } return int32(height), nil }
go
func (s *ChainService) GetBlockHeight(hash *chainhash.Hash) (int32, error) { _, height, err := s.BlockHeaders.FetchHeader(hash) if err != nil { return 0, err } return int32(height), nil }
[ "func", "(", "s", "*", "ChainService", ")", "GetBlockHeight", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "int32", ",", "error", ")", "{", "_", ",", "height", ",", "err", ":=", "s", ".", "BlockHeaders", ".", "FetchHeader", "(", "hash", ")",...
// GetBlockHeight gets the height of a block by its hash. An error is returned // if the given block hash is unknown.
[ "GetBlockHeight", "gets", "the", "height", "of", "a", "block", "by", "its", "hash", ".", "An", "error", "is", "returned", "if", "the", "given", "block", "hash", "is", "unknown", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L887-L893
train
lightninglabs/neutrino
neutrino.go
BanPeer
func (s *ChainService) BanPeer(sp *ServerPeer) { select { case s.banPeers <- sp: case <-s.quit: return } }
go
func (s *ChainService) BanPeer(sp *ServerPeer) { select { case s.banPeers <- sp: case <-s.quit: return } }
[ "func", "(", "s", "*", "ChainService", ")", "BanPeer", "(", "sp", "*", "ServerPeer", ")", "{", "select", "{", "case", "s", ".", "banPeers", "<-", "sp", ":", "case", "<-", "s", ".", "quit", ":", "return", "\n", "}", "\n", "}" ]
// BanPeer bans a peer that has already been connected to the server by ip.
[ "BanPeer", "bans", "a", "peer", "that", "has", "already", "been", "connected", "to", "the", "server", "by", "ip", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L896-L902
train
lightninglabs/neutrino
neutrino.go
AddPeer
func (s *ChainService) AddPeer(sp *ServerPeer) { select { case s.newPeers <- sp: case <-s.quit: return } }
go
func (s *ChainService) AddPeer(sp *ServerPeer) { select { case s.newPeers <- sp: case <-s.quit: return } }
[ "func", "(", "s", "*", "ChainService", ")", "AddPeer", "(", "sp", "*", "ServerPeer", ")", "{", "select", "{", "case", "s", ".", "newPeers", "<-", "sp", ":", "case", "<-", "s", ".", "quit", ":", "return", "\n", "}", "\n", "}" ]
// AddPeer adds a new peer that has already been connected to the server.
[ "AddPeer", "adds", "a", "new", "peer", "that", "has", "already", "been", "connected", "to", "the", "server", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L905-L911
train
lightninglabs/neutrino
neutrino.go
rollBackToHeight
func (s *ChainService) rollBackToHeight(height uint32) (*waddrmgr.BlockStamp, error) { header, headerHeight, err := s.BlockHeaders.ChainTip() if err != nil { return nil, err } bs := &waddrmgr.BlockStamp{ Height: int32(headerHeight), Hash: header.BlockHash(), } _, regHeight, err := s.RegFilterHeaders.ChainTip() if err != nil { return nil, err } for uint32(bs.Height) > height { header, _, err := s.BlockHeaders.FetchHeader(&bs.Hash) if err != nil { return nil, err } newTip := &header.PrevBlock // Only roll back filter headers if they've caught up this far. if uint32(bs.Height) <= regHeight { newFilterTip, err := s.RegFilterHeaders.RollbackLastBlock(newTip) if err != nil { return nil, err } regHeight = uint32(newFilterTip.Height) } bs, err = s.BlockHeaders.RollbackLastBlock() if err != nil { return nil, err } // Notifications are asynchronous, so we include the previous // header in the disconnected notification in case we're rolling // back farther and the notification subscriber needs it but // can't read it before it's deleted from the store. prevHeader, _, err := s.BlockHeaders.FetchHeader(newTip) if err != nil { return nil, err } // Now we send the block disconnected notifications. s.blockManager.onBlockDisconnected( *header, headerHeight, *prevHeader, ) } return bs, nil }
go
func (s *ChainService) rollBackToHeight(height uint32) (*waddrmgr.BlockStamp, error) { header, headerHeight, err := s.BlockHeaders.ChainTip() if err != nil { return nil, err } bs := &waddrmgr.BlockStamp{ Height: int32(headerHeight), Hash: header.BlockHash(), } _, regHeight, err := s.RegFilterHeaders.ChainTip() if err != nil { return nil, err } for uint32(bs.Height) > height { header, _, err := s.BlockHeaders.FetchHeader(&bs.Hash) if err != nil { return nil, err } newTip := &header.PrevBlock // Only roll back filter headers if they've caught up this far. if uint32(bs.Height) <= regHeight { newFilterTip, err := s.RegFilterHeaders.RollbackLastBlock(newTip) if err != nil { return nil, err } regHeight = uint32(newFilterTip.Height) } bs, err = s.BlockHeaders.RollbackLastBlock() if err != nil { return nil, err } // Notifications are asynchronous, so we include the previous // header in the disconnected notification in case we're rolling // back farther and the notification subscriber needs it but // can't read it before it's deleted from the store. prevHeader, _, err := s.BlockHeaders.FetchHeader(newTip) if err != nil { return nil, err } // Now we send the block disconnected notifications. s.blockManager.onBlockDisconnected( *header, headerHeight, *prevHeader, ) } return bs, nil }
[ "func", "(", "s", "*", "ChainService", ")", "rollBackToHeight", "(", "height", "uint32", ")", "(", "*", "waddrmgr", ".", "BlockStamp", ",", "error", ")", "{", "header", ",", "headerHeight", ",", "err", ":=", "s", ".", "BlockHeaders", ".", "ChainTip", "("...
// rollBackToHeight rolls back all blocks until it hits the specified height. // It sends notifications along the way.
[ "rollBackToHeight", "rolls", "back", "all", "blocks", "until", "it", "hits", "the", "specified", "height", ".", "It", "sends", "notifications", "along", "the", "way", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L934-L986
train
lightninglabs/neutrino
neutrino.go
isBanned
func (s *ChainService) isBanned(addr string, state *peerState) bool { // First, we'll extract the host so we can consider it without taking // into account the target port. host, _, err := net.SplitHostPort(addr) if err != nil { log.Debugf("can't split host/port: %s", err) return false } // With the host obtained, we'll check on the ban status of this peer. if banEnd, ok := state.banned[host]; ok { // If the ban duration of this peer is still active, then we'll // ignore it for now as it's still banned. if time.Now().Before(banEnd) { log.Debugf("Peer %s is banned for another %v - ignoring", host, banEnd.Sub(time.Now())) return true } // Otherwise, the peer was banned in the past, but is no longer // banned, so we'll remove this ban entry and return back to // the caller. log.Infof("Peer %s is no longer banned", host) delete(state.banned, host) return false } return false }
go
func (s *ChainService) isBanned(addr string, state *peerState) bool { // First, we'll extract the host so we can consider it without taking // into account the target port. host, _, err := net.SplitHostPort(addr) if err != nil { log.Debugf("can't split host/port: %s", err) return false } // With the host obtained, we'll check on the ban status of this peer. if banEnd, ok := state.banned[host]; ok { // If the ban duration of this peer is still active, then we'll // ignore it for now as it's still banned. if time.Now().Before(banEnd) { log.Debugf("Peer %s is banned for another %v - ignoring", host, banEnd.Sub(time.Now())) return true } // Otherwise, the peer was banned in the past, but is no longer // banned, so we'll remove this ban entry and return back to // the caller. log.Infof("Peer %s is no longer banned", host) delete(state.banned, host) return false } return false }
[ "func", "(", "s", "*", "ChainService", ")", "isBanned", "(", "addr", "string", ",", "state", "*", "peerState", ")", "bool", "{", "host", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{",...
// isBanned returns true if the passed peer address is still considered to be // banned.
[ "isBanned", "returns", "true", "if", "the", "passed", "peer", "address", "is", "still", "considered", "to", "be", "banned", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L1146-L1174
train
lightninglabs/neutrino
neutrino.go
SendTransaction
func (s *ChainService) SendTransaction(tx *wire.MsgTx) error { // TODO(roasbeef): pipe through querying interface return s.broadcaster.Broadcast(tx) }
go
func (s *ChainService) SendTransaction(tx *wire.MsgTx) error { // TODO(roasbeef): pipe through querying interface return s.broadcaster.Broadcast(tx) }
[ "func", "(", "s", "*", "ChainService", ")", "SendTransaction", "(", "tx", "*", "wire", ".", "MsgTx", ")", "error", "{", "return", "s", ".", "broadcaster", ".", "Broadcast", "(", "tx", ")", "\n", "}" ]
// SendTransaction broadcasts the transaction to all currently active peers so // it can be propagated to other nodes and eventually mined. 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.
[ "SendTransaction", "broadcasts", "the", "transaction", "to", "all", "currently", "active", "peers", "so", "it", "can", "be", "propagated", "to", "other", "nodes", "and", "eventually", "mined", ".", "An", "error", "won", "t", "be", "returned", "if", "the", "t...
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L1311-L1314
train
lightninglabs/neutrino
neutrino.go
newPeerConfig
func newPeerConfig(sp *ServerPeer) *peer.Config { return &peer.Config{ Listeners: peer.MessageListeners{ OnVersion: sp.OnVersion, //OnVerAck: sp.OnVerAck, // Don't use sendheaders yet OnInv: sp.OnInv, OnHeaders: sp.OnHeaders, OnReject: sp.OnReject, OnFeeFilter: sp.OnFeeFilter, OnAddr: sp.OnAddr, OnRead: sp.OnRead, OnWrite: sp.OnWrite, // Note: The reference client currently bans peers that send alerts // not signed with its key. We could verify against their key, but // since the reference client is currently unwilling to support // other implementations' alert messages, we will not relay theirs. OnAlert: nil, }, NewestBlock: sp.newestBlock, HostToNetAddress: sp.server.addrManager.HostToNetAddress, UserAgentName: sp.server.userAgentName, UserAgentVersion: sp.server.userAgentVersion, ChainParams: &sp.server.chainParams, Services: sp.server.services, ProtocolVersion: wire.FeeFilterVersion, DisableRelayTx: true, } }
go
func newPeerConfig(sp *ServerPeer) *peer.Config { return &peer.Config{ Listeners: peer.MessageListeners{ OnVersion: sp.OnVersion, //OnVerAck: sp.OnVerAck, // Don't use sendheaders yet OnInv: sp.OnInv, OnHeaders: sp.OnHeaders, OnReject: sp.OnReject, OnFeeFilter: sp.OnFeeFilter, OnAddr: sp.OnAddr, OnRead: sp.OnRead, OnWrite: sp.OnWrite, // Note: The reference client currently bans peers that send alerts // not signed with its key. We could verify against their key, but // since the reference client is currently unwilling to support // other implementations' alert messages, we will not relay theirs. OnAlert: nil, }, NewestBlock: sp.newestBlock, HostToNetAddress: sp.server.addrManager.HostToNetAddress, UserAgentName: sp.server.userAgentName, UserAgentVersion: sp.server.userAgentVersion, ChainParams: &sp.server.chainParams, Services: sp.server.services, ProtocolVersion: wire.FeeFilterVersion, DisableRelayTx: true, } }
[ "func", "newPeerConfig", "(", "sp", "*", "ServerPeer", ")", "*", "peer", ".", "Config", "{", "return", "&", "peer", ".", "Config", "{", "Listeners", ":", "peer", ".", "MessageListeners", "{", "OnVersion", ":", "sp", ".", "OnVersion", ",", "OnInv", ":", ...
// newPeerConfig returns the configuration for the given ServerPeer.
[ "newPeerConfig", "returns", "the", "configuration", "for", "the", "given", "ServerPeer", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L1317-L1345
train
lightninglabs/neutrino
neutrino.go
Start
func (s *ChainService) Start() error { // Already started? if atomic.AddInt32(&s.started, 1) != 1 { return nil } // Start the address manager and block manager, both of which are // needed by peers. s.addrManager.Start() s.blockManager.Start() s.blockSubscriptionMgr.Start() s.utxoScanner.Start() if err := s.broadcaster.Start(); err != nil { return fmt.Errorf("unable to start transaction broadcaster: %v", err) } go s.connManager.Start() // Start the peer handler which in turn starts the address and block // managers. s.wg.Add(1) go s.peerHandler() return nil }
go
func (s *ChainService) Start() error { // Already started? if atomic.AddInt32(&s.started, 1) != 1 { return nil } // Start the address manager and block manager, both of which are // needed by peers. s.addrManager.Start() s.blockManager.Start() s.blockSubscriptionMgr.Start() s.utxoScanner.Start() if err := s.broadcaster.Start(); err != nil { return fmt.Errorf("unable to start transaction broadcaster: %v", err) } go s.connManager.Start() // Start the peer handler which in turn starts the address and block // managers. s.wg.Add(1) go s.peerHandler() return nil }
[ "func", "(", "s", "*", "ChainService", ")", "Start", "(", ")", "error", "{", "if", "atomic", ".", "AddInt32", "(", "&", "s", ".", "started", ",", "1", ")", "!=", "1", "{", "return", "nil", "\n", "}", "\n", "s", ".", "addrManager", ".", "Start", ...
// Start begins connecting to peers and syncing the blockchain.
[ "Start", "begins", "connecting", "to", "peers", "and", "syncing", "the", "blockchain", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L1423-L1450
train
lightninglabs/neutrino
neutrino.go
PeerByAddr
func (s *ChainService) PeerByAddr(addr string) *ServerPeer { for _, peer := range s.Peers() { if peer.Addr() == addr { return peer } } return nil }
go
func (s *ChainService) PeerByAddr(addr string) *ServerPeer { for _, peer := range s.Peers() { if peer.Addr() == addr { return peer } } return nil }
[ "func", "(", "s", "*", "ChainService", ")", "PeerByAddr", "(", "addr", "string", ")", "*", "ServerPeer", "{", "for", "_", ",", "peer", ":=", "range", "s", ".", "Peers", "(", ")", "{", "if", "peer", ".", "Addr", "(", ")", "==", "addr", "{", "retur...
// PeerByAddr lets the caller look up a peer address in the service's peer // table, if connected to that peer address.
[ "PeerByAddr", "lets", "the", "caller", "look", "up", "a", "peer", "address", "in", "the", "service", "s", "peer", "table", "if", "connected", "to", "that", "peer", "address", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L1481-L1488
train
lightninglabs/neutrino
neutrino.go
GetBlockHeaderByHeight
func (s *RescanChainSource) GetBlockHeaderByHeight( height uint32) (*wire.BlockHeader, error) { return s.BlockHeaders.FetchHeaderByHeight(height) }
go
func (s *RescanChainSource) GetBlockHeaderByHeight( height uint32) (*wire.BlockHeader, error) { return s.BlockHeaders.FetchHeaderByHeight(height) }
[ "func", "(", "s", "*", "RescanChainSource", ")", "GetBlockHeaderByHeight", "(", "height", "uint32", ")", "(", "*", "wire", ".", "BlockHeader", ",", "error", ")", "{", "return", "s", ".", "BlockHeaders", ".", "FetchHeaderByHeight", "(", "height", ")", "\n", ...
// GetBlockHeaderByHeight returns the header of the block with the given height.
[ "GetBlockHeaderByHeight", "returns", "the", "header", "of", "the", "block", "with", "the", "given", "height", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L1501-L1504
train
lightninglabs/neutrino
neutrino.go
GetBlockHeader
func (s *RescanChainSource) GetBlockHeader( hash *chainhash.Hash) (*wire.BlockHeader, uint32, error) { return s.BlockHeaders.FetchHeader(hash) }
go
func (s *RescanChainSource) GetBlockHeader( hash *chainhash.Hash) (*wire.BlockHeader, uint32, error) { return s.BlockHeaders.FetchHeader(hash) }
[ "func", "(", "s", "*", "RescanChainSource", ")", "GetBlockHeader", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "wire", ".", "BlockHeader", ",", "uint32", ",", "error", ")", "{", "return", "s", ".", "BlockHeaders", ".", "FetchHeader", "(", ...
// GetBlockHeader returns the header of the block with the given hash.
[ "GetBlockHeader", "returns", "the", "header", "of", "the", "block", "with", "the", "given", "hash", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L1507-L1510
train
lightninglabs/neutrino
neutrino.go
GetFilterHeaderByHeight
func (s *RescanChainSource) GetFilterHeaderByHeight( height uint32) (*chainhash.Hash, error) { return s.RegFilterHeaders.FetchHeaderByHeight(height) }
go
func (s *RescanChainSource) GetFilterHeaderByHeight( height uint32) (*chainhash.Hash, error) { return s.RegFilterHeaders.FetchHeaderByHeight(height) }
[ "func", "(", "s", "*", "RescanChainSource", ")", "GetFilterHeaderByHeight", "(", "height", "uint32", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "return", "s", ".", "RegFilterHeaders", ".", "FetchHeaderByHeight", "(", "height", ")", "\n"...
// GetFilterHeaderByHeight returns the filter header of the block with the given // height.
[ "GetFilterHeaderByHeight", "returns", "the", "filter", "header", "of", "the", "block", "with", "the", "given", "height", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L1514-L1517
train
lightninglabs/neutrino
neutrino.go
Subscribe
func (s *RescanChainSource) Subscribe( bestHeight uint32) (*blockntfns.Subscription, error) { return s.blockSubscriptionMgr.NewSubscription(bestHeight) }
go
func (s *RescanChainSource) Subscribe( bestHeight uint32) (*blockntfns.Subscription, error) { return s.blockSubscriptionMgr.NewSubscription(bestHeight) }
[ "func", "(", "s", "*", "RescanChainSource", ")", "Subscribe", "(", "bestHeight", "uint32", ")", "(", "*", "blockntfns", ".", "Subscription", ",", "error", ")", "{", "return", "s", ".", "blockSubscriptionMgr", ".", "NewSubscription", "(", "bestHeight", ")", "...
// Subscribe returns a block subscription that delivers block notifications in // order. The bestHeight parameter can be used to signal that a backlog of // notifications should be delivered from this height. When providing a height // of 0, a backlog will not be delivered.
[ "Subscribe", "returns", "a", "block", "subscription", "that", "delivers", "block", "notifications", "in", "order", ".", "The", "bestHeight", "parameter", "can", "be", "used", "to", "signal", "that", "a", "backlog", "of", "notifications", "should", "be", "deliver...
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/neutrino.go#L1523-L1526
train
lightninglabs/neutrino
blockntfns/notification.go
NewBlockConnected
func NewBlockConnected(header wire.BlockHeader, height uint32) *Connected { return &Connected{header: header, height: height} }
go
func NewBlockConnected(header wire.BlockHeader, height uint32) *Connected { return &Connected{header: header, height: height} }
[ "func", "NewBlockConnected", "(", "header", "wire", ".", "BlockHeader", ",", "height", "uint32", ")", "*", "Connected", "{", "return", "&", "Connected", "{", "header", ":", "header", ",", "height", ":", "height", "}", "\n", "}" ]
// NewBlockConnected creates a new Connected notification for the given block.
[ "NewBlockConnected", "creates", "a", "new", "Connected", "notification", "for", "the", "given", "block", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockntfns/notification.go#L36-L38
train
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", "(", "\"block connected (height=%d, hash=%v)\"", ",", "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", ":", "he...
// 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", "(", "\"block disconnected (height=%d, hash=%v)\"", ",", "n", ".", "heightDisconnected", ",", "n", ".", "headerDisconnected", ".", "BlockHash", "(", ...
// 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", ",", "en...
// 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",...
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", "wire", ".", "Message", ",", "checkResponse", "func", "(", "sp", "*", "ServerPeer", ",", "resp", "wire", ".", "Message", ",", "quit", "chan", "<-", "struct", "{", "}", ",", "...
// 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", ...
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", "*", "ChainService", ",", "queryMsg", "wire", ".", "Message", ",", "checkResponse", "func", "(", "sp", "*", "ServerPeer", ",", "resp", "wire", ".", "Message", ",", "quit", "chan", "<-", "struct", "{", "}", ")", ...
// 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", ...
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", "...
// 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", ")", "{", "cacheK...
// 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", ",", ...
// 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", "{", "}", ")", "{", "response", ",", "ok", ":=", "resp", ".", "(", "*", "w...
// 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", ")", "{", "if", ...
// 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", "f...
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", ")", "{", "blockHeader", ",", "height", ",", "err", ":=", "s...
// 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", "immediatel...
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", "select", "{", "case", "s", ".", "query", "<-", "getPeersMsg", "{", "re...
// 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", "select", "{", "case", "s", ".", "query", "<-", "disconnectNodeMsg", "{", "cmp", ":"...
// 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", ...
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", "select", "{", "case", "s", ".", "query", "<-", "disconnectNodeMsg", "{", "cmp", ":", "...
// 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"...
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", "select", "{", "case", "s", ".", "query", "<-", "connectNodeMsg", ...
// 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...
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", "select", "{", "case", "s", ".", "query", "<-", "banQueryMsg", "{", "addr", ":", "...
// 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", ...
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", "...", ")"...
// 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", ...
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", "{", "var", "relevantTxs", "[", "]", "*"...
// 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", ")", "{", "block", ",", "err", ":=", "chain", ...
// 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", "{"...
// 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", ")", "{", "key", ":=", "builder", ".", "DeriveKey", "(", "blockHash", ...
// 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...
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", ")", "{", "filter", ",", "err", ":=", "chain", ".", "GetCFilter", "(", "*", "bloc...
// 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", ",", "...
// 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", ":=", "ran...
// 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", "txOutLoop", ":", "for", "outIdx", ",", "out", ":=", "range", "t...
// 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", "w...
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...
// 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...
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", "if", "!", "atomic", ".", "CompareAndSwapUint32", "(", "&", "r", ".", "started", ",", "0", ",...
// 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", "}"...
// 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", "...
// 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",...
// 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", "&&", "!", "IsBroadcastEr...
// 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", "sortedTxs", ":=", "wtxmgr", ".", "DependencySort", "(", "b", ".", "transactions", ")...
// 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"...
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", "select", "{", "case", "b", ".", "broadcastReqs", "<-", "&", "broad...
// 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", "."...
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", ")", ",", "newSubscription...
// 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", "log", ".", "Debug", "(", "\"Starting block notificat...
// 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", "log", ".", "Debug", "(", "\"Stopping block notificati...
// 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", ")", "{", "sub", ":=", "&", "newSubscription", "{", "id", ":", "atomic", ".", "AddUint64", "(", "&", "m", ".",...
// 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", ...
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", "(", "\"Registering block subscription: id=%d\"", ",", "sub", ".", "id", ")", "\n", "blocks", ",", "currentHei...
// 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", "<-", "...
// 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", ")", "{", "sub", ",", "ok", ":=", "m", ".", "subscribers", "[", "msg", ".", "id", "]", "\n", "if", "!", "ok", "{", "return", "\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", "(", "\"Notifying %v\"", ",", "ntfn", ")", "\n", "for", "_", ",", "subscriber", ":=", "range", "m", ".", "subscribers", "{", ...
// 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", "<-", "su...
// 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", ":", ...
// 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", ...
// 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", "("...
// 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", "s", ".", "wg", ".", "A...
// 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", "close", "(", "s", ".", ...
// 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", "(", "\"Enqueuing request for %s with birth height %d\"", ","...
// 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", "(", ")", ...
// 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", "{", "bestStamp", ",", "err", ":=", "s", ".", "cfg", ".", "BestSnapshot", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\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", "requ...
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", ...
// 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", ...
// 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", "(", "\"Block manager is already in the process of \"", "+", ...
// 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", ")", "{", "if", "atomic", ".", "LoadInt32", "(", "&", "b", ".", "shutdown", ")", "!=", "0", "{", "return", "\n", "}", "\n", "select", "{", "case", "b", ".", "pee...
// 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", ".", "newFilterH...
// 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"...
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", "len", "(", "checkpoints", ")", "==", "0", "{", "return", "0", "\n", "}", "\n", "minHeight", ":=", "uint32"...
// 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",...
// 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", "ret...
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", "{", "hash", ":=", "zeroHash", "\n", "for", "_", ",", "msg", ":=", "range", "headers", "{", "if", "len", "(...
// 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", ")", "{", ...
// 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", ...
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", ")", "{", "headers", ":=", "make",...
// 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", ...
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", "{", "filte...
// 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...
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...
// 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", ")", "{", "_", ",", "storeTip", ",", "err", ":=...
// 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", ...
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", "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", "{", "checkpoints", ":=", "b", ".", "server", ".", "chainParams", ".", "Checkpoints", "\n", "if", "len", "(", "checkpoint...
// 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", "c...
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", "{", "prevCheckpoint", ":=", "&", "chaincfg", ".", "Checkpoint", "{", "Height", ":", "0", ",", "Hash", ":", "b", "....
// 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", "checkpoi...
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", "f...
// 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", "header", ",", "height", ",", "err", ...
// 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