id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
163,200 | btcsuite/btcd | rpcclient/chain.go | GetBlockChainInfoAsync | func (c *Client) GetBlockChainInfoAsync() FutureGetBlockChainInfoResult {
cmd := btcjson.NewGetBlockChainInfoCmd()
return c.sendCmd(cmd)
} | go | func (c *Client) GetBlockChainInfoAsync() FutureGetBlockChainInfoResult {
cmd := btcjson.NewGetBlockChainInfoCmd()
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetBlockChainInfoAsync",
"(",
")",
"FutureGetBlockChainInfoResult",
"{",
"cmd",
":=",
"btcjson",
".",
"NewGetBlockChainInfoCmd",
"(",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // GetBlockChainInfoAsync returns an instance of a type that can be used to get
// the result of the RPC at some future time by invoking the Receive function
// on the returned instance.
//
// See GetBlockChainInfo for the blocking version and more details. | [
"GetBlockChainInfoAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L278-L281 |
163,201 | btcsuite/btcd | rpcclient/chain.go | GetBlockHashAsync | func (c *Client) GetBlockHashAsync(blockHeight int64) FutureGetBlockHashResult {
cmd := btcjson.NewGetBlockHashCmd(blockHeight)
return c.sendCmd(cmd)
} | go | func (c *Client) GetBlockHashAsync(blockHeight int64) FutureGetBlockHashResult {
cmd := btcjson.NewGetBlockHashCmd(blockHeight)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetBlockHashAsync",
"(",
"blockHeight",
"int64",
")",
"FutureGetBlockHashResult",
"{",
"cmd",
":=",
"btcjson",
".",
"NewGetBlockHashCmd",
"(",
"blockHeight",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\... | // GetBlockHashAsync returns an instance of a type that can be used to get the
// result of the RPC at some future time by invoking the Receive function on the
// returned instance.
//
// See GetBlockHash for the blocking version and more details. | [
"GetBlockHashAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
"in... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L316-L319 |
163,202 | btcsuite/btcd | rpcclient/chain.go | GetBlockHash | func (c *Client) GetBlockHash(blockHeight int64) (*chainhash.Hash, error) {
return c.GetBlockHashAsync(blockHeight).Receive()
} | go | func (c *Client) GetBlockHash(blockHeight int64) (*chainhash.Hash, error) {
return c.GetBlockHashAsync(blockHeight).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetBlockHash",
"(",
"blockHeight",
"int64",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"return",
"c",
".",
"GetBlockHashAsync",
"(",
"blockHeight",
")",
".",
"Receive",
"(",
")",
"\n",
"}"
] | // GetBlockHash returns the hash of the block in the best block chain at the
// given height. | [
"GetBlockHash",
"returns",
"the",
"hash",
"of",
"the",
"block",
"in",
"the",
"best",
"block",
"chain",
"at",
"the",
"given",
"height",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L323-L325 |
163,203 | btcsuite/btcd | rpcclient/chain.go | Receive | func (r FutureGetBlockHeaderResult) Receive() (*wire.BlockHeader, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a string.
var bhHex string
err = json.Unmarshal(res, &bhHex)
if err != nil {
return nil, err
}
serializedBH, err := hex.DecodeString(bhHex)
if err != nil {
return nil, err
}
// Deserialize the blockheader and return it.
var bh wire.BlockHeader
err = bh.Deserialize(bytes.NewReader(serializedBH))
if err != nil {
return nil, err
}
return &bh, err
} | go | func (r FutureGetBlockHeaderResult) Receive() (*wire.BlockHeader, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a string.
var bhHex string
err = json.Unmarshal(res, &bhHex)
if err != nil {
return nil, err
}
serializedBH, err := hex.DecodeString(bhHex)
if err != nil {
return nil, err
}
// Deserialize the blockheader and return it.
var bh wire.BlockHeader
err = bh.Deserialize(bytes.NewReader(serializedBH))
if err != nil {
return nil, err
}
return &bh, err
} | [
"func",
"(",
"r",
"FutureGetBlockHeaderResult",
")",
"Receive",
"(",
")",
"(",
"*",
"wire",
".",
"BlockHeader",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"receiveFuture",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
","... | // Receive waits for the response promised by the future and returns the
// blockheader requested from the server given its hash. | [
"Receive",
"waits",
"for",
"the",
"response",
"promised",
"by",
"the",
"future",
"and",
"returns",
"the",
"blockheader",
"requested",
"from",
"the",
"server",
"given",
"its",
"hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L333-L359 |
163,204 | btcsuite/btcd | rpcclient/chain.go | GetBlockHeaderAsync | func (c *Client) GetBlockHeaderAsync(blockHash *chainhash.Hash) FutureGetBlockHeaderResult {
hash := ""
if blockHash != nil {
hash = blockHash.String()
}
cmd := btcjson.NewGetBlockHeaderCmd(hash, btcjson.Bool(false))
return c.sendCmd(cmd)
} | go | func (c *Client) GetBlockHeaderAsync(blockHash *chainhash.Hash) FutureGetBlockHeaderResult {
hash := ""
if blockHash != nil {
hash = blockHash.String()
}
cmd := btcjson.NewGetBlockHeaderCmd(hash, btcjson.Bool(false))
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetBlockHeaderAsync",
"(",
"blockHash",
"*",
"chainhash",
".",
"Hash",
")",
"FutureGetBlockHeaderResult",
"{",
"hash",
":=",
"\"",
"\"",
"\n",
"if",
"blockHash",
"!=",
"nil",
"{",
"hash",
"=",
"blockHash",
".",
"Strin... | // GetBlockHeaderAsync returns an instance of a type that can be used to get the
// result of the RPC at some future time by invoking the Receive function on the
// returned instance.
//
// See GetBlockHeader for the blocking version and more details. | [
"GetBlockHeaderAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
"... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L366-L374 |
163,205 | btcsuite/btcd | rpcclient/chain.go | GetBlockHeader | func (c *Client) GetBlockHeader(blockHash *chainhash.Hash) (*wire.BlockHeader, error) {
return c.GetBlockHeaderAsync(blockHash).Receive()
} | go | func (c *Client) GetBlockHeader(blockHash *chainhash.Hash) (*wire.BlockHeader, error) {
return c.GetBlockHeaderAsync(blockHash).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetBlockHeader",
"(",
"blockHash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"wire",
".",
"BlockHeader",
",",
"error",
")",
"{",
"return",
"c",
".",
"GetBlockHeaderAsync",
"(",
"blockHash",
")",
".",
"Receive",
... | // GetBlockHeader returns the blockheader from the server given its hash.
//
// See GetBlockHeaderVerbose to retrieve a data structure with information about the
// block instead. | [
"GetBlockHeader",
"returns",
"the",
"blockheader",
"from",
"the",
"server",
"given",
"its",
"hash",
".",
"See",
"GetBlockHeaderVerbose",
"to",
"retrieve",
"a",
"data",
"structure",
"with",
"information",
"about",
"the",
"block",
"instead",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L380-L382 |
163,206 | btcsuite/btcd | rpcclient/chain.go | Receive | func (r FutureGetBlockHeaderVerboseResult) Receive() (*btcjson.GetBlockHeaderVerboseResult, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a string.
var bh btcjson.GetBlockHeaderVerboseResult
err = json.Unmarshal(res, &bh)
if err != nil {
return nil, err
}
return &bh, nil
} | go | func (r FutureGetBlockHeaderVerboseResult) Receive() (*btcjson.GetBlockHeaderVerboseResult, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a string.
var bh btcjson.GetBlockHeaderVerboseResult
err = json.Unmarshal(res, &bh)
if err != nil {
return nil, err
}
return &bh, nil
} | [
"func",
"(",
"r",
"FutureGetBlockHeaderVerboseResult",
")",
"Receive",
"(",
")",
"(",
"*",
"btcjson",
".",
"GetBlockHeaderVerboseResult",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"receiveFuture",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
... | // Receive waits for the response promised by the future and returns the
// data structure of the blockheader requested from the server given its hash. | [
"Receive",
"waits",
"for",
"the",
"response",
"promised",
"by",
"the",
"future",
"and",
"returns",
"the",
"data",
"structure",
"of",
"the",
"blockheader",
"requested",
"from",
"the",
"server",
"given",
"its",
"hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L390-L404 |
163,207 | btcsuite/btcd | rpcclient/chain.go | GetBlockHeaderVerboseAsync | func (c *Client) GetBlockHeaderVerboseAsync(blockHash *chainhash.Hash) FutureGetBlockHeaderVerboseResult {
hash := ""
if blockHash != nil {
hash = blockHash.String()
}
cmd := btcjson.NewGetBlockHeaderCmd(hash, btcjson.Bool(true))
return c.sendCmd(cmd)
} | go | func (c *Client) GetBlockHeaderVerboseAsync(blockHash *chainhash.Hash) FutureGetBlockHeaderVerboseResult {
hash := ""
if blockHash != nil {
hash = blockHash.String()
}
cmd := btcjson.NewGetBlockHeaderCmd(hash, btcjson.Bool(true))
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetBlockHeaderVerboseAsync",
"(",
"blockHash",
"*",
"chainhash",
".",
"Hash",
")",
"FutureGetBlockHeaderVerboseResult",
"{",
"hash",
":=",
"\"",
"\"",
"\n",
"if",
"blockHash",
"!=",
"nil",
"{",
"hash",
"=",
"blockHash",
... | // GetBlockHeaderVerboseAsync returns an instance of a type that can be used to get the
// result of the RPC at some future time by invoking the Receive function on the
// returned instance.
//
// See GetBlockHeader for the blocking version and more details. | [
"GetBlockHeaderVerboseAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returne... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L411-L419 |
163,208 | btcsuite/btcd | rpcclient/chain.go | GetBlockHeaderVerbose | func (c *Client) GetBlockHeaderVerbose(blockHash *chainhash.Hash) (*btcjson.GetBlockHeaderVerboseResult, error) {
return c.GetBlockHeaderVerboseAsync(blockHash).Receive()
} | go | func (c *Client) GetBlockHeaderVerbose(blockHash *chainhash.Hash) (*btcjson.GetBlockHeaderVerboseResult, error) {
return c.GetBlockHeaderVerboseAsync(blockHash).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetBlockHeaderVerbose",
"(",
"blockHash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"btcjson",
".",
"GetBlockHeaderVerboseResult",
",",
"error",
")",
"{",
"return",
"c",
".",
"GetBlockHeaderVerboseAsync",
"(",
"blockH... | // GetBlockHeaderVerbose returns a data structure with information about the
// blockheader from the server given its hash.
//
// See GetBlockHeader to retrieve a blockheader instead. | [
"GetBlockHeaderVerbose",
"returns",
"a",
"data",
"structure",
"with",
"information",
"about",
"the",
"blockheader",
"from",
"the",
"server",
"given",
"its",
"hash",
".",
"See",
"GetBlockHeader",
"to",
"retrieve",
"a",
"blockheader",
"instead",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L425-L427 |
163,209 | btcsuite/btcd | rpcclient/chain.go | Receive | func (r FutureGetMempoolEntryResult) Receive() (*btcjson.GetMempoolEntryResult, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal the result as an array of strings.
var mempoolEntryResult btcjson.GetMempoolEntryResult
err = json.Unmarshal(res, &mempoolEntryResult)
if err != nil {
return nil, err
}
return &mempoolEntryResult, nil
} | go | func (r FutureGetMempoolEntryResult) Receive() (*btcjson.GetMempoolEntryResult, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal the result as an array of strings.
var mempoolEntryResult btcjson.GetMempoolEntryResult
err = json.Unmarshal(res, &mempoolEntryResult)
if err != nil {
return nil, err
}
return &mempoolEntryResult, nil
} | [
"func",
"(",
"r",
"FutureGetMempoolEntryResult",
")",
"Receive",
"(",
")",
"(",
"*",
"btcjson",
".",
"GetMempoolEntryResult",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"receiveFuture",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // Receive waits for the response promised by the future and returns a data
// structure with information about the transaction in the memory pool given
// its hash. | [
"Receive",
"waits",
"for",
"the",
"response",
"promised",
"by",
"the",
"future",
"and",
"returns",
"a",
"data",
"structure",
"with",
"information",
"about",
"the",
"transaction",
"in",
"the",
"memory",
"pool",
"given",
"its",
"hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L436-L450 |
163,210 | btcsuite/btcd | rpcclient/chain.go | GetMempoolEntryAsync | func (c *Client) GetMempoolEntryAsync(txHash string) FutureGetMempoolEntryResult {
cmd := btcjson.NewGetMempoolEntryCmd(txHash)
return c.sendCmd(cmd)
} | go | func (c *Client) GetMempoolEntryAsync(txHash string) FutureGetMempoolEntryResult {
cmd := btcjson.NewGetMempoolEntryCmd(txHash)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetMempoolEntryAsync",
"(",
"txHash",
"string",
")",
"FutureGetMempoolEntryResult",
"{",
"cmd",
":=",
"btcjson",
".",
"NewGetMempoolEntryCmd",
"(",
"txHash",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\... | // GetMempoolEntryAsync returns an instance of a type that can be used to get the
// result of the RPC at some future time by invoking the Receive function on the
// returned instance.
//
// See GetMempoolEntry for the blocking version and more details. | [
"GetMempoolEntryAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L457-L460 |
163,211 | btcsuite/btcd | rpcclient/chain.go | GetMempoolEntry | func (c *Client) GetMempoolEntry(txHash string) (*btcjson.GetMempoolEntryResult, error) {
return c.GetMempoolEntryAsync(txHash).Receive()
} | go | func (c *Client) GetMempoolEntry(txHash string) (*btcjson.GetMempoolEntryResult, error) {
return c.GetMempoolEntryAsync(txHash).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetMempoolEntry",
"(",
"txHash",
"string",
")",
"(",
"*",
"btcjson",
".",
"GetMempoolEntryResult",
",",
"error",
")",
"{",
"return",
"c",
".",
"GetMempoolEntryAsync",
"(",
"txHash",
")",
".",
"Receive",
"(",
")",
"\... | // GetMempoolEntry returns a data structure with information about the
// transaction in the memory pool given its hash. | [
"GetMempoolEntry",
"returns",
"a",
"data",
"structure",
"with",
"information",
"about",
"the",
"transaction",
"in",
"the",
"memory",
"pool",
"given",
"its",
"hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L464-L466 |
163,212 | btcsuite/btcd | rpcclient/chain.go | Receive | func (r FutureGetRawMempoolResult) Receive() ([]*chainhash.Hash, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal the result as an array of strings.
var txHashStrs []string
err = json.Unmarshal(res, &txHashStrs)
if err != nil {
return nil, err
}
// Create a slice of ShaHash arrays from the string slice.
txHashes := make([]*chainhash.Hash, 0, len(txHashStrs))
for _, hashStr := range txHashStrs {
txHash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
return nil, err
}
txHashes = append(txHashes, txHash)
}
return txHashes, nil
} | go | func (r FutureGetRawMempoolResult) Receive() ([]*chainhash.Hash, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal the result as an array of strings.
var txHashStrs []string
err = json.Unmarshal(res, &txHashStrs)
if err != nil {
return nil, err
}
// Create a slice of ShaHash arrays from the string slice.
txHashes := make([]*chainhash.Hash, 0, len(txHashStrs))
for _, hashStr := range txHashStrs {
txHash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
return nil, err
}
txHashes = append(txHashes, txHash)
}
return txHashes, nil
} | [
"func",
"(",
"r",
"FutureGetRawMempoolResult",
")",
"Receive",
"(",
")",
"(",
"[",
"]",
"*",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"receiveFuture",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"... | // Receive waits for the response promised by the future and returns the hashes
// of all transactions in the memory pool. | [
"Receive",
"waits",
"for",
"the",
"response",
"promised",
"by",
"the",
"future",
"and",
"returns",
"the",
"hashes",
"of",
"all",
"transactions",
"in",
"the",
"memory",
"pool",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L474-L498 |
163,213 | btcsuite/btcd | rpcclient/chain.go | GetRawMempoolAsync | func (c *Client) GetRawMempoolAsync() FutureGetRawMempoolResult {
cmd := btcjson.NewGetRawMempoolCmd(btcjson.Bool(false))
return c.sendCmd(cmd)
} | go | func (c *Client) GetRawMempoolAsync() FutureGetRawMempoolResult {
cmd := btcjson.NewGetRawMempoolCmd(btcjson.Bool(false))
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetRawMempoolAsync",
"(",
")",
"FutureGetRawMempoolResult",
"{",
"cmd",
":=",
"btcjson",
".",
"NewGetRawMempoolCmd",
"(",
"btcjson",
".",
"Bool",
"(",
"false",
")",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd"... | // GetRawMempoolAsync returns an instance of a type that can be used to get the
// result of the RPC at some future time by invoking the Receive function on the
// returned instance.
//
// See GetRawMempool for the blocking version and more details. | [
"GetRawMempoolAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
"i... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L505-L508 |
163,214 | btcsuite/btcd | rpcclient/chain.go | Receive | func (r FutureGetRawMempoolVerboseResult) Receive() (map[string]btcjson.GetRawMempoolVerboseResult, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal the result as a map of strings (tx shas) to their detailed
// results.
var mempoolItems map[string]btcjson.GetRawMempoolVerboseResult
err = json.Unmarshal(res, &mempoolItems)
if err != nil {
return nil, err
}
return mempoolItems, nil
} | go | func (r FutureGetRawMempoolVerboseResult) Receive() (map[string]btcjson.GetRawMempoolVerboseResult, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal the result as a map of strings (tx shas) to their detailed
// results.
var mempoolItems map[string]btcjson.GetRawMempoolVerboseResult
err = json.Unmarshal(res, &mempoolItems)
if err != nil {
return nil, err
}
return mempoolItems, nil
} | [
"func",
"(",
"r",
"FutureGetRawMempoolVerboseResult",
")",
"Receive",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"btcjson",
".",
"GetRawMempoolVerboseResult",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"receiveFuture",
"(",
"r",
")",
"\n",
"if",
"err"... | // Receive waits for the response promised by the future and returns a map of
// transaction hashes to an associated data structure with information about the
// transaction for all transactions in the memory pool. | [
"Receive",
"waits",
"for",
"the",
"response",
"promised",
"by",
"the",
"future",
"and",
"returns",
"a",
"map",
"of",
"transaction",
"hashes",
"to",
"an",
"associated",
"data",
"structure",
"with",
"information",
"about",
"the",
"transaction",
"for",
"all",
"tr... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L525-L539 |
163,215 | btcsuite/btcd | rpcclient/chain.go | GetRawMempoolVerboseAsync | func (c *Client) GetRawMempoolVerboseAsync() FutureGetRawMempoolVerboseResult {
cmd := btcjson.NewGetRawMempoolCmd(btcjson.Bool(true))
return c.sendCmd(cmd)
} | go | func (c *Client) GetRawMempoolVerboseAsync() FutureGetRawMempoolVerboseResult {
cmd := btcjson.NewGetRawMempoolCmd(btcjson.Bool(true))
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetRawMempoolVerboseAsync",
"(",
")",
"FutureGetRawMempoolVerboseResult",
"{",
"cmd",
":=",
"btcjson",
".",
"NewGetRawMempoolCmd",
"(",
"btcjson",
".",
"Bool",
"(",
"true",
")",
")",
"\n",
"return",
"c",
".",
"sendCmd",
... | // GetRawMempoolVerboseAsync returns an instance of a type that can be used to
// get the result of the RPC at some future time by invoking the Receive
// function on the returned instance.
//
// See GetRawMempoolVerbose for the blocking version and more details. | [
"GetRawMempoolVerboseAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L546-L549 |
163,216 | btcsuite/btcd | rpcclient/chain.go | GetRawMempoolVerbose | func (c *Client) GetRawMempoolVerbose() (map[string]btcjson.GetRawMempoolVerboseResult, error) {
return c.GetRawMempoolVerboseAsync().Receive()
} | go | func (c *Client) GetRawMempoolVerbose() (map[string]btcjson.GetRawMempoolVerboseResult, error) {
return c.GetRawMempoolVerboseAsync().Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetRawMempoolVerbose",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"btcjson",
".",
"GetRawMempoolVerboseResult",
",",
"error",
")",
"{",
"return",
"c",
".",
"GetRawMempoolVerboseAsync",
"(",
")",
".",
"Receive",
"(",
")... | // GetRawMempoolVerbose returns a map of transaction hashes to an associated
// data structure with information about the transaction for all transactions in
// the memory pool.
//
// See GetRawMempool to retrieve only the transaction hashes instead. | [
"GetRawMempoolVerbose",
"returns",
"a",
"map",
"of",
"transaction",
"hashes",
"to",
"an",
"associated",
"data",
"structure",
"with",
"information",
"about",
"the",
"transaction",
"for",
"all",
"transactions",
"in",
"the",
"memory",
"pool",
".",
"See",
"GetRawMempo... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L556-L558 |
163,217 | btcsuite/btcd | rpcclient/chain.go | EstimateFeeAsync | func (c *Client) EstimateFeeAsync(numBlocks int64) FutureEstimateFeeResult {
cmd := btcjson.NewEstimateFeeCmd(numBlocks)
return c.sendCmd(cmd)
} | go | func (c *Client) EstimateFeeAsync(numBlocks int64) FutureEstimateFeeResult {
cmd := btcjson.NewEstimateFeeCmd(numBlocks)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"EstimateFeeAsync",
"(",
"numBlocks",
"int64",
")",
"FutureEstimateFeeResult",
"{",
"cmd",
":=",
"btcjson",
".",
"NewEstimateFeeCmd",
"(",
"numBlocks",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"... | // EstimateFeeAsync returns an instance of a type that can be used to get the result
// of the RPC at some future time by invoking the Receive function on the
// returned instance.
//
// See EstimateFee for the blocking version and more details. | [
"EstimateFeeAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
"ins... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L587-L590 |
163,218 | btcsuite/btcd | rpcclient/chain.go | EstimateFee | func (c *Client) EstimateFee(numBlocks int64) (float64, error) {
return c.EstimateFeeAsync(numBlocks).Receive()
} | go | func (c *Client) EstimateFee(numBlocks int64) (float64, error) {
return c.EstimateFeeAsync(numBlocks).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"EstimateFee",
"(",
"numBlocks",
"int64",
")",
"(",
"float64",
",",
"error",
")",
"{",
"return",
"c",
".",
"EstimateFeeAsync",
"(",
"numBlocks",
")",
".",
"Receive",
"(",
")",
"\n",
"}"
] | // EstimateFee provides an estimated fee in bitcoins per kilobyte. | [
"EstimateFee",
"provides",
"an",
"estimated",
"fee",
"in",
"bitcoins",
"per",
"kilobyte",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L593-L595 |
163,219 | btcsuite/btcd | rpcclient/chain.go | Receive | func (r FutureVerifyChainResult) Receive() (bool, error) {
res, err := receiveFuture(r)
if err != nil {
return false, err
}
// Unmarshal the result as a boolean.
var verified bool
err = json.Unmarshal(res, &verified)
if err != nil {
return false, err
}
return verified, nil
} | go | func (r FutureVerifyChainResult) Receive() (bool, error) {
res, err := receiveFuture(r)
if err != nil {
return false, err
}
// Unmarshal the result as a boolean.
var verified bool
err = json.Unmarshal(res, &verified)
if err != nil {
return false, err
}
return verified, nil
} | [
"func",
"(",
"r",
"FutureVerifyChainResult",
")",
"Receive",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"receiveFuture",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\... | // Receive waits for the response promised by the future and returns whether
// or not the chain verified based on the check level and number of blocks
// to verify specified in the original call. | [
"Receive",
"waits",
"for",
"the",
"response",
"promised",
"by",
"the",
"future",
"and",
"returns",
"whether",
"or",
"not",
"the",
"chain",
"verified",
"based",
"on",
"the",
"check",
"level",
"and",
"number",
"of",
"blocks",
"to",
"verify",
"specified",
"in",... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L605-L618 |
163,220 | btcsuite/btcd | rpcclient/chain.go | VerifyChainAsync | func (c *Client) VerifyChainAsync() FutureVerifyChainResult {
cmd := btcjson.NewVerifyChainCmd(nil, nil)
return c.sendCmd(cmd)
} | go | func (c *Client) VerifyChainAsync() FutureVerifyChainResult {
cmd := btcjson.NewVerifyChainCmd(nil, nil)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"VerifyChainAsync",
"(",
")",
"FutureVerifyChainResult",
"{",
"cmd",
":=",
"btcjson",
".",
"NewVerifyChainCmd",
"(",
"nil",
",",
"nil",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // VerifyChainAsync returns an instance of a type that can be used to get the
// result of the RPC at some future time by invoking the Receive function on the
// returned instance.
//
// See VerifyChain for the blocking version and more details. | [
"VerifyChainAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
"ins... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L625-L628 |
163,221 | btcsuite/btcd | rpcclient/chain.go | VerifyChainLevelAsync | func (c *Client) VerifyChainLevelAsync(checkLevel int32) FutureVerifyChainResult {
cmd := btcjson.NewVerifyChainCmd(&checkLevel, nil)
return c.sendCmd(cmd)
} | go | func (c *Client) VerifyChainLevelAsync(checkLevel int32) FutureVerifyChainResult {
cmd := btcjson.NewVerifyChainCmd(&checkLevel, nil)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"VerifyChainLevelAsync",
"(",
"checkLevel",
"int32",
")",
"FutureVerifyChainResult",
"{",
"cmd",
":=",
"btcjson",
".",
"NewVerifyChainCmd",
"(",
"&",
"checkLevel",
",",
"nil",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(... | // VerifyChainLevelAsync returns an instance of a type that can be used to get
// the result of the RPC at some future time by invoking the Receive function on
// the returned instance.
//
// See VerifyChainLevel for the blocking version and more details. | [
"VerifyChainLevelAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L643-L646 |
163,222 | btcsuite/btcd | rpcclient/chain.go | VerifyChainLevel | func (c *Client) VerifyChainLevel(checkLevel int32) (bool, error) {
return c.VerifyChainLevelAsync(checkLevel).Receive()
} | go | func (c *Client) VerifyChainLevel(checkLevel int32) (bool, error) {
return c.VerifyChainLevelAsync(checkLevel).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"VerifyChainLevel",
"(",
"checkLevel",
"int32",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"c",
".",
"VerifyChainLevelAsync",
"(",
"checkLevel",
")",
".",
"Receive",
"(",
")",
"\n",
"}"
] | // VerifyChainLevel requests the server to verify the block chain database using
// the passed check level and default number of blocks to verify.
//
// The check level controls how thorough the verification is with higher numbers
// increasing the amount of checks done as consequently how long the
// verification takes.
//
// See VerifyChain to use the default check level and VerifyChainBlocks to
// override the number of blocks to verify. | [
"VerifyChainLevel",
"requests",
"the",
"server",
"to",
"verify",
"the",
"block",
"chain",
"database",
"using",
"the",
"passed",
"check",
"level",
"and",
"default",
"number",
"of",
"blocks",
"to",
"verify",
".",
"The",
"check",
"level",
"controls",
"how",
"thor... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L657-L659 |
163,223 | btcsuite/btcd | rpcclient/chain.go | VerifyChainBlocksAsync | func (c *Client) VerifyChainBlocksAsync(checkLevel, numBlocks int32) FutureVerifyChainResult {
cmd := btcjson.NewVerifyChainCmd(&checkLevel, &numBlocks)
return c.sendCmd(cmd)
} | go | func (c *Client) VerifyChainBlocksAsync(checkLevel, numBlocks int32) FutureVerifyChainResult {
cmd := btcjson.NewVerifyChainCmd(&checkLevel, &numBlocks)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"VerifyChainBlocksAsync",
"(",
"checkLevel",
",",
"numBlocks",
"int32",
")",
"FutureVerifyChainResult",
"{",
"cmd",
":=",
"btcjson",
".",
"NewVerifyChainCmd",
"(",
"&",
"checkLevel",
",",
"&",
"numBlocks",
")",
"\n",
"retu... | // VerifyChainBlocksAsync returns an instance of a type that can be used to get
// the result of the RPC at some future time by invoking the Receive function on
// the returned instance.
//
// See VerifyChainBlocks for the blocking version and more details. | [
"VerifyChainBlocksAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L666-L669 |
163,224 | btcsuite/btcd | rpcclient/chain.go | VerifyChainBlocks | func (c *Client) VerifyChainBlocks(checkLevel, numBlocks int32) (bool, error) {
return c.VerifyChainBlocksAsync(checkLevel, numBlocks).Receive()
} | go | func (c *Client) VerifyChainBlocks(checkLevel, numBlocks int32) (bool, error) {
return c.VerifyChainBlocksAsync(checkLevel, numBlocks).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"VerifyChainBlocks",
"(",
"checkLevel",
",",
"numBlocks",
"int32",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"c",
".",
"VerifyChainBlocksAsync",
"(",
"checkLevel",
",",
"numBlocks",
")",
".",
"Receive",
"(",
... | // VerifyChainBlocks requests the server to verify the block chain database
// using the passed check level and number of blocks to verify.
//
// The check level controls how thorough the verification is with higher numbers
// increasing the amount of checks done as consequently how long the
// verification takes.
//
// The number of blocks refers to the number of blocks from the end of the
// current longest chain.
//
// See VerifyChain and VerifyChainLevel to use defaults. | [
"VerifyChainBlocks",
"requests",
"the",
"server",
"to",
"verify",
"the",
"block",
"chain",
"database",
"using",
"the",
"passed",
"check",
"level",
"and",
"number",
"of",
"blocks",
"to",
"verify",
".",
"The",
"check",
"level",
"controls",
"how",
"thorough",
"th... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L682-L684 |
163,225 | btcsuite/btcd | rpcclient/chain.go | GetTxOutAsync | func (c *Client) GetTxOutAsync(txHash *chainhash.Hash, index uint32, mempool bool) FutureGetTxOutResult {
hash := ""
if txHash != nil {
hash = txHash.String()
}
cmd := btcjson.NewGetTxOutCmd(hash, index, &mempool)
return c.sendCmd(cmd)
} | go | func (c *Client) GetTxOutAsync(txHash *chainhash.Hash, index uint32, mempool bool) FutureGetTxOutResult {
hash := ""
if txHash != nil {
hash = txHash.String()
}
cmd := btcjson.NewGetTxOutCmd(hash, index, &mempool)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetTxOutAsync",
"(",
"txHash",
"*",
"chainhash",
".",
"Hash",
",",
"index",
"uint32",
",",
"mempool",
"bool",
")",
"FutureGetTxOutResult",
"{",
"hash",
":=",
"\"",
"\"",
"\n",
"if",
"txHash",
"!=",
"nil",
"{",
"ha... | // GetTxOutAsync returns an instance of a type that can be used to get
// the result of the RPC at some future time by invoking the Receive function on
// the returned instance.
//
// See GetTxOut for the blocking version and more details. | [
"GetTxOutAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
"instan... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L719-L727 |
163,226 | btcsuite/btcd | rpcclient/chain.go | GetTxOut | func (c *Client) GetTxOut(txHash *chainhash.Hash, index uint32, mempool bool) (*btcjson.GetTxOutResult, error) {
return c.GetTxOutAsync(txHash, index, mempool).Receive()
} | go | func (c *Client) GetTxOut(txHash *chainhash.Hash, index uint32, mempool bool) (*btcjson.GetTxOutResult, error) {
return c.GetTxOutAsync(txHash, index, mempool).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetTxOut",
"(",
"txHash",
"*",
"chainhash",
".",
"Hash",
",",
"index",
"uint32",
",",
"mempool",
"bool",
")",
"(",
"*",
"btcjson",
".",
"GetTxOutResult",
",",
"error",
")",
"{",
"return",
"c",
".",
"GetTxOutAsync"... | // GetTxOut returns the transaction output info if it's unspent and
// nil, otherwise. | [
"GetTxOut",
"returns",
"the",
"transaction",
"output",
"info",
"if",
"it",
"s",
"unspent",
"and",
"nil",
"otherwise",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L731-L733 |
163,227 | btcsuite/btcd | rpcclient/chain.go | InvalidateBlockAsync | func (c *Client) InvalidateBlockAsync(blockHash *chainhash.Hash) FutureInvalidateBlockResult {
hash := ""
if blockHash != nil {
hash = blockHash.String()
}
cmd := btcjson.NewInvalidateBlockCmd(hash)
return c.sendCmd(cmd)
} | go | func (c *Client) InvalidateBlockAsync(blockHash *chainhash.Hash) FutureInvalidateBlockResult {
hash := ""
if blockHash != nil {
hash = blockHash.String()
}
cmd := btcjson.NewInvalidateBlockCmd(hash)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"InvalidateBlockAsync",
"(",
"blockHash",
"*",
"chainhash",
".",
"Hash",
")",
"FutureInvalidateBlockResult",
"{",
"hash",
":=",
"\"",
"\"",
"\n",
"if",
"blockHash",
"!=",
"nil",
"{",
"hash",
"=",
"blockHash",
".",
"Str... | // InvalidateBlockAsync returns an instance of a type that can be used to get the
// result of the RPC at some future time by invoking the Receive function on the
// returned instance.
//
// See InvalidateBlock for the blocking version and more details. | [
"InvalidateBlockAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L807-L815 |
163,228 | btcsuite/btcd | rpcclient/chain.go | InvalidateBlock | func (c *Client) InvalidateBlock(blockHash *chainhash.Hash) error {
return c.InvalidateBlockAsync(blockHash).Receive()
} | go | func (c *Client) InvalidateBlock(blockHash *chainhash.Hash) error {
return c.InvalidateBlockAsync(blockHash).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"InvalidateBlock",
"(",
"blockHash",
"*",
"chainhash",
".",
"Hash",
")",
"error",
"{",
"return",
"c",
".",
"InvalidateBlockAsync",
"(",
"blockHash",
")",
".",
"Receive",
"(",
")",
"\n",
"}"
] | // InvalidateBlock invalidates a specific block. | [
"InvalidateBlock",
"invalidates",
"a",
"specific",
"block",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L818-L820 |
163,229 | btcsuite/btcd | rpcclient/chain.go | Receive | func (r FutureGetCFilterResult) Receive() (*wire.MsgCFilter, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a string.
var filterHex string
err = json.Unmarshal(res, &filterHex)
if err != nil {
return nil, err
}
// Decode the serialized cf hex to raw bytes.
serializedFilter, err := hex.DecodeString(filterHex)
if err != nil {
return nil, err
}
// Assign the filter bytes to the correct field of the wire message.
// We aren't going to set the block hash or extended flag, since we
// don't actually get that back in the RPC response.
var msgCFilter wire.MsgCFilter
msgCFilter.Data = serializedFilter
return &msgCFilter, nil
} | go | func (r FutureGetCFilterResult) Receive() (*wire.MsgCFilter, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a string.
var filterHex string
err = json.Unmarshal(res, &filterHex)
if err != nil {
return nil, err
}
// Decode the serialized cf hex to raw bytes.
serializedFilter, err := hex.DecodeString(filterHex)
if err != nil {
return nil, err
}
// Assign the filter bytes to the correct field of the wire message.
// We aren't going to set the block hash or extended flag, since we
// don't actually get that back in the RPC response.
var msgCFilter wire.MsgCFilter
msgCFilter.Data = serializedFilter
return &msgCFilter, nil
} | [
"func",
"(",
"r",
"FutureGetCFilterResult",
")",
"Receive",
"(",
")",
"(",
"*",
"wire",
".",
"MsgCFilter",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"receiveFuture",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"... | // Receive waits for the response promised by the future and returns the raw
// filter requested from the server given its block hash. | [
"Receive",
"waits",
"for",
"the",
"response",
"promised",
"by",
"the",
"future",
"and",
"returns",
"the",
"raw",
"filter",
"requested",
"from",
"the",
"server",
"given",
"its",
"block",
"hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L828-L853 |
163,230 | btcsuite/btcd | rpcclient/chain.go | GetCFilterAsync | func (c *Client) GetCFilterAsync(blockHash *chainhash.Hash,
filterType wire.FilterType) FutureGetCFilterResult {
hash := ""
if blockHash != nil {
hash = blockHash.String()
}
cmd := btcjson.NewGetCFilterCmd(hash, filterType)
return c.sendCmd(cmd)
} | go | func (c *Client) GetCFilterAsync(blockHash *chainhash.Hash,
filterType wire.FilterType) FutureGetCFilterResult {
hash := ""
if blockHash != nil {
hash = blockHash.String()
}
cmd := btcjson.NewGetCFilterCmd(hash, filterType)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetCFilterAsync",
"(",
"blockHash",
"*",
"chainhash",
".",
"Hash",
",",
"filterType",
"wire",
".",
"FilterType",
")",
"FutureGetCFilterResult",
"{",
"hash",
":=",
"\"",
"\"",
"\n",
"if",
"blockHash",
"!=",
"nil",
"{",... | // GetCFilterAsync returns an instance of a type that can be used to get the
// result of the RPC at some future time by invoking the Receive function on the
// returned instance.
//
// See GetCFilter for the blocking version and more details. | [
"GetCFilterAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
"inst... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L860-L869 |
163,231 | btcsuite/btcd | rpcclient/chain.go | GetCFilter | func (c *Client) GetCFilter(blockHash *chainhash.Hash,
filterType wire.FilterType) (*wire.MsgCFilter, error) {
return c.GetCFilterAsync(blockHash, filterType).Receive()
} | go | func (c *Client) GetCFilter(blockHash *chainhash.Hash,
filterType wire.FilterType) (*wire.MsgCFilter, error) {
return c.GetCFilterAsync(blockHash, filterType).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetCFilter",
"(",
"blockHash",
"*",
"chainhash",
".",
"Hash",
",",
"filterType",
"wire",
".",
"FilterType",
")",
"(",
"*",
"wire",
".",
"MsgCFilter",
",",
"error",
")",
"{",
"return",
"c",
".",
"GetCFilterAsync",
... | // GetCFilter returns a raw filter from the server given its block hash. | [
"GetCFilter",
"returns",
"a",
"raw",
"filter",
"from",
"the",
"server",
"given",
"its",
"block",
"hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L872-L875 |
163,232 | btcsuite/btcd | rpcclient/chain.go | Receive | func (r FutureGetCFilterHeaderResult) Receive() (*wire.MsgCFHeaders, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a string.
var headerHex string
err = json.Unmarshal(res, &headerHex)
if err != nil {
return nil, err
}
// Assign the decoded header into a hash
headerHash, err := chainhash.NewHashFromStr(headerHex)
if err != nil {
return nil, err
}
// Assign the hash to a headers message and return it.
msgCFHeaders := wire.MsgCFHeaders{PrevFilterHeader: *headerHash}
return &msgCFHeaders, nil
} | go | func (r FutureGetCFilterHeaderResult) Receive() (*wire.MsgCFHeaders, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a string.
var headerHex string
err = json.Unmarshal(res, &headerHex)
if err != nil {
return nil, err
}
// Assign the decoded header into a hash
headerHash, err := chainhash.NewHashFromStr(headerHex)
if err != nil {
return nil, err
}
// Assign the hash to a headers message and return it.
msgCFHeaders := wire.MsgCFHeaders{PrevFilterHeader: *headerHash}
return &msgCFHeaders, nil
} | [
"func",
"(",
"r",
"FutureGetCFilterHeaderResult",
")",
"Receive",
"(",
")",
"(",
"*",
"wire",
".",
"MsgCFHeaders",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"receiveFuture",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
... | // Receive waits for the response promised by the future and returns the raw
// filter header requested from the server given its block hash. | [
"Receive",
"waits",
"for",
"the",
"response",
"promised",
"by",
"the",
"future",
"and",
"returns",
"the",
"raw",
"filter",
"header",
"requested",
"from",
"the",
"server",
"given",
"its",
"block",
"hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L883-L906 |
163,233 | btcsuite/btcd | rpcclient/chain.go | GetCFilterHeaderAsync | func (c *Client) GetCFilterHeaderAsync(blockHash *chainhash.Hash,
filterType wire.FilterType) FutureGetCFilterHeaderResult {
hash := ""
if blockHash != nil {
hash = blockHash.String()
}
cmd := btcjson.NewGetCFilterHeaderCmd(hash, filterType)
return c.sendCmd(cmd)
} | go | func (c *Client) GetCFilterHeaderAsync(blockHash *chainhash.Hash,
filterType wire.FilterType) FutureGetCFilterHeaderResult {
hash := ""
if blockHash != nil {
hash = blockHash.String()
}
cmd := btcjson.NewGetCFilterHeaderCmd(hash, filterType)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetCFilterHeaderAsync",
"(",
"blockHash",
"*",
"chainhash",
".",
"Hash",
",",
"filterType",
"wire",
".",
"FilterType",
")",
"FutureGetCFilterHeaderResult",
"{",
"hash",
":=",
"\"",
"\"",
"\n",
"if",
"blockHash",
"!=",
"... | // GetCFilterHeaderAsync returns an instance of a type that can be used to get
// the result of the RPC at some future time by invoking the Receive function
// on the returned instance.
//
// See GetCFilterHeader for the blocking version and more details. | [
"GetCFilterHeaderAsync",
"returns",
"an",
"instance",
"of",
"a",
"type",
"that",
"can",
"be",
"used",
"to",
"get",
"the",
"result",
"of",
"the",
"RPC",
"at",
"some",
"future",
"time",
"by",
"invoking",
"the",
"Receive",
"function",
"on",
"the",
"returned",
... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L913-L922 |
163,234 | btcsuite/btcd | rpcclient/chain.go | GetCFilterHeader | func (c *Client) GetCFilterHeader(blockHash *chainhash.Hash,
filterType wire.FilterType) (*wire.MsgCFHeaders, error) {
return c.GetCFilterHeaderAsync(blockHash, filterType).Receive()
} | go | func (c *Client) GetCFilterHeader(blockHash *chainhash.Hash,
filterType wire.FilterType) (*wire.MsgCFHeaders, error) {
return c.GetCFilterHeaderAsync(blockHash, filterType).Receive()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetCFilterHeader",
"(",
"blockHash",
"*",
"chainhash",
".",
"Hash",
",",
"filterType",
"wire",
".",
"FilterType",
")",
"(",
"*",
"wire",
".",
"MsgCFHeaders",
",",
"error",
")",
"{",
"return",
"c",
".",
"GetCFilterHe... | // GetCFilterHeader returns a raw filter header from the server given its block
// hash. | [
"GetCFilterHeader",
"returns",
"a",
"raw",
"filter",
"header",
"from",
"the",
"server",
"given",
"its",
"block",
"hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L926-L929 |
163,235 | btcsuite/btcd | wire/msggetcfilters.go | NewMsgGetCFilters | func NewMsgGetCFilters(filterType FilterType, startHeight uint32,
stopHash *chainhash.Hash) *MsgGetCFilters {
return &MsgGetCFilters{
FilterType: filterType,
StartHeight: startHeight,
StopHash: *stopHash,
}
} | go | func NewMsgGetCFilters(filterType FilterType, startHeight uint32,
stopHash *chainhash.Hash) *MsgGetCFilters {
return &MsgGetCFilters{
FilterType: filterType,
StartHeight: startHeight,
StopHash: *stopHash,
}
} | [
"func",
"NewMsgGetCFilters",
"(",
"filterType",
"FilterType",
",",
"startHeight",
"uint32",
",",
"stopHash",
"*",
"chainhash",
".",
"Hash",
")",
"*",
"MsgGetCFilters",
"{",
"return",
"&",
"MsgGetCFilters",
"{",
"FilterType",
":",
"filterType",
",",
"StartHeight",
... | // NewMsgGetCFilters returns a new bitcoin getcfilters message that conforms to
// the Message interface using the passed parameters and defaults for the
// remaining fields. | [
"NewMsgGetCFilters",
"returns",
"a",
"new",
"bitcoin",
"getcfilters",
"message",
"that",
"conforms",
"to",
"the",
"Message",
"interface",
"using",
"the",
"passed",
"parameters",
"and",
"defaults",
"for",
"the",
"remaining",
"fields",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msggetcfilters.go#L74-L81 |
163,236 | btcsuite/btcd | server.go | forAllPeers | func (ps *peerState) forAllPeers(closure func(sp *serverPeer)) {
for _, e := range ps.inboundPeers {
closure(e)
}
ps.forAllOutboundPeers(closure)
} | go | func (ps *peerState) forAllPeers(closure func(sp *serverPeer)) {
for _, e := range ps.inboundPeers {
closure(e)
}
ps.forAllOutboundPeers(closure)
} | [
"func",
"(",
"ps",
"*",
"peerState",
")",
"forAllPeers",
"(",
"closure",
"func",
"(",
"sp",
"*",
"serverPeer",
")",
")",
"{",
"for",
"_",
",",
"e",
":=",
"range",
"ps",
".",
"inboundPeers",
"{",
"closure",
"(",
"e",
")",
"\n",
"}",
"\n",
"ps",
".... | // forAllPeers is a helper function that runs closure on all peers known to
// peerState. | [
"forAllPeers",
"is",
"a",
"helper",
"function",
"that",
"runs",
"closure",
"on",
"all",
"peers",
"known",
"to",
"peerState",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L182-L187 |
163,237 | btcsuite/btcd | server.go | newServerPeer | func newServerPeer(s *server, isPersistent bool) *serverPeer {
return &serverPeer{
server: s,
persistent: isPersistent,
filter: bloom.LoadFilter(nil),
knownAddresses: make(map[string]struct{}),
quit: make(chan struct{}),
txProcessed: make(chan struct{}, 1),
blockProcessed: make(chan struct{}, 1),
}
} | go | func newServerPeer(s *server, isPersistent bool) *serverPeer {
return &serverPeer{
server: s,
persistent: isPersistent,
filter: bloom.LoadFilter(nil),
knownAddresses: make(map[string]struct{}),
quit: make(chan struct{}),
txProcessed: make(chan struct{}, 1),
blockProcessed: make(chan struct{}, 1),
}
} | [
"func",
"newServerPeer",
"(",
"s",
"*",
"server",
",",
"isPersistent",
"bool",
")",
"*",
"serverPeer",
"{",
"return",
"&",
"serverPeer",
"{",
"server",
":",
"s",
",",
"persistent",
":",
"isPersistent",
",",
"filter",
":",
"bloom",
".",
"LoadFilter",
"(",
... | // newServerPeer returns a new serverPeer instance. The peer needs to be set by
// the caller. | [
"newServerPeer",
"returns",
"a",
"new",
"serverPeer",
"instance",
".",
"The",
"peer",
"needs",
"to",
"be",
"set",
"by",
"the",
"caller",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L286-L296 |
163,238 | btcsuite/btcd | server.go | addressKnown | func (sp *serverPeer) addressKnown(na *wire.NetAddress) bool {
_, exists := sp.knownAddresses[addrmgr.NetAddressKey(na)]
return exists
} | go | func (sp *serverPeer) addressKnown(na *wire.NetAddress) bool {
_, exists := sp.knownAddresses[addrmgr.NetAddressKey(na)]
return exists
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"addressKnown",
"(",
"na",
"*",
"wire",
".",
"NetAddress",
")",
"bool",
"{",
"_",
",",
"exists",
":=",
"sp",
".",
"knownAddresses",
"[",
"addrmgr",
".",
"NetAddressKey",
"(",
"na",
")",
"]",
"\n",
"return",
... | // addressKnown true if the given address is already known to the peer. | [
"addressKnown",
"true",
"if",
"the",
"given",
"address",
"is",
"already",
"known",
"to",
"the",
"peer",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L314-L317 |
163,239 | btcsuite/btcd | server.go | setDisableRelayTx | func (sp *serverPeer) setDisableRelayTx(disable bool) {
sp.relayMtx.Lock()
sp.disableRelayTx = disable
sp.relayMtx.Unlock()
} | go | func (sp *serverPeer) setDisableRelayTx(disable bool) {
sp.relayMtx.Lock()
sp.disableRelayTx = disable
sp.relayMtx.Unlock()
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"setDisableRelayTx",
"(",
"disable",
"bool",
")",
"{",
"sp",
".",
"relayMtx",
".",
"Lock",
"(",
")",
"\n",
"sp",
".",
"disableRelayTx",
"=",
"disable",
"\n",
"sp",
".",
"relayMtx",
".",
"Unlock",
"(",
")",
"... | // setDisableRelayTx toggles relaying of transactions for the given peer.
// It is safe for concurrent access. | [
"setDisableRelayTx",
"toggles",
"relaying",
"of",
"transactions",
"for",
"the",
"given",
"peer",
".",
"It",
"is",
"safe",
"for",
"concurrent",
"access",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L321-L325 |
163,240 | btcsuite/btcd | server.go | relayTxDisabled | func (sp *serverPeer) relayTxDisabled() bool {
sp.relayMtx.Lock()
isDisabled := sp.disableRelayTx
sp.relayMtx.Unlock()
return isDisabled
} | go | func (sp *serverPeer) relayTxDisabled() bool {
sp.relayMtx.Lock()
isDisabled := sp.disableRelayTx
sp.relayMtx.Unlock()
return isDisabled
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"relayTxDisabled",
"(",
")",
"bool",
"{",
"sp",
".",
"relayMtx",
".",
"Lock",
"(",
")",
"\n",
"isDisabled",
":=",
"sp",
".",
"disableRelayTx",
"\n",
"sp",
".",
"relayMtx",
".",
"Unlock",
"(",
")",
"\n\n",
"r... | // relayTxDisabled returns whether or not relaying of transactions for the given
// peer is disabled.
// It is safe for concurrent access. | [
"relayTxDisabled",
"returns",
"whether",
"or",
"not",
"relaying",
"of",
"transactions",
"for",
"the",
"given",
"peer",
"is",
"disabled",
".",
"It",
"is",
"safe",
"for",
"concurrent",
"access",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L330-L336 |
163,241 | btcsuite/btcd | server.go | pushAddrMsg | func (sp *serverPeer) pushAddrMsg(addresses []*wire.NetAddress) {
// Filter addresses already known to the peer.
addrs := make([]*wire.NetAddress, 0, len(addresses))
for _, addr := range addresses {
if !sp.addressKnown(addr) {
addrs = append(addrs, addr)
}
}
known, err := sp.PushAddrMsg(addrs)
if err != nil {
peerLog.Errorf("Can't push address message to %s: %v", sp.Peer, err)
sp.Disconnect()
return
}
sp.addKnownAddresses(known)
} | go | func (sp *serverPeer) pushAddrMsg(addresses []*wire.NetAddress) {
// Filter addresses already known to the peer.
addrs := make([]*wire.NetAddress, 0, len(addresses))
for _, addr := range addresses {
if !sp.addressKnown(addr) {
addrs = append(addrs, addr)
}
}
known, err := sp.PushAddrMsg(addrs)
if err != nil {
peerLog.Errorf("Can't push address message to %s: %v", sp.Peer, err)
sp.Disconnect()
return
}
sp.addKnownAddresses(known)
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"pushAddrMsg",
"(",
"addresses",
"[",
"]",
"*",
"wire",
".",
"NetAddress",
")",
"{",
"// Filter addresses already known to the peer.",
"addrs",
":=",
"make",
"(",
"[",
"]",
"*",
"wire",
".",
"NetAddress",
",",
"0",
... | // pushAddrMsg sends an addr message to the connected peer using the provided
// addresses. | [
"pushAddrMsg",
"sends",
"an",
"addr",
"message",
"to",
"the",
"connected",
"peer",
"using",
"the",
"provided",
"addresses",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L340-L355 |
163,242 | btcsuite/btcd | server.go | OnMemPool | func (sp *serverPeer) OnMemPool(_ *peer.Peer, msg *wire.MsgMemPool) {
// Only allow mempool requests if the server has bloom filtering
// enabled.
if sp.server.services&wire.SFNodeBloom != wire.SFNodeBloom {
peerLog.Debugf("peer %v sent mempool request with bloom "+
"filtering disabled -- disconnecting", sp)
sp.Disconnect()
return
}
// A decaying ban score increase is applied to prevent flooding.
// The ban score accumulates and passes the ban threshold if a burst of
// mempool messages comes from a peer. The score decays each minute to
// half of its value.
sp.addBanScore(0, 33, "mempool")
// Generate inventory message with the available transactions in the
// transaction memory pool. Limit it to the max allowed inventory
// per message. The NewMsgInvSizeHint function automatically limits
// the passed hint to the maximum allowed, so it's safe to pass it
// without double checking it here.
txMemPool := sp.server.txMemPool
txDescs := txMemPool.TxDescs()
invMsg := wire.NewMsgInvSizeHint(uint(len(txDescs)))
for _, txDesc := range txDescs {
// Either add all transactions when there is no bloom filter,
// or only the transactions that match the filter when there is
// one.
if !sp.filter.IsLoaded() || sp.filter.MatchTxAndUpdate(txDesc.Tx) {
iv := wire.NewInvVect(wire.InvTypeTx, txDesc.Tx.Hash())
invMsg.AddInvVect(iv)
if len(invMsg.InvList)+1 > wire.MaxInvPerMsg {
break
}
}
}
// Send the inventory message if there is anything to send.
if len(invMsg.InvList) > 0 {
sp.QueueMessage(invMsg, nil)
}
} | go | func (sp *serverPeer) OnMemPool(_ *peer.Peer, msg *wire.MsgMemPool) {
// Only allow mempool requests if the server has bloom filtering
// enabled.
if sp.server.services&wire.SFNodeBloom != wire.SFNodeBloom {
peerLog.Debugf("peer %v sent mempool request with bloom "+
"filtering disabled -- disconnecting", sp)
sp.Disconnect()
return
}
// A decaying ban score increase is applied to prevent flooding.
// The ban score accumulates and passes the ban threshold if a burst of
// mempool messages comes from a peer. The score decays each minute to
// half of its value.
sp.addBanScore(0, 33, "mempool")
// Generate inventory message with the available transactions in the
// transaction memory pool. Limit it to the max allowed inventory
// per message. The NewMsgInvSizeHint function automatically limits
// the passed hint to the maximum allowed, so it's safe to pass it
// without double checking it here.
txMemPool := sp.server.txMemPool
txDescs := txMemPool.TxDescs()
invMsg := wire.NewMsgInvSizeHint(uint(len(txDescs)))
for _, txDesc := range txDescs {
// Either add all transactions when there is no bloom filter,
// or only the transactions that match the filter when there is
// one.
if !sp.filter.IsLoaded() || sp.filter.MatchTxAndUpdate(txDesc.Tx) {
iv := wire.NewInvVect(wire.InvTypeTx, txDesc.Tx.Hash())
invMsg.AddInvVect(iv)
if len(invMsg.InvList)+1 > wire.MaxInvPerMsg {
break
}
}
}
// Send the inventory message if there is anything to send.
if len(invMsg.InvList) > 0 {
sp.QueueMessage(invMsg, nil)
}
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnMemPool",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"msg",
"*",
"wire",
".",
"MsgMemPool",
")",
"{",
"// Only allow mempool requests if the server has bloom filtering",
"// enabled.",
"if",
"sp",
".",
"server",
".",
... | // OnMemPool is invoked when a peer receives a mempool bitcoin message.
// It creates and sends an inventory message with the contents of the memory
// pool up to the maximum inventory allowed per message. When the peer has a
// bloom filter loaded, the contents are filtered accordingly. | [
"OnMemPool",
"is",
"invoked",
"when",
"a",
"peer",
"receives",
"a",
"mempool",
"bitcoin",
"message",
".",
"It",
"creates",
"and",
"sends",
"an",
"inventory",
"message",
"with",
"the",
"contents",
"of",
"the",
"memory",
"pool",
"up",
"to",
"the",
"maximum",
... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L509-L551 |
163,243 | btcsuite/btcd | server.go | OnTx | func (sp *serverPeer) OnTx(_ *peer.Peer, msg *wire.MsgTx) {
if cfg.BlocksOnly {
peerLog.Tracef("Ignoring tx %v from %v - blocksonly enabled",
msg.TxHash(), sp)
return
}
// Add the transaction to the known inventory for the peer.
// Convert the raw MsgTx to a btcutil.Tx which provides some convenience
// methods and things such as hash caching.
tx := btcutil.NewTx(msg)
iv := wire.NewInvVect(wire.InvTypeTx, tx.Hash())
sp.AddKnownInventory(iv)
// Queue the transaction up to be handled by the sync manager and
// intentionally block further receives until the transaction is fully
// processed and known good or bad. This helps prevent a malicious peer
// from queuing up a bunch of bad transactions before disconnecting (or
// being disconnected) and wasting memory.
sp.server.syncManager.QueueTx(tx, sp.Peer, sp.txProcessed)
<-sp.txProcessed
} | go | func (sp *serverPeer) OnTx(_ *peer.Peer, msg *wire.MsgTx) {
if cfg.BlocksOnly {
peerLog.Tracef("Ignoring tx %v from %v - blocksonly enabled",
msg.TxHash(), sp)
return
}
// Add the transaction to the known inventory for the peer.
// Convert the raw MsgTx to a btcutil.Tx which provides some convenience
// methods and things such as hash caching.
tx := btcutil.NewTx(msg)
iv := wire.NewInvVect(wire.InvTypeTx, tx.Hash())
sp.AddKnownInventory(iv)
// Queue the transaction up to be handled by the sync manager and
// intentionally block further receives until the transaction is fully
// processed and known good or bad. This helps prevent a malicious peer
// from queuing up a bunch of bad transactions before disconnecting (or
// being disconnected) and wasting memory.
sp.server.syncManager.QueueTx(tx, sp.Peer, sp.txProcessed)
<-sp.txProcessed
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnTx",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"msg",
"*",
"wire",
".",
"MsgTx",
")",
"{",
"if",
"cfg",
".",
"BlocksOnly",
"{",
"peerLog",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"msg",
".",
"TxHash",
"... | // OnTx is invoked when a peer receives a tx bitcoin message. It blocks
// until the bitcoin transaction has been fully processed. Unlock the block
// handler this does not serialize all transactions through a single thread
// transactions don't rely on the previous one in a linear fashion like blocks. | [
"OnTx",
"is",
"invoked",
"when",
"a",
"peer",
"receives",
"a",
"tx",
"bitcoin",
"message",
".",
"It",
"blocks",
"until",
"the",
"bitcoin",
"transaction",
"has",
"been",
"fully",
"processed",
".",
"Unlock",
"the",
"block",
"handler",
"this",
"does",
"not",
... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L557-L578 |
163,244 | btcsuite/btcd | server.go | OnBlock | func (sp *serverPeer) OnBlock(_ *peer.Peer, msg *wire.MsgBlock, buf []byte) {
// Convert the raw MsgBlock to a btcutil.Block which provides some
// convenience methods and things such as hash caching.
block := btcutil.NewBlockFromBlockAndBytes(msg, buf)
// Add the block to the known inventory for the peer.
iv := wire.NewInvVect(wire.InvTypeBlock, block.Hash())
sp.AddKnownInventory(iv)
// Queue the block up to be handled by the block
// manager and intentionally block further receives
// until the bitcoin block is fully processed and known
// good or bad. This helps prevent a malicious peer
// from queuing up a bunch of bad blocks before
// disconnecting (or being disconnected) and wasting
// memory. Additionally, this behavior is depended on
// by at least the block acceptance test tool as the
// reference implementation processes blocks in the same
// thread and therefore blocks further messages until
// the bitcoin block has been fully processed.
sp.server.syncManager.QueueBlock(block, sp.Peer, sp.blockProcessed)
<-sp.blockProcessed
} | go | func (sp *serverPeer) OnBlock(_ *peer.Peer, msg *wire.MsgBlock, buf []byte) {
// Convert the raw MsgBlock to a btcutil.Block which provides some
// convenience methods and things such as hash caching.
block := btcutil.NewBlockFromBlockAndBytes(msg, buf)
// Add the block to the known inventory for the peer.
iv := wire.NewInvVect(wire.InvTypeBlock, block.Hash())
sp.AddKnownInventory(iv)
// Queue the block up to be handled by the block
// manager and intentionally block further receives
// until the bitcoin block is fully processed and known
// good or bad. This helps prevent a malicious peer
// from queuing up a bunch of bad blocks before
// disconnecting (or being disconnected) and wasting
// memory. Additionally, this behavior is depended on
// by at least the block acceptance test tool as the
// reference implementation processes blocks in the same
// thread and therefore blocks further messages until
// the bitcoin block has been fully processed.
sp.server.syncManager.QueueBlock(block, sp.Peer, sp.blockProcessed)
<-sp.blockProcessed
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnBlock",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"msg",
"*",
"wire",
".",
"MsgBlock",
",",
"buf",
"[",
"]",
"byte",
")",
"{",
"// Convert the raw MsgBlock to a btcutil.Block which provides some",
"// convenience meth... | // OnBlock is invoked when a peer receives a block bitcoin message. It
// blocks until the bitcoin block has been fully processed. | [
"OnBlock",
"is",
"invoked",
"when",
"a",
"peer",
"receives",
"a",
"block",
"bitcoin",
"message",
".",
"It",
"blocks",
"until",
"the",
"bitcoin",
"block",
"has",
"been",
"fully",
"processed",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L582-L604 |
163,245 | btcsuite/btcd | server.go | OnHeaders | func (sp *serverPeer) OnHeaders(_ *peer.Peer, msg *wire.MsgHeaders) {
sp.server.syncManager.QueueHeaders(msg, sp.Peer)
} | go | func (sp *serverPeer) OnHeaders(_ *peer.Peer, msg *wire.MsgHeaders) {
sp.server.syncManager.QueueHeaders(msg, sp.Peer)
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnHeaders",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"msg",
"*",
"wire",
".",
"MsgHeaders",
")",
"{",
"sp",
".",
"server",
".",
"syncManager",
".",
"QueueHeaders",
"(",
"msg",
",",
"sp",
".",
"Peer",
")",... | // OnHeaders is invoked when a peer receives a headers bitcoin
// message. The message is passed down to the sync manager. | [
"OnHeaders",
"is",
"invoked",
"when",
"a",
"peer",
"receives",
"a",
"headers",
"bitcoin",
"message",
".",
"The",
"message",
"is",
"passed",
"down",
"to",
"the",
"sync",
"manager",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L645-L647 |
163,246 | btcsuite/btcd | server.go | OnGetData | func (sp *serverPeer) OnGetData(_ *peer.Peer, msg *wire.MsgGetData) {
numAdded := 0
notFound := wire.NewMsgNotFound()
length := len(msg.InvList)
// A decaying ban score increase is applied to prevent exhausting resources
// with unusually large inventory queries.
// Requesting more than the maximum inventory vector length within a short
// period of time yields a score above the default ban threshold. Sustained
// bursts of small requests are not penalized as that would potentially ban
// peers performing IBD.
// This incremental score decays each minute to half of its value.
sp.addBanScore(0, uint32(length)*99/wire.MaxInvPerMsg, "getdata")
// We wait on this wait channel periodically to prevent queuing
// far more data than we can send in a reasonable time, wasting memory.
// The waiting occurs after the database fetch for the next one to
// provide a little pipelining.
var waitChan chan struct{}
doneChan := make(chan struct{}, 1)
for i, iv := range msg.InvList {
var c chan struct{}
// If this will be the last message we send.
if i == length-1 && len(notFound.InvList) == 0 {
c = doneChan
} else if (i+1)%3 == 0 {
// Buffered so as to not make the send goroutine block.
c = make(chan struct{}, 1)
}
var err error
switch iv.Type {
case wire.InvTypeWitnessTx:
err = sp.server.pushTxMsg(sp, &iv.Hash, c, waitChan, wire.WitnessEncoding)
case wire.InvTypeTx:
err = sp.server.pushTxMsg(sp, &iv.Hash, c, waitChan, wire.BaseEncoding)
case wire.InvTypeWitnessBlock:
err = sp.server.pushBlockMsg(sp, &iv.Hash, c, waitChan, wire.WitnessEncoding)
case wire.InvTypeBlock:
err = sp.server.pushBlockMsg(sp, &iv.Hash, c, waitChan, wire.BaseEncoding)
case wire.InvTypeFilteredWitnessBlock:
err = sp.server.pushMerkleBlockMsg(sp, &iv.Hash, c, waitChan, wire.WitnessEncoding)
case wire.InvTypeFilteredBlock:
err = sp.server.pushMerkleBlockMsg(sp, &iv.Hash, c, waitChan, wire.BaseEncoding)
default:
peerLog.Warnf("Unknown type in inventory request %d",
iv.Type)
continue
}
if err != nil {
notFound.AddInvVect(iv)
// When there is a failure fetching the final entry
// and the done channel was sent in due to there
// being no outstanding not found inventory, consume
// it here because there is now not found inventory
// that will use the channel momentarily.
if i == len(msg.InvList)-1 && c != nil {
<-c
}
}
numAdded++
waitChan = c
}
if len(notFound.InvList) != 0 {
sp.QueueMessage(notFound, doneChan)
}
// Wait for messages to be sent. We can send quite a lot of data at this
// point and this will keep the peer busy for a decent amount of time.
// We don't process anything else by them in this time so that we
// have an idea of when we should hear back from them - else the idle
// timeout could fire when we were only half done sending the blocks.
if numAdded > 0 {
<-doneChan
}
} | go | func (sp *serverPeer) OnGetData(_ *peer.Peer, msg *wire.MsgGetData) {
numAdded := 0
notFound := wire.NewMsgNotFound()
length := len(msg.InvList)
// A decaying ban score increase is applied to prevent exhausting resources
// with unusually large inventory queries.
// Requesting more than the maximum inventory vector length within a short
// period of time yields a score above the default ban threshold. Sustained
// bursts of small requests are not penalized as that would potentially ban
// peers performing IBD.
// This incremental score decays each minute to half of its value.
sp.addBanScore(0, uint32(length)*99/wire.MaxInvPerMsg, "getdata")
// We wait on this wait channel periodically to prevent queuing
// far more data than we can send in a reasonable time, wasting memory.
// The waiting occurs after the database fetch for the next one to
// provide a little pipelining.
var waitChan chan struct{}
doneChan := make(chan struct{}, 1)
for i, iv := range msg.InvList {
var c chan struct{}
// If this will be the last message we send.
if i == length-1 && len(notFound.InvList) == 0 {
c = doneChan
} else if (i+1)%3 == 0 {
// Buffered so as to not make the send goroutine block.
c = make(chan struct{}, 1)
}
var err error
switch iv.Type {
case wire.InvTypeWitnessTx:
err = sp.server.pushTxMsg(sp, &iv.Hash, c, waitChan, wire.WitnessEncoding)
case wire.InvTypeTx:
err = sp.server.pushTxMsg(sp, &iv.Hash, c, waitChan, wire.BaseEncoding)
case wire.InvTypeWitnessBlock:
err = sp.server.pushBlockMsg(sp, &iv.Hash, c, waitChan, wire.WitnessEncoding)
case wire.InvTypeBlock:
err = sp.server.pushBlockMsg(sp, &iv.Hash, c, waitChan, wire.BaseEncoding)
case wire.InvTypeFilteredWitnessBlock:
err = sp.server.pushMerkleBlockMsg(sp, &iv.Hash, c, waitChan, wire.WitnessEncoding)
case wire.InvTypeFilteredBlock:
err = sp.server.pushMerkleBlockMsg(sp, &iv.Hash, c, waitChan, wire.BaseEncoding)
default:
peerLog.Warnf("Unknown type in inventory request %d",
iv.Type)
continue
}
if err != nil {
notFound.AddInvVect(iv)
// When there is a failure fetching the final entry
// and the done channel was sent in due to there
// being no outstanding not found inventory, consume
// it here because there is now not found inventory
// that will use the channel momentarily.
if i == len(msg.InvList)-1 && c != nil {
<-c
}
}
numAdded++
waitChan = c
}
if len(notFound.InvList) != 0 {
sp.QueueMessage(notFound, doneChan)
}
// Wait for messages to be sent. We can send quite a lot of data at this
// point and this will keep the peer busy for a decent amount of time.
// We don't process anything else by them in this time so that we
// have an idea of when we should hear back from them - else the idle
// timeout could fire when we were only half done sending the blocks.
if numAdded > 0 {
<-doneChan
}
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnGetData",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"msg",
"*",
"wire",
".",
"MsgGetData",
")",
"{",
"numAdded",
":=",
"0",
"\n",
"notFound",
":=",
"wire",
".",
"NewMsgNotFound",
"(",
")",
"\n\n",
"length"... | // handleGetData is invoked when a peer receives a getdata bitcoin message and
// is used to deliver block and transaction information. | [
"handleGetData",
"is",
"invoked",
"when",
"a",
"peer",
"receives",
"a",
"getdata",
"bitcoin",
"message",
"and",
"is",
"used",
"to",
"deliver",
"block",
"and",
"transaction",
"information",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L651-L727 |
163,247 | btcsuite/btcd | server.go | OnGetBlocks | func (sp *serverPeer) OnGetBlocks(_ *peer.Peer, msg *wire.MsgGetBlocks) {
// Find the most recent known block in the best chain based on the block
// locator and fetch all of the block hashes after it until either
// wire.MaxBlocksPerMsg have been fetched or the provided stop hash is
// encountered.
//
// Use the block after the genesis block if no other blocks in the
// provided locator are known. This does mean the client will start
// over with the genesis block if unknown block locators are provided.
//
// This mirrors the behavior in the reference implementation.
chain := sp.server.chain
hashList := chain.LocateBlocks(msg.BlockLocatorHashes, &msg.HashStop,
wire.MaxBlocksPerMsg)
// Generate inventory message.
invMsg := wire.NewMsgInv()
for i := range hashList {
iv := wire.NewInvVect(wire.InvTypeBlock, &hashList[i])
invMsg.AddInvVect(iv)
}
// Send the inventory message if there is anything to send.
if len(invMsg.InvList) > 0 {
invListLen := len(invMsg.InvList)
if invListLen == wire.MaxBlocksPerMsg {
// Intentionally use a copy of the final hash so there
// is not a reference into the inventory slice which
// would prevent the entire slice from being eligible
// for GC as soon as it's sent.
continueHash := invMsg.InvList[invListLen-1].Hash
sp.continueHash = &continueHash
}
sp.QueueMessage(invMsg, nil)
}
} | go | func (sp *serverPeer) OnGetBlocks(_ *peer.Peer, msg *wire.MsgGetBlocks) {
// Find the most recent known block in the best chain based on the block
// locator and fetch all of the block hashes after it until either
// wire.MaxBlocksPerMsg have been fetched or the provided stop hash is
// encountered.
//
// Use the block after the genesis block if no other blocks in the
// provided locator are known. This does mean the client will start
// over with the genesis block if unknown block locators are provided.
//
// This mirrors the behavior in the reference implementation.
chain := sp.server.chain
hashList := chain.LocateBlocks(msg.BlockLocatorHashes, &msg.HashStop,
wire.MaxBlocksPerMsg)
// Generate inventory message.
invMsg := wire.NewMsgInv()
for i := range hashList {
iv := wire.NewInvVect(wire.InvTypeBlock, &hashList[i])
invMsg.AddInvVect(iv)
}
// Send the inventory message if there is anything to send.
if len(invMsg.InvList) > 0 {
invListLen := len(invMsg.InvList)
if invListLen == wire.MaxBlocksPerMsg {
// Intentionally use a copy of the final hash so there
// is not a reference into the inventory slice which
// would prevent the entire slice from being eligible
// for GC as soon as it's sent.
continueHash := invMsg.InvList[invListLen-1].Hash
sp.continueHash = &continueHash
}
sp.QueueMessage(invMsg, nil)
}
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnGetBlocks",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"msg",
"*",
"wire",
".",
"MsgGetBlocks",
")",
"{",
"// Find the most recent known block in the best chain based on the block",
"// locator and fetch all of the block hashes ... | // OnGetBlocks is invoked when a peer receives a getblocks bitcoin
// message. | [
"OnGetBlocks",
"is",
"invoked",
"when",
"a",
"peer",
"receives",
"a",
"getblocks",
"bitcoin",
"message",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L731-L766 |
163,248 | btcsuite/btcd | server.go | OnGetHeaders | func (sp *serverPeer) OnGetHeaders(_ *peer.Peer, msg *wire.MsgGetHeaders) {
// Ignore getheaders requests if not in sync.
if !sp.server.syncManager.IsCurrent() {
return
}
// Find the most recent known block in the best chain based on the block
// locator and fetch all of the headers after it until either
// wire.MaxBlockHeadersPerMsg have been fetched or the provided stop
// hash is encountered.
//
// Use the block after the genesis block if no other blocks in the
// provided locator are known. This does mean the client will start
// over with the genesis block if unknown block locators are provided.
//
// This mirrors the behavior in the reference implementation.
chain := sp.server.chain
headers := chain.LocateHeaders(msg.BlockLocatorHashes, &msg.HashStop)
// Send found headers to the requesting peer.
blockHeaders := make([]*wire.BlockHeader, len(headers))
for i := range headers {
blockHeaders[i] = &headers[i]
}
sp.QueueMessage(&wire.MsgHeaders{Headers: blockHeaders}, nil)
} | go | func (sp *serverPeer) OnGetHeaders(_ *peer.Peer, msg *wire.MsgGetHeaders) {
// Ignore getheaders requests if not in sync.
if !sp.server.syncManager.IsCurrent() {
return
}
// Find the most recent known block in the best chain based on the block
// locator and fetch all of the headers after it until either
// wire.MaxBlockHeadersPerMsg have been fetched or the provided stop
// hash is encountered.
//
// Use the block after the genesis block if no other blocks in the
// provided locator are known. This does mean the client will start
// over with the genesis block if unknown block locators are provided.
//
// This mirrors the behavior in the reference implementation.
chain := sp.server.chain
headers := chain.LocateHeaders(msg.BlockLocatorHashes, &msg.HashStop)
// Send found headers to the requesting peer.
blockHeaders := make([]*wire.BlockHeader, len(headers))
for i := range headers {
blockHeaders[i] = &headers[i]
}
sp.QueueMessage(&wire.MsgHeaders{Headers: blockHeaders}, nil)
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnGetHeaders",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"msg",
"*",
"wire",
".",
"MsgGetHeaders",
")",
"{",
"// Ignore getheaders requests if not in sync.",
"if",
"!",
"sp",
".",
"server",
".",
"syncManager",
".",
... | // OnGetHeaders is invoked when a peer receives a getheaders bitcoin
// message. | [
"OnGetHeaders",
"is",
"invoked",
"when",
"a",
"peer",
"receives",
"a",
"getheaders",
"bitcoin",
"message",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L770-L795 |
163,249 | btcsuite/btcd | server.go | OnGetCFilters | func (sp *serverPeer) OnGetCFilters(_ *peer.Peer, msg *wire.MsgGetCFilters) {
// Ignore getcfilters requests if not in sync.
if !sp.server.syncManager.IsCurrent() {
return
}
// We'll also ensure that the remote party is requesting a set of
// filters that we actually currently maintain.
switch msg.FilterType {
case wire.GCSFilterRegular:
break
default:
peerLog.Debug("Filter request for unknown filter: %v",
msg.FilterType)
return
}
hashes, err := sp.server.chain.HeightToHashRange(
int32(msg.StartHeight), &msg.StopHash, wire.MaxGetCFiltersReqRange,
)
if err != nil {
peerLog.Debugf("Invalid getcfilters request: %v", err)
return
}
// Create []*chainhash.Hash from []chainhash.Hash to pass to
// FiltersByBlockHashes.
hashPtrs := make([]*chainhash.Hash, len(hashes))
for i := range hashes {
hashPtrs[i] = &hashes[i]
}
filters, err := sp.server.cfIndex.FiltersByBlockHashes(
hashPtrs, msg.FilterType,
)
if err != nil {
peerLog.Errorf("Error retrieving cfilters: %v", err)
return
}
for i, filterBytes := range filters {
if len(filterBytes) == 0 {
peerLog.Warnf("Could not obtain cfilter for %v",
hashes[i])
return
}
filterMsg := wire.NewMsgCFilter(
msg.FilterType, &hashes[i], filterBytes,
)
sp.QueueMessage(filterMsg, nil)
}
} | go | func (sp *serverPeer) OnGetCFilters(_ *peer.Peer, msg *wire.MsgGetCFilters) {
// Ignore getcfilters requests if not in sync.
if !sp.server.syncManager.IsCurrent() {
return
}
// We'll also ensure that the remote party is requesting a set of
// filters that we actually currently maintain.
switch msg.FilterType {
case wire.GCSFilterRegular:
break
default:
peerLog.Debug("Filter request for unknown filter: %v",
msg.FilterType)
return
}
hashes, err := sp.server.chain.HeightToHashRange(
int32(msg.StartHeight), &msg.StopHash, wire.MaxGetCFiltersReqRange,
)
if err != nil {
peerLog.Debugf("Invalid getcfilters request: %v", err)
return
}
// Create []*chainhash.Hash from []chainhash.Hash to pass to
// FiltersByBlockHashes.
hashPtrs := make([]*chainhash.Hash, len(hashes))
for i := range hashes {
hashPtrs[i] = &hashes[i]
}
filters, err := sp.server.cfIndex.FiltersByBlockHashes(
hashPtrs, msg.FilterType,
)
if err != nil {
peerLog.Errorf("Error retrieving cfilters: %v", err)
return
}
for i, filterBytes := range filters {
if len(filterBytes) == 0 {
peerLog.Warnf("Could not obtain cfilter for %v",
hashes[i])
return
}
filterMsg := wire.NewMsgCFilter(
msg.FilterType, &hashes[i], filterBytes,
)
sp.QueueMessage(filterMsg, nil)
}
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnGetCFilters",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"msg",
"*",
"wire",
".",
"MsgGetCFilters",
")",
"{",
"// Ignore getcfilters requests if not in sync.",
"if",
"!",
"sp",
".",
"server",
".",
"syncManager",
".... | // OnGetCFilters is invoked when a peer receives a getcfilters bitcoin message. | [
"OnGetCFilters",
"is",
"invoked",
"when",
"a",
"peer",
"receives",
"a",
"getcfilters",
"bitcoin",
"message",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L798-L851 |
163,250 | btcsuite/btcd | server.go | OnGetCFHeaders | func (sp *serverPeer) OnGetCFHeaders(_ *peer.Peer, msg *wire.MsgGetCFHeaders) {
// Ignore getcfilterheader requests if not in sync.
if !sp.server.syncManager.IsCurrent() {
return
}
// We'll also ensure that the remote party is requesting a set of
// headers for filters that we actually currently maintain.
switch msg.FilterType {
case wire.GCSFilterRegular:
break
default:
peerLog.Debug("Filter request for unknown headers for "+
"filter: %v", msg.FilterType)
return
}
startHeight := int32(msg.StartHeight)
maxResults := wire.MaxCFHeadersPerMsg
// If StartHeight is positive, fetch the predecessor block hash so we
// can populate the PrevFilterHeader field.
if msg.StartHeight > 0 {
startHeight--
maxResults++
}
// Fetch the hashes from the block index.
hashList, err := sp.server.chain.HeightToHashRange(
startHeight, &msg.StopHash, maxResults,
)
if err != nil {
peerLog.Debugf("Invalid getcfheaders request: %v", err)
}
// This is possible if StartHeight is one greater that the height of
// StopHash, and we pull a valid range of hashes including the previous
// filter header.
if len(hashList) == 0 || (msg.StartHeight > 0 && len(hashList) == 1) {
peerLog.Debug("No results for getcfheaders request")
return
}
// Create []*chainhash.Hash from []chainhash.Hash to pass to
// FilterHeadersByBlockHashes.
hashPtrs := make([]*chainhash.Hash, len(hashList))
for i := range hashList {
hashPtrs[i] = &hashList[i]
}
// Fetch the raw filter hash bytes from the database for all blocks.
filterHashes, err := sp.server.cfIndex.FilterHashesByBlockHashes(
hashPtrs, msg.FilterType,
)
if err != nil {
peerLog.Errorf("Error retrieving cfilter hashes: %v", err)
return
}
// Generate cfheaders message and send it.
headersMsg := wire.NewMsgCFHeaders()
// Populate the PrevFilterHeader field.
if msg.StartHeight > 0 {
prevBlockHash := &hashList[0]
// Fetch the raw committed filter header bytes from the
// database.
headerBytes, err := sp.server.cfIndex.FilterHeaderByBlockHash(
prevBlockHash, msg.FilterType)
if err != nil {
peerLog.Errorf("Error retrieving CF header: %v", err)
return
}
if len(headerBytes) == 0 {
peerLog.Warnf("Could not obtain CF header for %v", prevBlockHash)
return
}
// Deserialize the hash into PrevFilterHeader.
err = headersMsg.PrevFilterHeader.SetBytes(headerBytes)
if err != nil {
peerLog.Warnf("Committed filter header deserialize "+
"failed: %v", err)
return
}
hashList = hashList[1:]
filterHashes = filterHashes[1:]
}
// Populate HeaderHashes.
for i, hashBytes := range filterHashes {
if len(hashBytes) == 0 {
peerLog.Warnf("Could not obtain CF hash for %v", hashList[i])
return
}
// Deserialize the hash.
filterHash, err := chainhash.NewHash(hashBytes)
if err != nil {
peerLog.Warnf("Committed filter hash deserialize "+
"failed: %v", err)
return
}
headersMsg.AddCFHash(filterHash)
}
headersMsg.FilterType = msg.FilterType
headersMsg.StopHash = msg.StopHash
sp.QueueMessage(headersMsg, nil)
} | go | func (sp *serverPeer) OnGetCFHeaders(_ *peer.Peer, msg *wire.MsgGetCFHeaders) {
// Ignore getcfilterheader requests if not in sync.
if !sp.server.syncManager.IsCurrent() {
return
}
// We'll also ensure that the remote party is requesting a set of
// headers for filters that we actually currently maintain.
switch msg.FilterType {
case wire.GCSFilterRegular:
break
default:
peerLog.Debug("Filter request for unknown headers for "+
"filter: %v", msg.FilterType)
return
}
startHeight := int32(msg.StartHeight)
maxResults := wire.MaxCFHeadersPerMsg
// If StartHeight is positive, fetch the predecessor block hash so we
// can populate the PrevFilterHeader field.
if msg.StartHeight > 0 {
startHeight--
maxResults++
}
// Fetch the hashes from the block index.
hashList, err := sp.server.chain.HeightToHashRange(
startHeight, &msg.StopHash, maxResults,
)
if err != nil {
peerLog.Debugf("Invalid getcfheaders request: %v", err)
}
// This is possible if StartHeight is one greater that the height of
// StopHash, and we pull a valid range of hashes including the previous
// filter header.
if len(hashList) == 0 || (msg.StartHeight > 0 && len(hashList) == 1) {
peerLog.Debug("No results for getcfheaders request")
return
}
// Create []*chainhash.Hash from []chainhash.Hash to pass to
// FilterHeadersByBlockHashes.
hashPtrs := make([]*chainhash.Hash, len(hashList))
for i := range hashList {
hashPtrs[i] = &hashList[i]
}
// Fetch the raw filter hash bytes from the database for all blocks.
filterHashes, err := sp.server.cfIndex.FilterHashesByBlockHashes(
hashPtrs, msg.FilterType,
)
if err != nil {
peerLog.Errorf("Error retrieving cfilter hashes: %v", err)
return
}
// Generate cfheaders message and send it.
headersMsg := wire.NewMsgCFHeaders()
// Populate the PrevFilterHeader field.
if msg.StartHeight > 0 {
prevBlockHash := &hashList[0]
// Fetch the raw committed filter header bytes from the
// database.
headerBytes, err := sp.server.cfIndex.FilterHeaderByBlockHash(
prevBlockHash, msg.FilterType)
if err != nil {
peerLog.Errorf("Error retrieving CF header: %v", err)
return
}
if len(headerBytes) == 0 {
peerLog.Warnf("Could not obtain CF header for %v", prevBlockHash)
return
}
// Deserialize the hash into PrevFilterHeader.
err = headersMsg.PrevFilterHeader.SetBytes(headerBytes)
if err != nil {
peerLog.Warnf("Committed filter header deserialize "+
"failed: %v", err)
return
}
hashList = hashList[1:]
filterHashes = filterHashes[1:]
}
// Populate HeaderHashes.
for i, hashBytes := range filterHashes {
if len(hashBytes) == 0 {
peerLog.Warnf("Could not obtain CF hash for %v", hashList[i])
return
}
// Deserialize the hash.
filterHash, err := chainhash.NewHash(hashBytes)
if err != nil {
peerLog.Warnf("Committed filter hash deserialize "+
"failed: %v", err)
return
}
headersMsg.AddCFHash(filterHash)
}
headersMsg.FilterType = msg.FilterType
headersMsg.StopHash = msg.StopHash
sp.QueueMessage(headersMsg, nil)
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnGetCFHeaders",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"msg",
"*",
"wire",
".",
"MsgGetCFHeaders",
")",
"{",
"// Ignore getcfilterheader requests if not in sync.",
"if",
"!",
"sp",
".",
"server",
".",
"syncManager... | // OnGetCFHeaders is invoked when a peer receives a getcfheader bitcoin message. | [
"OnGetCFHeaders",
"is",
"invoked",
"when",
"a",
"peer",
"receives",
"a",
"getcfheader",
"bitcoin",
"message",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L854-L968 |
163,251 | btcsuite/btcd | server.go | enforceNodeBloomFlag | func (sp *serverPeer) enforceNodeBloomFlag(cmd string) bool {
if sp.server.services&wire.SFNodeBloom != wire.SFNodeBloom {
// Ban the peer if the protocol version is high enough that the
// peer is knowingly violating the protocol and banning is
// enabled.
//
// NOTE: Even though the addBanScore function already examines
// whether or not banning is enabled, it is checked here as well
// to ensure the violation is logged and the peer is
// disconnected regardless.
if sp.ProtocolVersion() >= wire.BIP0111Version &&
!cfg.DisableBanning {
// Disconnect the peer regardless of whether it was
// banned.
sp.addBanScore(100, 0, cmd)
sp.Disconnect()
return false
}
// Disconnect the peer regardless of protocol version or banning
// state.
peerLog.Debugf("%s sent an unsupported %s request -- "+
"disconnecting", sp, cmd)
sp.Disconnect()
return false
}
return true
} | go | func (sp *serverPeer) enforceNodeBloomFlag(cmd string) bool {
if sp.server.services&wire.SFNodeBloom != wire.SFNodeBloom {
// Ban the peer if the protocol version is high enough that the
// peer is knowingly violating the protocol and banning is
// enabled.
//
// NOTE: Even though the addBanScore function already examines
// whether or not banning is enabled, it is checked here as well
// to ensure the violation is logged and the peer is
// disconnected regardless.
if sp.ProtocolVersion() >= wire.BIP0111Version &&
!cfg.DisableBanning {
// Disconnect the peer regardless of whether it was
// banned.
sp.addBanScore(100, 0, cmd)
sp.Disconnect()
return false
}
// Disconnect the peer regardless of protocol version or banning
// state.
peerLog.Debugf("%s sent an unsupported %s request -- "+
"disconnecting", sp, cmd)
sp.Disconnect()
return false
}
return true
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"enforceNodeBloomFlag",
"(",
"cmd",
"string",
")",
"bool",
"{",
"if",
"sp",
".",
"server",
".",
"services",
"&",
"wire",
".",
"SFNodeBloom",
"!=",
"wire",
".",
"SFNodeBloom",
"{",
"// Ban the peer if the protocol vers... | // enforceNodeBloomFlag disconnects the peer if the server is not configured to
// allow bloom filters. Additionally, if the peer has negotiated to a protocol
// version that is high enough to observe the bloom filter service support bit,
// it will be banned since it is intentionally violating the protocol. | [
"enforceNodeBloomFlag",
"disconnects",
"the",
"peer",
"if",
"the",
"server",
"is",
"not",
"configured",
"to",
"allow",
"bloom",
"filters",
".",
"Additionally",
"if",
"the",
"peer",
"has",
"negotiated",
"to",
"a",
"protocol",
"version",
"that",
"is",
"high",
"e... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1125-L1154 |
163,252 | btcsuite/btcd | server.go | OnFeeFilter | func (sp *serverPeer) OnFeeFilter(_ *peer.Peer, msg *wire.MsgFeeFilter) {
// Check that the passed minimum fee is a valid amount.
if msg.MinFee < 0 || msg.MinFee > btcutil.MaxSatoshi {
peerLog.Debugf("Peer %v sent an invalid feefilter '%v' -- "+
"disconnecting", sp, btcutil.Amount(msg.MinFee))
sp.Disconnect()
return
}
atomic.StoreInt64(&sp.feeFilter, msg.MinFee)
} | go | func (sp *serverPeer) OnFeeFilter(_ *peer.Peer, msg *wire.MsgFeeFilter) {
// Check that the passed minimum fee is a valid amount.
if msg.MinFee < 0 || msg.MinFee > btcutil.MaxSatoshi {
peerLog.Debugf("Peer %v sent an invalid feefilter '%v' -- "+
"disconnecting", sp, btcutil.Amount(msg.MinFee))
sp.Disconnect()
return
}
atomic.StoreInt64(&sp.feeFilter, msg.MinFee)
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnFeeFilter",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"msg",
"*",
"wire",
".",
"MsgFeeFilter",
")",
"{",
"// Check that the passed minimum fee is a valid amount.",
"if",
"msg",
".",
"MinFee",
"<",
"0",
"||",
"msg"... | // OnFeeFilter is invoked when a peer receives a feefilter bitcoin message and
// is used by remote peers to request that no transactions which have a fee rate
// lower than provided value are inventoried to them. The peer will be
// disconnected if an invalid fee filter value is provided. | [
"OnFeeFilter",
"is",
"invoked",
"when",
"a",
"peer",
"receives",
"a",
"feefilter",
"bitcoin",
"message",
"and",
"is",
"used",
"by",
"remote",
"peers",
"to",
"request",
"that",
"no",
"transactions",
"which",
"have",
"a",
"fee",
"rate",
"lower",
"than",
"provi... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1160-L1170 |
163,253 | btcsuite/btcd | server.go | OnFilterAdd | func (sp *serverPeer) OnFilterAdd(_ *peer.Peer, msg *wire.MsgFilterAdd) {
// Disconnect and/or ban depending on the node bloom services flag and
// negotiated protocol version.
if !sp.enforceNodeBloomFlag(msg.Command()) {
return
}
if !sp.filter.IsLoaded() {
peerLog.Debugf("%s sent a filteradd request with no filter "+
"loaded -- disconnecting", sp)
sp.Disconnect()
return
}
sp.filter.Add(msg.Data)
} | go | func (sp *serverPeer) OnFilterAdd(_ *peer.Peer, msg *wire.MsgFilterAdd) {
// Disconnect and/or ban depending on the node bloom services flag and
// negotiated protocol version.
if !sp.enforceNodeBloomFlag(msg.Command()) {
return
}
if !sp.filter.IsLoaded() {
peerLog.Debugf("%s sent a filteradd request with no filter "+
"loaded -- disconnecting", sp)
sp.Disconnect()
return
}
sp.filter.Add(msg.Data)
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnFilterAdd",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"msg",
"*",
"wire",
".",
"MsgFilterAdd",
")",
"{",
"// Disconnect and/or ban depending on the node bloom services flag and",
"// negotiated protocol version.",
"if",
"!"... | // OnFilterAdd is invoked when a peer receives a filteradd bitcoin
// message and is used by remote peers to add data to an already loaded bloom
// filter. The peer will be disconnected if a filter is not loaded when this
// message is received or the server is not configured to allow bloom filters. | [
"OnFilterAdd",
"is",
"invoked",
"when",
"a",
"peer",
"receives",
"a",
"filteradd",
"bitcoin",
"message",
"and",
"is",
"used",
"by",
"remote",
"peers",
"to",
"add",
"data",
"to",
"an",
"already",
"loaded",
"bloom",
"filter",
".",
"The",
"peer",
"will",
"be"... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1176-L1191 |
163,254 | btcsuite/btcd | server.go | OnFilterClear | func (sp *serverPeer) OnFilterClear(_ *peer.Peer, msg *wire.MsgFilterClear) {
// Disconnect and/or ban depending on the node bloom services flag and
// negotiated protocol version.
if !sp.enforceNodeBloomFlag(msg.Command()) {
return
}
if !sp.filter.IsLoaded() {
peerLog.Debugf("%s sent a filterclear request with no "+
"filter loaded -- disconnecting", sp)
sp.Disconnect()
return
}
sp.filter.Unload()
} | go | func (sp *serverPeer) OnFilterClear(_ *peer.Peer, msg *wire.MsgFilterClear) {
// Disconnect and/or ban depending on the node bloom services flag and
// negotiated protocol version.
if !sp.enforceNodeBloomFlag(msg.Command()) {
return
}
if !sp.filter.IsLoaded() {
peerLog.Debugf("%s sent a filterclear request with no "+
"filter loaded -- disconnecting", sp)
sp.Disconnect()
return
}
sp.filter.Unload()
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnFilterClear",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"msg",
"*",
"wire",
".",
"MsgFilterClear",
")",
"{",
"// Disconnect and/or ban depending on the node bloom services flag and",
"// negotiated protocol version.",
"if",
... | // OnFilterClear is invoked when a peer receives a filterclear bitcoin
// message and is used by remote peers to clear an already loaded bloom filter.
// The peer will be disconnected if a filter is not loaded when this message is
// received or the server is not configured to allow bloom filters. | [
"OnFilterClear",
"is",
"invoked",
"when",
"a",
"peer",
"receives",
"a",
"filterclear",
"bitcoin",
"message",
"and",
"is",
"used",
"by",
"remote",
"peers",
"to",
"clear",
"an",
"already",
"loaded",
"bloom",
"filter",
".",
"The",
"peer",
"will",
"be",
"disconn... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1197-L1212 |
163,255 | btcsuite/btcd | server.go | OnFilterLoad | func (sp *serverPeer) OnFilterLoad(_ *peer.Peer, msg *wire.MsgFilterLoad) {
// Disconnect and/or ban depending on the node bloom services flag and
// negotiated protocol version.
if !sp.enforceNodeBloomFlag(msg.Command()) {
return
}
sp.setDisableRelayTx(false)
sp.filter.Reload(msg)
} | go | func (sp *serverPeer) OnFilterLoad(_ *peer.Peer, msg *wire.MsgFilterLoad) {
// Disconnect and/or ban depending on the node bloom services flag and
// negotiated protocol version.
if !sp.enforceNodeBloomFlag(msg.Command()) {
return
}
sp.setDisableRelayTx(false)
sp.filter.Reload(msg)
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnFilterLoad",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"msg",
"*",
"wire",
".",
"MsgFilterLoad",
")",
"{",
"// Disconnect and/or ban depending on the node bloom services flag and",
"// negotiated protocol version.",
"if",
"... | // OnFilterLoad is invoked when a peer receives a filterload bitcoin
// message and it used to load a bloom filter that should be used for
// delivering merkle blocks and associated transactions that match the filter.
// The peer will be disconnected if the server is not configured to allow bloom
// filters. | [
"OnFilterLoad",
"is",
"invoked",
"when",
"a",
"peer",
"receives",
"a",
"filterload",
"bitcoin",
"message",
"and",
"it",
"used",
"to",
"load",
"a",
"bloom",
"filter",
"that",
"should",
"be",
"used",
"for",
"delivering",
"merkle",
"blocks",
"and",
"associated",
... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1219-L1229 |
163,256 | btcsuite/btcd | server.go | OnGetAddr | func (sp *serverPeer) OnGetAddr(_ *peer.Peer, msg *wire.MsgGetAddr) {
// Don't return any addresses when running on the simulation test
// network. This helps prevent the network from becoming another
// public test network since it will not be able to learn about other
// peers that have not specifically been provided.
if cfg.SimNet {
return
}
// Do not accept getaddr requests from outbound peers. This reduces
// fingerprinting attacks.
if !sp.Inbound() {
peerLog.Debugf("Ignoring getaddr request from outbound peer ",
"%v", sp)
return
}
// Only allow one getaddr request per connection to discourage
// address stamping of inv announcements.
if sp.sentAddrs {
peerLog.Debugf("Ignoring repeated getaddr request from peer ",
"%v", sp)
return
}
sp.sentAddrs = true
// Get the current known addresses from the address manager.
addrCache := sp.server.addrManager.AddressCache()
// Push the addresses.
sp.pushAddrMsg(addrCache)
} | go | func (sp *serverPeer) OnGetAddr(_ *peer.Peer, msg *wire.MsgGetAddr) {
// Don't return any addresses when running on the simulation test
// network. This helps prevent the network from becoming another
// public test network since it will not be able to learn about other
// peers that have not specifically been provided.
if cfg.SimNet {
return
}
// Do not accept getaddr requests from outbound peers. This reduces
// fingerprinting attacks.
if !sp.Inbound() {
peerLog.Debugf("Ignoring getaddr request from outbound peer ",
"%v", sp)
return
}
// Only allow one getaddr request per connection to discourage
// address stamping of inv announcements.
if sp.sentAddrs {
peerLog.Debugf("Ignoring repeated getaddr request from peer ",
"%v", sp)
return
}
sp.sentAddrs = true
// Get the current known addresses from the address manager.
addrCache := sp.server.addrManager.AddressCache()
// Push the addresses.
sp.pushAddrMsg(addrCache)
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnGetAddr",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"msg",
"*",
"wire",
".",
"MsgGetAddr",
")",
"{",
"// Don't return any addresses when running on the simulation test",
"// network. This helps prevent the network from becomin... | // OnGetAddr is invoked when a peer receives a getaddr bitcoin message
// and is used to provide the peer with known addresses from the address
// manager. | [
"OnGetAddr",
"is",
"invoked",
"when",
"a",
"peer",
"receives",
"a",
"getaddr",
"bitcoin",
"message",
"and",
"is",
"used",
"to",
"provide",
"the",
"peer",
"with",
"known",
"addresses",
"from",
"the",
"address",
"manager",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1234-L1265 |
163,257 | btcsuite/btcd | server.go | OnWrite | func (sp *serverPeer) OnWrite(_ *peer.Peer, bytesWritten int, msg wire.Message, err error) {
sp.server.AddBytesSent(uint64(bytesWritten))
} | go | func (sp *serverPeer) OnWrite(_ *peer.Peer, bytesWritten int, msg wire.Message, err error) {
sp.server.AddBytesSent(uint64(bytesWritten))
} | [
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"OnWrite",
"(",
"_",
"*",
"peer",
".",
"Peer",
",",
"bytesWritten",
"int",
",",
"msg",
"wire",
".",
"Message",
",",
"err",
"error",
")",
"{",
"sp",
".",
"server",
".",
"AddBytesSent",
"(",
"uint64",
"(",
"... | // OnWrite is invoked when a peer sends a message and it is used to update
// the bytes sent by the server. | [
"OnWrite",
"is",
"invoked",
"when",
"a",
"peer",
"sends",
"a",
"message",
"and",
"it",
"is",
"used",
"to",
"update",
"the",
"bytes",
"sent",
"by",
"the",
"server",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1325-L1327 |
163,258 | btcsuite/btcd | server.go | randomUint16Number | func randomUint16Number(max uint16) uint16 {
// In order to avoid modulo bias and ensure every possible outcome in
// [0, max) has equal probability, the random number must be sampled
// from a random source that has a range limited to a multiple of the
// modulus.
var randomNumber uint16
var limitRange = (math.MaxUint16 / max) * max
for {
binary.Read(rand.Reader, binary.LittleEndian, &randomNumber)
if randomNumber < limitRange {
return (randomNumber % max)
}
}
} | go | func randomUint16Number(max uint16) uint16 {
// In order to avoid modulo bias and ensure every possible outcome in
// [0, max) has equal probability, the random number must be sampled
// from a random source that has a range limited to a multiple of the
// modulus.
var randomNumber uint16
var limitRange = (math.MaxUint16 / max) * max
for {
binary.Read(rand.Reader, binary.LittleEndian, &randomNumber)
if randomNumber < limitRange {
return (randomNumber % max)
}
}
} | [
"func",
"randomUint16Number",
"(",
"max",
"uint16",
")",
"uint16",
"{",
"// In order to avoid modulo bias and ensure every possible outcome in",
"// [0, max) has equal probability, the random number must be sampled",
"// from a random source that has a range limited to a multiple of the",
"// ... | // randomUint16Number returns a random uint16 in a specified input range. Note
// that the range is in zeroth ordering; if you pass it 1800, you will get
// values from 0 to 1800. | [
"randomUint16Number",
"returns",
"a",
"random",
"uint16",
"in",
"a",
"specified",
"input",
"range",
".",
"Note",
"that",
"the",
"range",
"is",
"in",
"zeroth",
"ordering",
";",
"if",
"you",
"pass",
"it",
"1800",
"you",
"will",
"get",
"values",
"from",
"0",
... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1332-L1345 |
163,259 | btcsuite/btcd | server.go | AddRebroadcastInventory | func (s *server) AddRebroadcastInventory(iv *wire.InvVect, data interface{}) {
// Ignore if shutting down.
if atomic.LoadInt32(&s.shutdown) != 0 {
return
}
s.modifyRebroadcastInv <- broadcastInventoryAdd{invVect: iv, data: data}
} | go | func (s *server) AddRebroadcastInventory(iv *wire.InvVect, data interface{}) {
// Ignore if shutting down.
if atomic.LoadInt32(&s.shutdown) != 0 {
return
}
s.modifyRebroadcastInv <- broadcastInventoryAdd{invVect: iv, data: data}
} | [
"func",
"(",
"s",
"*",
"server",
")",
"AddRebroadcastInventory",
"(",
"iv",
"*",
"wire",
".",
"InvVect",
",",
"data",
"interface",
"{",
"}",
")",
"{",
"// Ignore if shutting down.",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"s",
".",
"shutdown",
")",
"... | // AddRebroadcastInventory adds 'iv' to the list of inventories to be
// rebroadcasted at random intervals until they show up in a block. | [
"AddRebroadcastInventory",
"adds",
"iv",
"to",
"the",
"list",
"of",
"inventories",
"to",
"be",
"rebroadcasted",
"at",
"random",
"intervals",
"until",
"they",
"show",
"up",
"in",
"a",
"block",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1349-L1356 |
163,260 | btcsuite/btcd | server.go | RemoveRebroadcastInventory | func (s *server) RemoveRebroadcastInventory(iv *wire.InvVect) {
// Ignore if shutting down.
if atomic.LoadInt32(&s.shutdown) != 0 {
return
}
s.modifyRebroadcastInv <- broadcastInventoryDel(iv)
} | go | func (s *server) RemoveRebroadcastInventory(iv *wire.InvVect) {
// Ignore if shutting down.
if atomic.LoadInt32(&s.shutdown) != 0 {
return
}
s.modifyRebroadcastInv <- broadcastInventoryDel(iv)
} | [
"func",
"(",
"s",
"*",
"server",
")",
"RemoveRebroadcastInventory",
"(",
"iv",
"*",
"wire",
".",
"InvVect",
")",
"{",
"// Ignore if shutting down.",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"s",
".",
"shutdown",
")",
"!=",
"0",
"{",
"return",
"\n",
"}... | // RemoveRebroadcastInventory removes 'iv' from the list of items to be
// rebroadcasted if present. | [
"RemoveRebroadcastInventory",
"removes",
"iv",
"from",
"the",
"list",
"of",
"items",
"to",
"be",
"rebroadcasted",
"if",
"present",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1360-L1367 |
163,261 | btcsuite/btcd | server.go | relayTransactions | func (s *server) relayTransactions(txns []*mempool.TxDesc) {
for _, txD := range txns {
iv := wire.NewInvVect(wire.InvTypeTx, txD.Tx.Hash())
s.RelayInventory(iv, txD)
}
} | go | func (s *server) relayTransactions(txns []*mempool.TxDesc) {
for _, txD := range txns {
iv := wire.NewInvVect(wire.InvTypeTx, txD.Tx.Hash())
s.RelayInventory(iv, txD)
}
} | [
"func",
"(",
"s",
"*",
"server",
")",
"relayTransactions",
"(",
"txns",
"[",
"]",
"*",
"mempool",
".",
"TxDesc",
")",
"{",
"for",
"_",
",",
"txD",
":=",
"range",
"txns",
"{",
"iv",
":=",
"wire",
".",
"NewInvVect",
"(",
"wire",
".",
"InvTypeTx",
","... | // relayTransactions generates and relays inventory vectors for all of the
// passed transactions to all connected peers. | [
"relayTransactions",
"generates",
"and",
"relays",
"inventory",
"vectors",
"for",
"all",
"of",
"the",
"passed",
"transactions",
"to",
"all",
"connected",
"peers",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1371-L1376 |
163,262 | btcsuite/btcd | server.go | AnnounceNewTransactions | func (s *server) AnnounceNewTransactions(txns []*mempool.TxDesc) {
// Generate and relay inventory vectors for all newly accepted
// transactions.
s.relayTransactions(txns)
// Notify both websocket and getblocktemplate long poll clients of all
// newly accepted transactions.
if s.rpcServer != nil {
s.rpcServer.NotifyNewTransactions(txns)
}
} | go | func (s *server) AnnounceNewTransactions(txns []*mempool.TxDesc) {
// Generate and relay inventory vectors for all newly accepted
// transactions.
s.relayTransactions(txns)
// Notify both websocket and getblocktemplate long poll clients of all
// newly accepted transactions.
if s.rpcServer != nil {
s.rpcServer.NotifyNewTransactions(txns)
}
} | [
"func",
"(",
"s",
"*",
"server",
")",
"AnnounceNewTransactions",
"(",
"txns",
"[",
"]",
"*",
"mempool",
".",
"TxDesc",
")",
"{",
"// Generate and relay inventory vectors for all newly accepted",
"// transactions.",
"s",
".",
"relayTransactions",
"(",
"txns",
")",
"\... | // AnnounceNewTransactions generates and relays inventory vectors and notifies
// both websocket and getblocktemplate long poll clients of the passed
// transactions. This function should be called whenever new transactions
// are added to the mempool. | [
"AnnounceNewTransactions",
"generates",
"and",
"relays",
"inventory",
"vectors",
"and",
"notifies",
"both",
"websocket",
"and",
"getblocktemplate",
"long",
"poll",
"clients",
"of",
"the",
"passed",
"transactions",
".",
"This",
"function",
"should",
"be",
"called",
"... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1382-L1392 |
163,263 | btcsuite/btcd | server.go | TransactionConfirmed | func (s *server) TransactionConfirmed(tx *btcutil.Tx) {
// Rebroadcasting is only necessary when the RPC server is active.
if s.rpcServer == nil {
return
}
iv := wire.NewInvVect(wire.InvTypeTx, tx.Hash())
s.RemoveRebroadcastInventory(iv)
} | go | func (s *server) TransactionConfirmed(tx *btcutil.Tx) {
// Rebroadcasting is only necessary when the RPC server is active.
if s.rpcServer == nil {
return
}
iv := wire.NewInvVect(wire.InvTypeTx, tx.Hash())
s.RemoveRebroadcastInventory(iv)
} | [
"func",
"(",
"s",
"*",
"server",
")",
"TransactionConfirmed",
"(",
"tx",
"*",
"btcutil",
".",
"Tx",
")",
"{",
"// Rebroadcasting is only necessary when the RPC server is active.",
"if",
"s",
".",
"rpcServer",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"iv",
... | // Transaction has one confirmation on the main chain. Now we can mark it as no
// longer needing rebroadcasting. | [
"Transaction",
"has",
"one",
"confirmation",
"on",
"the",
"main",
"chain",
".",
"Now",
"we",
"can",
"mark",
"it",
"as",
"no",
"longer",
"needing",
"rebroadcasting",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1396-L1404 |
163,264 | btcsuite/btcd | server.go | pushTxMsg | func (s *server) pushTxMsg(sp *serverPeer, hash *chainhash.Hash, doneChan chan<- struct{},
waitChan <-chan struct{}, encoding wire.MessageEncoding) error {
// Attempt to fetch the requested transaction from the pool. A
// call could be made to check for existence first, but simply trying
// to fetch a missing transaction results in the same behavior.
tx, err := s.txMemPool.FetchTransaction(hash)
if err != nil {
peerLog.Tracef("Unable to fetch tx %v from transaction "+
"pool: %v", hash, err)
if doneChan != nil {
doneChan <- struct{}{}
}
return err
}
// Once we have fetched data wait for any previous operation to finish.
if waitChan != nil {
<-waitChan
}
sp.QueueMessageWithEncoding(tx.MsgTx(), doneChan, encoding)
return nil
} | go | func (s *server) pushTxMsg(sp *serverPeer, hash *chainhash.Hash, doneChan chan<- struct{},
waitChan <-chan struct{}, encoding wire.MessageEncoding) error {
// Attempt to fetch the requested transaction from the pool. A
// call could be made to check for existence first, but simply trying
// to fetch a missing transaction results in the same behavior.
tx, err := s.txMemPool.FetchTransaction(hash)
if err != nil {
peerLog.Tracef("Unable to fetch tx %v from transaction "+
"pool: %v", hash, err)
if doneChan != nil {
doneChan <- struct{}{}
}
return err
}
// Once we have fetched data wait for any previous operation to finish.
if waitChan != nil {
<-waitChan
}
sp.QueueMessageWithEncoding(tx.MsgTx(), doneChan, encoding)
return nil
} | [
"func",
"(",
"s",
"*",
"server",
")",
"pushTxMsg",
"(",
"sp",
"*",
"serverPeer",
",",
"hash",
"*",
"chainhash",
".",
"Hash",
",",
"doneChan",
"chan",
"<-",
"struct",
"{",
"}",
",",
"waitChan",
"<-",
"chan",
"struct",
"{",
"}",
",",
"encoding",
"wire"... | // pushTxMsg sends a tx message for the provided transaction hash to the
// connected peer. An error is returned if the transaction hash is not known. | [
"pushTxMsg",
"sends",
"a",
"tx",
"message",
"for",
"the",
"provided",
"transaction",
"hash",
"to",
"the",
"connected",
"peer",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"transaction",
"hash",
"is",
"not",
"known",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1408-L1433 |
163,265 | btcsuite/btcd | server.go | pushBlockMsg | func (s *server) pushBlockMsg(sp *serverPeer, hash *chainhash.Hash, doneChan chan<- struct{},
waitChan <-chan struct{}, encoding wire.MessageEncoding) error {
// Fetch the raw block bytes from the database.
var blockBytes []byte
err := sp.server.db.View(func(dbTx database.Tx) error {
var err error
blockBytes, err = dbTx.FetchBlock(hash)
return err
})
if err != nil {
peerLog.Tracef("Unable to fetch requested block hash %v: %v",
hash, err)
if doneChan != nil {
doneChan <- struct{}{}
}
return err
}
// Deserialize the block.
var msgBlock wire.MsgBlock
err = msgBlock.Deserialize(bytes.NewReader(blockBytes))
if err != nil {
peerLog.Tracef("Unable to deserialize requested block hash "+
"%v: %v", hash, err)
if doneChan != nil {
doneChan <- struct{}{}
}
return err
}
// Once we have fetched data wait for any previous operation to finish.
if waitChan != nil {
<-waitChan
}
// We only send the channel for this message if we aren't sending
// an inv straight after.
var dc chan<- struct{}
continueHash := sp.continueHash
sendInv := continueHash != nil && continueHash.IsEqual(hash)
if !sendInv {
dc = doneChan
}
sp.QueueMessageWithEncoding(&msgBlock, dc, encoding)
// When the peer requests the final block that was advertised in
// response to a getblocks message which requested more blocks than
// would fit into a single message, send it a new inventory message
// to trigger it to issue another getblocks message for the next
// batch of inventory.
if sendInv {
best := sp.server.chain.BestSnapshot()
invMsg := wire.NewMsgInvSizeHint(1)
iv := wire.NewInvVect(wire.InvTypeBlock, &best.Hash)
invMsg.AddInvVect(iv)
sp.QueueMessage(invMsg, doneChan)
sp.continueHash = nil
}
return nil
} | go | func (s *server) pushBlockMsg(sp *serverPeer, hash *chainhash.Hash, doneChan chan<- struct{},
waitChan <-chan struct{}, encoding wire.MessageEncoding) error {
// Fetch the raw block bytes from the database.
var blockBytes []byte
err := sp.server.db.View(func(dbTx database.Tx) error {
var err error
blockBytes, err = dbTx.FetchBlock(hash)
return err
})
if err != nil {
peerLog.Tracef("Unable to fetch requested block hash %v: %v",
hash, err)
if doneChan != nil {
doneChan <- struct{}{}
}
return err
}
// Deserialize the block.
var msgBlock wire.MsgBlock
err = msgBlock.Deserialize(bytes.NewReader(blockBytes))
if err != nil {
peerLog.Tracef("Unable to deserialize requested block hash "+
"%v: %v", hash, err)
if doneChan != nil {
doneChan <- struct{}{}
}
return err
}
// Once we have fetched data wait for any previous operation to finish.
if waitChan != nil {
<-waitChan
}
// We only send the channel for this message if we aren't sending
// an inv straight after.
var dc chan<- struct{}
continueHash := sp.continueHash
sendInv := continueHash != nil && continueHash.IsEqual(hash)
if !sendInv {
dc = doneChan
}
sp.QueueMessageWithEncoding(&msgBlock, dc, encoding)
// When the peer requests the final block that was advertised in
// response to a getblocks message which requested more blocks than
// would fit into a single message, send it a new inventory message
// to trigger it to issue another getblocks message for the next
// batch of inventory.
if sendInv {
best := sp.server.chain.BestSnapshot()
invMsg := wire.NewMsgInvSizeHint(1)
iv := wire.NewInvVect(wire.InvTypeBlock, &best.Hash)
invMsg.AddInvVect(iv)
sp.QueueMessage(invMsg, doneChan)
sp.continueHash = nil
}
return nil
} | [
"func",
"(",
"s",
"*",
"server",
")",
"pushBlockMsg",
"(",
"sp",
"*",
"serverPeer",
",",
"hash",
"*",
"chainhash",
".",
"Hash",
",",
"doneChan",
"chan",
"<-",
"struct",
"{",
"}",
",",
"waitChan",
"<-",
"chan",
"struct",
"{",
"}",
",",
"encoding",
"wi... | // pushBlockMsg sends a block message for the provided block hash to the
// connected peer. An error is returned if the block hash is not known. | [
"pushBlockMsg",
"sends",
"a",
"block",
"message",
"for",
"the",
"provided",
"block",
"hash",
"to",
"the",
"connected",
"peer",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"block",
"hash",
"is",
"not",
"known",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1437-L1499 |
163,266 | btcsuite/btcd | server.go | pushMerkleBlockMsg | func (s *server) pushMerkleBlockMsg(sp *serverPeer, hash *chainhash.Hash,
doneChan chan<- struct{}, waitChan <-chan struct{}, encoding wire.MessageEncoding) error {
// Do not send a response if the peer doesn't have a filter loaded.
if !sp.filter.IsLoaded() {
if doneChan != nil {
doneChan <- struct{}{}
}
return nil
}
// Fetch the raw block bytes from the database.
blk, err := sp.server.chain.BlockByHash(hash)
if err != nil {
peerLog.Tracef("Unable to fetch requested block hash %v: %v",
hash, err)
if doneChan != nil {
doneChan <- struct{}{}
}
return err
}
// Generate a merkle block by filtering the requested block according
// to the filter for the peer.
merkle, matchedTxIndices := bloom.NewMerkleBlock(blk, sp.filter)
// Once we have fetched data wait for any previous operation to finish.
if waitChan != nil {
<-waitChan
}
// Send the merkleblock. Only send the done channel with this message
// if no transactions will be sent afterwards.
var dc chan<- struct{}
if len(matchedTxIndices) == 0 {
dc = doneChan
}
sp.QueueMessage(merkle, dc)
// Finally, send any matched transactions.
blkTransactions := blk.MsgBlock().Transactions
for i, txIndex := range matchedTxIndices {
// Only send the done channel on the final transaction.
var dc chan<- struct{}
if i == len(matchedTxIndices)-1 {
dc = doneChan
}
if txIndex < uint32(len(blkTransactions)) {
sp.QueueMessageWithEncoding(blkTransactions[txIndex], dc,
encoding)
}
}
return nil
} | go | func (s *server) pushMerkleBlockMsg(sp *serverPeer, hash *chainhash.Hash,
doneChan chan<- struct{}, waitChan <-chan struct{}, encoding wire.MessageEncoding) error {
// Do not send a response if the peer doesn't have a filter loaded.
if !sp.filter.IsLoaded() {
if doneChan != nil {
doneChan <- struct{}{}
}
return nil
}
// Fetch the raw block bytes from the database.
blk, err := sp.server.chain.BlockByHash(hash)
if err != nil {
peerLog.Tracef("Unable to fetch requested block hash %v: %v",
hash, err)
if doneChan != nil {
doneChan <- struct{}{}
}
return err
}
// Generate a merkle block by filtering the requested block according
// to the filter for the peer.
merkle, matchedTxIndices := bloom.NewMerkleBlock(blk, sp.filter)
// Once we have fetched data wait for any previous operation to finish.
if waitChan != nil {
<-waitChan
}
// Send the merkleblock. Only send the done channel with this message
// if no transactions will be sent afterwards.
var dc chan<- struct{}
if len(matchedTxIndices) == 0 {
dc = doneChan
}
sp.QueueMessage(merkle, dc)
// Finally, send any matched transactions.
blkTransactions := blk.MsgBlock().Transactions
for i, txIndex := range matchedTxIndices {
// Only send the done channel on the final transaction.
var dc chan<- struct{}
if i == len(matchedTxIndices)-1 {
dc = doneChan
}
if txIndex < uint32(len(blkTransactions)) {
sp.QueueMessageWithEncoding(blkTransactions[txIndex], dc,
encoding)
}
}
return nil
} | [
"func",
"(",
"s",
"*",
"server",
")",
"pushMerkleBlockMsg",
"(",
"sp",
"*",
"serverPeer",
",",
"hash",
"*",
"chainhash",
".",
"Hash",
",",
"doneChan",
"chan",
"<-",
"struct",
"{",
"}",
",",
"waitChan",
"<-",
"chan",
"struct",
"{",
"}",
",",
"encoding",... | // pushMerkleBlockMsg sends a merkleblock message for the provided block hash to
// the connected peer. Since a merkle block requires the peer to have a filter
// loaded, this call will simply be ignored if there is no filter loaded. An
// error is returned if the block hash is not known. | [
"pushMerkleBlockMsg",
"sends",
"a",
"merkleblock",
"message",
"for",
"the",
"provided",
"block",
"hash",
"to",
"the",
"connected",
"peer",
".",
"Since",
"a",
"merkle",
"block",
"requires",
"the",
"peer",
"to",
"have",
"a",
"filter",
"loaded",
"this",
"call",
... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1505-L1560 |
163,267 | btcsuite/btcd | server.go | handleRelayInvMsg | func (s *server) handleRelayInvMsg(state *peerState, msg relayMsg) {
state.forAllPeers(func(sp *serverPeer) {
if !sp.Connected() {
return
}
// If the inventory is a block and the peer prefers headers,
// generate and send a headers message instead of an inventory
// message.
if msg.invVect.Type == wire.InvTypeBlock && sp.WantsHeaders() {
blockHeader, ok := msg.data.(wire.BlockHeader)
if !ok {
peerLog.Warnf("Underlying data for headers" +
" is not a block header")
return
}
msgHeaders := wire.NewMsgHeaders()
if err := msgHeaders.AddBlockHeader(&blockHeader); err != nil {
peerLog.Errorf("Failed to add block"+
" header: %v", err)
return
}
sp.QueueMessage(msgHeaders, nil)
return
}
if msg.invVect.Type == wire.InvTypeTx {
// Don't relay the transaction to the peer when it has
// transaction relaying disabled.
if sp.relayTxDisabled() {
return
}
txD, ok := msg.data.(*mempool.TxDesc)
if !ok {
peerLog.Warnf("Underlying data for tx inv "+
"relay is not a *mempool.TxDesc: %T",
msg.data)
return
}
// Don't relay the transaction if the transaction fee-per-kb
// is less than the peer's feefilter.
feeFilter := atomic.LoadInt64(&sp.feeFilter)
if feeFilter > 0 && txD.FeePerKB < feeFilter {
return
}
// Don't relay the transaction if there is a bloom
// filter loaded and the transaction doesn't match it.
if sp.filter.IsLoaded() {
if !sp.filter.MatchTxAndUpdate(txD.Tx) {
return
}
}
}
// Queue the inventory to be relayed with the next batch.
// It will be ignored if the peer is already known to
// have the inventory.
sp.QueueInventory(msg.invVect)
})
} | go | func (s *server) handleRelayInvMsg(state *peerState, msg relayMsg) {
state.forAllPeers(func(sp *serverPeer) {
if !sp.Connected() {
return
}
// If the inventory is a block and the peer prefers headers,
// generate and send a headers message instead of an inventory
// message.
if msg.invVect.Type == wire.InvTypeBlock && sp.WantsHeaders() {
blockHeader, ok := msg.data.(wire.BlockHeader)
if !ok {
peerLog.Warnf("Underlying data for headers" +
" is not a block header")
return
}
msgHeaders := wire.NewMsgHeaders()
if err := msgHeaders.AddBlockHeader(&blockHeader); err != nil {
peerLog.Errorf("Failed to add block"+
" header: %v", err)
return
}
sp.QueueMessage(msgHeaders, nil)
return
}
if msg.invVect.Type == wire.InvTypeTx {
// Don't relay the transaction to the peer when it has
// transaction relaying disabled.
if sp.relayTxDisabled() {
return
}
txD, ok := msg.data.(*mempool.TxDesc)
if !ok {
peerLog.Warnf("Underlying data for tx inv "+
"relay is not a *mempool.TxDesc: %T",
msg.data)
return
}
// Don't relay the transaction if the transaction fee-per-kb
// is less than the peer's feefilter.
feeFilter := atomic.LoadInt64(&sp.feeFilter)
if feeFilter > 0 && txD.FeePerKB < feeFilter {
return
}
// Don't relay the transaction if there is a bloom
// filter loaded and the transaction doesn't match it.
if sp.filter.IsLoaded() {
if !sp.filter.MatchTxAndUpdate(txD.Tx) {
return
}
}
}
// Queue the inventory to be relayed with the next batch.
// It will be ignored if the peer is already known to
// have the inventory.
sp.QueueInventory(msg.invVect)
})
} | [
"func",
"(",
"s",
"*",
"server",
")",
"handleRelayInvMsg",
"(",
"state",
"*",
"peerState",
",",
"msg",
"relayMsg",
")",
"{",
"state",
".",
"forAllPeers",
"(",
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"{",
"if",
"!",
"sp",
".",
"Connected",
"(",
")"... | // handleRelayInvMsg deals with relaying inventory to peers that are not already
// known to have it. It is invoked from the peerHandler goroutine. | [
"handleRelayInvMsg",
"deals",
"with",
"relaying",
"inventory",
"to",
"peers",
"that",
"are",
"not",
"already",
"known",
"to",
"have",
"it",
".",
"It",
"is",
"invoked",
"from",
"the",
"peerHandler",
"goroutine",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1710-L1772 |
163,268 | btcsuite/btcd | server.go | handleBroadcastMsg | func (s *server) handleBroadcastMsg(state *peerState, bmsg *broadcastMsg) {
state.forAllPeers(func(sp *serverPeer) {
if !sp.Connected() {
return
}
for _, ep := range bmsg.excludePeers {
if sp == ep {
return
}
}
sp.QueueMessage(bmsg.message, nil)
})
} | go | func (s *server) handleBroadcastMsg(state *peerState, bmsg *broadcastMsg) {
state.forAllPeers(func(sp *serverPeer) {
if !sp.Connected() {
return
}
for _, ep := range bmsg.excludePeers {
if sp == ep {
return
}
}
sp.QueueMessage(bmsg.message, nil)
})
} | [
"func",
"(",
"s",
"*",
"server",
")",
"handleBroadcastMsg",
"(",
"state",
"*",
"peerState",
",",
"bmsg",
"*",
"broadcastMsg",
")",
"{",
"state",
".",
"forAllPeers",
"(",
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"{",
"if",
"!",
"sp",
".",
"Connected",... | // handleBroadcastMsg deals with broadcasting messages to peers. It is invoked
// from the peerHandler goroutine. | [
"handleBroadcastMsg",
"deals",
"with",
"broadcasting",
"messages",
"to",
"peers",
".",
"It",
"is",
"invoked",
"from",
"the",
"peerHandler",
"goroutine",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1776-L1790 |
163,269 | btcsuite/btcd | server.go | newPeerConfig | func newPeerConfig(sp *serverPeer) *peer.Config {
return &peer.Config{
Listeners: peer.MessageListeners{
OnVersion: sp.OnVersion,
OnMemPool: sp.OnMemPool,
OnTx: sp.OnTx,
OnBlock: sp.OnBlock,
OnInv: sp.OnInv,
OnHeaders: sp.OnHeaders,
OnGetData: sp.OnGetData,
OnGetBlocks: sp.OnGetBlocks,
OnGetHeaders: sp.OnGetHeaders,
OnGetCFilters: sp.OnGetCFilters,
OnGetCFHeaders: sp.OnGetCFHeaders,
OnGetCFCheckpt: sp.OnGetCFCheckpt,
OnFeeFilter: sp.OnFeeFilter,
OnFilterAdd: sp.OnFilterAdd,
OnFilterClear: sp.OnFilterClear,
OnFilterLoad: sp.OnFilterLoad,
OnGetAddr: sp.OnGetAddr,
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,
Proxy: cfg.Proxy,
UserAgentName: userAgentName,
UserAgentVersion: userAgentVersion,
UserAgentComments: cfg.UserAgentComments,
ChainParams: sp.server.chainParams,
Services: sp.server.services,
DisableRelayTx: cfg.BlocksOnly,
ProtocolVersion: peer.MaxProtocolVersion,
TrickleInterval: cfg.TrickleInterval,
}
} | go | func newPeerConfig(sp *serverPeer) *peer.Config {
return &peer.Config{
Listeners: peer.MessageListeners{
OnVersion: sp.OnVersion,
OnMemPool: sp.OnMemPool,
OnTx: sp.OnTx,
OnBlock: sp.OnBlock,
OnInv: sp.OnInv,
OnHeaders: sp.OnHeaders,
OnGetData: sp.OnGetData,
OnGetBlocks: sp.OnGetBlocks,
OnGetHeaders: sp.OnGetHeaders,
OnGetCFilters: sp.OnGetCFilters,
OnGetCFHeaders: sp.OnGetCFHeaders,
OnGetCFCheckpt: sp.OnGetCFCheckpt,
OnFeeFilter: sp.OnFeeFilter,
OnFilterAdd: sp.OnFilterAdd,
OnFilterClear: sp.OnFilterClear,
OnFilterLoad: sp.OnFilterLoad,
OnGetAddr: sp.OnGetAddr,
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,
Proxy: cfg.Proxy,
UserAgentName: userAgentName,
UserAgentVersion: userAgentVersion,
UserAgentComments: cfg.UserAgentComments,
ChainParams: sp.server.chainParams,
Services: sp.server.services,
DisableRelayTx: cfg.BlocksOnly,
ProtocolVersion: peer.MaxProtocolVersion,
TrickleInterval: cfg.TrickleInterval,
}
} | [
"func",
"newPeerConfig",
"(",
"sp",
"*",
"serverPeer",
")",
"*",
"peer",
".",
"Config",
"{",
"return",
"&",
"peer",
".",
"Config",
"{",
"Listeners",
":",
"peer",
".",
"MessageListeners",
"{",
"OnVersion",
":",
"sp",
".",
"OnVersion",
",",
"OnMemPool",
":... | // newPeerConfig returns the configuration for the given serverPeer. | [
"newPeerConfig",
"returns",
"the",
"configuration",
"for",
"the",
"given",
"serverPeer",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1962-L2004 |
163,270 | btcsuite/btcd | server.go | inboundPeerConnected | func (s *server) inboundPeerConnected(conn net.Conn) {
sp := newServerPeer(s, false)
sp.isWhitelisted = isWhitelisted(conn.RemoteAddr())
sp.Peer = peer.NewInboundPeer(newPeerConfig(sp))
sp.AssociateConnection(conn)
go s.peerDoneHandler(sp)
} | go | func (s *server) inboundPeerConnected(conn net.Conn) {
sp := newServerPeer(s, false)
sp.isWhitelisted = isWhitelisted(conn.RemoteAddr())
sp.Peer = peer.NewInboundPeer(newPeerConfig(sp))
sp.AssociateConnection(conn)
go s.peerDoneHandler(sp)
} | [
"func",
"(",
"s",
"*",
"server",
")",
"inboundPeerConnected",
"(",
"conn",
"net",
".",
"Conn",
")",
"{",
"sp",
":=",
"newServerPeer",
"(",
"s",
",",
"false",
")",
"\n",
"sp",
".",
"isWhitelisted",
"=",
"isWhitelisted",
"(",
"conn",
".",
"RemoteAddr",
"... | // inboundPeerConnected is invoked by the connection manager when a new inbound
// connection is established. It initializes a new inbound server peer
// instance, associates it with the connection, and starts a goroutine to wait
// for disconnection. | [
"inboundPeerConnected",
"is",
"invoked",
"by",
"the",
"connection",
"manager",
"when",
"a",
"new",
"inbound",
"connection",
"is",
"established",
".",
"It",
"initializes",
"a",
"new",
"inbound",
"server",
"peer",
"instance",
"associates",
"it",
"with",
"the",
"co... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L2010-L2016 |
163,271 | btcsuite/btcd | server.go | RelayInventory | func (s *server) RelayInventory(invVect *wire.InvVect, data interface{}) {
s.relayInv <- relayMsg{invVect: invVect, data: data}
} | go | func (s *server) RelayInventory(invVect *wire.InvVect, data interface{}) {
s.relayInv <- relayMsg{invVect: invVect, data: data}
} | [
"func",
"(",
"s",
"*",
"server",
")",
"RelayInventory",
"(",
"invVect",
"*",
"wire",
".",
"InvVect",
",",
"data",
"interface",
"{",
"}",
")",
"{",
"s",
".",
"relayInv",
"<-",
"relayMsg",
"{",
"invVect",
":",
"invVect",
",",
"data",
":",
"data",
"}",
... | // RelayInventory relays the passed inventory vector to all connected peers
// that are not already known to have it. | [
"RelayInventory",
"relays",
"the",
"passed",
"inventory",
"vector",
"to",
"all",
"connected",
"peers",
"that",
"are",
"not",
"already",
"known",
"to",
"have",
"it",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L2171-L2173 |
163,272 | btcsuite/btcd | server.go | BroadcastMessage | func (s *server) BroadcastMessage(msg wire.Message, exclPeers ...*serverPeer) {
// XXX: Need to determine if this is an alert that has already been
// broadcast and refrain from broadcasting again.
bmsg := broadcastMsg{message: msg, excludePeers: exclPeers}
s.broadcast <- bmsg
} | go | func (s *server) BroadcastMessage(msg wire.Message, exclPeers ...*serverPeer) {
// XXX: Need to determine if this is an alert that has already been
// broadcast and refrain from broadcasting again.
bmsg := broadcastMsg{message: msg, excludePeers: exclPeers}
s.broadcast <- bmsg
} | [
"func",
"(",
"s",
"*",
"server",
")",
"BroadcastMessage",
"(",
"msg",
"wire",
".",
"Message",
",",
"exclPeers",
"...",
"*",
"serverPeer",
")",
"{",
"// XXX: Need to determine if this is an alert that has already been",
"// broadcast and refrain from broadcasting again.",
"b... | // BroadcastMessage sends msg to all peers currently connected to the server
// except those in the passed peers to exclude. | [
"BroadcastMessage",
"sends",
"msg",
"to",
"all",
"peers",
"currently",
"connected",
"to",
"the",
"server",
"except",
"those",
"in",
"the",
"passed",
"peers",
"to",
"exclude",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L2177-L2182 |
163,273 | btcsuite/btcd | server.go | rebroadcastHandler | func (s *server) rebroadcastHandler() {
// Wait 5 min before first tx rebroadcast.
timer := time.NewTimer(5 * time.Minute)
pendingInvs := make(map[wire.InvVect]interface{})
out:
for {
select {
case riv := <-s.modifyRebroadcastInv:
switch msg := riv.(type) {
// Incoming InvVects are added to our map of RPC txs.
case broadcastInventoryAdd:
pendingInvs[*msg.invVect] = msg.data
// When an InvVect has been added to a block, we can
// now remove it, if it was present.
case broadcastInventoryDel:
if _, ok := pendingInvs[*msg]; ok {
delete(pendingInvs, *msg)
}
}
case <-timer.C:
// Any inventory we have has not made it into a block
// yet. We periodically resubmit them until they have.
for iv, data := range pendingInvs {
ivCopy := iv
s.RelayInventory(&ivCopy, data)
}
// Process at a random time up to 30mins (in seconds)
// in the future.
timer.Reset(time.Second *
time.Duration(randomUint16Number(1800)))
case <-s.quit:
break out
}
}
timer.Stop()
// Drain channels before exiting so nothing is left waiting around
// to send.
cleanup:
for {
select {
case <-s.modifyRebroadcastInv:
default:
break cleanup
}
}
s.wg.Done()
} | go | func (s *server) rebroadcastHandler() {
// Wait 5 min before first tx rebroadcast.
timer := time.NewTimer(5 * time.Minute)
pendingInvs := make(map[wire.InvVect]interface{})
out:
for {
select {
case riv := <-s.modifyRebroadcastInv:
switch msg := riv.(type) {
// Incoming InvVects are added to our map of RPC txs.
case broadcastInventoryAdd:
pendingInvs[*msg.invVect] = msg.data
// When an InvVect has been added to a block, we can
// now remove it, if it was present.
case broadcastInventoryDel:
if _, ok := pendingInvs[*msg]; ok {
delete(pendingInvs, *msg)
}
}
case <-timer.C:
// Any inventory we have has not made it into a block
// yet. We periodically resubmit them until they have.
for iv, data := range pendingInvs {
ivCopy := iv
s.RelayInventory(&ivCopy, data)
}
// Process at a random time up to 30mins (in seconds)
// in the future.
timer.Reset(time.Second *
time.Duration(randomUint16Number(1800)))
case <-s.quit:
break out
}
}
timer.Stop()
// Drain channels before exiting so nothing is left waiting around
// to send.
cleanup:
for {
select {
case <-s.modifyRebroadcastInv:
default:
break cleanup
}
}
s.wg.Done()
} | [
"func",
"(",
"s",
"*",
"server",
")",
"rebroadcastHandler",
"(",
")",
"{",
"// Wait 5 min before first tx rebroadcast.",
"timer",
":=",
"time",
".",
"NewTimer",
"(",
"5",
"*",
"time",
".",
"Minute",
")",
"\n",
"pendingInvs",
":=",
"make",
"(",
"map",
"[",
... | // rebroadcastHandler keeps track of user submitted inventories that we have
// sent out but have not yet made it into a block. We periodically rebroadcast
// them in case our peers restarted or otherwise lost track of them. | [
"rebroadcastHandler",
"keeps",
"track",
"of",
"user",
"submitted",
"inventories",
"that",
"we",
"have",
"sent",
"out",
"but",
"have",
"not",
"yet",
"made",
"it",
"into",
"a",
"block",
".",
"We",
"periodically",
"rebroadcast",
"them",
"in",
"case",
"our",
"pe... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L2235-L2288 |
163,274 | btcsuite/btcd | server.go | Start | func (s *server) Start() {
// Already started?
if atomic.AddInt32(&s.started, 1) != 1 {
return
}
srvrLog.Trace("Starting server")
// Server startup time. Used for the uptime command for uptime calculation.
s.startupTime = time.Now().Unix()
// Start the peer handler which in turn starts the address and block
// managers.
s.wg.Add(1)
go s.peerHandler()
if s.nat != nil {
s.wg.Add(1)
go s.upnpUpdateThread()
}
if !cfg.DisableRPC {
s.wg.Add(1)
// Start the rebroadcastHandler, which ensures user tx received by
// the RPC server are rebroadcast until being included in a block.
go s.rebroadcastHandler()
s.rpcServer.Start()
}
// Start the CPU miner if generation is enabled.
if cfg.Generate {
s.cpuMiner.Start()
}
} | go | func (s *server) Start() {
// Already started?
if atomic.AddInt32(&s.started, 1) != 1 {
return
}
srvrLog.Trace("Starting server")
// Server startup time. Used for the uptime command for uptime calculation.
s.startupTime = time.Now().Unix()
// Start the peer handler which in turn starts the address and block
// managers.
s.wg.Add(1)
go s.peerHandler()
if s.nat != nil {
s.wg.Add(1)
go s.upnpUpdateThread()
}
if !cfg.DisableRPC {
s.wg.Add(1)
// Start the rebroadcastHandler, which ensures user tx received by
// the RPC server are rebroadcast until being included in a block.
go s.rebroadcastHandler()
s.rpcServer.Start()
}
// Start the CPU miner if generation is enabled.
if cfg.Generate {
s.cpuMiner.Start()
}
} | [
"func",
"(",
"s",
"*",
"server",
")",
"Start",
"(",
")",
"{",
"// Already started?",
"if",
"atomic",
".",
"AddInt32",
"(",
"&",
"s",
".",
"started",
",",
"1",
")",
"!=",
"1",
"{",
"return",
"\n",
"}",
"\n\n",
"srvrLog",
".",
"Trace",
"(",
"\"",
"... | // Start begins accepting connections from peers. | [
"Start",
"begins",
"accepting",
"connections",
"from",
"peers",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L2291-L2326 |
163,275 | btcsuite/btcd | server.go | ScheduleShutdown | func (s *server) ScheduleShutdown(duration time.Duration) {
// Don't schedule shutdown more than once.
if atomic.AddInt32(&s.shutdownSched, 1) != 1 {
return
}
srvrLog.Warnf("Server shutdown in %v", duration)
go func() {
remaining := duration
tickDuration := dynamicTickDuration(remaining)
done := time.After(remaining)
ticker := time.NewTicker(tickDuration)
out:
for {
select {
case <-done:
ticker.Stop()
s.Stop()
break out
case <-ticker.C:
remaining = remaining - tickDuration
if remaining < time.Second {
continue
}
// Change tick duration dynamically based on remaining time.
newDuration := dynamicTickDuration(remaining)
if tickDuration != newDuration {
tickDuration = newDuration
ticker.Stop()
ticker = time.NewTicker(tickDuration)
}
srvrLog.Warnf("Server shutdown in %v", remaining)
}
}
}()
} | go | func (s *server) ScheduleShutdown(duration time.Duration) {
// Don't schedule shutdown more than once.
if atomic.AddInt32(&s.shutdownSched, 1) != 1 {
return
}
srvrLog.Warnf("Server shutdown in %v", duration)
go func() {
remaining := duration
tickDuration := dynamicTickDuration(remaining)
done := time.After(remaining)
ticker := time.NewTicker(tickDuration)
out:
for {
select {
case <-done:
ticker.Stop()
s.Stop()
break out
case <-ticker.C:
remaining = remaining - tickDuration
if remaining < time.Second {
continue
}
// Change tick duration dynamically based on remaining time.
newDuration := dynamicTickDuration(remaining)
if tickDuration != newDuration {
tickDuration = newDuration
ticker.Stop()
ticker = time.NewTicker(tickDuration)
}
srvrLog.Warnf("Server shutdown in %v", remaining)
}
}
}()
} | [
"func",
"(",
"s",
"*",
"server",
")",
"ScheduleShutdown",
"(",
"duration",
"time",
".",
"Duration",
")",
"{",
"// Don't schedule shutdown more than once.",
"if",
"atomic",
".",
"AddInt32",
"(",
"&",
"s",
".",
"shutdownSched",
",",
"1",
")",
"!=",
"1",
"{",
... | // ScheduleShutdown schedules a server shutdown after the specified duration.
// It also dynamically adjusts how often to warn the server is going down based
// on remaining duration. | [
"ScheduleShutdown",
"schedules",
"a",
"server",
"shutdown",
"after",
"the",
"specified",
"duration",
".",
"It",
"also",
"dynamically",
"adjusts",
"how",
"often",
"to",
"warn",
"the",
"server",
"is",
"going",
"down",
"based",
"on",
"remaining",
"duration",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L2368-L2403 |
163,276 | btcsuite/btcd | server.go | parseListeners | func parseListeners(addrs []string) ([]net.Addr, error) {
netAddrs := make([]net.Addr, 0, len(addrs)*2)
for _, addr := range addrs {
host, _, err := net.SplitHostPort(addr)
if err != nil {
// Shouldn't happen due to already being normalized.
return nil, err
}
// Empty host or host of * on plan9 is both IPv4 and IPv6.
if host == "" || (host == "*" && runtime.GOOS == "plan9") {
netAddrs = append(netAddrs, simpleAddr{net: "tcp4", addr: addr})
netAddrs = append(netAddrs, simpleAddr{net: "tcp6", addr: addr})
continue
}
// Strip IPv6 zone id if present since net.ParseIP does not
// handle it.
zoneIndex := strings.LastIndex(host, "%")
if zoneIndex > 0 {
host = host[:zoneIndex]
}
// Parse the IP.
ip := net.ParseIP(host)
if ip == nil {
return nil, fmt.Errorf("'%s' is not a valid IP address", host)
}
// To4 returns nil when the IP is not an IPv4 address, so use
// this determine the address type.
if ip.To4() == nil {
netAddrs = append(netAddrs, simpleAddr{net: "tcp6", addr: addr})
} else {
netAddrs = append(netAddrs, simpleAddr{net: "tcp4", addr: addr})
}
}
return netAddrs, nil
} | go | func parseListeners(addrs []string) ([]net.Addr, error) {
netAddrs := make([]net.Addr, 0, len(addrs)*2)
for _, addr := range addrs {
host, _, err := net.SplitHostPort(addr)
if err != nil {
// Shouldn't happen due to already being normalized.
return nil, err
}
// Empty host or host of * on plan9 is both IPv4 and IPv6.
if host == "" || (host == "*" && runtime.GOOS == "plan9") {
netAddrs = append(netAddrs, simpleAddr{net: "tcp4", addr: addr})
netAddrs = append(netAddrs, simpleAddr{net: "tcp6", addr: addr})
continue
}
// Strip IPv6 zone id if present since net.ParseIP does not
// handle it.
zoneIndex := strings.LastIndex(host, "%")
if zoneIndex > 0 {
host = host[:zoneIndex]
}
// Parse the IP.
ip := net.ParseIP(host)
if ip == nil {
return nil, fmt.Errorf("'%s' is not a valid IP address", host)
}
// To4 returns nil when the IP is not an IPv4 address, so use
// this determine the address type.
if ip.To4() == nil {
netAddrs = append(netAddrs, simpleAddr{net: "tcp6", addr: addr})
} else {
netAddrs = append(netAddrs, simpleAddr{net: "tcp4", addr: addr})
}
}
return netAddrs, nil
} | [
"func",
"parseListeners",
"(",
"addrs",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"net",
".",
"Addr",
",",
"error",
")",
"{",
"netAddrs",
":=",
"make",
"(",
"[",
"]",
"net",
".",
"Addr",
",",
"0",
",",
"len",
"(",
"addrs",
")",
"*",
"2",
")",
"... | // parseListeners determines whether each listen address is IPv4 and IPv6 and
// returns a slice of appropriate net.Addrs to listen on with TCP. It also
// properly detects addresses which apply to "all interfaces" and adds the
// address as both IPv4 and IPv6. | [
"parseListeners",
"determines",
"whether",
"each",
"listen",
"address",
"is",
"IPv4",
"and",
"IPv6",
"and",
"returns",
"a",
"slice",
"of",
"appropriate",
"net",
".",
"Addrs",
"to",
"listen",
"on",
"with",
"TCP",
".",
"It",
"also",
"properly",
"detects",
"add... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L2409-L2447 |
163,277 | btcsuite/btcd | server.go | setupRPCListeners | func setupRPCListeners() ([]net.Listener, error) {
// Setup TLS if not disabled.
listenFunc := net.Listen
if !cfg.DisableTLS {
// Generate the TLS cert and key file if both don't already
// exist.
if !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {
err := genCertPair(cfg.RPCCert, cfg.RPCKey)
if err != nil {
return nil, err
}
}
keypair, err := tls.LoadX509KeyPair(cfg.RPCCert, cfg.RPCKey)
if err != nil {
return nil, err
}
tlsConfig := tls.Config{
Certificates: []tls.Certificate{keypair},
MinVersion: tls.VersionTLS12,
}
// Change the standard net.Listen function to the tls one.
listenFunc = func(net string, laddr string) (net.Listener, error) {
return tls.Listen(net, laddr, &tlsConfig)
}
}
netAddrs, err := parseListeners(cfg.RPCListeners)
if err != nil {
return nil, err
}
listeners := make([]net.Listener, 0, len(netAddrs))
for _, addr := range netAddrs {
listener, err := listenFunc(addr.Network(), addr.String())
if err != nil {
rpcsLog.Warnf("Can't listen on %s: %v", addr, err)
continue
}
listeners = append(listeners, listener)
}
return listeners, nil
} | go | func setupRPCListeners() ([]net.Listener, error) {
// Setup TLS if not disabled.
listenFunc := net.Listen
if !cfg.DisableTLS {
// Generate the TLS cert and key file if both don't already
// exist.
if !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {
err := genCertPair(cfg.RPCCert, cfg.RPCKey)
if err != nil {
return nil, err
}
}
keypair, err := tls.LoadX509KeyPair(cfg.RPCCert, cfg.RPCKey)
if err != nil {
return nil, err
}
tlsConfig := tls.Config{
Certificates: []tls.Certificate{keypair},
MinVersion: tls.VersionTLS12,
}
// Change the standard net.Listen function to the tls one.
listenFunc = func(net string, laddr string) (net.Listener, error) {
return tls.Listen(net, laddr, &tlsConfig)
}
}
netAddrs, err := parseListeners(cfg.RPCListeners)
if err != nil {
return nil, err
}
listeners := make([]net.Listener, 0, len(netAddrs))
for _, addr := range netAddrs {
listener, err := listenFunc(addr.Network(), addr.String())
if err != nil {
rpcsLog.Warnf("Can't listen on %s: %v", addr, err)
continue
}
listeners = append(listeners, listener)
}
return listeners, nil
} | [
"func",
"setupRPCListeners",
"(",
")",
"(",
"[",
"]",
"net",
".",
"Listener",
",",
"error",
")",
"{",
"// Setup TLS if not disabled.",
"listenFunc",
":=",
"net",
".",
"Listen",
"\n",
"if",
"!",
"cfg",
".",
"DisableTLS",
"{",
"// Generate the TLS cert and key fil... | // setupRPCListeners returns a slice of listeners that are configured for use
// with the RPC server depending on the configuration settings for listen
// addresses and TLS. | [
"setupRPCListeners",
"returns",
"a",
"slice",
"of",
"listeners",
"that",
"are",
"configured",
"for",
"use",
"with",
"the",
"RPC",
"server",
"depending",
"on",
"the",
"configuration",
"settings",
"for",
"listen",
"addresses",
"and",
"TLS",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L2506-L2550 |
163,278 | btcsuite/btcd | server.go | initListeners | func initListeners(amgr *addrmgr.AddrManager, listenAddrs []string, services wire.ServiceFlag) ([]net.Listener, NAT, error) {
// Listen for TCP connections at the configured addresses
netAddrs, err := parseListeners(listenAddrs)
if err != nil {
return nil, nil, err
}
listeners := make([]net.Listener, 0, len(netAddrs))
for _, addr := range netAddrs {
listener, err := net.Listen(addr.Network(), addr.String())
if err != nil {
srvrLog.Warnf("Can't listen on %s: %v", addr, err)
continue
}
listeners = append(listeners, listener)
}
var nat NAT
if len(cfg.ExternalIPs) != 0 {
defaultPort, err := strconv.ParseUint(activeNetParams.DefaultPort, 10, 16)
if err != nil {
srvrLog.Errorf("Can not parse default port %s for active chain: %v",
activeNetParams.DefaultPort, err)
return nil, nil, err
}
for _, sip := range cfg.ExternalIPs {
eport := uint16(defaultPort)
host, portstr, err := net.SplitHostPort(sip)
if err != nil {
// no port, use default.
host = sip
} else {
port, err := strconv.ParseUint(portstr, 10, 16)
if err != nil {
srvrLog.Warnf("Can not parse port from %s for "+
"externalip: %v", sip, err)
continue
}
eport = uint16(port)
}
na, err := amgr.HostToNetAddress(host, eport, services)
if err != nil {
srvrLog.Warnf("Not adding %s as externalip: %v", sip, err)
continue
}
err = amgr.AddLocalAddress(na, addrmgr.ManualPrio)
if err != nil {
amgrLog.Warnf("Skipping specified external IP: %v", err)
}
}
} else {
if cfg.Upnp {
var err error
nat, err = Discover()
if err != nil {
srvrLog.Warnf("Can't discover upnp: %v", err)
}
// nil nat here is fine, just means no upnp on network.
}
// Add bound addresses to address manager to be advertised to peers.
for _, listener := range listeners {
addr := listener.Addr().String()
err := addLocalAddress(amgr, addr, services)
if err != nil {
amgrLog.Warnf("Skipping bound address %s: %v", addr, err)
}
}
}
return listeners, nat, nil
} | go | func initListeners(amgr *addrmgr.AddrManager, listenAddrs []string, services wire.ServiceFlag) ([]net.Listener, NAT, error) {
// Listen for TCP connections at the configured addresses
netAddrs, err := parseListeners(listenAddrs)
if err != nil {
return nil, nil, err
}
listeners := make([]net.Listener, 0, len(netAddrs))
for _, addr := range netAddrs {
listener, err := net.Listen(addr.Network(), addr.String())
if err != nil {
srvrLog.Warnf("Can't listen on %s: %v", addr, err)
continue
}
listeners = append(listeners, listener)
}
var nat NAT
if len(cfg.ExternalIPs) != 0 {
defaultPort, err := strconv.ParseUint(activeNetParams.DefaultPort, 10, 16)
if err != nil {
srvrLog.Errorf("Can not parse default port %s for active chain: %v",
activeNetParams.DefaultPort, err)
return nil, nil, err
}
for _, sip := range cfg.ExternalIPs {
eport := uint16(defaultPort)
host, portstr, err := net.SplitHostPort(sip)
if err != nil {
// no port, use default.
host = sip
} else {
port, err := strconv.ParseUint(portstr, 10, 16)
if err != nil {
srvrLog.Warnf("Can not parse port from %s for "+
"externalip: %v", sip, err)
continue
}
eport = uint16(port)
}
na, err := amgr.HostToNetAddress(host, eport, services)
if err != nil {
srvrLog.Warnf("Not adding %s as externalip: %v", sip, err)
continue
}
err = amgr.AddLocalAddress(na, addrmgr.ManualPrio)
if err != nil {
amgrLog.Warnf("Skipping specified external IP: %v", err)
}
}
} else {
if cfg.Upnp {
var err error
nat, err = Discover()
if err != nil {
srvrLog.Warnf("Can't discover upnp: %v", err)
}
// nil nat here is fine, just means no upnp on network.
}
// Add bound addresses to address manager to be advertised to peers.
for _, listener := range listeners {
addr := listener.Addr().String()
err := addLocalAddress(amgr, addr, services)
if err != nil {
amgrLog.Warnf("Skipping bound address %s: %v", addr, err)
}
}
}
return listeners, nat, nil
} | [
"func",
"initListeners",
"(",
"amgr",
"*",
"addrmgr",
".",
"AddrManager",
",",
"listenAddrs",
"[",
"]",
"string",
",",
"services",
"wire",
".",
"ServiceFlag",
")",
"(",
"[",
"]",
"net",
".",
"Listener",
",",
"NAT",
",",
"error",
")",
"{",
"// Listen for ... | // initListeners initializes the configured net listeners and adds any bound
// addresses to the address manager. Returns the listeners and a NAT interface,
// which is non-nil if UPnP is in use. | [
"initListeners",
"initializes",
"the",
"configured",
"net",
"listeners",
"and",
"adds",
"any",
"bound",
"addresses",
"to",
"the",
"address",
"manager",
".",
"Returns",
"the",
"listeners",
"and",
"a",
"NAT",
"interface",
"which",
"is",
"non",
"-",
"nil",
"if",
... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L2893-L2966 |
163,279 | btcsuite/btcd | server.go | addLocalAddress | func addLocalAddress(addrMgr *addrmgr.AddrManager, addr string, services wire.ServiceFlag) error {
host, portStr, err := net.SplitHostPort(addr)
if err != nil {
return err
}
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return err
}
if ip := net.ParseIP(host); ip != nil && ip.IsUnspecified() {
// If bound to unspecified address, advertise all local interfaces
addrs, err := net.InterfaceAddrs()
if err != nil {
return err
}
for _, addr := range addrs {
ifaceIP, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
// If bound to 0.0.0.0, do not add IPv6 interfaces and if bound to
// ::, do not add IPv4 interfaces.
if (ip.To4() == nil) != (ifaceIP.To4() == nil) {
continue
}
netAddr := wire.NewNetAddressIPPort(ifaceIP, uint16(port), services)
addrMgr.AddLocalAddress(netAddr, addrmgr.BoundPrio)
}
} else {
netAddr, err := addrMgr.HostToNetAddress(host, uint16(port), services)
if err != nil {
return err
}
addrMgr.AddLocalAddress(netAddr, addrmgr.BoundPrio)
}
return nil
} | go | func addLocalAddress(addrMgr *addrmgr.AddrManager, addr string, services wire.ServiceFlag) error {
host, portStr, err := net.SplitHostPort(addr)
if err != nil {
return err
}
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return err
}
if ip := net.ParseIP(host); ip != nil && ip.IsUnspecified() {
// If bound to unspecified address, advertise all local interfaces
addrs, err := net.InterfaceAddrs()
if err != nil {
return err
}
for _, addr := range addrs {
ifaceIP, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
// If bound to 0.0.0.0, do not add IPv6 interfaces and if bound to
// ::, do not add IPv4 interfaces.
if (ip.To4() == nil) != (ifaceIP.To4() == nil) {
continue
}
netAddr := wire.NewNetAddressIPPort(ifaceIP, uint16(port), services)
addrMgr.AddLocalAddress(netAddr, addrmgr.BoundPrio)
}
} else {
netAddr, err := addrMgr.HostToNetAddress(host, uint16(port), services)
if err != nil {
return err
}
addrMgr.AddLocalAddress(netAddr, addrmgr.BoundPrio)
}
return nil
} | [
"func",
"addLocalAddress",
"(",
"addrMgr",
"*",
"addrmgr",
".",
"AddrManager",
",",
"addr",
"string",
",",
"services",
"wire",
".",
"ServiceFlag",
")",
"error",
"{",
"host",
",",
"portStr",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"addr",
")",
... | // addLocalAddress adds an address that this node is listening on to the
// address manager so that it may be relayed to peers. | [
"addLocalAddress",
"adds",
"an",
"address",
"that",
"this",
"node",
"is",
"listening",
"on",
"to",
"the",
"address",
"manager",
"so",
"that",
"it",
"may",
"be",
"relayed",
"to",
"peers",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L3018-L3060 |
163,280 | btcsuite/btcd | server.go | dynamicTickDuration | func dynamicTickDuration(remaining time.Duration) time.Duration {
switch {
case remaining <= time.Second*5:
return time.Second
case remaining <= time.Second*15:
return time.Second * 5
case remaining <= time.Minute:
return time.Second * 15
case remaining <= time.Minute*5:
return time.Minute
case remaining <= time.Minute*15:
return time.Minute * 5
case remaining <= time.Hour:
return time.Minute * 15
}
return time.Hour
} | go | func dynamicTickDuration(remaining time.Duration) time.Duration {
switch {
case remaining <= time.Second*5:
return time.Second
case remaining <= time.Second*15:
return time.Second * 5
case remaining <= time.Minute:
return time.Second * 15
case remaining <= time.Minute*5:
return time.Minute
case remaining <= time.Minute*15:
return time.Minute * 5
case remaining <= time.Hour:
return time.Minute * 15
}
return time.Hour
} | [
"func",
"dynamicTickDuration",
"(",
"remaining",
"time",
".",
"Duration",
")",
"time",
".",
"Duration",
"{",
"switch",
"{",
"case",
"remaining",
"<=",
"time",
".",
"Second",
"*",
"5",
":",
"return",
"time",
".",
"Second",
"\n",
"case",
"remaining",
"<=",
... | // dynamicTickDuration is a convenience function used to dynamically choose a
// tick duration based on remaining time. It is primarily used during
// server shutdown to make shutdown warnings more frequent as the shutdown time
// approaches. | [
"dynamicTickDuration",
"is",
"a",
"convenience",
"function",
"used",
"to",
"dynamically",
"choose",
"a",
"tick",
"duration",
"based",
"on",
"remaining",
"time",
".",
"It",
"is",
"primarily",
"used",
"during",
"server",
"shutdown",
"to",
"make",
"shutdown",
"warn... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L3066-L3082 |
163,281 | btcsuite/btcd | server.go | isWhitelisted | func isWhitelisted(addr net.Addr) bool {
if len(cfg.whitelists) == 0 {
return false
}
host, _, err := net.SplitHostPort(addr.String())
if err != nil {
srvrLog.Warnf("Unable to SplitHostPort on '%s': %v", addr, err)
return false
}
ip := net.ParseIP(host)
if ip == nil {
srvrLog.Warnf("Unable to parse IP '%s'", addr)
return false
}
for _, ipnet := range cfg.whitelists {
if ipnet.Contains(ip) {
return true
}
}
return false
} | go | func isWhitelisted(addr net.Addr) bool {
if len(cfg.whitelists) == 0 {
return false
}
host, _, err := net.SplitHostPort(addr.String())
if err != nil {
srvrLog.Warnf("Unable to SplitHostPort on '%s': %v", addr, err)
return false
}
ip := net.ParseIP(host)
if ip == nil {
srvrLog.Warnf("Unable to parse IP '%s'", addr)
return false
}
for _, ipnet := range cfg.whitelists {
if ipnet.Contains(ip) {
return true
}
}
return false
} | [
"func",
"isWhitelisted",
"(",
"addr",
"net",
".",
"Addr",
")",
"bool",
"{",
"if",
"len",
"(",
"cfg",
".",
"whitelists",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"host",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",... | // isWhitelisted returns whether the IP address is included in the whitelisted
// networks and IPs. | [
"isWhitelisted",
"returns",
"whether",
"the",
"IP",
"address",
"is",
"included",
"in",
"the",
"whitelisted",
"networks",
"and",
"IPs",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L3086-L3108 |
163,282 | btcsuite/btcd | server.go | Swap | func (s checkpointSorter) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
} | go | func (s checkpointSorter) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
} | [
"func",
"(",
"s",
"checkpointSorter",
")",
"Swap",
"(",
"i",
",",
"j",
"int",
")",
"{",
"s",
"[",
"i",
"]",
",",
"s",
"[",
"j",
"]",
"=",
"s",
"[",
"j",
"]",
",",
"s",
"[",
"i",
"]",
"\n",
"}"
] | // Swap swaps the checkpoints at the passed indices. It is part of the
// sort.Interface implementation. | [
"Swap",
"swaps",
"the",
"checkpoints",
"at",
"the",
"passed",
"indices",
".",
"It",
"is",
"part",
"of",
"the",
"sort",
".",
"Interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L3122-L3124 |
163,283 | btcsuite/btcd | server.go | Less | func (s checkpointSorter) Less(i, j int) bool {
return s[i].Height < s[j].Height
} | go | func (s checkpointSorter) Less(i, j int) bool {
return s[i].Height < s[j].Height
} | [
"func",
"(",
"s",
"checkpointSorter",
")",
"Less",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"s",
"[",
"i",
"]",
".",
"Height",
"<",
"s",
"[",
"j",
"]",
".",
"Height",
"\n",
"}"
] | // Less returns whether the checkpoint with index i should sort before the
// checkpoint with index j. It is part of the sort.Interface implementation. | [
"Less",
"returns",
"whether",
"the",
"checkpoint",
"with",
"index",
"i",
"should",
"sort",
"before",
"the",
"checkpoint",
"with",
"index",
"j",
".",
"It",
"is",
"part",
"of",
"the",
"sort",
".",
"Interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L3128-L3130 |
163,284 | btcsuite/btcd | server.go | mergeCheckpoints | func mergeCheckpoints(defaultCheckpoints, additional []chaincfg.Checkpoint) []chaincfg.Checkpoint {
// Create a map of the additional checkpoints to remove duplicates while
// leaving the most recently-specified checkpoint.
extra := make(map[int32]chaincfg.Checkpoint)
for _, checkpoint := range additional {
extra[checkpoint.Height] = checkpoint
}
// Add all default checkpoints that do not have an override in the
// additional checkpoints.
numDefault := len(defaultCheckpoints)
checkpoints := make([]chaincfg.Checkpoint, 0, numDefault+len(extra))
for _, checkpoint := range defaultCheckpoints {
if _, exists := extra[checkpoint.Height]; !exists {
checkpoints = append(checkpoints, checkpoint)
}
}
// Append the additional checkpoints and return the sorted results.
for _, checkpoint := range extra {
checkpoints = append(checkpoints, checkpoint)
}
sort.Sort(checkpointSorter(checkpoints))
return checkpoints
} | go | func mergeCheckpoints(defaultCheckpoints, additional []chaincfg.Checkpoint) []chaincfg.Checkpoint {
// Create a map of the additional checkpoints to remove duplicates while
// leaving the most recently-specified checkpoint.
extra := make(map[int32]chaincfg.Checkpoint)
for _, checkpoint := range additional {
extra[checkpoint.Height] = checkpoint
}
// Add all default checkpoints that do not have an override in the
// additional checkpoints.
numDefault := len(defaultCheckpoints)
checkpoints := make([]chaincfg.Checkpoint, 0, numDefault+len(extra))
for _, checkpoint := range defaultCheckpoints {
if _, exists := extra[checkpoint.Height]; !exists {
checkpoints = append(checkpoints, checkpoint)
}
}
// Append the additional checkpoints and return the sorted results.
for _, checkpoint := range extra {
checkpoints = append(checkpoints, checkpoint)
}
sort.Sort(checkpointSorter(checkpoints))
return checkpoints
} | [
"func",
"mergeCheckpoints",
"(",
"defaultCheckpoints",
",",
"additional",
"[",
"]",
"chaincfg",
".",
"Checkpoint",
")",
"[",
"]",
"chaincfg",
".",
"Checkpoint",
"{",
"// Create a map of the additional checkpoints to remove duplicates while",
"// leaving the most recently-specif... | // mergeCheckpoints returns two slices of checkpoints merged into one slice
// such that the checkpoints are sorted by height. In the case the additional
// checkpoints contain a checkpoint with the same height as a checkpoint in the
// default checkpoints, the additional checkpoint will take precedence and
// overwrite the default one. | [
"mergeCheckpoints",
"returns",
"two",
"slices",
"of",
"checkpoints",
"merged",
"into",
"one",
"slice",
"such",
"that",
"the",
"checkpoints",
"are",
"sorted",
"by",
"height",
".",
"In",
"the",
"case",
"the",
"additional",
"checkpoints",
"contain",
"a",
"checkpoin... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L3137-L3161 |
163,285 | btcsuite/btcd | txscript/sign.go | RawTxInWitnessSignature | func RawTxInWitnessSignature(tx *wire.MsgTx, sigHashes *TxSigHashes, idx int,
amt int64, subScript []byte, hashType SigHashType,
key *btcec.PrivateKey) ([]byte, error) {
parsedScript, err := parseScript(subScript)
if err != nil {
return nil, fmt.Errorf("cannot parse output script: %v", err)
}
hash, err := calcWitnessSignatureHash(parsedScript, sigHashes, hashType, tx,
idx, amt)
if err != nil {
return nil, err
}
signature, err := key.Sign(hash)
if err != nil {
return nil, fmt.Errorf("cannot sign tx input: %s", err)
}
return append(signature.Serialize(), byte(hashType)), nil
} | go | func RawTxInWitnessSignature(tx *wire.MsgTx, sigHashes *TxSigHashes, idx int,
amt int64, subScript []byte, hashType SigHashType,
key *btcec.PrivateKey) ([]byte, error) {
parsedScript, err := parseScript(subScript)
if err != nil {
return nil, fmt.Errorf("cannot parse output script: %v", err)
}
hash, err := calcWitnessSignatureHash(parsedScript, sigHashes, hashType, tx,
idx, amt)
if err != nil {
return nil, err
}
signature, err := key.Sign(hash)
if err != nil {
return nil, fmt.Errorf("cannot sign tx input: %s", err)
}
return append(signature.Serialize(), byte(hashType)), nil
} | [
"func",
"RawTxInWitnessSignature",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
",",
"sigHashes",
"*",
"TxSigHashes",
",",
"idx",
"int",
",",
"amt",
"int64",
",",
"subScript",
"[",
"]",
"byte",
",",
"hashType",
"SigHashType",
",",
"key",
"*",
"btcec",
".",
"Pri... | // RawTxInWitnessSignature returns the serialized ECDA signature for the input
// idx of the given transaction, with the hashType appended to it. This
// function is identical to RawTxInSignature, however the signature generated
// signs a new sighash digest defined in BIP0143. | [
"RawTxInWitnessSignature",
"returns",
"the",
"serialized",
"ECDA",
"signature",
"for",
"the",
"input",
"idx",
"of",
"the",
"given",
"transaction",
"with",
"the",
"hashType",
"appended",
"to",
"it",
".",
"This",
"function",
"is",
"identical",
"to",
"RawTxInSignatur... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/sign.go#L21-L42 |
163,286 | btcsuite/btcd | txscript/sign.go | WitnessSignature | func WitnessSignature(tx *wire.MsgTx, sigHashes *TxSigHashes, idx int, amt int64,
subscript []byte, hashType SigHashType, privKey *btcec.PrivateKey,
compress bool) (wire.TxWitness, error) {
sig, err := RawTxInWitnessSignature(tx, sigHashes, idx, amt, subscript,
hashType, privKey)
if err != nil {
return nil, err
}
pk := (*btcec.PublicKey)(&privKey.PublicKey)
var pkData []byte
if compress {
pkData = pk.SerializeCompressed()
} else {
pkData = pk.SerializeUncompressed()
}
// A witness script is actually a stack, so we return an array of byte
// slices here, rather than a single byte slice.
return wire.TxWitness{sig, pkData}, nil
} | go | func WitnessSignature(tx *wire.MsgTx, sigHashes *TxSigHashes, idx int, amt int64,
subscript []byte, hashType SigHashType, privKey *btcec.PrivateKey,
compress bool) (wire.TxWitness, error) {
sig, err := RawTxInWitnessSignature(tx, sigHashes, idx, amt, subscript,
hashType, privKey)
if err != nil {
return nil, err
}
pk := (*btcec.PublicKey)(&privKey.PublicKey)
var pkData []byte
if compress {
pkData = pk.SerializeCompressed()
} else {
pkData = pk.SerializeUncompressed()
}
// A witness script is actually a stack, so we return an array of byte
// slices here, rather than a single byte slice.
return wire.TxWitness{sig, pkData}, nil
} | [
"func",
"WitnessSignature",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
",",
"sigHashes",
"*",
"TxSigHashes",
",",
"idx",
"int",
",",
"amt",
"int64",
",",
"subscript",
"[",
"]",
"byte",
",",
"hashType",
"SigHashType",
",",
"privKey",
"*",
"btcec",
".",
"Privat... | // WitnessSignature creates an input witness stack for tx to spend BTC sent
// from a previous output to the owner of privKey using the p2wkh script
// template. The passed transaction must contain all the inputs and outputs as
// dictated by the passed hashType. The signature generated observes the new
// transaction digest algorithm defined within BIP0143. | [
"WitnessSignature",
"creates",
"an",
"input",
"witness",
"stack",
"for",
"tx",
"to",
"spend",
"BTC",
"sent",
"from",
"a",
"previous",
"output",
"to",
"the",
"owner",
"of",
"privKey",
"using",
"the",
"p2wkh",
"script",
"template",
".",
"The",
"passed",
"trans... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/sign.go#L49-L70 |
163,287 | btcsuite/btcd | txscript/sign.go | RawTxInSignature | func RawTxInSignature(tx *wire.MsgTx, idx int, subScript []byte,
hashType SigHashType, key *btcec.PrivateKey) ([]byte, error) {
hash, err := CalcSignatureHash(subScript, hashType, tx, idx)
if err != nil {
return nil, err
}
signature, err := key.Sign(hash)
if err != nil {
return nil, fmt.Errorf("cannot sign tx input: %s", err)
}
return append(signature.Serialize(), byte(hashType)), nil
} | go | func RawTxInSignature(tx *wire.MsgTx, idx int, subScript []byte,
hashType SigHashType, key *btcec.PrivateKey) ([]byte, error) {
hash, err := CalcSignatureHash(subScript, hashType, tx, idx)
if err != nil {
return nil, err
}
signature, err := key.Sign(hash)
if err != nil {
return nil, fmt.Errorf("cannot sign tx input: %s", err)
}
return append(signature.Serialize(), byte(hashType)), nil
} | [
"func",
"RawTxInSignature",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
",",
"idx",
"int",
",",
"subScript",
"[",
"]",
"byte",
",",
"hashType",
"SigHashType",
",",
"key",
"*",
"btcec",
".",
"PrivateKey",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
... | // RawTxInSignature returns the serialized ECDSA signature for the input idx of
// the given transaction, with hashType appended to it. | [
"RawTxInSignature",
"returns",
"the",
"serialized",
"ECDSA",
"signature",
"for",
"the",
"input",
"idx",
"of",
"the",
"given",
"transaction",
"with",
"hashType",
"appended",
"to",
"it",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/sign.go#L74-L87 |
163,288 | btcsuite/btcd | txscript/sign.go | SignatureScript | func SignatureScript(tx *wire.MsgTx, idx int, subscript []byte, hashType SigHashType, privKey *btcec.PrivateKey, compress bool) ([]byte, error) {
sig, err := RawTxInSignature(tx, idx, subscript, hashType, privKey)
if err != nil {
return nil, err
}
pk := (*btcec.PublicKey)(&privKey.PublicKey)
var pkData []byte
if compress {
pkData = pk.SerializeCompressed()
} else {
pkData = pk.SerializeUncompressed()
}
return NewScriptBuilder().AddData(sig).AddData(pkData).Script()
} | go | func SignatureScript(tx *wire.MsgTx, idx int, subscript []byte, hashType SigHashType, privKey *btcec.PrivateKey, compress bool) ([]byte, error) {
sig, err := RawTxInSignature(tx, idx, subscript, hashType, privKey)
if err != nil {
return nil, err
}
pk := (*btcec.PublicKey)(&privKey.PublicKey)
var pkData []byte
if compress {
pkData = pk.SerializeCompressed()
} else {
pkData = pk.SerializeUncompressed()
}
return NewScriptBuilder().AddData(sig).AddData(pkData).Script()
} | [
"func",
"SignatureScript",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
",",
"idx",
"int",
",",
"subscript",
"[",
"]",
"byte",
",",
"hashType",
"SigHashType",
",",
"privKey",
"*",
"btcec",
".",
"PrivateKey",
",",
"compress",
"bool",
")",
"(",
"[",
"]",
"byte"... | // SignatureScript creates an input signature script for tx to spend BTC sent
// from a previous output to the owner of privKey. tx must include all
// transaction inputs and outputs, however txin scripts are allowed to be filled
// or empty. The returned script is calculated to be used as the idx'th txin
// sigscript for tx. subscript is the PkScript of the previous output being used
// as the idx'th input. privKey is serialized in either a compressed or
// uncompressed format based on compress. This format must match the same format
// used to generate the payment address, or the script validation will fail. | [
"SignatureScript",
"creates",
"an",
"input",
"signature",
"script",
"for",
"tx",
"to",
"spend",
"BTC",
"sent",
"from",
"a",
"previous",
"output",
"to",
"the",
"owner",
"of",
"privKey",
".",
"tx",
"must",
"include",
"all",
"transaction",
"inputs",
"and",
"out... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/sign.go#L97-L112 |
163,289 | btcsuite/btcd | txscript/sign.go | mergeScripts | func mergeScripts(chainParams *chaincfg.Params, tx *wire.MsgTx, idx int,
pkScript []byte, class ScriptClass, addresses []btcutil.Address,
nRequired int, sigScript, prevScript []byte) []byte {
// TODO: the scripthash and multisig paths here are overly
// inefficient in that they will recompute already known data.
// some internal refactoring could probably make this avoid needless
// extra calculations.
switch class {
case ScriptHashTy:
// Remove the last push in the script and then recurse.
// this could be a lot less inefficient.
sigPops, err := parseScript(sigScript)
if err != nil || len(sigPops) == 0 {
return prevScript
}
prevPops, err := parseScript(prevScript)
if err != nil || len(prevPops) == 0 {
return sigScript
}
// assume that script in sigPops is the correct one, we just
// made it.
script := sigPops[len(sigPops)-1].data
// We already know this information somewhere up the stack.
class, addresses, nrequired, _ :=
ExtractPkScriptAddrs(script, chainParams)
// regenerate scripts.
sigScript, _ := unparseScript(sigPops)
prevScript, _ := unparseScript(prevPops)
// Merge
mergedScript := mergeScripts(chainParams, tx, idx, script,
class, addresses, nrequired, sigScript, prevScript)
// Reappend the script and return the result.
builder := NewScriptBuilder()
builder.AddOps(mergedScript)
builder.AddData(script)
finalScript, _ := builder.Script()
return finalScript
case MultiSigTy:
return mergeMultiSig(tx, idx, addresses, nRequired, pkScript,
sigScript, prevScript)
// It doesn't actually make sense to merge anything other than multiig
// and scripthash (because it could contain multisig). Everything else
// has either zero signature, can't be spent, or has a single signature
// which is either present or not. The other two cases are handled
// above. In the conflict case here we just assume the longest is
// correct (this matches behaviour of the reference implementation).
default:
if len(sigScript) > len(prevScript) {
return sigScript
}
return prevScript
}
} | go | func mergeScripts(chainParams *chaincfg.Params, tx *wire.MsgTx, idx int,
pkScript []byte, class ScriptClass, addresses []btcutil.Address,
nRequired int, sigScript, prevScript []byte) []byte {
// TODO: the scripthash and multisig paths here are overly
// inefficient in that they will recompute already known data.
// some internal refactoring could probably make this avoid needless
// extra calculations.
switch class {
case ScriptHashTy:
// Remove the last push in the script and then recurse.
// this could be a lot less inefficient.
sigPops, err := parseScript(sigScript)
if err != nil || len(sigPops) == 0 {
return prevScript
}
prevPops, err := parseScript(prevScript)
if err != nil || len(prevPops) == 0 {
return sigScript
}
// assume that script in sigPops is the correct one, we just
// made it.
script := sigPops[len(sigPops)-1].data
// We already know this information somewhere up the stack.
class, addresses, nrequired, _ :=
ExtractPkScriptAddrs(script, chainParams)
// regenerate scripts.
sigScript, _ := unparseScript(sigPops)
prevScript, _ := unparseScript(prevPops)
// Merge
mergedScript := mergeScripts(chainParams, tx, idx, script,
class, addresses, nrequired, sigScript, prevScript)
// Reappend the script and return the result.
builder := NewScriptBuilder()
builder.AddOps(mergedScript)
builder.AddData(script)
finalScript, _ := builder.Script()
return finalScript
case MultiSigTy:
return mergeMultiSig(tx, idx, addresses, nRequired, pkScript,
sigScript, prevScript)
// It doesn't actually make sense to merge anything other than multiig
// and scripthash (because it could contain multisig). Everything else
// has either zero signature, can't be spent, or has a single signature
// which is either present or not. The other two cases are handled
// above. In the conflict case here we just assume the longest is
// correct (this matches behaviour of the reference implementation).
default:
if len(sigScript) > len(prevScript) {
return sigScript
}
return prevScript
}
} | [
"func",
"mergeScripts",
"(",
"chainParams",
"*",
"chaincfg",
".",
"Params",
",",
"tx",
"*",
"wire",
".",
"MsgTx",
",",
"idx",
"int",
",",
"pkScript",
"[",
"]",
"byte",
",",
"class",
"ScriptClass",
",",
"addresses",
"[",
"]",
"btcutil",
".",
"Address",
... | // mergeScripts merges sigScript and prevScript assuming they are both
// partial solutions for pkScript spending output idx of tx. class, addresses
// and nrequired are the result of extracting the addresses from pkscript.
// The return value is the best effort merging of the two scripts. Calling this
// function with addresses, class and nrequired that do not match pkScript is
// an error and results in undefined behaviour. | [
"mergeScripts",
"merges",
"sigScript",
"and",
"prevScript",
"assuming",
"they",
"are",
"both",
"partial",
"solutions",
"for",
"pkScript",
"spending",
"output",
"idx",
"of",
"tx",
".",
"class",
"addresses",
"and",
"nrequired",
"are",
"the",
"result",
"of",
"extra... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/sign.go#L221-L280 |
163,290 | btcsuite/btcd | txscript/sign.go | mergeMultiSig | func mergeMultiSig(tx *wire.MsgTx, idx int, addresses []btcutil.Address,
nRequired int, pkScript, sigScript, prevScript []byte) []byte {
// This is an internal only function and we already parsed this script
// as ok for multisig (this is how we got here), so if this fails then
// all assumptions are broken and who knows which way is up?
pkPops, _ := parseScript(pkScript)
sigPops, err := parseScript(sigScript)
if err != nil || len(sigPops) == 0 {
return prevScript
}
prevPops, err := parseScript(prevScript)
if err != nil || len(prevPops) == 0 {
return sigScript
}
// Convenience function to avoid duplication.
extractSigs := func(pops []parsedOpcode, sigs [][]byte) [][]byte {
for _, pop := range pops {
if len(pop.data) != 0 {
sigs = append(sigs, pop.data)
}
}
return sigs
}
possibleSigs := make([][]byte, 0, len(sigPops)+len(prevPops))
possibleSigs = extractSigs(sigPops, possibleSigs)
possibleSigs = extractSigs(prevPops, possibleSigs)
// Now we need to match the signatures to pubkeys, the only real way to
// do that is to try to verify them all and match it to the pubkey
// that verifies it. we then can go through the addresses in order
// to build our script. Anything that doesn't parse or doesn't verify we
// throw away.
addrToSig := make(map[string][]byte)
sigLoop:
for _, sig := range possibleSigs {
// can't have a valid signature that doesn't at least have a
// hashtype, in practise it is even longer than this. but
// that'll be checked next.
if len(sig) < 1 {
continue
}
tSig := sig[:len(sig)-1]
hashType := SigHashType(sig[len(sig)-1])
pSig, err := btcec.ParseDERSignature(tSig, btcec.S256())
if err != nil {
continue
}
// We have to do this each round since hash types may vary
// between signatures and so the hash will vary. We can,
// however, assume no sigs etc are in the script since that
// would make the transaction nonstandard and thus not
// MultiSigTy, so we just need to hash the full thing.
hash := calcSignatureHash(pkPops, hashType, tx, idx)
for _, addr := range addresses {
// All multisig addresses should be pubkey addresses
// it is an error to call this internal function with
// bad input.
pkaddr := addr.(*btcutil.AddressPubKey)
pubKey := pkaddr.PubKey()
// If it matches we put it in the map. We only
// can take one signature per public key so if we
// already have one, we can throw this away.
if pSig.Verify(hash, pubKey) {
aStr := addr.EncodeAddress()
if _, ok := addrToSig[aStr]; !ok {
addrToSig[aStr] = sig
}
continue sigLoop
}
}
}
// Extra opcode to handle the extra arg consumed (due to previous bugs
// in the reference implementation).
builder := NewScriptBuilder().AddOp(OP_FALSE)
doneSigs := 0
// This assumes that addresses are in the same order as in the script.
for _, addr := range addresses {
sig, ok := addrToSig[addr.EncodeAddress()]
if !ok {
continue
}
builder.AddData(sig)
doneSigs++
if doneSigs == nRequired {
break
}
}
// padding for missing ones.
for i := doneSigs; i < nRequired; i++ {
builder.AddOp(OP_0)
}
script, _ := builder.Script()
return script
} | go | func mergeMultiSig(tx *wire.MsgTx, idx int, addresses []btcutil.Address,
nRequired int, pkScript, sigScript, prevScript []byte) []byte {
// This is an internal only function and we already parsed this script
// as ok for multisig (this is how we got here), so if this fails then
// all assumptions are broken and who knows which way is up?
pkPops, _ := parseScript(pkScript)
sigPops, err := parseScript(sigScript)
if err != nil || len(sigPops) == 0 {
return prevScript
}
prevPops, err := parseScript(prevScript)
if err != nil || len(prevPops) == 0 {
return sigScript
}
// Convenience function to avoid duplication.
extractSigs := func(pops []parsedOpcode, sigs [][]byte) [][]byte {
for _, pop := range pops {
if len(pop.data) != 0 {
sigs = append(sigs, pop.data)
}
}
return sigs
}
possibleSigs := make([][]byte, 0, len(sigPops)+len(prevPops))
possibleSigs = extractSigs(sigPops, possibleSigs)
possibleSigs = extractSigs(prevPops, possibleSigs)
// Now we need to match the signatures to pubkeys, the only real way to
// do that is to try to verify them all and match it to the pubkey
// that verifies it. we then can go through the addresses in order
// to build our script. Anything that doesn't parse or doesn't verify we
// throw away.
addrToSig := make(map[string][]byte)
sigLoop:
for _, sig := range possibleSigs {
// can't have a valid signature that doesn't at least have a
// hashtype, in practise it is even longer than this. but
// that'll be checked next.
if len(sig) < 1 {
continue
}
tSig := sig[:len(sig)-1]
hashType := SigHashType(sig[len(sig)-1])
pSig, err := btcec.ParseDERSignature(tSig, btcec.S256())
if err != nil {
continue
}
// We have to do this each round since hash types may vary
// between signatures and so the hash will vary. We can,
// however, assume no sigs etc are in the script since that
// would make the transaction nonstandard and thus not
// MultiSigTy, so we just need to hash the full thing.
hash := calcSignatureHash(pkPops, hashType, tx, idx)
for _, addr := range addresses {
// All multisig addresses should be pubkey addresses
// it is an error to call this internal function with
// bad input.
pkaddr := addr.(*btcutil.AddressPubKey)
pubKey := pkaddr.PubKey()
// If it matches we put it in the map. We only
// can take one signature per public key so if we
// already have one, we can throw this away.
if pSig.Verify(hash, pubKey) {
aStr := addr.EncodeAddress()
if _, ok := addrToSig[aStr]; !ok {
addrToSig[aStr] = sig
}
continue sigLoop
}
}
}
// Extra opcode to handle the extra arg consumed (due to previous bugs
// in the reference implementation).
builder := NewScriptBuilder().AddOp(OP_FALSE)
doneSigs := 0
// This assumes that addresses are in the same order as in the script.
for _, addr := range addresses {
sig, ok := addrToSig[addr.EncodeAddress()]
if !ok {
continue
}
builder.AddData(sig)
doneSigs++
if doneSigs == nRequired {
break
}
}
// padding for missing ones.
for i := doneSigs; i < nRequired; i++ {
builder.AddOp(OP_0)
}
script, _ := builder.Script()
return script
} | [
"func",
"mergeMultiSig",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
",",
"idx",
"int",
",",
"addresses",
"[",
"]",
"btcutil",
".",
"Address",
",",
"nRequired",
"int",
",",
"pkScript",
",",
"sigScript",
",",
"prevScript",
"[",
"]",
"byte",
")",
"[",
"]",
"... | // mergeMultiSig combines the two signature scripts sigScript and prevScript
// that both provide signatures for pkScript in output idx of tx. addresses
// and nRequired should be the results from extracting the addresses from
// pkScript. Since this function is internal only we assume that the arguments
// have come from other functions internally and thus are all consistent with
// each other, behaviour is undefined if this contract is broken. | [
"mergeMultiSig",
"combines",
"the",
"two",
"signature",
"scripts",
"sigScript",
"and",
"prevScript",
"that",
"both",
"provide",
"signatures",
"for",
"pkScript",
"in",
"output",
"idx",
"of",
"tx",
".",
"addresses",
"and",
"nRequired",
"should",
"be",
"the",
"resu... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/sign.go#L288-L395 |
163,291 | btcsuite/btcd | txscript/sign.go | GetKey | func (kc KeyClosure) GetKey(address btcutil.Address) (*btcec.PrivateKey,
bool, error) {
return kc(address)
} | go | func (kc KeyClosure) GetKey(address btcutil.Address) (*btcec.PrivateKey,
bool, error) {
return kc(address)
} | [
"func",
"(",
"kc",
"KeyClosure",
")",
"GetKey",
"(",
"address",
"btcutil",
".",
"Address",
")",
"(",
"*",
"btcec",
".",
"PrivateKey",
",",
"bool",
",",
"error",
")",
"{",
"return",
"kc",
"(",
"address",
")",
"\n",
"}"
] | // GetKey implements KeyDB by returning the result of calling the closure. | [
"GetKey",
"implements",
"KeyDB",
"by",
"returning",
"the",
"result",
"of",
"calling",
"the",
"closure",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/sign.go#L407-L410 |
163,292 | btcsuite/btcd | txscript/sign.go | GetScript | func (sc ScriptClosure) GetScript(address btcutil.Address) ([]byte, error) {
return sc(address)
} | go | func (sc ScriptClosure) GetScript(address btcutil.Address) ([]byte, error) {
return sc(address)
} | [
"func",
"(",
"sc",
"ScriptClosure",
")",
"GetScript",
"(",
"address",
"btcutil",
".",
"Address",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"sc",
"(",
"address",
")",
"\n",
"}"
] | // GetScript implements ScriptDB by returning the result of calling the closure. | [
"GetScript",
"implements",
"ScriptDB",
"by",
"returning",
"the",
"result",
"of",
"calling",
"the",
"closure",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/sign.go#L422-L424 |
163,293 | btcsuite/btcd | database/log.go | UseLogger | func UseLogger(logger btclog.Logger) {
log = logger
// Update the logger for the registered drivers.
for _, drv := range drivers {
if drv.UseLogger != nil {
drv.UseLogger(logger)
}
}
} | go | func UseLogger(logger btclog.Logger) {
log = logger
// Update the logger for the registered drivers.
for _, drv := range drivers {
if drv.UseLogger != nil {
drv.UseLogger(logger)
}
}
} | [
"func",
"UseLogger",
"(",
"logger",
"btclog",
".",
"Logger",
")",
"{",
"log",
"=",
"logger",
"\n\n",
"// Update the logger for the registered drivers.",
"for",
"_",
",",
"drv",
":=",
"range",
"drivers",
"{",
"if",
"drv",
".",
"UseLogger",
"!=",
"nil",
"{",
"... | // UseLogger uses a specified Logger to output package logging info. | [
"UseLogger",
"uses",
"a",
"specified",
"Logger",
"to",
"output",
"package",
"logging",
"info",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/log.go#L28-L37 |
163,294 | btcsuite/btcd | mempool/error.go | txRuleError | func txRuleError(c wire.RejectCode, desc string) RuleError {
return RuleError{
Err: TxRuleError{RejectCode: c, Description: desc},
}
} | go | func txRuleError(c wire.RejectCode, desc string) RuleError {
return RuleError{
Err: TxRuleError{RejectCode: c, Description: desc},
}
} | [
"func",
"txRuleError",
"(",
"c",
"wire",
".",
"RejectCode",
",",
"desc",
"string",
")",
"RuleError",
"{",
"return",
"RuleError",
"{",
"Err",
":",
"TxRuleError",
"{",
"RejectCode",
":",
"c",
",",
"Description",
":",
"desc",
"}",
",",
"}",
"\n",
"}"
] | // txRuleError creates an underlying TxRuleError with the given a set of
// arguments and returns a RuleError that encapsulates it. | [
"txRuleError",
"creates",
"an",
"underlying",
"TxRuleError",
"with",
"the",
"given",
"a",
"set",
"of",
"arguments",
"and",
"returns",
"a",
"RuleError",
"that",
"encapsulates",
"it",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/error.go#L47-L51 |
163,295 | btcsuite/btcd | mempool/error.go | extractRejectCode | func extractRejectCode(err error) (wire.RejectCode, bool) {
// Pull the underlying error out of a RuleError.
if rerr, ok := err.(RuleError); ok {
err = rerr.Err
}
switch err := err.(type) {
case blockchain.RuleError:
// Convert the chain error to a reject code.
var code wire.RejectCode
switch err.ErrorCode {
// Rejected due to duplicate.
case blockchain.ErrDuplicateBlock:
code = wire.RejectDuplicate
// Rejected due to obsolete version.
case blockchain.ErrBlockVersionTooOld:
code = wire.RejectObsolete
// Rejected due to checkpoint.
case blockchain.ErrCheckpointTimeTooOld:
fallthrough
case blockchain.ErrDifficultyTooLow:
fallthrough
case blockchain.ErrBadCheckpoint:
fallthrough
case blockchain.ErrForkTooOld:
code = wire.RejectCheckpoint
// Everything else is due to the block or transaction being invalid.
default:
code = wire.RejectInvalid
}
return code, true
case TxRuleError:
return err.RejectCode, true
case nil:
return wire.RejectInvalid, false
}
return wire.RejectInvalid, false
} | go | func extractRejectCode(err error) (wire.RejectCode, bool) {
// Pull the underlying error out of a RuleError.
if rerr, ok := err.(RuleError); ok {
err = rerr.Err
}
switch err := err.(type) {
case blockchain.RuleError:
// Convert the chain error to a reject code.
var code wire.RejectCode
switch err.ErrorCode {
// Rejected due to duplicate.
case blockchain.ErrDuplicateBlock:
code = wire.RejectDuplicate
// Rejected due to obsolete version.
case blockchain.ErrBlockVersionTooOld:
code = wire.RejectObsolete
// Rejected due to checkpoint.
case blockchain.ErrCheckpointTimeTooOld:
fallthrough
case blockchain.ErrDifficultyTooLow:
fallthrough
case blockchain.ErrBadCheckpoint:
fallthrough
case blockchain.ErrForkTooOld:
code = wire.RejectCheckpoint
// Everything else is due to the block or transaction being invalid.
default:
code = wire.RejectInvalid
}
return code, true
case TxRuleError:
return err.RejectCode, true
case nil:
return wire.RejectInvalid, false
}
return wire.RejectInvalid, false
} | [
"func",
"extractRejectCode",
"(",
"err",
"error",
")",
"(",
"wire",
".",
"RejectCode",
",",
"bool",
")",
"{",
"// Pull the underlying error out of a RuleError.",
"if",
"rerr",
",",
"ok",
":=",
"err",
".",
"(",
"RuleError",
")",
";",
"ok",
"{",
"err",
"=",
... | // extractRejectCode attempts to return a relevant reject code for a given error
// by examining the error for known types. It will return true if a code
// was successfully extracted. | [
"extractRejectCode",
"attempts",
"to",
"return",
"a",
"relevant",
"reject",
"code",
"for",
"a",
"given",
"error",
"by",
"examining",
"the",
"error",
"for",
"known",
"types",
".",
"It",
"will",
"return",
"true",
"if",
"a",
"code",
"was",
"successfully",
"extr... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/error.go#L64-L108 |
163,296 | btcsuite/btcd | mempool/error.go | ErrToRejectErr | func ErrToRejectErr(err error) (wire.RejectCode, string) {
// Return the reject code along with the error text if it can be
// extracted from the error.
rejectCode, found := extractRejectCode(err)
if found {
return rejectCode, err.Error()
}
// Return a generic rejected string if there is no error. This really
// should not happen unless the code elsewhere is not setting an error
// as it should be, but it's best to be safe and simply return a generic
// string rather than allowing the following code that dereferences the
// err to panic.
if err == nil {
return wire.RejectInvalid, "rejected"
}
// When the underlying error is not one of the above cases, just return
// wire.RejectInvalid with a generic rejected string plus the error
// text.
return wire.RejectInvalid, "rejected: " + err.Error()
} | go | func ErrToRejectErr(err error) (wire.RejectCode, string) {
// Return the reject code along with the error text if it can be
// extracted from the error.
rejectCode, found := extractRejectCode(err)
if found {
return rejectCode, err.Error()
}
// Return a generic rejected string if there is no error. This really
// should not happen unless the code elsewhere is not setting an error
// as it should be, but it's best to be safe and simply return a generic
// string rather than allowing the following code that dereferences the
// err to panic.
if err == nil {
return wire.RejectInvalid, "rejected"
}
// When the underlying error is not one of the above cases, just return
// wire.RejectInvalid with a generic rejected string plus the error
// text.
return wire.RejectInvalid, "rejected: " + err.Error()
} | [
"func",
"ErrToRejectErr",
"(",
"err",
"error",
")",
"(",
"wire",
".",
"RejectCode",
",",
"string",
")",
"{",
"// Return the reject code along with the error text if it can be",
"// extracted from the error.",
"rejectCode",
",",
"found",
":=",
"extractRejectCode",
"(",
"er... | // ErrToRejectErr examines the underlying type of the error and returns a reject
// code and string appropriate to be sent in a wire.MsgReject message. | [
"ErrToRejectErr",
"examines",
"the",
"underlying",
"type",
"of",
"the",
"error",
"and",
"returns",
"a",
"reject",
"code",
"and",
"string",
"appropriate",
"to",
"be",
"sent",
"in",
"a",
"wire",
".",
"MsgReject",
"message",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/error.go#L112-L133 |
163,297 | btcsuite/btcd | btcec/signature.go | Verify | func (sig *Signature) Verify(hash []byte, pubKey *PublicKey) bool {
return ecdsa.Verify(pubKey.ToECDSA(), hash, sig.R, sig.S)
} | go | func (sig *Signature) Verify(hash []byte, pubKey *PublicKey) bool {
return ecdsa.Verify(pubKey.ToECDSA(), hash, sig.R, sig.S)
} | [
"func",
"(",
"sig",
"*",
"Signature",
")",
"Verify",
"(",
"hash",
"[",
"]",
"byte",
",",
"pubKey",
"*",
"PublicKey",
")",
"bool",
"{",
"return",
"ecdsa",
".",
"Verify",
"(",
"pubKey",
".",
"ToECDSA",
"(",
")",
",",
"hash",
",",
"sig",
".",
"R",
"... | // Verify calls ecdsa.Verify to verify the signature of hash using the public
// key. It returns true if the signature is valid, false otherwise. | [
"Verify",
"calls",
"ecdsa",
".",
"Verify",
"to",
"verify",
"the",
"signature",
"of",
"hash",
"using",
"the",
"public",
"key",
".",
"It",
"returns",
"true",
"if",
"the",
"signature",
"is",
"valid",
"false",
"otherwise",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/signature.go#L76-L78 |
163,298 | btcsuite/btcd | btcec/signature.go | IsEqual | func (sig *Signature) IsEqual(otherSig *Signature) bool {
return sig.R.Cmp(otherSig.R) == 0 &&
sig.S.Cmp(otherSig.S) == 0
} | go | func (sig *Signature) IsEqual(otherSig *Signature) bool {
return sig.R.Cmp(otherSig.R) == 0 &&
sig.S.Cmp(otherSig.S) == 0
} | [
"func",
"(",
"sig",
"*",
"Signature",
")",
"IsEqual",
"(",
"otherSig",
"*",
"Signature",
")",
"bool",
"{",
"return",
"sig",
".",
"R",
".",
"Cmp",
"(",
"otherSig",
".",
"R",
")",
"==",
"0",
"&&",
"sig",
".",
"S",
".",
"Cmp",
"(",
"otherSig",
".",
... | // IsEqual compares this Signature instance to the one passed, returning true
// if both Signatures are equivalent. A signature is equivalent to another, if
// they both have the same scalar value for R and S. | [
"IsEqual",
"compares",
"this",
"Signature",
"instance",
"to",
"the",
"one",
"passed",
"returning",
"true",
"if",
"both",
"Signatures",
"are",
"equivalent",
".",
"A",
"signature",
"is",
"equivalent",
"to",
"another",
"if",
"they",
"both",
"have",
"the",
"same",... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/signature.go#L83-L86 |
163,299 | btcsuite/btcd | btcec/signature.go | ParseSignature | func ParseSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) {
return parseSig(sigStr, curve, false)
} | go | func ParseSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) {
return parseSig(sigStr, curve, false)
} | [
"func",
"ParseSignature",
"(",
"sigStr",
"[",
"]",
"byte",
",",
"curve",
"elliptic",
".",
"Curve",
")",
"(",
"*",
"Signature",
",",
"error",
")",
"{",
"return",
"parseSig",
"(",
"sigStr",
",",
"curve",
",",
"false",
")",
"\n",
"}"
] | // ParseSignature parses a signature in BER format for the curve type `curve'
// into a Signature type, perfoming some basic sanity checks. If parsing
// according to the more strict DER format is needed, use ParseDERSignature. | [
"ParseSignature",
"parses",
"a",
"signature",
"in",
"BER",
"format",
"for",
"the",
"curve",
"type",
"curve",
"into",
"a",
"Signature",
"type",
"perfoming",
"some",
"basic",
"sanity",
"checks",
".",
"If",
"parsing",
"according",
"to",
"the",
"more",
"strict",
... | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/signature.go#L211-L213 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.