repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
btcsuite/btcwallet | wallet/recovery.go | ExtendHorizon | func (brs *BranchRecoveryState) ExtendHorizon() (uint32, uint32) {
// Compute the new horizon, which should surpass our last found address
// by the recovery window.
curHorizon := brs.horizon
nInvalid := brs.NumInvalidInHorizon()
minValidHorizon := brs.nextUnfound + brs.recoveryWindow + nInvalid
// If the curr... | go | func (brs *BranchRecoveryState) ExtendHorizon() (uint32, uint32) {
// Compute the new horizon, which should surpass our last found address
// by the recovery window.
curHorizon := brs.horizon
nInvalid := brs.NumInvalidInHorizon()
minValidHorizon := brs.nextUnfound + brs.recoveryWindow + nInvalid
// If the curr... | [
"func",
"(",
"brs",
"*",
"BranchRecoveryState",
")",
"ExtendHorizon",
"(",
")",
"(",
"uint32",
",",
"uint32",
")",
"{",
"// Compute the new horizon, which should surpass our last found address",
"// by the recovery window.",
"curHorizon",
":=",
"brs",
".",
"horizon",
"\n\... | // ExtendHorizon returns the current horizon and the number of addresses that
// must be derived in order to maintain the desired recovery window. | [
"ExtendHorizon",
"returns",
"the",
"current",
"horizon",
"and",
"the",
"number",
"of",
"addresses",
"that",
"must",
"be",
"derived",
"in",
"order",
"to",
"maintain",
"the",
"desired",
"recovery",
"window",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L324-L345 | train |
btcsuite/btcwallet | wallet/recovery.go | AddAddr | func (brs *BranchRecoveryState) AddAddr(index uint32, addr btcutil.Address) {
brs.addresses[index] = addr
} | go | func (brs *BranchRecoveryState) AddAddr(index uint32, addr btcutil.Address) {
brs.addresses[index] = addr
} | [
"func",
"(",
"brs",
"*",
"BranchRecoveryState",
")",
"AddAddr",
"(",
"index",
"uint32",
",",
"addr",
"btcutil",
".",
"Address",
")",
"{",
"brs",
".",
"addresses",
"[",
"index",
"]",
"=",
"addr",
"\n",
"}"
] | // AddAddr adds a freshly derived address from our lookahead into the map of
// known addresses for this branch. | [
"AddAddr",
"adds",
"a",
"freshly",
"derived",
"address",
"from",
"our",
"lookahead",
"into",
"the",
"map",
"of",
"known",
"addresses",
"for",
"this",
"branch",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L349-L351 | train |
btcsuite/btcwallet | wallet/recovery.go | GetAddr | func (brs *BranchRecoveryState) GetAddr(index uint32) btcutil.Address {
return brs.addresses[index]
} | go | func (brs *BranchRecoveryState) GetAddr(index uint32) btcutil.Address {
return brs.addresses[index]
} | [
"func",
"(",
"brs",
"*",
"BranchRecoveryState",
")",
"GetAddr",
"(",
"index",
"uint32",
")",
"btcutil",
".",
"Address",
"{",
"return",
"brs",
".",
"addresses",
"[",
"index",
"]",
"\n",
"}"
] | // GetAddr returns the address derived from a given child index. | [
"GetAddr",
"returns",
"the",
"address",
"derived",
"from",
"a",
"given",
"child",
"index",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L354-L356 | train |
btcsuite/btcwallet | wallet/recovery.go | ReportFound | func (brs *BranchRecoveryState) ReportFound(index uint32) {
if index >= brs.nextUnfound {
brs.nextUnfound = index + 1
// Prune all invalid child indexes that fall below our last
// found index. We don't need to keep these entries any longer,
// since they will not affect our required look-ahead.
for childIn... | go | func (brs *BranchRecoveryState) ReportFound(index uint32) {
if index >= brs.nextUnfound {
brs.nextUnfound = index + 1
// Prune all invalid child indexes that fall below our last
// found index. We don't need to keep these entries any longer,
// since they will not affect our required look-ahead.
for childIn... | [
"func",
"(",
"brs",
"*",
"BranchRecoveryState",
")",
"ReportFound",
"(",
"index",
"uint32",
")",
"{",
"if",
"index",
">=",
"brs",
".",
"nextUnfound",
"{",
"brs",
".",
"nextUnfound",
"=",
"index",
"+",
"1",
"\n\n",
"// Prune all invalid child indexes that fall be... | // ReportFound updates the last found index if the reported index exceeds the
// current value. | [
"ReportFound",
"updates",
"the",
"last",
"found",
"index",
"if",
"the",
"reported",
"index",
"exceeds",
"the",
"current",
"value",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L360-L373 | train |
btcsuite/btcwallet | wallet/recovery.go | MarkInvalidChild | func (brs *BranchRecoveryState) MarkInvalidChild(index uint32) {
brs.invalidChildren[index] = struct{}{}
brs.horizon++
} | go | func (brs *BranchRecoveryState) MarkInvalidChild(index uint32) {
brs.invalidChildren[index] = struct{}{}
brs.horizon++
} | [
"func",
"(",
"brs",
"*",
"BranchRecoveryState",
")",
"MarkInvalidChild",
"(",
"index",
"uint32",
")",
"{",
"brs",
".",
"invalidChildren",
"[",
"index",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"brs",
".",
"horizon",
"++",
"\n",
"}"
] | // MarkInvalidChild records that a particular child index results in deriving an
// invalid address. In addition, the branch's horizon is increment, as we expect
// the caller to perform an additional derivation to replace the invalid child.
// This is used to ensure that we are always have the proper lookahead when an... | [
"MarkInvalidChild",
"records",
"that",
"a",
"particular",
"child",
"index",
"results",
"in",
"deriving",
"an",
"invalid",
"address",
".",
"In",
"addition",
"the",
"branch",
"s",
"horizon",
"is",
"increment",
"as",
"we",
"expect",
"the",
"caller",
"to",
"perfor... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L380-L383 | train |
btcsuite/btcwallet | wallet/recovery.go | NumInvalidInHorizon | func (brs *BranchRecoveryState) NumInvalidInHorizon() uint32 {
var nInvalid uint32
for childIndex := range brs.invalidChildren {
if brs.nextUnfound <= childIndex && childIndex < brs.horizon {
nInvalid++
}
}
return nInvalid
} | go | func (brs *BranchRecoveryState) NumInvalidInHorizon() uint32 {
var nInvalid uint32
for childIndex := range brs.invalidChildren {
if brs.nextUnfound <= childIndex && childIndex < brs.horizon {
nInvalid++
}
}
return nInvalid
} | [
"func",
"(",
"brs",
"*",
"BranchRecoveryState",
")",
"NumInvalidInHorizon",
"(",
")",
"uint32",
"{",
"var",
"nInvalid",
"uint32",
"\n",
"for",
"childIndex",
":=",
"range",
"brs",
".",
"invalidChildren",
"{",
"if",
"brs",
".",
"nextUnfound",
"<=",
"childIndex",... | // NumInvalidInHorizon computes the number of invalid child indexes that lie
// between the last found and current horizon. This informs how many additional
// indexes to derive in order to maintain the proper number of valid addresses
// within our horizon. | [
"NumInvalidInHorizon",
"computes",
"the",
"number",
"of",
"invalid",
"child",
"indexes",
"that",
"lie",
"between",
"the",
"last",
"found",
"and",
"current",
"horizon",
".",
"This",
"informs",
"how",
"many",
"additional",
"indexes",
"to",
"derive",
"in",
"order",... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L401-L410 | train |
btcsuite/btcwallet | wtxmgr/db.go | appendRawBlockRecord | func appendRawBlockRecord(v []byte, txHash *chainhash.Hash) ([]byte, error) {
if len(v) < 44 {
str := fmt.Sprintf("%s: short read (expected %d bytes, read %d)",
bucketBlocks, 44, len(v))
return nil, storeError(ErrData, str, nil)
}
newv := append(v[:len(v):len(v)], txHash[:]...)
n := byteOrder.Uint32(newv[40:... | go | func appendRawBlockRecord(v []byte, txHash *chainhash.Hash) ([]byte, error) {
if len(v) < 44 {
str := fmt.Sprintf("%s: short read (expected %d bytes, read %d)",
bucketBlocks, 44, len(v))
return nil, storeError(ErrData, str, nil)
}
newv := append(v[:len(v):len(v)], txHash[:]...)
n := byteOrder.Uint32(newv[40:... | [
"func",
"appendRawBlockRecord",
"(",
"v",
"[",
"]",
"byte",
",",
"txHash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"v",
")",
"<",
"44",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"... | // appendRawBlockRecord returns a new block record value with a transaction
// hash appended to the end and an incremented number of transactions. | [
"appendRawBlockRecord",
"returns",
"a",
"new",
"block",
"record",
"value",
"with",
"a",
"transaction",
"hash",
"appended",
"to",
"the",
"end",
"and",
"an",
"incremented",
"number",
"of",
"transactions",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L160-L170 | train |
btcsuite/btcwallet | wtxmgr/db.go | valueUnspentCredit | func valueUnspentCredit(cred *credit) []byte {
v := make([]byte, 9)
byteOrder.PutUint64(v, uint64(cred.amount))
if cred.change {
v[8] |= 1 << 1
}
return v
} | go | func valueUnspentCredit(cred *credit) []byte {
v := make([]byte, 9)
byteOrder.PutUint64(v, uint64(cred.amount))
if cred.change {
v[8] |= 1 << 1
}
return v
} | [
"func",
"valueUnspentCredit",
"(",
"cred",
"*",
"credit",
")",
"[",
"]",
"byte",
"{",
"v",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"9",
")",
"\n",
"byteOrder",
".",
"PutUint64",
"(",
"v",
",",
"uint64",
"(",
"cred",
".",
"amount",
")",
")",
"\n... | // valueUnspentCredit creates a new credit value for an unspent credit. All
// credits are created unspent, and are only marked spent later, so there is no
// value function to create either spent or unspent credits. | [
"valueUnspentCredit",
"creates",
"a",
"new",
"credit",
"value",
"for",
"an",
"unspent",
"credit",
".",
"All",
"credits",
"are",
"created",
"unspent",
"and",
"are",
"only",
"marked",
"spent",
"later",
"so",
"there",
"is",
"no",
"value",
"function",
"to",
"cre... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L541-L548 | train |
btcsuite/btcwallet | wtxmgr/db.go | putUnspentCredit | func putUnspentCredit(ns walletdb.ReadWriteBucket, cred *credit) error {
k := keyCredit(&cred.outPoint.Hash, cred.outPoint.Index, &cred.block)
v := valueUnspentCredit(cred)
return putRawCredit(ns, k, v)
} | go | func putUnspentCredit(ns walletdb.ReadWriteBucket, cred *credit) error {
k := keyCredit(&cred.outPoint.Hash, cred.outPoint.Index, &cred.block)
v := valueUnspentCredit(cred)
return putRawCredit(ns, k, v)
} | [
"func",
"putUnspentCredit",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"cred",
"*",
"credit",
")",
"error",
"{",
"k",
":=",
"keyCredit",
"(",
"&",
"cred",
".",
"outPoint",
".",
"Hash",
",",
"cred",
".",
"outPoint",
".",
"Index",
",",
"&",
"cre... | // putUnspentCredit puts a credit record for an unspent credit. It may only be
// used when the credit is already know to be unspent, or spent by an
// unconfirmed transaction. | [
"putUnspentCredit",
"puts",
"a",
"credit",
"record",
"for",
"an",
"unspent",
"credit",
".",
"It",
"may",
"only",
"be",
"used",
"when",
"the",
"credit",
"is",
"already",
"know",
"to",
"be",
"unspent",
"or",
"spent",
"by",
"an",
"unconfirmed",
"transaction",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L562-L566 | train |
btcsuite/btcwallet | wtxmgr/db.go | fetchRawCreditAmount | func fetchRawCreditAmount(v []byte) (btcutil.Amount, error) {
if len(v) < 9 {
str := fmt.Sprintf("%s: short read (expected %d bytes, read %d)",
bucketCredits, 9, len(v))
return 0, storeError(ErrData, str, nil)
}
return btcutil.Amount(byteOrder.Uint64(v)), nil
} | go | func fetchRawCreditAmount(v []byte) (btcutil.Amount, error) {
if len(v) < 9 {
str := fmt.Sprintf("%s: short read (expected %d bytes, read %d)",
bucketCredits, 9, len(v))
return 0, storeError(ErrData, str, nil)
}
return btcutil.Amount(byteOrder.Uint64(v)), nil
} | [
"func",
"fetchRawCreditAmount",
"(",
"v",
"[",
"]",
"byte",
")",
"(",
"btcutil",
".",
"Amount",
",",
"error",
")",
"{",
"if",
"len",
"(",
"v",
")",
"<",
"9",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"bucketCredits",
",",
"9"... | // fetchRawCreditAmount returns the amount of the credit. | [
"fetchRawCreditAmount",
"returns",
"the",
"amount",
"of",
"the",
"credit",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L577-L584 | train |
btcsuite/btcwallet | wtxmgr/db.go | fetchRawCreditAmountSpent | func fetchRawCreditAmountSpent(v []byte) (btcutil.Amount, bool, error) {
if len(v) < 9 {
str := fmt.Sprintf("%s: short read (expected %d bytes, read %d)",
bucketCredits, 9, len(v))
return 0, false, storeError(ErrData, str, nil)
}
return btcutil.Amount(byteOrder.Uint64(v)), v[8]&(1<<0) != 0, nil
} | go | func fetchRawCreditAmountSpent(v []byte) (btcutil.Amount, bool, error) {
if len(v) < 9 {
str := fmt.Sprintf("%s: short read (expected %d bytes, read %d)",
bucketCredits, 9, len(v))
return 0, false, storeError(ErrData, str, nil)
}
return btcutil.Amount(byteOrder.Uint64(v)), v[8]&(1<<0) != 0, nil
} | [
"func",
"fetchRawCreditAmountSpent",
"(",
"v",
"[",
"]",
"byte",
")",
"(",
"btcutil",
".",
"Amount",
",",
"bool",
",",
"error",
")",
"{",
"if",
"len",
"(",
"v",
")",
"<",
"9",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"bucket... | // fetchRawCreditAmountSpent returns the amount of the credit and whether the
// credit is spent. | [
"fetchRawCreditAmountSpent",
"returns",
"the",
"amount",
"of",
"the",
"credit",
"and",
"whether",
"the",
"credit",
"is",
"spent",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L588-L595 | train |
btcsuite/btcwallet | wtxmgr/db.go | fetchRawCreditUnspentValue | func fetchRawCreditUnspentValue(k []byte) ([]byte, error) {
if len(k) < 72 {
str := fmt.Sprintf("%s: short key (expected %d bytes, read %d)",
bucketCredits, 72, len(k))
return nil, storeError(ErrData, str, nil)
}
return k[32:68], nil
} | go | func fetchRawCreditUnspentValue(k []byte) ([]byte, error) {
if len(k) < 72 {
str := fmt.Sprintf("%s: short key (expected %d bytes, read %d)",
bucketCredits, 72, len(k))
return nil, storeError(ErrData, str, nil)
}
return k[32:68], nil
} | [
"func",
"fetchRawCreditUnspentValue",
"(",
"k",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"k",
")",
"<",
"72",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"bucketCredits",
",",
"72"... | // fetchRawCreditUnspentValue returns the unspent value for a raw credit key.
// This may be used to mark a credit as unspent. | [
"fetchRawCreditUnspentValue",
"returns",
"the",
"unspent",
"value",
"for",
"a",
"raw",
"credit",
"key",
".",
"This",
"may",
"be",
"used",
"to",
"mark",
"a",
"credit",
"as",
"unspent",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L610-L617 | train |
btcsuite/btcwallet | wtxmgr/db.go | spendCredit | func spendCredit(ns walletdb.ReadWriteBucket, k []byte, spender *indexedIncidence) (btcutil.Amount, error) {
v := ns.NestedReadBucket(bucketCredits).Get(k)
newv := make([]byte, 81)
copy(newv, v)
v = newv
v[8] |= 1 << 0
copy(v[9:41], spender.txHash[:])
byteOrder.PutUint32(v[41:45], uint32(spender.block.Height))
... | go | func spendCredit(ns walletdb.ReadWriteBucket, k []byte, spender *indexedIncidence) (btcutil.Amount, error) {
v := ns.NestedReadBucket(bucketCredits).Get(k)
newv := make([]byte, 81)
copy(newv, v)
v = newv
v[8] |= 1 << 0
copy(v[9:41], spender.txHash[:])
byteOrder.PutUint32(v[41:45], uint32(spender.block.Height))
... | [
"func",
"spendCredit",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"k",
"[",
"]",
"byte",
",",
"spender",
"*",
"indexedIncidence",
")",
"(",
"btcutil",
".",
"Amount",
",",
"error",
")",
"{",
"v",
":=",
"ns",
".",
"NestedReadBucket",
"(",
"bucketC... | // spendRawCredit marks the credit with a given key as mined at some particular
// block as spent by the input at some transaction incidence. The debited
// amount is returned. | [
"spendRawCredit",
"marks",
"the",
"credit",
"with",
"a",
"given",
"key",
"as",
"mined",
"at",
"some",
"particular",
"block",
"as",
"spent",
"by",
"the",
"input",
"at",
"some",
"transaction",
"incidence",
".",
"The",
"debited",
"amount",
"is",
"returned",
"."... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L622-L634 | train |
btcsuite/btcwallet | wtxmgr/db.go | unspendRawCredit | func unspendRawCredit(ns walletdb.ReadWriteBucket, k []byte) (btcutil.Amount, error) {
b := ns.NestedReadWriteBucket(bucketCredits)
v := b.Get(k)
if v == nil {
return 0, nil
}
newv := make([]byte, 9)
copy(newv, v)
newv[8] &^= 1 << 0
err := b.Put(k, newv)
if err != nil {
str := "failed to put credit"
ret... | go | func unspendRawCredit(ns walletdb.ReadWriteBucket, k []byte) (btcutil.Amount, error) {
b := ns.NestedReadWriteBucket(bucketCredits)
v := b.Get(k)
if v == nil {
return 0, nil
}
newv := make([]byte, 9)
copy(newv, v)
newv[8] &^= 1 << 0
err := b.Put(k, newv)
if err != nil {
str := "failed to put credit"
ret... | [
"func",
"unspendRawCredit",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"k",
"[",
"]",
"byte",
")",
"(",
"btcutil",
".",
"Amount",
",",
"error",
")",
"{",
"b",
":=",
"ns",
".",
"NestedReadWriteBucket",
"(",
"bucketCredits",
")",
"\n",
"v",
":=",
... | // unspendRawCredit rewrites the credit for the given key as unspent. The
// output amount of the credit is returned. It returns without error if no
// credit exists for the key. | [
"unspendRawCredit",
"rewrites",
"the",
"credit",
"for",
"the",
"given",
"key",
"as",
"unspent",
".",
"The",
"output",
"amount",
"of",
"the",
"credit",
"is",
"returned",
".",
"It",
"returns",
"without",
"error",
"if",
"no",
"credit",
"exists",
"for",
"the",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L639-L655 | train |
btcsuite/btcwallet | wtxmgr/db.go | existsUnspent | func existsUnspent(ns walletdb.ReadBucket, outPoint *wire.OutPoint) (k, credKey []byte) {
k = canonicalOutPoint(&outPoint.Hash, outPoint.Index)
credKey = existsRawUnspent(ns, k)
return k, credKey
} | go | func existsUnspent(ns walletdb.ReadBucket, outPoint *wire.OutPoint) (k, credKey []byte) {
k = canonicalOutPoint(&outPoint.Hash, outPoint.Index)
credKey = existsRawUnspent(ns, k)
return k, credKey
} | [
"func",
"existsUnspent",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"outPoint",
"*",
"wire",
".",
"OutPoint",
")",
"(",
"k",
",",
"credKey",
"[",
"]",
"byte",
")",
"{",
"k",
"=",
"canonicalOutPoint",
"(",
"&",
"outPoint",
".",
"Hash",
",",
"outPoin... | // existsUnspent returns the key for the unspent output and the corresponding
// key for the credits bucket. If there is no unspent output recorded, the
// credit key is nil. | [
"existsUnspent",
"returns",
"the",
"key",
"for",
"the",
"unspent",
"output",
"and",
"the",
"corresponding",
"key",
"for",
"the",
"credits",
"bucket",
".",
"If",
"there",
"is",
"no",
"unspent",
"output",
"recorded",
"the",
"credit",
"key",
"is",
"nil",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L810-L814 | train |
btcsuite/btcwallet | wtxmgr/db.go | existsDebit | func existsDebit(ns walletdb.ReadBucket, txHash *chainhash.Hash, index uint32, block *Block) (k, credKey []byte, err error) {
k = keyDebit(txHash, index, block)
v := ns.NestedReadBucket(bucketDebits).Get(k)
if v == nil {
return nil, nil, nil
}
if len(v) < 80 {
str := fmt.Sprintf("%s: short read (expected 80 by... | go | func existsDebit(ns walletdb.ReadBucket, txHash *chainhash.Hash, index uint32, block *Block) (k, credKey []byte, err error) {
k = keyDebit(txHash, index, block)
v := ns.NestedReadBucket(bucketDebits).Get(k)
if v == nil {
return nil, nil, nil
}
if len(v) < 80 {
str := fmt.Sprintf("%s: short read (expected 80 by... | [
"func",
"existsDebit",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"txHash",
"*",
"chainhash",
".",
"Hash",
",",
"index",
"uint32",
",",
"block",
"*",
"Block",
")",
"(",
"k",
",",
"credKey",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"k",
... | // existsDebit checks for the existance of a debit. If found, the debit and
// previous credit keys are returned. If the debit does not exist, both keys
// are nil. | [
"existsDebit",
"checks",
"for",
"the",
"existance",
"of",
"a",
"debit",
".",
"If",
"found",
"the",
"debit",
"and",
"previous",
"credit",
"keys",
"are",
"returned",
".",
"If",
"the",
"debit",
"does",
"not",
"exist",
"both",
"keys",
"are",
"nil",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L893-L905 | train |
btcsuite/btcwallet | wtxmgr/db.go | fetchUnminedInputSpendTxHashes | func fetchUnminedInputSpendTxHashes(ns walletdb.ReadBucket, k []byte) []chainhash.Hash {
rawSpendTxHashes := ns.NestedReadBucket(bucketUnminedInputs).Get(k)
if rawSpendTxHashes == nil {
return nil
}
// Each transaction hash is 32 bytes.
spendTxHashes := make([]chainhash.Hash, 0, len(rawSpendTxHashes)/32)
for l... | go | func fetchUnminedInputSpendTxHashes(ns walletdb.ReadBucket, k []byte) []chainhash.Hash {
rawSpendTxHashes := ns.NestedReadBucket(bucketUnminedInputs).Get(k)
if rawSpendTxHashes == nil {
return nil
}
// Each transaction hash is 32 bytes.
spendTxHashes := make([]chainhash.Hash, 0, len(rawSpendTxHashes)/32)
for l... | [
"func",
"fetchUnminedInputSpendTxHashes",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"k",
"[",
"]",
"byte",
")",
"[",
"]",
"chainhash",
".",
"Hash",
"{",
"rawSpendTxHashes",
":=",
"ns",
".",
"NestedReadBucket",
"(",
"bucketUnminedInputs",
")",
".",
"Get",
... | // fetchUnminedInputSpendTxHashes fetches the list of unmined transactions that
// spend the serialized outpoint. | [
"fetchUnminedInputSpendTxHashes",
"fetches",
"the",
"list",
"of",
"unmined",
"transactions",
"that",
"spend",
"the",
"serialized",
"outpoint",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L1231-L1247 | train |
btcsuite/btcwallet | wtxmgr/db.go | deleteRawUnminedInput | func deleteRawUnminedInput(ns walletdb.ReadWriteBucket, outPointKey []byte,
targetSpendHash chainhash.Hash) error {
// We'll start by fetching all of the possible spending transactions.
unminedInputs := ns.NestedReadWriteBucket(bucketUnminedInputs)
spendHashes := unminedInputs.Get(outPointKey)
if len(spendHashes)... | go | func deleteRawUnminedInput(ns walletdb.ReadWriteBucket, outPointKey []byte,
targetSpendHash chainhash.Hash) error {
// We'll start by fetching all of the possible spending transactions.
unminedInputs := ns.NestedReadWriteBucket(bucketUnminedInputs)
spendHashes := unminedInputs.Get(outPointKey)
if len(spendHashes)... | [
"func",
"deleteRawUnminedInput",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"outPointKey",
"[",
"]",
"byte",
",",
"targetSpendHash",
"chainhash",
".",
"Hash",
")",
"error",
"{",
"// We'll start by fetching all of the possible spending transactions.",
"unminedInputs... | // deleteRawUnminedInput removes a spending transaction entry from the list of
// spending transactions for a given input. | [
"deleteRawUnminedInput",
"removes",
"a",
"spending",
"transaction",
"entry",
"from",
"the",
"list",
"of",
"spending",
"transactions",
"for",
"a",
"given",
"input",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L1251-L1287 | train |
btcsuite/btcwallet | wtxmgr/db.go | openStore | func openStore(ns walletdb.ReadBucket) error {
version, err := fetchVersion(ns)
if err != nil {
return err
}
latestVersion := getLatestVersion()
if version < latestVersion {
str := fmt.Sprintf("a database upgrade is required to upgrade "+
"wtxmgr from recorded version %d to the latest version %d",
versi... | go | func openStore(ns walletdb.ReadBucket) error {
version, err := fetchVersion(ns)
if err != nil {
return err
}
latestVersion := getLatestVersion()
if version < latestVersion {
str := fmt.Sprintf("a database upgrade is required to upgrade "+
"wtxmgr from recorded version %d to the latest version %d",
versi... | [
"func",
"openStore",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
")",
"error",
"{",
"version",
",",
"err",
":=",
"fetchVersion",
"(",
"ns",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"latestVersion",
":=",
"getLatestVersi... | // openStore opens an existing transaction store from the passed namespace. | [
"openStore",
"opens",
"an",
"existing",
"transaction",
"store",
"from",
"the",
"passed",
"namespace",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L1290-L1311 | train |
btcsuite/btcwallet | wtxmgr/db.go | createBuckets | func createBuckets(ns walletdb.ReadWriteBucket) error {
if _, err := ns.CreateBucket(bucketBlocks); err != nil {
str := "failed to create blocks bucket"
return storeError(ErrDatabase, str, err)
}
if _, err := ns.CreateBucket(bucketTxRecords); err != nil {
str := "failed to create tx records bucket"
return st... | go | func createBuckets(ns walletdb.ReadWriteBucket) error {
if _, err := ns.CreateBucket(bucketBlocks); err != nil {
str := "failed to create blocks bucket"
return storeError(ErrDatabase, str, err)
}
if _, err := ns.CreateBucket(bucketTxRecords); err != nil {
str := "failed to create tx records bucket"
return st... | [
"func",
"createBuckets",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
")",
"error",
"{",
"if",
"_",
",",
"err",
":=",
"ns",
".",
"CreateBucket",
"(",
"bucketBlocks",
")",
";",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"storeEr... | // createBuckets creates all of the descendants buckets required for the
// transaction store to properly carry its duties. | [
"createBuckets",
"creates",
"all",
"of",
"the",
"descendants",
"buckets",
"required",
"for",
"the",
"transaction",
"store",
"to",
"properly",
"carry",
"its",
"duties",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L1351-L1386 | train |
btcsuite/btcwallet | wtxmgr/db.go | deleteBuckets | func deleteBuckets(ns walletdb.ReadWriteBucket) error {
if err := ns.DeleteNestedBucket(bucketBlocks); err != nil {
str := "failed to delete blocks bucket"
return storeError(ErrDatabase, str, err)
}
if err := ns.DeleteNestedBucket(bucketTxRecords); err != nil {
str := "failed to delete tx records bucket"
ret... | go | func deleteBuckets(ns walletdb.ReadWriteBucket) error {
if err := ns.DeleteNestedBucket(bucketBlocks); err != nil {
str := "failed to delete blocks bucket"
return storeError(ErrDatabase, str, err)
}
if err := ns.DeleteNestedBucket(bucketTxRecords); err != nil {
str := "failed to delete tx records bucket"
ret... | [
"func",
"deleteBuckets",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
")",
"error",
"{",
"if",
"err",
":=",
"ns",
".",
"DeleteNestedBucket",
"(",
"bucketBlocks",
")",
";",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"storeError",
... | // deleteBuckets deletes all of the descendants buckets required for the
// transaction store to properly carry its duties. | [
"deleteBuckets",
"deletes",
"all",
"of",
"the",
"descendants",
"buckets",
"required",
"for",
"the",
"transaction",
"store",
"to",
"properly",
"carry",
"its",
"duties",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L1390-L1425 | train |
btcsuite/btcwallet | wtxmgr/db.go | putVersion | func putVersion(ns walletdb.ReadWriteBucket, version uint32) error {
var v [4]byte
byteOrder.PutUint32(v[:], version)
if err := ns.Put(rootVersion, v[:]); err != nil {
str := "failed to store database version"
return storeError(ErrDatabase, str, err)
}
return nil
} | go | func putVersion(ns walletdb.ReadWriteBucket, version uint32) error {
var v [4]byte
byteOrder.PutUint32(v[:], version)
if err := ns.Put(rootVersion, v[:]); err != nil {
str := "failed to store database version"
return storeError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"putVersion",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"version",
"uint32",
")",
"error",
"{",
"var",
"v",
"[",
"4",
"]",
"byte",
"\n",
"byteOrder",
".",
"PutUint32",
"(",
"v",
"[",
":",
"]",
",",
"version",
")",
"\n",
"if",
"err",... | // putVersion modifies the version of the store to reflect the given version
// number. | [
"putVersion",
"modifies",
"the",
"version",
"of",
"the",
"store",
"to",
"reflect",
"the",
"given",
"version",
"number",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L1429-L1438 | train |
btcsuite/btcwallet | wtxmgr/db.go | fetchVersion | func fetchVersion(ns walletdb.ReadBucket) (uint32, error) {
v := ns.Get(rootVersion)
if len(v) != 4 {
str := "no transaction store exists in namespace"
return 0, storeError(ErrNoExists, str, nil)
}
return byteOrder.Uint32(v), nil
} | go | func fetchVersion(ns walletdb.ReadBucket) (uint32, error) {
v := ns.Get(rootVersion)
if len(v) != 4 {
str := "no transaction store exists in namespace"
return 0, storeError(ErrNoExists, str, nil)
}
return byteOrder.Uint32(v), nil
} | [
"func",
"fetchVersion",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"v",
":=",
"ns",
".",
"Get",
"(",
"rootVersion",
")",
"\n",
"if",
"len",
"(",
"v",
")",
"!=",
"4",
"{",
"str",
":=",
"\"",
"\"",
"\n",
... | // fetchVersion fetches the current version of the store. | [
"fetchVersion",
"fetches",
"the",
"current",
"version",
"of",
"the",
"store",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/db.go#L1441-L1449 | train |
olahol/melody | session.go | Write | func (s *Session) Write(msg []byte) error {
if s.closed() {
return errors.New("session is closed")
}
s.writeMessage(&envelope{t: websocket.TextMessage, msg: msg})
return nil
} | go | func (s *Session) Write(msg []byte) error {
if s.closed() {
return errors.New("session is closed")
}
s.writeMessage(&envelope{t: websocket.TextMessage, msg: msg})
return nil
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Write",
"(",
"msg",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"s",
".",
"closed",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"s",
".",
"writeMessage",
"(",
... | // Write writes message to session. | [
"Write",
"writes",
"message",
"to",
"session",
"."
] | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/session.go#L143-L151 | train |
olahol/melody | session.go | WriteBinary | func (s *Session) WriteBinary(msg []byte) error {
if s.closed() {
return errors.New("session is closed")
}
s.writeMessage(&envelope{t: websocket.BinaryMessage, msg: msg})
return nil
} | go | func (s *Session) WriteBinary(msg []byte) error {
if s.closed() {
return errors.New("session is closed")
}
s.writeMessage(&envelope{t: websocket.BinaryMessage, msg: msg})
return nil
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"WriteBinary",
"(",
"msg",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"s",
".",
"closed",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"s",
".",
"writeMessage",
"... | // WriteBinary writes a binary message to session. | [
"WriteBinary",
"writes",
"a",
"binary",
"message",
"to",
"session",
"."
] | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/session.go#L154-L162 | train |
olahol/melody | session.go | Close | func (s *Session) Close() error {
if s.closed() {
return errors.New("session is already closed")
}
s.writeMessage(&envelope{t: websocket.CloseMessage, msg: []byte{}})
return nil
} | go | func (s *Session) Close() error {
if s.closed() {
return errors.New("session is already closed")
}
s.writeMessage(&envelope{t: websocket.CloseMessage, msg: []byte{}})
return nil
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"s",
".",
"closed",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"s",
".",
"writeMessage",
"(",
"&",
"envelope",
"{",
"t",
... | // Close closes session. | [
"Close",
"closes",
"session",
"."
] | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/session.go#L165-L173 | train |
olahol/melody | melody.go | New | func New() *Melody {
upgrader := &websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
hub := newHub()
go hub.run()
return &Melody{
Config: newConfig(),
Upgrader: upgrader,
messageHandler: ... | go | func New() *Melody {
upgrader := &websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
hub := newHub()
go hub.run()
return &Melody{
Config: newConfig(),
Upgrader: upgrader,
messageHandler: ... | [
"func",
"New",
"(",
")",
"*",
"Melody",
"{",
"upgrader",
":=",
"&",
"websocket",
".",
"Upgrader",
"{",
"ReadBufferSize",
":",
"1024",
",",
"WriteBufferSize",
":",
"1024",
",",
"CheckOrigin",
":",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"boo... | // New creates a new melody instance with default Upgrader and Config. | [
"New",
"creates",
"a",
"new",
"melody",
"instance",
"with",
"default",
"Upgrader",
"and",
"Config",
"."
] | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/melody.go#L73-L98 | train |
olahol/melody | melody.go | HandleClose | func (m *Melody) HandleClose(fn func(*Session, int, string) error) {
if fn != nil {
m.closeHandler = fn
}
} | go | func (m *Melody) HandleClose(fn func(*Session, int, string) error) {
if fn != nil {
m.closeHandler = fn
}
} | [
"func",
"(",
"m",
"*",
"Melody",
")",
"HandleClose",
"(",
"fn",
"func",
"(",
"*",
"Session",
",",
"int",
",",
"string",
")",
"error",
")",
"{",
"if",
"fn",
"!=",
"nil",
"{",
"m",
".",
"closeHandler",
"=",
"fn",
"\n",
"}",
"\n",
"}"
] | // HandleClose sets the handler for close messages received from the session.
// The code argument to h is the received close code or CloseNoStatusReceived
// if the close message is empty. The default close handler sends a close frame
// back to the session.
//
// The application must read the connection to process cl... | [
"HandleClose",
"sets",
"the",
"handler",
"for",
"close",
"messages",
"received",
"from",
"the",
"session",
".",
"The",
"code",
"argument",
"to",
"h",
"is",
"the",
"received",
"close",
"code",
"or",
"CloseNoStatusReceived",
"if",
"the",
"close",
"message",
"is"... | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/melody.go#L153-L157 | train |
olahol/melody | melody.go | HandleRequest | func (m *Melody) HandleRequest(w http.ResponseWriter, r *http.Request) error {
return m.HandleRequestWithKeys(w, r, nil)
} | go | func (m *Melody) HandleRequest(w http.ResponseWriter, r *http.Request) error {
return m.HandleRequestWithKeys(w, r, nil)
} | [
"func",
"(",
"m",
"*",
"Melody",
")",
"HandleRequest",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"return",
"m",
".",
"HandleRequestWithKeys",
"(",
"w",
",",
"r",
",",
"nil",
")",
"\n",
"}"
] | // HandleRequest upgrades http requests to websocket connections and dispatches them to be handled by the melody instance. | [
"HandleRequest",
"upgrades",
"http",
"requests",
"to",
"websocket",
"connections",
"and",
"dispatches",
"them",
"to",
"be",
"handled",
"by",
"the",
"melody",
"instance",
"."
] | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/melody.go#L160-L162 | train |
olahol/melody | melody.go | HandleRequestWithKeys | func (m *Melody) HandleRequestWithKeys(w http.ResponseWriter, r *http.Request, keys map[string]interface{}) error {
if m.hub.closed() {
return errors.New("melody instance is closed")
}
conn, err := m.Upgrader.Upgrade(w, r, w.Header())
if err != nil {
return err
}
session := &Session{
Request: r,
Keys: ... | go | func (m *Melody) HandleRequestWithKeys(w http.ResponseWriter, r *http.Request, keys map[string]interface{}) error {
if m.hub.closed() {
return errors.New("melody instance is closed")
}
conn, err := m.Upgrader.Upgrade(w, r, w.Header())
if err != nil {
return err
}
session := &Session{
Request: r,
Keys: ... | [
"func",
"(",
"m",
"*",
"Melody",
")",
"HandleRequestWithKeys",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"keys",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"m",
".",
"hub",
... | // HandleRequestWithKeys does the same as HandleRequest but populates session.Keys with keys. | [
"HandleRequestWithKeys",
"does",
"the",
"same",
"as",
"HandleRequest",
"but",
"populates",
"session",
".",
"Keys",
"with",
"keys",
"."
] | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/melody.go#L165-L203 | train |
olahol/melody | melody.go | Broadcast | func (m *Melody) Broadcast(msg []byte) error {
if m.hub.closed() {
return errors.New("melody instance is closed")
}
message := &envelope{t: websocket.TextMessage, msg: msg}
m.hub.broadcast <- message
return nil
} | go | func (m *Melody) Broadcast(msg []byte) error {
if m.hub.closed() {
return errors.New("melody instance is closed")
}
message := &envelope{t: websocket.TextMessage, msg: msg}
m.hub.broadcast <- message
return nil
} | [
"func",
"(",
"m",
"*",
"Melody",
")",
"Broadcast",
"(",
"msg",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"m",
".",
"hub",
".",
"closed",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"message",
":=",
... | // Broadcast broadcasts a text message to all sessions. | [
"Broadcast",
"broadcasts",
"a",
"text",
"message",
"to",
"all",
"sessions",
"."
] | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/melody.go#L206-L215 | train |
olahol/melody | melody.go | BroadcastOthers | func (m *Melody) BroadcastOthers(msg []byte, s *Session) error {
return m.BroadcastFilter(msg, func(q *Session) bool {
return s != q
})
} | go | func (m *Melody) BroadcastOthers(msg []byte, s *Session) error {
return m.BroadcastFilter(msg, func(q *Session) bool {
return s != q
})
} | [
"func",
"(",
"m",
"*",
"Melody",
")",
"BroadcastOthers",
"(",
"msg",
"[",
"]",
"byte",
",",
"s",
"*",
"Session",
")",
"error",
"{",
"return",
"m",
".",
"BroadcastFilter",
"(",
"msg",
",",
"func",
"(",
"q",
"*",
"Session",
")",
"bool",
"{",
"return"... | // BroadcastOthers broadcasts a text message to all sessions except session s. | [
"BroadcastOthers",
"broadcasts",
"a",
"text",
"message",
"to",
"all",
"sessions",
"except",
"session",
"s",
"."
] | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/melody.go#L230-L234 | train |
olahol/melody | melody.go | BroadcastMultiple | func (m *Melody) BroadcastMultiple(msg []byte, sessions []*Session) error {
for _, sess := range sessions {
if writeErr := sess.Write(msg); writeErr != nil {
return writeErr
}
}
return nil
} | go | func (m *Melody) BroadcastMultiple(msg []byte, sessions []*Session) error {
for _, sess := range sessions {
if writeErr := sess.Write(msg); writeErr != nil {
return writeErr
}
}
return nil
} | [
"func",
"(",
"m",
"*",
"Melody",
")",
"BroadcastMultiple",
"(",
"msg",
"[",
"]",
"byte",
",",
"sessions",
"[",
"]",
"*",
"Session",
")",
"error",
"{",
"for",
"_",
",",
"sess",
":=",
"range",
"sessions",
"{",
"if",
"writeErr",
":=",
"sess",
".",
"Wr... | // BroadcastMultiple broadcasts a text message to multiple sessions given in the sessions slice. | [
"BroadcastMultiple",
"broadcasts",
"a",
"text",
"message",
"to",
"multiple",
"sessions",
"given",
"in",
"the",
"sessions",
"slice",
"."
] | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/melody.go#L237-L244 | train |
olahol/melody | melody.go | BroadcastBinary | func (m *Melody) BroadcastBinary(msg []byte) error {
if m.hub.closed() {
return errors.New("melody instance is closed")
}
message := &envelope{t: websocket.BinaryMessage, msg: msg}
m.hub.broadcast <- message
return nil
} | go | func (m *Melody) BroadcastBinary(msg []byte) error {
if m.hub.closed() {
return errors.New("melody instance is closed")
}
message := &envelope{t: websocket.BinaryMessage, msg: msg}
m.hub.broadcast <- message
return nil
} | [
"func",
"(",
"m",
"*",
"Melody",
")",
"BroadcastBinary",
"(",
"msg",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"m",
".",
"hub",
".",
"closed",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"message",
"... | // BroadcastBinary broadcasts a binary message to all sessions. | [
"BroadcastBinary",
"broadcasts",
"a",
"binary",
"message",
"to",
"all",
"sessions",
"."
] | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/melody.go#L247-L256 | train |
olahol/melody | melody.go | BroadcastBinaryFilter | func (m *Melody) BroadcastBinaryFilter(msg []byte, fn func(*Session) bool) error {
if m.hub.closed() {
return errors.New("melody instance is closed")
}
message := &envelope{t: websocket.BinaryMessage, msg: msg, filter: fn}
m.hub.broadcast <- message
return nil
} | go | func (m *Melody) BroadcastBinaryFilter(msg []byte, fn func(*Session) bool) error {
if m.hub.closed() {
return errors.New("melody instance is closed")
}
message := &envelope{t: websocket.BinaryMessage, msg: msg, filter: fn}
m.hub.broadcast <- message
return nil
} | [
"func",
"(",
"m",
"*",
"Melody",
")",
"BroadcastBinaryFilter",
"(",
"msg",
"[",
"]",
"byte",
",",
"fn",
"func",
"(",
"*",
"Session",
")",
"bool",
")",
"error",
"{",
"if",
"m",
".",
"hub",
".",
"closed",
"(",
")",
"{",
"return",
"errors",
".",
"Ne... | // BroadcastBinaryFilter broadcasts a binary message to all sessions that fn returns true for. | [
"BroadcastBinaryFilter",
"broadcasts",
"a",
"binary",
"message",
"to",
"all",
"sessions",
"that",
"fn",
"returns",
"true",
"for",
"."
] | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/melody.go#L259-L268 | train |
olahol/melody | melody.go | BroadcastBinaryOthers | func (m *Melody) BroadcastBinaryOthers(msg []byte, s *Session) error {
return m.BroadcastBinaryFilter(msg, func(q *Session) bool {
return s != q
})
} | go | func (m *Melody) BroadcastBinaryOthers(msg []byte, s *Session) error {
return m.BroadcastBinaryFilter(msg, func(q *Session) bool {
return s != q
})
} | [
"func",
"(",
"m",
"*",
"Melody",
")",
"BroadcastBinaryOthers",
"(",
"msg",
"[",
"]",
"byte",
",",
"s",
"*",
"Session",
")",
"error",
"{",
"return",
"m",
".",
"BroadcastBinaryFilter",
"(",
"msg",
",",
"func",
"(",
"q",
"*",
"Session",
")",
"bool",
"{"... | // BroadcastBinaryOthers broadcasts a binary message to all sessions except session s. | [
"BroadcastBinaryOthers",
"broadcasts",
"a",
"binary",
"message",
"to",
"all",
"sessions",
"except",
"session",
"s",
"."
] | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/melody.go#L271-L275 | train |
olahol/melody | melody.go | Close | func (m *Melody) Close() error {
if m.hub.closed() {
return errors.New("melody instance is already closed")
}
m.hub.exit <- &envelope{t: websocket.CloseMessage, msg: []byte{}}
return nil
} | go | func (m *Melody) Close() error {
if m.hub.closed() {
return errors.New("melody instance is already closed")
}
m.hub.exit <- &envelope{t: websocket.CloseMessage, msg: []byte{}}
return nil
} | [
"func",
"(",
"m",
"*",
"Melody",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"m",
".",
"hub",
".",
"closed",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"m",
".",
"hub",
".",
"exit",
"<-",
"&",
"e... | // Close closes the melody instance and all connected sessions. | [
"Close",
"closes",
"the",
"melody",
"instance",
"and",
"all",
"connected",
"sessions",
"."
] | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/melody.go#L278-L286 | train |
olahol/melody | melody.go | FormatCloseMessage | func FormatCloseMessage(closeCode int, text string) []byte {
return websocket.FormatCloseMessage(closeCode, text)
} | go | func FormatCloseMessage(closeCode int, text string) []byte {
return websocket.FormatCloseMessage(closeCode, text)
} | [
"func",
"FormatCloseMessage",
"(",
"closeCode",
"int",
",",
"text",
"string",
")",
"[",
"]",
"byte",
"{",
"return",
"websocket",
".",
"FormatCloseMessage",
"(",
"closeCode",
",",
"text",
")",
"\n",
"}"
] | // FormatCloseMessage formats closeCode and text as a WebSocket close message. | [
"FormatCloseMessage",
"formats",
"closeCode",
"and",
"text",
"as",
"a",
"WebSocket",
"close",
"message",
"."
] | 7bd65910e5abdd2e7396c23acb13475bff79d1af | https://github.com/olahol/melody/blob/7bd65910e5abdd2e7396c23acb13475bff79d1af/melody.go#L311-L313 | train |
hashicorp/mdns | zone.go | Records | func (m *MDNSService) Records(q dns.Question) []dns.RR {
switch q.Name {
case m.enumAddr:
return m.serviceEnum(q)
case m.serviceAddr:
return m.serviceRecords(q)
case m.instanceAddr:
return m.instanceRecords(q)
case m.HostName:
if q.Qtype == dns.TypeA || q.Qtype == dns.TypeAAAA {
return m.instanceRecords... | go | func (m *MDNSService) Records(q dns.Question) []dns.RR {
switch q.Name {
case m.enumAddr:
return m.serviceEnum(q)
case m.serviceAddr:
return m.serviceRecords(q)
case m.instanceAddr:
return m.instanceRecords(q)
case m.HostName:
if q.Qtype == dns.TypeA || q.Qtype == dns.TypeAAAA {
return m.instanceRecords... | [
"func",
"(",
"m",
"*",
"MDNSService",
")",
"Records",
"(",
"q",
"dns",
".",
"Question",
")",
"[",
"]",
"dns",
".",
"RR",
"{",
"switch",
"q",
".",
"Name",
"{",
"case",
"m",
".",
"enumAddr",
":",
"return",
"m",
".",
"serviceEnum",
"(",
"q",
")",
... | // Records returns DNS records in response to a DNS question. | [
"Records",
"returns",
"DNS",
"records",
"in",
"response",
"to",
"a",
"DNS",
"question",
"."
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/zone.go#L137-L153 | train |
hashicorp/mdns | zone.go | serviceRecords | func (m *MDNSService) serviceRecords(q dns.Question) []dns.RR {
switch q.Qtype {
case dns.TypeANY:
fallthrough
case dns.TypePTR:
// Build a PTR response for the service
rr := &dns.PTR{
Hdr: dns.RR_Header{
Name: q.Name,
Rrtype: dns.TypePTR,
Class: dns.ClassINET,
Ttl: defaultTTL,
},
... | go | func (m *MDNSService) serviceRecords(q dns.Question) []dns.RR {
switch q.Qtype {
case dns.TypeANY:
fallthrough
case dns.TypePTR:
// Build a PTR response for the service
rr := &dns.PTR{
Hdr: dns.RR_Header{
Name: q.Name,
Rrtype: dns.TypePTR,
Class: dns.ClassINET,
Ttl: defaultTTL,
},
... | [
"func",
"(",
"m",
"*",
"MDNSService",
")",
"serviceRecords",
"(",
"q",
"dns",
".",
"Question",
")",
"[",
"]",
"dns",
".",
"RR",
"{",
"switch",
"q",
".",
"Qtype",
"{",
"case",
"dns",
".",
"TypeANY",
":",
"fallthrough",
"\n",
"case",
"dns",
".",
"Typ... | // serviceRecords is called when the query matches the service name | [
"serviceRecords",
"is",
"called",
"when",
"the",
"query",
"matches",
"the",
"service",
"name"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/zone.go#L176-L204 | train |
hashicorp/mdns | zone.go | instanceRecords | func (m *MDNSService) instanceRecords(q dns.Question) []dns.RR {
switch q.Qtype {
case dns.TypeANY:
// Get the SRV, which includes A and AAAA
recs := m.instanceRecords(dns.Question{
Name: m.instanceAddr,
Qtype: dns.TypeSRV,
})
// Add the TXT record
recs = append(recs, m.instanceRecords(dns.Question{... | go | func (m *MDNSService) instanceRecords(q dns.Question) []dns.RR {
switch q.Qtype {
case dns.TypeANY:
// Get the SRV, which includes A and AAAA
recs := m.instanceRecords(dns.Question{
Name: m.instanceAddr,
Qtype: dns.TypeSRV,
})
// Add the TXT record
recs = append(recs, m.instanceRecords(dns.Question{... | [
"func",
"(",
"m",
"*",
"MDNSService",
")",
"instanceRecords",
"(",
"q",
"dns",
".",
"Question",
")",
"[",
"]",
"dns",
".",
"RR",
"{",
"switch",
"q",
".",
"Qtype",
"{",
"case",
"dns",
".",
"TypeANY",
":",
"// Get the SRV, which includes A and AAAA",
"recs",... | // serviceRecords is called when the query matches the instance name | [
"serviceRecords",
"is",
"called",
"when",
"the",
"query",
"matches",
"the",
"instance",
"name"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/zone.go#L207-L307 | train |
hashicorp/mdns | server.go | NewServer | func NewServer(config *Config) (*Server, error) {
// Create the listeners
ipv4List, _ := net.ListenMulticastUDP("udp4", config.Iface, ipv4Addr)
ipv6List, _ := net.ListenMulticastUDP("udp6", config.Iface, ipv6Addr)
// Check if we have any listener
if ipv4List == nil && ipv6List == nil {
return nil, fmt.Errorf("N... | go | func NewServer(config *Config) (*Server, error) {
// Create the listeners
ipv4List, _ := net.ListenMulticastUDP("udp4", config.Iface, ipv4Addr)
ipv6List, _ := net.ListenMulticastUDP("udp6", config.Iface, ipv6Addr)
// Check if we have any listener
if ipv4List == nil && ipv6List == nil {
return nil, fmt.Errorf("N... | [
"func",
"NewServer",
"(",
"config",
"*",
"Config",
")",
"(",
"*",
"Server",
",",
"error",
")",
"{",
"// Create the listeners",
"ipv4List",
",",
"_",
":=",
"net",
".",
"ListenMulticastUDP",
"(",
"\"",
"\"",
",",
"config",
".",
"Iface",
",",
"ipv4Addr",
")... | // NewServer is used to create a new mDNS server from a config | [
"NewServer",
"is",
"used",
"to",
"create",
"a",
"new",
"mDNS",
"server",
"from",
"a",
"config"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/server.go#L59-L85 | train |
hashicorp/mdns | server.go | Shutdown | func (s *Server) Shutdown() error {
if !atomic.CompareAndSwapInt32(&s.shutdown, 0, 1) {
// something else already closed us
return nil
}
close(s.shutdownCh)
if s.ipv4List != nil {
s.ipv4List.Close()
}
if s.ipv6List != nil {
s.ipv6List.Close()
}
return nil
} | go | func (s *Server) Shutdown() error {
if !atomic.CompareAndSwapInt32(&s.shutdown, 0, 1) {
// something else already closed us
return nil
}
close(s.shutdownCh)
if s.ipv4List != nil {
s.ipv4List.Close()
}
if s.ipv6List != nil {
s.ipv6List.Close()
}
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Shutdown",
"(",
")",
"error",
"{",
"if",
"!",
"atomic",
".",
"CompareAndSwapInt32",
"(",
"&",
"s",
".",
"shutdown",
",",
"0",
",",
"1",
")",
"{",
"// something else already closed us",
"return",
"nil",
"\n",
"}",
... | // Shutdown is used to shutdown the listener | [
"Shutdown",
"is",
"used",
"to",
"shutdown",
"the",
"listener"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/server.go#L88-L103 | train |
hashicorp/mdns | server.go | parsePacket | func (s *Server) parsePacket(packet []byte, from net.Addr) error {
var msg dns.Msg
if err := msg.Unpack(packet); err != nil {
log.Printf("[ERR] mdns: Failed to unpack packet: %v", err)
return err
}
return s.handleQuery(&msg, from)
} | go | func (s *Server) parsePacket(packet []byte, from net.Addr) error {
var msg dns.Msg
if err := msg.Unpack(packet); err != nil {
log.Printf("[ERR] mdns: Failed to unpack packet: %v", err)
return err
}
return s.handleQuery(&msg, from)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"parsePacket",
"(",
"packet",
"[",
"]",
"byte",
",",
"from",
"net",
".",
"Addr",
")",
"error",
"{",
"var",
"msg",
"dns",
".",
"Msg",
"\n",
"if",
"err",
":=",
"msg",
".",
"Unpack",
"(",
"packet",
")",
";",
"... | // parsePacket is used to parse an incoming packet | [
"parsePacket",
"is",
"used",
"to",
"parse",
"an",
"incoming",
"packet"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/server.go#L124-L131 | train |
hashicorp/mdns | server.go | handleQuestion | func (s *Server) handleQuestion(q dns.Question) (multicastRecs, unicastRecs []dns.RR) {
records := s.config.Zone.Records(q)
if len(records) == 0 {
return nil, nil
}
// Handle unicast and multicast responses.
// TODO(reddaly): The decision about sending over unicast vs. multicast is not
// yet fully compliant ... | go | func (s *Server) handleQuestion(q dns.Question) (multicastRecs, unicastRecs []dns.RR) {
records := s.config.Zone.Records(q)
if len(records) == 0 {
return nil, nil
}
// Handle unicast and multicast responses.
// TODO(reddaly): The decision about sending over unicast vs. multicast is not
// yet fully compliant ... | [
"func",
"(",
"s",
"*",
"Server",
")",
"handleQuestion",
"(",
"q",
"dns",
".",
"Question",
")",
"(",
"multicastRecs",
",",
"unicastRecs",
"[",
"]",
"dns",
".",
"RR",
")",
"{",
"records",
":=",
"s",
".",
"config",
".",
"Zone",
".",
"Records",
"(",
"q... | // handleQuestion is used to handle an incoming question
//
// The response to a question may be transmitted over multicast, unicast, or
// both. The return values are DNS records for each transmission type. | [
"handleQuestion",
"is",
"used",
"to",
"handle",
"an",
"incoming",
"question",
"The",
"response",
"to",
"a",
"question",
"may",
"be",
"transmitted",
"over",
"multicast",
"unicast",
"or",
"both",
".",
"The",
"return",
"values",
"are",
"DNS",
"records",
"for",
... | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/server.go#L246-L268 | train |
hashicorp/mdns | server.go | sendResponse | func (s *Server) sendResponse(resp *dns.Msg, from net.Addr, unicast bool) error {
// TODO(reddaly): Respect the unicast argument, and allow sending responses
// over multicast.
buf, err := resp.Pack()
if err != nil {
return err
}
// Determine the socket to send from
addr := from.(*net.UDPAddr)
if addr.IP.To4... | go | func (s *Server) sendResponse(resp *dns.Msg, from net.Addr, unicast bool) error {
// TODO(reddaly): Respect the unicast argument, and allow sending responses
// over multicast.
buf, err := resp.Pack()
if err != nil {
return err
}
// Determine the socket to send from
addr := from.(*net.UDPAddr)
if addr.IP.To4... | [
"func",
"(",
"s",
"*",
"Server",
")",
"sendResponse",
"(",
"resp",
"*",
"dns",
".",
"Msg",
",",
"from",
"net",
".",
"Addr",
",",
"unicast",
"bool",
")",
"error",
"{",
"// TODO(reddaly): Respect the unicast argument, and allow sending responses",
"// over multicast."... | // sendResponse is used to send a response packet | [
"sendResponse",
"is",
"used",
"to",
"send",
"a",
"response",
"packet"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/server.go#L271-L288 | train |
hashicorp/mdns | client.go | complete | func (s *ServiceEntry) complete() bool {
return (s.AddrV4 != nil || s.AddrV6 != nil || s.Addr != nil) && s.Port != 0 && s.hasTXT
} | go | func (s *ServiceEntry) complete() bool {
return (s.AddrV4 != nil || s.AddrV6 != nil || s.Addr != nil) && s.Port != 0 && s.hasTXT
} | [
"func",
"(",
"s",
"*",
"ServiceEntry",
")",
"complete",
"(",
")",
"bool",
"{",
"return",
"(",
"s",
".",
"AddrV4",
"!=",
"nil",
"||",
"s",
".",
"AddrV6",
"!=",
"nil",
"||",
"s",
".",
"Addr",
"!=",
"nil",
")",
"&&",
"s",
".",
"Port",
"!=",
"0",
... | // complete is used to check if we have all the info we need | [
"complete",
"is",
"used",
"to",
"check",
"if",
"we",
"have",
"all",
"the",
"info",
"we",
"need"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/client.go#L33-L35 | train |
hashicorp/mdns | client.go | DefaultParams | func DefaultParams(service string) *QueryParam {
return &QueryParam{
Service: service,
Domain: "local",
Timeout: time.Second,
Entries: make(chan *ServiceEntry),
WantUnicastResponse: false, // TODO(reddaly): Change this default.
}
} | go | func DefaultParams(service string) *QueryParam {
return &QueryParam{
Service: service,
Domain: "local",
Timeout: time.Second,
Entries: make(chan *ServiceEntry),
WantUnicastResponse: false, // TODO(reddaly): Change this default.
}
} | [
"func",
"DefaultParams",
"(",
"service",
"string",
")",
"*",
"QueryParam",
"{",
"return",
"&",
"QueryParam",
"{",
"Service",
":",
"service",
",",
"Domain",
":",
"\"",
"\"",
",",
"Timeout",
":",
"time",
".",
"Second",
",",
"Entries",
":",
"make",
"(",
"... | // DefaultParams is used to return a default set of QueryParam's | [
"DefaultParams",
"is",
"used",
"to",
"return",
"a",
"default",
"set",
"of",
"QueryParam",
"s"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/client.go#L48-L56 | train |
hashicorp/mdns | client.go | Query | func Query(params *QueryParam) error {
// Create a new client
client, err := newClient()
if err != nil {
return err
}
defer client.Close()
// Set the multicast interface
if params.Interface != nil {
if err := client.setInterface(params.Interface); err != nil {
return err
}
}
// Ensure defaults are s... | go | func Query(params *QueryParam) error {
// Create a new client
client, err := newClient()
if err != nil {
return err
}
defer client.Close()
// Set the multicast interface
if params.Interface != nil {
if err := client.setInterface(params.Interface); err != nil {
return err
}
}
// Ensure defaults are s... | [
"func",
"Query",
"(",
"params",
"*",
"QueryParam",
")",
"error",
"{",
"// Create a new client",
"client",
",",
"err",
":=",
"newClient",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"client",
".",
"Close",
"... | // Query looks up a given service, in a domain, waiting at most
// for a timeout before finishing the query. The results are streamed
// to a channel. Sends will not block, so clients should make sure to
// either read or buffer. | [
"Query",
"looks",
"up",
"a",
"given",
"service",
"in",
"a",
"domain",
"waiting",
"at",
"most",
"for",
"a",
"timeout",
"before",
"finishing",
"the",
"query",
".",
"The",
"results",
"are",
"streamed",
"to",
"a",
"channel",
".",
"Sends",
"will",
"not",
"blo... | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/client.go#L62-L87 | train |
hashicorp/mdns | client.go | Lookup | func Lookup(service string, entries chan<- *ServiceEntry) error {
params := DefaultParams(service)
params.Entries = entries
return Query(params)
} | go | func Lookup(service string, entries chan<- *ServiceEntry) error {
params := DefaultParams(service)
params.Entries = entries
return Query(params)
} | [
"func",
"Lookup",
"(",
"service",
"string",
",",
"entries",
"chan",
"<-",
"*",
"ServiceEntry",
")",
"error",
"{",
"params",
":=",
"DefaultParams",
"(",
"service",
")",
"\n",
"params",
".",
"Entries",
"=",
"entries",
"\n",
"return",
"Query",
"(",
"params",
... | // Lookup is the same as Query, however it uses all the default parameters | [
"Lookup",
"is",
"the",
"same",
"as",
"Query",
"however",
"it",
"uses",
"all",
"the",
"default",
"parameters"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/client.go#L90-L94 | train |
hashicorp/mdns | client.go | newClient | func newClient() (*client, error) {
// TODO(reddaly): At least attempt to bind to the port required in the spec.
// Create a IPv4 listener
uconn4, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero, Port: 0})
if err != nil {
log.Printf("[ERR] mdns: Failed to bind to udp4 port: %v", err)
}
uconn6, err :=... | go | func newClient() (*client, error) {
// TODO(reddaly): At least attempt to bind to the port required in the spec.
// Create a IPv4 listener
uconn4, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero, Port: 0})
if err != nil {
log.Printf("[ERR] mdns: Failed to bind to udp4 port: %v", err)
}
uconn6, err :=... | [
"func",
"newClient",
"(",
")",
"(",
"*",
"client",
",",
"error",
")",
"{",
"// TODO(reddaly): At least attempt to bind to the port required in the spec.",
"// Create a IPv4 listener",
"uconn4",
",",
"err",
":=",
"net",
".",
"ListenUDP",
"(",
"\"",
"\"",
",",
"&",
"n... | // NewClient creates a new mdns Client that can be used to query
// for records | [
"NewClient",
"creates",
"a",
"new",
"mdns",
"Client",
"that",
"can",
"be",
"used",
"to",
"query",
"for",
"records"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/client.go#L111-L148 | train |
hashicorp/mdns | client.go | Close | func (c *client) Close() error {
if !atomic.CompareAndSwapInt32(&c.closed, 0, 1) {
// something else already closed it
return nil
}
log.Printf("[INFO] mdns: Closing client %v", *c)
close(c.closedCh)
if c.ipv4UnicastConn != nil {
c.ipv4UnicastConn.Close()
}
if c.ipv6UnicastConn != nil {
c.ipv6UnicastCon... | go | func (c *client) Close() error {
if !atomic.CompareAndSwapInt32(&c.closed, 0, 1) {
// something else already closed it
return nil
}
log.Printf("[INFO] mdns: Closing client %v", *c)
close(c.closedCh)
if c.ipv4UnicastConn != nil {
c.ipv4UnicastConn.Close()
}
if c.ipv6UnicastConn != nil {
c.ipv6UnicastCon... | [
"func",
"(",
"c",
"*",
"client",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"!",
"atomic",
".",
"CompareAndSwapInt32",
"(",
"&",
"c",
".",
"closed",
",",
"0",
",",
"1",
")",
"{",
"// something else already closed it",
"return",
"nil",
"\n",
"}",
"\n\n... | // Close is used to cleanup the client | [
"Close",
"is",
"used",
"to",
"cleanup",
"the",
"client"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/client.go#L151-L174 | train |
hashicorp/mdns | client.go | setInterface | func (c *client) setInterface(iface *net.Interface) error {
p := ipv4.NewPacketConn(c.ipv4UnicastConn)
if err := p.SetMulticastInterface(iface); err != nil {
return err
}
p2 := ipv6.NewPacketConn(c.ipv6UnicastConn)
if err := p2.SetMulticastInterface(iface); err != nil {
return err
}
p = ipv4.NewPacketConn(c.... | go | func (c *client) setInterface(iface *net.Interface) error {
p := ipv4.NewPacketConn(c.ipv4UnicastConn)
if err := p.SetMulticastInterface(iface); err != nil {
return err
}
p2 := ipv6.NewPacketConn(c.ipv6UnicastConn)
if err := p2.SetMulticastInterface(iface); err != nil {
return err
}
p = ipv4.NewPacketConn(c.... | [
"func",
"(",
"c",
"*",
"client",
")",
"setInterface",
"(",
"iface",
"*",
"net",
".",
"Interface",
")",
"error",
"{",
"p",
":=",
"ipv4",
".",
"NewPacketConn",
"(",
"c",
".",
"ipv4UnicastConn",
")",
"\n",
"if",
"err",
":=",
"p",
".",
"SetMulticastInterfa... | // setInterface is used to set the query interface, uses sytem
// default if not provided | [
"setInterface",
"is",
"used",
"to",
"set",
"the",
"query",
"interface",
"uses",
"sytem",
"default",
"if",
"not",
"provided"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/client.go#L178-L196 | train |
hashicorp/mdns | client.go | sendQuery | func (c *client) sendQuery(q *dns.Msg) error {
buf, err := q.Pack()
if err != nil {
return err
}
if c.ipv4UnicastConn != nil {
c.ipv4UnicastConn.WriteToUDP(buf, ipv4Addr)
}
if c.ipv6UnicastConn != nil {
c.ipv6UnicastConn.WriteToUDP(buf, ipv6Addr)
}
return nil
} | go | func (c *client) sendQuery(q *dns.Msg) error {
buf, err := q.Pack()
if err != nil {
return err
}
if c.ipv4UnicastConn != nil {
c.ipv4UnicastConn.WriteToUDP(buf, ipv4Addr)
}
if c.ipv6UnicastConn != nil {
c.ipv6UnicastConn.WriteToUDP(buf, ipv6Addr)
}
return nil
} | [
"func",
"(",
"c",
"*",
"client",
")",
"sendQuery",
"(",
"q",
"*",
"dns",
".",
"Msg",
")",
"error",
"{",
"buf",
",",
"err",
":=",
"q",
".",
"Pack",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"c",
"... | // sendQuery is used to multicast a query out | [
"sendQuery",
"is",
"used",
"to",
"multicast",
"a",
"query",
"out"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/client.go#L305-L317 | train |
hashicorp/mdns | client.go | recv | func (c *client) recv(l *net.UDPConn, msgCh chan *dns.Msg) {
if l == nil {
return
}
buf := make([]byte, 65536)
for atomic.LoadInt32(&c.closed) == 0 {
n, err := l.Read(buf)
if atomic.LoadInt32(&c.closed) == 1 {
return
}
if err != nil {
log.Printf("[ERR] mdns: Failed to read packet: %v", err)
con... | go | func (c *client) recv(l *net.UDPConn, msgCh chan *dns.Msg) {
if l == nil {
return
}
buf := make([]byte, 65536)
for atomic.LoadInt32(&c.closed) == 0 {
n, err := l.Read(buf)
if atomic.LoadInt32(&c.closed) == 1 {
return
}
if err != nil {
log.Printf("[ERR] mdns: Failed to read packet: %v", err)
con... | [
"func",
"(",
"c",
"*",
"client",
")",
"recv",
"(",
"l",
"*",
"net",
".",
"UDPConn",
",",
"msgCh",
"chan",
"*",
"dns",
".",
"Msg",
")",
"{",
"if",
"l",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
... | // recv is used to receive until we get a shutdown | [
"recv",
"is",
"used",
"to",
"receive",
"until",
"we",
"get",
"a",
"shutdown"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/client.go#L320-L347 | train |
hashicorp/mdns | client.go | ensureName | func ensureName(inprogress map[string]*ServiceEntry, name string) *ServiceEntry {
if inp, ok := inprogress[name]; ok {
return inp
}
inp := &ServiceEntry{
Name: name,
}
inprogress[name] = inp
return inp
} | go | func ensureName(inprogress map[string]*ServiceEntry, name string) *ServiceEntry {
if inp, ok := inprogress[name]; ok {
return inp
}
inp := &ServiceEntry{
Name: name,
}
inprogress[name] = inp
return inp
} | [
"func",
"ensureName",
"(",
"inprogress",
"map",
"[",
"string",
"]",
"*",
"ServiceEntry",
",",
"name",
"string",
")",
"*",
"ServiceEntry",
"{",
"if",
"inp",
",",
"ok",
":=",
"inprogress",
"[",
"name",
"]",
";",
"ok",
"{",
"return",
"inp",
"\n",
"}",
"... | // ensureName is used to ensure the named node is in progress | [
"ensureName",
"is",
"used",
"to",
"ensure",
"the",
"named",
"node",
"is",
"in",
"progress"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/client.go#L350-L359 | train |
hashicorp/mdns | client.go | alias | func alias(inprogress map[string]*ServiceEntry, src, dst string) {
srcEntry := ensureName(inprogress, src)
inprogress[dst] = srcEntry
} | go | func alias(inprogress map[string]*ServiceEntry, src, dst string) {
srcEntry := ensureName(inprogress, src)
inprogress[dst] = srcEntry
} | [
"func",
"alias",
"(",
"inprogress",
"map",
"[",
"string",
"]",
"*",
"ServiceEntry",
",",
"src",
",",
"dst",
"string",
")",
"{",
"srcEntry",
":=",
"ensureName",
"(",
"inprogress",
",",
"src",
")",
"\n",
"inprogress",
"[",
"dst",
"]",
"=",
"srcEntry",
"\... | // alias is used to setup an alias between two entries | [
"alias",
"is",
"used",
"to",
"setup",
"an",
"alias",
"between",
"two",
"entries"
] | 06dd1a31b32c42d4d6c2cf8dbce70597d1118f54 | https://github.com/hashicorp/mdns/blob/06dd1a31b32c42d4d6c2cf8dbce70597d1118f54/client.go#L362-L365 | train |
otiai10/gosseract | client.go | Version | func Version() string {
api := C.Create()
defer C.Free(api)
version := C.Version(api)
return C.GoString(version)
} | go | func Version() string {
api := C.Create()
defer C.Free(api)
version := C.Version(api)
return C.GoString(version)
} | [
"func",
"Version",
"(",
")",
"string",
"{",
"api",
":=",
"C",
".",
"Create",
"(",
")",
"\n",
"defer",
"C",
".",
"Free",
"(",
"api",
")",
"\n",
"version",
":=",
"C",
".",
"Version",
"(",
"api",
")",
"\n",
"return",
"C",
".",
"GoString",
"(",
"ve... | // Version returns the version of Tesseract-OCR | [
"Version",
"returns",
"the",
"version",
"of",
"Tesseract",
"-",
"OCR"
] | 02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4 | https://github.com/otiai10/gosseract/blob/02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4/client.go#L23-L28 | train |
otiai10/gosseract | client.go | NewClient | func NewClient() *Client {
client := &Client{
api: C.Create(),
Variables: map[SettableVariable]string{},
Trim: true,
shouldInit: true,
}
return client
} | go | func NewClient() *Client {
client := &Client{
api: C.Create(),
Variables: map[SettableVariable]string{},
Trim: true,
shouldInit: true,
}
return client
} | [
"func",
"NewClient",
"(",
")",
"*",
"Client",
"{",
"client",
":=",
"&",
"Client",
"{",
"api",
":",
"C",
".",
"Create",
"(",
")",
",",
"Variables",
":",
"map",
"[",
"SettableVariable",
"]",
"string",
"{",
"}",
",",
"Trim",
":",
"true",
",",
"shouldI... | // NewClient construct new Client. It's due to caller to Close this client. | [
"NewClient",
"construct",
"new",
"Client",
".",
"It",
"s",
"due",
"to",
"caller",
"to",
"Close",
"this",
"client",
"."
] | 02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4 | https://github.com/otiai10/gosseract/blob/02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4/client.go#L73-L81 | train |
otiai10/gosseract | client.go | Close | func (client *Client) Close() (err error) {
// defer func() {
// if e := recover(); e != nil {
// err = fmt.Errorf("%v", e)
// }
// }()
C.Clear(client.api)
C.Free(client.api)
if client.pixImage != nil {
C.DestroyPixImage(client.pixImage)
client.pixImage = nil
}
return err
} | go | func (client *Client) Close() (err error) {
// defer func() {
// if e := recover(); e != nil {
// err = fmt.Errorf("%v", e)
// }
// }()
C.Clear(client.api)
C.Free(client.api)
if client.pixImage != nil {
C.DestroyPixImage(client.pixImage)
client.pixImage = nil
}
return err
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"Close",
"(",
")",
"(",
"err",
"error",
")",
"{",
"// defer func() {",
"// \tif e := recover(); e != nil {",
"// \t\terr = fmt.Errorf(\"%v\", e)",
"// \t}",
"// }()",
"C",
".",
"Clear",
"(",
"client",
".",
"api",
")",
"... | // Close frees allocated API. This MUST be called for ANY client constructed by "NewClient" function. | [
"Close",
"frees",
"allocated",
"API",
".",
"This",
"MUST",
"be",
"called",
"for",
"ANY",
"client",
"constructed",
"by",
"NewClient",
"function",
"."
] | 02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4 | https://github.com/otiai10/gosseract/blob/02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4/client.go#L84-L97 | train |
otiai10/gosseract | client.go | SetImage | func (client *Client) SetImage(imagepath string) error {
if client.api == nil {
return fmt.Errorf("TessBaseAPI is not constructed, please use `gosseract.NewClient`")
}
if imagepath == "" {
return fmt.Errorf("image path cannot be empty")
}
if _, err := os.Stat(imagepath); err != nil {
return fmt.Errorf("cann... | go | func (client *Client) SetImage(imagepath string) error {
if client.api == nil {
return fmt.Errorf("TessBaseAPI is not constructed, please use `gosseract.NewClient`")
}
if imagepath == "" {
return fmt.Errorf("image path cannot be empty")
}
if _, err := os.Stat(imagepath); err != nil {
return fmt.Errorf("cann... | [
"func",
"(",
"client",
"*",
"Client",
")",
"SetImage",
"(",
"imagepath",
"string",
")",
"error",
"{",
"if",
"client",
".",
"api",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"imagepath",
"==",
"\""... | // SetImage sets path to image file to be processed OCR. | [
"SetImage",
"sets",
"path",
"to",
"image",
"file",
"to",
"be",
"processed",
"OCR",
"."
] | 02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4 | https://github.com/otiai10/gosseract/blob/02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4/client.go#L100-L124 | train |
otiai10/gosseract | client.go | SetImageFromBytes | func (client *Client) SetImageFromBytes(data []byte) error {
if client.api == nil {
return fmt.Errorf("TessBaseAPI is not constructed, please use `gosseract.NewClient`")
}
if len(data) == 0 {
return fmt.Errorf("image data cannot be empty")
}
if client.pixImage != nil {
C.DestroyPixImage(client.pixImage)
... | go | func (client *Client) SetImageFromBytes(data []byte) error {
if client.api == nil {
return fmt.Errorf("TessBaseAPI is not constructed, please use `gosseract.NewClient`")
}
if len(data) == 0 {
return fmt.Errorf("image data cannot be empty")
}
if client.pixImage != nil {
C.DestroyPixImage(client.pixImage)
... | [
"func",
"(",
"client",
"*",
"Client",
")",
"SetImageFromBytes",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"client",
".",
"api",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(... | // SetImageFromBytes sets the image data to be processed OCR. | [
"SetImageFromBytes",
"sets",
"the",
"image",
"data",
"to",
"be",
"processed",
"OCR",
"."
] | 02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4 | https://github.com/otiai10/gosseract/blob/02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4/client.go#L127-L145 | train |
otiai10/gosseract | client.go | SetLanguage | func (client *Client) SetLanguage(langs ...string) error {
if len(langs) == 0 {
return fmt.Errorf("languages cannot be empty")
}
client.Languages = langs
client.flagForInit()
return nil
} | go | func (client *Client) SetLanguage(langs ...string) error {
if len(langs) == 0 {
return fmt.Errorf("languages cannot be empty")
}
client.Languages = langs
client.flagForInit()
return nil
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"SetLanguage",
"(",
"langs",
"...",
"string",
")",
"error",
"{",
"if",
"len",
"(",
"langs",
")",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"client",
".",
"L... | // SetLanguage sets languages to use. English as default. | [
"SetLanguage",
"sets",
"languages",
"to",
"use",
".",
"English",
"as",
"default",
"."
] | 02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4 | https://github.com/otiai10/gosseract/blob/02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4/client.go#L148-L158 | train |
otiai10/gosseract | client.go | SetConfigFile | func (client *Client) SetConfigFile(fpath string) error {
info, err := os.Stat(fpath)
if err != nil {
return err
}
if info.IsDir() {
return fmt.Errorf("the specified config file path seems to be a directory")
}
client.ConfigFilePath = fpath
client.flagForInit()
return nil
} | go | func (client *Client) SetConfigFile(fpath string) error {
info, err := os.Stat(fpath)
if err != nil {
return err
}
if info.IsDir() {
return fmt.Errorf("the specified config file path seems to be a directory")
}
client.ConfigFilePath = fpath
client.flagForInit()
return nil
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"SetConfigFile",
"(",
"fpath",
"string",
")",
"error",
"{",
"info",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"fpath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"i... | // SetConfigFile sets the file path to config file. | [
"SetConfigFile",
"sets",
"the",
"file",
"path",
"to",
"config",
"file",
"."
] | 02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4 | https://github.com/otiai10/gosseract/blob/02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4/client.go#L209-L222 | train |
otiai10/gosseract | client.go | GetBoundingBoxes | func (client *Client) GetBoundingBoxes(level PageIteratorLevel) (out []BoundingBox, err error) {
if client.api == nil {
return out, fmt.Errorf("TessBaseAPI is not constructed, please use `gosseract.NewClient`")
}
if err = client.init(); err != nil {
return
}
boxArray := C.GetBoundingBoxes(client.api, C.int(lev... | go | func (client *Client) GetBoundingBoxes(level PageIteratorLevel) (out []BoundingBox, err error) {
if client.api == nil {
return out, fmt.Errorf("TessBaseAPI is not constructed, please use `gosseract.NewClient`")
}
if err = client.init(); err != nil {
return
}
boxArray := C.GetBoundingBoxes(client.api, C.int(lev... | [
"func",
"(",
"client",
"*",
"Client",
")",
"GetBoundingBoxes",
"(",
"level",
"PageIteratorLevel",
")",
"(",
"out",
"[",
"]",
"BoundingBox",
",",
"err",
"error",
")",
"{",
"if",
"client",
".",
"api",
"==",
"nil",
"{",
"return",
"out",
",",
"fmt",
".",
... | // GetBoundingBoxes returns bounding boxes for each matched word | [
"GetBoundingBoxes",
"returns",
"bounding",
"boxes",
"for",
"each",
"matched",
"word"
] | 02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4 | https://github.com/otiai10/gosseract/blob/02d1df59ab53ed08b5eb2f5be04751e9f7a8f0a4/client.go#L334-L357 | train |
libp2p/go-libp2p-kad-dht | query.go | Run | func (q *dhtQuery) Run(ctx context.Context, peers []peer.ID) (*dhtQueryResult, error) {
if len(peers) == 0 {
logger.Warning("Running query with no peers!")
return nil, kb.ErrLookupFailure
}
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()... | go | func (q *dhtQuery) Run(ctx context.Context, peers []peer.ID) (*dhtQueryResult, error) {
if len(peers) == 0 {
logger.Warning("Running query with no peers!")
return nil, kb.ErrLookupFailure
}
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()... | [
"func",
"(",
"q",
"*",
"dhtQuery",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"peers",
"[",
"]",
"peer",
".",
"ID",
")",
"(",
"*",
"dhtQueryResult",
",",
"error",
")",
"{",
"if",
"len",
"(",
"peers",
")",
"==",
"0",
"{",
"logger",
... | // Run runs the query at hand. pass in a list of peers to use first. | [
"Run",
"runs",
"the",
"query",
"at",
"hand",
".",
"pass",
"in",
"a",
"list",
"of",
"peers",
"to",
"use",
"first",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/query.go#L61-L78 | train |
libp2p/go-libp2p-kad-dht | dht_net.go | handleNewStream | func (dht *IpfsDHT) handleNewStream(s inet.Stream) {
defer s.Reset()
if dht.handleNewMessage(s) {
// Gracefully close the stream for writes.
s.Close()
}
} | go | func (dht *IpfsDHT) handleNewStream(s inet.Stream) {
defer s.Reset()
if dht.handleNewMessage(s) {
// Gracefully close the stream for writes.
s.Close()
}
} | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"handleNewStream",
"(",
"s",
"inet",
".",
"Stream",
")",
"{",
"defer",
"s",
".",
"Reset",
"(",
")",
"\n",
"if",
"dht",
".",
"handleNewMessage",
"(",
"s",
")",
"{",
"// Gracefully close the stream for writes.",
"s",
... | // handleNewStream implements the inet.StreamHandler | [
"handleNewStream",
"implements",
"the",
"inet",
".",
"StreamHandler"
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht_net.go#L50-L56 | train |
libp2p/go-libp2p-kad-dht | dht_net.go | sendRequest | func (dht *IpfsDHT) sendRequest(ctx context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error) {
ctx, _ = tag.New(ctx, metrics.UpsertMessageType(pmes))
ms, err := dht.messageSenderForPeer(ctx, p)
if err != nil {
stats.Record(ctx, metrics.SentRequestErrors.M(1))
return nil, err
}
start := time.Now()
... | go | func (dht *IpfsDHT) sendRequest(ctx context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error) {
ctx, _ = tag.New(ctx, metrics.UpsertMessageType(pmes))
ms, err := dht.messageSenderForPeer(ctx, p)
if err != nil {
stats.Record(ctx, metrics.SentRequestErrors.M(1))
return nil, err
}
start := time.Now()
... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"sendRequest",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"peer",
".",
"ID",
",",
"pmes",
"*",
"pb",
".",
"Message",
")",
"(",
"*",
"pb",
".",
"Message",
",",
"error",
")",
"{",
"ctx",
",",
"_",
"=... | // sendRequest sends out a request, but also makes sure to
// measure the RTT for latency measurements. | [
"sendRequest",
"sends",
"out",
"a",
"request",
"but",
"also",
"makes",
"sure",
"to",
"measure",
"the",
"RTT",
"for",
"latency",
"measurements",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht_net.go#L139-L170 | train |
libp2p/go-libp2p-kad-dht | dht_net.go | sendMessage | func (dht *IpfsDHT) sendMessage(ctx context.Context, p peer.ID, pmes *pb.Message) error {
ctx, _ = tag.New(ctx, metrics.UpsertMessageType(pmes))
ms, err := dht.messageSenderForPeer(ctx, p)
if err != nil {
stats.Record(ctx, metrics.SentMessageErrors.M(1))
return err
}
if err := ms.SendMessage(ctx, pmes); err ... | go | func (dht *IpfsDHT) sendMessage(ctx context.Context, p peer.ID, pmes *pb.Message) error {
ctx, _ = tag.New(ctx, metrics.UpsertMessageType(pmes))
ms, err := dht.messageSenderForPeer(ctx, p)
if err != nil {
stats.Record(ctx, metrics.SentMessageErrors.M(1))
return err
}
if err := ms.SendMessage(ctx, pmes); err ... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"sendMessage",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"peer",
".",
"ID",
",",
"pmes",
"*",
"pb",
".",
"Message",
")",
"error",
"{",
"ctx",
",",
"_",
"=",
"tag",
".",
"New",
"(",
"ctx",
",",
"me... | // sendMessage sends out a message | [
"sendMessage",
"sends",
"out",
"a",
"message"
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht_net.go#L173-L194 | train |
libp2p/go-libp2p-kad-dht | lookup.go | GetClosestPeers | func (dht *IpfsDHT) GetClosestPeers(ctx context.Context, key string) (<-chan peer.ID, error) {
e := logger.EventBegin(ctx, "getClosestPeers", loggableKey(key))
tablepeers := dht.routingTable.NearestPeers(kb.ConvertKey(key), AlphaValue)
if len(tablepeers) == 0 {
return nil, kb.ErrLookupFailure
}
out := make(chan... | go | func (dht *IpfsDHT) GetClosestPeers(ctx context.Context, key string) (<-chan peer.ID, error) {
e := logger.EventBegin(ctx, "getClosestPeers", loggableKey(key))
tablepeers := dht.routingTable.NearestPeers(kb.ConvertKey(key), AlphaValue)
if len(tablepeers) == 0 {
return nil, kb.ErrLookupFailure
}
out := make(chan... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"GetClosestPeers",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"(",
"<-",
"chan",
"peer",
".",
"ID",
",",
"error",
")",
"{",
"e",
":=",
"logger",
".",
"EventBegin",
"(",
"ctx",
",",
"\"... | // Kademlia 'node lookup' operation. Returns a channel of the K closest peers
// to the given key | [
"Kademlia",
"node",
"lookup",
"operation",
".",
"Returns",
"a",
"channel",
"of",
"the",
"K",
"closest",
"peers",
"to",
"the",
"given",
"key"
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/lookup.go#L56-L114 | train |
libp2p/go-libp2p-kad-dht | dht_bootstrap.go | Bootstrap | func (dht *IpfsDHT) Bootstrap(ctx context.Context) error {
return dht.BootstrapWithConfig(ctx, DefaultBootstrapConfig)
} | go | func (dht *IpfsDHT) Bootstrap(ctx context.Context) error {
return dht.BootstrapWithConfig(ctx, DefaultBootstrapConfig)
} | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"Bootstrap",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"dht",
".",
"BootstrapWithConfig",
"(",
"ctx",
",",
"DefaultBootstrapConfig",
")",
"\n",
"}"
] | // A method in the IpfsRouting interface. It calls BootstrapWithConfig with
// the default bootstrap config. | [
"A",
"method",
"in",
"the",
"IpfsRouting",
"interface",
".",
"It",
"calls",
"BootstrapWithConfig",
"with",
"the",
"default",
"bootstrap",
"config",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht_bootstrap.go#L71-L73 | train |
libp2p/go-libp2p-kad-dht | dht_bootstrap.go | BootstrapWithConfig | func (dht *IpfsDHT) BootstrapWithConfig(ctx context.Context, cfg BootstrapConfig) error {
// Because this method is not synchronous, we have to duplicate sanity
// checks on the config so that callers aren't oblivious.
if cfg.Queries <= 0 {
return fmt.Errorf("invalid number of queries: %d", cfg.Queries)
}
go fun... | go | func (dht *IpfsDHT) BootstrapWithConfig(ctx context.Context, cfg BootstrapConfig) error {
// Because this method is not synchronous, we have to duplicate sanity
// checks on the config so that callers aren't oblivious.
if cfg.Queries <= 0 {
return fmt.Errorf("invalid number of queries: %d", cfg.Queries)
}
go fun... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"BootstrapWithConfig",
"(",
"ctx",
"context",
".",
"Context",
",",
"cfg",
"BootstrapConfig",
")",
"error",
"{",
"// Because this method is not synchronous, we have to duplicate sanity",
"// checks on the config so that callers aren't obl... | // Runs cfg.Queries bootstrap queries every cfg.Period. | [
"Runs",
"cfg",
".",
"Queries",
"bootstrap",
"queries",
"every",
"cfg",
".",
"Period",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht_bootstrap.go#L76-L96 | train |
libp2p/go-libp2p-kad-dht | dht_bootstrap.go | BootstrapOnce | func (dht *IpfsDHT) BootstrapOnce(ctx context.Context, cfg BootstrapConfig) error {
if cfg.Queries <= 0 {
return fmt.Errorf("invalid number of queries: %d", cfg.Queries)
}
return dht.runBootstrap(ctx, cfg)
} | go | func (dht *IpfsDHT) BootstrapOnce(ctx context.Context, cfg BootstrapConfig) error {
if cfg.Queries <= 0 {
return fmt.Errorf("invalid number of queries: %d", cfg.Queries)
}
return dht.runBootstrap(ctx, cfg)
} | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"BootstrapOnce",
"(",
"ctx",
"context",
".",
"Context",
",",
"cfg",
"BootstrapConfig",
")",
"error",
"{",
"if",
"cfg",
".",
"Queries",
"<=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cfg... | // This is a synchronous bootstrap. cfg.Queries queries will run each with a
// timeout of cfg.Timeout. cfg.Period is not used. | [
"This",
"is",
"a",
"synchronous",
"bootstrap",
".",
"cfg",
".",
"Queries",
"queries",
"will",
"run",
"each",
"with",
"a",
"timeout",
"of",
"cfg",
".",
"Timeout",
".",
"cfg",
".",
"Period",
"is",
"not",
"used",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht_bootstrap.go#L100-L105 | train |
libp2p/go-libp2p-kad-dht | dht_bootstrap.go | walk | func (dht *IpfsDHT) walk(ctx context.Context, target peer.ID) (pstore.PeerInfo, error) {
// TODO: Extract the query action (traversal logic?) inside FindPeer,
// don't actually call through the FindPeer machinery, which can return
// things out of the peer store etc.
return dht.FindPeer(ctx, target)
} | go | func (dht *IpfsDHT) walk(ctx context.Context, target peer.ID) (pstore.PeerInfo, error) {
// TODO: Extract the query action (traversal logic?) inside FindPeer,
// don't actually call through the FindPeer machinery, which can return
// things out of the peer store etc.
return dht.FindPeer(ctx, target)
} | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"walk",
"(",
"ctx",
"context",
".",
"Context",
",",
"target",
"peer",
".",
"ID",
")",
"(",
"pstore",
".",
"PeerInfo",
",",
"error",
")",
"{",
"// TODO: Extract the query action (traversal logic?) inside FindPeer,",
"// do... | // Traverse the DHT toward the given ID. | [
"Traverse",
"the",
"DHT",
"toward",
"the",
"given",
"ID",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht_bootstrap.go#L115-L120 | train |
libp2p/go-libp2p-kad-dht | dht_bootstrap.go | randomWalk | func (dht *IpfsDHT) randomWalk(ctx context.Context) error {
id := newRandomPeerId()
p, err := dht.walk(ctx, id)
switch err {
case routing.ErrNotFound:
return nil
case nil:
// We found a peer from a randomly generated ID. This should be very
// unlikely.
logger.Warningf("random walk toward %s actually found... | go | func (dht *IpfsDHT) randomWalk(ctx context.Context) error {
id := newRandomPeerId()
p, err := dht.walk(ctx, id)
switch err {
case routing.ErrNotFound:
return nil
case nil:
// We found a peer from a randomly generated ID. This should be very
// unlikely.
logger.Warningf("random walk toward %s actually found... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"randomWalk",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"id",
":=",
"newRandomPeerId",
"(",
")",
"\n",
"p",
",",
"err",
":=",
"dht",
".",
"walk",
"(",
"ctx",
",",
"id",
")",
"\n",
"switch",
... | // Traverse the DHT toward a random ID. | [
"Traverse",
"the",
"DHT",
"toward",
"a",
"random",
"ID",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht_bootstrap.go#L123-L137 | train |
libp2p/go-libp2p-kad-dht | dht_bootstrap.go | selfWalk | func (dht *IpfsDHT) selfWalk(ctx context.Context) error {
_, err := dht.walk(ctx, dht.self)
if err == routing.ErrNotFound {
return nil
}
return err
} | go | func (dht *IpfsDHT) selfWalk(ctx context.Context) error {
_, err := dht.walk(ctx, dht.self)
if err == routing.ErrNotFound {
return nil
}
return err
} | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"selfWalk",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"_",
",",
"err",
":=",
"dht",
".",
"walk",
"(",
"ctx",
",",
"dht",
".",
"self",
")",
"\n",
"if",
"err",
"==",
"routing",
".",
"ErrNotFo... | // Traverse the DHT toward the self ID | [
"Traverse",
"the",
"DHT",
"toward",
"the",
"self",
"ID"
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht_bootstrap.go#L140-L146 | train |
libp2p/go-libp2p-kad-dht | dht_bootstrap.go | runBootstrap | func (dht *IpfsDHT) runBootstrap(ctx context.Context, cfg BootstrapConfig) error {
doQuery := func(n int, target string, f func(context.Context) error) error {
logger.Infof("starting bootstrap query (%d/%d) to %s (routing table size was %d)",
n, cfg.Queries, target, dht.routingTable.Size())
defer func() {
lo... | go | func (dht *IpfsDHT) runBootstrap(ctx context.Context, cfg BootstrapConfig) error {
doQuery := func(n int, target string, f func(context.Context) error) error {
logger.Infof("starting bootstrap query (%d/%d) to %s (routing table size was %d)",
n, cfg.Queries, target, dht.routingTable.Size())
defer func() {
lo... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"runBootstrap",
"(",
"ctx",
"context",
".",
"Context",
",",
"cfg",
"BootstrapConfig",
")",
"error",
"{",
"doQuery",
":=",
"func",
"(",
"n",
"int",
",",
"target",
"string",
",",
"f",
"func",
"(",
"context",
".",
... | // runBootstrap builds up list of peers by requesting random peer IDs | [
"runBootstrap",
"builds",
"up",
"list",
"of",
"peers",
"by",
"requesting",
"random",
"peer",
"IDs"
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht_bootstrap.go#L149-L176 | train |
libp2p/go-libp2p-kad-dht | providers/providers.go | AddProvider | func (pm *ProviderManager) AddProvider(ctx context.Context, k cid.Cid, val peer.ID) {
prov := &addProv{
k: k,
val: val,
}
select {
case pm.newprovs <- prov:
case <-ctx.Done():
}
} | go | func (pm *ProviderManager) AddProvider(ctx context.Context, k cid.Cid, val peer.ID) {
prov := &addProv{
k: k,
val: val,
}
select {
case pm.newprovs <- prov:
case <-ctx.Done():
}
} | [
"func",
"(",
"pm",
"*",
"ProviderManager",
")",
"AddProvider",
"(",
"ctx",
"context",
".",
"Context",
",",
"k",
"cid",
".",
"Cid",
",",
"val",
"peer",
".",
"ID",
")",
"{",
"prov",
":=",
"&",
"addProv",
"{",
"k",
":",
"k",
",",
"val",
":",
"val",
... | // AddProvider adds a provider. | [
"AddProvider",
"adds",
"a",
"provider",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/providers/providers.go#L302-L311 | train |
libp2p/go-libp2p-kad-dht | providers/providers.go | GetProviders | func (pm *ProviderManager) GetProviders(ctx context.Context, k cid.Cid) []peer.ID {
gp := &getProv{
k: k,
resp: make(chan []peer.ID, 1), // buffered to prevent sender from blocking
}
select {
case <-ctx.Done():
return nil
case pm.getprovs <- gp:
}
select {
case <-ctx.Done():
return nil
case peers :=... | go | func (pm *ProviderManager) GetProviders(ctx context.Context, k cid.Cid) []peer.ID {
gp := &getProv{
k: k,
resp: make(chan []peer.ID, 1), // buffered to prevent sender from blocking
}
select {
case <-ctx.Done():
return nil
case pm.getprovs <- gp:
}
select {
case <-ctx.Done():
return nil
case peers :=... | [
"func",
"(",
"pm",
"*",
"ProviderManager",
")",
"GetProviders",
"(",
"ctx",
"context",
".",
"Context",
",",
"k",
"cid",
".",
"Cid",
")",
"[",
"]",
"peer",
".",
"ID",
"{",
"gp",
":=",
"&",
"getProv",
"{",
"k",
":",
"k",
",",
"resp",
":",
"make",
... | // GetProviders returns the set of providers for the given key.
// This method _does not_ copy the set. Do not modify it. | [
"GetProviders",
"returns",
"the",
"set",
"of",
"providers",
"for",
"the",
"given",
"key",
".",
"This",
"method",
"_does",
"not_",
"copy",
"the",
"set",
".",
"Do",
"not",
"modify",
"it",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/providers/providers.go#L315-L331 | train |
libp2p/go-libp2p-kad-dht | dht.go | New | func New(ctx context.Context, h host.Host, options ...opts.Option) (*IpfsDHT, error) {
var cfg opts.Options
if err := cfg.Apply(append([]opts.Option{opts.Defaults}, options...)...); err != nil {
return nil, err
}
dht := makeDHT(ctx, h, cfg.Datastore, cfg.Protocols)
// register for network notifs.
dht.host.Netw... | go | func New(ctx context.Context, h host.Host, options ...opts.Option) (*IpfsDHT, error) {
var cfg opts.Options
if err := cfg.Apply(append([]opts.Option{opts.Defaults}, options...)...); err != nil {
return nil, err
}
dht := makeDHT(ctx, h, cfg.Datastore, cfg.Protocols)
// register for network notifs.
dht.host.Netw... | [
"func",
"New",
"(",
"ctx",
"context",
".",
"Context",
",",
"h",
"host",
".",
"Host",
",",
"options",
"...",
"opts",
".",
"Option",
")",
"(",
"*",
"IpfsDHT",
",",
"error",
")",
"{",
"var",
"cfg",
"opts",
".",
"Options",
"\n",
"if",
"err",
":=",
"c... | // New creates a new DHT with the specified host and options. | [
"New",
"creates",
"a",
"new",
"DHT",
"with",
"the",
"specified",
"host",
"and",
"options",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht.go#L81-L106 | train |
libp2p/go-libp2p-kad-dht | dht.go | NewDHT | func NewDHT(ctx context.Context, h host.Host, dstore ds.Batching) *IpfsDHT {
dht, err := New(ctx, h, opts.Datastore(dstore))
if err != nil {
panic(err)
}
return dht
} | go | func NewDHT(ctx context.Context, h host.Host, dstore ds.Batching) *IpfsDHT {
dht, err := New(ctx, h, opts.Datastore(dstore))
if err != nil {
panic(err)
}
return dht
} | [
"func",
"NewDHT",
"(",
"ctx",
"context",
".",
"Context",
",",
"h",
"host",
".",
"Host",
",",
"dstore",
"ds",
".",
"Batching",
")",
"*",
"IpfsDHT",
"{",
"dht",
",",
"err",
":=",
"New",
"(",
"ctx",
",",
"h",
",",
"opts",
".",
"Datastore",
"(",
"dst... | // NewDHT creates a new DHT object with the given peer as the 'local' host.
// IpfsDHT's initialized with this function will respond to DHT requests,
// whereas IpfsDHT's initialized with NewDHTClient will not. | [
"NewDHT",
"creates",
"a",
"new",
"DHT",
"object",
"with",
"the",
"given",
"peer",
"as",
"the",
"local",
"host",
".",
"IpfsDHT",
"s",
"initialized",
"with",
"this",
"function",
"will",
"respond",
"to",
"DHT",
"requests",
"whereas",
"IpfsDHT",
"s",
"initialize... | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht.go#L111-L117 | train |
libp2p/go-libp2p-kad-dht | dht.go | getValueSingle | func (dht *IpfsDHT) getValueSingle(ctx context.Context, p peer.ID, key string) (*pb.Message, error) {
meta := logging.LoggableMap{
"key": key,
"peer": p,
}
eip := logger.EventBegin(ctx, "getValueSingle", meta)
defer eip.Done()
pmes := pb.NewMessage(pb.Message_GET_VALUE, []byte(key), 0)
resp, err := dht.sen... | go | func (dht *IpfsDHT) getValueSingle(ctx context.Context, p peer.ID, key string) (*pb.Message, error) {
meta := logging.LoggableMap{
"key": key,
"peer": p,
}
eip := logger.EventBegin(ctx, "getValueSingle", meta)
defer eip.Done()
pmes := pb.NewMessage(pb.Message_GET_VALUE, []byte(key), 0)
resp, err := dht.sen... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"getValueSingle",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"peer",
".",
"ID",
",",
"key",
"string",
")",
"(",
"*",
"pb",
".",
"Message",
",",
"error",
")",
"{",
"meta",
":=",
"logging",
".",
"Loggabl... | // getValueSingle simply performs the get value RPC with the given parameters | [
"getValueSingle",
"simply",
"performs",
"the",
"get",
"value",
"RPC",
"with",
"the",
"given",
"parameters"
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht.go#L220-L241 | train |
libp2p/go-libp2p-kad-dht | dht.go | getLocal | func (dht *IpfsDHT) getLocal(key string) (*recpb.Record, error) {
logger.Debugf("getLocal %s", key)
rec, err := dht.getRecordFromDatastore(mkDsKey(key))
if err != nil {
logger.Warningf("getLocal: %s", err)
return nil, err
}
// Double check the key. Can't hurt.
if rec != nil && string(rec.GetKey()) != key {
... | go | func (dht *IpfsDHT) getLocal(key string) (*recpb.Record, error) {
logger.Debugf("getLocal %s", key)
rec, err := dht.getRecordFromDatastore(mkDsKey(key))
if err != nil {
logger.Warningf("getLocal: %s", err)
return nil, err
}
// Double check the key. Can't hurt.
if rec != nil && string(rec.GetKey()) != key {
... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"getLocal",
"(",
"key",
"string",
")",
"(",
"*",
"recpb",
".",
"Record",
",",
"error",
")",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"rec",
",",
"err",
":=",
"dht",
".",
"get... | // getLocal attempts to retrieve the value from the datastore | [
"getLocal",
"attempts",
"to",
"retrieve",
"the",
"value",
"from",
"the",
"datastore"
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht.go#L244-L259 | train |
libp2p/go-libp2p-kad-dht | dht.go | putLocal | func (dht *IpfsDHT) putLocal(key string, rec *recpb.Record) error {
logger.Debugf("putLocal: %v %v", key, rec)
data, err := proto.Marshal(rec)
if err != nil {
logger.Warningf("putLocal: %s", err)
return err
}
return dht.datastore.Put(mkDsKey(key), data)
} | go | func (dht *IpfsDHT) putLocal(key string, rec *recpb.Record) error {
logger.Debugf("putLocal: %v %v", key, rec)
data, err := proto.Marshal(rec)
if err != nil {
logger.Warningf("putLocal: %s", err)
return err
}
return dht.datastore.Put(mkDsKey(key), data)
} | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"putLocal",
"(",
"key",
"string",
",",
"rec",
"*",
"recpb",
".",
"Record",
")",
"error",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"key",
",",
"rec",
")",
"\n",
"data",
",",
"err",
":=",
"proto",... | // putLocal stores the key value pair in the datastore | [
"putLocal",
"stores",
"the",
"key",
"value",
"pair",
"in",
"the",
"datastore"
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht.go#L262-L271 | train |
libp2p/go-libp2p-kad-dht | dht.go | Update | func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
logger.Event(ctx, "updatePeer", p)
dht.routingTable.Update(p)
} | go | func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
logger.Event(ctx, "updatePeer", p)
dht.routingTable.Update(p)
} | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"Update",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"peer",
".",
"ID",
")",
"{",
"logger",
".",
"Event",
"(",
"ctx",
",",
"\"",
"\"",
",",
"p",
")",
"\n",
"dht",
".",
"routingTable",
".",
"Update",
... | // Update signals the routingTable to Update its last-seen status
// on the given peer. | [
"Update",
"signals",
"the",
"routingTable",
"to",
"Update",
"its",
"last",
"-",
"seen",
"status",
"on",
"the",
"given",
"peer",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht.go#L275-L278 | train |
libp2p/go-libp2p-kad-dht | dht.go | FindLocal | func (dht *IpfsDHT) FindLocal(id peer.ID) pstore.PeerInfo {
switch dht.host.Network().Connectedness(id) {
case inet.Connected, inet.CanConnect:
return dht.peerstore.PeerInfo(id)
default:
return pstore.PeerInfo{}
}
} | go | func (dht *IpfsDHT) FindLocal(id peer.ID) pstore.PeerInfo {
switch dht.host.Network().Connectedness(id) {
case inet.Connected, inet.CanConnect:
return dht.peerstore.PeerInfo(id)
default:
return pstore.PeerInfo{}
}
} | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"FindLocal",
"(",
"id",
"peer",
".",
"ID",
")",
"pstore",
".",
"PeerInfo",
"{",
"switch",
"dht",
".",
"host",
".",
"Network",
"(",
")",
".",
"Connectedness",
"(",
"id",
")",
"{",
"case",
"inet",
".",
"Connec... | // FindLocal looks for a peer with a given ID connected to this dht and returns the peer and the table it was found in. | [
"FindLocal",
"looks",
"for",
"a",
"peer",
"with",
"a",
"given",
"ID",
"connected",
"to",
"this",
"dht",
"and",
"returns",
"the",
"peer",
"and",
"the",
"table",
"it",
"was",
"found",
"in",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht.go#L281-L288 | train |
libp2p/go-libp2p-kad-dht | dht.go | findPeerSingle | func (dht *IpfsDHT) findPeerSingle(ctx context.Context, p peer.ID, id peer.ID) (*pb.Message, error) {
eip := logger.EventBegin(ctx, "findPeerSingle",
logging.LoggableMap{
"peer": p,
"target": id,
})
defer eip.Done()
pmes := pb.NewMessage(pb.Message_FIND_NODE, []byte(id), 0)
resp, err := dht.sendRequest... | go | func (dht *IpfsDHT) findPeerSingle(ctx context.Context, p peer.ID, id peer.ID) (*pb.Message, error) {
eip := logger.EventBegin(ctx, "findPeerSingle",
logging.LoggableMap{
"peer": p,
"target": id,
})
defer eip.Done()
pmes := pb.NewMessage(pb.Message_FIND_NODE, []byte(id), 0)
resp, err := dht.sendRequest... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"findPeerSingle",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"peer",
".",
"ID",
",",
"id",
"peer",
".",
"ID",
")",
"(",
"*",
"pb",
".",
"Message",
",",
"error",
")",
"{",
"eip",
":=",
"logger",
".",
... | // findPeerSingle asks peer 'p' if they know where the peer with id 'id' is | [
"findPeerSingle",
"asks",
"peer",
"p",
"if",
"they",
"know",
"where",
"the",
"peer",
"with",
"id",
"id",
"is"
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht.go#L291-L311 | train |
libp2p/go-libp2p-kad-dht | dht.go | nearestPeersToQuery | func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
closer := dht.routingTable.NearestPeers(kb.ConvertKey(string(pmes.GetKey())), count)
return closer
} | go | func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
closer := dht.routingTable.NearestPeers(kb.ConvertKey(string(pmes.GetKey())), count)
return closer
} | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"nearestPeersToQuery",
"(",
"pmes",
"*",
"pb",
".",
"Message",
",",
"count",
"int",
")",
"[",
"]",
"peer",
".",
"ID",
"{",
"closer",
":=",
"dht",
".",
"routingTable",
".",
"NearestPeers",
"(",
"kb",
".",
"Conv... | // nearestPeersToQuery returns the routing tables closest peers. | [
"nearestPeersToQuery",
"returns",
"the",
"routing",
"tables",
"closest",
"peers",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht.go#L332-L335 | train |
libp2p/go-libp2p-kad-dht | dht.go | betterPeersToQuery | func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
closer := dht.nearestPeersToQuery(pmes, count)
// no node? nil
if closer == nil {
logger.Warning("betterPeersToQuery: no closer peers to send:", p)
return nil
}
filtered := make([]peer.ID, 0, len(closer))
for _, clp :... | go | func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
closer := dht.nearestPeersToQuery(pmes, count)
// no node? nil
if closer == nil {
logger.Warning("betterPeersToQuery: no closer peers to send:", p)
return nil
}
filtered := make([]peer.ID, 0, len(closer))
for _, clp :... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"betterPeersToQuery",
"(",
"pmes",
"*",
"pb",
".",
"Message",
",",
"p",
"peer",
".",
"ID",
",",
"count",
"int",
")",
"[",
"]",
"peer",
".",
"ID",
"{",
"closer",
":=",
"dht",
".",
"nearestPeersToQuery",
"(",
... | // betterPeersToQuery returns nearestPeersToQuery, but if and only if closer than self. | [
"betterPeersToQuery",
"returns",
"nearestPeersToQuery",
"but",
"if",
"and",
"only",
"if",
"closer",
"than",
"self",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht.go#L338-L365 | train |
libp2p/go-libp2p-kad-dht | dht.go | newContextWithLocalTags | func (dht *IpfsDHT) newContextWithLocalTags(ctx context.Context, extraTags ...tag.Mutator) context.Context {
extraTags = append(
extraTags,
tag.Upsert(metrics.KeyPeerID, dht.self.Pretty()),
tag.Upsert(metrics.KeyInstanceID, fmt.Sprintf("%p", dht)),
)
ctx, _ = tag.New(
ctx,
extraTags...,
) // ignoring erro... | go | func (dht *IpfsDHT) newContextWithLocalTags(ctx context.Context, extraTags ...tag.Mutator) context.Context {
extraTags = append(
extraTags,
tag.Upsert(metrics.KeyPeerID, dht.self.Pretty()),
tag.Upsert(metrics.KeyInstanceID, fmt.Sprintf("%p", dht)),
)
ctx, _ = tag.New(
ctx,
extraTags...,
) // ignoring erro... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"newContextWithLocalTags",
"(",
"ctx",
"context",
".",
"Context",
",",
"extraTags",
"...",
"tag",
".",
"Mutator",
")",
"context",
".",
"Context",
"{",
"extraTags",
"=",
"append",
"(",
"extraTags",
",",
"tag",
".",
... | // newContextWithLocalTags returns a new context.Context with the InstanceID and
// PeerID keys populated. It will also take any extra tags that need adding to
// the context as tag.Mutators. | [
"newContextWithLocalTags",
"returns",
"a",
"new",
"context",
".",
"Context",
"with",
"the",
"InstanceID",
"and",
"PeerID",
"keys",
"populated",
".",
"It",
"will",
"also",
"take",
"any",
"extra",
"tags",
"that",
"need",
"adding",
"to",
"the",
"context",
"as",
... | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dht.go#L427-L438 | train |
libp2p/go-libp2p-kad-dht | dial_queue.go | dqDefaultConfig | func dqDefaultConfig() dqConfig {
return dqConfig{
minParallelism: DefaultDialQueueMinParallelism,
maxParallelism: DefaultDialQueueMaxParallelism,
scalingFactor: DefaultDialQueueScalingFactor,
maxIdle: DefaultDialQueueMaxIdle,
mutePeriod: DefaultDialQueueScalingMutePeriod,
}
} | go | func dqDefaultConfig() dqConfig {
return dqConfig{
minParallelism: DefaultDialQueueMinParallelism,
maxParallelism: DefaultDialQueueMaxParallelism,
scalingFactor: DefaultDialQueueScalingFactor,
maxIdle: DefaultDialQueueMaxIdle,
mutePeriod: DefaultDialQueueScalingMutePeriod,
}
} | [
"func",
"dqDefaultConfig",
"(",
")",
"dqConfig",
"{",
"return",
"dqConfig",
"{",
"minParallelism",
":",
"DefaultDialQueueMinParallelism",
",",
"maxParallelism",
":",
"DefaultDialQueueMaxParallelism",
",",
"scalingFactor",
":",
"DefaultDialQueueScalingFactor",
",",
"maxIdle"... | // dqDefaultConfig returns the default configuration for dial queues. See const documentation to learn the default values. | [
"dqDefaultConfig",
"returns",
"the",
"default",
"configuration",
"for",
"dial",
"queues",
".",
"See",
"const",
"documentation",
"to",
"learn",
"the",
"default",
"values",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/dial_queue.go#L68-L76 | train |
libp2p/go-libp2p-kad-dht | routing.go | GetValue | func (dht *IpfsDHT) GetValue(ctx context.Context, key string, opts ...ropts.Option) (_ []byte, err error) {
eip := logger.EventBegin(ctx, "GetValue")
defer func() {
eip.Append(loggableKey(key))
if err != nil {
eip.SetError(err)
}
eip.Done()
}()
// apply defaultQuorum if relevant
var cfg ropts.Options
... | go | func (dht *IpfsDHT) GetValue(ctx context.Context, key string, opts ...ropts.Option) (_ []byte, err error) {
eip := logger.EventBegin(ctx, "GetValue")
defer func() {
eip.Append(loggableKey(key))
if err != nil {
eip.SetError(err)
}
eip.Done()
}()
// apply defaultQuorum if relevant
var cfg ropts.Options
... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"GetValue",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
",",
"opts",
"...",
"ropts",
".",
"Option",
")",
"(",
"_",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"eip",
":=",
"logger",
"... | // GetValue searches for the value corresponding to given Key. | [
"GetValue",
"searches",
"for",
"the",
"value",
"corresponding",
"to",
"given",
"Key",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/routing.go#L113-L149 | train |
libp2p/go-libp2p-kad-dht | routing.go | GetValues | func (dht *IpfsDHT) GetValues(ctx context.Context, key string, nvals int) (_ []RecvdVal, err error) {
eip := logger.EventBegin(ctx, "GetValues")
eip.Append(loggableKey(key))
defer eip.Done()
valCh, err := dht.getValues(ctx, key, nvals)
if err != nil {
eip.SetError(err)
return nil, err
}
out := make([]Recv... | go | func (dht *IpfsDHT) GetValues(ctx context.Context, key string, nvals int) (_ []RecvdVal, err error) {
eip := logger.EventBegin(ctx, "GetValues")
eip.Append(loggableKey(key))
defer eip.Done()
valCh, err := dht.getValues(ctx, key, nvals)
if err != nil {
eip.SetError(err)
return nil, err
}
out := make([]Recv... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"GetValues",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
",",
"nvals",
"int",
")",
"(",
"_",
"[",
"]",
"RecvdVal",
",",
"err",
"error",
")",
"{",
"eip",
":=",
"logger",
".",
"EventBegin",
"(... | // GetValues gets nvals values corresponding to the given key. | [
"GetValues",
"gets",
"nvals",
"values",
"corresponding",
"to",
"the",
"given",
"key",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/routing.go#L253-L271 | train |
libp2p/go-libp2p-kad-dht | routing.go | Provide | func (dht *IpfsDHT) Provide(ctx context.Context, key cid.Cid, brdcst bool) (err error) {
eip := logger.EventBegin(ctx, "Provide", key, logging.LoggableMap{"broadcast": brdcst})
defer func() {
if err != nil {
eip.SetError(err)
}
eip.Done()
}()
// add self locally
dht.providers.AddProvider(ctx, key, dht.se... | go | func (dht *IpfsDHT) Provide(ctx context.Context, key cid.Cid, brdcst bool) (err error) {
eip := logger.EventBegin(ctx, "Provide", key, logging.LoggableMap{"broadcast": brdcst})
defer func() {
if err != nil {
eip.SetError(err)
}
eip.Done()
}()
// add self locally
dht.providers.AddProvider(ctx, key, dht.se... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"Provide",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"cid",
".",
"Cid",
",",
"brdcst",
"bool",
")",
"(",
"err",
"error",
")",
"{",
"eip",
":=",
"logger",
".",
"EventBegin",
"(",
"ctx",
",",
"\"",
... | // Provider abstraction for indirect stores.
// Some DHTs store values directly, while an indirect store stores pointers to
// locations of the value, similarly to Coral and Mainline DHT.
// Provide makes this node announce that it can provide a value for the given key | [
"Provider",
"abstraction",
"for",
"indirect",
"stores",
".",
"Some",
"DHTs",
"store",
"values",
"directly",
"while",
"an",
"indirect",
"store",
"stores",
"pointers",
"to",
"locations",
"of",
"the",
"value",
"similarly",
"to",
"Coral",
"and",
"Mainline",
"DHT",
... | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/routing.go#L398-L437 | train |
libp2p/go-libp2p-kad-dht | routing.go | FindProviders | func (dht *IpfsDHT) FindProviders(ctx context.Context, c cid.Cid) ([]pstore.PeerInfo, error) {
var providers []pstore.PeerInfo
for p := range dht.FindProvidersAsync(ctx, c, KValue) {
providers = append(providers, p)
}
return providers, nil
} | go | func (dht *IpfsDHT) FindProviders(ctx context.Context, c cid.Cid) ([]pstore.PeerInfo, error) {
var providers []pstore.PeerInfo
for p := range dht.FindProvidersAsync(ctx, c, KValue) {
providers = append(providers, p)
}
return providers, nil
} | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"FindProviders",
"(",
"ctx",
"context",
".",
"Context",
",",
"c",
"cid",
".",
"Cid",
")",
"(",
"[",
"]",
"pstore",
".",
"PeerInfo",
",",
"error",
")",
"{",
"var",
"providers",
"[",
"]",
"pstore",
".",
"PeerI... | // FindProviders searches until the context expires. | [
"FindProviders",
"searches",
"until",
"the",
"context",
"expires",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/routing.go#L456-L462 | train |
libp2p/go-libp2p-kad-dht | routing.go | FindProvidersAsync | func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key cid.Cid, count int) <-chan pstore.PeerInfo {
logger.Event(ctx, "findProviders", key)
peerOut := make(chan pstore.PeerInfo, count)
go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
return peerOut
} | go | func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key cid.Cid, count int) <-chan pstore.PeerInfo {
logger.Event(ctx, "findProviders", key)
peerOut := make(chan pstore.PeerInfo, count)
go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
return peerOut
} | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"FindProvidersAsync",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"cid",
".",
"Cid",
",",
"count",
"int",
")",
"<-",
"chan",
"pstore",
".",
"PeerInfo",
"{",
"logger",
".",
"Event",
"(",
"ctx",
",",
"\""... | // FindProvidersAsync is the same thing as FindProviders, but returns a channel.
// Peers will be returned on the channel as soon as they are found, even before
// the search query completes. | [
"FindProvidersAsync",
"is",
"the",
"same",
"thing",
"as",
"FindProviders",
"but",
"returns",
"a",
"channel",
".",
"Peers",
"will",
"be",
"returned",
"on",
"the",
"channel",
"as",
"soon",
"as",
"they",
"are",
"found",
"even",
"before",
"the",
"search",
"query... | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/routing.go#L467-L472 | train |
libp2p/go-libp2p-kad-dht | routing.go | FindPeer | func (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (_ pstore.PeerInfo, err error) {
eip := logger.EventBegin(ctx, "FindPeer", id)
defer func() {
if err != nil {
eip.SetError(err)
}
eip.Done()
}()
// Check if were already connected to them
if pi := dht.FindLocal(id); pi.ID != "" {
return pi, ... | go | func (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (_ pstore.PeerInfo, err error) {
eip := logger.EventBegin(ctx, "FindPeer", id)
defer func() {
if err != nil {
eip.SetError(err)
}
eip.Done()
}()
// Check if were already connected to them
if pi := dht.FindLocal(id); pi.ID != "" {
return pi, ... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"FindPeer",
"(",
"ctx",
"context",
".",
"Context",
",",
"id",
"peer",
".",
"ID",
")",
"(",
"_",
"pstore",
".",
"PeerInfo",
",",
"err",
"error",
")",
"{",
"eip",
":=",
"logger",
".",
"EventBegin",
"(",
"ctx",... | // FindPeer searches for a peer with given ID. | [
"FindPeer",
"searches",
"for",
"a",
"peer",
"with",
"given",
"ID",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/routing.go#L578-L652 | train |
libp2p/go-libp2p-kad-dht | routing.go | FindPeersConnectedToPeer | func (dht *IpfsDHT) FindPeersConnectedToPeer(ctx context.Context, id peer.ID) (<-chan *pstore.PeerInfo, error) {
peerchan := make(chan *pstore.PeerInfo, asyncQueryBuffer)
peersSeen := make(map[peer.ID]struct{})
var peersSeenMx sync.Mutex
peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
if... | go | func (dht *IpfsDHT) FindPeersConnectedToPeer(ctx context.Context, id peer.ID) (<-chan *pstore.PeerInfo, error) {
peerchan := make(chan *pstore.PeerInfo, asyncQueryBuffer)
peersSeen := make(map[peer.ID]struct{})
var peersSeenMx sync.Mutex
peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
if... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"FindPeersConnectedToPeer",
"(",
"ctx",
"context",
".",
"Context",
",",
"id",
"peer",
".",
"ID",
")",
"(",
"<-",
"chan",
"*",
"pstore",
".",
"PeerInfo",
",",
"error",
")",
"{",
"peerchan",
":=",
"make",
"(",
"... | // FindPeersConnectedToPeer searches for peers directly connected to a given peer. | [
"FindPeersConnectedToPeer",
"searches",
"for",
"peers",
"directly",
"connected",
"to",
"a",
"given",
"peer",
"."
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/routing.go#L655-L719 | train |
libp2p/go-libp2p-kad-dht | handlers.go | handlePutValue | func (dht *IpfsDHT) handlePutValue(ctx context.Context, p peer.ID, pmes *pb.Message) (_ *pb.Message, err error) {
ctx = logger.Start(ctx, "handlePutValue")
logger.SetTag(ctx, "peer", p)
defer func() { logger.FinishWithErr(ctx, err) }()
rec := pmes.GetRecord()
if rec == nil {
logger.Infof("Got nil record from: %... | go | func (dht *IpfsDHT) handlePutValue(ctx context.Context, p peer.ID, pmes *pb.Message) (_ *pb.Message, err error) {
ctx = logger.Start(ctx, "handlePutValue")
logger.SetTag(ctx, "peer", p)
defer func() { logger.FinishWithErr(ctx, err) }()
rec := pmes.GetRecord()
if rec == nil {
logger.Infof("Got nil record from: %... | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"handlePutValue",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"peer",
".",
"ID",
",",
"pmes",
"*",
"pb",
".",
"Message",
")",
"(",
"_",
"*",
"pb",
".",
"Message",
",",
"err",
"error",
")",
"{",
"ctx",... | // Store a value in this peer local storage | [
"Store",
"a",
"value",
"in",
"this",
"peer",
"local",
"storage"
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/handlers.go#L148-L205 | train |
libp2p/go-libp2p-kad-dht | opts/options.go | Apply | func (o *Options) Apply(opts ...Option) error {
for i, opt := range opts {
if err := opt(o); err != nil {
return fmt.Errorf("dht option %d failed: %s", i, err)
}
}
return nil
} | go | func (o *Options) Apply(opts ...Option) error {
for i, opt := range opts {
if err := opt(o); err != nil {
return fmt.Errorf("dht option %d failed: %s", i, err)
}
}
return nil
} | [
"func",
"(",
"o",
"*",
"Options",
")",
"Apply",
"(",
"opts",
"...",
"Option",
")",
"error",
"{",
"for",
"i",
",",
"opt",
":=",
"range",
"opts",
"{",
"if",
"err",
":=",
"opt",
"(",
"o",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
... | // Apply applies the given options to this Option | [
"Apply",
"applies",
"the",
"given",
"options",
"to",
"this",
"Option"
] | fb62272e7ee5e16c07f88c30cb76e0f69e36ab69 | https://github.com/libp2p/go-libp2p-kad-dht/blob/fb62272e7ee5e16c07f88c30cb76e0f69e36ab69/opts/options.go#L30-L37 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.