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
rpcwebsocket.go
handleNotifyReceived
func handleNotifyReceived(wsc *wsClient, icmd interface{}) (interface{}, error) { cmd, ok := icmd.(*btcjson.NotifyReceivedCmd) if !ok { return nil, btcjson.ErrRPCInternal } // Decode addresses to validate input, but the strings slice is used // directly if these are all ok. err := checkAddressValidity(cmd.Addresses, wsc.server.cfg.ChainParams) if err != nil { return nil, err } wsc.server.ntfnMgr.RegisterTxOutAddressRequests(wsc, cmd.Addresses) return nil, nil }
go
func handleNotifyReceived(wsc *wsClient, icmd interface{}) (interface{}, error) { cmd, ok := icmd.(*btcjson.NotifyReceivedCmd) if !ok { return nil, btcjson.ErrRPCInternal } // Decode addresses to validate input, but the strings slice is used // directly if these are all ok. err := checkAddressValidity(cmd.Addresses, wsc.server.cfg.ChainParams) if err != nil { return nil, err } wsc.server.ntfnMgr.RegisterTxOutAddressRequests(wsc, cmd.Addresses) return nil, nil }
[ "func", "handleNotifyReceived", "(", "wsc", "*", "wsClient", ",", "icmd", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ",", "ok", ":=", "icmd", ".", "(", "*", "btcjson", ".", "NotifyReceivedCmd", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "btcjson", ".", "ErrRPCInternal", "\n", "}", "\n\n", "// Decode addresses to validate input, but the strings slice is used", "// directly if these are all ok.", "err", ":=", "checkAddressValidity", "(", "cmd", ".", "Addresses", ",", "wsc", ".", "server", ".", "cfg", ".", "ChainParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "wsc", ".", "server", ".", "ntfnMgr", ".", "RegisterTxOutAddressRequests", "(", "wsc", ",", "cmd", ".", "Addresses", ")", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// handleNotifyReceived implements the notifyreceived command extension for // websocket connections.
[ "handleNotifyReceived", "implements", "the", "notifyreceived", "command", "extension", "for", "websocket", "connections", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1887-L1902
train
btcsuite/btcd
rpcwebsocket.go
handleStopNotifySpent
func handleStopNotifySpent(wsc *wsClient, icmd interface{}) (interface{}, error) { cmd, ok := icmd.(*btcjson.StopNotifySpentCmd) if !ok { return nil, btcjson.ErrRPCInternal } outpoints, err := deserializeOutpoints(cmd.OutPoints) if err != nil { return nil, err } for _, outpoint := range outpoints { wsc.server.ntfnMgr.UnregisterSpentRequest(wsc, outpoint) } return nil, nil }
go
func handleStopNotifySpent(wsc *wsClient, icmd interface{}) (interface{}, error) { cmd, ok := icmd.(*btcjson.StopNotifySpentCmd) if !ok { return nil, btcjson.ErrRPCInternal } outpoints, err := deserializeOutpoints(cmd.OutPoints) if err != nil { return nil, err } for _, outpoint := range outpoints { wsc.server.ntfnMgr.UnregisterSpentRequest(wsc, outpoint) } return nil, nil }
[ "func", "handleStopNotifySpent", "(", "wsc", "*", "wsClient", ",", "icmd", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ",", "ok", ":=", "icmd", ".", "(", "*", "btcjson", ".", "StopNotifySpentCmd", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "btcjson", ".", "ErrRPCInternal", "\n", "}", "\n\n", "outpoints", ",", "err", ":=", "deserializeOutpoints", "(", "cmd", ".", "OutPoints", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "outpoint", ":=", "range", "outpoints", "{", "wsc", ".", "server", ".", "ntfnMgr", ".", "UnregisterSpentRequest", "(", "wsc", ",", "outpoint", ")", "\n", "}", "\n\n", "return", "nil", ",", "nil", "\n", "}" ]
// handleStopNotifySpent implements the stopnotifyspent command extension for // websocket connections.
[ "handleStopNotifySpent", "implements", "the", "stopnotifyspent", "command", "extension", "for", "websocket", "connections", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1906-L1922
train
btcsuite/btcd
rpcwebsocket.go
handleStopNotifyReceived
func handleStopNotifyReceived(wsc *wsClient, icmd interface{}) (interface{}, error) { cmd, ok := icmd.(*btcjson.StopNotifyReceivedCmd) if !ok { return nil, btcjson.ErrRPCInternal } // Decode addresses to validate input, but the strings slice is used // directly if these are all ok. err := checkAddressValidity(cmd.Addresses, wsc.server.cfg.ChainParams) if err != nil { return nil, err } for _, addr := range cmd.Addresses { wsc.server.ntfnMgr.UnregisterTxOutAddressRequest(wsc, addr) } return nil, nil }
go
func handleStopNotifyReceived(wsc *wsClient, icmd interface{}) (interface{}, error) { cmd, ok := icmd.(*btcjson.StopNotifyReceivedCmd) if !ok { return nil, btcjson.ErrRPCInternal } // Decode addresses to validate input, but the strings slice is used // directly if these are all ok. err := checkAddressValidity(cmd.Addresses, wsc.server.cfg.ChainParams) if err != nil { return nil, err } for _, addr := range cmd.Addresses { wsc.server.ntfnMgr.UnregisterTxOutAddressRequest(wsc, addr) } return nil, nil }
[ "func", "handleStopNotifyReceived", "(", "wsc", "*", "wsClient", ",", "icmd", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ",", "ok", ":=", "icmd", ".", "(", "*", "btcjson", ".", "StopNotifyReceivedCmd", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "btcjson", ".", "ErrRPCInternal", "\n", "}", "\n\n", "// Decode addresses to validate input, but the strings slice is used", "// directly if these are all ok.", "err", ":=", "checkAddressValidity", "(", "cmd", ".", "Addresses", ",", "wsc", ".", "server", ".", "cfg", ".", "ChainParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "addr", ":=", "range", "cmd", ".", "Addresses", "{", "wsc", ".", "server", ".", "ntfnMgr", ".", "UnregisterTxOutAddressRequest", "(", "wsc", ",", "addr", ")", "\n", "}", "\n\n", "return", "nil", ",", "nil", "\n", "}" ]
// handleStopNotifyReceived implements the stopnotifyreceived command extension // for websocket connections.
[ "handleStopNotifyReceived", "implements", "the", "stopnotifyreceived", "command", "extension", "for", "websocket", "connections", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1926-L1944
train
btcsuite/btcd
rpcwebsocket.go
checkAddressValidity
func checkAddressValidity(addrs []string, params *chaincfg.Params) error { for _, addr := range addrs { _, err := btcutil.DecodeAddress(addr, params) if err != nil { return &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidAddressOrKey, Message: fmt.Sprintf("Invalid address or key: %v", addr), } } } return nil }
go
func checkAddressValidity(addrs []string, params *chaincfg.Params) error { for _, addr := range addrs { _, err := btcutil.DecodeAddress(addr, params) if err != nil { return &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidAddressOrKey, Message: fmt.Sprintf("Invalid address or key: %v", addr), } } } return nil }
[ "func", "checkAddressValidity", "(", "addrs", "[", "]", "string", ",", "params", "*", "chaincfg", ".", "Params", ")", "error", "{", "for", "_", ",", "addr", ":=", "range", "addrs", "{", "_", ",", "err", ":=", "btcutil", ".", "DecodeAddress", "(", "addr", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCInvalidAddressOrKey", ",", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "addr", ")", ",", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkAddressValidity checks the validity of each address in the passed // string slice. It does this by attempting to decode each address using the // current active network parameters. If any single address fails to decode // properly, the function returns an error. Otherwise, nil is returned.
[ "checkAddressValidity", "checks", "the", "validity", "of", "each", "address", "in", "the", "passed", "string", "slice", ".", "It", "does", "this", "by", "attempting", "to", "decode", "each", "address", "using", "the", "current", "active", "network", "parameters", ".", "If", "any", "single", "address", "fails", "to", "decode", "properly", "the", "function", "returns", "an", "error", ".", "Otherwise", "nil", "is", "returned", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1950-L1962
train
btcsuite/btcd
rpcwebsocket.go
deserializeOutpoints
func deserializeOutpoints(serializedOuts []btcjson.OutPoint) ([]*wire.OutPoint, error) { outpoints := make([]*wire.OutPoint, 0, len(serializedOuts)) for i := range serializedOuts { blockHash, err := chainhash.NewHashFromStr(serializedOuts[i].Hash) if err != nil { return nil, rpcDecodeHexError(serializedOuts[i].Hash) } index := serializedOuts[i].Index outpoints = append(outpoints, wire.NewOutPoint(blockHash, index)) } return outpoints, nil }
go
func deserializeOutpoints(serializedOuts []btcjson.OutPoint) ([]*wire.OutPoint, error) { outpoints := make([]*wire.OutPoint, 0, len(serializedOuts)) for i := range serializedOuts { blockHash, err := chainhash.NewHashFromStr(serializedOuts[i].Hash) if err != nil { return nil, rpcDecodeHexError(serializedOuts[i].Hash) } index := serializedOuts[i].Index outpoints = append(outpoints, wire.NewOutPoint(blockHash, index)) } return outpoints, nil }
[ "func", "deserializeOutpoints", "(", "serializedOuts", "[", "]", "btcjson", ".", "OutPoint", ")", "(", "[", "]", "*", "wire", ".", "OutPoint", ",", "error", ")", "{", "outpoints", ":=", "make", "(", "[", "]", "*", "wire", ".", "OutPoint", ",", "0", ",", "len", "(", "serializedOuts", ")", ")", "\n", "for", "i", ":=", "range", "serializedOuts", "{", "blockHash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "serializedOuts", "[", "i", "]", ".", "Hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "rpcDecodeHexError", "(", "serializedOuts", "[", "i", "]", ".", "Hash", ")", "\n", "}", "\n", "index", ":=", "serializedOuts", "[", "i", "]", ".", "Index", "\n", "outpoints", "=", "append", "(", "outpoints", ",", "wire", ".", "NewOutPoint", "(", "blockHash", ",", "index", ")", ")", "\n", "}", "\n\n", "return", "outpoints", ",", "nil", "\n", "}" ]
// deserializeOutpoints deserializes each serialized outpoint.
[ "deserializeOutpoints", "deserializes", "each", "serialized", "outpoint", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1965-L1977
train
btcsuite/btcd
rpcwebsocket.go
unspentSlice
func (r *rescanKeys) unspentSlice() []*wire.OutPoint { ops := make([]*wire.OutPoint, 0, len(r.unspent)) for op := range r.unspent { opCopy := op ops = append(ops, &opCopy) } return ops }
go
func (r *rescanKeys) unspentSlice() []*wire.OutPoint { ops := make([]*wire.OutPoint, 0, len(r.unspent)) for op := range r.unspent { opCopy := op ops = append(ops, &opCopy) } return ops }
[ "func", "(", "r", "*", "rescanKeys", ")", "unspentSlice", "(", ")", "[", "]", "*", "wire", ".", "OutPoint", "{", "ops", ":=", "make", "(", "[", "]", "*", "wire", ".", "OutPoint", ",", "0", ",", "len", "(", "r", ".", "unspent", ")", ")", "\n", "for", "op", ":=", "range", "r", ".", "unspent", "{", "opCopy", ":=", "op", "\n", "ops", "=", "append", "(", "ops", ",", "&", "opCopy", ")", "\n", "}", "\n", "return", "ops", "\n", "}" ]
// unspentSlice returns a slice of currently-unspent outpoints for the rescan // lookup keys. This is primarily intended to be used to register outpoints // for continuous notifications after a rescan has completed.
[ "unspentSlice", "returns", "a", "slice", "of", "currently", "-", "unspent", "outpoints", "for", "the", "rescan", "lookup", "keys", ".", "This", "is", "primarily", "intended", "to", "be", "used", "to", "register", "outpoints", "for", "continuous", "notifications", "after", "a", "rescan", "has", "completed", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1987-L1994
train
btcsuite/btcd
rpcwebsocket.go
recoverFromReorg
func recoverFromReorg(chain *blockchain.BlockChain, minBlock, maxBlock int32, lastBlock *chainhash.Hash) ([]chainhash.Hash, error) { hashList, err := chain.HeightRange(minBlock, maxBlock) if err != nil { rpcsLog.Errorf("Error looking up block range: %v", err) return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDatabase, Message: "Database error: " + err.Error(), } } if lastBlock == nil || len(hashList) == 0 { return hashList, nil } blk, err := chain.BlockByHash(&hashList[0]) if err != nil { rpcsLog.Errorf("Error looking up possibly reorged block: %v", err) return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDatabase, Message: "Database error: " + err.Error(), } } jsonErr := descendantBlock(lastBlock, blk) if jsonErr != nil { return nil, jsonErr } return hashList, nil }
go
func recoverFromReorg(chain *blockchain.BlockChain, minBlock, maxBlock int32, lastBlock *chainhash.Hash) ([]chainhash.Hash, error) { hashList, err := chain.HeightRange(minBlock, maxBlock) if err != nil { rpcsLog.Errorf("Error looking up block range: %v", err) return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDatabase, Message: "Database error: " + err.Error(), } } if lastBlock == nil || len(hashList) == 0 { return hashList, nil } blk, err := chain.BlockByHash(&hashList[0]) if err != nil { rpcsLog.Errorf("Error looking up possibly reorged block: %v", err) return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDatabase, Message: "Database error: " + err.Error(), } } jsonErr := descendantBlock(lastBlock, blk) if jsonErr != nil { return nil, jsonErr } return hashList, nil }
[ "func", "recoverFromReorg", "(", "chain", "*", "blockchain", ".", "BlockChain", ",", "minBlock", ",", "maxBlock", "int32", ",", "lastBlock", "*", "chainhash", ".", "Hash", ")", "(", "[", "]", "chainhash", ".", "Hash", ",", "error", ")", "{", "hashList", ",", "err", ":=", "chain", ".", "HeightRange", "(", "minBlock", ",", "maxBlock", ")", "\n", "if", "err", "!=", "nil", "{", "rpcsLog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCDatabase", ",", "Message", ":", "\"", "\"", "+", "err", ".", "Error", "(", ")", ",", "}", "\n", "}", "\n", "if", "lastBlock", "==", "nil", "||", "len", "(", "hashList", ")", "==", "0", "{", "return", "hashList", ",", "nil", "\n", "}", "\n\n", "blk", ",", "err", ":=", "chain", ".", "BlockByHash", "(", "&", "hashList", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "rpcsLog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCDatabase", ",", "Message", ":", "\"", "\"", "+", "err", ".", "Error", "(", ")", ",", "}", "\n", "}", "\n", "jsonErr", ":=", "descendantBlock", "(", "lastBlock", ",", "blk", ")", "\n", "if", "jsonErr", "!=", "nil", "{", "return", "nil", ",", "jsonErr", "\n", "}", "\n", "return", "hashList", ",", "nil", "\n", "}" ]
// recoverFromReorg attempts to recover from a detected reorganize during a // rescan. It fetches a new range of block shas from the database and // verifies that the new range of blocks is on the same fork as a previous // range of blocks. If this condition does not hold true, the JSON-RPC error // for an unrecoverable reorganize is returned.
[ "recoverFromReorg", "attempts", "to", "recover", "from", "a", "detected", "reorganize", "during", "a", "rescan", ".", "It", "fetches", "a", "new", "range", "of", "block", "shas", "from", "the", "database", "and", "verifies", "that", "the", "new", "range", "of", "blocks", "is", "on", "the", "same", "fork", "as", "a", "previous", "range", "of", "blocks", ".", "If", "this", "condition", "does", "not", "hold", "true", "the", "JSON", "-", "RPC", "error", "for", "an", "unrecoverable", "reorganize", "is", "returned", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L2281-L2310
train
btcsuite/btcd
rpcwebsocket.go
descendantBlock
func descendantBlock(prevHash *chainhash.Hash, curBlock *btcutil.Block) error { curHash := &curBlock.MsgBlock().Header.PrevBlock if !prevHash.IsEqual(curHash) { rpcsLog.Errorf("Stopping rescan for reorged block %v "+ "(replaced by block %v)", prevHash, curHash) return &ErrRescanReorg } return nil }
go
func descendantBlock(prevHash *chainhash.Hash, curBlock *btcutil.Block) error { curHash := &curBlock.MsgBlock().Header.PrevBlock if !prevHash.IsEqual(curHash) { rpcsLog.Errorf("Stopping rescan for reorged block %v "+ "(replaced by block %v)", prevHash, curHash) return &ErrRescanReorg } return nil }
[ "func", "descendantBlock", "(", "prevHash", "*", "chainhash", ".", "Hash", ",", "curBlock", "*", "btcutil", ".", "Block", ")", "error", "{", "curHash", ":=", "&", "curBlock", ".", "MsgBlock", "(", ")", ".", "Header", ".", "PrevBlock", "\n", "if", "!", "prevHash", ".", "IsEqual", "(", "curHash", ")", "{", "rpcsLog", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "prevHash", ",", "curHash", ")", "\n", "return", "&", "ErrRescanReorg", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// descendantBlock returns the appropriate JSON-RPC error if a current block // fetched during a reorganize is not a direct child of the parent block hash.
[ "descendantBlock", "returns", "the", "appropriate", "JSON", "-", "RPC", "error", "if", "a", "current", "block", "fetched", "during", "a", "reorganize", "is", "not", "a", "direct", "child", "of", "the", "parent", "block", "hash", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L2314-L2322
train
btcsuite/btcd
btcec/ciphering.go
Decrypt
func Decrypt(priv *PrivateKey, in []byte) ([]byte, error) { // IV + Curve params/X/Y + 1 block + HMAC-256 if len(in) < aes.BlockSize+70+aes.BlockSize+sha256.Size { return nil, errInputTooShort } // read iv iv := in[:aes.BlockSize] offset := aes.BlockSize // start reading pubkey if !bytes.Equal(in[offset:offset+2], ciphCurveBytes[:]) { return nil, errUnsupportedCurve } offset += 2 if !bytes.Equal(in[offset:offset+2], ciphCoordLength[:]) { return nil, errInvalidXLength } offset += 2 xBytes := in[offset : offset+32] offset += 32 if !bytes.Equal(in[offset:offset+2], ciphCoordLength[:]) { return nil, errInvalidYLength } offset += 2 yBytes := in[offset : offset+32] offset += 32 pb := make([]byte, 65) pb[0] = byte(0x04) // uncompressed copy(pb[1:33], xBytes) copy(pb[33:], yBytes) // check if (X, Y) lies on the curve and create a Pubkey if it does pubkey, err := ParsePubKey(pb, S256()) if err != nil { return nil, err } // check for cipher text length if (len(in)-aes.BlockSize-offset-sha256.Size)%aes.BlockSize != 0 { return nil, errInvalidPadding // not padded to 16 bytes } // read hmac messageMAC := in[len(in)-sha256.Size:] // generate shared secret ecdhKey := GenerateSharedSecret(priv, pubkey) derivedKey := sha512.Sum512(ecdhKey) keyE := derivedKey[:32] keyM := derivedKey[32:] // verify mac hm := hmac.New(sha256.New, keyM) hm.Write(in[:len(in)-sha256.Size]) // everything is hashed expectedMAC := hm.Sum(nil) if !hmac.Equal(messageMAC, expectedMAC) { return nil, ErrInvalidMAC } // start decryption block, err := aes.NewCipher(keyE) if err != nil { return nil, err } mode := cipher.NewCBCDecrypter(block, iv) // same length as ciphertext plaintext := make([]byte, len(in)-offset-sha256.Size) mode.CryptBlocks(plaintext, in[offset:len(in)-sha256.Size]) return removePKCSPadding(plaintext) }
go
func Decrypt(priv *PrivateKey, in []byte) ([]byte, error) { // IV + Curve params/X/Y + 1 block + HMAC-256 if len(in) < aes.BlockSize+70+aes.BlockSize+sha256.Size { return nil, errInputTooShort } // read iv iv := in[:aes.BlockSize] offset := aes.BlockSize // start reading pubkey if !bytes.Equal(in[offset:offset+2], ciphCurveBytes[:]) { return nil, errUnsupportedCurve } offset += 2 if !bytes.Equal(in[offset:offset+2], ciphCoordLength[:]) { return nil, errInvalidXLength } offset += 2 xBytes := in[offset : offset+32] offset += 32 if !bytes.Equal(in[offset:offset+2], ciphCoordLength[:]) { return nil, errInvalidYLength } offset += 2 yBytes := in[offset : offset+32] offset += 32 pb := make([]byte, 65) pb[0] = byte(0x04) // uncompressed copy(pb[1:33], xBytes) copy(pb[33:], yBytes) // check if (X, Y) lies on the curve and create a Pubkey if it does pubkey, err := ParsePubKey(pb, S256()) if err != nil { return nil, err } // check for cipher text length if (len(in)-aes.BlockSize-offset-sha256.Size)%aes.BlockSize != 0 { return nil, errInvalidPadding // not padded to 16 bytes } // read hmac messageMAC := in[len(in)-sha256.Size:] // generate shared secret ecdhKey := GenerateSharedSecret(priv, pubkey) derivedKey := sha512.Sum512(ecdhKey) keyE := derivedKey[:32] keyM := derivedKey[32:] // verify mac hm := hmac.New(sha256.New, keyM) hm.Write(in[:len(in)-sha256.Size]) // everything is hashed expectedMAC := hm.Sum(nil) if !hmac.Equal(messageMAC, expectedMAC) { return nil, ErrInvalidMAC } // start decryption block, err := aes.NewCipher(keyE) if err != nil { return nil, err } mode := cipher.NewCBCDecrypter(block, iv) // same length as ciphertext plaintext := make([]byte, len(in)-offset-sha256.Size) mode.CryptBlocks(plaintext, in[offset:len(in)-sha256.Size]) return removePKCSPadding(plaintext) }
[ "func", "Decrypt", "(", "priv", "*", "PrivateKey", ",", "in", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// IV + Curve params/X/Y + 1 block + HMAC-256", "if", "len", "(", "in", ")", "<", "aes", ".", "BlockSize", "+", "70", "+", "aes", ".", "BlockSize", "+", "sha256", ".", "Size", "{", "return", "nil", ",", "errInputTooShort", "\n", "}", "\n\n", "// read iv", "iv", ":=", "in", "[", ":", "aes", ".", "BlockSize", "]", "\n", "offset", ":=", "aes", ".", "BlockSize", "\n\n", "// start reading pubkey", "if", "!", "bytes", ".", "Equal", "(", "in", "[", "offset", ":", "offset", "+", "2", "]", ",", "ciphCurveBytes", "[", ":", "]", ")", "{", "return", "nil", ",", "errUnsupportedCurve", "\n", "}", "\n", "offset", "+=", "2", "\n\n", "if", "!", "bytes", ".", "Equal", "(", "in", "[", "offset", ":", "offset", "+", "2", "]", ",", "ciphCoordLength", "[", ":", "]", ")", "{", "return", "nil", ",", "errInvalidXLength", "\n", "}", "\n", "offset", "+=", "2", "\n\n", "xBytes", ":=", "in", "[", "offset", ":", "offset", "+", "32", "]", "\n", "offset", "+=", "32", "\n\n", "if", "!", "bytes", ".", "Equal", "(", "in", "[", "offset", ":", "offset", "+", "2", "]", ",", "ciphCoordLength", "[", ":", "]", ")", "{", "return", "nil", ",", "errInvalidYLength", "\n", "}", "\n", "offset", "+=", "2", "\n\n", "yBytes", ":=", "in", "[", "offset", ":", "offset", "+", "32", "]", "\n", "offset", "+=", "32", "\n\n", "pb", ":=", "make", "(", "[", "]", "byte", ",", "65", ")", "\n", "pb", "[", "0", "]", "=", "byte", "(", "0x04", ")", "// uncompressed", "\n", "copy", "(", "pb", "[", "1", ":", "33", "]", ",", "xBytes", ")", "\n", "copy", "(", "pb", "[", "33", ":", "]", ",", "yBytes", ")", "\n", "// check if (X, Y) lies on the curve and create a Pubkey if it does", "pubkey", ",", "err", ":=", "ParsePubKey", "(", "pb", ",", "S256", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// check for cipher text length", "if", "(", "len", "(", "in", ")", "-", "aes", ".", "BlockSize", "-", "offset", "-", "sha256", ".", "Size", ")", "%", "aes", ".", "BlockSize", "!=", "0", "{", "return", "nil", ",", "errInvalidPadding", "// not padded to 16 bytes", "\n", "}", "\n\n", "// read hmac", "messageMAC", ":=", "in", "[", "len", "(", "in", ")", "-", "sha256", ".", "Size", ":", "]", "\n\n", "// generate shared secret", "ecdhKey", ":=", "GenerateSharedSecret", "(", "priv", ",", "pubkey", ")", "\n", "derivedKey", ":=", "sha512", ".", "Sum512", "(", "ecdhKey", ")", "\n", "keyE", ":=", "derivedKey", "[", ":", "32", "]", "\n", "keyM", ":=", "derivedKey", "[", "32", ":", "]", "\n\n", "// verify mac", "hm", ":=", "hmac", ".", "New", "(", "sha256", ".", "New", ",", "keyM", ")", "\n", "hm", ".", "Write", "(", "in", "[", ":", "len", "(", "in", ")", "-", "sha256", ".", "Size", "]", ")", "// everything is hashed", "\n", "expectedMAC", ":=", "hm", ".", "Sum", "(", "nil", ")", "\n", "if", "!", "hmac", ".", "Equal", "(", "messageMAC", ",", "expectedMAC", ")", "{", "return", "nil", ",", "ErrInvalidMAC", "\n", "}", "\n\n", "// start decryption", "block", ",", "err", ":=", "aes", ".", "NewCipher", "(", "keyE", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "mode", ":=", "cipher", ".", "NewCBCDecrypter", "(", "block", ",", "iv", ")", "\n", "// same length as ciphertext", "plaintext", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "in", ")", "-", "offset", "-", "sha256", ".", "Size", ")", "\n", "mode", ".", "CryptBlocks", "(", "plaintext", ",", "in", "[", "offset", ":", "len", "(", "in", ")", "-", "sha256", ".", "Size", "]", ")", "\n\n", "return", "removePKCSPadding", "(", "plaintext", ")", "\n", "}" ]
// Decrypt decrypts data that was encrypted using the Encrypt function.
[ "Decrypt", "decrypts", "data", "that", "was", "encrypted", "using", "the", "Encrypt", "function", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/ciphering.go#L121-L196
train
btcsuite/btcd
btcec/ciphering.go
removePKCSPadding
func removePKCSPadding(src []byte) ([]byte, error) { length := len(src) padLength := int(src[length-1]) if padLength > aes.BlockSize || length < aes.BlockSize { return nil, errInvalidPadding } return src[:length-padLength], nil }
go
func removePKCSPadding(src []byte) ([]byte, error) { length := len(src) padLength := int(src[length-1]) if padLength > aes.BlockSize || length < aes.BlockSize { return nil, errInvalidPadding } return src[:length-padLength], nil }
[ "func", "removePKCSPadding", "(", "src", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "length", ":=", "len", "(", "src", ")", "\n", "padLength", ":=", "int", "(", "src", "[", "length", "-", "1", "]", ")", "\n", "if", "padLength", ">", "aes", ".", "BlockSize", "||", "length", "<", "aes", ".", "BlockSize", "{", "return", "nil", ",", "errInvalidPadding", "\n", "}", "\n\n", "return", "src", "[", ":", "length", "-", "padLength", "]", ",", "nil", "\n", "}" ]
// removePKCSPadding removes padding from data that was added with addPKCSPadding
[ "removePKCSPadding", "removes", "padding", "from", "data", "that", "was", "added", "with", "addPKCSPadding" ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/ciphering.go#L208-L216
train
btcsuite/btcd
database/internal/treap/common.go
nodeSize
func nodeSize(node *treapNode) uint64 { return nodeFieldsSize + uint64(len(node.key)+len(node.value)) }
go
func nodeSize(node *treapNode) uint64 { return nodeFieldsSize + uint64(len(node.key)+len(node.value)) }
[ "func", "nodeSize", "(", "node", "*", "treapNode", ")", "uint64", "{", "return", "nodeFieldsSize", "+", "uint64", "(", "len", "(", "node", ".", "key", ")", "+", "len", "(", "node", ".", "value", ")", ")", "\n", "}" ]
// nodeSize returns the number of bytes the specified node occupies including // the struct fields and the contents of the key and value.
[ "nodeSize", "returns", "the", "number", "of", "bytes", "the", "specified", "node", "occupies", "including", "the", "struct", "fields", "and", "the", "contents", "of", "the", "key", "and", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/internal/treap/common.go#L47-L49
train
btcsuite/btcd
database/internal/treap/common.go
newTreapNode
func newTreapNode(key, value []byte, priority int) *treapNode { return &treapNode{key: key, value: value, priority: priority} }
go
func newTreapNode(key, value []byte, priority int) *treapNode { return &treapNode{key: key, value: value, priority: priority} }
[ "func", "newTreapNode", "(", "key", ",", "value", "[", "]", "byte", ",", "priority", "int", ")", "*", "treapNode", "{", "return", "&", "treapNode", "{", "key", ":", "key", ",", "value", ":", "value", ",", "priority", ":", "priority", "}", "\n", "}" ]
// newTreapNode returns a new node from the given key, value, and priority. The // node is not initially linked to any others.
[ "newTreapNode", "returns", "a", "new", "node", "from", "the", "given", "key", "value", "and", "priority", ".", "The", "node", "is", "not", "initially", "linked", "to", "any", "others", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/internal/treap/common.go#L53-L55
train
btcsuite/btcd
database/internal/treap/common.go
At
func (s *parentStack) At(n int) *treapNode { index := s.index - n - 1 if index < 0 { return nil } if index < staticDepth { return s.items[index] } return s.overflow[index-staticDepth] }
go
func (s *parentStack) At(n int) *treapNode { index := s.index - n - 1 if index < 0 { return nil } if index < staticDepth { return s.items[index] } return s.overflow[index-staticDepth] }
[ "func", "(", "s", "*", "parentStack", ")", "At", "(", "n", "int", ")", "*", "treapNode", "{", "index", ":=", "s", ".", "index", "-", "n", "-", "1", "\n", "if", "index", "<", "0", "{", "return", "nil", "\n", "}", "\n\n", "if", "index", "<", "staticDepth", "{", "return", "s", ".", "items", "[", "index", "]", "\n", "}", "\n\n", "return", "s", ".", "overflow", "[", "index", "-", "staticDepth", "]", "\n", "}" ]
// At returns the item n number of items from the top of the stack, where 0 is // the topmost item, without removing it. It returns nil if n exceeds the // number of items on the stack.
[ "At", "returns", "the", "item", "n", "number", "of", "items", "from", "the", "top", "of", "the", "stack", "where", "0", "is", "the", "topmost", "item", "without", "removing", "it", ".", "It", "returns", "nil", "if", "n", "exceeds", "the", "number", "of", "items", "on", "the", "stack", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/internal/treap/common.go#L78-L89
train
btcsuite/btcd
database/internal/treap/common.go
Pop
func (s *parentStack) Pop() *treapNode { if s.index == 0 { return nil } s.index-- if s.index < staticDepth { node := s.items[s.index] s.items[s.index] = nil return node } node := s.overflow[s.index-staticDepth] s.overflow[s.index-staticDepth] = nil return node }
go
func (s *parentStack) Pop() *treapNode { if s.index == 0 { return nil } s.index-- if s.index < staticDepth { node := s.items[s.index] s.items[s.index] = nil return node } node := s.overflow[s.index-staticDepth] s.overflow[s.index-staticDepth] = nil return node }
[ "func", "(", "s", "*", "parentStack", ")", "Pop", "(", ")", "*", "treapNode", "{", "if", "s", ".", "index", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "s", ".", "index", "--", "\n", "if", "s", ".", "index", "<", "staticDepth", "{", "node", ":=", "s", ".", "items", "[", "s", ".", "index", "]", "\n", "s", ".", "items", "[", "s", ".", "index", "]", "=", "nil", "\n", "return", "node", "\n", "}", "\n\n", "node", ":=", "s", ".", "overflow", "[", "s", ".", "index", "-", "staticDepth", "]", "\n", "s", ".", "overflow", "[", "s", ".", "index", "-", "staticDepth", "]", "=", "nil", "\n", "return", "node", "\n", "}" ]
// Pop removes the top item from the stack. It returns nil if the stack is // empty.
[ "Pop", "removes", "the", "top", "item", "from", "the", "stack", ".", "It", "returns", "nil", "if", "the", "stack", "is", "empty", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/internal/treap/common.go#L93-L108
train
btcsuite/btcd
database/internal/treap/common.go
Push
func (s *parentStack) Push(node *treapNode) { if s.index < staticDepth { s.items[s.index] = node s.index++ return } // This approach is used over append because reslicing the slice to pop // the item causes the compiler to make unneeded allocations. Also, // since the max number of items is related to the tree depth which // requires expontentially more items to increase, only increase the cap // one item at a time. This is more intelligent than the generic append // expansion algorithm which often doubles the cap. index := s.index - staticDepth if index+1 > cap(s.overflow) { overflow := make([]*treapNode, index+1) copy(overflow, s.overflow) s.overflow = overflow } s.overflow[index] = node s.index++ }
go
func (s *parentStack) Push(node *treapNode) { if s.index < staticDepth { s.items[s.index] = node s.index++ return } // This approach is used over append because reslicing the slice to pop // the item causes the compiler to make unneeded allocations. Also, // since the max number of items is related to the tree depth which // requires expontentially more items to increase, only increase the cap // one item at a time. This is more intelligent than the generic append // expansion algorithm which often doubles the cap. index := s.index - staticDepth if index+1 > cap(s.overflow) { overflow := make([]*treapNode, index+1) copy(overflow, s.overflow) s.overflow = overflow } s.overflow[index] = node s.index++ }
[ "func", "(", "s", "*", "parentStack", ")", "Push", "(", "node", "*", "treapNode", ")", "{", "if", "s", ".", "index", "<", "staticDepth", "{", "s", ".", "items", "[", "s", ".", "index", "]", "=", "node", "\n", "s", ".", "index", "++", "\n", "return", "\n", "}", "\n\n", "// This approach is used over append because reslicing the slice to pop", "// the item causes the compiler to make unneeded allocations. Also,", "// since the max number of items is related to the tree depth which", "// requires expontentially more items to increase, only increase the cap", "// one item at a time. This is more intelligent than the generic append", "// expansion algorithm which often doubles the cap.", "index", ":=", "s", ".", "index", "-", "staticDepth", "\n", "if", "index", "+", "1", ">", "cap", "(", "s", ".", "overflow", ")", "{", "overflow", ":=", "make", "(", "[", "]", "*", "treapNode", ",", "index", "+", "1", ")", "\n", "copy", "(", "overflow", ",", "s", ".", "overflow", ")", "\n", "s", ".", "overflow", "=", "overflow", "\n", "}", "\n", "s", ".", "overflow", "[", "index", "]", "=", "node", "\n", "s", ".", "index", "++", "\n", "}" ]
// Push pushes the passed item onto the top of the stack.
[ "Push", "pushes", "the", "passed", "item", "onto", "the", "top", "of", "the", "stack", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/internal/treap/common.go#L111-L132
train
btcsuite/btcd
peer/peer.go
newNetAddress
func newNetAddress(addr net.Addr, services wire.ServiceFlag) (*wire.NetAddress, error) { // addr will be a net.TCPAddr when not using a proxy. if tcpAddr, ok := addr.(*net.TCPAddr); ok { ip := tcpAddr.IP port := uint16(tcpAddr.Port) na := wire.NewNetAddressIPPort(ip, port, services) return na, nil } // addr will be a socks.ProxiedAddr when using a proxy. if proxiedAddr, ok := addr.(*socks.ProxiedAddr); ok { ip := net.ParseIP(proxiedAddr.Host) if ip == nil { ip = net.ParseIP("0.0.0.0") } port := uint16(proxiedAddr.Port) na := wire.NewNetAddressIPPort(ip, port, services) return na, nil } // For the most part, addr should be one of the two above cases, but // to be safe, fall back to trying to parse the information from the // address string as a last resort. host, portStr, err := net.SplitHostPort(addr.String()) if err != nil { return nil, err } ip := net.ParseIP(host) port, err := strconv.ParseUint(portStr, 10, 16) if err != nil { return nil, err } na := wire.NewNetAddressIPPort(ip, uint16(port), services) return na, nil }
go
func newNetAddress(addr net.Addr, services wire.ServiceFlag) (*wire.NetAddress, error) { // addr will be a net.TCPAddr when not using a proxy. if tcpAddr, ok := addr.(*net.TCPAddr); ok { ip := tcpAddr.IP port := uint16(tcpAddr.Port) na := wire.NewNetAddressIPPort(ip, port, services) return na, nil } // addr will be a socks.ProxiedAddr when using a proxy. if proxiedAddr, ok := addr.(*socks.ProxiedAddr); ok { ip := net.ParseIP(proxiedAddr.Host) if ip == nil { ip = net.ParseIP("0.0.0.0") } port := uint16(proxiedAddr.Port) na := wire.NewNetAddressIPPort(ip, port, services) return na, nil } // For the most part, addr should be one of the two above cases, but // to be safe, fall back to trying to parse the information from the // address string as a last resort. host, portStr, err := net.SplitHostPort(addr.String()) if err != nil { return nil, err } ip := net.ParseIP(host) port, err := strconv.ParseUint(portStr, 10, 16) if err != nil { return nil, err } na := wire.NewNetAddressIPPort(ip, uint16(port), services) return na, nil }
[ "func", "newNetAddress", "(", "addr", "net", ".", "Addr", ",", "services", "wire", ".", "ServiceFlag", ")", "(", "*", "wire", ".", "NetAddress", ",", "error", ")", "{", "// addr will be a net.TCPAddr when not using a proxy.", "if", "tcpAddr", ",", "ok", ":=", "addr", ".", "(", "*", "net", ".", "TCPAddr", ")", ";", "ok", "{", "ip", ":=", "tcpAddr", ".", "IP", "\n", "port", ":=", "uint16", "(", "tcpAddr", ".", "Port", ")", "\n", "na", ":=", "wire", ".", "NewNetAddressIPPort", "(", "ip", ",", "port", ",", "services", ")", "\n", "return", "na", ",", "nil", "\n", "}", "\n\n", "// addr will be a socks.ProxiedAddr when using a proxy.", "if", "proxiedAddr", ",", "ok", ":=", "addr", ".", "(", "*", "socks", ".", "ProxiedAddr", ")", ";", "ok", "{", "ip", ":=", "net", ".", "ParseIP", "(", "proxiedAddr", ".", "Host", ")", "\n", "if", "ip", "==", "nil", "{", "ip", "=", "net", ".", "ParseIP", "(", "\"", "\"", ")", "\n", "}", "\n", "port", ":=", "uint16", "(", "proxiedAddr", ".", "Port", ")", "\n", "na", ":=", "wire", ".", "NewNetAddressIPPort", "(", "ip", ",", "port", ",", "services", ")", "\n", "return", "na", ",", "nil", "\n", "}", "\n\n", "// For the most part, addr should be one of the two above cases, but", "// to be safe, fall back to trying to parse the information from the", "// address string as a last resort.", "host", ",", "portStr", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "addr", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ip", ":=", "net", ".", "ParseIP", "(", "host", ")", "\n", "port", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "portStr", ",", "10", ",", "16", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "na", ":=", "wire", ".", "NewNetAddressIPPort", "(", "ip", ",", "uint16", "(", "port", ")", ",", "services", ")", "\n", "return", "na", ",", "nil", "\n", "}" ]
// newNetAddress attempts to extract the IP address and port from the passed // net.Addr interface and create a bitcoin NetAddress structure using that // information.
[ "newNetAddress", "attempts", "to", "extract", "the", "IP", "address", "and", "port", "from", "the", "passed", "net", ".", "Addr", "interface", "and", "create", "a", "bitcoin", "NetAddress", "structure", "using", "that", "information", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L292-L326
train
btcsuite/btcd
peer/peer.go
String
func (p *Peer) String() string { return fmt.Sprintf("%s (%s)", p.addr, directionString(p.inbound)) }
go
func (p *Peer) String() string { return fmt.Sprintf("%s (%s)", p.addr, directionString(p.inbound)) }
[ "func", "(", "p", "*", "Peer", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "addr", ",", "directionString", "(", "p", ".", "inbound", ")", ")", "\n", "}" ]
// String returns the peer's address and directionality as a human-readable // string. // // This function is safe for concurrent access.
[ "String", "returns", "the", "peer", "s", "address", "and", "directionality", "as", "a", "human", "-", "readable", "string", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L488-L490
train
btcsuite/btcd
peer/peer.go
UpdateLastBlockHeight
func (p *Peer) UpdateLastBlockHeight(newHeight int32) { p.statsMtx.Lock() log.Tracef("Updating last block height of peer %v from %v to %v", p.addr, p.lastBlock, newHeight) p.lastBlock = newHeight p.statsMtx.Unlock() }
go
func (p *Peer) UpdateLastBlockHeight(newHeight int32) { p.statsMtx.Lock() log.Tracef("Updating last block height of peer %v from %v to %v", p.addr, p.lastBlock, newHeight) p.lastBlock = newHeight p.statsMtx.Unlock() }
[ "func", "(", "p", "*", "Peer", ")", "UpdateLastBlockHeight", "(", "newHeight", "int32", ")", "{", "p", ".", "statsMtx", ".", "Lock", "(", ")", "\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "p", ".", "addr", ",", "p", ".", "lastBlock", ",", "newHeight", ")", "\n", "p", ".", "lastBlock", "=", "newHeight", "\n", "p", ".", "statsMtx", ".", "Unlock", "(", ")", "\n", "}" ]
// UpdateLastBlockHeight updates the last known block for the peer. // // This function is safe for concurrent access.
[ "UpdateLastBlockHeight", "updates", "the", "last", "known", "block", "for", "the", "peer", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L495-L501
train
btcsuite/btcd
peer/peer.go
UpdateLastAnnouncedBlock
func (p *Peer) UpdateLastAnnouncedBlock(blkHash *chainhash.Hash) { log.Tracef("Updating last blk for peer %v, %v", p.addr, blkHash) p.statsMtx.Lock() p.lastAnnouncedBlock = blkHash p.statsMtx.Unlock() }
go
func (p *Peer) UpdateLastAnnouncedBlock(blkHash *chainhash.Hash) { log.Tracef("Updating last blk for peer %v, %v", p.addr, blkHash) p.statsMtx.Lock() p.lastAnnouncedBlock = blkHash p.statsMtx.Unlock() }
[ "func", "(", "p", "*", "Peer", ")", "UpdateLastAnnouncedBlock", "(", "blkHash", "*", "chainhash", ".", "Hash", ")", "{", "log", ".", "Tracef", "(", "\"", "\"", ",", "p", ".", "addr", ",", "blkHash", ")", "\n\n", "p", ".", "statsMtx", ".", "Lock", "(", ")", "\n", "p", ".", "lastAnnouncedBlock", "=", "blkHash", "\n", "p", ".", "statsMtx", ".", "Unlock", "(", ")", "\n", "}" ]
// UpdateLastAnnouncedBlock updates meta-data about the last block hash this // peer is known to have announced. // // This function is safe for concurrent access.
[ "UpdateLastAnnouncedBlock", "updates", "meta", "-", "data", "about", "the", "last", "block", "hash", "this", "peer", "is", "known", "to", "have", "announced", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L507-L513
train
btcsuite/btcd
peer/peer.go
AddKnownInventory
func (p *Peer) AddKnownInventory(invVect *wire.InvVect) { p.knownInventory.Add(invVect) }
go
func (p *Peer) AddKnownInventory(invVect *wire.InvVect) { p.knownInventory.Add(invVect) }
[ "func", "(", "p", "*", "Peer", ")", "AddKnownInventory", "(", "invVect", "*", "wire", ".", "InvVect", ")", "{", "p", ".", "knownInventory", ".", "Add", "(", "invVect", ")", "\n", "}" ]
// AddKnownInventory adds the passed inventory to the cache of known inventory // for the peer. // // This function is safe for concurrent access.
[ "AddKnownInventory", "adds", "the", "passed", "inventory", "to", "the", "cache", "of", "known", "inventory", "for", "the", "peer", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L519-L521
train
btcsuite/btcd
peer/peer.go
StatsSnapshot
func (p *Peer) StatsSnapshot() *StatsSnap { p.statsMtx.RLock() p.flagsMtx.Lock() id := p.id addr := p.addr userAgent := p.userAgent services := p.services protocolVersion := p.advertisedProtoVer p.flagsMtx.Unlock() // Get a copy of all relevant flags and stats. statsSnap := &StatsSnap{ ID: id, Addr: addr, UserAgent: userAgent, Services: services, LastSend: p.LastSend(), LastRecv: p.LastRecv(), BytesSent: p.BytesSent(), BytesRecv: p.BytesReceived(), ConnTime: p.timeConnected, TimeOffset: p.timeOffset, Version: protocolVersion, Inbound: p.inbound, StartingHeight: p.startingHeight, LastBlock: p.lastBlock, LastPingNonce: p.lastPingNonce, LastPingMicros: p.lastPingMicros, LastPingTime: p.lastPingTime, } p.statsMtx.RUnlock() return statsSnap }
go
func (p *Peer) StatsSnapshot() *StatsSnap { p.statsMtx.RLock() p.flagsMtx.Lock() id := p.id addr := p.addr userAgent := p.userAgent services := p.services protocolVersion := p.advertisedProtoVer p.flagsMtx.Unlock() // Get a copy of all relevant flags and stats. statsSnap := &StatsSnap{ ID: id, Addr: addr, UserAgent: userAgent, Services: services, LastSend: p.LastSend(), LastRecv: p.LastRecv(), BytesSent: p.BytesSent(), BytesRecv: p.BytesReceived(), ConnTime: p.timeConnected, TimeOffset: p.timeOffset, Version: protocolVersion, Inbound: p.inbound, StartingHeight: p.startingHeight, LastBlock: p.lastBlock, LastPingNonce: p.lastPingNonce, LastPingMicros: p.lastPingMicros, LastPingTime: p.lastPingTime, } p.statsMtx.RUnlock() return statsSnap }
[ "func", "(", "p", "*", "Peer", ")", "StatsSnapshot", "(", ")", "*", "StatsSnap", "{", "p", ".", "statsMtx", ".", "RLock", "(", ")", "\n\n", "p", ".", "flagsMtx", ".", "Lock", "(", ")", "\n", "id", ":=", "p", ".", "id", "\n", "addr", ":=", "p", ".", "addr", "\n", "userAgent", ":=", "p", ".", "userAgent", "\n", "services", ":=", "p", ".", "services", "\n", "protocolVersion", ":=", "p", ".", "advertisedProtoVer", "\n", "p", ".", "flagsMtx", ".", "Unlock", "(", ")", "\n\n", "// Get a copy of all relevant flags and stats.", "statsSnap", ":=", "&", "StatsSnap", "{", "ID", ":", "id", ",", "Addr", ":", "addr", ",", "UserAgent", ":", "userAgent", ",", "Services", ":", "services", ",", "LastSend", ":", "p", ".", "LastSend", "(", ")", ",", "LastRecv", ":", "p", ".", "LastRecv", "(", ")", ",", "BytesSent", ":", "p", ".", "BytesSent", "(", ")", ",", "BytesRecv", ":", "p", ".", "BytesReceived", "(", ")", ",", "ConnTime", ":", "p", ".", "timeConnected", ",", "TimeOffset", ":", "p", ".", "timeOffset", ",", "Version", ":", "protocolVersion", ",", "Inbound", ":", "p", ".", "inbound", ",", "StartingHeight", ":", "p", ".", "startingHeight", ",", "LastBlock", ":", "p", ".", "lastBlock", ",", "LastPingNonce", ":", "p", ".", "lastPingNonce", ",", "LastPingMicros", ":", "p", ".", "lastPingMicros", ",", "LastPingTime", ":", "p", ".", "lastPingTime", ",", "}", "\n\n", "p", ".", "statsMtx", ".", "RUnlock", "(", ")", "\n", "return", "statsSnap", "\n", "}" ]
// StatsSnapshot returns a snapshot of the current peer flags and statistics. // // This function is safe for concurrent access.
[ "StatsSnapshot", "returns", "a", "snapshot", "of", "the", "current", "peer", "flags", "and", "statistics", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L526-L560
train
btcsuite/btcd
peer/peer.go
ID
func (p *Peer) ID() int32 { p.flagsMtx.Lock() id := p.id p.flagsMtx.Unlock() return id }
go
func (p *Peer) ID() int32 { p.flagsMtx.Lock() id := p.id p.flagsMtx.Unlock() return id }
[ "func", "(", "p", "*", "Peer", ")", "ID", "(", ")", "int32", "{", "p", ".", "flagsMtx", ".", "Lock", "(", ")", "\n", "id", ":=", "p", ".", "id", "\n", "p", ".", "flagsMtx", ".", "Unlock", "(", ")", "\n\n", "return", "id", "\n", "}" ]
// ID returns the peer id. // // This function is safe for concurrent access.
[ "ID", "returns", "the", "peer", "id", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L565-L571
train
btcsuite/btcd
peer/peer.go
NA
func (p *Peer) NA() *wire.NetAddress { p.flagsMtx.Lock() na := p.na p.flagsMtx.Unlock() return na }
go
func (p *Peer) NA() *wire.NetAddress { p.flagsMtx.Lock() na := p.na p.flagsMtx.Unlock() return na }
[ "func", "(", "p", "*", "Peer", ")", "NA", "(", ")", "*", "wire", ".", "NetAddress", "{", "p", ".", "flagsMtx", ".", "Lock", "(", ")", "\n", "na", ":=", "p", ".", "na", "\n", "p", ".", "flagsMtx", ".", "Unlock", "(", ")", "\n\n", "return", "na", "\n", "}" ]
// NA returns the peer network address. // // This function is safe for concurrent access.
[ "NA", "returns", "the", "peer", "network", "address", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L576-L582
train
btcsuite/btcd
peer/peer.go
Services
func (p *Peer) Services() wire.ServiceFlag { p.flagsMtx.Lock() services := p.services p.flagsMtx.Unlock() return services }
go
func (p *Peer) Services() wire.ServiceFlag { p.flagsMtx.Lock() services := p.services p.flagsMtx.Unlock() return services }
[ "func", "(", "p", "*", "Peer", ")", "Services", "(", ")", "wire", ".", "ServiceFlag", "{", "p", ".", "flagsMtx", ".", "Lock", "(", ")", "\n", "services", ":=", "p", ".", "services", "\n", "p", ".", "flagsMtx", ".", "Unlock", "(", ")", "\n\n", "return", "services", "\n", "}" ]
// Services returns the services flag of the remote peer. // // This function is safe for concurrent access.
[ "Services", "returns", "the", "services", "flag", "of", "the", "remote", "peer", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L603-L609
train
btcsuite/btcd
peer/peer.go
UserAgent
func (p *Peer) UserAgent() string { p.flagsMtx.Lock() userAgent := p.userAgent p.flagsMtx.Unlock() return userAgent }
go
func (p *Peer) UserAgent() string { p.flagsMtx.Lock() userAgent := p.userAgent p.flagsMtx.Unlock() return userAgent }
[ "func", "(", "p", "*", "Peer", ")", "UserAgent", "(", ")", "string", "{", "p", ".", "flagsMtx", ".", "Lock", "(", ")", "\n", "userAgent", ":=", "p", ".", "userAgent", "\n", "p", ".", "flagsMtx", ".", "Unlock", "(", ")", "\n\n", "return", "userAgent", "\n", "}" ]
// UserAgent returns the user agent of the remote peer. // // This function is safe for concurrent access.
[ "UserAgent", "returns", "the", "user", "agent", "of", "the", "remote", "peer", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L614-L620
train
btcsuite/btcd
peer/peer.go
LastAnnouncedBlock
func (p *Peer) LastAnnouncedBlock() *chainhash.Hash { p.statsMtx.RLock() lastAnnouncedBlock := p.lastAnnouncedBlock p.statsMtx.RUnlock() return lastAnnouncedBlock }
go
func (p *Peer) LastAnnouncedBlock() *chainhash.Hash { p.statsMtx.RLock() lastAnnouncedBlock := p.lastAnnouncedBlock p.statsMtx.RUnlock() return lastAnnouncedBlock }
[ "func", "(", "p", "*", "Peer", ")", "LastAnnouncedBlock", "(", ")", "*", "chainhash", ".", "Hash", "{", "p", ".", "statsMtx", ".", "RLock", "(", ")", "\n", "lastAnnouncedBlock", ":=", "p", ".", "lastAnnouncedBlock", "\n", "p", ".", "statsMtx", ".", "RUnlock", "(", ")", "\n\n", "return", "lastAnnouncedBlock", "\n", "}" ]
// LastAnnouncedBlock returns the last announced block of the remote peer. // // This function is safe for concurrent access.
[ "LastAnnouncedBlock", "returns", "the", "last", "announced", "block", "of", "the", "remote", "peer", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L625-L631
train
btcsuite/btcd
peer/peer.go
LastPingNonce
func (p *Peer) LastPingNonce() uint64 { p.statsMtx.RLock() lastPingNonce := p.lastPingNonce p.statsMtx.RUnlock() return lastPingNonce }
go
func (p *Peer) LastPingNonce() uint64 { p.statsMtx.RLock() lastPingNonce := p.lastPingNonce p.statsMtx.RUnlock() return lastPingNonce }
[ "func", "(", "p", "*", "Peer", ")", "LastPingNonce", "(", ")", "uint64", "{", "p", ".", "statsMtx", ".", "RLock", "(", ")", "\n", "lastPingNonce", ":=", "p", ".", "lastPingNonce", "\n", "p", ".", "statsMtx", ".", "RUnlock", "(", ")", "\n\n", "return", "lastPingNonce", "\n", "}" ]
// LastPingNonce returns the last ping nonce of the remote peer. // // This function is safe for concurrent access.
[ "LastPingNonce", "returns", "the", "last", "ping", "nonce", "of", "the", "remote", "peer", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L636-L642
train
btcsuite/btcd
peer/peer.go
LastPingTime
func (p *Peer) LastPingTime() time.Time { p.statsMtx.RLock() lastPingTime := p.lastPingTime p.statsMtx.RUnlock() return lastPingTime }
go
func (p *Peer) LastPingTime() time.Time { p.statsMtx.RLock() lastPingTime := p.lastPingTime p.statsMtx.RUnlock() return lastPingTime }
[ "func", "(", "p", "*", "Peer", ")", "LastPingTime", "(", ")", "time", ".", "Time", "{", "p", ".", "statsMtx", ".", "RLock", "(", ")", "\n", "lastPingTime", ":=", "p", ".", "lastPingTime", "\n", "p", ".", "statsMtx", ".", "RUnlock", "(", ")", "\n\n", "return", "lastPingTime", "\n", "}" ]
// LastPingTime returns the last ping time of the remote peer. // // This function is safe for concurrent access.
[ "LastPingTime", "returns", "the", "last", "ping", "time", "of", "the", "remote", "peer", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L647-L653
train
btcsuite/btcd
peer/peer.go
LastPingMicros
func (p *Peer) LastPingMicros() int64 { p.statsMtx.RLock() lastPingMicros := p.lastPingMicros p.statsMtx.RUnlock() return lastPingMicros }
go
func (p *Peer) LastPingMicros() int64 { p.statsMtx.RLock() lastPingMicros := p.lastPingMicros p.statsMtx.RUnlock() return lastPingMicros }
[ "func", "(", "p", "*", "Peer", ")", "LastPingMicros", "(", ")", "int64", "{", "p", ".", "statsMtx", ".", "RLock", "(", ")", "\n", "lastPingMicros", ":=", "p", ".", "lastPingMicros", "\n", "p", ".", "statsMtx", ".", "RUnlock", "(", ")", "\n\n", "return", "lastPingMicros", "\n", "}" ]
// LastPingMicros returns the last ping micros of the remote peer. // // This function is safe for concurrent access.
[ "LastPingMicros", "returns", "the", "last", "ping", "micros", "of", "the", "remote", "peer", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L658-L664
train
btcsuite/btcd
peer/peer.go
VersionKnown
func (p *Peer) VersionKnown() bool { p.flagsMtx.Lock() versionKnown := p.versionKnown p.flagsMtx.Unlock() return versionKnown }
go
func (p *Peer) VersionKnown() bool { p.flagsMtx.Lock() versionKnown := p.versionKnown p.flagsMtx.Unlock() return versionKnown }
[ "func", "(", "p", "*", "Peer", ")", "VersionKnown", "(", ")", "bool", "{", "p", ".", "flagsMtx", ".", "Lock", "(", ")", "\n", "versionKnown", ":=", "p", ".", "versionKnown", "\n", "p", ".", "flagsMtx", ".", "Unlock", "(", ")", "\n\n", "return", "versionKnown", "\n", "}" ]
// VersionKnown returns the whether or not the version of a peer is known // locally. // // This function is safe for concurrent access.
[ "VersionKnown", "returns", "the", "whether", "or", "not", "the", "version", "of", "a", "peer", "is", "known", "locally", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L670-L676
train
btcsuite/btcd
peer/peer.go
VerAckReceived
func (p *Peer) VerAckReceived() bool { p.flagsMtx.Lock() verAckReceived := p.verAckReceived p.flagsMtx.Unlock() return verAckReceived }
go
func (p *Peer) VerAckReceived() bool { p.flagsMtx.Lock() verAckReceived := p.verAckReceived p.flagsMtx.Unlock() return verAckReceived }
[ "func", "(", "p", "*", "Peer", ")", "VerAckReceived", "(", ")", "bool", "{", "p", ".", "flagsMtx", ".", "Lock", "(", ")", "\n", "verAckReceived", ":=", "p", ".", "verAckReceived", "\n", "p", ".", "flagsMtx", ".", "Unlock", "(", ")", "\n\n", "return", "verAckReceived", "\n", "}" ]
// VerAckReceived returns whether or not a verack message was received by the // peer. // // This function is safe for concurrent access.
[ "VerAckReceived", "returns", "whether", "or", "not", "a", "verack", "message", "was", "received", "by", "the", "peer", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L682-L688
train
btcsuite/btcd
peer/peer.go
ProtocolVersion
func (p *Peer) ProtocolVersion() uint32 { p.flagsMtx.Lock() protocolVersion := p.protocolVersion p.flagsMtx.Unlock() return protocolVersion }
go
func (p *Peer) ProtocolVersion() uint32 { p.flagsMtx.Lock() protocolVersion := p.protocolVersion p.flagsMtx.Unlock() return protocolVersion }
[ "func", "(", "p", "*", "Peer", ")", "ProtocolVersion", "(", ")", "uint32", "{", "p", ".", "flagsMtx", ".", "Lock", "(", ")", "\n", "protocolVersion", ":=", "p", ".", "protocolVersion", "\n", "p", ".", "flagsMtx", ".", "Unlock", "(", ")", "\n\n", "return", "protocolVersion", "\n", "}" ]
// ProtocolVersion returns the negotiated peer protocol version. // // This function is safe for concurrent access.
[ "ProtocolVersion", "returns", "the", "negotiated", "peer", "protocol", "version", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L693-L699
train
btcsuite/btcd
peer/peer.go
LastBlock
func (p *Peer) LastBlock() int32 { p.statsMtx.RLock() lastBlock := p.lastBlock p.statsMtx.RUnlock() return lastBlock }
go
func (p *Peer) LastBlock() int32 { p.statsMtx.RLock() lastBlock := p.lastBlock p.statsMtx.RUnlock() return lastBlock }
[ "func", "(", "p", "*", "Peer", ")", "LastBlock", "(", ")", "int32", "{", "p", ".", "statsMtx", ".", "RLock", "(", ")", "\n", "lastBlock", ":=", "p", ".", "lastBlock", "\n", "p", ".", "statsMtx", ".", "RUnlock", "(", ")", "\n\n", "return", "lastBlock", "\n", "}" ]
// LastBlock returns the last block of the peer. // // This function is safe for concurrent access.
[ "LastBlock", "returns", "the", "last", "block", "of", "the", "peer", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L704-L710
train
btcsuite/btcd
peer/peer.go
LastSend
func (p *Peer) LastSend() time.Time { return time.Unix(atomic.LoadInt64(&p.lastSend), 0) }
go
func (p *Peer) LastSend() time.Time { return time.Unix(atomic.LoadInt64(&p.lastSend), 0) }
[ "func", "(", "p", "*", "Peer", ")", "LastSend", "(", ")", "time", ".", "Time", "{", "return", "time", ".", "Unix", "(", "atomic", ".", "LoadInt64", "(", "&", "p", ".", "lastSend", ")", ",", "0", ")", "\n", "}" ]
// LastSend returns the last send time of the peer. // // This function is safe for concurrent access.
[ "LastSend", "returns", "the", "last", "send", "time", "of", "the", "peer", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L715-L717
train
btcsuite/btcd
peer/peer.go
LastRecv
func (p *Peer) LastRecv() time.Time { return time.Unix(atomic.LoadInt64(&p.lastRecv), 0) }
go
func (p *Peer) LastRecv() time.Time { return time.Unix(atomic.LoadInt64(&p.lastRecv), 0) }
[ "func", "(", "p", "*", "Peer", ")", "LastRecv", "(", ")", "time", ".", "Time", "{", "return", "time", ".", "Unix", "(", "atomic", ".", "LoadInt64", "(", "&", "p", ".", "lastRecv", ")", ",", "0", ")", "\n", "}" ]
// LastRecv returns the last recv time of the peer. // // This function is safe for concurrent access.
[ "LastRecv", "returns", "the", "last", "recv", "time", "of", "the", "peer", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L722-L724
train
btcsuite/btcd
peer/peer.go
LocalAddr
func (p *Peer) LocalAddr() net.Addr { var localAddr net.Addr if atomic.LoadInt32(&p.connected) != 0 { localAddr = p.conn.LocalAddr() } return localAddr }
go
func (p *Peer) LocalAddr() net.Addr { var localAddr net.Addr if atomic.LoadInt32(&p.connected) != 0 { localAddr = p.conn.LocalAddr() } return localAddr }
[ "func", "(", "p", "*", "Peer", ")", "LocalAddr", "(", ")", "net", ".", "Addr", "{", "var", "localAddr", "net", ".", "Addr", "\n", "if", "atomic", ".", "LoadInt32", "(", "&", "p", ".", "connected", ")", "!=", "0", "{", "localAddr", "=", "p", ".", "conn", ".", "LocalAddr", "(", ")", "\n", "}", "\n", "return", "localAddr", "\n", "}" ]
// LocalAddr returns the local address of the connection. // // This function is safe fo concurrent access.
[ "LocalAddr", "returns", "the", "local", "address", "of", "the", "connection", ".", "This", "function", "is", "safe", "fo", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L729-L735
train
btcsuite/btcd
peer/peer.go
TimeConnected
func (p *Peer) TimeConnected() time.Time { p.statsMtx.RLock() timeConnected := p.timeConnected p.statsMtx.RUnlock() return timeConnected }
go
func (p *Peer) TimeConnected() time.Time { p.statsMtx.RLock() timeConnected := p.timeConnected p.statsMtx.RUnlock() return timeConnected }
[ "func", "(", "p", "*", "Peer", ")", "TimeConnected", "(", ")", "time", ".", "Time", "{", "p", ".", "statsMtx", ".", "RLock", "(", ")", "\n", "timeConnected", ":=", "p", ".", "timeConnected", "\n", "p", ".", "statsMtx", ".", "RUnlock", "(", ")", "\n\n", "return", "timeConnected", "\n", "}" ]
// TimeConnected returns the time at which the peer connected. // // This function is safe for concurrent access.
[ "TimeConnected", "returns", "the", "time", "at", "which", "the", "peer", "connected", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L754-L760
train
btcsuite/btcd
peer/peer.go
TimeOffset
func (p *Peer) TimeOffset() int64 { p.statsMtx.RLock() timeOffset := p.timeOffset p.statsMtx.RUnlock() return timeOffset }
go
func (p *Peer) TimeOffset() int64 { p.statsMtx.RLock() timeOffset := p.timeOffset p.statsMtx.RUnlock() return timeOffset }
[ "func", "(", "p", "*", "Peer", ")", "TimeOffset", "(", ")", "int64", "{", "p", ".", "statsMtx", ".", "RLock", "(", ")", "\n", "timeOffset", ":=", "p", ".", "timeOffset", "\n", "p", ".", "statsMtx", ".", "RUnlock", "(", ")", "\n\n", "return", "timeOffset", "\n", "}" ]
// TimeOffset returns the number of seconds the local time was offset from the // time the peer reported during the initial negotiation phase. Negative values // indicate the remote peer's time is before the local time. // // This function is safe for concurrent access.
[ "TimeOffset", "returns", "the", "number", "of", "seconds", "the", "local", "time", "was", "offset", "from", "the", "time", "the", "peer", "reported", "during", "the", "initial", "negotiation", "phase", ".", "Negative", "values", "indicate", "the", "remote", "peer", "s", "time", "is", "before", "the", "local", "time", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L767-L773
train
btcsuite/btcd
peer/peer.go
StartingHeight
func (p *Peer) StartingHeight() int32 { p.statsMtx.RLock() startingHeight := p.startingHeight p.statsMtx.RUnlock() return startingHeight }
go
func (p *Peer) StartingHeight() int32 { p.statsMtx.RLock() startingHeight := p.startingHeight p.statsMtx.RUnlock() return startingHeight }
[ "func", "(", "p", "*", "Peer", ")", "StartingHeight", "(", ")", "int32", "{", "p", ".", "statsMtx", ".", "RLock", "(", ")", "\n", "startingHeight", ":=", "p", ".", "startingHeight", "\n", "p", ".", "statsMtx", ".", "RUnlock", "(", ")", "\n\n", "return", "startingHeight", "\n", "}" ]
// StartingHeight returns the last known height the peer reported during the // initial negotiation phase. // // This function is safe for concurrent access.
[ "StartingHeight", "returns", "the", "last", "known", "height", "the", "peer", "reported", "during", "the", "initial", "negotiation", "phase", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L779-L785
train
btcsuite/btcd
peer/peer.go
WantsHeaders
func (p *Peer) WantsHeaders() bool { p.flagsMtx.Lock() sendHeadersPreferred := p.sendHeadersPreferred p.flagsMtx.Unlock() return sendHeadersPreferred }
go
func (p *Peer) WantsHeaders() bool { p.flagsMtx.Lock() sendHeadersPreferred := p.sendHeadersPreferred p.flagsMtx.Unlock() return sendHeadersPreferred }
[ "func", "(", "p", "*", "Peer", ")", "WantsHeaders", "(", ")", "bool", "{", "p", ".", "flagsMtx", ".", "Lock", "(", ")", "\n", "sendHeadersPreferred", ":=", "p", ".", "sendHeadersPreferred", "\n", "p", ".", "flagsMtx", ".", "Unlock", "(", ")", "\n\n", "return", "sendHeadersPreferred", "\n", "}" ]
// WantsHeaders returns if the peer wants header messages instead of // inventory vectors for blocks. // // This function is safe for concurrent access.
[ "WantsHeaders", "returns", "if", "the", "peer", "wants", "header", "messages", "instead", "of", "inventory", "vectors", "for", "blocks", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L791-L797
train
btcsuite/btcd
peer/peer.go
IsWitnessEnabled
func (p *Peer) IsWitnessEnabled() bool { p.flagsMtx.Lock() witnessEnabled := p.witnessEnabled p.flagsMtx.Unlock() return witnessEnabled }
go
func (p *Peer) IsWitnessEnabled() bool { p.flagsMtx.Lock() witnessEnabled := p.witnessEnabled p.flagsMtx.Unlock() return witnessEnabled }
[ "func", "(", "p", "*", "Peer", ")", "IsWitnessEnabled", "(", ")", "bool", "{", "p", ".", "flagsMtx", ".", "Lock", "(", ")", "\n", "witnessEnabled", ":=", "p", ".", "witnessEnabled", "\n", "p", ".", "flagsMtx", ".", "Unlock", "(", ")", "\n\n", "return", "witnessEnabled", "\n", "}" ]
// IsWitnessEnabled returns true if the peer has signalled that it supports // segregated witness. // // This function is safe for concurrent access.
[ "IsWitnessEnabled", "returns", "true", "if", "the", "peer", "has", "signalled", "that", "it", "supports", "segregated", "witness", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L803-L809
train
btcsuite/btcd
peer/peer.go
PushAddrMsg
func (p *Peer) PushAddrMsg(addresses []*wire.NetAddress) ([]*wire.NetAddress, error) { addressCount := len(addresses) // Nothing to send. if addressCount == 0 { return nil, nil } msg := wire.NewMsgAddr() msg.AddrList = make([]*wire.NetAddress, addressCount) copy(msg.AddrList, addresses) // Randomize the addresses sent if there are more than the maximum allowed. if addressCount > wire.MaxAddrPerMsg { // Shuffle the address list. for i := 0; i < wire.MaxAddrPerMsg; i++ { j := i + rand.Intn(addressCount-i) msg.AddrList[i], msg.AddrList[j] = msg.AddrList[j], msg.AddrList[i] } // Truncate it to the maximum size. msg.AddrList = msg.AddrList[:wire.MaxAddrPerMsg] } p.QueueMessage(msg, nil) return msg.AddrList, nil }
go
func (p *Peer) PushAddrMsg(addresses []*wire.NetAddress) ([]*wire.NetAddress, error) { addressCount := len(addresses) // Nothing to send. if addressCount == 0 { return nil, nil } msg := wire.NewMsgAddr() msg.AddrList = make([]*wire.NetAddress, addressCount) copy(msg.AddrList, addresses) // Randomize the addresses sent if there are more than the maximum allowed. if addressCount > wire.MaxAddrPerMsg { // Shuffle the address list. for i := 0; i < wire.MaxAddrPerMsg; i++ { j := i + rand.Intn(addressCount-i) msg.AddrList[i], msg.AddrList[j] = msg.AddrList[j], msg.AddrList[i] } // Truncate it to the maximum size. msg.AddrList = msg.AddrList[:wire.MaxAddrPerMsg] } p.QueueMessage(msg, nil) return msg.AddrList, nil }
[ "func", "(", "p", "*", "Peer", ")", "PushAddrMsg", "(", "addresses", "[", "]", "*", "wire", ".", "NetAddress", ")", "(", "[", "]", "*", "wire", ".", "NetAddress", ",", "error", ")", "{", "addressCount", ":=", "len", "(", "addresses", ")", "\n\n", "// Nothing to send.", "if", "addressCount", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "msg", ":=", "wire", ".", "NewMsgAddr", "(", ")", "\n", "msg", ".", "AddrList", "=", "make", "(", "[", "]", "*", "wire", ".", "NetAddress", ",", "addressCount", ")", "\n", "copy", "(", "msg", ".", "AddrList", ",", "addresses", ")", "\n\n", "// Randomize the addresses sent if there are more than the maximum allowed.", "if", "addressCount", ">", "wire", ".", "MaxAddrPerMsg", "{", "// Shuffle the address list.", "for", "i", ":=", "0", ";", "i", "<", "wire", ".", "MaxAddrPerMsg", ";", "i", "++", "{", "j", ":=", "i", "+", "rand", ".", "Intn", "(", "addressCount", "-", "i", ")", "\n", "msg", ".", "AddrList", "[", "i", "]", ",", "msg", ".", "AddrList", "[", "j", "]", "=", "msg", ".", "AddrList", "[", "j", "]", ",", "msg", ".", "AddrList", "[", "i", "]", "\n", "}", "\n\n", "// Truncate it to the maximum size.", "msg", ".", "AddrList", "=", "msg", ".", "AddrList", "[", ":", "wire", ".", "MaxAddrPerMsg", "]", "\n", "}", "\n\n", "p", ".", "QueueMessage", "(", "msg", ",", "nil", ")", "\n", "return", "msg", ".", "AddrList", ",", "nil", "\n", "}" ]
// PushAddrMsg sends an addr message to the connected peer using the provided // addresses. This function is useful over manually sending the message via // QueueMessage since it automatically limits the addresses to the maximum // number allowed by the message and randomizes the chosen addresses when there // are too many. It returns the addresses that were actually sent and no // message will be sent if there are no entries in the provided addresses slice. // // This function is safe for concurrent access.
[ "PushAddrMsg", "sends", "an", "addr", "message", "to", "the", "connected", "peer", "using", "the", "provided", "addresses", ".", "This", "function", "is", "useful", "over", "manually", "sending", "the", "message", "via", "QueueMessage", "since", "it", "automatically", "limits", "the", "addresses", "to", "the", "maximum", "number", "allowed", "by", "the", "message", "and", "randomizes", "the", "chosen", "addresses", "when", "there", "are", "too", "many", ".", "It", "returns", "the", "addresses", "that", "were", "actually", "sent", "and", "no", "message", "will", "be", "sent", "if", "there", "are", "no", "entries", "in", "the", "provided", "addresses", "slice", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L819-L845
train
btcsuite/btcd
peer/peer.go
PushGetBlocksMsg
func (p *Peer) PushGetBlocksMsg(locator blockchain.BlockLocator, stopHash *chainhash.Hash) error { // Extract the begin hash from the block locator, if one was specified, // to use for filtering duplicate getblocks requests. var beginHash *chainhash.Hash if len(locator) > 0 { beginHash = locator[0] } // Filter duplicate getblocks requests. p.prevGetBlocksMtx.Lock() isDuplicate := p.prevGetBlocksStop != nil && p.prevGetBlocksBegin != nil && beginHash != nil && stopHash.IsEqual(p.prevGetBlocksStop) && beginHash.IsEqual(p.prevGetBlocksBegin) p.prevGetBlocksMtx.Unlock() if isDuplicate { log.Tracef("Filtering duplicate [getblocks] with begin "+ "hash %v, stop hash %v", beginHash, stopHash) return nil } // Construct the getblocks request and queue it to be sent. msg := wire.NewMsgGetBlocks(stopHash) for _, hash := range locator { err := msg.AddBlockLocatorHash(hash) if err != nil { return err } } p.QueueMessage(msg, nil) // Update the previous getblocks request information for filtering // duplicates. p.prevGetBlocksMtx.Lock() p.prevGetBlocksBegin = beginHash p.prevGetBlocksStop = stopHash p.prevGetBlocksMtx.Unlock() return nil }
go
func (p *Peer) PushGetBlocksMsg(locator blockchain.BlockLocator, stopHash *chainhash.Hash) error { // Extract the begin hash from the block locator, if one was specified, // to use for filtering duplicate getblocks requests. var beginHash *chainhash.Hash if len(locator) > 0 { beginHash = locator[0] } // Filter duplicate getblocks requests. p.prevGetBlocksMtx.Lock() isDuplicate := p.prevGetBlocksStop != nil && p.prevGetBlocksBegin != nil && beginHash != nil && stopHash.IsEqual(p.prevGetBlocksStop) && beginHash.IsEqual(p.prevGetBlocksBegin) p.prevGetBlocksMtx.Unlock() if isDuplicate { log.Tracef("Filtering duplicate [getblocks] with begin "+ "hash %v, stop hash %v", beginHash, stopHash) return nil } // Construct the getblocks request and queue it to be sent. msg := wire.NewMsgGetBlocks(stopHash) for _, hash := range locator { err := msg.AddBlockLocatorHash(hash) if err != nil { return err } } p.QueueMessage(msg, nil) // Update the previous getblocks request information for filtering // duplicates. p.prevGetBlocksMtx.Lock() p.prevGetBlocksBegin = beginHash p.prevGetBlocksStop = stopHash p.prevGetBlocksMtx.Unlock() return nil }
[ "func", "(", "p", "*", "Peer", ")", "PushGetBlocksMsg", "(", "locator", "blockchain", ".", "BlockLocator", ",", "stopHash", "*", "chainhash", ".", "Hash", ")", "error", "{", "// Extract the begin hash from the block locator, if one was specified,", "// to use for filtering duplicate getblocks requests.", "var", "beginHash", "*", "chainhash", ".", "Hash", "\n", "if", "len", "(", "locator", ")", ">", "0", "{", "beginHash", "=", "locator", "[", "0", "]", "\n", "}", "\n\n", "// Filter duplicate getblocks requests.", "p", ".", "prevGetBlocksMtx", ".", "Lock", "(", ")", "\n", "isDuplicate", ":=", "p", ".", "prevGetBlocksStop", "!=", "nil", "&&", "p", ".", "prevGetBlocksBegin", "!=", "nil", "&&", "beginHash", "!=", "nil", "&&", "stopHash", ".", "IsEqual", "(", "p", ".", "prevGetBlocksStop", ")", "&&", "beginHash", ".", "IsEqual", "(", "p", ".", "prevGetBlocksBegin", ")", "\n", "p", ".", "prevGetBlocksMtx", ".", "Unlock", "(", ")", "\n\n", "if", "isDuplicate", "{", "log", ".", "Tracef", "(", "\"", "\"", "+", "\"", "\"", ",", "beginHash", ",", "stopHash", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// Construct the getblocks request and queue it to be sent.", "msg", ":=", "wire", ".", "NewMsgGetBlocks", "(", "stopHash", ")", "\n", "for", "_", ",", "hash", ":=", "range", "locator", "{", "err", ":=", "msg", ".", "AddBlockLocatorHash", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "p", ".", "QueueMessage", "(", "msg", ",", "nil", ")", "\n\n", "// Update the previous getblocks request information for filtering", "// duplicates.", "p", ".", "prevGetBlocksMtx", ".", "Lock", "(", ")", "\n", "p", ".", "prevGetBlocksBegin", "=", "beginHash", "\n", "p", ".", "prevGetBlocksStop", "=", "stopHash", "\n", "p", ".", "prevGetBlocksMtx", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// PushGetBlocksMsg sends a getblocks message for the provided block locator // and stop hash. It will ignore back-to-back duplicate requests. // // This function is safe for concurrent access.
[ "PushGetBlocksMsg", "sends", "a", "getblocks", "message", "for", "the", "provided", "block", "locator", "and", "stop", "hash", ".", "It", "will", "ignore", "back", "-", "to", "-", "back", "duplicate", "requests", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L851-L889
train
btcsuite/btcd
peer/peer.go
PushGetHeadersMsg
func (p *Peer) PushGetHeadersMsg(locator blockchain.BlockLocator, stopHash *chainhash.Hash) error { // Extract the begin hash from the block locator, if one was specified, // to use for filtering duplicate getheaders requests. var beginHash *chainhash.Hash if len(locator) > 0 { beginHash = locator[0] } // Filter duplicate getheaders requests. p.prevGetHdrsMtx.Lock() isDuplicate := p.prevGetHdrsStop != nil && p.prevGetHdrsBegin != nil && beginHash != nil && stopHash.IsEqual(p.prevGetHdrsStop) && beginHash.IsEqual(p.prevGetHdrsBegin) p.prevGetHdrsMtx.Unlock() if isDuplicate { log.Tracef("Filtering duplicate [getheaders] with begin hash %v", beginHash) return nil } // Construct the getheaders request and queue it to be sent. msg := wire.NewMsgGetHeaders() msg.HashStop = *stopHash for _, hash := range locator { err := msg.AddBlockLocatorHash(hash) if err != nil { return err } } p.QueueMessage(msg, nil) // Update the previous getheaders request information for filtering // duplicates. p.prevGetHdrsMtx.Lock() p.prevGetHdrsBegin = beginHash p.prevGetHdrsStop = stopHash p.prevGetHdrsMtx.Unlock() return nil }
go
func (p *Peer) PushGetHeadersMsg(locator blockchain.BlockLocator, stopHash *chainhash.Hash) error { // Extract the begin hash from the block locator, if one was specified, // to use for filtering duplicate getheaders requests. var beginHash *chainhash.Hash if len(locator) > 0 { beginHash = locator[0] } // Filter duplicate getheaders requests. p.prevGetHdrsMtx.Lock() isDuplicate := p.prevGetHdrsStop != nil && p.prevGetHdrsBegin != nil && beginHash != nil && stopHash.IsEqual(p.prevGetHdrsStop) && beginHash.IsEqual(p.prevGetHdrsBegin) p.prevGetHdrsMtx.Unlock() if isDuplicate { log.Tracef("Filtering duplicate [getheaders] with begin hash %v", beginHash) return nil } // Construct the getheaders request and queue it to be sent. msg := wire.NewMsgGetHeaders() msg.HashStop = *stopHash for _, hash := range locator { err := msg.AddBlockLocatorHash(hash) if err != nil { return err } } p.QueueMessage(msg, nil) // Update the previous getheaders request information for filtering // duplicates. p.prevGetHdrsMtx.Lock() p.prevGetHdrsBegin = beginHash p.prevGetHdrsStop = stopHash p.prevGetHdrsMtx.Unlock() return nil }
[ "func", "(", "p", "*", "Peer", ")", "PushGetHeadersMsg", "(", "locator", "blockchain", ".", "BlockLocator", ",", "stopHash", "*", "chainhash", ".", "Hash", ")", "error", "{", "// Extract the begin hash from the block locator, if one was specified,", "// to use for filtering duplicate getheaders requests.", "var", "beginHash", "*", "chainhash", ".", "Hash", "\n", "if", "len", "(", "locator", ")", ">", "0", "{", "beginHash", "=", "locator", "[", "0", "]", "\n", "}", "\n\n", "// Filter duplicate getheaders requests.", "p", ".", "prevGetHdrsMtx", ".", "Lock", "(", ")", "\n", "isDuplicate", ":=", "p", ".", "prevGetHdrsStop", "!=", "nil", "&&", "p", ".", "prevGetHdrsBegin", "!=", "nil", "&&", "beginHash", "!=", "nil", "&&", "stopHash", ".", "IsEqual", "(", "p", ".", "prevGetHdrsStop", ")", "&&", "beginHash", ".", "IsEqual", "(", "p", ".", "prevGetHdrsBegin", ")", "\n", "p", ".", "prevGetHdrsMtx", ".", "Unlock", "(", ")", "\n\n", "if", "isDuplicate", "{", "log", ".", "Tracef", "(", "\"", "\"", ",", "beginHash", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// Construct the getheaders request and queue it to be sent.", "msg", ":=", "wire", ".", "NewMsgGetHeaders", "(", ")", "\n", "msg", ".", "HashStop", "=", "*", "stopHash", "\n", "for", "_", ",", "hash", ":=", "range", "locator", "{", "err", ":=", "msg", ".", "AddBlockLocatorHash", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "p", ".", "QueueMessage", "(", "msg", ",", "nil", ")", "\n\n", "// Update the previous getheaders request information for filtering", "// duplicates.", "p", ".", "prevGetHdrsMtx", ".", "Lock", "(", ")", "\n", "p", ".", "prevGetHdrsBegin", "=", "beginHash", "\n", "p", ".", "prevGetHdrsStop", "=", "stopHash", "\n", "p", ".", "prevGetHdrsMtx", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// PushGetHeadersMsg sends a getblocks message for the provided block locator // and stop hash. It will ignore back-to-back duplicate requests. // // This function is safe for concurrent access.
[ "PushGetHeadersMsg", "sends", "a", "getblocks", "message", "for", "the", "provided", "block", "locator", "and", "stop", "hash", ".", "It", "will", "ignore", "back", "-", "to", "-", "back", "duplicate", "requests", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L895-L934
train
btcsuite/btcd
peer/peer.go
PushRejectMsg
func (p *Peer) PushRejectMsg(command string, code wire.RejectCode, reason string, hash *chainhash.Hash, wait bool) { // Don't bother sending the reject message if the protocol version // is too low. if p.VersionKnown() && p.ProtocolVersion() < wire.RejectVersion { return } msg := wire.NewMsgReject(command, code, reason) if command == wire.CmdTx || command == wire.CmdBlock { if hash == nil { log.Warnf("Sending a reject message for command "+ "type %v which should have specified a hash "+ "but does not", command) hash = &zeroHash } msg.Hash = *hash } // Send the message without waiting if the caller has not requested it. if !wait { p.QueueMessage(msg, nil) return } // Send the message and block until it has been sent before returning. doneChan := make(chan struct{}, 1) p.QueueMessage(msg, doneChan) <-doneChan }
go
func (p *Peer) PushRejectMsg(command string, code wire.RejectCode, reason string, hash *chainhash.Hash, wait bool) { // Don't bother sending the reject message if the protocol version // is too low. if p.VersionKnown() && p.ProtocolVersion() < wire.RejectVersion { return } msg := wire.NewMsgReject(command, code, reason) if command == wire.CmdTx || command == wire.CmdBlock { if hash == nil { log.Warnf("Sending a reject message for command "+ "type %v which should have specified a hash "+ "but does not", command) hash = &zeroHash } msg.Hash = *hash } // Send the message without waiting if the caller has not requested it. if !wait { p.QueueMessage(msg, nil) return } // Send the message and block until it has been sent before returning. doneChan := make(chan struct{}, 1) p.QueueMessage(msg, doneChan) <-doneChan }
[ "func", "(", "p", "*", "Peer", ")", "PushRejectMsg", "(", "command", "string", ",", "code", "wire", ".", "RejectCode", ",", "reason", "string", ",", "hash", "*", "chainhash", ".", "Hash", ",", "wait", "bool", ")", "{", "// Don't bother sending the reject message if the protocol version", "// is too low.", "if", "p", ".", "VersionKnown", "(", ")", "&&", "p", ".", "ProtocolVersion", "(", ")", "<", "wire", ".", "RejectVersion", "{", "return", "\n", "}", "\n\n", "msg", ":=", "wire", ".", "NewMsgReject", "(", "command", ",", "code", ",", "reason", ")", "\n", "if", "command", "==", "wire", ".", "CmdTx", "||", "command", "==", "wire", ".", "CmdBlock", "{", "if", "hash", "==", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "command", ")", "\n", "hash", "=", "&", "zeroHash", "\n", "}", "\n", "msg", ".", "Hash", "=", "*", "hash", "\n", "}", "\n\n", "// Send the message without waiting if the caller has not requested it.", "if", "!", "wait", "{", "p", ".", "QueueMessage", "(", "msg", ",", "nil", ")", "\n", "return", "\n", "}", "\n\n", "// Send the message and block until it has been sent before returning.", "doneChan", ":=", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", "\n", "p", ".", "QueueMessage", "(", "msg", ",", "doneChan", ")", "\n", "<-", "doneChan", "\n", "}" ]
// PushRejectMsg sends a reject message for the provided command, reject code, // reject reason, and hash. The hash will only be used when the command is a tx // or block and should be nil in other cases. The wait parameter will cause the // function to block until the reject message has actually been sent. // // This function is safe for concurrent access.
[ "PushRejectMsg", "sends", "a", "reject", "message", "for", "the", "provided", "command", "reject", "code", "reject", "reason", "and", "hash", ".", "The", "hash", "will", "only", "be", "used", "when", "the", "command", "is", "a", "tx", "or", "block", "and", "should", "be", "nil", "in", "other", "cases", ".", "The", "wait", "parameter", "will", "cause", "the", "function", "to", "block", "until", "the", "reject", "message", "has", "actually", "been", "sent", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L942-L970
train
btcsuite/btcd
peer/peer.go
readMessage
func (p *Peer) readMessage(encoding wire.MessageEncoding) (wire.Message, []byte, error) { n, msg, buf, err := wire.ReadMessageWithEncodingN(p.conn, p.ProtocolVersion(), p.cfg.ChainParams.Net, encoding) atomic.AddUint64(&p.bytesReceived, uint64(n)) if p.cfg.Listeners.OnRead != nil { p.cfg.Listeners.OnRead(p, n, msg, err) } if err != nil { return nil, nil, err } // Use closures to log expensive operations so they are only run when // the logging level requires it. log.Debugf("%v", newLogClosure(func() string { // Debug summary of message. summary := messageSummary(msg) if len(summary) > 0 { summary = " (" + summary + ")" } return fmt.Sprintf("Received %v%s from %s", msg.Command(), summary, p) })) log.Tracef("%v", newLogClosure(func() string { return spew.Sdump(msg) })) log.Tracef("%v", newLogClosure(func() string { return spew.Sdump(buf) })) return msg, buf, nil }
go
func (p *Peer) readMessage(encoding wire.MessageEncoding) (wire.Message, []byte, error) { n, msg, buf, err := wire.ReadMessageWithEncodingN(p.conn, p.ProtocolVersion(), p.cfg.ChainParams.Net, encoding) atomic.AddUint64(&p.bytesReceived, uint64(n)) if p.cfg.Listeners.OnRead != nil { p.cfg.Listeners.OnRead(p, n, msg, err) } if err != nil { return nil, nil, err } // Use closures to log expensive operations so they are only run when // the logging level requires it. log.Debugf("%v", newLogClosure(func() string { // Debug summary of message. summary := messageSummary(msg) if len(summary) > 0 { summary = " (" + summary + ")" } return fmt.Sprintf("Received %v%s from %s", msg.Command(), summary, p) })) log.Tracef("%v", newLogClosure(func() string { return spew.Sdump(msg) })) log.Tracef("%v", newLogClosure(func() string { return spew.Sdump(buf) })) return msg, buf, nil }
[ "func", "(", "p", "*", "Peer", ")", "readMessage", "(", "encoding", "wire", ".", "MessageEncoding", ")", "(", "wire", ".", "Message", ",", "[", "]", "byte", ",", "error", ")", "{", "n", ",", "msg", ",", "buf", ",", "err", ":=", "wire", ".", "ReadMessageWithEncodingN", "(", "p", ".", "conn", ",", "p", ".", "ProtocolVersion", "(", ")", ",", "p", ".", "cfg", ".", "ChainParams", ".", "Net", ",", "encoding", ")", "\n", "atomic", ".", "AddUint64", "(", "&", "p", ".", "bytesReceived", ",", "uint64", "(", "n", ")", ")", "\n", "if", "p", ".", "cfg", ".", "Listeners", ".", "OnRead", "!=", "nil", "{", "p", ".", "cfg", ".", "Listeners", ".", "OnRead", "(", "p", ",", "n", ",", "msg", ",", "err", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// Use closures to log expensive operations so they are only run when", "// the logging level requires it.", "log", ".", "Debugf", "(", "\"", "\"", ",", "newLogClosure", "(", "func", "(", ")", "string", "{", "// Debug summary of message.", "summary", ":=", "messageSummary", "(", "msg", ")", "\n", "if", "len", "(", "summary", ")", ">", "0", "{", "summary", "=", "\"", "\"", "+", "summary", "+", "\"", "\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ".", "Command", "(", ")", ",", "summary", ",", "p", ")", "\n", "}", ")", ")", "\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "newLogClosure", "(", "func", "(", ")", "string", "{", "return", "spew", ".", "Sdump", "(", "msg", ")", "\n", "}", ")", ")", "\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "newLogClosure", "(", "func", "(", ")", "string", "{", "return", "spew", ".", "Sdump", "(", "buf", ")", "\n", "}", ")", ")", "\n\n", "return", "msg", ",", "buf", ",", "nil", "\n", "}" ]
// readMessage reads the next bitcoin message from the peer with logging.
[ "readMessage", "reads", "the", "next", "bitcoin", "message", "from", "the", "peer", "with", "logging", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L1008-L1038
train
btcsuite/btcd
peer/peer.go
writeMessage
func (p *Peer) writeMessage(msg wire.Message, enc wire.MessageEncoding) error { // Don't do anything if we're disconnecting. if atomic.LoadInt32(&p.disconnect) != 0 { return nil } // Use closures to log expensive operations so they are only run when // the logging level requires it. log.Debugf("%v", newLogClosure(func() string { // Debug summary of message. summary := messageSummary(msg) if len(summary) > 0 { summary = " (" + summary + ")" } return fmt.Sprintf("Sending %v%s to %s", msg.Command(), summary, p) })) log.Tracef("%v", newLogClosure(func() string { return spew.Sdump(msg) })) log.Tracef("%v", newLogClosure(func() string { var buf bytes.Buffer _, err := wire.WriteMessageWithEncodingN(&buf, msg, p.ProtocolVersion(), p.cfg.ChainParams.Net, enc) if err != nil { return err.Error() } return spew.Sdump(buf.Bytes()) })) // Write the message to the peer. n, err := wire.WriteMessageWithEncodingN(p.conn, msg, p.ProtocolVersion(), p.cfg.ChainParams.Net, enc) atomic.AddUint64(&p.bytesSent, uint64(n)) if p.cfg.Listeners.OnWrite != nil { p.cfg.Listeners.OnWrite(p, n, msg, err) } return err }
go
func (p *Peer) writeMessage(msg wire.Message, enc wire.MessageEncoding) error { // Don't do anything if we're disconnecting. if atomic.LoadInt32(&p.disconnect) != 0 { return nil } // Use closures to log expensive operations so they are only run when // the logging level requires it. log.Debugf("%v", newLogClosure(func() string { // Debug summary of message. summary := messageSummary(msg) if len(summary) > 0 { summary = " (" + summary + ")" } return fmt.Sprintf("Sending %v%s to %s", msg.Command(), summary, p) })) log.Tracef("%v", newLogClosure(func() string { return spew.Sdump(msg) })) log.Tracef("%v", newLogClosure(func() string { var buf bytes.Buffer _, err := wire.WriteMessageWithEncodingN(&buf, msg, p.ProtocolVersion(), p.cfg.ChainParams.Net, enc) if err != nil { return err.Error() } return spew.Sdump(buf.Bytes()) })) // Write the message to the peer. n, err := wire.WriteMessageWithEncodingN(p.conn, msg, p.ProtocolVersion(), p.cfg.ChainParams.Net, enc) atomic.AddUint64(&p.bytesSent, uint64(n)) if p.cfg.Listeners.OnWrite != nil { p.cfg.Listeners.OnWrite(p, n, msg, err) } return err }
[ "func", "(", "p", "*", "Peer", ")", "writeMessage", "(", "msg", "wire", ".", "Message", ",", "enc", "wire", ".", "MessageEncoding", ")", "error", "{", "// Don't do anything if we're disconnecting.", "if", "atomic", ".", "LoadInt32", "(", "&", "p", ".", "disconnect", ")", "!=", "0", "{", "return", "nil", "\n", "}", "\n\n", "// Use closures to log expensive operations so they are only run when", "// the logging level requires it.", "log", ".", "Debugf", "(", "\"", "\"", ",", "newLogClosure", "(", "func", "(", ")", "string", "{", "// Debug summary of message.", "summary", ":=", "messageSummary", "(", "msg", ")", "\n", "if", "len", "(", "summary", ")", ">", "0", "{", "summary", "=", "\"", "\"", "+", "summary", "+", "\"", "\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ".", "Command", "(", ")", ",", "summary", ",", "p", ")", "\n", "}", ")", ")", "\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "newLogClosure", "(", "func", "(", ")", "string", "{", "return", "spew", ".", "Sdump", "(", "msg", ")", "\n", "}", ")", ")", "\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "newLogClosure", "(", "func", "(", ")", "string", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "_", ",", "err", ":=", "wire", ".", "WriteMessageWithEncodingN", "(", "&", "buf", ",", "msg", ",", "p", ".", "ProtocolVersion", "(", ")", ",", "p", ".", "cfg", ".", "ChainParams", ".", "Net", ",", "enc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Error", "(", ")", "\n", "}", "\n", "return", "spew", ".", "Sdump", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "}", ")", ")", "\n\n", "// Write the message to the peer.", "n", ",", "err", ":=", "wire", ".", "WriteMessageWithEncodingN", "(", "p", ".", "conn", ",", "msg", ",", "p", ".", "ProtocolVersion", "(", ")", ",", "p", ".", "cfg", ".", "ChainParams", ".", "Net", ",", "enc", ")", "\n", "atomic", ".", "AddUint64", "(", "&", "p", ".", "bytesSent", ",", "uint64", "(", "n", ")", ")", "\n", "if", "p", ".", "cfg", ".", "Listeners", ".", "OnWrite", "!=", "nil", "{", "p", ".", "cfg", ".", "Listeners", ".", "OnWrite", "(", "p", ",", "n", ",", "msg", ",", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// writeMessage sends a bitcoin message to the peer with logging.
[ "writeMessage", "sends", "a", "bitcoin", "message", "to", "the", "peer", "with", "logging", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L1041-L1079
train
btcsuite/btcd
peer/peer.go
isAllowedReadError
func (p *Peer) isAllowedReadError(err error) bool { // Only allow read errors in regression test mode. if p.cfg.ChainParams.Net != wire.TestNet { return false } // Don't allow the error if it's not specifically a malformed message error. if _, ok := err.(*wire.MessageError); !ok { return false } // Don't allow the error if it's not coming from localhost or the // hostname can't be determined for some reason. host, _, err := net.SplitHostPort(p.addr) if err != nil { return false } if host != "127.0.0.1" && host != "localhost" { return false } // Allowed if all checks passed. return true }
go
func (p *Peer) isAllowedReadError(err error) bool { // Only allow read errors in regression test mode. if p.cfg.ChainParams.Net != wire.TestNet { return false } // Don't allow the error if it's not specifically a malformed message error. if _, ok := err.(*wire.MessageError); !ok { return false } // Don't allow the error if it's not coming from localhost or the // hostname can't be determined for some reason. host, _, err := net.SplitHostPort(p.addr) if err != nil { return false } if host != "127.0.0.1" && host != "localhost" { return false } // Allowed if all checks passed. return true }
[ "func", "(", "p", "*", "Peer", ")", "isAllowedReadError", "(", "err", "error", ")", "bool", "{", "// Only allow read errors in regression test mode.", "if", "p", ".", "cfg", ".", "ChainParams", ".", "Net", "!=", "wire", ".", "TestNet", "{", "return", "false", "\n", "}", "\n\n", "// Don't allow the error if it's not specifically a malformed message error.", "if", "_", ",", "ok", ":=", "err", ".", "(", "*", "wire", ".", "MessageError", ")", ";", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "// Don't allow the error if it's not coming from localhost or the", "// hostname can't be determined for some reason.", "host", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "p", ".", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "if", "host", "!=", "\"", "\"", "&&", "host", "!=", "\"", "\"", "{", "return", "false", "\n", "}", "\n\n", "// Allowed if all checks passed.", "return", "true", "\n", "}" ]
// isAllowedReadError returns whether or not the passed error is allowed without // disconnecting the peer. In particular, regression tests need to be allowed // to send malformed messages without the peer being disconnected.
[ "isAllowedReadError", "returns", "whether", "or", "not", "the", "passed", "error", "is", "allowed", "without", "disconnecting", "the", "peer", ".", "In", "particular", "regression", "tests", "need", "to", "be", "allowed", "to", "send", "malformed", "messages", "without", "the", "peer", "being", "disconnected", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L1084-L1108
train
btcsuite/btcd
peer/peer.go
maybeAddDeadline
func (p *Peer) maybeAddDeadline(pendingResponses map[string]time.Time, msgCmd string) { // Setup a deadline for each message being sent that expects a response. // // NOTE: Pings are intentionally ignored here since they are typically // sent asynchronously and as a result of a long backlock of messages, // such as is typical in the case of initial block download, the // response won't be received in time. deadline := time.Now().Add(stallResponseTimeout) switch msgCmd { case wire.CmdVersion: // Expects a verack message. pendingResponses[wire.CmdVerAck] = deadline case wire.CmdMemPool: // Expects an inv message. pendingResponses[wire.CmdInv] = deadline case wire.CmdGetBlocks: // Expects an inv message. pendingResponses[wire.CmdInv] = deadline case wire.CmdGetData: // Expects a block, merkleblock, tx, or notfound message. pendingResponses[wire.CmdBlock] = deadline pendingResponses[wire.CmdMerkleBlock] = deadline pendingResponses[wire.CmdTx] = deadline pendingResponses[wire.CmdNotFound] = deadline case wire.CmdGetHeaders: // Expects a headers message. Use a longer deadline since it // can take a while for the remote peer to load all of the // headers. deadline = time.Now().Add(stallResponseTimeout * 3) pendingResponses[wire.CmdHeaders] = deadline } }
go
func (p *Peer) maybeAddDeadline(pendingResponses map[string]time.Time, msgCmd string) { // Setup a deadline for each message being sent that expects a response. // // NOTE: Pings are intentionally ignored here since they are typically // sent asynchronously and as a result of a long backlock of messages, // such as is typical in the case of initial block download, the // response won't be received in time. deadline := time.Now().Add(stallResponseTimeout) switch msgCmd { case wire.CmdVersion: // Expects a verack message. pendingResponses[wire.CmdVerAck] = deadline case wire.CmdMemPool: // Expects an inv message. pendingResponses[wire.CmdInv] = deadline case wire.CmdGetBlocks: // Expects an inv message. pendingResponses[wire.CmdInv] = deadline case wire.CmdGetData: // Expects a block, merkleblock, tx, or notfound message. pendingResponses[wire.CmdBlock] = deadline pendingResponses[wire.CmdMerkleBlock] = deadline pendingResponses[wire.CmdTx] = deadline pendingResponses[wire.CmdNotFound] = deadline case wire.CmdGetHeaders: // Expects a headers message. Use a longer deadline since it // can take a while for the remote peer to load all of the // headers. deadline = time.Now().Add(stallResponseTimeout * 3) pendingResponses[wire.CmdHeaders] = deadline } }
[ "func", "(", "p", "*", "Peer", ")", "maybeAddDeadline", "(", "pendingResponses", "map", "[", "string", "]", "time", ".", "Time", ",", "msgCmd", "string", ")", "{", "// Setup a deadline for each message being sent that expects a response.", "//", "// NOTE: Pings are intentionally ignored here since they are typically", "// sent asynchronously and as a result of a long backlock of messages,", "// such as is typical in the case of initial block download, the", "// response won't be received in time.", "deadline", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "stallResponseTimeout", ")", "\n", "switch", "msgCmd", "{", "case", "wire", ".", "CmdVersion", ":", "// Expects a verack message.", "pendingResponses", "[", "wire", ".", "CmdVerAck", "]", "=", "deadline", "\n\n", "case", "wire", ".", "CmdMemPool", ":", "// Expects an inv message.", "pendingResponses", "[", "wire", ".", "CmdInv", "]", "=", "deadline", "\n\n", "case", "wire", ".", "CmdGetBlocks", ":", "// Expects an inv message.", "pendingResponses", "[", "wire", ".", "CmdInv", "]", "=", "deadline", "\n\n", "case", "wire", ".", "CmdGetData", ":", "// Expects a block, merkleblock, tx, or notfound message.", "pendingResponses", "[", "wire", ".", "CmdBlock", "]", "=", "deadline", "\n", "pendingResponses", "[", "wire", ".", "CmdMerkleBlock", "]", "=", "deadline", "\n", "pendingResponses", "[", "wire", ".", "CmdTx", "]", "=", "deadline", "\n", "pendingResponses", "[", "wire", ".", "CmdNotFound", "]", "=", "deadline", "\n\n", "case", "wire", ".", "CmdGetHeaders", ":", "// Expects a headers message. Use a longer deadline since it", "// can take a while for the remote peer to load all of the", "// headers.", "deadline", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "stallResponseTimeout", "*", "3", ")", "\n", "pendingResponses", "[", "wire", ".", "CmdHeaders", "]", "=", "deadline", "\n", "}", "\n", "}" ]
// maybeAddDeadline potentially adds a deadline for the appropriate expected // response for the passed wire protocol command to the pending responses map.
[ "maybeAddDeadline", "potentially", "adds", "a", "deadline", "for", "the", "appropriate", "expected", "response", "for", "the", "passed", "wire", "protocol", "command", "to", "the", "pending", "responses", "map", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L1134-L1169
train
btcsuite/btcd
peer/peer.go
stallHandler
func (p *Peer) stallHandler() { // These variables are used to adjust the deadline times forward by the // time it takes callbacks to execute. This is done because new // messages aren't read until the previous one is finished processing // (which includes callbacks), so the deadline for receiving a response // for a given message must account for the processing time as well. var handlerActive bool var handlersStartTime time.Time var deadlineOffset time.Duration // pendingResponses tracks the expected response deadline times. pendingResponses := make(map[string]time.Time) // stallTicker is used to periodically check pending responses that have // exceeded the expected deadline and disconnect the peer due to // stalling. stallTicker := time.NewTicker(stallTickInterval) defer stallTicker.Stop() // ioStopped is used to detect when both the input and output handler // goroutines are done. var ioStopped bool out: for { select { case msg := <-p.stallControl: switch msg.command { case sccSendMessage: // Add a deadline for the expected response // message if needed. p.maybeAddDeadline(pendingResponses, msg.message.Command()) case sccReceiveMessage: // Remove received messages from the expected // response map. Since certain commands expect // one of a group of responses, remove // everything in the expected group accordingly. switch msgCmd := msg.message.Command(); msgCmd { case wire.CmdBlock: fallthrough case wire.CmdMerkleBlock: fallthrough case wire.CmdTx: fallthrough case wire.CmdNotFound: delete(pendingResponses, wire.CmdBlock) delete(pendingResponses, wire.CmdMerkleBlock) delete(pendingResponses, wire.CmdTx) delete(pendingResponses, wire.CmdNotFound) default: delete(pendingResponses, msgCmd) } case sccHandlerStart: // Warn on unbalanced callback signalling. if handlerActive { log.Warn("Received handler start " + "control command while a " + "handler is already active") continue } handlerActive = true handlersStartTime = time.Now() case sccHandlerDone: // Warn on unbalanced callback signalling. if !handlerActive { log.Warn("Received handler done " + "control command when a " + "handler is not already active") continue } // Extend active deadlines by the time it took // to execute the callback. duration := time.Since(handlersStartTime) deadlineOffset += duration handlerActive = false default: log.Warnf("Unsupported message command %v", msg.command) } case <-stallTicker.C: // Calculate the offset to apply to the deadline based // on how long the handlers have taken to execute since // the last tick. now := time.Now() offset := deadlineOffset if handlerActive { offset += now.Sub(handlersStartTime) } // Disconnect the peer if any of the pending responses // don't arrive by their adjusted deadline. for command, deadline := range pendingResponses { if now.Before(deadline.Add(offset)) { continue } log.Debugf("Peer %s appears to be stalled or "+ "misbehaving, %s timeout -- "+ "disconnecting", p, command) p.Disconnect() break } // Reset the deadline offset for the next tick. deadlineOffset = 0 case <-p.inQuit: // The stall handler can exit once both the input and // output handler goroutines are done. if ioStopped { break out } ioStopped = true case <-p.outQuit: // The stall handler can exit once both the input and // output handler goroutines are done. if ioStopped { break out } ioStopped = true } } // Drain any wait channels before going away so there is nothing left // waiting on this goroutine. cleanup: for { select { case <-p.stallControl: default: break cleanup } } log.Tracef("Peer stall handler done for %s", p) }
go
func (p *Peer) stallHandler() { // These variables are used to adjust the deadline times forward by the // time it takes callbacks to execute. This is done because new // messages aren't read until the previous one is finished processing // (which includes callbacks), so the deadline for receiving a response // for a given message must account for the processing time as well. var handlerActive bool var handlersStartTime time.Time var deadlineOffset time.Duration // pendingResponses tracks the expected response deadline times. pendingResponses := make(map[string]time.Time) // stallTicker is used to periodically check pending responses that have // exceeded the expected deadline and disconnect the peer due to // stalling. stallTicker := time.NewTicker(stallTickInterval) defer stallTicker.Stop() // ioStopped is used to detect when both the input and output handler // goroutines are done. var ioStopped bool out: for { select { case msg := <-p.stallControl: switch msg.command { case sccSendMessage: // Add a deadline for the expected response // message if needed. p.maybeAddDeadline(pendingResponses, msg.message.Command()) case sccReceiveMessage: // Remove received messages from the expected // response map. Since certain commands expect // one of a group of responses, remove // everything in the expected group accordingly. switch msgCmd := msg.message.Command(); msgCmd { case wire.CmdBlock: fallthrough case wire.CmdMerkleBlock: fallthrough case wire.CmdTx: fallthrough case wire.CmdNotFound: delete(pendingResponses, wire.CmdBlock) delete(pendingResponses, wire.CmdMerkleBlock) delete(pendingResponses, wire.CmdTx) delete(pendingResponses, wire.CmdNotFound) default: delete(pendingResponses, msgCmd) } case sccHandlerStart: // Warn on unbalanced callback signalling. if handlerActive { log.Warn("Received handler start " + "control command while a " + "handler is already active") continue } handlerActive = true handlersStartTime = time.Now() case sccHandlerDone: // Warn on unbalanced callback signalling. if !handlerActive { log.Warn("Received handler done " + "control command when a " + "handler is not already active") continue } // Extend active deadlines by the time it took // to execute the callback. duration := time.Since(handlersStartTime) deadlineOffset += duration handlerActive = false default: log.Warnf("Unsupported message command %v", msg.command) } case <-stallTicker.C: // Calculate the offset to apply to the deadline based // on how long the handlers have taken to execute since // the last tick. now := time.Now() offset := deadlineOffset if handlerActive { offset += now.Sub(handlersStartTime) } // Disconnect the peer if any of the pending responses // don't arrive by their adjusted deadline. for command, deadline := range pendingResponses { if now.Before(deadline.Add(offset)) { continue } log.Debugf("Peer %s appears to be stalled or "+ "misbehaving, %s timeout -- "+ "disconnecting", p, command) p.Disconnect() break } // Reset the deadline offset for the next tick. deadlineOffset = 0 case <-p.inQuit: // The stall handler can exit once both the input and // output handler goroutines are done. if ioStopped { break out } ioStopped = true case <-p.outQuit: // The stall handler can exit once both the input and // output handler goroutines are done. if ioStopped { break out } ioStopped = true } } // Drain any wait channels before going away so there is nothing left // waiting on this goroutine. cleanup: for { select { case <-p.stallControl: default: break cleanup } } log.Tracef("Peer stall handler done for %s", p) }
[ "func", "(", "p", "*", "Peer", ")", "stallHandler", "(", ")", "{", "// These variables are used to adjust the deadline times forward by the", "// time it takes callbacks to execute. This is done because new", "// messages aren't read until the previous one is finished processing", "// (which includes callbacks), so the deadline for receiving a response", "// for a given message must account for the processing time as well.", "var", "handlerActive", "bool", "\n", "var", "handlersStartTime", "time", ".", "Time", "\n", "var", "deadlineOffset", "time", ".", "Duration", "\n\n", "// pendingResponses tracks the expected response deadline times.", "pendingResponses", ":=", "make", "(", "map", "[", "string", "]", "time", ".", "Time", ")", "\n\n", "// stallTicker is used to periodically check pending responses that have", "// exceeded the expected deadline and disconnect the peer due to", "// stalling.", "stallTicker", ":=", "time", ".", "NewTicker", "(", "stallTickInterval", ")", "\n", "defer", "stallTicker", ".", "Stop", "(", ")", "\n\n", "// ioStopped is used to detect when both the input and output handler", "// goroutines are done.", "var", "ioStopped", "bool", "\n", "out", ":", "for", "{", "select", "{", "case", "msg", ":=", "<-", "p", ".", "stallControl", ":", "switch", "msg", ".", "command", "{", "case", "sccSendMessage", ":", "// Add a deadline for the expected response", "// message if needed.", "p", ".", "maybeAddDeadline", "(", "pendingResponses", ",", "msg", ".", "message", ".", "Command", "(", ")", ")", "\n\n", "case", "sccReceiveMessage", ":", "// Remove received messages from the expected", "// response map. Since certain commands expect", "// one of a group of responses, remove", "// everything in the expected group accordingly.", "switch", "msgCmd", ":=", "msg", ".", "message", ".", "Command", "(", ")", ";", "msgCmd", "{", "case", "wire", ".", "CmdBlock", ":", "fallthrough", "\n", "case", "wire", ".", "CmdMerkleBlock", ":", "fallthrough", "\n", "case", "wire", ".", "CmdTx", ":", "fallthrough", "\n", "case", "wire", ".", "CmdNotFound", ":", "delete", "(", "pendingResponses", ",", "wire", ".", "CmdBlock", ")", "\n", "delete", "(", "pendingResponses", ",", "wire", ".", "CmdMerkleBlock", ")", "\n", "delete", "(", "pendingResponses", ",", "wire", ".", "CmdTx", ")", "\n", "delete", "(", "pendingResponses", ",", "wire", ".", "CmdNotFound", ")", "\n\n", "default", ":", "delete", "(", "pendingResponses", ",", "msgCmd", ")", "\n", "}", "\n\n", "case", "sccHandlerStart", ":", "// Warn on unbalanced callback signalling.", "if", "handlerActive", "{", "log", ".", "Warn", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ")", "\n", "continue", "\n", "}", "\n\n", "handlerActive", "=", "true", "\n", "handlersStartTime", "=", "time", ".", "Now", "(", ")", "\n\n", "case", "sccHandlerDone", ":", "// Warn on unbalanced callback signalling.", "if", "!", "handlerActive", "{", "log", ".", "Warn", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ")", "\n", "continue", "\n", "}", "\n\n", "// Extend active deadlines by the time it took", "// to execute the callback.", "duration", ":=", "time", ".", "Since", "(", "handlersStartTime", ")", "\n", "deadlineOffset", "+=", "duration", "\n", "handlerActive", "=", "false", "\n\n", "default", ":", "log", ".", "Warnf", "(", "\"", "\"", ",", "msg", ".", "command", ")", "\n", "}", "\n\n", "case", "<-", "stallTicker", ".", "C", ":", "// Calculate the offset to apply to the deadline based", "// on how long the handlers have taken to execute since", "// the last tick.", "now", ":=", "time", ".", "Now", "(", ")", "\n", "offset", ":=", "deadlineOffset", "\n", "if", "handlerActive", "{", "offset", "+=", "now", ".", "Sub", "(", "handlersStartTime", ")", "\n", "}", "\n\n", "// Disconnect the peer if any of the pending responses", "// don't arrive by their adjusted deadline.", "for", "command", ",", "deadline", ":=", "range", "pendingResponses", "{", "if", "now", ".", "Before", "(", "deadline", ".", "Add", "(", "offset", ")", ")", "{", "continue", "\n", "}", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "p", ",", "command", ")", "\n", "p", ".", "Disconnect", "(", ")", "\n", "break", "\n", "}", "\n\n", "// Reset the deadline offset for the next tick.", "deadlineOffset", "=", "0", "\n\n", "case", "<-", "p", ".", "inQuit", ":", "// The stall handler can exit once both the input and", "// output handler goroutines are done.", "if", "ioStopped", "{", "break", "out", "\n", "}", "\n", "ioStopped", "=", "true", "\n\n", "case", "<-", "p", ".", "outQuit", ":", "// The stall handler can exit once both the input and", "// output handler goroutines are done.", "if", "ioStopped", "{", "break", "out", "\n", "}", "\n", "ioStopped", "=", "true", "\n", "}", "\n", "}", "\n\n", "// Drain any wait channels before going away so there is nothing left", "// waiting on this goroutine.", "cleanup", ":", "for", "{", "select", "{", "case", "<-", "p", ".", "stallControl", ":", "default", ":", "break", "cleanup", "\n", "}", "\n", "}", "\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "p", ")", "\n", "}" ]
// stallHandler handles stall detection for the peer. This entails keeping // track of expected responses and assigning them deadlines while accounting for // the time spent in callbacks. It must be run as a goroutine.
[ "stallHandler", "handles", "stall", "detection", "for", "the", "peer", ".", "This", "entails", "keeping", "track", "of", "expected", "responses", "and", "assigning", "them", "deadlines", "while", "accounting", "for", "the", "time", "spent", "in", "callbacks", ".", "It", "must", "be", "run", "as", "a", "goroutine", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L1174-L1317
train
btcsuite/btcd
peer/peer.go
shouldLogWriteError
func (p *Peer) shouldLogWriteError(err error) bool { // No logging when the peer is being forcibly disconnected. if atomic.LoadInt32(&p.disconnect) != 0 { return false } // No logging when the remote peer has been disconnected. if err == io.EOF { return false } if opErr, ok := err.(*net.OpError); ok && !opErr.Temporary() { return false } return true }
go
func (p *Peer) shouldLogWriteError(err error) bool { // No logging when the peer is being forcibly disconnected. if atomic.LoadInt32(&p.disconnect) != 0 { return false } // No logging when the remote peer has been disconnected. if err == io.EOF { return false } if opErr, ok := err.(*net.OpError); ok && !opErr.Temporary() { return false } return true }
[ "func", "(", "p", "*", "Peer", ")", "shouldLogWriteError", "(", "err", "error", ")", "bool", "{", "// No logging when the peer is being forcibly disconnected.", "if", "atomic", ".", "LoadInt32", "(", "&", "p", ".", "disconnect", ")", "!=", "0", "{", "return", "false", "\n", "}", "\n\n", "// No logging when the remote peer has been disconnected.", "if", "err", "==", "io", ".", "EOF", "{", "return", "false", "\n", "}", "\n", "if", "opErr", ",", "ok", ":=", "err", ".", "(", "*", "net", ".", "OpError", ")", ";", "ok", "&&", "!", "opErr", ".", "Temporary", "(", ")", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// shouldLogWriteError returns whether or not the passed error, which is // expected to have come from writing to the remote peer in the outHandler, // should be logged.
[ "shouldLogWriteError", "returns", "whether", "or", "not", "the", "passed", "error", "which", "is", "expected", "to", "have", "come", "from", "writing", "to", "the", "remote", "peer", "in", "the", "outHandler", "should", "be", "logged", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L1693-L1708
train
btcsuite/btcd
peer/peer.go
outHandler
func (p *Peer) outHandler() { out: for { select { case msg := <-p.sendQueue: switch m := msg.msg.(type) { case *wire.MsgPing: // Only expects a pong message in later protocol // versions. Also set up statistics. if p.ProtocolVersion() > wire.BIP0031Version { p.statsMtx.Lock() p.lastPingNonce = m.Nonce p.lastPingTime = time.Now() p.statsMtx.Unlock() } } p.stallControl <- stallControlMsg{sccSendMessage, msg.msg} err := p.writeMessage(msg.msg, msg.encoding) if err != nil { p.Disconnect() if p.shouldLogWriteError(err) { log.Errorf("Failed to send message to "+ "%s: %v", p, err) } if msg.doneChan != nil { msg.doneChan <- struct{}{} } continue } // At this point, the message was successfully sent, so // update the last send time, signal the sender of the // message that it has been sent (if requested), and // signal the send queue to the deliver the next queued // message. atomic.StoreInt64(&p.lastSend, time.Now().Unix()) if msg.doneChan != nil { msg.doneChan <- struct{}{} } p.sendDoneQueue <- struct{}{} case <-p.quit: break out } } <-p.queueQuit // Drain any wait channels before we go away so we don't leave something // waiting for us. We have waited on queueQuit and thus we can be sure // that we will not miss anything sent on sendQueue. cleanup: for { select { case msg := <-p.sendQueue: if msg.doneChan != nil { msg.doneChan <- struct{}{} } // no need to send on sendDoneQueue since queueHandler // has been waited on and already exited. default: break cleanup } } close(p.outQuit) log.Tracef("Peer output handler done for %s", p) }
go
func (p *Peer) outHandler() { out: for { select { case msg := <-p.sendQueue: switch m := msg.msg.(type) { case *wire.MsgPing: // Only expects a pong message in later protocol // versions. Also set up statistics. if p.ProtocolVersion() > wire.BIP0031Version { p.statsMtx.Lock() p.lastPingNonce = m.Nonce p.lastPingTime = time.Now() p.statsMtx.Unlock() } } p.stallControl <- stallControlMsg{sccSendMessage, msg.msg} err := p.writeMessage(msg.msg, msg.encoding) if err != nil { p.Disconnect() if p.shouldLogWriteError(err) { log.Errorf("Failed to send message to "+ "%s: %v", p, err) } if msg.doneChan != nil { msg.doneChan <- struct{}{} } continue } // At this point, the message was successfully sent, so // update the last send time, signal the sender of the // message that it has been sent (if requested), and // signal the send queue to the deliver the next queued // message. atomic.StoreInt64(&p.lastSend, time.Now().Unix()) if msg.doneChan != nil { msg.doneChan <- struct{}{} } p.sendDoneQueue <- struct{}{} case <-p.quit: break out } } <-p.queueQuit // Drain any wait channels before we go away so we don't leave something // waiting for us. We have waited on queueQuit and thus we can be sure // that we will not miss anything sent on sendQueue. cleanup: for { select { case msg := <-p.sendQueue: if msg.doneChan != nil { msg.doneChan <- struct{}{} } // no need to send on sendDoneQueue since queueHandler // has been waited on and already exited. default: break cleanup } } close(p.outQuit) log.Tracef("Peer output handler done for %s", p) }
[ "func", "(", "p", "*", "Peer", ")", "outHandler", "(", ")", "{", "out", ":", "for", "{", "select", "{", "case", "msg", ":=", "<-", "p", ".", "sendQueue", ":", "switch", "m", ":=", "msg", ".", "msg", ".", "(", "type", ")", "{", "case", "*", "wire", ".", "MsgPing", ":", "// Only expects a pong message in later protocol", "// versions. Also set up statistics.", "if", "p", ".", "ProtocolVersion", "(", ")", ">", "wire", ".", "BIP0031Version", "{", "p", ".", "statsMtx", ".", "Lock", "(", ")", "\n", "p", ".", "lastPingNonce", "=", "m", ".", "Nonce", "\n", "p", ".", "lastPingTime", "=", "time", ".", "Now", "(", ")", "\n", "p", ".", "statsMtx", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "\n\n", "p", ".", "stallControl", "<-", "stallControlMsg", "{", "sccSendMessage", ",", "msg", ".", "msg", "}", "\n\n", "err", ":=", "p", ".", "writeMessage", "(", "msg", ".", "msg", ",", "msg", ".", "encoding", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "Disconnect", "(", ")", "\n", "if", "p", ".", "shouldLogWriteError", "(", "err", ")", "{", "log", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "p", ",", "err", ")", "\n", "}", "\n", "if", "msg", ".", "doneChan", "!=", "nil", "{", "msg", ".", "doneChan", "<-", "struct", "{", "}", "{", "}", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "// At this point, the message was successfully sent, so", "// update the last send time, signal the sender of the", "// message that it has been sent (if requested), and", "// signal the send queue to the deliver the next queued", "// message.", "atomic", ".", "StoreInt64", "(", "&", "p", ".", "lastSend", ",", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ")", "\n", "if", "msg", ".", "doneChan", "!=", "nil", "{", "msg", ".", "doneChan", "<-", "struct", "{", "}", "{", "}", "\n", "}", "\n", "p", ".", "sendDoneQueue", "<-", "struct", "{", "}", "{", "}", "\n\n", "case", "<-", "p", ".", "quit", ":", "break", "out", "\n", "}", "\n", "}", "\n\n", "<-", "p", ".", "queueQuit", "\n\n", "// Drain any wait channels before we go away so we don't leave something", "// waiting for us. We have waited on queueQuit and thus we can be sure", "// that we will not miss anything sent on sendQueue.", "cleanup", ":", "for", "{", "select", "{", "case", "msg", ":=", "<-", "p", ".", "sendQueue", ":", "if", "msg", ".", "doneChan", "!=", "nil", "{", "msg", ".", "doneChan", "<-", "struct", "{", "}", "{", "}", "\n", "}", "\n", "// no need to send on sendDoneQueue since queueHandler", "// has been waited on and already exited.", "default", ":", "break", "cleanup", "\n", "}", "\n", "}", "\n", "close", "(", "p", ".", "outQuit", ")", "\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "p", ")", "\n", "}" ]
// outHandler handles all outgoing messages for the peer. It must be run as a // goroutine. It uses a buffered channel to serialize output messages while // allowing the sender to continue running asynchronously.
[ "outHandler", "handles", "all", "outgoing", "messages", "for", "the", "peer", ".", "It", "must", "be", "run", "as", "a", "goroutine", ".", "It", "uses", "a", "buffered", "channel", "to", "serialize", "output", "messages", "while", "allowing", "the", "sender", "to", "continue", "running", "asynchronously", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L1713-L1781
train
btcsuite/btcd
peer/peer.go
pingHandler
func (p *Peer) pingHandler() { pingTicker := time.NewTicker(pingInterval) defer pingTicker.Stop() out: for { select { case <-pingTicker.C: nonce, err := wire.RandomUint64() if err != nil { log.Errorf("Not sending ping to %s: %v", p, err) continue } p.QueueMessage(wire.NewMsgPing(nonce), nil) case <-p.quit: break out } } }
go
func (p *Peer) pingHandler() { pingTicker := time.NewTicker(pingInterval) defer pingTicker.Stop() out: for { select { case <-pingTicker.C: nonce, err := wire.RandomUint64() if err != nil { log.Errorf("Not sending ping to %s: %v", p, err) continue } p.QueueMessage(wire.NewMsgPing(nonce), nil) case <-p.quit: break out } } }
[ "func", "(", "p", "*", "Peer", ")", "pingHandler", "(", ")", "{", "pingTicker", ":=", "time", ".", "NewTicker", "(", "pingInterval", ")", "\n", "defer", "pingTicker", ".", "Stop", "(", ")", "\n\n", "out", ":", "for", "{", "select", "{", "case", "<-", "pingTicker", ".", "C", ":", "nonce", ",", "err", ":=", "wire", ".", "RandomUint64", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "p", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "p", ".", "QueueMessage", "(", "wire", ".", "NewMsgPing", "(", "nonce", ")", ",", "nil", ")", "\n\n", "case", "<-", "p", ".", "quit", ":", "break", "out", "\n", "}", "\n", "}", "\n", "}" ]
// pingHandler periodically pings the peer. It must be run as a goroutine.
[ "pingHandler", "periodically", "pings", "the", "peer", ".", "It", "must", "be", "run", "as", "a", "goroutine", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L1784-L1803
train
btcsuite/btcd
peer/peer.go
QueueMessage
func (p *Peer) QueueMessage(msg wire.Message, doneChan chan<- struct{}) { p.QueueMessageWithEncoding(msg, doneChan, wire.BaseEncoding) }
go
func (p *Peer) QueueMessage(msg wire.Message, doneChan chan<- struct{}) { p.QueueMessageWithEncoding(msg, doneChan, wire.BaseEncoding) }
[ "func", "(", "p", "*", "Peer", ")", "QueueMessage", "(", "msg", "wire", ".", "Message", ",", "doneChan", "chan", "<-", "struct", "{", "}", ")", "{", "p", ".", "QueueMessageWithEncoding", "(", "msg", ",", "doneChan", ",", "wire", ".", "BaseEncoding", ")", "\n", "}" ]
// QueueMessage adds the passed bitcoin message to the peer send queue. // // This function is safe for concurrent access.
[ "QueueMessage", "adds", "the", "passed", "bitcoin", "message", "to", "the", "peer", "send", "queue", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L1808-L1810
train
btcsuite/btcd
peer/peer.go
QueueInventory
func (p *Peer) QueueInventory(invVect *wire.InvVect) { // Don't add the inventory to the send queue if the peer is already // known to have it. if p.knownInventory.Exists(invVect) { return } // Avoid risk of deadlock if goroutine already exited. The goroutine // we will be sending to hangs around until it knows for a fact that // it is marked as disconnected and *then* it drains the channels. if !p.Connected() { return } p.outputInvChan <- invVect }
go
func (p *Peer) QueueInventory(invVect *wire.InvVect) { // Don't add the inventory to the send queue if the peer is already // known to have it. if p.knownInventory.Exists(invVect) { return } // Avoid risk of deadlock if goroutine already exited. The goroutine // we will be sending to hangs around until it knows for a fact that // it is marked as disconnected and *then* it drains the channels. if !p.Connected() { return } p.outputInvChan <- invVect }
[ "func", "(", "p", "*", "Peer", ")", "QueueInventory", "(", "invVect", "*", "wire", ".", "InvVect", ")", "{", "// Don't add the inventory to the send queue if the peer is already", "// known to have it.", "if", "p", ".", "knownInventory", ".", "Exists", "(", "invVect", ")", "{", "return", "\n", "}", "\n\n", "// Avoid risk of deadlock if goroutine already exited. The goroutine", "// we will be sending to hangs around until it knows for a fact that", "// it is marked as disconnected and *then* it drains the channels.", "if", "!", "p", ".", "Connected", "(", ")", "{", "return", "\n", "}", "\n\n", "p", ".", "outputInvChan", "<-", "invVect", "\n", "}" ]
// QueueInventory adds the passed inventory to the inventory send queue which // might not be sent right away, rather it is trickled to the peer in batches. // Inventory that the peer is already known to have is ignored. // // This function is safe for concurrent access.
[ "QueueInventory", "adds", "the", "passed", "inventory", "to", "the", "inventory", "send", "queue", "which", "might", "not", "be", "sent", "right", "away", "rather", "it", "is", "trickled", "to", "the", "peer", "in", "batches", ".", "Inventory", "that", "the", "peer", "is", "already", "known", "to", "have", "is", "ignored", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L1840-L1855
train
btcsuite/btcd
peer/peer.go
Connected
func (p *Peer) Connected() bool { return atomic.LoadInt32(&p.connected) != 0 && atomic.LoadInt32(&p.disconnect) == 0 }
go
func (p *Peer) Connected() bool { return atomic.LoadInt32(&p.connected) != 0 && atomic.LoadInt32(&p.disconnect) == 0 }
[ "func", "(", "p", "*", "Peer", ")", "Connected", "(", ")", "bool", "{", "return", "atomic", ".", "LoadInt32", "(", "&", "p", ".", "connected", ")", "!=", "0", "&&", "atomic", ".", "LoadInt32", "(", "&", "p", ".", "disconnect", ")", "==", "0", "\n", "}" ]
// Connected returns whether or not the peer is currently connected. // // This function is safe for concurrent access.
[ "Connected", "returns", "whether", "or", "not", "the", "peer", "is", "currently", "connected", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L1860-L1863
train
btcsuite/btcd
peer/peer.go
Disconnect
func (p *Peer) Disconnect() { if atomic.AddInt32(&p.disconnect, 1) != 1 { return } log.Tracef("Disconnecting %s", p) if atomic.LoadInt32(&p.connected) != 0 { p.conn.Close() } close(p.quit) }
go
func (p *Peer) Disconnect() { if atomic.AddInt32(&p.disconnect, 1) != 1 { return } log.Tracef("Disconnecting %s", p) if atomic.LoadInt32(&p.connected) != 0 { p.conn.Close() } close(p.quit) }
[ "func", "(", "p", "*", "Peer", ")", "Disconnect", "(", ")", "{", "if", "atomic", ".", "AddInt32", "(", "&", "p", ".", "disconnect", ",", "1", ")", "!=", "1", "{", "return", "\n", "}", "\n\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "p", ")", "\n", "if", "atomic", ".", "LoadInt32", "(", "&", "p", ".", "connected", ")", "!=", "0", "{", "p", ".", "conn", ".", "Close", "(", ")", "\n", "}", "\n", "close", "(", "p", ".", "quit", ")", "\n", "}" ]
// Disconnect disconnects the peer by closing the connection. Calling this // function when the peer is already disconnected or in the process of // disconnecting will have no effect.
[ "Disconnect", "disconnects", "the", "peer", "by", "closing", "the", "connection", ".", "Calling", "this", "function", "when", "the", "peer", "is", "already", "disconnected", "or", "in", "the", "process", "of", "disconnecting", "will", "have", "no", "effect", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L1868-L1878
train
btcsuite/btcd
peer/peer.go
readRemoteVersionMsg
func (p *Peer) readRemoteVersionMsg() error { // Read their version message. remoteMsg, _, err := p.readMessage(wire.LatestEncoding) if err != nil { return err } // Notify and disconnect clients if the first message is not a version // message. msg, ok := remoteMsg.(*wire.MsgVersion) if !ok { reason := "a version message must precede all others" rejectMsg := wire.NewMsgReject(msg.Command(), wire.RejectMalformed, reason) _ = p.writeMessage(rejectMsg, wire.LatestEncoding) return errors.New(reason) } // Detect self connections. if !allowSelfConns && sentNonces.Exists(msg.Nonce) { return errors.New("disconnecting peer connected to self") } // Negotiate the protocol version and set the services to what the remote // peer advertised. p.flagsMtx.Lock() p.advertisedProtoVer = uint32(msg.ProtocolVersion) p.protocolVersion = minUint32(p.protocolVersion, p.advertisedProtoVer) p.versionKnown = true p.services = msg.Services p.flagsMtx.Unlock() log.Debugf("Negotiated protocol version %d for peer %s", p.protocolVersion, p) // Updating a bunch of stats including block based stats, and the // peer's time offset. p.statsMtx.Lock() p.lastBlock = msg.LastBlock p.startingHeight = msg.LastBlock p.timeOffset = msg.Timestamp.Unix() - time.Now().Unix() p.statsMtx.Unlock() // Set the peer's ID, user agent, and potentially the flag which // specifies the witness support is enabled. p.flagsMtx.Lock() p.id = atomic.AddInt32(&nodeCount, 1) p.userAgent = msg.UserAgent // Determine if the peer would like to receive witness data with // transactions, or not. if p.services&wire.SFNodeWitness == wire.SFNodeWitness { p.witnessEnabled = true } p.flagsMtx.Unlock() // Once the version message has been exchanged, we're able to determine // if this peer knows how to encode witness data over the wire // protocol. If so, then we'll switch to a decoding mode which is // prepared for the new transaction format introduced as part of // BIP0144. if p.services&wire.SFNodeWitness == wire.SFNodeWitness { p.wireEncoding = wire.WitnessEncoding } // Invoke the callback if specified. if p.cfg.Listeners.OnVersion != nil { rejectMsg := p.cfg.Listeners.OnVersion(p, msg) if rejectMsg != nil { _ = p.writeMessage(rejectMsg, wire.LatestEncoding) return errors.New(rejectMsg.Reason) } } // Notify and disconnect clients that have a protocol version that is // too old. // // NOTE: If minAcceptableProtocolVersion is raised to be higher than // wire.RejectVersion, this should send a reject packet before // disconnecting. if uint32(msg.ProtocolVersion) < MinAcceptableProtocolVersion { // Send a reject message indicating the protocol version is // obsolete and wait for the message to be sent before // disconnecting. reason := fmt.Sprintf("protocol version must be %d or greater", MinAcceptableProtocolVersion) rejectMsg := wire.NewMsgReject(msg.Command(), wire.RejectObsolete, reason) _ = p.writeMessage(rejectMsg, wire.LatestEncoding) return errors.New(reason) } return nil }
go
func (p *Peer) readRemoteVersionMsg() error { // Read their version message. remoteMsg, _, err := p.readMessage(wire.LatestEncoding) if err != nil { return err } // Notify and disconnect clients if the first message is not a version // message. msg, ok := remoteMsg.(*wire.MsgVersion) if !ok { reason := "a version message must precede all others" rejectMsg := wire.NewMsgReject(msg.Command(), wire.RejectMalformed, reason) _ = p.writeMessage(rejectMsg, wire.LatestEncoding) return errors.New(reason) } // Detect self connections. if !allowSelfConns && sentNonces.Exists(msg.Nonce) { return errors.New("disconnecting peer connected to self") } // Negotiate the protocol version and set the services to what the remote // peer advertised. p.flagsMtx.Lock() p.advertisedProtoVer = uint32(msg.ProtocolVersion) p.protocolVersion = minUint32(p.protocolVersion, p.advertisedProtoVer) p.versionKnown = true p.services = msg.Services p.flagsMtx.Unlock() log.Debugf("Negotiated protocol version %d for peer %s", p.protocolVersion, p) // Updating a bunch of stats including block based stats, and the // peer's time offset. p.statsMtx.Lock() p.lastBlock = msg.LastBlock p.startingHeight = msg.LastBlock p.timeOffset = msg.Timestamp.Unix() - time.Now().Unix() p.statsMtx.Unlock() // Set the peer's ID, user agent, and potentially the flag which // specifies the witness support is enabled. p.flagsMtx.Lock() p.id = atomic.AddInt32(&nodeCount, 1) p.userAgent = msg.UserAgent // Determine if the peer would like to receive witness data with // transactions, or not. if p.services&wire.SFNodeWitness == wire.SFNodeWitness { p.witnessEnabled = true } p.flagsMtx.Unlock() // Once the version message has been exchanged, we're able to determine // if this peer knows how to encode witness data over the wire // protocol. If so, then we'll switch to a decoding mode which is // prepared for the new transaction format introduced as part of // BIP0144. if p.services&wire.SFNodeWitness == wire.SFNodeWitness { p.wireEncoding = wire.WitnessEncoding } // Invoke the callback if specified. if p.cfg.Listeners.OnVersion != nil { rejectMsg := p.cfg.Listeners.OnVersion(p, msg) if rejectMsg != nil { _ = p.writeMessage(rejectMsg, wire.LatestEncoding) return errors.New(rejectMsg.Reason) } } // Notify and disconnect clients that have a protocol version that is // too old. // // NOTE: If minAcceptableProtocolVersion is raised to be higher than // wire.RejectVersion, this should send a reject packet before // disconnecting. if uint32(msg.ProtocolVersion) < MinAcceptableProtocolVersion { // Send a reject message indicating the protocol version is // obsolete and wait for the message to be sent before // disconnecting. reason := fmt.Sprintf("protocol version must be %d or greater", MinAcceptableProtocolVersion) rejectMsg := wire.NewMsgReject(msg.Command(), wire.RejectObsolete, reason) _ = p.writeMessage(rejectMsg, wire.LatestEncoding) return errors.New(reason) } return nil }
[ "func", "(", "p", "*", "Peer", ")", "readRemoteVersionMsg", "(", ")", "error", "{", "// Read their version message.", "remoteMsg", ",", "_", ",", "err", ":=", "p", ".", "readMessage", "(", "wire", ".", "LatestEncoding", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Notify and disconnect clients if the first message is not a version", "// message.", "msg", ",", "ok", ":=", "remoteMsg", ".", "(", "*", "wire", ".", "MsgVersion", ")", "\n", "if", "!", "ok", "{", "reason", ":=", "\"", "\"", "\n", "rejectMsg", ":=", "wire", ".", "NewMsgReject", "(", "msg", ".", "Command", "(", ")", ",", "wire", ".", "RejectMalformed", ",", "reason", ")", "\n", "_", "=", "p", ".", "writeMessage", "(", "rejectMsg", ",", "wire", ".", "LatestEncoding", ")", "\n", "return", "errors", ".", "New", "(", "reason", ")", "\n", "}", "\n\n", "// Detect self connections.", "if", "!", "allowSelfConns", "&&", "sentNonces", ".", "Exists", "(", "msg", ".", "Nonce", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Negotiate the protocol version and set the services to what the remote", "// peer advertised.", "p", ".", "flagsMtx", ".", "Lock", "(", ")", "\n", "p", ".", "advertisedProtoVer", "=", "uint32", "(", "msg", ".", "ProtocolVersion", ")", "\n", "p", ".", "protocolVersion", "=", "minUint32", "(", "p", ".", "protocolVersion", ",", "p", ".", "advertisedProtoVer", ")", "\n", "p", ".", "versionKnown", "=", "true", "\n", "p", ".", "services", "=", "msg", ".", "Services", "\n", "p", ".", "flagsMtx", ".", "Unlock", "(", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "p", ".", "protocolVersion", ",", "p", ")", "\n\n", "// Updating a bunch of stats including block based stats, and the", "// peer's time offset.", "p", ".", "statsMtx", ".", "Lock", "(", ")", "\n", "p", ".", "lastBlock", "=", "msg", ".", "LastBlock", "\n", "p", ".", "startingHeight", "=", "msg", ".", "LastBlock", "\n", "p", ".", "timeOffset", "=", "msg", ".", "Timestamp", ".", "Unix", "(", ")", "-", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", "\n", "p", ".", "statsMtx", ".", "Unlock", "(", ")", "\n\n", "// Set the peer's ID, user agent, and potentially the flag which", "// specifies the witness support is enabled.", "p", ".", "flagsMtx", ".", "Lock", "(", ")", "\n", "p", ".", "id", "=", "atomic", ".", "AddInt32", "(", "&", "nodeCount", ",", "1", ")", "\n", "p", ".", "userAgent", "=", "msg", ".", "UserAgent", "\n\n", "// Determine if the peer would like to receive witness data with", "// transactions, or not.", "if", "p", ".", "services", "&", "wire", ".", "SFNodeWitness", "==", "wire", ".", "SFNodeWitness", "{", "p", ".", "witnessEnabled", "=", "true", "\n", "}", "\n", "p", ".", "flagsMtx", ".", "Unlock", "(", ")", "\n\n", "// Once the version message has been exchanged, we're able to determine", "// if this peer knows how to encode witness data over the wire", "// protocol. If so, then we'll switch to a decoding mode which is", "// prepared for the new transaction format introduced as part of", "// BIP0144.", "if", "p", ".", "services", "&", "wire", ".", "SFNodeWitness", "==", "wire", ".", "SFNodeWitness", "{", "p", ".", "wireEncoding", "=", "wire", ".", "WitnessEncoding", "\n", "}", "\n\n", "// Invoke the callback if specified.", "if", "p", ".", "cfg", ".", "Listeners", ".", "OnVersion", "!=", "nil", "{", "rejectMsg", ":=", "p", ".", "cfg", ".", "Listeners", ".", "OnVersion", "(", "p", ",", "msg", ")", "\n", "if", "rejectMsg", "!=", "nil", "{", "_", "=", "p", ".", "writeMessage", "(", "rejectMsg", ",", "wire", ".", "LatestEncoding", ")", "\n", "return", "errors", ".", "New", "(", "rejectMsg", ".", "Reason", ")", "\n", "}", "\n", "}", "\n\n", "// Notify and disconnect clients that have a protocol version that is", "// too old.", "//", "// NOTE: If minAcceptableProtocolVersion is raised to be higher than", "// wire.RejectVersion, this should send a reject packet before", "// disconnecting.", "if", "uint32", "(", "msg", ".", "ProtocolVersion", ")", "<", "MinAcceptableProtocolVersion", "{", "// Send a reject message indicating the protocol version is", "// obsolete and wait for the message to be sent before", "// disconnecting.", "reason", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "MinAcceptableProtocolVersion", ")", "\n", "rejectMsg", ":=", "wire", ".", "NewMsgReject", "(", "msg", ".", "Command", "(", ")", ",", "wire", ".", "RejectObsolete", ",", "reason", ")", "\n", "_", "=", "p", ".", "writeMessage", "(", "rejectMsg", ",", "wire", ".", "LatestEncoding", ")", "\n", "return", "errors", ".", "New", "(", "reason", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// readRemoteVersionMsg waits for the next message to arrive from the remote // peer. If the next message is not a version message or the version is not // acceptable then return an error.
[ "readRemoteVersionMsg", "waits", "for", "the", "next", "message", "to", "arrive", "from", "the", "remote", "peer", ".", "If", "the", "next", "message", "is", "not", "a", "version", "message", "or", "the", "version", "is", "not", "acceptable", "then", "return", "an", "error", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L1883-L1975
train
btcsuite/btcd
peer/peer.go
localVersionMsg
func (p *Peer) localVersionMsg() (*wire.MsgVersion, error) { var blockNum int32 if p.cfg.NewestBlock != nil { var err error _, blockNum, err = p.cfg.NewestBlock() if err != nil { return nil, err } } theirNA := p.na // If we are behind a proxy and the connection comes from the proxy then // we return an unroutable address as their address. This is to prevent // leaking the tor proxy address. if p.cfg.Proxy != "" { proxyaddress, _, err := net.SplitHostPort(p.cfg.Proxy) // invalid proxy means poorly configured, be on the safe side. if err != nil || p.na.IP.String() == proxyaddress { theirNA = wire.NewNetAddressIPPort(net.IP([]byte{0, 0, 0, 0}), 0, theirNA.Services) } } // Create a wire.NetAddress with only the services set to use as the // "addrme" in the version message. // // Older nodes previously added the IP and port information to the // address manager which proved to be unreliable as an inbound // connection from a peer didn't necessarily mean the peer itself // accepted inbound connections. // // Also, the timestamp is unused in the version message. ourNA := &wire.NetAddress{ Services: p.cfg.Services, } // Generate a unique nonce for this peer so self connections can be // detected. This is accomplished by adding it to a size-limited map of // recently seen nonces. nonce := uint64(rand.Int63()) sentNonces.Add(nonce) // Version message. msg := wire.NewMsgVersion(ourNA, theirNA, nonce, blockNum) msg.AddUserAgent(p.cfg.UserAgentName, p.cfg.UserAgentVersion, p.cfg.UserAgentComments...) // Advertise local services. msg.Services = p.cfg.Services // Advertise our max supported protocol version. msg.ProtocolVersion = int32(p.cfg.ProtocolVersion) // Advertise if inv messages for transactions are desired. msg.DisableRelayTx = p.cfg.DisableRelayTx return msg, nil }
go
func (p *Peer) localVersionMsg() (*wire.MsgVersion, error) { var blockNum int32 if p.cfg.NewestBlock != nil { var err error _, blockNum, err = p.cfg.NewestBlock() if err != nil { return nil, err } } theirNA := p.na // If we are behind a proxy and the connection comes from the proxy then // we return an unroutable address as their address. This is to prevent // leaking the tor proxy address. if p.cfg.Proxy != "" { proxyaddress, _, err := net.SplitHostPort(p.cfg.Proxy) // invalid proxy means poorly configured, be on the safe side. if err != nil || p.na.IP.String() == proxyaddress { theirNA = wire.NewNetAddressIPPort(net.IP([]byte{0, 0, 0, 0}), 0, theirNA.Services) } } // Create a wire.NetAddress with only the services set to use as the // "addrme" in the version message. // // Older nodes previously added the IP and port information to the // address manager which proved to be unreliable as an inbound // connection from a peer didn't necessarily mean the peer itself // accepted inbound connections. // // Also, the timestamp is unused in the version message. ourNA := &wire.NetAddress{ Services: p.cfg.Services, } // Generate a unique nonce for this peer so self connections can be // detected. This is accomplished by adding it to a size-limited map of // recently seen nonces. nonce := uint64(rand.Int63()) sentNonces.Add(nonce) // Version message. msg := wire.NewMsgVersion(ourNA, theirNA, nonce, blockNum) msg.AddUserAgent(p.cfg.UserAgentName, p.cfg.UserAgentVersion, p.cfg.UserAgentComments...) // Advertise local services. msg.Services = p.cfg.Services // Advertise our max supported protocol version. msg.ProtocolVersion = int32(p.cfg.ProtocolVersion) // Advertise if inv messages for transactions are desired. msg.DisableRelayTx = p.cfg.DisableRelayTx return msg, nil }
[ "func", "(", "p", "*", "Peer", ")", "localVersionMsg", "(", ")", "(", "*", "wire", ".", "MsgVersion", ",", "error", ")", "{", "var", "blockNum", "int32", "\n", "if", "p", ".", "cfg", ".", "NewestBlock", "!=", "nil", "{", "var", "err", "error", "\n", "_", ",", "blockNum", ",", "err", "=", "p", ".", "cfg", ".", "NewestBlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "theirNA", ":=", "p", ".", "na", "\n\n", "// If we are behind a proxy and the connection comes from the proxy then", "// we return an unroutable address as their address. This is to prevent", "// leaking the tor proxy address.", "if", "p", ".", "cfg", ".", "Proxy", "!=", "\"", "\"", "{", "proxyaddress", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "p", ".", "cfg", ".", "Proxy", ")", "\n", "// invalid proxy means poorly configured, be on the safe side.", "if", "err", "!=", "nil", "||", "p", ".", "na", ".", "IP", ".", "String", "(", ")", "==", "proxyaddress", "{", "theirNA", "=", "wire", ".", "NewNetAddressIPPort", "(", "net", ".", "IP", "(", "[", "]", "byte", "{", "0", ",", "0", ",", "0", ",", "0", "}", ")", ",", "0", ",", "theirNA", ".", "Services", ")", "\n", "}", "\n", "}", "\n\n", "// Create a wire.NetAddress with only the services set to use as the", "// \"addrme\" in the version message.", "//", "// Older nodes previously added the IP and port information to the", "// address manager which proved to be unreliable as an inbound", "// connection from a peer didn't necessarily mean the peer itself", "// accepted inbound connections.", "//", "// Also, the timestamp is unused in the version message.", "ourNA", ":=", "&", "wire", ".", "NetAddress", "{", "Services", ":", "p", ".", "cfg", ".", "Services", ",", "}", "\n\n", "// Generate a unique nonce for this peer so self connections can be", "// detected. This is accomplished by adding it to a size-limited map of", "// recently seen nonces.", "nonce", ":=", "uint64", "(", "rand", ".", "Int63", "(", ")", ")", "\n", "sentNonces", ".", "Add", "(", "nonce", ")", "\n\n", "// Version message.", "msg", ":=", "wire", ".", "NewMsgVersion", "(", "ourNA", ",", "theirNA", ",", "nonce", ",", "blockNum", ")", "\n", "msg", ".", "AddUserAgent", "(", "p", ".", "cfg", ".", "UserAgentName", ",", "p", ".", "cfg", ".", "UserAgentVersion", ",", "p", ".", "cfg", ".", "UserAgentComments", "...", ")", "\n\n", "// Advertise local services.", "msg", ".", "Services", "=", "p", ".", "cfg", ".", "Services", "\n\n", "// Advertise our max supported protocol version.", "msg", ".", "ProtocolVersion", "=", "int32", "(", "p", ".", "cfg", ".", "ProtocolVersion", ")", "\n\n", "// Advertise if inv messages for transactions are desired.", "msg", ".", "DisableRelayTx", "=", "p", ".", "cfg", ".", "DisableRelayTx", "\n\n", "return", "msg", ",", "nil", "\n", "}" ]
// localVersionMsg creates a version message that can be used to send to the // remote peer.
[ "localVersionMsg", "creates", "a", "version", "message", "that", "can", "be", "used", "to", "send", "to", "the", "remote", "peer", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L1979-L2037
train
btcsuite/btcd
peer/peer.go
writeLocalVersionMsg
func (p *Peer) writeLocalVersionMsg() error { localVerMsg, err := p.localVersionMsg() if err != nil { return err } return p.writeMessage(localVerMsg, wire.LatestEncoding) }
go
func (p *Peer) writeLocalVersionMsg() error { localVerMsg, err := p.localVersionMsg() if err != nil { return err } return p.writeMessage(localVerMsg, wire.LatestEncoding) }
[ "func", "(", "p", "*", "Peer", ")", "writeLocalVersionMsg", "(", ")", "error", "{", "localVerMsg", ",", "err", ":=", "p", ".", "localVersionMsg", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "p", ".", "writeMessage", "(", "localVerMsg", ",", "wire", ".", "LatestEncoding", ")", "\n", "}" ]
// writeLocalVersionMsg writes our version message to the remote peer.
[ "writeLocalVersionMsg", "writes", "our", "version", "message", "to", "the", "remote", "peer", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L2040-L2047
train
btcsuite/btcd
peer/peer.go
negotiateInboundProtocol
func (p *Peer) negotiateInboundProtocol() error { if err := p.readRemoteVersionMsg(); err != nil { return err } return p.writeLocalVersionMsg() }
go
func (p *Peer) negotiateInboundProtocol() error { if err := p.readRemoteVersionMsg(); err != nil { return err } return p.writeLocalVersionMsg() }
[ "func", "(", "p", "*", "Peer", ")", "negotiateInboundProtocol", "(", ")", "error", "{", "if", "err", ":=", "p", ".", "readRemoteVersionMsg", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "p", ".", "writeLocalVersionMsg", "(", ")", "\n", "}" ]
// negotiateInboundProtocol waits to receive a version message from the peer // then sends our version message. If the events do not occur in that order then // it returns an error.
[ "negotiateInboundProtocol", "waits", "to", "receive", "a", "version", "message", "from", "the", "peer", "then", "sends", "our", "version", "message", ".", "If", "the", "events", "do", "not", "occur", "in", "that", "order", "then", "it", "returns", "an", "error", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L2052-L2058
train
btcsuite/btcd
peer/peer.go
negotiateOutboundProtocol
func (p *Peer) negotiateOutboundProtocol() error { if err := p.writeLocalVersionMsg(); err != nil { return err } return p.readRemoteVersionMsg() }
go
func (p *Peer) negotiateOutboundProtocol() error { if err := p.writeLocalVersionMsg(); err != nil { return err } return p.readRemoteVersionMsg() }
[ "func", "(", "p", "*", "Peer", ")", "negotiateOutboundProtocol", "(", ")", "error", "{", "if", "err", ":=", "p", ".", "writeLocalVersionMsg", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "p", ".", "readRemoteVersionMsg", "(", ")", "\n", "}" ]
// negotiateOutboundProtocol sends our version message then waits to receive a // version message from the peer. If the events do not occur in that order then // it returns an error.
[ "negotiateOutboundProtocol", "sends", "our", "version", "message", "then", "waits", "to", "receive", "a", "version", "message", "from", "the", "peer", ".", "If", "the", "events", "do", "not", "occur", "in", "that", "order", "then", "it", "returns", "an", "error", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L2063-L2069
train
btcsuite/btcd
peer/peer.go
AssociateConnection
func (p *Peer) AssociateConnection(conn net.Conn) { // Already connected? if !atomic.CompareAndSwapInt32(&p.connected, 0, 1) { return } p.conn = conn p.timeConnected = time.Now() if p.inbound { p.addr = p.conn.RemoteAddr().String() // Set up a NetAddress for the peer to be used with AddrManager. We // only do this inbound because outbound set this up at connection time // and no point recomputing. na, err := newNetAddress(p.conn.RemoteAddr(), p.services) if err != nil { log.Errorf("Cannot create remote net address: %v", err) p.Disconnect() return } p.na = na } go func() { if err := p.start(); err != nil { log.Debugf("Cannot start peer %v: %v", p, err) p.Disconnect() } }() }
go
func (p *Peer) AssociateConnection(conn net.Conn) { // Already connected? if !atomic.CompareAndSwapInt32(&p.connected, 0, 1) { return } p.conn = conn p.timeConnected = time.Now() if p.inbound { p.addr = p.conn.RemoteAddr().String() // Set up a NetAddress for the peer to be used with AddrManager. We // only do this inbound because outbound set this up at connection time // and no point recomputing. na, err := newNetAddress(p.conn.RemoteAddr(), p.services) if err != nil { log.Errorf("Cannot create remote net address: %v", err) p.Disconnect() return } p.na = na } go func() { if err := p.start(); err != nil { log.Debugf("Cannot start peer %v: %v", p, err) p.Disconnect() } }() }
[ "func", "(", "p", "*", "Peer", ")", "AssociateConnection", "(", "conn", "net", ".", "Conn", ")", "{", "// Already connected?", "if", "!", "atomic", ".", "CompareAndSwapInt32", "(", "&", "p", ".", "connected", ",", "0", ",", "1", ")", "{", "return", "\n", "}", "\n\n", "p", ".", "conn", "=", "conn", "\n", "p", ".", "timeConnected", "=", "time", ".", "Now", "(", ")", "\n\n", "if", "p", ".", "inbound", "{", "p", ".", "addr", "=", "p", ".", "conn", ".", "RemoteAddr", "(", ")", ".", "String", "(", ")", "\n\n", "// Set up a NetAddress for the peer to be used with AddrManager. We", "// only do this inbound because outbound set this up at connection time", "// and no point recomputing.", "na", ",", "err", ":=", "newNetAddress", "(", "p", ".", "conn", ".", "RemoteAddr", "(", ")", ",", "p", ".", "services", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "p", ".", "Disconnect", "(", ")", "\n", "return", "\n", "}", "\n", "p", ".", "na", "=", "na", "\n", "}", "\n\n", "go", "func", "(", ")", "{", "if", "err", ":=", "p", ".", "start", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "p", ",", "err", ")", "\n", "p", ".", "Disconnect", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// AssociateConnection associates the given conn to the peer. Calling this // function when the peer is already connected will have no effect.
[ "AssociateConnection", "associates", "the", "given", "conn", "to", "the", "peer", ".", "Calling", "this", "function", "when", "the", "peer", "is", "already", "connected", "will", "have", "no", "effect", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L2112-L2142
train
btcsuite/btcd
peer/peer.go
newPeerBase
func newPeerBase(origCfg *Config, inbound bool) *Peer { // Default to the max supported protocol version if not specified by the // caller. cfg := *origCfg // Copy to avoid mutating caller. if cfg.ProtocolVersion == 0 { cfg.ProtocolVersion = MaxProtocolVersion } // Set the chain parameters to testnet if the caller did not specify any. if cfg.ChainParams == nil { cfg.ChainParams = &chaincfg.TestNet3Params } // Set the trickle interval if a non-positive value is specified. if cfg.TrickleInterval <= 0 { cfg.TrickleInterval = DefaultTrickleInterval } p := Peer{ inbound: inbound, wireEncoding: wire.BaseEncoding, knownInventory: newMruInventoryMap(maxKnownInventory), stallControl: make(chan stallControlMsg, 1), // nonblocking sync outputQueue: make(chan outMsg, outputBufferSize), sendQueue: make(chan outMsg, 1), // nonblocking sync sendDoneQueue: make(chan struct{}, 1), // nonblocking sync outputInvChan: make(chan *wire.InvVect, outputBufferSize), inQuit: make(chan struct{}), queueQuit: make(chan struct{}), outQuit: make(chan struct{}), quit: make(chan struct{}), cfg: cfg, // Copy so caller can't mutate. services: cfg.Services, protocolVersion: cfg.ProtocolVersion, } return &p }
go
func newPeerBase(origCfg *Config, inbound bool) *Peer { // Default to the max supported protocol version if not specified by the // caller. cfg := *origCfg // Copy to avoid mutating caller. if cfg.ProtocolVersion == 0 { cfg.ProtocolVersion = MaxProtocolVersion } // Set the chain parameters to testnet if the caller did not specify any. if cfg.ChainParams == nil { cfg.ChainParams = &chaincfg.TestNet3Params } // Set the trickle interval if a non-positive value is specified. if cfg.TrickleInterval <= 0 { cfg.TrickleInterval = DefaultTrickleInterval } p := Peer{ inbound: inbound, wireEncoding: wire.BaseEncoding, knownInventory: newMruInventoryMap(maxKnownInventory), stallControl: make(chan stallControlMsg, 1), // nonblocking sync outputQueue: make(chan outMsg, outputBufferSize), sendQueue: make(chan outMsg, 1), // nonblocking sync sendDoneQueue: make(chan struct{}, 1), // nonblocking sync outputInvChan: make(chan *wire.InvVect, outputBufferSize), inQuit: make(chan struct{}), queueQuit: make(chan struct{}), outQuit: make(chan struct{}), quit: make(chan struct{}), cfg: cfg, // Copy so caller can't mutate. services: cfg.Services, protocolVersion: cfg.ProtocolVersion, } return &p }
[ "func", "newPeerBase", "(", "origCfg", "*", "Config", ",", "inbound", "bool", ")", "*", "Peer", "{", "// Default to the max supported protocol version if not specified by the", "// caller.", "cfg", ":=", "*", "origCfg", "// Copy to avoid mutating caller.", "\n", "if", "cfg", ".", "ProtocolVersion", "==", "0", "{", "cfg", ".", "ProtocolVersion", "=", "MaxProtocolVersion", "\n", "}", "\n\n", "// Set the chain parameters to testnet if the caller did not specify any.", "if", "cfg", ".", "ChainParams", "==", "nil", "{", "cfg", ".", "ChainParams", "=", "&", "chaincfg", ".", "TestNet3Params", "\n", "}", "\n\n", "// Set the trickle interval if a non-positive value is specified.", "if", "cfg", ".", "TrickleInterval", "<=", "0", "{", "cfg", ".", "TrickleInterval", "=", "DefaultTrickleInterval", "\n", "}", "\n\n", "p", ":=", "Peer", "{", "inbound", ":", "inbound", ",", "wireEncoding", ":", "wire", ".", "BaseEncoding", ",", "knownInventory", ":", "newMruInventoryMap", "(", "maxKnownInventory", ")", ",", "stallControl", ":", "make", "(", "chan", "stallControlMsg", ",", "1", ")", ",", "// nonblocking sync", "outputQueue", ":", "make", "(", "chan", "outMsg", ",", "outputBufferSize", ")", ",", "sendQueue", ":", "make", "(", "chan", "outMsg", ",", "1", ")", ",", "// nonblocking sync", "sendDoneQueue", ":", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", ",", "// nonblocking sync", "outputInvChan", ":", "make", "(", "chan", "*", "wire", ".", "InvVect", ",", "outputBufferSize", ")", ",", "inQuit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "queueQuit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "outQuit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "cfg", ":", "cfg", ",", "// Copy so caller can't mutate.", "services", ":", "cfg", ".", "Services", ",", "protocolVersion", ":", "cfg", ".", "ProtocolVersion", ",", "}", "\n", "return", "&", "p", "\n", "}" ]
// newPeerBase returns a new base bitcoin peer based on the inbound flag. This // is used by the NewInboundPeer and NewOutboundPeer functions to perform base // setup needed by both types of peers.
[ "newPeerBase", "returns", "a", "new", "base", "bitcoin", "peer", "based", "on", "the", "inbound", "flag", ".", "This", "is", "used", "by", "the", "NewInboundPeer", "and", "NewOutboundPeer", "functions", "to", "perform", "base", "setup", "needed", "by", "both", "types", "of", "peers", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L2155-L2191
train
btcsuite/btcd
peer/peer.go
NewOutboundPeer
func NewOutboundPeer(cfg *Config, addr string) (*Peer, error) { p := newPeerBase(cfg, false) p.addr = addr host, portStr, err := net.SplitHostPort(addr) if err != nil { return nil, err } port, err := strconv.ParseUint(portStr, 10, 16) if err != nil { return nil, err } if cfg.HostToNetAddress != nil { na, err := cfg.HostToNetAddress(host, uint16(port), 0) if err != nil { return nil, err } p.na = na } else { p.na = wire.NewNetAddressIPPort(net.ParseIP(host), uint16(port), 0) } return p, nil }
go
func NewOutboundPeer(cfg *Config, addr string) (*Peer, error) { p := newPeerBase(cfg, false) p.addr = addr host, portStr, err := net.SplitHostPort(addr) if err != nil { return nil, err } port, err := strconv.ParseUint(portStr, 10, 16) if err != nil { return nil, err } if cfg.HostToNetAddress != nil { na, err := cfg.HostToNetAddress(host, uint16(port), 0) if err != nil { return nil, err } p.na = na } else { p.na = wire.NewNetAddressIPPort(net.ParseIP(host), uint16(port), 0) } return p, nil }
[ "func", "NewOutboundPeer", "(", "cfg", "*", "Config", ",", "addr", "string", ")", "(", "*", "Peer", ",", "error", ")", "{", "p", ":=", "newPeerBase", "(", "cfg", ",", "false", ")", "\n", "p", ".", "addr", "=", "addr", "\n\n", "host", ",", "portStr", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "port", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "portStr", ",", "10", ",", "16", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "cfg", ".", "HostToNetAddress", "!=", "nil", "{", "na", ",", "err", ":=", "cfg", ".", "HostToNetAddress", "(", "host", ",", "uint16", "(", "port", ")", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "p", ".", "na", "=", "na", "\n", "}", "else", "{", "p", ".", "na", "=", "wire", ".", "NewNetAddressIPPort", "(", "net", ".", "ParseIP", "(", "host", ")", ",", "uint16", "(", "port", ")", ",", "0", ")", "\n", "}", "\n\n", "return", "p", ",", "nil", "\n", "}" ]
// NewOutboundPeer returns a new outbound bitcoin peer.
[ "NewOutboundPeer", "returns", "a", "new", "outbound", "bitcoin", "peer", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/peer.go#L2200-L2225
train
btcsuite/btcd
wire/message.go
makeEmptyMessage
func makeEmptyMessage(command string) (Message, error) { var msg Message switch command { case CmdVersion: msg = &MsgVersion{} case CmdVerAck: msg = &MsgVerAck{} case CmdGetAddr: msg = &MsgGetAddr{} case CmdAddr: msg = &MsgAddr{} case CmdGetBlocks: msg = &MsgGetBlocks{} case CmdBlock: msg = &MsgBlock{} case CmdInv: msg = &MsgInv{} case CmdGetData: msg = &MsgGetData{} case CmdNotFound: msg = &MsgNotFound{} case CmdTx: msg = &MsgTx{} case CmdPing: msg = &MsgPing{} case CmdPong: msg = &MsgPong{} case CmdGetHeaders: msg = &MsgGetHeaders{} case CmdHeaders: msg = &MsgHeaders{} case CmdAlert: msg = &MsgAlert{} case CmdMemPool: msg = &MsgMemPool{} case CmdFilterAdd: msg = &MsgFilterAdd{} case CmdFilterClear: msg = &MsgFilterClear{} case CmdFilterLoad: msg = &MsgFilterLoad{} case CmdMerkleBlock: msg = &MsgMerkleBlock{} case CmdReject: msg = &MsgReject{} case CmdSendHeaders: msg = &MsgSendHeaders{} case CmdFeeFilter: msg = &MsgFeeFilter{} case CmdGetCFilters: msg = &MsgGetCFilters{} case CmdGetCFHeaders: msg = &MsgGetCFHeaders{} case CmdGetCFCheckpt: msg = &MsgGetCFCheckpt{} case CmdCFilter: msg = &MsgCFilter{} case CmdCFHeaders: msg = &MsgCFHeaders{} case CmdCFCheckpt: msg = &MsgCFCheckpt{} default: return nil, fmt.Errorf("unhandled command [%s]", command) } return msg, nil }
go
func makeEmptyMessage(command string) (Message, error) { var msg Message switch command { case CmdVersion: msg = &MsgVersion{} case CmdVerAck: msg = &MsgVerAck{} case CmdGetAddr: msg = &MsgGetAddr{} case CmdAddr: msg = &MsgAddr{} case CmdGetBlocks: msg = &MsgGetBlocks{} case CmdBlock: msg = &MsgBlock{} case CmdInv: msg = &MsgInv{} case CmdGetData: msg = &MsgGetData{} case CmdNotFound: msg = &MsgNotFound{} case CmdTx: msg = &MsgTx{} case CmdPing: msg = &MsgPing{} case CmdPong: msg = &MsgPong{} case CmdGetHeaders: msg = &MsgGetHeaders{} case CmdHeaders: msg = &MsgHeaders{} case CmdAlert: msg = &MsgAlert{} case CmdMemPool: msg = &MsgMemPool{} case CmdFilterAdd: msg = &MsgFilterAdd{} case CmdFilterClear: msg = &MsgFilterClear{} case CmdFilterLoad: msg = &MsgFilterLoad{} case CmdMerkleBlock: msg = &MsgMerkleBlock{} case CmdReject: msg = &MsgReject{} case CmdSendHeaders: msg = &MsgSendHeaders{} case CmdFeeFilter: msg = &MsgFeeFilter{} case CmdGetCFilters: msg = &MsgGetCFilters{} case CmdGetCFHeaders: msg = &MsgGetCFHeaders{} case CmdGetCFCheckpt: msg = &MsgGetCFCheckpt{} case CmdCFilter: msg = &MsgCFilter{} case CmdCFHeaders: msg = &MsgCFHeaders{} case CmdCFCheckpt: msg = &MsgCFCheckpt{} default: return nil, fmt.Errorf("unhandled command [%s]", command) } return msg, nil }
[ "func", "makeEmptyMessage", "(", "command", "string", ")", "(", "Message", ",", "error", ")", "{", "var", "msg", "Message", "\n", "switch", "command", "{", "case", "CmdVersion", ":", "msg", "=", "&", "MsgVersion", "{", "}", "\n\n", "case", "CmdVerAck", ":", "msg", "=", "&", "MsgVerAck", "{", "}", "\n\n", "case", "CmdGetAddr", ":", "msg", "=", "&", "MsgGetAddr", "{", "}", "\n\n", "case", "CmdAddr", ":", "msg", "=", "&", "MsgAddr", "{", "}", "\n\n", "case", "CmdGetBlocks", ":", "msg", "=", "&", "MsgGetBlocks", "{", "}", "\n\n", "case", "CmdBlock", ":", "msg", "=", "&", "MsgBlock", "{", "}", "\n\n", "case", "CmdInv", ":", "msg", "=", "&", "MsgInv", "{", "}", "\n\n", "case", "CmdGetData", ":", "msg", "=", "&", "MsgGetData", "{", "}", "\n\n", "case", "CmdNotFound", ":", "msg", "=", "&", "MsgNotFound", "{", "}", "\n\n", "case", "CmdTx", ":", "msg", "=", "&", "MsgTx", "{", "}", "\n\n", "case", "CmdPing", ":", "msg", "=", "&", "MsgPing", "{", "}", "\n\n", "case", "CmdPong", ":", "msg", "=", "&", "MsgPong", "{", "}", "\n\n", "case", "CmdGetHeaders", ":", "msg", "=", "&", "MsgGetHeaders", "{", "}", "\n\n", "case", "CmdHeaders", ":", "msg", "=", "&", "MsgHeaders", "{", "}", "\n\n", "case", "CmdAlert", ":", "msg", "=", "&", "MsgAlert", "{", "}", "\n\n", "case", "CmdMemPool", ":", "msg", "=", "&", "MsgMemPool", "{", "}", "\n\n", "case", "CmdFilterAdd", ":", "msg", "=", "&", "MsgFilterAdd", "{", "}", "\n\n", "case", "CmdFilterClear", ":", "msg", "=", "&", "MsgFilterClear", "{", "}", "\n\n", "case", "CmdFilterLoad", ":", "msg", "=", "&", "MsgFilterLoad", "{", "}", "\n\n", "case", "CmdMerkleBlock", ":", "msg", "=", "&", "MsgMerkleBlock", "{", "}", "\n\n", "case", "CmdReject", ":", "msg", "=", "&", "MsgReject", "{", "}", "\n\n", "case", "CmdSendHeaders", ":", "msg", "=", "&", "MsgSendHeaders", "{", "}", "\n\n", "case", "CmdFeeFilter", ":", "msg", "=", "&", "MsgFeeFilter", "{", "}", "\n\n", "case", "CmdGetCFilters", ":", "msg", "=", "&", "MsgGetCFilters", "{", "}", "\n\n", "case", "CmdGetCFHeaders", ":", "msg", "=", "&", "MsgGetCFHeaders", "{", "}", "\n\n", "case", "CmdGetCFCheckpt", ":", "msg", "=", "&", "MsgGetCFCheckpt", "{", "}", "\n\n", "case", "CmdCFilter", ":", "msg", "=", "&", "MsgCFilter", "{", "}", "\n\n", "case", "CmdCFHeaders", ":", "msg", "=", "&", "MsgCFHeaders", "{", "}", "\n\n", "case", "CmdCFCheckpt", ":", "msg", "=", "&", "MsgCFCheckpt", "{", "}", "\n\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "command", ")", "\n", "}", "\n", "return", "msg", ",", "nil", "\n", "}" ]
// makeEmptyMessage creates a message of the appropriate concrete type based // on the command.
[ "makeEmptyMessage", "creates", "a", "message", "of", "the", "appropriate", "concrete", "type", "based", "on", "the", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/message.go#L93-L187
train
btcsuite/btcd
wire/message.go
readMessageHeader
func readMessageHeader(r io.Reader) (int, *messageHeader, error) { // Since readElements doesn't return the amount of bytes read, attempt // to read the entire header into a buffer first in case there is a // short read so the proper amount of read bytes are known. This works // since the header is a fixed size. var headerBytes [MessageHeaderSize]byte n, err := io.ReadFull(r, headerBytes[:]) if err != nil { return n, nil, err } hr := bytes.NewReader(headerBytes[:]) // Create and populate a messageHeader struct from the raw header bytes. hdr := messageHeader{} var command [CommandSize]byte readElements(hr, &hdr.magic, &command, &hdr.length, &hdr.checksum) // Strip trailing zeros from command string. hdr.command = string(bytes.TrimRight(command[:], string(0))) return n, &hdr, nil }
go
func readMessageHeader(r io.Reader) (int, *messageHeader, error) { // Since readElements doesn't return the amount of bytes read, attempt // to read the entire header into a buffer first in case there is a // short read so the proper amount of read bytes are known. This works // since the header is a fixed size. var headerBytes [MessageHeaderSize]byte n, err := io.ReadFull(r, headerBytes[:]) if err != nil { return n, nil, err } hr := bytes.NewReader(headerBytes[:]) // Create and populate a messageHeader struct from the raw header bytes. hdr := messageHeader{} var command [CommandSize]byte readElements(hr, &hdr.magic, &command, &hdr.length, &hdr.checksum) // Strip trailing zeros from command string. hdr.command = string(bytes.TrimRight(command[:], string(0))) return n, &hdr, nil }
[ "func", "readMessageHeader", "(", "r", "io", ".", "Reader", ")", "(", "int", ",", "*", "messageHeader", ",", "error", ")", "{", "// Since readElements doesn't return the amount of bytes read, attempt", "// to read the entire header into a buffer first in case there is a", "// short read so the proper amount of read bytes are known. This works", "// since the header is a fixed size.", "var", "headerBytes", "[", "MessageHeaderSize", "]", "byte", "\n", "n", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "headerBytes", "[", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "n", ",", "nil", ",", "err", "\n", "}", "\n", "hr", ":=", "bytes", ".", "NewReader", "(", "headerBytes", "[", ":", "]", ")", "\n\n", "// Create and populate a messageHeader struct from the raw header bytes.", "hdr", ":=", "messageHeader", "{", "}", "\n", "var", "command", "[", "CommandSize", "]", "byte", "\n", "readElements", "(", "hr", ",", "&", "hdr", ".", "magic", ",", "&", "command", ",", "&", "hdr", ".", "length", ",", "&", "hdr", ".", "checksum", ")", "\n\n", "// Strip trailing zeros from command string.", "hdr", ".", "command", "=", "string", "(", "bytes", ".", "TrimRight", "(", "command", "[", ":", "]", ",", "string", "(", "0", ")", ")", ")", "\n\n", "return", "n", ",", "&", "hdr", ",", "nil", "\n", "}" ]
// readMessageHeader reads a bitcoin message header from r.
[ "readMessageHeader", "reads", "a", "bitcoin", "message", "header", "from", "r", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/message.go#L198-L219
train
btcsuite/btcd
wire/message.go
discardInput
func discardInput(r io.Reader, n uint32) { maxSize := uint32(10 * 1024) // 10k at a time numReads := n / maxSize bytesRemaining := n % maxSize if n > 0 { buf := make([]byte, maxSize) for i := uint32(0); i < numReads; i++ { io.ReadFull(r, buf) } } if bytesRemaining > 0 { buf := make([]byte, bytesRemaining) io.ReadFull(r, buf) } }
go
func discardInput(r io.Reader, n uint32) { maxSize := uint32(10 * 1024) // 10k at a time numReads := n / maxSize bytesRemaining := n % maxSize if n > 0 { buf := make([]byte, maxSize) for i := uint32(0); i < numReads; i++ { io.ReadFull(r, buf) } } if bytesRemaining > 0 { buf := make([]byte, bytesRemaining) io.ReadFull(r, buf) } }
[ "func", "discardInput", "(", "r", "io", ".", "Reader", ",", "n", "uint32", ")", "{", "maxSize", ":=", "uint32", "(", "10", "*", "1024", ")", "// 10k at a time", "\n", "numReads", ":=", "n", "/", "maxSize", "\n", "bytesRemaining", ":=", "n", "%", "maxSize", "\n", "if", "n", ">", "0", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "maxSize", ")", "\n", "for", "i", ":=", "uint32", "(", "0", ")", ";", "i", "<", "numReads", ";", "i", "++", "{", "io", ".", "ReadFull", "(", "r", ",", "buf", ")", "\n", "}", "\n", "}", "\n", "if", "bytesRemaining", ">", "0", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "bytesRemaining", ")", "\n", "io", ".", "ReadFull", "(", "r", ",", "buf", ")", "\n", "}", "\n", "}" ]
// discardInput reads n bytes from reader r in chunks and discards the read // bytes. This is used to skip payloads when various errors occur and helps // prevent rogue nodes from causing massive memory allocation through forging // header length.
[ "discardInput", "reads", "n", "bytes", "from", "reader", "r", "in", "chunks", "and", "discards", "the", "read", "bytes", ".", "This", "is", "used", "to", "skip", "payloads", "when", "various", "errors", "occur", "and", "helps", "prevent", "rogue", "nodes", "from", "causing", "massive", "memory", "allocation", "through", "forging", "header", "length", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/message.go#L225-L239
train
btcsuite/btcd
wire/message.go
WriteMessageN
func WriteMessageN(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet) (int, error) { return WriteMessageWithEncodingN(w, msg, pver, btcnet, BaseEncoding) }
go
func WriteMessageN(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet) (int, error) { return WriteMessageWithEncodingN(w, msg, pver, btcnet, BaseEncoding) }
[ "func", "WriteMessageN", "(", "w", "io", ".", "Writer", ",", "msg", "Message", ",", "pver", "uint32", ",", "btcnet", "BitcoinNet", ")", "(", "int", ",", "error", ")", "{", "return", "WriteMessageWithEncodingN", "(", "w", ",", "msg", ",", "pver", ",", "btcnet", ",", "BaseEncoding", ")", "\n", "}" ]
// WriteMessageN writes a bitcoin Message to w including the necessary header // information and returns the number of bytes written. This function is the // same as WriteMessage except it also returns the number of bytes written.
[ "WriteMessageN", "writes", "a", "bitcoin", "Message", "to", "w", "including", "the", "necessary", "header", "information", "and", "returns", "the", "number", "of", "bytes", "written", ".", "This", "function", "is", "the", "same", "as", "WriteMessage", "except", "it", "also", "returns", "the", "number", "of", "bytes", "written", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/message.go#L244-L246
train
btcsuite/btcd
wire/message.go
WriteMessage
func WriteMessage(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet) error { _, err := WriteMessageN(w, msg, pver, btcnet) return err }
go
func WriteMessage(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet) error { _, err := WriteMessageN(w, msg, pver, btcnet) return err }
[ "func", "WriteMessage", "(", "w", "io", ".", "Writer", ",", "msg", "Message", ",", "pver", "uint32", ",", "btcnet", "BitcoinNet", ")", "error", "{", "_", ",", "err", ":=", "WriteMessageN", "(", "w", ",", "msg", ",", "pver", ",", "btcnet", ")", "\n", "return", "err", "\n", "}" ]
// WriteMessage writes a bitcoin Message to w including the necessary header // information. This function is the same as WriteMessageN except it doesn't // doesn't return the number of bytes written. This function is mainly provided // for backwards compatibility with the original API, but it's also useful for // callers that don't care about byte counts.
[ "WriteMessage", "writes", "a", "bitcoin", "Message", "to", "w", "including", "the", "necessary", "header", "information", ".", "This", "function", "is", "the", "same", "as", "WriteMessageN", "except", "it", "doesn", "t", "doesn", "t", "return", "the", "number", "of", "bytes", "written", ".", "This", "function", "is", "mainly", "provided", "for", "backwards", "compatibility", "with", "the", "original", "API", "but", "it", "s", "also", "useful", "for", "callers", "that", "don", "t", "care", "about", "byte", "counts", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/message.go#L253-L256
train
btcsuite/btcd
wire/message.go
WriteMessageWithEncodingN
func WriteMessageWithEncodingN(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet, encoding MessageEncoding) (int, error) { totalBytes := 0 // Enforce max command size. var command [CommandSize]byte cmd := msg.Command() if len(cmd) > CommandSize { str := fmt.Sprintf("command [%s] is too long [max %v]", cmd, CommandSize) return totalBytes, messageError("WriteMessage", str) } copy(command[:], []byte(cmd)) // Encode the message payload. var bw bytes.Buffer err := msg.BtcEncode(&bw, pver, encoding) if err != nil { return totalBytes, err } payload := bw.Bytes() lenp := len(payload) // Enforce maximum overall message payload. if lenp > MaxMessagePayload { str := fmt.Sprintf("message payload is too large - encoded "+ "%d bytes, but maximum message payload is %d bytes", lenp, MaxMessagePayload) return totalBytes, messageError("WriteMessage", str) } // Enforce maximum message payload based on the message type. mpl := msg.MaxPayloadLength(pver) if uint32(lenp) > mpl { str := fmt.Sprintf("message payload is too large - encoded "+ "%d bytes, but maximum message payload size for "+ "messages of type [%s] is %d.", lenp, cmd, mpl) return totalBytes, messageError("WriteMessage", str) } // Create header for the message. hdr := messageHeader{} hdr.magic = btcnet hdr.command = cmd hdr.length = uint32(lenp) copy(hdr.checksum[:], chainhash.DoubleHashB(payload)[0:4]) // Encode the header for the message. This is done to a buffer // rather than directly to the writer since writeElements doesn't // return the number of bytes written. hw := bytes.NewBuffer(make([]byte, 0, MessageHeaderSize)) writeElements(hw, hdr.magic, command, hdr.length, hdr.checksum) // Write header. n, err := w.Write(hw.Bytes()) totalBytes += n if err != nil { return totalBytes, err } // Write payload. n, err = w.Write(payload) totalBytes += n return totalBytes, err }
go
func WriteMessageWithEncodingN(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet, encoding MessageEncoding) (int, error) { totalBytes := 0 // Enforce max command size. var command [CommandSize]byte cmd := msg.Command() if len(cmd) > CommandSize { str := fmt.Sprintf("command [%s] is too long [max %v]", cmd, CommandSize) return totalBytes, messageError("WriteMessage", str) } copy(command[:], []byte(cmd)) // Encode the message payload. var bw bytes.Buffer err := msg.BtcEncode(&bw, pver, encoding) if err != nil { return totalBytes, err } payload := bw.Bytes() lenp := len(payload) // Enforce maximum overall message payload. if lenp > MaxMessagePayload { str := fmt.Sprintf("message payload is too large - encoded "+ "%d bytes, but maximum message payload is %d bytes", lenp, MaxMessagePayload) return totalBytes, messageError("WriteMessage", str) } // Enforce maximum message payload based on the message type. mpl := msg.MaxPayloadLength(pver) if uint32(lenp) > mpl { str := fmt.Sprintf("message payload is too large - encoded "+ "%d bytes, but maximum message payload size for "+ "messages of type [%s] is %d.", lenp, cmd, mpl) return totalBytes, messageError("WriteMessage", str) } // Create header for the message. hdr := messageHeader{} hdr.magic = btcnet hdr.command = cmd hdr.length = uint32(lenp) copy(hdr.checksum[:], chainhash.DoubleHashB(payload)[0:4]) // Encode the header for the message. This is done to a buffer // rather than directly to the writer since writeElements doesn't // return the number of bytes written. hw := bytes.NewBuffer(make([]byte, 0, MessageHeaderSize)) writeElements(hw, hdr.magic, command, hdr.length, hdr.checksum) // Write header. n, err := w.Write(hw.Bytes()) totalBytes += n if err != nil { return totalBytes, err } // Write payload. n, err = w.Write(payload) totalBytes += n return totalBytes, err }
[ "func", "WriteMessageWithEncodingN", "(", "w", "io", ".", "Writer", ",", "msg", "Message", ",", "pver", "uint32", ",", "btcnet", "BitcoinNet", ",", "encoding", "MessageEncoding", ")", "(", "int", ",", "error", ")", "{", "totalBytes", ":=", "0", "\n\n", "// Enforce max command size.", "var", "command", "[", "CommandSize", "]", "byte", "\n", "cmd", ":=", "msg", ".", "Command", "(", ")", "\n", "if", "len", "(", "cmd", ")", ">", "CommandSize", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cmd", ",", "CommandSize", ")", "\n", "return", "totalBytes", ",", "messageError", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n", "copy", "(", "command", "[", ":", "]", ",", "[", "]", "byte", "(", "cmd", ")", ")", "\n\n", "// Encode the message payload.", "var", "bw", "bytes", ".", "Buffer", "\n", "err", ":=", "msg", ".", "BtcEncode", "(", "&", "bw", ",", "pver", ",", "encoding", ")", "\n", "if", "err", "!=", "nil", "{", "return", "totalBytes", ",", "err", "\n", "}", "\n", "payload", ":=", "bw", ".", "Bytes", "(", ")", "\n", "lenp", ":=", "len", "(", "payload", ")", "\n\n", "// Enforce maximum overall message payload.", "if", "lenp", ">", "MaxMessagePayload", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "lenp", ",", "MaxMessagePayload", ")", "\n", "return", "totalBytes", ",", "messageError", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n\n", "// Enforce maximum message payload based on the message type.", "mpl", ":=", "msg", ".", "MaxPayloadLength", "(", "pver", ")", "\n", "if", "uint32", "(", "lenp", ")", ">", "mpl", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "lenp", ",", "cmd", ",", "mpl", ")", "\n", "return", "totalBytes", ",", "messageError", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n\n", "// Create header for the message.", "hdr", ":=", "messageHeader", "{", "}", "\n", "hdr", ".", "magic", "=", "btcnet", "\n", "hdr", ".", "command", "=", "cmd", "\n", "hdr", ".", "length", "=", "uint32", "(", "lenp", ")", "\n", "copy", "(", "hdr", ".", "checksum", "[", ":", "]", ",", "chainhash", ".", "DoubleHashB", "(", "payload", ")", "[", "0", ":", "4", "]", ")", "\n\n", "// Encode the header for the message. This is done to a buffer", "// rather than directly to the writer since writeElements doesn't", "// return the number of bytes written.", "hw", ":=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "MessageHeaderSize", ")", ")", "\n", "writeElements", "(", "hw", ",", "hdr", ".", "magic", ",", "command", ",", "hdr", ".", "length", ",", "hdr", ".", "checksum", ")", "\n\n", "// Write header.", "n", ",", "err", ":=", "w", ".", "Write", "(", "hw", ".", "Bytes", "(", ")", ")", "\n", "totalBytes", "+=", "n", "\n", "if", "err", "!=", "nil", "{", "return", "totalBytes", ",", "err", "\n", "}", "\n\n", "// Write payload.", "n", ",", "err", "=", "w", ".", "Write", "(", "payload", ")", "\n", "totalBytes", "+=", "n", "\n", "return", "totalBytes", ",", "err", "\n", "}" ]
// WriteMessageWithEncodingN writes a bitcoin Message to w including the // necessary header information and returns the number of bytes written. // This function is the same as WriteMessageN except it also allows the caller // to specify the message encoding format to be used when serializing wire // messages.
[ "WriteMessageWithEncodingN", "writes", "a", "bitcoin", "Message", "to", "w", "including", "the", "necessary", "header", "information", "and", "returns", "the", "number", "of", "bytes", "written", ".", "This", "function", "is", "the", "same", "as", "WriteMessageN", "except", "it", "also", "allows", "the", "caller", "to", "specify", "the", "message", "encoding", "format", "to", "be", "used", "when", "serializing", "wire", "messages", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/message.go#L263-L328
train
btcsuite/btcd
wire/message.go
ReadMessageWithEncodingN
func ReadMessageWithEncodingN(r io.Reader, pver uint32, btcnet BitcoinNet, enc MessageEncoding) (int, Message, []byte, error) { totalBytes := 0 n, hdr, err := readMessageHeader(r) totalBytes += n if err != nil { return totalBytes, nil, nil, err } // Enforce maximum message payload. if hdr.length > MaxMessagePayload { str := fmt.Sprintf("message payload is too large - header "+ "indicates %d bytes, but max message payload is %d "+ "bytes.", hdr.length, MaxMessagePayload) return totalBytes, nil, nil, messageError("ReadMessage", str) } // Check for messages from the wrong bitcoin network. if hdr.magic != btcnet { discardInput(r, hdr.length) str := fmt.Sprintf("message from other network [%v]", hdr.magic) return totalBytes, nil, nil, messageError("ReadMessage", str) } // Check for malformed commands. command := hdr.command if !utf8.ValidString(command) { discardInput(r, hdr.length) str := fmt.Sprintf("invalid command %v", []byte(command)) return totalBytes, nil, nil, messageError("ReadMessage", str) } // Create struct of appropriate message type based on the command. msg, err := makeEmptyMessage(command) if err != nil { discardInput(r, hdr.length) return totalBytes, nil, nil, messageError("ReadMessage", err.Error()) } // Check for maximum length based on the message type as a malicious client // could otherwise create a well-formed header and set the length to max // numbers in order to exhaust the machine's memory. mpl := msg.MaxPayloadLength(pver) if hdr.length > mpl { discardInput(r, hdr.length) str := fmt.Sprintf("payload exceeds max length - header "+ "indicates %v bytes, but max payload size for "+ "messages of type [%v] is %v.", hdr.length, command, mpl) return totalBytes, nil, nil, messageError("ReadMessage", str) } // Read payload. payload := make([]byte, hdr.length) n, err = io.ReadFull(r, payload) totalBytes += n if err != nil { return totalBytes, nil, nil, err } // Test checksum. checksum := chainhash.DoubleHashB(payload)[0:4] if !bytes.Equal(checksum[:], hdr.checksum[:]) { str := fmt.Sprintf("payload checksum failed - header "+ "indicates %v, but actual checksum is %v.", hdr.checksum, checksum) return totalBytes, nil, nil, messageError("ReadMessage", str) } // Unmarshal message. NOTE: This must be a *bytes.Buffer since the // MsgVersion BtcDecode function requires it. pr := bytes.NewBuffer(payload) err = msg.BtcDecode(pr, pver, enc) if err != nil { return totalBytes, nil, nil, err } return totalBytes, msg, payload, nil }
go
func ReadMessageWithEncodingN(r io.Reader, pver uint32, btcnet BitcoinNet, enc MessageEncoding) (int, Message, []byte, error) { totalBytes := 0 n, hdr, err := readMessageHeader(r) totalBytes += n if err != nil { return totalBytes, nil, nil, err } // Enforce maximum message payload. if hdr.length > MaxMessagePayload { str := fmt.Sprintf("message payload is too large - header "+ "indicates %d bytes, but max message payload is %d "+ "bytes.", hdr.length, MaxMessagePayload) return totalBytes, nil, nil, messageError("ReadMessage", str) } // Check for messages from the wrong bitcoin network. if hdr.magic != btcnet { discardInput(r, hdr.length) str := fmt.Sprintf("message from other network [%v]", hdr.magic) return totalBytes, nil, nil, messageError("ReadMessage", str) } // Check for malformed commands. command := hdr.command if !utf8.ValidString(command) { discardInput(r, hdr.length) str := fmt.Sprintf("invalid command %v", []byte(command)) return totalBytes, nil, nil, messageError("ReadMessage", str) } // Create struct of appropriate message type based on the command. msg, err := makeEmptyMessage(command) if err != nil { discardInput(r, hdr.length) return totalBytes, nil, nil, messageError("ReadMessage", err.Error()) } // Check for maximum length based on the message type as a malicious client // could otherwise create a well-formed header and set the length to max // numbers in order to exhaust the machine's memory. mpl := msg.MaxPayloadLength(pver) if hdr.length > mpl { discardInput(r, hdr.length) str := fmt.Sprintf("payload exceeds max length - header "+ "indicates %v bytes, but max payload size for "+ "messages of type [%v] is %v.", hdr.length, command, mpl) return totalBytes, nil, nil, messageError("ReadMessage", str) } // Read payload. payload := make([]byte, hdr.length) n, err = io.ReadFull(r, payload) totalBytes += n if err != nil { return totalBytes, nil, nil, err } // Test checksum. checksum := chainhash.DoubleHashB(payload)[0:4] if !bytes.Equal(checksum[:], hdr.checksum[:]) { str := fmt.Sprintf("payload checksum failed - header "+ "indicates %v, but actual checksum is %v.", hdr.checksum, checksum) return totalBytes, nil, nil, messageError("ReadMessage", str) } // Unmarshal message. NOTE: This must be a *bytes.Buffer since the // MsgVersion BtcDecode function requires it. pr := bytes.NewBuffer(payload) err = msg.BtcDecode(pr, pver, enc) if err != nil { return totalBytes, nil, nil, err } return totalBytes, msg, payload, nil }
[ "func", "ReadMessageWithEncodingN", "(", "r", "io", ".", "Reader", ",", "pver", "uint32", ",", "btcnet", "BitcoinNet", ",", "enc", "MessageEncoding", ")", "(", "int", ",", "Message", ",", "[", "]", "byte", ",", "error", ")", "{", "totalBytes", ":=", "0", "\n", "n", ",", "hdr", ",", "err", ":=", "readMessageHeader", "(", "r", ")", "\n", "totalBytes", "+=", "n", "\n", "if", "err", "!=", "nil", "{", "return", "totalBytes", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// Enforce maximum message payload.", "if", "hdr", ".", "length", ">", "MaxMessagePayload", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "hdr", ".", "length", ",", "MaxMessagePayload", ")", "\n", "return", "totalBytes", ",", "nil", ",", "nil", ",", "messageError", "(", "\"", "\"", ",", "str", ")", "\n\n", "}", "\n\n", "// Check for messages from the wrong bitcoin network.", "if", "hdr", ".", "magic", "!=", "btcnet", "{", "discardInput", "(", "r", ",", "hdr", ".", "length", ")", "\n", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "hdr", ".", "magic", ")", "\n", "return", "totalBytes", ",", "nil", ",", "nil", ",", "messageError", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n\n", "// Check for malformed commands.", "command", ":=", "hdr", ".", "command", "\n", "if", "!", "utf8", ".", "ValidString", "(", "command", ")", "{", "discardInput", "(", "r", ",", "hdr", ".", "length", ")", "\n", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "[", "]", "byte", "(", "command", ")", ")", "\n", "return", "totalBytes", ",", "nil", ",", "nil", ",", "messageError", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n\n", "// Create struct of appropriate message type based on the command.", "msg", ",", "err", ":=", "makeEmptyMessage", "(", "command", ")", "\n", "if", "err", "!=", "nil", "{", "discardInput", "(", "r", ",", "hdr", ".", "length", ")", "\n", "return", "totalBytes", ",", "nil", ",", "nil", ",", "messageError", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "// Check for maximum length based on the message type as a malicious client", "// could otherwise create a well-formed header and set the length to max", "// numbers in order to exhaust the machine's memory.", "mpl", ":=", "msg", ".", "MaxPayloadLength", "(", "pver", ")", "\n", "if", "hdr", ".", "length", ">", "mpl", "{", "discardInput", "(", "r", ",", "hdr", ".", "length", ")", "\n", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "hdr", ".", "length", ",", "command", ",", "mpl", ")", "\n", "return", "totalBytes", ",", "nil", ",", "nil", ",", "messageError", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n\n", "// Read payload.", "payload", ":=", "make", "(", "[", "]", "byte", ",", "hdr", ".", "length", ")", "\n", "n", ",", "err", "=", "io", ".", "ReadFull", "(", "r", ",", "payload", ")", "\n", "totalBytes", "+=", "n", "\n", "if", "err", "!=", "nil", "{", "return", "totalBytes", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// Test checksum.", "checksum", ":=", "chainhash", ".", "DoubleHashB", "(", "payload", ")", "[", "0", ":", "4", "]", "\n", "if", "!", "bytes", ".", "Equal", "(", "checksum", "[", ":", "]", ",", "hdr", ".", "checksum", "[", ":", "]", ")", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "hdr", ".", "checksum", ",", "checksum", ")", "\n", "return", "totalBytes", ",", "nil", ",", "nil", ",", "messageError", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n\n", "// Unmarshal message. NOTE: This must be a *bytes.Buffer since the", "// MsgVersion BtcDecode function requires it.", "pr", ":=", "bytes", ".", "NewBuffer", "(", "payload", ")", "\n", "err", "=", "msg", ".", "BtcDecode", "(", "pr", ",", "pver", ",", "enc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "totalBytes", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "return", "totalBytes", ",", "msg", ",", "payload", ",", "nil", "\n", "}" ]
// ReadMessageWithEncodingN reads, validates, and parses the next bitcoin Message // from r for the provided protocol version and bitcoin network. It returns the // number of bytes read in addition to the parsed Message and raw bytes which // comprise the message. This function is the same as ReadMessageN except it // allows the caller to specify which message encoding is to to consult when // decoding wire messages.
[ "ReadMessageWithEncodingN", "reads", "validates", "and", "parses", "the", "next", "bitcoin", "Message", "from", "r", "for", "the", "provided", "protocol", "version", "and", "bitcoin", "network", ".", "It", "returns", "the", "number", "of", "bytes", "read", "in", "addition", "to", "the", "parsed", "Message", "and", "raw", "bytes", "which", "comprise", "the", "message", ".", "This", "function", "is", "the", "same", "as", "ReadMessageN", "except", "it", "allows", "the", "caller", "to", "specify", "which", "message", "encoding", "is", "to", "to", "consult", "when", "decoding", "wire", "messages", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/message.go#L336-L416
train
btcsuite/btcd
wire/message.go
ReadMessageN
func ReadMessageN(r io.Reader, pver uint32, btcnet BitcoinNet) (int, Message, []byte, error) { return ReadMessageWithEncodingN(r, pver, btcnet, BaseEncoding) }
go
func ReadMessageN(r io.Reader, pver uint32, btcnet BitcoinNet) (int, Message, []byte, error) { return ReadMessageWithEncodingN(r, pver, btcnet, BaseEncoding) }
[ "func", "ReadMessageN", "(", "r", "io", ".", "Reader", ",", "pver", "uint32", ",", "btcnet", "BitcoinNet", ")", "(", "int", ",", "Message", ",", "[", "]", "byte", ",", "error", ")", "{", "return", "ReadMessageWithEncodingN", "(", "r", ",", "pver", ",", "btcnet", ",", "BaseEncoding", ")", "\n", "}" ]
// ReadMessageN reads, validates, and parses the next bitcoin Message from r for // the provided protocol version and bitcoin network. It returns the number of // bytes read in addition to the parsed Message and raw bytes which comprise the // message. This function is the same as ReadMessage except it also returns the // number of bytes read.
[ "ReadMessageN", "reads", "validates", "and", "parses", "the", "next", "bitcoin", "Message", "from", "r", "for", "the", "provided", "protocol", "version", "and", "bitcoin", "network", ".", "It", "returns", "the", "number", "of", "bytes", "read", "in", "addition", "to", "the", "parsed", "Message", "and", "raw", "bytes", "which", "comprise", "the", "message", ".", "This", "function", "is", "the", "same", "as", "ReadMessage", "except", "it", "also", "returns", "the", "number", "of", "bytes", "read", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/message.go#L423-L425
train
btcsuite/btcd
wire/message.go
ReadMessage
func ReadMessage(r io.Reader, pver uint32, btcnet BitcoinNet) (Message, []byte, error) { _, msg, buf, err := ReadMessageN(r, pver, btcnet) return msg, buf, err }
go
func ReadMessage(r io.Reader, pver uint32, btcnet BitcoinNet) (Message, []byte, error) { _, msg, buf, err := ReadMessageN(r, pver, btcnet) return msg, buf, err }
[ "func", "ReadMessage", "(", "r", "io", ".", "Reader", ",", "pver", "uint32", ",", "btcnet", "BitcoinNet", ")", "(", "Message", ",", "[", "]", "byte", ",", "error", ")", "{", "_", ",", "msg", ",", "buf", ",", "err", ":=", "ReadMessageN", "(", "r", ",", "pver", ",", "btcnet", ")", "\n", "return", "msg", ",", "buf", ",", "err", "\n", "}" ]
// ReadMessage reads, validates, and parses the next bitcoin Message from r for // the provided protocol version and bitcoin network. It returns the parsed // Message and raw bytes which comprise the message. This function only differs // from ReadMessageN in that it doesn't return the number of bytes read. This // function is mainly provided for backwards compatibility with the original // API, but it's also useful for callers that don't care about byte counts.
[ "ReadMessage", "reads", "validates", "and", "parses", "the", "next", "bitcoin", "Message", "from", "r", "for", "the", "provided", "protocol", "version", "and", "bitcoin", "network", ".", "It", "returns", "the", "parsed", "Message", "and", "raw", "bytes", "which", "comprise", "the", "message", ".", "This", "function", "only", "differs", "from", "ReadMessageN", "in", "that", "it", "doesn", "t", "return", "the", "number", "of", "bytes", "read", ".", "This", "function", "is", "mainly", "provided", "for", "backwards", "compatibility", "with", "the", "original", "API", "but", "it", "s", "also", "useful", "for", "callers", "that", "don", "t", "care", "about", "byte", "counts", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/message.go#L433-L436
train
btcsuite/btcd
database/internal/treap/treapiter.go
limitIterator
func (iter *Iterator) limitIterator() bool { if iter.node == nil { return false } node := iter.node if iter.startKey != nil && bytes.Compare(node.key, iter.startKey) < 0 { iter.node = nil return false } if iter.limitKey != nil && bytes.Compare(node.key, iter.limitKey) >= 0 { iter.node = nil return false } return true }
go
func (iter *Iterator) limitIterator() bool { if iter.node == nil { return false } node := iter.node if iter.startKey != nil && bytes.Compare(node.key, iter.startKey) < 0 { iter.node = nil return false } if iter.limitKey != nil && bytes.Compare(node.key, iter.limitKey) >= 0 { iter.node = nil return false } return true }
[ "func", "(", "iter", "*", "Iterator", ")", "limitIterator", "(", ")", "bool", "{", "if", "iter", ".", "node", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "node", ":=", "iter", ".", "node", "\n", "if", "iter", ".", "startKey", "!=", "nil", "&&", "bytes", ".", "Compare", "(", "node", ".", "key", ",", "iter", ".", "startKey", ")", "<", "0", "{", "iter", ".", "node", "=", "nil", "\n", "return", "false", "\n", "}", "\n\n", "if", "iter", ".", "limitKey", "!=", "nil", "&&", "bytes", ".", "Compare", "(", "node", ".", "key", ",", "iter", ".", "limitKey", ")", ">=", "0", "{", "iter", ".", "node", "=", "nil", "\n", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// limitIterator clears the current iterator node if it is outside of the range // specified when the iterator was created. It returns whether the iterator is // valid.
[ "limitIterator", "clears", "the", "current", "iterator", "node", "if", "it", "is", "outside", "of", "the", "range", "specified", "when", "the", "iterator", "was", "created", ".", "It", "returns", "whether", "the", "iterator", "is", "valid", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/internal/treap/treapiter.go#L25-L42
train
btcsuite/btcd
btcjson/chainsvrresults.go
MarshalJSON
func (v *Vin) MarshalJSON() ([]byte, error) { if v.IsCoinBase() { coinbaseStruct := struct { Coinbase string `json:"coinbase"` Sequence uint32 `json:"sequence"` Witness []string `json:"witness,omitempty"` }{ Coinbase: v.Coinbase, Sequence: v.Sequence, Witness: v.Witness, } return json.Marshal(coinbaseStruct) } if v.HasWitness() { txStruct := struct { Txid string `json:"txid"` Vout uint32 `json:"vout"` ScriptSig *ScriptSig `json:"scriptSig"` Witness []string `json:"txinwitness"` Sequence uint32 `json:"sequence"` }{ Txid: v.Txid, Vout: v.Vout, ScriptSig: v.ScriptSig, Witness: v.Witness, Sequence: v.Sequence, } return json.Marshal(txStruct) } txStruct := struct { Txid string `json:"txid"` Vout uint32 `json:"vout"` ScriptSig *ScriptSig `json:"scriptSig"` Sequence uint32 `json:"sequence"` }{ Txid: v.Txid, Vout: v.Vout, ScriptSig: v.ScriptSig, Sequence: v.Sequence, } return json.Marshal(txStruct) }
go
func (v *Vin) MarshalJSON() ([]byte, error) { if v.IsCoinBase() { coinbaseStruct := struct { Coinbase string `json:"coinbase"` Sequence uint32 `json:"sequence"` Witness []string `json:"witness,omitempty"` }{ Coinbase: v.Coinbase, Sequence: v.Sequence, Witness: v.Witness, } return json.Marshal(coinbaseStruct) } if v.HasWitness() { txStruct := struct { Txid string `json:"txid"` Vout uint32 `json:"vout"` ScriptSig *ScriptSig `json:"scriptSig"` Witness []string `json:"txinwitness"` Sequence uint32 `json:"sequence"` }{ Txid: v.Txid, Vout: v.Vout, ScriptSig: v.ScriptSig, Witness: v.Witness, Sequence: v.Sequence, } return json.Marshal(txStruct) } txStruct := struct { Txid string `json:"txid"` Vout uint32 `json:"vout"` ScriptSig *ScriptSig `json:"scriptSig"` Sequence uint32 `json:"sequence"` }{ Txid: v.Txid, Vout: v.Vout, ScriptSig: v.ScriptSig, Sequence: v.Sequence, } return json.Marshal(txStruct) }
[ "func", "(", "v", "*", "Vin", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "v", ".", "IsCoinBase", "(", ")", "{", "coinbaseStruct", ":=", "struct", "{", "Coinbase", "string", "`json:\"coinbase\"`", "\n", "Sequence", "uint32", "`json:\"sequence\"`", "\n", "Witness", "[", "]", "string", "`json:\"witness,omitempty\"`", "\n", "}", "{", "Coinbase", ":", "v", ".", "Coinbase", ",", "Sequence", ":", "v", ".", "Sequence", ",", "Witness", ":", "v", ".", "Witness", ",", "}", "\n", "return", "json", ".", "Marshal", "(", "coinbaseStruct", ")", "\n", "}", "\n\n", "if", "v", ".", "HasWitness", "(", ")", "{", "txStruct", ":=", "struct", "{", "Txid", "string", "`json:\"txid\"`", "\n", "Vout", "uint32", "`json:\"vout\"`", "\n", "ScriptSig", "*", "ScriptSig", "`json:\"scriptSig\"`", "\n", "Witness", "[", "]", "string", "`json:\"txinwitness\"`", "\n", "Sequence", "uint32", "`json:\"sequence\"`", "\n", "}", "{", "Txid", ":", "v", ".", "Txid", ",", "Vout", ":", "v", ".", "Vout", ",", "ScriptSig", ":", "v", ".", "ScriptSig", ",", "Witness", ":", "v", ".", "Witness", ",", "Sequence", ":", "v", ".", "Sequence", ",", "}", "\n", "return", "json", ".", "Marshal", "(", "txStruct", ")", "\n", "}", "\n\n", "txStruct", ":=", "struct", "{", "Txid", "string", "`json:\"txid\"`", "\n", "Vout", "uint32", "`json:\"vout\"`", "\n", "ScriptSig", "*", "ScriptSig", "`json:\"scriptSig\"`", "\n", "Sequence", "uint32", "`json:\"sequence\"`", "\n", "}", "{", "Txid", ":", "v", ".", "Txid", ",", "Vout", ":", "v", ".", "Vout", ",", "ScriptSig", ":", "v", ".", "ScriptSig", ",", "Sequence", ":", "v", ".", "Sequence", ",", "}", "\n", "return", "json", ".", "Marshal", "(", "txStruct", ")", "\n", "}" ]
// MarshalJSON provides a custom Marshal method for Vin.
[ "MarshalJSON", "provides", "a", "custom", "Marshal", "method", "for", "Vin", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrresults.go#L334-L377
train
btcsuite/btcd
wire/msgheaders.go
AddBlockHeader
func (msg *MsgHeaders) AddBlockHeader(bh *BlockHeader) error { if len(msg.Headers)+1 > MaxBlockHeadersPerMsg { str := fmt.Sprintf("too many block headers in message [max %v]", MaxBlockHeadersPerMsg) return messageError("MsgHeaders.AddBlockHeader", str) } msg.Headers = append(msg.Headers, bh) return nil }
go
func (msg *MsgHeaders) AddBlockHeader(bh *BlockHeader) error { if len(msg.Headers)+1 > MaxBlockHeadersPerMsg { str := fmt.Sprintf("too many block headers in message [max %v]", MaxBlockHeadersPerMsg) return messageError("MsgHeaders.AddBlockHeader", str) } msg.Headers = append(msg.Headers, bh) return nil }
[ "func", "(", "msg", "*", "MsgHeaders", ")", "AddBlockHeader", "(", "bh", "*", "BlockHeader", ")", "error", "{", "if", "len", "(", "msg", ".", "Headers", ")", "+", "1", ">", "MaxBlockHeadersPerMsg", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "MaxBlockHeadersPerMsg", ")", "\n", "return", "messageError", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n\n", "msg", ".", "Headers", "=", "append", "(", "msg", ".", "Headers", ",", "bh", ")", "\n", "return", "nil", "\n", "}" ]
// AddBlockHeader adds a new block header to the message.
[ "AddBlockHeader", "adds", "a", "new", "block", "header", "to", "the", "message", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgheaders.go#L26-L35
train
btcsuite/btcd
btcd.go
removeRegressionDB
func removeRegressionDB(dbPath string) error { // Don't do anything if not in regression test mode. if !cfg.RegressionTest { return nil } // Remove the old regression test database if it already exists. fi, err := os.Stat(dbPath) if err == nil { btcdLog.Infof("Removing regression test database from '%s'", dbPath) if fi.IsDir() { err := os.RemoveAll(dbPath) if err != nil { return err } } else { err := os.Remove(dbPath) if err != nil { return err } } } return nil }
go
func removeRegressionDB(dbPath string) error { // Don't do anything if not in regression test mode. if !cfg.RegressionTest { return nil } // Remove the old regression test database if it already exists. fi, err := os.Stat(dbPath) if err == nil { btcdLog.Infof("Removing regression test database from '%s'", dbPath) if fi.IsDir() { err := os.RemoveAll(dbPath) if err != nil { return err } } else { err := os.Remove(dbPath) if err != nil { return err } } } return nil }
[ "func", "removeRegressionDB", "(", "dbPath", "string", ")", "error", "{", "// Don't do anything if not in regression test mode.", "if", "!", "cfg", ".", "RegressionTest", "{", "return", "nil", "\n", "}", "\n\n", "// Remove the old regression test database if it already exists.", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "dbPath", ")", "\n", "if", "err", "==", "nil", "{", "btcdLog", ".", "Infof", "(", "\"", "\"", ",", "dbPath", ")", "\n", "if", "fi", ".", "IsDir", "(", ")", "{", "err", ":=", "os", ".", "RemoveAll", "(", "dbPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "err", ":=", "os", ".", "Remove", "(", "dbPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// removeRegressionDB removes the existing regression test database if running // in regression test mode and it already exists.
[ "removeRegressionDB", "removes", "the", "existing", "regression", "test", "database", "if", "running", "in", "regression", "test", "mode", "and", "it", "already", "exists", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcd.go#L176-L200
train
btcsuite/btcd
btcd.go
blockDbPath
func blockDbPath(dbType string) string { // The database name is based on the database type. dbName := blockDbNamePrefix + "_" + dbType if dbType == "sqlite" { dbName = dbName + ".db" } dbPath := filepath.Join(cfg.DataDir, dbName) return dbPath }
go
func blockDbPath(dbType string) string { // The database name is based on the database type. dbName := blockDbNamePrefix + "_" + dbType if dbType == "sqlite" { dbName = dbName + ".db" } dbPath := filepath.Join(cfg.DataDir, dbName) return dbPath }
[ "func", "blockDbPath", "(", "dbType", "string", ")", "string", "{", "// The database name is based on the database type.", "dbName", ":=", "blockDbNamePrefix", "+", "\"", "\"", "+", "dbType", "\n", "if", "dbType", "==", "\"", "\"", "{", "dbName", "=", "dbName", "+", "\"", "\"", "\n", "}", "\n", "dbPath", ":=", "filepath", ".", "Join", "(", "cfg", ".", "DataDir", ",", "dbName", ")", "\n", "return", "dbPath", "\n", "}" ]
// dbPath returns the path to the block database given a database type.
[ "dbPath", "returns", "the", "path", "to", "the", "block", "database", "given", "a", "database", "type", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcd.go#L203-L211
train
btcsuite/btcd
btcd.go
warnMultipleDBs
func warnMultipleDBs() { // This is intentionally not using the known db types which depend // on the database types compiled into the binary since we want to // detect legacy db types as well. dbTypes := []string{"ffldb", "leveldb", "sqlite"} duplicateDbPaths := make([]string, 0, len(dbTypes)-1) for _, dbType := range dbTypes { if dbType == cfg.DbType { continue } // Store db path as a duplicate db if it exists. dbPath := blockDbPath(dbType) if fileExists(dbPath) { duplicateDbPaths = append(duplicateDbPaths, dbPath) } } // Warn if there are extra databases. if len(duplicateDbPaths) > 0 { selectedDbPath := blockDbPath(cfg.DbType) btcdLog.Warnf("WARNING: There are multiple block chain databases "+ "using different database types.\nYou probably don't "+ "want to waste disk space by having more than one.\n"+ "Your current database is located at [%v].\nThe "+ "additional database is located at %v", selectedDbPath, duplicateDbPaths) } }
go
func warnMultipleDBs() { // This is intentionally not using the known db types which depend // on the database types compiled into the binary since we want to // detect legacy db types as well. dbTypes := []string{"ffldb", "leveldb", "sqlite"} duplicateDbPaths := make([]string, 0, len(dbTypes)-1) for _, dbType := range dbTypes { if dbType == cfg.DbType { continue } // Store db path as a duplicate db if it exists. dbPath := blockDbPath(dbType) if fileExists(dbPath) { duplicateDbPaths = append(duplicateDbPaths, dbPath) } } // Warn if there are extra databases. if len(duplicateDbPaths) > 0 { selectedDbPath := blockDbPath(cfg.DbType) btcdLog.Warnf("WARNING: There are multiple block chain databases "+ "using different database types.\nYou probably don't "+ "want to waste disk space by having more than one.\n"+ "Your current database is located at [%v].\nThe "+ "additional database is located at %v", selectedDbPath, duplicateDbPaths) } }
[ "func", "warnMultipleDBs", "(", ")", "{", "// This is intentionally not using the known db types which depend", "// on the database types compiled into the binary since we want to", "// detect legacy db types as well.", "dbTypes", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "\n", "duplicateDbPaths", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "dbTypes", ")", "-", "1", ")", "\n", "for", "_", ",", "dbType", ":=", "range", "dbTypes", "{", "if", "dbType", "==", "cfg", ".", "DbType", "{", "continue", "\n", "}", "\n\n", "// Store db path as a duplicate db if it exists.", "dbPath", ":=", "blockDbPath", "(", "dbType", ")", "\n", "if", "fileExists", "(", "dbPath", ")", "{", "duplicateDbPaths", "=", "append", "(", "duplicateDbPaths", ",", "dbPath", ")", "\n", "}", "\n", "}", "\n\n", "// Warn if there are extra databases.", "if", "len", "(", "duplicateDbPaths", ")", ">", "0", "{", "selectedDbPath", ":=", "blockDbPath", "(", "cfg", ".", "DbType", ")", "\n", "btcdLog", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", "\"", ",", "selectedDbPath", ",", "duplicateDbPaths", ")", "\n", "}", "\n", "}" ]
// warnMultipleDBs shows a warning if multiple block database types are detected. // This is not a situation most users want. It is handy for development however // to support multiple side-by-side databases.
[ "warnMultipleDBs", "shows", "a", "warning", "if", "multiple", "block", "database", "types", "are", "detected", ".", "This", "is", "not", "a", "situation", "most", "users", "want", ".", "It", "is", "handy", "for", "development", "however", "to", "support", "multiple", "side", "-", "by", "-", "side", "databases", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcd.go#L216-L244
train
btcsuite/btcd
wire/msgversion.go
HasService
func (msg *MsgVersion) HasService(service ServiceFlag) bool { return msg.Services&service == service }
go
func (msg *MsgVersion) HasService(service ServiceFlag) bool { return msg.Services&service == service }
[ "func", "(", "msg", "*", "MsgVersion", ")", "HasService", "(", "service", "ServiceFlag", ")", "bool", "{", "return", "msg", ".", "Services", "&", "service", "==", "service", "\n", "}" ]
// HasService returns whether the specified service is supported by the peer // that generated the message.
[ "HasService", "returns", "whether", "the", "specified", "service", "is", "supported", "by", "the", "peer", "that", "generated", "the", "message", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgversion.go#L62-L64
train
btcsuite/btcd
wire/msgversion.go
NewMsgVersion
func NewMsgVersion(me *NetAddress, you *NetAddress, nonce uint64, lastBlock int32) *MsgVersion { // Limit the timestamp to one second precision since the protocol // doesn't support better. return &MsgVersion{ ProtocolVersion: int32(ProtocolVersion), Services: 0, Timestamp: time.Unix(time.Now().Unix(), 0), AddrYou: *you, AddrMe: *me, Nonce: nonce, UserAgent: DefaultUserAgent, LastBlock: lastBlock, DisableRelayTx: false, } }
go
func NewMsgVersion(me *NetAddress, you *NetAddress, nonce uint64, lastBlock int32) *MsgVersion { // Limit the timestamp to one second precision since the protocol // doesn't support better. return &MsgVersion{ ProtocolVersion: int32(ProtocolVersion), Services: 0, Timestamp: time.Unix(time.Now().Unix(), 0), AddrYou: *you, AddrMe: *me, Nonce: nonce, UserAgent: DefaultUserAgent, LastBlock: lastBlock, DisableRelayTx: false, } }
[ "func", "NewMsgVersion", "(", "me", "*", "NetAddress", ",", "you", "*", "NetAddress", ",", "nonce", "uint64", ",", "lastBlock", "int32", ")", "*", "MsgVersion", "{", "// Limit the timestamp to one second precision since the protocol", "// doesn't support better.", "return", "&", "MsgVersion", "{", "ProtocolVersion", ":", "int32", "(", "ProtocolVersion", ")", ",", "Services", ":", "0", ",", "Timestamp", ":", "time", ".", "Unix", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ",", "0", ")", ",", "AddrYou", ":", "*", "you", ",", "AddrMe", ":", "*", "me", ",", "Nonce", ":", "nonce", ",", "UserAgent", ":", "DefaultUserAgent", ",", "LastBlock", ":", "lastBlock", ",", "DisableRelayTx", ":", "false", ",", "}", "\n", "}" ]
// NewMsgVersion returns a new bitcoin version message that conforms to the // Message interface using the passed parameters and defaults for the remaining // fields.
[ "NewMsgVersion", "returns", "a", "new", "bitcoin", "version", "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/msgversion.go#L223-L239
train
btcsuite/btcd
wire/msgversion.go
validateUserAgent
func validateUserAgent(userAgent string) error { if len(userAgent) > MaxUserAgentLen { str := fmt.Sprintf("user agent too long [len %v, max %v]", len(userAgent), MaxUserAgentLen) return messageError("MsgVersion", str) } return nil }
go
func validateUserAgent(userAgent string) error { if len(userAgent) > MaxUserAgentLen { str := fmt.Sprintf("user agent too long [len %v, max %v]", len(userAgent), MaxUserAgentLen) return messageError("MsgVersion", str) } return nil }
[ "func", "validateUserAgent", "(", "userAgent", "string", ")", "error", "{", "if", "len", "(", "userAgent", ")", ">", "MaxUserAgentLen", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "len", "(", "userAgent", ")", ",", "MaxUserAgentLen", ")", "\n", "return", "messageError", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateUserAgent checks userAgent length against MaxUserAgentLen
[ "validateUserAgent", "checks", "userAgent", "length", "against", "MaxUserAgentLen" ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgversion.go#L242-L249
train
btcsuite/btcd
upgrade.go
dirEmpty
func dirEmpty(dirPath string) (bool, error) { f, err := os.Open(dirPath) if err != nil { return false, err } defer f.Close() // Read the names of a max of one entry from the directory. When the // directory is empty, an io.EOF error will be returned, so allow it. names, err := f.Readdirnames(1) if err != nil && err != io.EOF { return false, err } return len(names) == 0, nil }
go
func dirEmpty(dirPath string) (bool, error) { f, err := os.Open(dirPath) if err != nil { return false, err } defer f.Close() // Read the names of a max of one entry from the directory. When the // directory is empty, an io.EOF error will be returned, so allow it. names, err := f.Readdirnames(1) if err != nil && err != io.EOF { return false, err } return len(names) == 0, nil }
[ "func", "dirEmpty", "(", "dirPath", "string", ")", "(", "bool", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "dirPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "// Read the names of a max of one entry from the directory. When the", "// directory is empty, an io.EOF error will be returned, so allow it.", "names", ",", "err", ":=", "f", ".", "Readdirnames", "(", "1", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "io", ".", "EOF", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "return", "len", "(", "names", ")", "==", "0", ",", "nil", "\n", "}" ]
// dirEmpty returns whether or not the specified directory path is empty.
[ "dirEmpty", "returns", "whether", "or", "not", "the", "specified", "directory", "path", "is", "empty", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/upgrade.go#L14-L29
train
btcsuite/btcd
upgrade.go
oldBtcdHomeDir
func oldBtcdHomeDir() string { // Search for Windows APPDATA first. This won't exist on POSIX OSes. appData := os.Getenv("APPDATA") if appData != "" { return filepath.Join(appData, "btcd") } // Fall back to standard HOME directory that works for most POSIX OSes. home := os.Getenv("HOME") if home != "" { return filepath.Join(home, ".btcd") } // In the worst case, use the current directory. return "." }
go
func oldBtcdHomeDir() string { // Search for Windows APPDATA first. This won't exist on POSIX OSes. appData := os.Getenv("APPDATA") if appData != "" { return filepath.Join(appData, "btcd") } // Fall back to standard HOME directory that works for most POSIX OSes. home := os.Getenv("HOME") if home != "" { return filepath.Join(home, ".btcd") } // In the worst case, use the current directory. return "." }
[ "func", "oldBtcdHomeDir", "(", ")", "string", "{", "// Search for Windows APPDATA first. This won't exist on POSIX OSes.", "appData", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "appData", "!=", "\"", "\"", "{", "return", "filepath", ".", "Join", "(", "appData", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Fall back to standard HOME directory that works for most POSIX OSes.", "home", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "home", "!=", "\"", "\"", "{", "return", "filepath", ".", "Join", "(", "home", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// In the worst case, use the current directory.", "return", "\"", "\"", "\n", "}" ]
// oldBtcdHomeDir returns the OS specific home directory btcd used prior to // version 0.3.3. This has since been replaced with btcutil.AppDataDir, but // this function is still provided for the automatic upgrade path.
[ "oldBtcdHomeDir", "returns", "the", "OS", "specific", "home", "directory", "btcd", "used", "prior", "to", "version", "0", ".", "3", ".", "3", ".", "This", "has", "since", "been", "replaced", "with", "btcutil", ".", "AppDataDir", "but", "this", "function", "is", "still", "provided", "for", "the", "automatic", "upgrade", "path", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/upgrade.go#L34-L49
train
btcsuite/btcd
upgrade.go
upgradeDBPathNet
func upgradeDBPathNet(oldDbPath, netName string) error { // Prior to version 0.2.0, the database was named the same thing for // both sqlite and leveldb. Use heuristics to figure out the type // of the database and move it to the new path and name introduced with // version 0.2.0 accordingly. fi, err := os.Stat(oldDbPath) if err == nil { oldDbType := "sqlite" if fi.IsDir() { oldDbType = "leveldb" } // The new database name is based on the database type and // resides in a directory named after the network type. newDbRoot := filepath.Join(filepath.Dir(cfg.DataDir), netName) newDbName := blockDbNamePrefix + "_" + oldDbType if oldDbType == "sqlite" { newDbName = newDbName + ".db" } newDbPath := filepath.Join(newDbRoot, newDbName) // Create the new path if needed. err = os.MkdirAll(newDbRoot, 0700) if err != nil { return err } // Move and rename the old database. err := os.Rename(oldDbPath, newDbPath) if err != nil { return err } } return nil }
go
func upgradeDBPathNet(oldDbPath, netName string) error { // Prior to version 0.2.0, the database was named the same thing for // both sqlite and leveldb. Use heuristics to figure out the type // of the database and move it to the new path and name introduced with // version 0.2.0 accordingly. fi, err := os.Stat(oldDbPath) if err == nil { oldDbType := "sqlite" if fi.IsDir() { oldDbType = "leveldb" } // The new database name is based on the database type and // resides in a directory named after the network type. newDbRoot := filepath.Join(filepath.Dir(cfg.DataDir), netName) newDbName := blockDbNamePrefix + "_" + oldDbType if oldDbType == "sqlite" { newDbName = newDbName + ".db" } newDbPath := filepath.Join(newDbRoot, newDbName) // Create the new path if needed. err = os.MkdirAll(newDbRoot, 0700) if err != nil { return err } // Move and rename the old database. err := os.Rename(oldDbPath, newDbPath) if err != nil { return err } } return nil }
[ "func", "upgradeDBPathNet", "(", "oldDbPath", ",", "netName", "string", ")", "error", "{", "// Prior to version 0.2.0, the database was named the same thing for", "// both sqlite and leveldb. Use heuristics to figure out the type", "// of the database and move it to the new path and name introduced with", "// version 0.2.0 accordingly.", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "oldDbPath", ")", "\n", "if", "err", "==", "nil", "{", "oldDbType", ":=", "\"", "\"", "\n", "if", "fi", ".", "IsDir", "(", ")", "{", "oldDbType", "=", "\"", "\"", "\n", "}", "\n\n", "// The new database name is based on the database type and", "// resides in a directory named after the network type.", "newDbRoot", ":=", "filepath", ".", "Join", "(", "filepath", ".", "Dir", "(", "cfg", ".", "DataDir", ")", ",", "netName", ")", "\n", "newDbName", ":=", "blockDbNamePrefix", "+", "\"", "\"", "+", "oldDbType", "\n", "if", "oldDbType", "==", "\"", "\"", "{", "newDbName", "=", "newDbName", "+", "\"", "\"", "\n", "}", "\n", "newDbPath", ":=", "filepath", ".", "Join", "(", "newDbRoot", ",", "newDbName", ")", "\n\n", "// Create the new path if needed.", "err", "=", "os", ".", "MkdirAll", "(", "newDbRoot", ",", "0700", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Move and rename the old database.", "err", ":=", "os", ".", "Rename", "(", "oldDbPath", ",", "newDbPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// upgradeDBPathNet moves the database for a specific network from its // location prior to btcd version 0.2.0 and uses heuristics to ascertain the old // database type to rename to the new format.
[ "upgradeDBPathNet", "moves", "the", "database", "for", "a", "specific", "network", "from", "its", "location", "prior", "to", "btcd", "version", "0", ".", "2", ".", "0", "and", "uses", "heuristics", "to", "ascertain", "the", "old", "database", "type", "to", "rename", "to", "the", "new", "format", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/upgrade.go#L54-L89
train
btcsuite/btcd
upgrade.go
upgradeDBPaths
func upgradeDBPaths() error { // Prior to version 0.2.0, the databases were in the "db" directory and // their names were suffixed by "testnet" and "regtest" for their // respective networks. Check for the old database and update it to the // new path introduced with version 0.2.0 accordingly. oldDbRoot := filepath.Join(oldBtcdHomeDir(), "db") upgradeDBPathNet(filepath.Join(oldDbRoot, "btcd.db"), "mainnet") upgradeDBPathNet(filepath.Join(oldDbRoot, "btcd_testnet.db"), "testnet") upgradeDBPathNet(filepath.Join(oldDbRoot, "btcd_regtest.db"), "regtest") // Remove the old db directory. return os.RemoveAll(oldDbRoot) }
go
func upgradeDBPaths() error { // Prior to version 0.2.0, the databases were in the "db" directory and // their names were suffixed by "testnet" and "regtest" for their // respective networks. Check for the old database and update it to the // new path introduced with version 0.2.0 accordingly. oldDbRoot := filepath.Join(oldBtcdHomeDir(), "db") upgradeDBPathNet(filepath.Join(oldDbRoot, "btcd.db"), "mainnet") upgradeDBPathNet(filepath.Join(oldDbRoot, "btcd_testnet.db"), "testnet") upgradeDBPathNet(filepath.Join(oldDbRoot, "btcd_regtest.db"), "regtest") // Remove the old db directory. return os.RemoveAll(oldDbRoot) }
[ "func", "upgradeDBPaths", "(", ")", "error", "{", "// Prior to version 0.2.0, the databases were in the \"db\" directory and", "// their names were suffixed by \"testnet\" and \"regtest\" for their", "// respective networks. Check for the old database and update it to the", "// new path introduced with version 0.2.0 accordingly.", "oldDbRoot", ":=", "filepath", ".", "Join", "(", "oldBtcdHomeDir", "(", ")", ",", "\"", "\"", ")", "\n", "upgradeDBPathNet", "(", "filepath", ".", "Join", "(", "oldDbRoot", ",", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "upgradeDBPathNet", "(", "filepath", ".", "Join", "(", "oldDbRoot", ",", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "upgradeDBPathNet", "(", "filepath", ".", "Join", "(", "oldDbRoot", ",", "\"", "\"", ")", ",", "\"", "\"", ")", "\n\n", "// Remove the old db directory.", "return", "os", ".", "RemoveAll", "(", "oldDbRoot", ")", "\n", "}" ]
// upgradeDBPaths moves the databases from their locations prior to btcd // version 0.2.0 to their new locations.
[ "upgradeDBPaths", "moves", "the", "databases", "from", "their", "locations", "prior", "to", "btcd", "version", "0", ".", "2", ".", "0", "to", "their", "new", "locations", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/upgrade.go#L93-L105
train
btcsuite/btcd
upgrade.go
upgradeDataPaths
func upgradeDataPaths() error { // No need to migrate if the old and new home paths are the same. oldHomePath := oldBtcdHomeDir() newHomePath := defaultHomeDir if oldHomePath == newHomePath { return nil } // Only migrate if the old path exists and the new one doesn't. if fileExists(oldHomePath) && !fileExists(newHomePath) { // Create the new path. btcdLog.Infof("Migrating application home path from '%s' to '%s'", oldHomePath, newHomePath) err := os.MkdirAll(newHomePath, 0700) if err != nil { return err } // Move old btcd.conf into new location if needed. oldConfPath := filepath.Join(oldHomePath, defaultConfigFilename) newConfPath := filepath.Join(newHomePath, defaultConfigFilename) if fileExists(oldConfPath) && !fileExists(newConfPath) { err := os.Rename(oldConfPath, newConfPath) if err != nil { return err } } // Move old data directory into new location if needed. oldDataPath := filepath.Join(oldHomePath, defaultDataDirname) newDataPath := filepath.Join(newHomePath, defaultDataDirname) if fileExists(oldDataPath) && !fileExists(newDataPath) { err := os.Rename(oldDataPath, newDataPath) if err != nil { return err } } // Remove the old home if it is empty or show a warning if not. ohpEmpty, err := dirEmpty(oldHomePath) if err != nil { return err } if ohpEmpty { err := os.Remove(oldHomePath) if err != nil { return err } } else { btcdLog.Warnf("Not removing '%s' since it contains files "+ "not created by this application. You may "+ "want to manually move them or delete them.", oldHomePath) } } return nil }
go
func upgradeDataPaths() error { // No need to migrate if the old and new home paths are the same. oldHomePath := oldBtcdHomeDir() newHomePath := defaultHomeDir if oldHomePath == newHomePath { return nil } // Only migrate if the old path exists and the new one doesn't. if fileExists(oldHomePath) && !fileExists(newHomePath) { // Create the new path. btcdLog.Infof("Migrating application home path from '%s' to '%s'", oldHomePath, newHomePath) err := os.MkdirAll(newHomePath, 0700) if err != nil { return err } // Move old btcd.conf into new location if needed. oldConfPath := filepath.Join(oldHomePath, defaultConfigFilename) newConfPath := filepath.Join(newHomePath, defaultConfigFilename) if fileExists(oldConfPath) && !fileExists(newConfPath) { err := os.Rename(oldConfPath, newConfPath) if err != nil { return err } } // Move old data directory into new location if needed. oldDataPath := filepath.Join(oldHomePath, defaultDataDirname) newDataPath := filepath.Join(newHomePath, defaultDataDirname) if fileExists(oldDataPath) && !fileExists(newDataPath) { err := os.Rename(oldDataPath, newDataPath) if err != nil { return err } } // Remove the old home if it is empty or show a warning if not. ohpEmpty, err := dirEmpty(oldHomePath) if err != nil { return err } if ohpEmpty { err := os.Remove(oldHomePath) if err != nil { return err } } else { btcdLog.Warnf("Not removing '%s' since it contains files "+ "not created by this application. You may "+ "want to manually move them or delete them.", oldHomePath) } } return nil }
[ "func", "upgradeDataPaths", "(", ")", "error", "{", "// No need to migrate if the old and new home paths are the same.", "oldHomePath", ":=", "oldBtcdHomeDir", "(", ")", "\n", "newHomePath", ":=", "defaultHomeDir", "\n", "if", "oldHomePath", "==", "newHomePath", "{", "return", "nil", "\n", "}", "\n\n", "// Only migrate if the old path exists and the new one doesn't.", "if", "fileExists", "(", "oldHomePath", ")", "&&", "!", "fileExists", "(", "newHomePath", ")", "{", "// Create the new path.", "btcdLog", ".", "Infof", "(", "\"", "\"", ",", "oldHomePath", ",", "newHomePath", ")", "\n", "err", ":=", "os", ".", "MkdirAll", "(", "newHomePath", ",", "0700", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Move old btcd.conf into new location if needed.", "oldConfPath", ":=", "filepath", ".", "Join", "(", "oldHomePath", ",", "defaultConfigFilename", ")", "\n", "newConfPath", ":=", "filepath", ".", "Join", "(", "newHomePath", ",", "defaultConfigFilename", ")", "\n", "if", "fileExists", "(", "oldConfPath", ")", "&&", "!", "fileExists", "(", "newConfPath", ")", "{", "err", ":=", "os", ".", "Rename", "(", "oldConfPath", ",", "newConfPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Move old data directory into new location if needed.", "oldDataPath", ":=", "filepath", ".", "Join", "(", "oldHomePath", ",", "defaultDataDirname", ")", "\n", "newDataPath", ":=", "filepath", ".", "Join", "(", "newHomePath", ",", "defaultDataDirname", ")", "\n", "if", "fileExists", "(", "oldDataPath", ")", "&&", "!", "fileExists", "(", "newDataPath", ")", "{", "err", ":=", "os", ".", "Rename", "(", "oldDataPath", ",", "newDataPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Remove the old home if it is empty or show a warning if not.", "ohpEmpty", ",", "err", ":=", "dirEmpty", "(", "oldHomePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "ohpEmpty", "{", "err", ":=", "os", ".", "Remove", "(", "oldHomePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "btcdLog", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "oldHomePath", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// upgradeDataPaths moves the application data from its location prior to btcd // version 0.3.3 to its new location.
[ "upgradeDataPaths", "moves", "the", "application", "data", "from", "its", "location", "prior", "to", "btcd", "version", "0", ".", "3", ".", "3", "to", "its", "new", "location", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/upgrade.go#L109-L166
train
btcsuite/btcd
btcjson/register.go
String
func (fl UsageFlag) String() string { // No flags are set. if fl == 0 { return "0x0" } // Add individual bit flags. s := "" for flag := UFWalletOnly; flag < highestUsageFlagBit; flag <<= 1 { if fl&flag == flag { s += usageFlagStrings[flag] + "|" fl -= flag } } // Add remaining value as raw hex. s = strings.TrimRight(s, "|") if fl != 0 { s += "|0x" + strconv.FormatUint(uint64(fl), 16) } s = strings.TrimLeft(s, "|") return s }
go
func (fl UsageFlag) String() string { // No flags are set. if fl == 0 { return "0x0" } // Add individual bit flags. s := "" for flag := UFWalletOnly; flag < highestUsageFlagBit; flag <<= 1 { if fl&flag == flag { s += usageFlagStrings[flag] + "|" fl -= flag } } // Add remaining value as raw hex. s = strings.TrimRight(s, "|") if fl != 0 { s += "|0x" + strconv.FormatUint(uint64(fl), 16) } s = strings.TrimLeft(s, "|") return s }
[ "func", "(", "fl", "UsageFlag", ")", "String", "(", ")", "string", "{", "// No flags are set.", "if", "fl", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "// Add individual bit flags.", "s", ":=", "\"", "\"", "\n", "for", "flag", ":=", "UFWalletOnly", ";", "flag", "<", "highestUsageFlagBit", ";", "flag", "<<=", "1", "{", "if", "fl", "&", "flag", "==", "flag", "{", "s", "+=", "usageFlagStrings", "[", "flag", "]", "+", "\"", "\"", "\n", "fl", "-=", "flag", "\n", "}", "\n", "}", "\n\n", "// Add remaining value as raw hex.", "s", "=", "strings", ".", "TrimRight", "(", "s", ",", "\"", "\"", ")", "\n", "if", "fl", "!=", "0", "{", "s", "+=", "\"", "\"", "+", "strconv", ".", "FormatUint", "(", "uint64", "(", "fl", ")", ",", "16", ")", "\n", "}", "\n", "s", "=", "strings", ".", "TrimLeft", "(", "s", ",", "\"", "\"", ")", "\n", "return", "s", "\n", "}" ]
// String returns the UsageFlag in human-readable form.
[ "String", "returns", "the", "UsageFlag", "in", "human", "-", "readable", "form", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/register.go#L50-L72
train
btcsuite/btcd
btcjson/register.go
baseKindString
func baseKindString(rt reflect.Type) string { numIndirects := 0 for rt.Kind() == reflect.Ptr { numIndirects++ rt = rt.Elem() } return fmt.Sprintf("%s%s", strings.Repeat("*", numIndirects), rt.Kind()) }
go
func baseKindString(rt reflect.Type) string { numIndirects := 0 for rt.Kind() == reflect.Ptr { numIndirects++ rt = rt.Elem() } return fmt.Sprintf("%s%s", strings.Repeat("*", numIndirects), rt.Kind()) }
[ "func", "baseKindString", "(", "rt", "reflect", ".", "Type", ")", "string", "{", "numIndirects", ":=", "0", "\n", "for", "rt", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "numIndirects", "++", "\n", "rt", "=", "rt", ".", "Elem", "(", ")", "\n", "}", "\n\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "Repeat", "(", "\"", "\"", ",", "numIndirects", ")", ",", "rt", ".", "Kind", "(", ")", ")", "\n", "}" ]
// baseKindString returns the base kind for a given reflect.Type after // indirecting through all pointers.
[ "baseKindString", "returns", "the", "base", "kind", "for", "a", "given", "reflect", ".", "Type", "after", "indirecting", "through", "all", "pointers", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/register.go#L95-L103
train
btcsuite/btcd
btcjson/register.go
isAcceptableKind
func isAcceptableKind(kind reflect.Kind) bool { switch kind { case reflect.Chan: fallthrough case reflect.Complex64: fallthrough case reflect.Complex128: fallthrough case reflect.Func: fallthrough case reflect.Ptr: fallthrough case reflect.Interface: return false } return true }
go
func isAcceptableKind(kind reflect.Kind) bool { switch kind { case reflect.Chan: fallthrough case reflect.Complex64: fallthrough case reflect.Complex128: fallthrough case reflect.Func: fallthrough case reflect.Ptr: fallthrough case reflect.Interface: return false } return true }
[ "func", "isAcceptableKind", "(", "kind", "reflect", ".", "Kind", ")", "bool", "{", "switch", "kind", "{", "case", "reflect", ".", "Chan", ":", "fallthrough", "\n", "case", "reflect", ".", "Complex64", ":", "fallthrough", "\n", "case", "reflect", ".", "Complex128", ":", "fallthrough", "\n", "case", "reflect", ".", "Func", ":", "fallthrough", "\n", "case", "reflect", ".", "Ptr", ":", "fallthrough", "\n", "case", "reflect", ".", "Interface", ":", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// isAcceptableKind returns whether or not the passed field type is a supported // type. It is called after the first pointer indirection, so further pointers // are not supported.
[ "isAcceptableKind", "returns", "whether", "or", "not", "the", "passed", "field", "type", "is", "a", "supported", "type", ".", "It", "is", "called", "after", "the", "first", "pointer", "indirection", "so", "further", "pointers", "are", "not", "supported", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/register.go#L108-L125
train
btcsuite/btcd
btcjson/register.go
MustRegisterCmd
func MustRegisterCmd(method string, cmd interface{}, flags UsageFlag) { if err := RegisterCmd(method, cmd, flags); err != nil { panic(fmt.Sprintf("failed to register type %q: %v\n", method, err)) } }
go
func MustRegisterCmd(method string, cmd interface{}, flags UsageFlag) { if err := RegisterCmd(method, cmd, flags); err != nil { panic(fmt.Sprintf("failed to register type %q: %v\n", method, err)) } }
[ "func", "MustRegisterCmd", "(", "method", "string", ",", "cmd", "interface", "{", "}", ",", "flags", "UsageFlag", ")", "{", "if", "err", ":=", "RegisterCmd", "(", "method", ",", "cmd", ",", "flags", ")", ";", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "method", ",", "err", ")", ")", "\n", "}", "\n", "}" ]
// MustRegisterCmd performs the same function as RegisterCmd except it panics // if there is an error. This should only be called from package init // functions.
[ "MustRegisterCmd", "performs", "the", "same", "function", "as", "RegisterCmd", "except", "it", "panics", "if", "there", "is", "an", "error", ".", "This", "should", "only", "be", "called", "from", "package", "init", "functions", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/register.go#L272-L277
train
btcsuite/btcd
btcjson/register.go
RegisteredCmdMethods
func RegisteredCmdMethods() []string { registerLock.Lock() defer registerLock.Unlock() methods := make([]string, 0, len(methodToInfo)) for k := range methodToInfo { methods = append(methods, k) } sort.Sort(sort.StringSlice(methods)) return methods }
go
func RegisteredCmdMethods() []string { registerLock.Lock() defer registerLock.Unlock() methods := make([]string, 0, len(methodToInfo)) for k := range methodToInfo { methods = append(methods, k) } sort.Sort(sort.StringSlice(methods)) return methods }
[ "func", "RegisteredCmdMethods", "(", ")", "[", "]", "string", "{", "registerLock", ".", "Lock", "(", ")", "\n", "defer", "registerLock", ".", "Unlock", "(", ")", "\n\n", "methods", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "methodToInfo", ")", ")", "\n", "for", "k", ":=", "range", "methodToInfo", "{", "methods", "=", "append", "(", "methods", ",", "k", ")", "\n", "}", "\n\n", "sort", ".", "Sort", "(", "sort", ".", "StringSlice", "(", "methods", ")", ")", "\n", "return", "methods", "\n", "}" ]
// RegisteredCmdMethods returns a sorted list of methods for all registered // commands.
[ "RegisteredCmdMethods", "returns", "a", "sorted", "list", "of", "methods", "for", "all", "registered", "commands", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/register.go#L281-L292
train
btcsuite/btcd
rpcclient/mining.go
Receive
func (r FutureGenerateResult) Receive() ([]*chainhash.Hash, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal result as a list of strings. var result []string err = json.Unmarshal(res, &result) if err != nil { return nil, err } // Convert each block hash to a chainhash.Hash and store a pointer to // each. convertedResult := make([]*chainhash.Hash, len(result)) for i, hashString := range result { convertedResult[i], err = chainhash.NewHashFromStr(hashString) if err != nil { return nil, err } } return convertedResult, nil }
go
func (r FutureGenerateResult) Receive() ([]*chainhash.Hash, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal result as a list of strings. var result []string err = json.Unmarshal(res, &result) if err != nil { return nil, err } // Convert each block hash to a chainhash.Hash and store a pointer to // each. convertedResult := make([]*chainhash.Hash, len(result)) for i, hashString := range result { convertedResult[i], err = chainhash.NewHashFromStr(hashString) if err != nil { return nil, err } } return convertedResult, nil }
[ "func", "(", "r", "FutureGenerateResult", ")", "Receive", "(", ")", "(", "[", "]", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "res", ",", "err", ":=", "receiveFuture", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Unmarshal result as a list of strings.", "var", "result", "[", "]", "string", "\n", "err", "=", "json", ".", "Unmarshal", "(", "res", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Convert each block hash to a chainhash.Hash and store a pointer to", "// each.", "convertedResult", ":=", "make", "(", "[", "]", "*", "chainhash", ".", "Hash", ",", "len", "(", "result", ")", ")", "\n", "for", "i", ",", "hashString", ":=", "range", "result", "{", "convertedResult", "[", "i", "]", ",", "err", "=", "chainhash", ".", "NewHashFromStr", "(", "hashString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "convertedResult", ",", "nil", "\n", "}" ]
// Receive waits for the response promised by the future and returns a list of // block hashes generated by the call.
[ "Receive", "waits", "for", "the", "response", "promised", "by", "the", "future", "and", "returns", "a", "list", "of", "block", "hashes", "generated", "by", "the", "call", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L23-L47
train
btcsuite/btcd
rpcclient/mining.go
GenerateAsync
func (c *Client) GenerateAsync(numBlocks uint32) FutureGenerateResult { cmd := btcjson.NewGenerateCmd(numBlocks) return c.sendCmd(cmd) }
go
func (c *Client) GenerateAsync(numBlocks uint32) FutureGenerateResult { cmd := btcjson.NewGenerateCmd(numBlocks) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "GenerateAsync", "(", "numBlocks", "uint32", ")", "FutureGenerateResult", "{", "cmd", ":=", "btcjson", ".", "NewGenerateCmd", "(", "numBlocks", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// GenerateAsync 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 Generate for the blocking version and more details.
[ "GenerateAsync", "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", "Generate", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L54-L57
train
btcsuite/btcd
rpcclient/mining.go
Generate
func (c *Client) Generate(numBlocks uint32) ([]*chainhash.Hash, error) { return c.GenerateAsync(numBlocks).Receive() }
go
func (c *Client) Generate(numBlocks uint32) ([]*chainhash.Hash, error) { return c.GenerateAsync(numBlocks).Receive() }
[ "func", "(", "c", "*", "Client", ")", "Generate", "(", "numBlocks", "uint32", ")", "(", "[", "]", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "return", "c", ".", "GenerateAsync", "(", "numBlocks", ")", ".", "Receive", "(", ")", "\n", "}" ]
// Generate generates numBlocks blocks and returns their hashes.
[ "Generate", "generates", "numBlocks", "blocks", "and", "returns", "their", "hashes", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L60-L62
train
btcsuite/btcd
rpcclient/mining.go
Receive
func (r FutureGetGenerateResult) Receive() (bool, error) { res, err := receiveFuture(r) if err != nil { return false, err } // Unmarshal result as a boolean. var result bool err = json.Unmarshal(res, &result) if err != nil { return false, err } return result, nil }
go
func (r FutureGetGenerateResult) Receive() (bool, error) { res, err := receiveFuture(r) if err != nil { return false, err } // Unmarshal result as a boolean. var result bool err = json.Unmarshal(res, &result) if err != nil { return false, err } return result, nil }
[ "func", "(", "r", "FutureGetGenerateResult", ")", "Receive", "(", ")", "(", "bool", ",", "error", ")", "{", "res", ",", "err", ":=", "receiveFuture", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "// Unmarshal result as a boolean.", "var", "result", "bool", "\n", "err", "=", "json", ".", "Unmarshal", "(", "res", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// Receive waits for the response promised by the future and returns true if the // server is set to mine, otherwise false.
[ "Receive", "waits", "for", "the", "response", "promised", "by", "the", "future", "and", "returns", "true", "if", "the", "server", "is", "set", "to", "mine", "otherwise", "false", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L70-L84
train
btcsuite/btcd
rpcclient/mining.go
GetGenerateAsync
func (c *Client) GetGenerateAsync() FutureGetGenerateResult { cmd := btcjson.NewGetGenerateCmd() return c.sendCmd(cmd) }
go
func (c *Client) GetGenerateAsync() FutureGetGenerateResult { cmd := btcjson.NewGetGenerateCmd() return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "GetGenerateAsync", "(", ")", "FutureGetGenerateResult", "{", "cmd", ":=", "btcjson", ".", "NewGetGenerateCmd", "(", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// GetGenerateAsync 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 GetGenerate for the blocking version and more details.
[ "GetGenerateAsync", "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", "GetGenerate", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L91-L94
train
btcsuite/btcd
rpcclient/mining.go
SetGenerateAsync
func (c *Client) SetGenerateAsync(enable bool, numCPUs int) FutureSetGenerateResult { cmd := btcjson.NewSetGenerateCmd(enable, &numCPUs) return c.sendCmd(cmd) }
go
func (c *Client) SetGenerateAsync(enable bool, numCPUs int) FutureSetGenerateResult { cmd := btcjson.NewSetGenerateCmd(enable, &numCPUs) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "SetGenerateAsync", "(", "enable", "bool", ",", "numCPUs", "int", ")", "FutureSetGenerateResult", "{", "cmd", ":=", "btcjson", ".", "NewSetGenerateCmd", "(", "enable", ",", "&", "numCPUs", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// SetGenerateAsync 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 SetGenerate for the blocking version and more details.
[ "SetGenerateAsync", "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", "SetGenerate", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L117-L120
train
btcsuite/btcd
rpcclient/mining.go
GetHashesPerSecAsync
func (c *Client) GetHashesPerSecAsync() FutureGetHashesPerSecResult { cmd := btcjson.NewGetHashesPerSecCmd() return c.sendCmd(cmd) }
go
func (c *Client) GetHashesPerSecAsync() FutureGetHashesPerSecResult { cmd := btcjson.NewGetHashesPerSecCmd() return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "GetHashesPerSecAsync", "(", ")", "FutureGetHashesPerSecResult", "{", "cmd", ":=", "btcjson", ".", "NewGetHashesPerSecCmd", "(", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// GetHashesPerSecAsync 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 GetHashesPerSec for the blocking version and more details.
[ "GetHashesPerSecAsync", "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", "GetHashesPerSec", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/mining.go#L155-L158
train