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
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
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",
"instance",
".",
"See",
"GetBlockChainInfo",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L278-L281 | train |
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",
")",
"\n",
"}"
] | // 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",
"instance",
".",
"See",
"GetBlockHash",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L316-L319 | train |
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 | train |
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",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal result as a string.",
"var",
"bhHex",
"string",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"bhHex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"serializedBH",
",",
"err",
":=",
"hex",
".",
"DecodeString",
"(",
"bhHex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Deserialize the blockheader and return it.",
"var",
"bh",
"wire",
".",
"BlockHeader",
"\n",
"err",
"=",
"bh",
".",
"Deserialize",
"(",
"bytes",
".",
"NewReader",
"(",
"serializedBH",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"bh",
",",
"err",
"\n",
"}"
] | // 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 | train |
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",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"cmd",
":=",
"btcjson",
".",
"NewGetBlockHeaderCmd",
"(",
"hash",
",",
"btcjson",
".",
"Bool",
"(",
"false",
")",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // 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",
"instance",
".",
"See",
"GetBlockHeader",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L366-L374 | train |
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",
"(",
")",
"\n",
"}"
] | // 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 | train |
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",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal result as a string.",
"var",
"bh",
"btcjson",
".",
"GetBlockHeaderVerboseResult",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"bh",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"bh",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"cmd",
":=",
"btcjson",
".",
"NewGetBlockHeaderCmd",
"(",
"hash",
",",
"btcjson",
".",
"Bool",
"(",
"true",
")",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // 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",
"returned",
"instance",
".",
"See",
"GetBlockHeader",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L411-L419 | train |
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",
"(",
"blockHash",
")",
".",
"Receive",
"(",
")",
"\n",
"}"
] | // 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 | train |
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",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal the result as an array of strings.",
"var",
"mempoolEntryResult",
"btcjson",
".",
"GetMempoolEntryResult",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"mempoolEntryResult",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"mempoolEntryResult",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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",
")",
"\n",
"}"
] | // 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",
"instance",
".",
"See",
"GetMempoolEntry",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L457-L460 | train |
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",
"(",
")",
"\n",
"}"
] | // 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 | train |
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",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal the result as an array of strings.",
"var",
"txHashStrs",
"[",
"]",
"string",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"txHashStrs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Create a slice of ShaHash arrays from the string slice.",
"txHashes",
":=",
"make",
"(",
"[",
"]",
"*",
"chainhash",
".",
"Hash",
",",
"0",
",",
"len",
"(",
"txHashStrs",
")",
")",
"\n",
"for",
"_",
",",
"hashStr",
":=",
"range",
"txHashStrs",
"{",
"txHash",
",",
"err",
":=",
"chainhash",
".",
"NewHashFromStr",
"(",
"hashStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"txHashes",
"=",
"append",
"(",
"txHashes",
",",
"txHash",
")",
"\n",
"}",
"\n\n",
"return",
"txHashes",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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",
")",
"\n",
"}"
] | // 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",
"instance",
".",
"See",
"GetRawMempool",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L505-L508 | train |
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",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal the result as a map of strings (tx shas) to their detailed",
"// results.",
"var",
"mempoolItems",
"map",
"[",
"string",
"]",
"btcjson",
".",
"GetRawMempoolVerboseResult",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"mempoolItems",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"mempoolItems",
",",
"nil",
"\n",
"}"
] | // 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",
"transactions",
"in",
"the",
"memory",
"pool",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L525-L539 | train |
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",
"(",
"cmd",
")",
"\n",
"}"
] | // 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",
"instance",
".",
"See",
"GetRawMempoolVerbose",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L546-L549 | train |
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",
"(",
")",
"\n",
"}"
] | // 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",
"GetRawMempool",
"to",
"retrieve",
"only",
"the",
"transaction",
"hashes",
"instead",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L556-L558 | train |
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",
"instance",
".",
"See",
"EstimateFee",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L587-L590 | train |
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 | train |
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\n",
"// Unmarshal the result as a boolean.",
"var",
"verified",
"bool",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"verified",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"verified",
",",
"nil",
"\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",
"the",
"original",
"call",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L605-L618 | train |
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",
"instance",
".",
"See",
"VerifyChain",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L625-L628 | train |
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",
"(",
"cmd",
")",
"\n",
"}"
] | // 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",
"instance",
".",
"See",
"VerifyChainLevel",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L643-L646 | train |
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",
"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",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L657-L659 | train |
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",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // 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",
"instance",
".",
"See",
"VerifyChainBlocks",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L666-L669 | train |
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",
"(",
")",
"\n",
"}"
] | // 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",
"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",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L682-L684 | train |
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",
"{",
"hash",
"=",
"txHash",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"cmd",
":=",
"btcjson",
".",
"NewGetTxOutCmd",
"(",
"hash",
",",
"index",
",",
"&",
"mempool",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // 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",
"instance",
".",
"See",
"GetTxOut",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L719-L727 | train |
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",
"(",
"txHash",
",",
"index",
",",
"mempool",
")",
".",
"Receive",
"(",
")",
"\n",
"}"
] | // 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 | train |
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",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"cmd",
":=",
"btcjson",
".",
"NewInvalidateBlockCmd",
"(",
"hash",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // 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",
"instance",
".",
"See",
"InvalidateBlock",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L807-L815 | train |
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 | train |
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",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal result as a string.",
"var",
"filterHex",
"string",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"filterHex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Decode the serialized cf hex to raw bytes.",
"serializedFilter",
",",
"err",
":=",
"hex",
".",
"DecodeString",
"(",
"filterHex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// 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",
"\n",
"msgCFilter",
".",
"Data",
"=",
"serializedFilter",
"\n",
"return",
"&",
"msgCFilter",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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",
"{",
"hash",
"=",
"blockHash",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"cmd",
":=",
"btcjson",
".",
"NewGetCFilterCmd",
"(",
"hash",
",",
"filterType",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // 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",
"instance",
".",
"See",
"GetCFilter",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L860-L869 | train |
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",
"(",
"blockHash",
",",
"filterType",
")",
".",
"Receive",
"(",
")",
"\n",
"}"
] | // 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 | train |
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",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal result as a string.",
"var",
"headerHex",
"string",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"headerHex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Assign the decoded header into a hash",
"headerHash",
",",
"err",
":=",
"chainhash",
".",
"NewHashFromStr",
"(",
"headerHex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Assign the hash to a headers message and return it.",
"msgCFHeaders",
":=",
"wire",
".",
"MsgCFHeaders",
"{",
"PrevFilterHeader",
":",
"*",
"headerHash",
"}",
"\n",
"return",
"&",
"msgCFHeaders",
",",
"nil",
"\n\n",
"}"
] | // 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 | train |
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",
"!=",
"nil",
"{",
"hash",
"=",
"blockHash",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"cmd",
":=",
"btcjson",
".",
"NewGetCFilterHeaderCmd",
"(",
"hash",
",",
"filterType",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // 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",
"instance",
".",
"See",
"GetCFilterHeader",
"for",
"the",
"blocking",
"version",
"and",
"more",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/chain.go#L913-L922 | train |
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",
".",
"GetCFilterHeaderAsync",
"(",
"blockHash",
",",
"filterType",
")",
".",
"Receive",
"(",
")",
"\n",
"}"
] | // 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 | train |
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",
":",
"startHeight",
",",
"StopHash",
":",
"*",
"stopHash",
",",
"}",
"\n",
"}"
] | // 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 | train |
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",
".",
"forAllOutboundPeers",
"(",
"closure",
")",
"\n",
"}"
] | // 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 | train |
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",
"(",
"nil",
")",
",",
"knownAddresses",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
",",
"quit",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"txProcessed",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
",",
"blockProcessed",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
",",
"}",
"\n",
"}"
] | // 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 | train |
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",
"exists",
"\n",
"}"
] | // 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 | train |
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",
"(",
")",
"\n",
"}"
] | // 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 | train |
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",
"return",
"isDisabled",
"\n",
"}"
] | // 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 | train |
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",
",",
"len",
"(",
"addresses",
")",
")",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"addresses",
"{",
"if",
"!",
"sp",
".",
"addressKnown",
"(",
"addr",
")",
"{",
"addrs",
"=",
"append",
"(",
"addrs",
",",
"addr",
")",
"\n",
"}",
"\n",
"}",
"\n",
"known",
",",
"err",
":=",
"sp",
".",
"PushAddrMsg",
"(",
"addrs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"peerLog",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sp",
".",
"Peer",
",",
"err",
")",
"\n",
"sp",
".",
"Disconnect",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"sp",
".",
"addKnownAddresses",
"(",
"known",
")",
"\n",
"}"
] | // 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 | train |
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",
".",
"services",
"&",
"wire",
".",
"SFNodeBloom",
"!=",
"wire",
".",
"SFNodeBloom",
"{",
"peerLog",
".",
"Debugf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"sp",
")",
"\n",
"sp",
".",
"Disconnect",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// 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",
",",
"\"",
"\"",
")",
"\n\n",
"// 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",
"\n",
"txDescs",
":=",
"txMemPool",
".",
"TxDescs",
"(",
")",
"\n",
"invMsg",
":=",
"wire",
".",
"NewMsgInvSizeHint",
"(",
"uint",
"(",
"len",
"(",
"txDescs",
")",
")",
")",
"\n\n",
"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",
"(",
")",
")",
"\n",
"invMsg",
".",
"AddInvVect",
"(",
"iv",
")",
"\n",
"if",
"len",
"(",
"invMsg",
".",
"InvList",
")",
"+",
"1",
">",
"wire",
".",
"MaxInvPerMsg",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Send the inventory message if there is anything to send.",
"if",
"len",
"(",
"invMsg",
".",
"InvList",
")",
">",
"0",
"{",
"sp",
".",
"QueueMessage",
"(",
"invMsg",
",",
"nil",
")",
"\n",
"}",
"\n",
"}"
] | // 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",
"inventory",
"allowed",
"per",
"message",
".",
"When",
"the",
"peer",
"has",
"a",
"bloom",
"filter",
"loaded",
"the",
"contents",
"are",
"filtered",
"accordingly",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L509-L551 | train |
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",
"(",
")",
",",
"sp",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// 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",
")",
"\n",
"iv",
":=",
"wire",
".",
"NewInvVect",
"(",
"wire",
".",
"InvTypeTx",
",",
"tx",
".",
"Hash",
"(",
")",
")",
"\n",
"sp",
".",
"AddKnownInventory",
"(",
"iv",
")",
"\n\n",
"// 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",
")",
"\n",
"<-",
"sp",
".",
"txProcessed",
"\n",
"}"
] | // 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",
"serialize",
"all",
"transactions",
"through",
"a",
"single",
"thread",
"transactions",
"don",
"t",
"rely",
"on",
"the",
"previous",
"one",
"in",
"a",
"linear",
"fashion",
"like",
"blocks",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L557-L578 | train |
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 methods and things such as hash caching.",
"block",
":=",
"btcutil",
".",
"NewBlockFromBlockAndBytes",
"(",
"msg",
",",
"buf",
")",
"\n\n",
"// Add the block to the known inventory for the peer.",
"iv",
":=",
"wire",
".",
"NewInvVect",
"(",
"wire",
".",
"InvTypeBlock",
",",
"block",
".",
"Hash",
"(",
")",
")",
"\n",
"sp",
".",
"AddKnownInventory",
"(",
"iv",
")",
"\n\n",
"// 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",
")",
"\n",
"<-",
"sp",
".",
"blockProcessed",
"\n",
"}"
] | // 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 | train |
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",
")",
"\n",
"}"
] | // 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 | train |
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",
":=",
"len",
"(",
"msg",
".",
"InvList",
")",
"\n",
"// 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",
",",
"\"",
"\"",
")",
"\n\n",
"// 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",
"{",
"}",
"\n",
"doneChan",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
"\n\n",
"for",
"i",
",",
"iv",
":=",
"range",
"msg",
".",
"InvList",
"{",
"var",
"c",
"chan",
"struct",
"{",
"}",
"\n",
"// If this will be the last message we send.",
"if",
"i",
"==",
"length",
"-",
"1",
"&&",
"len",
"(",
"notFound",
".",
"InvList",
")",
"==",
"0",
"{",
"c",
"=",
"doneChan",
"\n",
"}",
"else",
"if",
"(",
"i",
"+",
"1",
")",
"%",
"3",
"==",
"0",
"{",
"// Buffered so as to not make the send goroutine block.",
"c",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"switch",
"iv",
".",
"Type",
"{",
"case",
"wire",
".",
"InvTypeWitnessTx",
":",
"err",
"=",
"sp",
".",
"server",
".",
"pushTxMsg",
"(",
"sp",
",",
"&",
"iv",
".",
"Hash",
",",
"c",
",",
"waitChan",
",",
"wire",
".",
"WitnessEncoding",
")",
"\n",
"case",
"wire",
".",
"InvTypeTx",
":",
"err",
"=",
"sp",
".",
"server",
".",
"pushTxMsg",
"(",
"sp",
",",
"&",
"iv",
".",
"Hash",
",",
"c",
",",
"waitChan",
",",
"wire",
".",
"BaseEncoding",
")",
"\n",
"case",
"wire",
".",
"InvTypeWitnessBlock",
":",
"err",
"=",
"sp",
".",
"server",
".",
"pushBlockMsg",
"(",
"sp",
",",
"&",
"iv",
".",
"Hash",
",",
"c",
",",
"waitChan",
",",
"wire",
".",
"WitnessEncoding",
")",
"\n",
"case",
"wire",
".",
"InvTypeBlock",
":",
"err",
"=",
"sp",
".",
"server",
".",
"pushBlockMsg",
"(",
"sp",
",",
"&",
"iv",
".",
"Hash",
",",
"c",
",",
"waitChan",
",",
"wire",
".",
"BaseEncoding",
")",
"\n",
"case",
"wire",
".",
"InvTypeFilteredWitnessBlock",
":",
"err",
"=",
"sp",
".",
"server",
".",
"pushMerkleBlockMsg",
"(",
"sp",
",",
"&",
"iv",
".",
"Hash",
",",
"c",
",",
"waitChan",
",",
"wire",
".",
"WitnessEncoding",
")",
"\n",
"case",
"wire",
".",
"InvTypeFilteredBlock",
":",
"err",
"=",
"sp",
".",
"server",
".",
"pushMerkleBlockMsg",
"(",
"sp",
",",
"&",
"iv",
".",
"Hash",
",",
"c",
",",
"waitChan",
",",
"wire",
".",
"BaseEncoding",
")",
"\n",
"default",
":",
"peerLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"iv",
".",
"Type",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"notFound",
".",
"AddInvVect",
"(",
"iv",
")",
"\n\n",
"// 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",
"\n",
"}",
"\n",
"}",
"\n",
"numAdded",
"++",
"\n",
"waitChan",
"=",
"c",
"\n",
"}",
"\n",
"if",
"len",
"(",
"notFound",
".",
"InvList",
")",
"!=",
"0",
"{",
"sp",
".",
"QueueMessage",
"(",
"notFound",
",",
"doneChan",
")",
"\n",
"}",
"\n\n",
"// 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",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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 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",
"\n",
"hashList",
":=",
"chain",
".",
"LocateBlocks",
"(",
"msg",
".",
"BlockLocatorHashes",
",",
"&",
"msg",
".",
"HashStop",
",",
"wire",
".",
"MaxBlocksPerMsg",
")",
"\n\n",
"// Generate inventory message.",
"invMsg",
":=",
"wire",
".",
"NewMsgInv",
"(",
")",
"\n",
"for",
"i",
":=",
"range",
"hashList",
"{",
"iv",
":=",
"wire",
".",
"NewInvVect",
"(",
"wire",
".",
"InvTypeBlock",
",",
"&",
"hashList",
"[",
"i",
"]",
")",
"\n",
"invMsg",
".",
"AddInvVect",
"(",
"iv",
")",
"\n",
"}",
"\n\n",
"// Send the inventory message if there is anything to send.",
"if",
"len",
"(",
"invMsg",
".",
"InvList",
")",
">",
"0",
"{",
"invListLen",
":=",
"len",
"(",
"invMsg",
".",
"InvList",
")",
"\n",
"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",
"\n",
"sp",
".",
"continueHash",
"=",
"&",
"continueHash",
"\n",
"}",
"\n",
"sp",
".",
"QueueMessage",
"(",
"invMsg",
",",
"nil",
")",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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",
".",
"IsCurrent",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"// 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",
"\n",
"headers",
":=",
"chain",
".",
"LocateHeaders",
"(",
"msg",
".",
"BlockLocatorHashes",
",",
"&",
"msg",
".",
"HashStop",
")",
"\n\n",
"// Send found headers to the requesting peer.",
"blockHeaders",
":=",
"make",
"(",
"[",
"]",
"*",
"wire",
".",
"BlockHeader",
",",
"len",
"(",
"headers",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"headers",
"{",
"blockHeaders",
"[",
"i",
"]",
"=",
"&",
"headers",
"[",
"i",
"]",
"\n",
"}",
"\n",
"sp",
".",
"QueueMessage",
"(",
"&",
"wire",
".",
"MsgHeaders",
"{",
"Headers",
":",
"blockHeaders",
"}",
",",
"nil",
")",
"\n",
"}"
] | // 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 | train |
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",
".",
"IsCurrent",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"// 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",
"\n\n",
"default",
":",
"peerLog",
".",
"Debug",
"(",
"\"",
"\"",
",",
"msg",
".",
"FilterType",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"hashes",
",",
"err",
":=",
"sp",
".",
"server",
".",
"chain",
".",
"HeightToHashRange",
"(",
"int32",
"(",
"msg",
".",
"StartHeight",
")",
",",
"&",
"msg",
".",
"StopHash",
",",
"wire",
".",
"MaxGetCFiltersReqRange",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"peerLog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Create []*chainhash.Hash from []chainhash.Hash to pass to",
"// FiltersByBlockHashes.",
"hashPtrs",
":=",
"make",
"(",
"[",
"]",
"*",
"chainhash",
".",
"Hash",
",",
"len",
"(",
"hashes",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"hashes",
"{",
"hashPtrs",
"[",
"i",
"]",
"=",
"&",
"hashes",
"[",
"i",
"]",
"\n",
"}",
"\n\n",
"filters",
",",
"err",
":=",
"sp",
".",
"server",
".",
"cfIndex",
".",
"FiltersByBlockHashes",
"(",
"hashPtrs",
",",
"msg",
".",
"FilterType",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"peerLog",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"filterBytes",
":=",
"range",
"filters",
"{",
"if",
"len",
"(",
"filterBytes",
")",
"==",
"0",
"{",
"peerLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"hashes",
"[",
"i",
"]",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"filterMsg",
":=",
"wire",
".",
"NewMsgCFilter",
"(",
"msg",
".",
"FilterType",
",",
"&",
"hashes",
"[",
"i",
"]",
",",
"filterBytes",
",",
")",
"\n",
"sp",
".",
"QueueMessage",
"(",
"filterMsg",
",",
"nil",
")",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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",
".",
"IsCurrent",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"// 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",
"\n\n",
"default",
":",
"peerLog",
".",
"Debug",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"msg",
".",
"FilterType",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"startHeight",
":=",
"int32",
"(",
"msg",
".",
"StartHeight",
")",
"\n",
"maxResults",
":=",
"wire",
".",
"MaxCFHeadersPerMsg",
"\n\n",
"// If StartHeight is positive, fetch the predecessor block hash so we",
"// can populate the PrevFilterHeader field.",
"if",
"msg",
".",
"StartHeight",
">",
"0",
"{",
"startHeight",
"--",
"\n",
"maxResults",
"++",
"\n",
"}",
"\n\n",
"// Fetch the hashes from the block index.",
"hashList",
",",
"err",
":=",
"sp",
".",
"server",
".",
"chain",
".",
"HeightToHashRange",
"(",
"startHeight",
",",
"&",
"msg",
".",
"StopHash",
",",
"maxResults",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"peerLog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// 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",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Create []*chainhash.Hash from []chainhash.Hash to pass to",
"// FilterHeadersByBlockHashes.",
"hashPtrs",
":=",
"make",
"(",
"[",
"]",
"*",
"chainhash",
".",
"Hash",
",",
"len",
"(",
"hashList",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"hashList",
"{",
"hashPtrs",
"[",
"i",
"]",
"=",
"&",
"hashList",
"[",
"i",
"]",
"\n",
"}",
"\n\n",
"// Fetch the raw filter hash bytes from the database for all blocks.",
"filterHashes",
",",
"err",
":=",
"sp",
".",
"server",
".",
"cfIndex",
".",
"FilterHashesByBlockHashes",
"(",
"hashPtrs",
",",
"msg",
".",
"FilterType",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"peerLog",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Generate cfheaders message and send it.",
"headersMsg",
":=",
"wire",
".",
"NewMsgCFHeaders",
"(",
")",
"\n\n",
"// Populate the PrevFilterHeader field.",
"if",
"msg",
".",
"StartHeight",
">",
"0",
"{",
"prevBlockHash",
":=",
"&",
"hashList",
"[",
"0",
"]",
"\n\n",
"// Fetch the raw committed filter header bytes from the",
"// database.",
"headerBytes",
",",
"err",
":=",
"sp",
".",
"server",
".",
"cfIndex",
".",
"FilterHeaderByBlockHash",
"(",
"prevBlockHash",
",",
"msg",
".",
"FilterType",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"peerLog",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"len",
"(",
"headerBytes",
")",
"==",
"0",
"{",
"peerLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"prevBlockHash",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Deserialize the hash into PrevFilterHeader.",
"err",
"=",
"headersMsg",
".",
"PrevFilterHeader",
".",
"SetBytes",
"(",
"headerBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"peerLog",
".",
"Warnf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"hashList",
"=",
"hashList",
"[",
"1",
":",
"]",
"\n",
"filterHashes",
"=",
"filterHashes",
"[",
"1",
":",
"]",
"\n",
"}",
"\n\n",
"// Populate HeaderHashes.",
"for",
"i",
",",
"hashBytes",
":=",
"range",
"filterHashes",
"{",
"if",
"len",
"(",
"hashBytes",
")",
"==",
"0",
"{",
"peerLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"hashList",
"[",
"i",
"]",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Deserialize the hash.",
"filterHash",
",",
"err",
":=",
"chainhash",
".",
"NewHash",
"(",
"hashBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"peerLog",
".",
"Warnf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"headersMsg",
".",
"AddCFHash",
"(",
"filterHash",
")",
"\n",
"}",
"\n\n",
"headersMsg",
".",
"FilterType",
"=",
"msg",
".",
"FilterType",
"\n",
"headersMsg",
".",
"StopHash",
"=",
"msg",
".",
"StopHash",
"\n\n",
"sp",
".",
"QueueMessage",
"(",
"headersMsg",
",",
"nil",
")",
"\n",
"}"
] | // 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 | train |
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 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",
")",
"\n",
"sp",
".",
"Disconnect",
"(",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"// Disconnect the peer regardless of protocol version or banning",
"// state.",
"peerLog",
".",
"Debugf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"sp",
",",
"cmd",
")",
"\n",
"sp",
".",
"Disconnect",
"(",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}"
] | // 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",
"enough",
"to",
"observe",
"the",
"bloom",
"filter",
"service",
"support",
"bit",
"it",
"will",
"be",
"banned",
"since",
"it",
"is",
"intentionally",
"violating",
"the",
"protocol",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1125-L1154 | train |
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",
".",
"MinFee",
">",
"btcutil",
".",
"MaxSatoshi",
"{",
"peerLog",
".",
"Debugf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"sp",
",",
"btcutil",
".",
"Amount",
"(",
"msg",
".",
"MinFee",
")",
")",
"\n",
"sp",
".",
"Disconnect",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"atomic",
".",
"StoreInt64",
"(",
"&",
"sp",
".",
"feeFilter",
",",
"msg",
".",
"MinFee",
")",
"\n",
"}"
] | // 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",
"provided",
"value",
"are",
"inventoried",
"to",
"them",
".",
"The",
"peer",
"will",
"be",
"disconnected",
"if",
"an",
"invalid",
"fee",
"filter",
"value",
"is",
"provided",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1160-L1170 | train |
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",
"!",
"sp",
".",
"enforceNodeBloomFlag",
"(",
"msg",
".",
"Command",
"(",
")",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"!",
"sp",
".",
"filter",
".",
"IsLoaded",
"(",
")",
"{",
"peerLog",
".",
"Debugf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"sp",
")",
"\n",
"sp",
".",
"Disconnect",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"sp",
".",
"filter",
".",
"Add",
"(",
"msg",
".",
"Data",
")",
"\n",
"}"
] | // 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",
"disconnected",
"if",
"a",
"filter",
"is",
"not",
"loaded",
"when",
"this",
"message",
"is",
"received",
"or",
"the",
"server",
"is",
"not",
"configured",
"to",
"allow",
"bloom",
"filters",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1176-L1191 | train |
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",
"!",
"sp",
".",
"enforceNodeBloomFlag",
"(",
"msg",
".",
"Command",
"(",
")",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"!",
"sp",
".",
"filter",
".",
"IsLoaded",
"(",
")",
"{",
"peerLog",
".",
"Debugf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"sp",
")",
"\n",
"sp",
".",
"Disconnect",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"sp",
".",
"filter",
".",
"Unload",
"(",
")",
"\n",
"}"
] | // 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",
"disconnected",
"if",
"a",
"filter",
"is",
"not",
"loaded",
"when",
"this",
"message",
"is",
"received",
"or",
"the",
"server",
"is",
"not",
"configured",
"to",
"allow",
"bloom",
"filters",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1197-L1212 | train |
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",
"!",
"sp",
".",
"enforceNodeBloomFlag",
"(",
"msg",
".",
"Command",
"(",
")",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"sp",
".",
"setDisableRelayTx",
"(",
"false",
")",
"\n\n",
"sp",
".",
"filter",
".",
"Reload",
"(",
"msg",
")",
"\n",
"}"
] | // 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",
"transactions",
"that",
"match",
"the",
"filter",
".",
"The",
"peer",
"will",
"be",
"disconnected",
"if",
"the",
"server",
"is",
"not",
"configured",
"to",
"allow",
"bloom",
"filters",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1219-L1229 | train |
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 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",
"\n",
"}",
"\n\n",
"// Do not accept getaddr requests from outbound peers. This reduces",
"// fingerprinting attacks.",
"if",
"!",
"sp",
".",
"Inbound",
"(",
")",
"{",
"peerLog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"sp",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Only allow one getaddr request per connection to discourage",
"// address stamping of inv announcements.",
"if",
"sp",
".",
"sentAddrs",
"{",
"peerLog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"sp",
")",
"\n",
"return",
"\n",
"}",
"\n",
"sp",
".",
"sentAddrs",
"=",
"true",
"\n\n",
"// Get the current known addresses from the address manager.",
"addrCache",
":=",
"sp",
".",
"server",
".",
"addrManager",
".",
"AddressCache",
"(",
")",
"\n\n",
"// Push the addresses.",
"sp",
".",
"pushAddrMsg",
"(",
"addrCache",
")",
"\n",
"}"
] | // 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 | train |
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",
"(",
"bytesWritten",
")",
")",
"\n",
"}"
] | // 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 | train |
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",
"// modulus.",
"var",
"randomNumber",
"uint16",
"\n",
"var",
"limitRange",
"=",
"(",
"math",
".",
"MaxUint16",
"/",
"max",
")",
"*",
"max",
"\n",
"for",
"{",
"binary",
".",
"Read",
"(",
"rand",
".",
"Reader",
",",
"binary",
".",
"LittleEndian",
",",
"&",
"randomNumber",
")",
"\n",
"if",
"randomNumber",
"<",
"limitRange",
"{",
"return",
"(",
"randomNumber",
"%",
"max",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // 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",
"to",
"1800",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1332-L1345 | train |
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",
")",
"!=",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"s",
".",
"modifyRebroadcastInv",
"<-",
"broadcastInventoryAdd",
"{",
"invVect",
":",
"iv",
",",
"data",
":",
"data",
"}",
"\n",
"}"
] | // 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 | train |
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",
"}",
"\n\n",
"s",
".",
"modifyRebroadcastInv",
"<-",
"broadcastInventoryDel",
"(",
"iv",
")",
"\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 | train |
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",
",",
"txD",
".",
"Tx",
".",
"Hash",
"(",
")",
")",
"\n",
"s",
".",
"RelayInventory",
"(",
"iv",
",",
"txD",
")",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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",
")",
"\n\n",
"// Notify both websocket and getblocktemplate long poll clients of all",
"// newly accepted transactions.",
"if",
"s",
".",
"rpcServer",
"!=",
"nil",
"{",
"s",
".",
"rpcServer",
".",
"NotifyNewTransactions",
"(",
"txns",
")",
"\n",
"}",
"\n",
"}"
] | // 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",
"whenever",
"new",
"transactions",
"are",
"added",
"to",
"the",
"mempool",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1382-L1392 | train |
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",
":=",
"wire",
".",
"NewInvVect",
"(",
"wire",
".",
"InvTypeTx",
",",
"tx",
".",
"Hash",
"(",
")",
")",
"\n",
"s",
".",
"RemoveRebroadcastInventory",
"(",
"iv",
")",
"\n",
"}"
] | // 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 | train |
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",
".",
"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",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"peerLog",
".",
"Tracef",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"hash",
",",
"err",
")",
"\n\n",
"if",
"doneChan",
"!=",
"nil",
"{",
"doneChan",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Once we have fetched data wait for any previous operation to finish.",
"if",
"waitChan",
"!=",
"nil",
"{",
"<-",
"waitChan",
"\n",
"}",
"\n\n",
"sp",
".",
"QueueMessageWithEncoding",
"(",
"tx",
".",
"MsgTx",
"(",
")",
",",
"doneChan",
",",
"encoding",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // 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 | train |
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",
"wire",
".",
"MessageEncoding",
")",
"error",
"{",
"// Fetch the raw block bytes from the database.",
"var",
"blockBytes",
"[",
"]",
"byte",
"\n",
"err",
":=",
"sp",
".",
"server",
".",
"db",
".",
"View",
"(",
"func",
"(",
"dbTx",
"database",
".",
"Tx",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"blockBytes",
",",
"err",
"=",
"dbTx",
".",
"FetchBlock",
"(",
"hash",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"peerLog",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"hash",
",",
"err",
")",
"\n\n",
"if",
"doneChan",
"!=",
"nil",
"{",
"doneChan",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Deserialize the block.",
"var",
"msgBlock",
"wire",
".",
"MsgBlock",
"\n",
"err",
"=",
"msgBlock",
".",
"Deserialize",
"(",
"bytes",
".",
"NewReader",
"(",
"blockBytes",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"peerLog",
".",
"Tracef",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"hash",
",",
"err",
")",
"\n\n",
"if",
"doneChan",
"!=",
"nil",
"{",
"doneChan",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Once we have fetched data wait for any previous operation to finish.",
"if",
"waitChan",
"!=",
"nil",
"{",
"<-",
"waitChan",
"\n",
"}",
"\n\n",
"// We only send the channel for this message if we aren't sending",
"// an inv straight after.",
"var",
"dc",
"chan",
"<-",
"struct",
"{",
"}",
"\n",
"continueHash",
":=",
"sp",
".",
"continueHash",
"\n",
"sendInv",
":=",
"continueHash",
"!=",
"nil",
"&&",
"continueHash",
".",
"IsEqual",
"(",
"hash",
")",
"\n",
"if",
"!",
"sendInv",
"{",
"dc",
"=",
"doneChan",
"\n",
"}",
"\n",
"sp",
".",
"QueueMessageWithEncoding",
"(",
"&",
"msgBlock",
",",
"dc",
",",
"encoding",
")",
"\n\n",
"// 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",
"(",
")",
"\n",
"invMsg",
":=",
"wire",
".",
"NewMsgInvSizeHint",
"(",
"1",
")",
"\n",
"iv",
":=",
"wire",
".",
"NewInvVect",
"(",
"wire",
".",
"InvTypeBlock",
",",
"&",
"best",
".",
"Hash",
")",
"\n",
"invMsg",
".",
"AddInvVect",
"(",
"iv",
")",
"\n",
"sp",
".",
"QueueMessage",
"(",
"invMsg",
",",
"doneChan",
")",
"\n",
"sp",
".",
"continueHash",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // 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 | train |
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",
"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",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Fetch the raw block bytes from the database.",
"blk",
",",
"err",
":=",
"sp",
".",
"server",
".",
"chain",
".",
"BlockByHash",
"(",
"hash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"peerLog",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"hash",
",",
"err",
")",
"\n\n",
"if",
"doneChan",
"!=",
"nil",
"{",
"doneChan",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Generate a merkle block by filtering the requested block according",
"// to the filter for the peer.",
"merkle",
",",
"matchedTxIndices",
":=",
"bloom",
".",
"NewMerkleBlock",
"(",
"blk",
",",
"sp",
".",
"filter",
")",
"\n\n",
"// Once we have fetched data wait for any previous operation to finish.",
"if",
"waitChan",
"!=",
"nil",
"{",
"<-",
"waitChan",
"\n",
"}",
"\n\n",
"// Send the merkleblock. Only send the done channel with this message",
"// if no transactions will be sent afterwards.",
"var",
"dc",
"chan",
"<-",
"struct",
"{",
"}",
"\n",
"if",
"len",
"(",
"matchedTxIndices",
")",
"==",
"0",
"{",
"dc",
"=",
"doneChan",
"\n",
"}",
"\n",
"sp",
".",
"QueueMessage",
"(",
"merkle",
",",
"dc",
")",
"\n\n",
"// Finally, send any matched transactions.",
"blkTransactions",
":=",
"blk",
".",
"MsgBlock",
"(",
")",
".",
"Transactions",
"\n",
"for",
"i",
",",
"txIndex",
":=",
"range",
"matchedTxIndices",
"{",
"// Only send the done channel on the final transaction.",
"var",
"dc",
"chan",
"<-",
"struct",
"{",
"}",
"\n",
"if",
"i",
"==",
"len",
"(",
"matchedTxIndices",
")",
"-",
"1",
"{",
"dc",
"=",
"doneChan",
"\n",
"}",
"\n",
"if",
"txIndex",
"<",
"uint32",
"(",
"len",
"(",
"blkTransactions",
")",
")",
"{",
"sp",
".",
"QueueMessageWithEncoding",
"(",
"blkTransactions",
"[",
"txIndex",
"]",
",",
"dc",
",",
"encoding",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // 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",
"will",
"simply",
"be",
"ignored",
"if",
"there",
"is",
"no",
"filter",
"loaded",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"block",
"hash",
"is",
"not",
"known",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L1505-L1560 | train |
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",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"// 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",
")",
"\n",
"if",
"!",
"ok",
"{",
"peerLog",
".",
"Warnf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"msgHeaders",
":=",
"wire",
".",
"NewMsgHeaders",
"(",
")",
"\n",
"if",
"err",
":=",
"msgHeaders",
".",
"AddBlockHeader",
"(",
"&",
"blockHeader",
")",
";",
"err",
"!=",
"nil",
"{",
"peerLog",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"sp",
".",
"QueueMessage",
"(",
"msgHeaders",
",",
"nil",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"msg",
".",
"invVect",
".",
"Type",
"==",
"wire",
".",
"InvTypeTx",
"{",
"// Don't relay the transaction to the peer when it has",
"// transaction relaying disabled.",
"if",
"sp",
".",
"relayTxDisabled",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"txD",
",",
"ok",
":=",
"msg",
".",
"data",
".",
"(",
"*",
"mempool",
".",
"TxDesc",
")",
"\n",
"if",
"!",
"ok",
"{",
"peerLog",
".",
"Warnf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"msg",
".",
"data",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Don't relay the transaction if the transaction fee-per-kb",
"// is less than the peer's feefilter.",
"feeFilter",
":=",
"atomic",
".",
"LoadInt64",
"(",
"&",
"sp",
".",
"feeFilter",
")",
"\n",
"if",
"feeFilter",
">",
"0",
"&&",
"txD",
".",
"FeePerKB",
"<",
"feeFilter",
"{",
"return",
"\n",
"}",
"\n\n",
"// 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",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// 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",
")",
"\n",
"}",
")",
"\n",
"}"
] | // 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 | train |
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",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"ep",
":=",
"range",
"bmsg",
".",
"excludePeers",
"{",
"if",
"sp",
"==",
"ep",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"sp",
".",
"QueueMessage",
"(",
"bmsg",
".",
"message",
",",
"nil",
")",
"\n",
"}",
")",
"\n",
"}"
] | // 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 | train |
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",
":",
"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",
",",
"}",
"\n",
"}"
] | // 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 | train |
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",
"(",
")",
")",
"\n",
"sp",
".",
"Peer",
"=",
"peer",
".",
"NewInboundPeer",
"(",
"newPeerConfig",
"(",
"sp",
")",
")",
"\n",
"sp",
".",
"AssociateConnection",
"(",
"conn",
")",
"\n",
"go",
"s",
".",
"peerDoneHandler",
"(",
"sp",
")",
"\n",
"}"
] | // 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",
"connection",
"and",
"starts",
"a",
"goroutine",
"to",
"wait",
"for",
"disconnection",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L2010-L2016 | train |
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",
"}",
"\n",
"}"
] | // 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 | train |
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.",
"bmsg",
":=",
"broadcastMsg",
"{",
"message",
":",
"msg",
",",
"excludePeers",
":",
"exclPeers",
"}",
"\n",
"s",
".",
"broadcast",
"<-",
"bmsg",
"\n",
"}"
] | // 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 | train |
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",
"[",
"wire",
".",
"InvVect",
"]",
"interface",
"{",
"}",
")",
"\n\n",
"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",
"\n\n",
"// 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",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"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",
"\n",
"s",
".",
"RelayInventory",
"(",
"&",
"ivCopy",
",",
"data",
")",
"\n",
"}",
"\n\n",
"// Process at a random time up to 30mins (in seconds)",
"// in the future.",
"timer",
".",
"Reset",
"(",
"time",
".",
"Second",
"*",
"time",
".",
"Duration",
"(",
"randomUint16Number",
"(",
"1800",
")",
")",
")",
"\n\n",
"case",
"<-",
"s",
".",
"quit",
":",
"break",
"out",
"\n",
"}",
"\n",
"}",
"\n\n",
"timer",
".",
"Stop",
"(",
")",
"\n\n",
"// Drain channels before exiting so nothing is left waiting around",
"// to send.",
"cleanup",
":",
"for",
"{",
"select",
"{",
"case",
"<-",
"s",
".",
"modifyRebroadcastInv",
":",
"default",
":",
"break",
"cleanup",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"}"
] | // 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",
"peers",
"restarted",
"or",
"otherwise",
"lost",
"track",
"of",
"them",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L2235-L2288 | train |
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",
"(",
"\"",
"\"",
")",
"\n\n",
"// Server startup time. Used for the uptime command for uptime calculation.",
"s",
".",
"startupTime",
"=",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
"\n\n",
"// Start the peer handler which in turn starts the address and block",
"// managers.",
"s",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"s",
".",
"peerHandler",
"(",
")",
"\n\n",
"if",
"s",
".",
"nat",
"!=",
"nil",
"{",
"s",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"s",
".",
"upnpUpdateThread",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"cfg",
".",
"DisableRPC",
"{",
"s",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n\n",
"// Start the rebroadcastHandler, which ensures user tx received by",
"// the RPC server are rebroadcast until being included in a block.",
"go",
"s",
".",
"rebroadcastHandler",
"(",
")",
"\n\n",
"s",
".",
"rpcServer",
".",
"Start",
"(",
")",
"\n",
"}",
"\n\n",
"// Start the CPU miner if generation is enabled.",
"if",
"cfg",
".",
"Generate",
"{",
"s",
".",
"cpuMiner",
".",
"Start",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Start begins accepting connections from peers. | [
"Start",
"begins",
"accepting",
"connections",
"from",
"peers",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L2291-L2326 | train |
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",
"{",
"return",
"\n",
"}",
"\n",
"srvrLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"duration",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"remaining",
":=",
"duration",
"\n",
"tickDuration",
":=",
"dynamicTickDuration",
"(",
"remaining",
")",
"\n",
"done",
":=",
"time",
".",
"After",
"(",
"remaining",
")",
"\n",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"tickDuration",
")",
"\n",
"out",
":",
"for",
"{",
"select",
"{",
"case",
"<-",
"done",
":",
"ticker",
".",
"Stop",
"(",
")",
"\n",
"s",
".",
"Stop",
"(",
")",
"\n",
"break",
"out",
"\n",
"case",
"<-",
"ticker",
".",
"C",
":",
"remaining",
"=",
"remaining",
"-",
"tickDuration",
"\n",
"if",
"remaining",
"<",
"time",
".",
"Second",
"{",
"continue",
"\n",
"}",
"\n\n",
"// Change tick duration dynamically based on remaining time.",
"newDuration",
":=",
"dynamicTickDuration",
"(",
"remaining",
")",
"\n",
"if",
"tickDuration",
"!=",
"newDuration",
"{",
"tickDuration",
"=",
"newDuration",
"\n",
"ticker",
".",
"Stop",
"(",
")",
"\n",
"ticker",
"=",
"time",
".",
"NewTicker",
"(",
"tickDuration",
")",
"\n",
"}",
"\n",
"srvrLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"remaining",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}"
] | // 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 | train |
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",
")",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"addrs",
"{",
"host",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Shouldn't happen due to already being normalized.",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Empty host or host of * on plan9 is both IPv4 and IPv6.",
"if",
"host",
"==",
"\"",
"\"",
"||",
"(",
"host",
"==",
"\"",
"\"",
"&&",
"runtime",
".",
"GOOS",
"==",
"\"",
"\"",
")",
"{",
"netAddrs",
"=",
"append",
"(",
"netAddrs",
",",
"simpleAddr",
"{",
"net",
":",
"\"",
"\"",
",",
"addr",
":",
"addr",
"}",
")",
"\n",
"netAddrs",
"=",
"append",
"(",
"netAddrs",
",",
"simpleAddr",
"{",
"net",
":",
"\"",
"\"",
",",
"addr",
":",
"addr",
"}",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// Strip IPv6 zone id if present since net.ParseIP does not",
"// handle it.",
"zoneIndex",
":=",
"strings",
".",
"LastIndex",
"(",
"host",
",",
"\"",
"\"",
")",
"\n",
"if",
"zoneIndex",
">",
"0",
"{",
"host",
"=",
"host",
"[",
":",
"zoneIndex",
"]",
"\n",
"}",
"\n\n",
"// Parse the IP.",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"host",
")",
"\n",
"if",
"ip",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"host",
")",
"\n",
"}",
"\n\n",
"// 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",
":",
"\"",
"\"",
",",
"addr",
":",
"addr",
"}",
")",
"\n",
"}",
"else",
"{",
"netAddrs",
"=",
"append",
"(",
"netAddrs",
",",
"simpleAddr",
"{",
"net",
":",
"\"",
"\"",
",",
"addr",
":",
"addr",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"netAddrs",
",",
"nil",
"\n",
"}"
] | // 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",
"addresses",
"which",
"apply",
"to",
"all",
"interfaces",
"and",
"adds",
"the",
"address",
"as",
"both",
"IPv4",
"and",
"IPv6",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L2409-L2447 | train |
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 file if both don't already",
"// exist.",
"if",
"!",
"fileExists",
"(",
"cfg",
".",
"RPCKey",
")",
"&&",
"!",
"fileExists",
"(",
"cfg",
".",
"RPCCert",
")",
"{",
"err",
":=",
"genCertPair",
"(",
"cfg",
".",
"RPCCert",
",",
"cfg",
".",
"RPCKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"keypair",
",",
"err",
":=",
"tls",
".",
"LoadX509KeyPair",
"(",
"cfg",
".",
"RPCCert",
",",
"cfg",
".",
"RPCKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"tlsConfig",
":=",
"tls",
".",
"Config",
"{",
"Certificates",
":",
"[",
"]",
"tls",
".",
"Certificate",
"{",
"keypair",
"}",
",",
"MinVersion",
":",
"tls",
".",
"VersionTLS12",
",",
"}",
"\n\n",
"// 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",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"netAddrs",
",",
"err",
":=",
"parseListeners",
"(",
"cfg",
".",
"RPCListeners",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"listeners",
":=",
"make",
"(",
"[",
"]",
"net",
".",
"Listener",
",",
"0",
",",
"len",
"(",
"netAddrs",
")",
")",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"netAddrs",
"{",
"listener",
",",
"err",
":=",
"listenFunc",
"(",
"addr",
".",
"Network",
"(",
")",
",",
"addr",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"rpcsLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"addr",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"listeners",
"=",
"append",
"(",
"listeners",
",",
"listener",
")",
"\n",
"}",
"\n\n",
"return",
"listeners",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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 TCP connections at the configured addresses",
"netAddrs",
",",
"err",
":=",
"parseListeners",
"(",
"listenAddrs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"listeners",
":=",
"make",
"(",
"[",
"]",
"net",
".",
"Listener",
",",
"0",
",",
"len",
"(",
"netAddrs",
")",
")",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"netAddrs",
"{",
"listener",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"addr",
".",
"Network",
"(",
")",
",",
"addr",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"srvrLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"addr",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"listeners",
"=",
"append",
"(",
"listeners",
",",
"listener",
")",
"\n",
"}",
"\n\n",
"var",
"nat",
"NAT",
"\n",
"if",
"len",
"(",
"cfg",
".",
"ExternalIPs",
")",
"!=",
"0",
"{",
"defaultPort",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"activeNetParams",
".",
"DefaultPort",
",",
"10",
",",
"16",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"srvrLog",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"activeNetParams",
".",
"DefaultPort",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"sip",
":=",
"range",
"cfg",
".",
"ExternalIPs",
"{",
"eport",
":=",
"uint16",
"(",
"defaultPort",
")",
"\n",
"host",
",",
"portstr",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"sip",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// no port, use default.",
"host",
"=",
"sip",
"\n",
"}",
"else",
"{",
"port",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"portstr",
",",
"10",
",",
"16",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"srvrLog",
".",
"Warnf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"sip",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"eport",
"=",
"uint16",
"(",
"port",
")",
"\n",
"}",
"\n",
"na",
",",
"err",
":=",
"amgr",
".",
"HostToNetAddress",
"(",
"host",
",",
"eport",
",",
"services",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"srvrLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"sip",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"err",
"=",
"amgr",
".",
"AddLocalAddress",
"(",
"na",
",",
"addrmgr",
".",
"ManualPrio",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"amgrLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"cfg",
".",
"Upnp",
"{",
"var",
"err",
"error",
"\n",
"nat",
",",
"err",
"=",
"Discover",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"srvrLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"// nil nat here is fine, just means no upnp on network.",
"}",
"\n\n",
"// Add bound addresses to address manager to be advertised to peers.",
"for",
"_",
",",
"listener",
":=",
"range",
"listeners",
"{",
"addr",
":=",
"listener",
".",
"Addr",
"(",
")",
".",
"String",
"(",
")",
"\n",
"err",
":=",
"addLocalAddress",
"(",
"amgr",
",",
"addr",
",",
"services",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"amgrLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"addr",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"listeners",
",",
"nat",
",",
"nil",
"\n",
"}"
] | // 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",
"UPnP",
"is",
"in",
"use",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L2893-L2966 | train |
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",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"port",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"portStr",
",",
"10",
",",
"16",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"host",
")",
";",
"ip",
"!=",
"nil",
"&&",
"ip",
".",
"IsUnspecified",
"(",
")",
"{",
"// If bound to unspecified address, advertise all local interfaces",
"addrs",
",",
"err",
":=",
"net",
".",
"InterfaceAddrs",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"addr",
":=",
"range",
"addrs",
"{",
"ifaceIP",
",",
"_",
",",
"err",
":=",
"net",
".",
"ParseCIDR",
"(",
"addr",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"// 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",
"\n",
"}",
"\n\n",
"netAddr",
":=",
"wire",
".",
"NewNetAddressIPPort",
"(",
"ifaceIP",
",",
"uint16",
"(",
"port",
")",
",",
"services",
")",
"\n",
"addrMgr",
".",
"AddLocalAddress",
"(",
"netAddr",
",",
"addrmgr",
".",
"BoundPrio",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"netAddr",
",",
"err",
":=",
"addrMgr",
".",
"HostToNetAddress",
"(",
"host",
",",
"uint16",
"(",
"port",
")",
",",
"services",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"addrMgr",
".",
"AddLocalAddress",
"(",
"netAddr",
",",
"addrmgr",
".",
"BoundPrio",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // 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 | train |
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",
"<=",
"time",
".",
"Second",
"*",
"15",
":",
"return",
"time",
".",
"Second",
"*",
"5",
"\n",
"case",
"remaining",
"<=",
"time",
".",
"Minute",
":",
"return",
"time",
".",
"Second",
"*",
"15",
"\n",
"case",
"remaining",
"<=",
"time",
".",
"Minute",
"*",
"5",
":",
"return",
"time",
".",
"Minute",
"\n",
"case",
"remaining",
"<=",
"time",
".",
"Minute",
"*",
"15",
":",
"return",
"time",
".",
"Minute",
"*",
"5",
"\n",
"case",
"remaining",
"<=",
"time",
".",
"Hour",
":",
"return",
"time",
".",
"Minute",
"*",
"15",
"\n",
"}",
"\n",
"return",
"time",
".",
"Hour",
"\n",
"}"
] | // 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",
"warnings",
"more",
"frequent",
"as",
"the",
"shutdown",
"time",
"approaches",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L3066-L3082 | train |
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",
"(",
"addr",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"srvrLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"addr",
",",
"err",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"host",
")",
"\n",
"if",
"ip",
"==",
"nil",
"{",
"srvrLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"ipnet",
":=",
"range",
"cfg",
".",
"whitelists",
"{",
"if",
"ipnet",
".",
"Contains",
"(",
"ip",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // 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 | train |
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 | train |
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 | train |
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-specified checkpoint.",
"extra",
":=",
"make",
"(",
"map",
"[",
"int32",
"]",
"chaincfg",
".",
"Checkpoint",
")",
"\n",
"for",
"_",
",",
"checkpoint",
":=",
"range",
"additional",
"{",
"extra",
"[",
"checkpoint",
".",
"Height",
"]",
"=",
"checkpoint",
"\n",
"}",
"\n\n",
"// Add all default checkpoints that do not have an override in the",
"// additional checkpoints.",
"numDefault",
":=",
"len",
"(",
"defaultCheckpoints",
")",
"\n",
"checkpoints",
":=",
"make",
"(",
"[",
"]",
"chaincfg",
".",
"Checkpoint",
",",
"0",
",",
"numDefault",
"+",
"len",
"(",
"extra",
")",
")",
"\n",
"for",
"_",
",",
"checkpoint",
":=",
"range",
"defaultCheckpoints",
"{",
"if",
"_",
",",
"exists",
":=",
"extra",
"[",
"checkpoint",
".",
"Height",
"]",
";",
"!",
"exists",
"{",
"checkpoints",
"=",
"append",
"(",
"checkpoints",
",",
"checkpoint",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Append the additional checkpoints and return the sorted results.",
"for",
"_",
",",
"checkpoint",
":=",
"range",
"extra",
"{",
"checkpoints",
"=",
"append",
"(",
"checkpoints",
",",
"checkpoint",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"checkpointSorter",
"(",
"checkpoints",
")",
")",
"\n",
"return",
"checkpoints",
"\n",
"}"
] | // 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",
"checkpoint",
"with",
"the",
"same",
"height",
"as",
"a",
"checkpoint",
"in",
"the",
"default",
"checkpoints",
"the",
"additional",
"checkpoint",
"will",
"take",
"precedence",
"and",
"overwrite",
"the",
"default",
"one",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/server.go#L3137-L3161 | train |
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",
".",
"PrivateKey",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"parsedScript",
",",
"err",
":=",
"parseScript",
"(",
"subScript",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"hash",
",",
"err",
":=",
"calcWitnessSignatureHash",
"(",
"parsedScript",
",",
"sigHashes",
",",
"hashType",
",",
"tx",
",",
"idx",
",",
"amt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"signature",
",",
"err",
":=",
"key",
".",
"Sign",
"(",
"hash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"append",
"(",
"signature",
".",
"Serialize",
"(",
")",
",",
"byte",
"(",
"hashType",
")",
")",
",",
"nil",
"\n",
"}"
] | // 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",
"RawTxInSignature",
"however",
"the",
"signature",
"generated",
"signs",
"a",
"new",
"sighash",
"digest",
"defined",
"in",
"BIP0143",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/sign.go#L21-L42 | train |
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",
".",
"PrivateKey",
",",
"compress",
"bool",
")",
"(",
"wire",
".",
"TxWitness",
",",
"error",
")",
"{",
"sig",
",",
"err",
":=",
"RawTxInWitnessSignature",
"(",
"tx",
",",
"sigHashes",
",",
"idx",
",",
"amt",
",",
"subscript",
",",
"hashType",
",",
"privKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"pk",
":=",
"(",
"*",
"btcec",
".",
"PublicKey",
")",
"(",
"&",
"privKey",
".",
"PublicKey",
")",
"\n",
"var",
"pkData",
"[",
"]",
"byte",
"\n",
"if",
"compress",
"{",
"pkData",
"=",
"pk",
".",
"SerializeCompressed",
"(",
")",
"\n",
"}",
"else",
"{",
"pkData",
"=",
"pk",
".",
"SerializeUncompressed",
"(",
")",
"\n",
"}",
"\n\n",
"// 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",
"\n",
"}"
] | // 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",
"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",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/sign.go#L49-L70 | train |
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",
")",
"{",
"hash",
",",
"err",
":=",
"CalcSignatureHash",
"(",
"subScript",
",",
"hashType",
",",
"tx",
",",
"idx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"signature",
",",
"err",
":=",
"key",
".",
"Sign",
"(",
"hash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"append",
"(",
"signature",
".",
"Serialize",
"(",
")",
",",
"byte",
"(",
"hashType",
")",
")",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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",
",",
"error",
")",
"{",
"sig",
",",
"err",
":=",
"RawTxInSignature",
"(",
"tx",
",",
"idx",
",",
"subscript",
",",
"hashType",
",",
"privKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"pk",
":=",
"(",
"*",
"btcec",
".",
"PublicKey",
")",
"(",
"&",
"privKey",
".",
"PublicKey",
")",
"\n",
"var",
"pkData",
"[",
"]",
"byte",
"\n",
"if",
"compress",
"{",
"pkData",
"=",
"pk",
".",
"SerializeCompressed",
"(",
")",
"\n",
"}",
"else",
"{",
"pkData",
"=",
"pk",
".",
"SerializeUncompressed",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"NewScriptBuilder",
"(",
")",
".",
"AddData",
"(",
"sig",
")",
".",
"AddData",
"(",
"pkData",
")",
".",
"Script",
"(",
")",
"\n",
"}"
] | // 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",
"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",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/sign.go#L97-L112 | train |
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",
",",
"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",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"len",
"(",
"sigPops",
")",
"==",
"0",
"{",
"return",
"prevScript",
"\n",
"}",
"\n",
"prevPops",
",",
"err",
":=",
"parseScript",
"(",
"prevScript",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"len",
"(",
"prevPops",
")",
"==",
"0",
"{",
"return",
"sigScript",
"\n",
"}",
"\n\n",
"// assume that script in sigPops is the correct one, we just",
"// made it.",
"script",
":=",
"sigPops",
"[",
"len",
"(",
"sigPops",
")",
"-",
"1",
"]",
".",
"data",
"\n\n",
"// We already know this information somewhere up the stack.",
"class",
",",
"addresses",
",",
"nrequired",
",",
"_",
":=",
"ExtractPkScriptAddrs",
"(",
"script",
",",
"chainParams",
")",
"\n\n",
"// regenerate scripts.",
"sigScript",
",",
"_",
":=",
"unparseScript",
"(",
"sigPops",
")",
"\n",
"prevScript",
",",
"_",
":=",
"unparseScript",
"(",
"prevPops",
")",
"\n\n",
"// Merge",
"mergedScript",
":=",
"mergeScripts",
"(",
"chainParams",
",",
"tx",
",",
"idx",
",",
"script",
",",
"class",
",",
"addresses",
",",
"nrequired",
",",
"sigScript",
",",
"prevScript",
")",
"\n\n",
"// Reappend the script and return the result.",
"builder",
":=",
"NewScriptBuilder",
"(",
")",
"\n",
"builder",
".",
"AddOps",
"(",
"mergedScript",
")",
"\n",
"builder",
".",
"AddData",
"(",
"script",
")",
"\n",
"finalScript",
",",
"_",
":=",
"builder",
".",
"Script",
"(",
")",
"\n",
"return",
"finalScript",
"\n",
"case",
"MultiSigTy",
":",
"return",
"mergeMultiSig",
"(",
"tx",
",",
"idx",
",",
"addresses",
",",
"nRequired",
",",
"pkScript",
",",
"sigScript",
",",
"prevScript",
")",
"\n\n",
"// 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",
"\n",
"}",
"\n",
"return",
"prevScript",
"\n",
"}",
"\n",
"}"
] | // 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",
"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",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/sign.go#L221-L280 | train |
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",
")",
"[",
"]",
"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",
")",
"\n\n",
"sigPops",
",",
"err",
":=",
"parseScript",
"(",
"sigScript",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"len",
"(",
"sigPops",
")",
"==",
"0",
"{",
"return",
"prevScript",
"\n",
"}",
"\n\n",
"prevPops",
",",
"err",
":=",
"parseScript",
"(",
"prevScript",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"len",
"(",
"prevPops",
")",
"==",
"0",
"{",
"return",
"sigScript",
"\n",
"}",
"\n\n",
"// 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",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"sigs",
"\n",
"}",
"\n\n",
"possibleSigs",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"0",
",",
"len",
"(",
"sigPops",
")",
"+",
"len",
"(",
"prevPops",
")",
")",
"\n",
"possibleSigs",
"=",
"extractSigs",
"(",
"sigPops",
",",
"possibleSigs",
")",
"\n",
"possibleSigs",
"=",
"extractSigs",
"(",
"prevPops",
",",
"possibleSigs",
")",
"\n\n",
"// 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",
")",
"\n",
"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",
"\n",
"}",
"\n",
"tSig",
":=",
"sig",
"[",
":",
"len",
"(",
"sig",
")",
"-",
"1",
"]",
"\n",
"hashType",
":=",
"SigHashType",
"(",
"sig",
"[",
"len",
"(",
"sig",
")",
"-",
"1",
"]",
")",
"\n\n",
"pSig",
",",
"err",
":=",
"btcec",
".",
"ParseDERSignature",
"(",
"tSig",
",",
"btcec",
".",
"S256",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"// 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",
")",
"\n\n",
"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",
")",
"\n\n",
"pubKey",
":=",
"pkaddr",
".",
"PubKey",
"(",
")",
"\n\n",
"// 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",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"addrToSig",
"[",
"aStr",
"]",
";",
"!",
"ok",
"{",
"addrToSig",
"[",
"aStr",
"]",
"=",
"sig",
"\n",
"}",
"\n",
"continue",
"sigLoop",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Extra opcode to handle the extra arg consumed (due to previous bugs",
"// in the reference implementation).",
"builder",
":=",
"NewScriptBuilder",
"(",
")",
".",
"AddOp",
"(",
"OP_FALSE",
")",
"\n",
"doneSigs",
":=",
"0",
"\n",
"// This assumes that addresses are in the same order as in the script.",
"for",
"_",
",",
"addr",
":=",
"range",
"addresses",
"{",
"sig",
",",
"ok",
":=",
"addrToSig",
"[",
"addr",
".",
"EncodeAddress",
"(",
")",
"]",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"builder",
".",
"AddData",
"(",
"sig",
")",
"\n",
"doneSigs",
"++",
"\n",
"if",
"doneSigs",
"==",
"nRequired",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"// padding for missing ones.",
"for",
"i",
":=",
"doneSigs",
";",
"i",
"<",
"nRequired",
";",
"i",
"++",
"{",
"builder",
".",
"AddOp",
"(",
"OP_0",
")",
"\n",
"}",
"\n\n",
"script",
",",
"_",
":=",
"builder",
".",
"Script",
"(",
")",
"\n",
"return",
"script",
"\n",
"}"
] | // 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",
"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",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/sign.go#L288-L395 | train |
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 | train |
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 | train |
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",
"{",
"drv",
".",
"UseLogger",
"(",
"logger",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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 | train |
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",
"=",
"rerr",
".",
"Err",
"\n",
"}",
"\n\n",
"switch",
"err",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"blockchain",
".",
"RuleError",
":",
"// Convert the chain error to a reject code.",
"var",
"code",
"wire",
".",
"RejectCode",
"\n",
"switch",
"err",
".",
"ErrorCode",
"{",
"// Rejected due to duplicate.",
"case",
"blockchain",
".",
"ErrDuplicateBlock",
":",
"code",
"=",
"wire",
".",
"RejectDuplicate",
"\n\n",
"// Rejected due to obsolete version.",
"case",
"blockchain",
".",
"ErrBlockVersionTooOld",
":",
"code",
"=",
"wire",
".",
"RejectObsolete",
"\n\n",
"// Rejected due to checkpoint.",
"case",
"blockchain",
".",
"ErrCheckpointTimeTooOld",
":",
"fallthrough",
"\n",
"case",
"blockchain",
".",
"ErrDifficultyTooLow",
":",
"fallthrough",
"\n",
"case",
"blockchain",
".",
"ErrBadCheckpoint",
":",
"fallthrough",
"\n",
"case",
"blockchain",
".",
"ErrForkTooOld",
":",
"code",
"=",
"wire",
".",
"RejectCheckpoint",
"\n\n",
"// Everything else is due to the block or transaction being invalid.",
"default",
":",
"code",
"=",
"wire",
".",
"RejectInvalid",
"\n",
"}",
"\n\n",
"return",
"code",
",",
"true",
"\n\n",
"case",
"TxRuleError",
":",
"return",
"err",
".",
"RejectCode",
",",
"true",
"\n\n",
"case",
"nil",
":",
"return",
"wire",
".",
"RejectInvalid",
",",
"false",
"\n",
"}",
"\n\n",
"return",
"wire",
".",
"RejectInvalid",
",",
"false",
"\n",
"}"
] | // 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",
"extracted",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/error.go#L64-L108 | train |
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",
"(",
"err",
")",
"\n",
"if",
"found",
"{",
"return",
"rejectCode",
",",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"\n\n",
"// 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",
",",
"\"",
"\"",
"\n",
"}",
"\n\n",
"// 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",
",",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
"\n",
"}"
] | // 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 | train |
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",
",",
"sig",
".",
"S",
")",
"\n",
"}"
] | // 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 | train |
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",
".",
"S",
")",
"==",
"0",
"\n",
"}"
] | // 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",
"scalar",
"value",
"for",
"R",
"and",
"S",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/signature.go#L83-L86 | train |
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",
"DER",
"format",
"is",
"needed",
"use",
"ParseDERSignature",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/signature.go#L211-L213 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.