repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
btcsuite/btcwallet | chain/bitcoind_client.go | onRescanProgress | func (c *BitcoindClient) onRescanProgress(hash *chainhash.Hash, height int32,
timestamp time.Time) {
select {
case c.notificationQueue.ChanIn() <- &RescanProgress{
Hash: hash,
Height: height,
Time: timestamp,
}:
case <-c.quit:
}
} | go | func (c *BitcoindClient) onRescanProgress(hash *chainhash.Hash, height int32,
timestamp time.Time) {
select {
case c.notificationQueue.ChanIn() <- &RescanProgress{
Hash: hash,
Height: height,
Time: timestamp,
}:
case <-c.quit:
}
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"onRescanProgress",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
",",
"height",
"int32",
",",
"timestamp",
"time",
".",
"Time",
")",
"{",
"select",
"{",
"case",
"c",
".",
"notificationQueue",
".",
"ChanIn",
"(... | // onRescanProgress is a callback that's executed whenever a rescan is in
// progress. This will queue a RescanProgress notification to the caller with
// the current rescan progress details. | [
"onRescanProgress",
"is",
"a",
"callback",
"that",
"s",
"executed",
"whenever",
"a",
"rescan",
"is",
"in",
"progress",
".",
"This",
"will",
"queue",
"a",
"RescanProgress",
"notification",
"to",
"the",
"caller",
"with",
"the",
"current",
"rescan",
"progress",
"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L711-L722 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | onRescanFinished | func (c *BitcoindClient) onRescanFinished(hash *chainhash.Hash, height int32,
timestamp time.Time) {
log.Infof("Rescan finished at %d (%s)", height, hash)
select {
case c.notificationQueue.ChanIn() <- &RescanFinished{
Hash: hash,
Height: height,
Time: timestamp,
}:
case <-c.quit:
}
} | go | func (c *BitcoindClient) onRescanFinished(hash *chainhash.Hash, height int32,
timestamp time.Time) {
log.Infof("Rescan finished at %d (%s)", height, hash)
select {
case c.notificationQueue.ChanIn() <- &RescanFinished{
Hash: hash,
Height: height,
Time: timestamp,
}:
case <-c.quit:
}
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"onRescanFinished",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
",",
"height",
"int32",
",",
"timestamp",
"time",
".",
"Time",
")",
"{",
"log",
".",
"Infof",
"(",
"\"Rescan finished at %d (%s)\"",
",",
"height",
... | // onRescanFinished is a callback that's executed whenever a rescan has
// finished. This will queue a RescanFinished notification to the caller with
// the details of the last block in the range of the rescan. | [
"onRescanFinished",
"is",
"a",
"callback",
"that",
"s",
"executed",
"whenever",
"a",
"rescan",
"has",
"finished",
".",
"This",
"will",
"queue",
"a",
"RescanFinished",
"notification",
"to",
"the",
"caller",
"with",
"the",
"details",
"of",
"the",
"last",
"block"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L727-L740 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | reorg | func (c *BitcoindClient) reorg(currentBlock waddrmgr.BlockStamp,
reorgBlock *wire.MsgBlock) error {
log.Debugf("Possible reorg at block %s", reorgBlock.BlockHash())
// Retrieve the best known height based on the block which caused the
// reorg. This way, we can preserve the chain of blocks we need to
// retrieve.
bestHash := reorgBlock.BlockHash()
bestHeight, err := c.GetBlockHeight(&bestHash)
if err != nil {
return err
}
if bestHeight < currentBlock.Height {
log.Debug("Detected multiple reorgs")
return nil
}
// We'll now keep track of all the blocks known to the *chain*, starting
// from the best block known to us until the best block in the chain.
// This will let us fast-forward despite any future reorgs.
blocksToNotify := list.New()
blocksToNotify.PushFront(reorgBlock)
previousBlock := reorgBlock.Header.PrevBlock
for i := bestHeight - 1; i >= currentBlock.Height; i-- {
block, err := c.GetBlock(&previousBlock)
if err != nil {
return err
}
blocksToNotify.PushFront(block)
previousBlock = block.Header.PrevBlock
}
// Rewind back to the last common ancestor block using the previous
// block hash from each header to avoid any race conditions. If we
// encounter more reorgs, they'll be queued and we'll repeat the cycle.
//
// We'll start by retrieving the header to the best block known to us.
currentHeader, err := c.GetBlockHeader(¤tBlock.Hash)
if err != nil {
return err
}
// Then, we'll walk backwards in the chain until we find our common
// ancestor.
for previousBlock != currentHeader.PrevBlock {
// Since the previous hashes don't match, the current block has
// been reorged out of the chain, so we should send a
// BlockDisconnected notification for it.
log.Debugf("Disconnecting block %d (%v)", currentBlock.Height,
currentBlock.Hash)
c.onBlockDisconnected(
¤tBlock.Hash, currentBlock.Height,
currentBlock.Timestamp,
)
// Our current block should now reflect the previous one to
// continue the common ancestor search.
currentHeader, err = c.GetBlockHeader(¤tHeader.PrevBlock)
if err != nil {
return err
}
currentBlock.Height--
currentBlock.Hash = currentHeader.PrevBlock
currentBlock.Timestamp = currentHeader.Timestamp
// Store the correct block in our list in order to notify it
// once we've found our common ancestor.
block, err := c.GetBlock(&previousBlock)
if err != nil {
return err
}
blocksToNotify.PushFront(block)
previousBlock = block.Header.PrevBlock
}
// Disconnect the last block from the old chain. Since the previous
// block remains the same between the old and new chains, the tip will
// now be the last common ancestor.
log.Debugf("Disconnecting block %d (%v)", currentBlock.Height,
currentBlock.Hash)
c.onBlockDisconnected(
¤tBlock.Hash, currentBlock.Height, currentHeader.Timestamp,
)
currentBlock.Height--
// Now we fast-forward to the new block, notifying along the way.
for blocksToNotify.Front() != nil {
nextBlock := blocksToNotify.Front().Value.(*wire.MsgBlock)
nextHeight := currentBlock.Height + 1
nextHash := nextBlock.BlockHash()
nextHeader, err := c.GetBlockHeader(&nextHash)
if err != nil {
return err
}
_, err = c.filterBlock(nextBlock, nextHeight, true)
if err != nil {
return err
}
currentBlock.Height = nextHeight
currentBlock.Hash = nextHash
currentBlock.Timestamp = nextHeader.Timestamp
blocksToNotify.Remove(blocksToNotify.Front())
}
c.bestBlockMtx.Lock()
c.bestBlock = currentBlock
c.bestBlockMtx.Unlock()
return nil
} | go | func (c *BitcoindClient) reorg(currentBlock waddrmgr.BlockStamp,
reorgBlock *wire.MsgBlock) error {
log.Debugf("Possible reorg at block %s", reorgBlock.BlockHash())
// Retrieve the best known height based on the block which caused the
// reorg. This way, we can preserve the chain of blocks we need to
// retrieve.
bestHash := reorgBlock.BlockHash()
bestHeight, err := c.GetBlockHeight(&bestHash)
if err != nil {
return err
}
if bestHeight < currentBlock.Height {
log.Debug("Detected multiple reorgs")
return nil
}
// We'll now keep track of all the blocks known to the *chain*, starting
// from the best block known to us until the best block in the chain.
// This will let us fast-forward despite any future reorgs.
blocksToNotify := list.New()
blocksToNotify.PushFront(reorgBlock)
previousBlock := reorgBlock.Header.PrevBlock
for i := bestHeight - 1; i >= currentBlock.Height; i-- {
block, err := c.GetBlock(&previousBlock)
if err != nil {
return err
}
blocksToNotify.PushFront(block)
previousBlock = block.Header.PrevBlock
}
// Rewind back to the last common ancestor block using the previous
// block hash from each header to avoid any race conditions. If we
// encounter more reorgs, they'll be queued and we'll repeat the cycle.
//
// We'll start by retrieving the header to the best block known to us.
currentHeader, err := c.GetBlockHeader(¤tBlock.Hash)
if err != nil {
return err
}
// Then, we'll walk backwards in the chain until we find our common
// ancestor.
for previousBlock != currentHeader.PrevBlock {
// Since the previous hashes don't match, the current block has
// been reorged out of the chain, so we should send a
// BlockDisconnected notification for it.
log.Debugf("Disconnecting block %d (%v)", currentBlock.Height,
currentBlock.Hash)
c.onBlockDisconnected(
¤tBlock.Hash, currentBlock.Height,
currentBlock.Timestamp,
)
// Our current block should now reflect the previous one to
// continue the common ancestor search.
currentHeader, err = c.GetBlockHeader(¤tHeader.PrevBlock)
if err != nil {
return err
}
currentBlock.Height--
currentBlock.Hash = currentHeader.PrevBlock
currentBlock.Timestamp = currentHeader.Timestamp
// Store the correct block in our list in order to notify it
// once we've found our common ancestor.
block, err := c.GetBlock(&previousBlock)
if err != nil {
return err
}
blocksToNotify.PushFront(block)
previousBlock = block.Header.PrevBlock
}
// Disconnect the last block from the old chain. Since the previous
// block remains the same between the old and new chains, the tip will
// now be the last common ancestor.
log.Debugf("Disconnecting block %d (%v)", currentBlock.Height,
currentBlock.Hash)
c.onBlockDisconnected(
¤tBlock.Hash, currentBlock.Height, currentHeader.Timestamp,
)
currentBlock.Height--
// Now we fast-forward to the new block, notifying along the way.
for blocksToNotify.Front() != nil {
nextBlock := blocksToNotify.Front().Value.(*wire.MsgBlock)
nextHeight := currentBlock.Height + 1
nextHash := nextBlock.BlockHash()
nextHeader, err := c.GetBlockHeader(&nextHash)
if err != nil {
return err
}
_, err = c.filterBlock(nextBlock, nextHeight, true)
if err != nil {
return err
}
currentBlock.Height = nextHeight
currentBlock.Hash = nextHash
currentBlock.Timestamp = nextHeader.Timestamp
blocksToNotify.Remove(blocksToNotify.Front())
}
c.bestBlockMtx.Lock()
c.bestBlock = currentBlock
c.bestBlockMtx.Unlock()
return nil
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"reorg",
"(",
"currentBlock",
"waddrmgr",
".",
"BlockStamp",
",",
"reorgBlock",
"*",
"wire",
".",
"MsgBlock",
")",
"error",
"{",
"log",
".",
"Debugf",
"(",
"\"Possible reorg at block %s\"",
",",
"reorgBlock",
".",
... | // reorg processes a reorganization during chain synchronization. This is
// separate from a rescan's handling of a reorg. This will rewind back until it
// finds a common ancestor and notify all the new blocks since then. | [
"reorg",
"processes",
"a",
"reorganization",
"during",
"chain",
"synchronization",
".",
"This",
"is",
"separate",
"from",
"a",
"rescan",
"s",
"handling",
"of",
"a",
"reorg",
".",
"This",
"will",
"rewind",
"back",
"until",
"it",
"finds",
"a",
"common",
"ances... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L745-L863 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | filterBlock | func (c *BitcoindClient) filterBlock(block *wire.MsgBlock, height int32,
notify bool) ([]*wtxmgr.TxRecord, error) {
// If this block happened before the client's birthday, then we'll skip
// it entirely.
if block.Header.Timestamp.Before(c.birthday) {
return nil, nil
}
if c.shouldNotifyBlocks() {
log.Debugf("Filtering block %d (%s) with %d transactions",
height, block.BlockHash(), len(block.Transactions))
}
// Create a block details template to use for all of the confirmed
// transactions found within this block.
blockHash := block.BlockHash()
blockDetails := &btcjson.BlockDetails{
Hash: blockHash.String(),
Height: height,
Time: block.Header.Timestamp.Unix(),
}
// Now, we'll through all of the transactions in the block keeping track
// of any relevant to the caller.
var relevantTxs []*wtxmgr.TxRecord
confirmedTxs := make(map[chainhash.Hash]struct{})
for i, tx := range block.Transactions {
// Update the index in the block details with the index of this
// transaction.
blockDetails.Index = i
isRelevant, rec, err := c.filterTx(tx, blockDetails, notify)
if err != nil {
log.Warnf("Unable to filter transaction %v: %v",
tx.TxHash(), err)
continue
}
if isRelevant {
relevantTxs = append(relevantTxs, rec)
confirmedTxs[tx.TxHash()] = struct{}{}
}
}
// Update the expiration map by setting the block's confirmed
// transactions and deleting any in the mempool that were confirmed
// over 288 blocks ago.
c.watchMtx.Lock()
c.expiredMempool[height] = confirmedTxs
if oldBlock, ok := c.expiredMempool[height-288]; ok {
for txHash := range oldBlock {
delete(c.mempool, txHash)
}
delete(c.expiredMempool, height-288)
}
c.watchMtx.Unlock()
if notify {
c.onFilteredBlockConnected(height, &block.Header, relevantTxs)
c.onBlockConnected(&blockHash, height, block.Header.Timestamp)
}
return relevantTxs, nil
} | go | func (c *BitcoindClient) filterBlock(block *wire.MsgBlock, height int32,
notify bool) ([]*wtxmgr.TxRecord, error) {
// If this block happened before the client's birthday, then we'll skip
// it entirely.
if block.Header.Timestamp.Before(c.birthday) {
return nil, nil
}
if c.shouldNotifyBlocks() {
log.Debugf("Filtering block %d (%s) with %d transactions",
height, block.BlockHash(), len(block.Transactions))
}
// Create a block details template to use for all of the confirmed
// transactions found within this block.
blockHash := block.BlockHash()
blockDetails := &btcjson.BlockDetails{
Hash: blockHash.String(),
Height: height,
Time: block.Header.Timestamp.Unix(),
}
// Now, we'll through all of the transactions in the block keeping track
// of any relevant to the caller.
var relevantTxs []*wtxmgr.TxRecord
confirmedTxs := make(map[chainhash.Hash]struct{})
for i, tx := range block.Transactions {
// Update the index in the block details with the index of this
// transaction.
blockDetails.Index = i
isRelevant, rec, err := c.filterTx(tx, blockDetails, notify)
if err != nil {
log.Warnf("Unable to filter transaction %v: %v",
tx.TxHash(), err)
continue
}
if isRelevant {
relevantTxs = append(relevantTxs, rec)
confirmedTxs[tx.TxHash()] = struct{}{}
}
}
// Update the expiration map by setting the block's confirmed
// transactions and deleting any in the mempool that were confirmed
// over 288 blocks ago.
c.watchMtx.Lock()
c.expiredMempool[height] = confirmedTxs
if oldBlock, ok := c.expiredMempool[height-288]; ok {
for txHash := range oldBlock {
delete(c.mempool, txHash)
}
delete(c.expiredMempool, height-288)
}
c.watchMtx.Unlock()
if notify {
c.onFilteredBlockConnected(height, &block.Header, relevantTxs)
c.onBlockConnected(&blockHash, height, block.Header.Timestamp)
}
return relevantTxs, nil
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"filterBlock",
"(",
"block",
"*",
"wire",
".",
"MsgBlock",
",",
"height",
"int32",
",",
"notify",
"bool",
")",
"(",
"[",
"]",
"*",
"wtxmgr",
".",
"TxRecord",
",",
"error",
")",
"{",
"if",
"block",
".",
... | // filterBlock filters a block for watched outpoints and addresses, and returns
// any matching transactions, sending notifications along the way. | [
"filterBlock",
"filters",
"a",
"block",
"for",
"watched",
"outpoints",
"and",
"addresses",
"and",
"returns",
"any",
"matching",
"transactions",
"sending",
"notifications",
"along",
"the",
"way",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L1103-L1166 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | filterTx | func (c *BitcoindClient) filterTx(tx *wire.MsgTx,
blockDetails *btcjson.BlockDetails,
notify bool) (bool, *wtxmgr.TxRecord, error) {
txDetails := btcutil.NewTx(tx)
if blockDetails != nil {
txDetails.SetIndex(blockDetails.Index)
}
rec, err := wtxmgr.NewTxRecordFromMsgTx(txDetails.MsgTx(), time.Now())
if err != nil {
log.Errorf("Cannot create transaction record for relevant "+
"tx: %v", err)
return false, nil, err
}
if blockDetails != nil {
rec.Received = time.Unix(blockDetails.Time, 0)
}
// We'll begin the filtering process by holding the lock to ensure we
// match exactly against what's currently in the filters.
c.watchMtx.Lock()
defer c.watchMtx.Unlock()
// If we've already seen this transaction and it's now been confirmed,
// then we'll shortcut the filter process by immediately sending a
// notification to the caller that the filter matches.
if _, ok := c.mempool[tx.TxHash()]; ok {
if notify && blockDetails != nil {
c.onRelevantTx(rec, blockDetails)
}
return true, rec, nil
}
// Otherwise, this is a new transaction we have yet to see. We'll need
// to determine if this transaction is somehow relevant to the caller.
var isRelevant bool
// We'll start by checking all inputs and determining whether it spends
// an existing outpoint or a pkScript encoded as an address in our watch
// list.
for _, txIn := range tx.TxIn {
// If it matches an outpoint in our watch list, we can exit our
// loop early.
if _, ok := c.watchedOutPoints[txIn.PreviousOutPoint]; ok {
isRelevant = true
break
}
// Otherwise, we'll check whether it matches a pkScript in our
// watch list encoded as an address. To do so, we'll re-derive
// the pkScript of the output the input is attempting to spend.
pkScript, err := txscript.ComputePkScript(
txIn.SignatureScript, txIn.Witness,
)
if err != nil {
// Non-standard outputs can be safely skipped.
continue
}
addr, err := pkScript.Address(c.chainParams)
if err != nil {
// Non-standard outputs can be safely skipped.
continue
}
if _, ok := c.watchedAddresses[addr.String()]; ok {
isRelevant = true
break
}
}
// We'll also cycle through its outputs to determine if it pays to
// any of the currently watched addresses. If an output matches, we'll
// add it to our watch list.
for i, txOut := range tx.TxOut {
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
txOut.PkScript, c.chainParams,
)
if err != nil {
// Non-standard outputs can be safely skipped.
continue
}
for _, addr := range addrs {
if _, ok := c.watchedAddresses[addr.String()]; ok {
isRelevant = true
op := wire.OutPoint{
Hash: tx.TxHash(),
Index: uint32(i),
}
c.watchedOutPoints[op] = struct{}{}
}
}
}
// If the transaction didn't pay to any of our watched addresses, we'll
// check if we're currently watching for the hash of this transaction.
if !isRelevant {
if _, ok := c.watchedTxs[tx.TxHash()]; ok {
isRelevant = true
}
}
// If the transaction is not relevant to us, we can simply exit.
if !isRelevant {
return false, rec, nil
}
// Otherwise, the transaction matched our filters, so we should dispatch
// a notification for it. If it's still unconfirmed, we'll include it in
// our mempool so that it can also be notified as part of
// FilteredBlockConnected once it confirms.
if blockDetails == nil {
c.mempool[tx.TxHash()] = struct{}{}
}
c.onRelevantTx(rec, blockDetails)
return true, rec, nil
} | go | func (c *BitcoindClient) filterTx(tx *wire.MsgTx,
blockDetails *btcjson.BlockDetails,
notify bool) (bool, *wtxmgr.TxRecord, error) {
txDetails := btcutil.NewTx(tx)
if blockDetails != nil {
txDetails.SetIndex(blockDetails.Index)
}
rec, err := wtxmgr.NewTxRecordFromMsgTx(txDetails.MsgTx(), time.Now())
if err != nil {
log.Errorf("Cannot create transaction record for relevant "+
"tx: %v", err)
return false, nil, err
}
if blockDetails != nil {
rec.Received = time.Unix(blockDetails.Time, 0)
}
// We'll begin the filtering process by holding the lock to ensure we
// match exactly against what's currently in the filters.
c.watchMtx.Lock()
defer c.watchMtx.Unlock()
// If we've already seen this transaction and it's now been confirmed,
// then we'll shortcut the filter process by immediately sending a
// notification to the caller that the filter matches.
if _, ok := c.mempool[tx.TxHash()]; ok {
if notify && blockDetails != nil {
c.onRelevantTx(rec, blockDetails)
}
return true, rec, nil
}
// Otherwise, this is a new transaction we have yet to see. We'll need
// to determine if this transaction is somehow relevant to the caller.
var isRelevant bool
// We'll start by checking all inputs and determining whether it spends
// an existing outpoint or a pkScript encoded as an address in our watch
// list.
for _, txIn := range tx.TxIn {
// If it matches an outpoint in our watch list, we can exit our
// loop early.
if _, ok := c.watchedOutPoints[txIn.PreviousOutPoint]; ok {
isRelevant = true
break
}
// Otherwise, we'll check whether it matches a pkScript in our
// watch list encoded as an address. To do so, we'll re-derive
// the pkScript of the output the input is attempting to spend.
pkScript, err := txscript.ComputePkScript(
txIn.SignatureScript, txIn.Witness,
)
if err != nil {
// Non-standard outputs can be safely skipped.
continue
}
addr, err := pkScript.Address(c.chainParams)
if err != nil {
// Non-standard outputs can be safely skipped.
continue
}
if _, ok := c.watchedAddresses[addr.String()]; ok {
isRelevant = true
break
}
}
// We'll also cycle through its outputs to determine if it pays to
// any of the currently watched addresses. If an output matches, we'll
// add it to our watch list.
for i, txOut := range tx.TxOut {
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
txOut.PkScript, c.chainParams,
)
if err != nil {
// Non-standard outputs can be safely skipped.
continue
}
for _, addr := range addrs {
if _, ok := c.watchedAddresses[addr.String()]; ok {
isRelevant = true
op := wire.OutPoint{
Hash: tx.TxHash(),
Index: uint32(i),
}
c.watchedOutPoints[op] = struct{}{}
}
}
}
// If the transaction didn't pay to any of our watched addresses, we'll
// check if we're currently watching for the hash of this transaction.
if !isRelevant {
if _, ok := c.watchedTxs[tx.TxHash()]; ok {
isRelevant = true
}
}
// If the transaction is not relevant to us, we can simply exit.
if !isRelevant {
return false, rec, nil
}
// Otherwise, the transaction matched our filters, so we should dispatch
// a notification for it. If it's still unconfirmed, we'll include it in
// our mempool so that it can also be notified as part of
// FilteredBlockConnected once it confirms.
if blockDetails == nil {
c.mempool[tx.TxHash()] = struct{}{}
}
c.onRelevantTx(rec, blockDetails)
return true, rec, nil
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"filterTx",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
",",
"blockDetails",
"*",
"btcjson",
".",
"BlockDetails",
",",
"notify",
"bool",
")",
"(",
"bool",
",",
"*",
"wtxmgr",
".",
"TxRecord",
",",
"error",
")",
... | // filterTx determines whether a transaction is relevant to the client by
// inspecting the client's different filters. | [
"filterTx",
"determines",
"whether",
"a",
"transaction",
"is",
"relevant",
"to",
"the",
"client",
"by",
"inspecting",
"the",
"client",
"s",
"different",
"filters",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L1170-L1288 | train |
btcsuite/btcwallet | wtxmgr/migrations.go | dropTransactionHistory | func dropTransactionHistory(ns walletdb.ReadWriteBucket) error {
log.Info("Dropping wallet transaction history")
// To drop the store's transaction history, we'll need to remove all of
// the relevant descendant buckets and key/value pairs.
if err := deleteBuckets(ns); err != nil {
return err
}
if err := ns.Delete(rootMinedBalance); err != nil {
return err
}
// With everything removed, we'll now recreate our buckets.
if err := createBuckets(ns); err != nil {
return err
}
// Finally, we'll insert a 0 value for our mined balance.
return putMinedBalance(ns, 0)
} | go | func dropTransactionHistory(ns walletdb.ReadWriteBucket) error {
log.Info("Dropping wallet transaction history")
// To drop the store's transaction history, we'll need to remove all of
// the relevant descendant buckets and key/value pairs.
if err := deleteBuckets(ns); err != nil {
return err
}
if err := ns.Delete(rootMinedBalance); err != nil {
return err
}
// With everything removed, we'll now recreate our buckets.
if err := createBuckets(ns); err != nil {
return err
}
// Finally, we'll insert a 0 value for our mined balance.
return putMinedBalance(ns, 0)
} | [
"func",
"dropTransactionHistory",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
")",
"error",
"{",
"log",
".",
"Info",
"(",
"\"Dropping wallet transaction history\"",
")",
"\n",
"if",
"err",
":=",
"deleteBuckets",
"(",
"ns",
")",
";",
"err",
"!=",
"nil",
"{",... | // dropTransactionHistory is a migration that attempts to recreate the
// transaction store with a clean state. | [
"dropTransactionHistory",
"is",
"a",
"migration",
"that",
"attempts",
"to",
"recreate",
"the",
"transaction",
"store",
"with",
"a",
"clean",
"state",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/migrations.go#L91-L110 | train |
btcsuite/btcwallet | waddrmgr/sync.go | newSyncState | func newSyncState(startBlock, syncedTo *BlockStamp) *syncState {
return &syncState{
startBlock: *startBlock,
syncedTo: *syncedTo,
}
} | go | func newSyncState(startBlock, syncedTo *BlockStamp) *syncState {
return &syncState{
startBlock: *startBlock,
syncedTo: *syncedTo,
}
} | [
"func",
"newSyncState",
"(",
"startBlock",
",",
"syncedTo",
"*",
"BlockStamp",
")",
"*",
"syncState",
"{",
"return",
"&",
"syncState",
"{",
"startBlock",
":",
"*",
"startBlock",
",",
"syncedTo",
":",
"*",
"syncedTo",
",",
"}",
"\n",
"}"
] | // newSyncState returns a new sync state with the provided parameters. | [
"newSyncState",
"returns",
"a",
"new",
"sync",
"state",
"with",
"the",
"provided",
"parameters",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L37-L43 | train |
btcsuite/btcwallet | waddrmgr/sync.go | SetSyncedTo | func (m *Manager) SetSyncedTo(ns walletdb.ReadWriteBucket, bs *BlockStamp) error {
m.mtx.Lock()
defer m.mtx.Unlock()
// Use the stored start blockstamp and reset recent hashes and height
// when the provided blockstamp is nil.
if bs == nil {
bs = &m.syncState.startBlock
}
// Update the database.
err := PutSyncedTo(ns, bs)
if err != nil {
return err
}
// Update memory now that the database is updated.
m.syncState.syncedTo = *bs
return nil
} | go | func (m *Manager) SetSyncedTo(ns walletdb.ReadWriteBucket, bs *BlockStamp) error {
m.mtx.Lock()
defer m.mtx.Unlock()
// Use the stored start blockstamp and reset recent hashes and height
// when the provided blockstamp is nil.
if bs == nil {
bs = &m.syncState.startBlock
}
// Update the database.
err := PutSyncedTo(ns, bs)
if err != nil {
return err
}
// Update memory now that the database is updated.
m.syncState.syncedTo = *bs
return nil
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"SetSyncedTo",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"bs",
"*",
"BlockStamp",
")",
"error",
"{",
"m",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"mtx",
".",
"Unlock",
"(",
")",
... | // SetSyncedTo marks the address manager to be in sync with the recently-seen
// block described by the blockstamp. When the provided blockstamp is nil, the
// oldest blockstamp of the block the manager was created at and of all
// imported addresses will be used. This effectively allows the manager to be
// marked as unsynced back to the oldest known point any of the addresses have
// appeared in the block chain. | [
"SetSyncedTo",
"marks",
"the",
"address",
"manager",
"to",
"be",
"in",
"sync",
"with",
"the",
"recently",
"-",
"seen",
"block",
"described",
"by",
"the",
"blockstamp",
".",
"When",
"the",
"provided",
"blockstamp",
"is",
"nil",
"the",
"oldest",
"blockstamp",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L51-L70 | train |
btcsuite/btcwallet | waddrmgr/sync.go | SyncedTo | func (m *Manager) SyncedTo() BlockStamp {
m.mtx.Lock()
defer m.mtx.Unlock()
return m.syncState.syncedTo
} | go | func (m *Manager) SyncedTo() BlockStamp {
m.mtx.Lock()
defer m.mtx.Unlock()
return m.syncState.syncedTo
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"SyncedTo",
"(",
")",
"BlockStamp",
"{",
"m",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"return",
"m",
".",
"syncState",
".",
"syncedTo",
"\n",
"}"
] | // SyncedTo returns details about the block height and hash that the address
// manager is synced through at the very least. The intention is that callers
// can use this information for intelligently initiating rescans to sync back to
// the best chain from the last known good block. | [
"SyncedTo",
"returns",
"details",
"about",
"the",
"block",
"height",
"and",
"hash",
"that",
"the",
"address",
"manager",
"is",
"synced",
"through",
"at",
"the",
"very",
"least",
".",
"The",
"intention",
"is",
"that",
"callers",
"can",
"use",
"this",
"informa... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L76-L81 | train |
btcsuite/btcwallet | waddrmgr/sync.go | BlockHash | func (m *Manager) BlockHash(ns walletdb.ReadBucket, height int32) (
*chainhash.Hash, error) {
m.mtx.Lock()
defer m.mtx.Unlock()
return fetchBlockHash(ns, height)
} | go | func (m *Manager) BlockHash(ns walletdb.ReadBucket, height int32) (
*chainhash.Hash, error) {
m.mtx.Lock()
defer m.mtx.Unlock()
return fetchBlockHash(ns, height)
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"BlockHash",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"height",
"int32",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"m",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
"."... | // BlockHash returns the block hash at a particular block height. This
// information is useful for comparing against the chain back-end to see if a
// reorg is taking place and how far back it goes. | [
"BlockHash",
"returns",
"the",
"block",
"hash",
"at",
"a",
"particular",
"block",
"height",
".",
"This",
"information",
"is",
"useful",
"for",
"comparing",
"against",
"the",
"chain",
"back",
"-",
"end",
"to",
"see",
"if",
"a",
"reorg",
"is",
"taking",
"pla... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L86-L92 | train |
btcsuite/btcwallet | waddrmgr/sync.go | Birthday | func (m *Manager) Birthday() time.Time {
m.mtx.Lock()
defer m.mtx.Unlock()
return m.birthday
} | go | func (m *Manager) Birthday() time.Time {
m.mtx.Lock()
defer m.mtx.Unlock()
return m.birthday
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"Birthday",
"(",
")",
"time",
".",
"Time",
"{",
"m",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"return",
"m",
".",
"birthday",
"\n",
"}"
] | // Birthday returns the birthday, or earliest time a key could have been used,
// for the manager. | [
"Birthday",
"returns",
"the",
"birthday",
"or",
"earliest",
"time",
"a",
"key",
"could",
"have",
"been",
"used",
"for",
"the",
"manager",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L96-L101 | train |
btcsuite/btcwallet | waddrmgr/sync.go | SetBirthday | func (m *Manager) SetBirthday(ns walletdb.ReadWriteBucket,
birthday time.Time) error {
m.mtx.Lock()
defer m.mtx.Unlock()
m.birthday = birthday
return putBirthday(ns, birthday)
} | go | func (m *Manager) SetBirthday(ns walletdb.ReadWriteBucket,
birthday time.Time) error {
m.mtx.Lock()
defer m.mtx.Unlock()
m.birthday = birthday
return putBirthday(ns, birthday)
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"SetBirthday",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"birthday",
"time",
".",
"Time",
")",
"error",
"{",
"m",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"mtx",
".",
"Unlock",
"("... | // SetBirthday sets the birthday, or earliest time a key could have been used,
// for the manager. | [
"SetBirthday",
"sets",
"the",
"birthday",
"or",
"earliest",
"time",
"a",
"key",
"could",
"have",
"been",
"used",
"for",
"the",
"manager",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L105-L112 | train |
btcsuite/btcwallet | waddrmgr/sync.go | BirthdayBlock | func (m *Manager) BirthdayBlock(ns walletdb.ReadBucket) (BlockStamp, bool, error) {
birthdayBlock, err := FetchBirthdayBlock(ns)
if err != nil {
return BlockStamp{}, false, err
}
return birthdayBlock, fetchBirthdayBlockVerification(ns), nil
} | go | func (m *Manager) BirthdayBlock(ns walletdb.ReadBucket) (BlockStamp, bool, error) {
birthdayBlock, err := FetchBirthdayBlock(ns)
if err != nil {
return BlockStamp{}, false, err
}
return birthdayBlock, fetchBirthdayBlockVerification(ns), nil
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"BirthdayBlock",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
")",
"(",
"BlockStamp",
",",
"bool",
",",
"error",
")",
"{",
"birthdayBlock",
",",
"err",
":=",
"FetchBirthdayBlock",
"(",
"ns",
")",
"\n",
"if",
"err",
"... | // BirthdayBlock returns the birthday block, or earliest block a key could have
// been used, for the manager. A boolean is also returned to indicate whether
// the birthday block has been verified as correct. | [
"BirthdayBlock",
"returns",
"the",
"birthday",
"block",
"or",
"earliest",
"block",
"a",
"key",
"could",
"have",
"been",
"used",
"for",
"the",
"manager",
".",
"A",
"boolean",
"is",
"also",
"returned",
"to",
"indicate",
"whether",
"the",
"birthday",
"block",
"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L117-L124 | train |
btcsuite/btcwallet | waddrmgr/sync.go | SetBirthdayBlock | func (m *Manager) SetBirthdayBlock(ns walletdb.ReadWriteBucket,
block BlockStamp, verified bool) error {
if err := putBirthdayBlock(ns, block); err != nil {
return err
}
return putBirthdayBlockVerification(ns, verified)
} | go | func (m *Manager) SetBirthdayBlock(ns walletdb.ReadWriteBucket,
block BlockStamp, verified bool) error {
if err := putBirthdayBlock(ns, block); err != nil {
return err
}
return putBirthdayBlockVerification(ns, verified)
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"SetBirthdayBlock",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"block",
"BlockStamp",
",",
"verified",
"bool",
")",
"error",
"{",
"if",
"err",
":=",
"putBirthdayBlock",
"(",
"ns",
",",
"block",
")",
";",
"e... | // SetBirthdayBlock sets the birthday block, or earliest time a key could have
// been used, for the manager. The verified boolean can be used to specify
// whether this birthday block should be sanity checked to determine if there
// exists a better candidate to prevent less block fetching. | [
"SetBirthdayBlock",
"sets",
"the",
"birthday",
"block",
"or",
"earliest",
"time",
"a",
"key",
"could",
"have",
"been",
"used",
"for",
"the",
"manager",
".",
"The",
"verified",
"boolean",
"can",
"be",
"used",
"to",
"specify",
"whether",
"this",
"birthday",
"b... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/sync.go#L130-L137 | train |
btcsuite/btcwallet | wallet/recovery.go | NewRecoveryManager | func NewRecoveryManager(recoveryWindow, batchSize uint32,
chainParams *chaincfg.Params) *RecoveryManager {
return &RecoveryManager{
recoveryWindow: recoveryWindow,
blockBatch: make([]wtxmgr.BlockMeta, 0, batchSize),
chainParams: chainParams,
state: NewRecoveryState(recoveryWindow),
}
} | go | func NewRecoveryManager(recoveryWindow, batchSize uint32,
chainParams *chaincfg.Params) *RecoveryManager {
return &RecoveryManager{
recoveryWindow: recoveryWindow,
blockBatch: make([]wtxmgr.BlockMeta, 0, batchSize),
chainParams: chainParams,
state: NewRecoveryState(recoveryWindow),
}
} | [
"func",
"NewRecoveryManager",
"(",
"recoveryWindow",
",",
"batchSize",
"uint32",
",",
"chainParams",
"*",
"chaincfg",
".",
"Params",
")",
"*",
"RecoveryManager",
"{",
"return",
"&",
"RecoveryManager",
"{",
"recoveryWindow",
":",
"recoveryWindow",
",",
"blockBatch",
... | // NewRecoveryManager initializes a new RecoveryManager with a derivation
// look-ahead of `recoveryWindow` child indexes, and pre-allocates a backing
// array for `batchSize` blocks to scan at once. | [
"NewRecoveryManager",
"initializes",
"a",
"new",
"RecoveryManager",
"with",
"a",
"derivation",
"look",
"-",
"ahead",
"of",
"recoveryWindow",
"child",
"indexes",
"and",
"pre",
"-",
"allocates",
"a",
"backing",
"array",
"for",
"batchSize",
"blocks",
"to",
"scan",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L43-L52 | train |
btcsuite/btcwallet | wallet/recovery.go | Resurrect | func (rm *RecoveryManager) Resurrect(ns walletdb.ReadBucket,
scopedMgrs map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager,
credits []wtxmgr.Credit) error {
// First, for each scope that we are recovering, rederive all of the
// addresses up to the last found address known to each branch.
for keyScope, scopedMgr := range scopedMgrs {
// Load the current account properties for this scope, using the
// the default account number.
// TODO(conner): rescan for all created accounts if we allow
// users to use non-default address
scopeState := rm.state.StateForScope(keyScope)
acctProperties, err := scopedMgr.AccountProperties(
ns, waddrmgr.DefaultAccountNum,
)
if err != nil {
return err
}
// Fetch the external key count, which bounds the indexes we
// will need to rederive.
externalCount := acctProperties.ExternalKeyCount
// Walk through all indexes through the last external key,
// deriving each address and adding it to the external branch
// recovery state's set of addresses to look for.
for i := uint32(0); i < externalCount; i++ {
keyPath := externalKeyPath(i)
addr, err := scopedMgr.DeriveFromKeyPath(ns, keyPath)
if err != nil && err != hdkeychain.ErrInvalidChild {
return err
} else if err == hdkeychain.ErrInvalidChild {
scopeState.ExternalBranch.MarkInvalidChild(i)
continue
}
scopeState.ExternalBranch.AddAddr(i, addr.Address())
}
// Fetch the internal key count, which bounds the indexes we
// will need to rederive.
internalCount := acctProperties.InternalKeyCount
// Walk through all indexes through the last internal key,
// deriving each address and adding it to the internal branch
// recovery state's set of addresses to look for.
for i := uint32(0); i < internalCount; i++ {
keyPath := internalKeyPath(i)
addr, err := scopedMgr.DeriveFromKeyPath(ns, keyPath)
if err != nil && err != hdkeychain.ErrInvalidChild {
return err
} else if err == hdkeychain.ErrInvalidChild {
scopeState.InternalBranch.MarkInvalidChild(i)
continue
}
scopeState.InternalBranch.AddAddr(i, addr.Address())
}
// The key counts will point to the next key that can be
// derived, so we subtract one to point to last known key. If
// the key count is zero, then no addresses have been found.
if externalCount > 0 {
scopeState.ExternalBranch.ReportFound(externalCount - 1)
}
if internalCount > 0 {
scopeState.InternalBranch.ReportFound(internalCount - 1)
}
}
// In addition, we will re-add any outpoints that are known the wallet
// to our global set of watched outpoints, so that we can watch them for
// spends.
for _, credit := range credits {
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
credit.PkScript, rm.chainParams,
)
if err != nil {
return err
}
rm.state.AddWatchedOutPoint(&credit.OutPoint, addrs[0])
}
return nil
} | go | func (rm *RecoveryManager) Resurrect(ns walletdb.ReadBucket,
scopedMgrs map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager,
credits []wtxmgr.Credit) error {
// First, for each scope that we are recovering, rederive all of the
// addresses up to the last found address known to each branch.
for keyScope, scopedMgr := range scopedMgrs {
// Load the current account properties for this scope, using the
// the default account number.
// TODO(conner): rescan for all created accounts if we allow
// users to use non-default address
scopeState := rm.state.StateForScope(keyScope)
acctProperties, err := scopedMgr.AccountProperties(
ns, waddrmgr.DefaultAccountNum,
)
if err != nil {
return err
}
// Fetch the external key count, which bounds the indexes we
// will need to rederive.
externalCount := acctProperties.ExternalKeyCount
// Walk through all indexes through the last external key,
// deriving each address and adding it to the external branch
// recovery state's set of addresses to look for.
for i := uint32(0); i < externalCount; i++ {
keyPath := externalKeyPath(i)
addr, err := scopedMgr.DeriveFromKeyPath(ns, keyPath)
if err != nil && err != hdkeychain.ErrInvalidChild {
return err
} else if err == hdkeychain.ErrInvalidChild {
scopeState.ExternalBranch.MarkInvalidChild(i)
continue
}
scopeState.ExternalBranch.AddAddr(i, addr.Address())
}
// Fetch the internal key count, which bounds the indexes we
// will need to rederive.
internalCount := acctProperties.InternalKeyCount
// Walk through all indexes through the last internal key,
// deriving each address and adding it to the internal branch
// recovery state's set of addresses to look for.
for i := uint32(0); i < internalCount; i++ {
keyPath := internalKeyPath(i)
addr, err := scopedMgr.DeriveFromKeyPath(ns, keyPath)
if err != nil && err != hdkeychain.ErrInvalidChild {
return err
} else if err == hdkeychain.ErrInvalidChild {
scopeState.InternalBranch.MarkInvalidChild(i)
continue
}
scopeState.InternalBranch.AddAddr(i, addr.Address())
}
// The key counts will point to the next key that can be
// derived, so we subtract one to point to last known key. If
// the key count is zero, then no addresses have been found.
if externalCount > 0 {
scopeState.ExternalBranch.ReportFound(externalCount - 1)
}
if internalCount > 0 {
scopeState.InternalBranch.ReportFound(internalCount - 1)
}
}
// In addition, we will re-add any outpoints that are known the wallet
// to our global set of watched outpoints, so that we can watch them for
// spends.
for _, credit := range credits {
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
credit.PkScript, rm.chainParams,
)
if err != nil {
return err
}
rm.state.AddWatchedOutPoint(&credit.OutPoint, addrs[0])
}
return nil
} | [
"func",
"(",
"rm",
"*",
"RecoveryManager",
")",
"Resurrect",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"scopedMgrs",
"map",
"[",
"waddrmgr",
".",
"KeyScope",
"]",
"*",
"waddrmgr",
".",
"ScopedKeyManager",
",",
"credits",
"[",
"]",
"wtxmgr",
".",
"Cred... | // Resurrect restores all known addresses for the provided scopes that can be
// found in the walletdb namespace, in addition to restoring all outpoints that
// have been previously found. This method ensures that the recovery state's
// horizons properly start from the last found address of a prior recovery
// attempt. | [
"Resurrect",
"restores",
"all",
"known",
"addresses",
"for",
"the",
"provided",
"scopes",
"that",
"can",
"be",
"found",
"in",
"the",
"walletdb",
"namespace",
"in",
"addition",
"to",
"restoring",
"all",
"outpoints",
"that",
"have",
"been",
"previously",
"found",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L59-L144 | train |
btcsuite/btcwallet | wallet/recovery.go | AddToBlockBatch | func (rm *RecoveryManager) AddToBlockBatch(hash *chainhash.Hash, height int32,
timestamp time.Time) {
if !rm.started {
log.Infof("Seed birthday surpassed, starting recovery "+
"of wallet from height=%d hash=%v with "+
"recovery-window=%d", height, *hash, rm.recoveryWindow)
rm.started = true
}
block := wtxmgr.BlockMeta{
Block: wtxmgr.Block{
Hash: *hash,
Height: height,
},
Time: timestamp,
}
rm.blockBatch = append(rm.blockBatch, block)
} | go | func (rm *RecoveryManager) AddToBlockBatch(hash *chainhash.Hash, height int32,
timestamp time.Time) {
if !rm.started {
log.Infof("Seed birthday surpassed, starting recovery "+
"of wallet from height=%d hash=%v with "+
"recovery-window=%d", height, *hash, rm.recoveryWindow)
rm.started = true
}
block := wtxmgr.BlockMeta{
Block: wtxmgr.Block{
Hash: *hash,
Height: height,
},
Time: timestamp,
}
rm.blockBatch = append(rm.blockBatch, block)
} | [
"func",
"(",
"rm",
"*",
"RecoveryManager",
")",
"AddToBlockBatch",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
",",
"height",
"int32",
",",
"timestamp",
"time",
".",
"Time",
")",
"{",
"if",
"!",
"rm",
".",
"started",
"{",
"log",
".",
"Infof",
"(",
"\... | // AddToBlockBatch appends the block information, consisting of hash and height,
// to the batch of blocks to be searched. | [
"AddToBlockBatch",
"appends",
"the",
"block",
"information",
"consisting",
"of",
"hash",
"and",
"height",
"to",
"the",
"batch",
"of",
"blocks",
"to",
"be",
"searched",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L148-L166 | train |
btcsuite/btcwallet | wallet/recovery.go | NewRecoveryState | func NewRecoveryState(recoveryWindow uint32) *RecoveryState {
scopes := make(map[waddrmgr.KeyScope]*ScopeRecoveryState)
return &RecoveryState{
recoveryWindow: recoveryWindow,
scopes: scopes,
watchedOutPoints: make(map[wire.OutPoint]btcutil.Address),
}
} | go | func NewRecoveryState(recoveryWindow uint32) *RecoveryState {
scopes := make(map[waddrmgr.KeyScope]*ScopeRecoveryState)
return &RecoveryState{
recoveryWindow: recoveryWindow,
scopes: scopes,
watchedOutPoints: make(map[wire.OutPoint]btcutil.Address),
}
} | [
"func",
"NewRecoveryState",
"(",
"recoveryWindow",
"uint32",
")",
"*",
"RecoveryState",
"{",
"scopes",
":=",
"make",
"(",
"map",
"[",
"waddrmgr",
".",
"KeyScope",
"]",
"*",
"ScopeRecoveryState",
")",
"\n",
"return",
"&",
"RecoveryState",
"{",
"recoveryWindow",
... | // NewRecoveryState creates a new RecoveryState using the provided
// recoveryWindow. Each RecoveryState that is subsequently initialized for a
// particular key scope will receive the same recoveryWindow. | [
"NewRecoveryState",
"creates",
"a",
"new",
"RecoveryState",
"using",
"the",
"provided",
"recoveryWindow",
".",
"Each",
"RecoveryState",
"that",
"is",
"subsequently",
"initialized",
"for",
"a",
"particular",
"key",
"scope",
"will",
"receive",
"the",
"same",
"recovery... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L216-L224 | train |
btcsuite/btcwallet | wallet/recovery.go | StateForScope | func (rs *RecoveryState) StateForScope(
keyScope waddrmgr.KeyScope) *ScopeRecoveryState {
// If the account recovery state already exists, return it.
if scopeState, ok := rs.scopes[keyScope]; ok {
return scopeState
}
// Otherwise, initialize the recovery state for this scope with the
// chosen recovery window.
rs.scopes[keyScope] = NewScopeRecoveryState(rs.recoveryWindow)
return rs.scopes[keyScope]
} | go | func (rs *RecoveryState) StateForScope(
keyScope waddrmgr.KeyScope) *ScopeRecoveryState {
// If the account recovery state already exists, return it.
if scopeState, ok := rs.scopes[keyScope]; ok {
return scopeState
}
// Otherwise, initialize the recovery state for this scope with the
// chosen recovery window.
rs.scopes[keyScope] = NewScopeRecoveryState(rs.recoveryWindow)
return rs.scopes[keyScope]
} | [
"func",
"(",
"rs",
"*",
"RecoveryState",
")",
"StateForScope",
"(",
"keyScope",
"waddrmgr",
".",
"KeyScope",
")",
"*",
"ScopeRecoveryState",
"{",
"if",
"scopeState",
",",
"ok",
":=",
"rs",
".",
"scopes",
"[",
"keyScope",
"]",
";",
"ok",
"{",
"return",
"s... | // StateForScope returns a ScopeRecoveryState for the provided key scope. If one
// does not already exist, a new one will be generated with the RecoveryState's
// recoveryWindow. | [
"StateForScope",
"returns",
"a",
"ScopeRecoveryState",
"for",
"the",
"provided",
"key",
"scope",
".",
"If",
"one",
"does",
"not",
"already",
"exist",
"a",
"new",
"one",
"will",
"be",
"generated",
"with",
"the",
"RecoveryState",
"s",
"recoveryWindow",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L229-L242 | train |
btcsuite/btcwallet | wallet/recovery.go | AddWatchedOutPoint | func (rs *RecoveryState) AddWatchedOutPoint(outPoint *wire.OutPoint,
addr btcutil.Address) {
rs.watchedOutPoints[*outPoint] = addr
} | go | func (rs *RecoveryState) AddWatchedOutPoint(outPoint *wire.OutPoint,
addr btcutil.Address) {
rs.watchedOutPoints[*outPoint] = addr
} | [
"func",
"(",
"rs",
"*",
"RecoveryState",
")",
"AddWatchedOutPoint",
"(",
"outPoint",
"*",
"wire",
".",
"OutPoint",
",",
"addr",
"btcutil",
".",
"Address",
")",
"{",
"rs",
".",
"watchedOutPoints",
"[",
"*",
"outPoint",
"]",
"=",
"addr",
"\n",
"}"
] | // AddWatchedOutPoint updates the recovery state's set of known outpoints that
// we will monitor for spends during recovery. | [
"AddWatchedOutPoint",
"updates",
"the",
"recovery",
"state",
"s",
"set",
"of",
"known",
"outpoints",
"that",
"we",
"will",
"monitor",
"for",
"spends",
"during",
"recovery",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L252-L256 | train |
btcsuite/btcwallet | wallet/recovery.go | NewScopeRecoveryState | func NewScopeRecoveryState(recoveryWindow uint32) *ScopeRecoveryState {
return &ScopeRecoveryState{
ExternalBranch: NewBranchRecoveryState(recoveryWindow),
InternalBranch: NewBranchRecoveryState(recoveryWindow),
}
} | go | func NewScopeRecoveryState(recoveryWindow uint32) *ScopeRecoveryState {
return &ScopeRecoveryState{
ExternalBranch: NewBranchRecoveryState(recoveryWindow),
InternalBranch: NewBranchRecoveryState(recoveryWindow),
}
} | [
"func",
"NewScopeRecoveryState",
"(",
"recoveryWindow",
"uint32",
")",
"*",
"ScopeRecoveryState",
"{",
"return",
"&",
"ScopeRecoveryState",
"{",
"ExternalBranch",
":",
"NewBranchRecoveryState",
"(",
"recoveryWindow",
")",
",",
"InternalBranch",
":",
"NewBranchRecoveryStat... | // NewScopeRecoveryState initializes an ScopeRecoveryState with the chosen
// recovery window. | [
"NewScopeRecoveryState",
"initializes",
"an",
"ScopeRecoveryState",
"with",
"the",
"chosen",
"recovery",
"window",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L273-L278 | train |
btcsuite/btcwallet | wallet/recovery.go | NewBranchRecoveryState | func NewBranchRecoveryState(recoveryWindow uint32) *BranchRecoveryState {
return &BranchRecoveryState{
recoveryWindow: recoveryWindow,
addresses: make(map[uint32]btcutil.Address),
invalidChildren: make(map[uint32]struct{}),
}
} | go | func NewBranchRecoveryState(recoveryWindow uint32) *BranchRecoveryState {
return &BranchRecoveryState{
recoveryWindow: recoveryWindow,
addresses: make(map[uint32]btcutil.Address),
invalidChildren: make(map[uint32]struct{}),
}
} | [
"func",
"NewBranchRecoveryState",
"(",
"recoveryWindow",
"uint32",
")",
"*",
"BranchRecoveryState",
"{",
"return",
"&",
"BranchRecoveryState",
"{",
"recoveryWindow",
":",
"recoveryWindow",
",",
"addresses",
":",
"make",
"(",
"map",
"[",
"uint32",
"]",
"btcutil",
"... | // NewBranchRecoveryState creates a new BranchRecoveryState that can be used to
// track either the external or internal branch of an account's derivation path. | [
"NewBranchRecoveryState",
"creates",
"a",
"new",
"BranchRecoveryState",
"that",
"can",
"be",
"used",
"to",
"track",
"either",
"the",
"external",
"or",
"internal",
"branch",
"of",
"an",
"account",
"s",
"derivation",
"path",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/recovery.go#L314-L320 | train |
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 current horizon is sufficient, we will not have to derive any
// new keys.
if curHorizon >= minValidHorizon {
return curHorizon, 0
}
// Otherwise, the number of addresses we should derive corresponds to
// the delta of the two horizons, and we update our new horizon.
delta := minValidHorizon - curHorizon
brs.horizon = minValidHorizon
return curHorizon, delta
} | 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 current horizon is sufficient, we will not have to derive any
// new keys.
if curHorizon >= minValidHorizon {
return curHorizon, 0
}
// Otherwise, the number of addresses we should derive corresponds to
// the delta of the two horizons, and we update our new horizon.
delta := minValidHorizon - curHorizon
brs.horizon = minValidHorizon
return curHorizon, delta
} | [
"func",
"(",
"brs",
"*",
"BranchRecoveryState",
")",
"ExtendHorizon",
"(",
")",
"(",
"uint32",
",",
"uint32",
")",
"{",
"curHorizon",
":=",
"brs",
".",
"horizon",
"\n",
"nInvalid",
":=",
"brs",
".",
"NumInvalidInHorizon",
"(",
")",
"\n",
"minValidHorizon",
... | // 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 childIndex := range brs.invalidChildren {
if childIndex < index {
delete(brs.invalidChildren, childIndex)
}
}
}
} | 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 childIndex := range brs.invalidChildren {
if childIndex < index {
delete(brs.invalidChildren, childIndex)
}
}
}
} | [
"func",
"(",
"brs",
"*",
"BranchRecoveryState",
")",
"ReportFound",
"(",
"index",
"uint32",
")",
"{",
"if",
"index",
">=",
"brs",
".",
"nextUnfound",
"{",
"brs",
".",
"nextUnfound",
"=",
"index",
"+",
"1",
"\n",
"for",
"childIndex",
":=",
"range",
"brs",... | // 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
// invalid child is encountered. | [
"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:44])
byteOrder.PutUint32(newv[40:44], n+1)
return newv, nil
} | 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:44])
byteOrder.PutUint32(newv[40:44], n+1)
return newv, nil
} | [
"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",
"(",
"\"%s: short read (expected %d bytes, read %d)\"",
... | // 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",
"(",
"\"%s: short read (expected %d... | // 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",
"(",
"\"%s: short key (expected %d bytes, read %d)\"",
"... | // 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))
copy(v[45:77], spender.block.Hash[:])
byteOrder.PutUint32(v[77:81], spender.index)
return btcutil.Amount(byteOrder.Uint64(v[0:8])), putRawCredit(ns, k, v)
} | 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))
copy(v[45:77], spender.block.Hash[:])
byteOrder.PutUint32(v[77:81], spender.index)
return btcutil.Amount(byteOrder.Uint64(v[0:8])), putRawCredit(ns, k, v)
} | [
"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"
return 0, storeError(ErrDatabase, str, err)
}
return btcutil.Amount(byteOrder.Uint64(v[0:8])), nil
} | 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"
return 0, storeError(ErrDatabase, str, err)
}
return btcutil.Amount(byteOrder.Uint64(v[0:8])), nil
} | [
"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 bytes, read %v)",
bucketDebits, len(v))
return nil, nil, storeError(ErrData, str, nil)
}
return k, v[8:80], nil
} | 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 bytes, read %v)",
bucketDebits, len(v))
return nil, nil, storeError(ErrData, str, nil)
}
return k, v[8:80], nil
} | [
"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 len(rawSpendTxHashes) > 0 {
var spendTxHash chainhash.Hash
copy(spendTxHash[:], rawSpendTxHashes[:32])
spendTxHashes = append(spendTxHashes, spendTxHash)
rawSpendTxHashes = rawSpendTxHashes[32:]
}
return spendTxHashes
} | 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 len(rawSpendTxHashes) > 0 {
var spendTxHash chainhash.Hash
copy(spendTxHash[:], rawSpendTxHashes[:32])
spendTxHashes = append(spendTxHashes, spendTxHash)
rawSpendTxHashes = rawSpendTxHashes[32:]
}
return spendTxHashes
} | [
"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) == 0 {
return nil
}
// We'll iterate through them and pick all the ones that don't match the
// specified spending transaction.
var newSpendHashes []byte
numHashes := len(spendHashes) / 32
for i, idx := 0, 0; i < numHashes; i, idx = i+1, idx+32 {
spendHash := spendHashes[idx : idx+32]
if !bytes.Equal(targetSpendHash[:], spendHash) {
newSpendHashes = append(newSpendHashes, spendHash...)
}
}
// If there aren't any entries left after filtering them, then we can
// remove the record completely. Otherwise, we'll store the filtered
// records.
var err error
if len(newSpendHashes) == 0 {
err = unminedInputs.Delete(outPointKey)
} else {
err = unminedInputs.Put(outPointKey, newSpendHashes)
}
if err != nil {
str := "failed to delete unmined input spend"
return storeError(ErrDatabase, str, err)
}
return nil
} | 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) == 0 {
return nil
}
// We'll iterate through them and pick all the ones that don't match the
// specified spending transaction.
var newSpendHashes []byte
numHashes := len(spendHashes) / 32
for i, idx := 0, 0; i < numHashes; i, idx = i+1, idx+32 {
spendHash := spendHashes[idx : idx+32]
if !bytes.Equal(targetSpendHash[:], spendHash) {
newSpendHashes = append(newSpendHashes, spendHash...)
}
}
// If there aren't any entries left after filtering them, then we can
// remove the record completely. Otherwise, we'll store the filtered
// records.
var err error
if len(newSpendHashes) == 0 {
err = unminedInputs.Delete(outPointKey)
} else {
err = unminedInputs.Put(outPointKey, newSpendHashes)
}
if err != nil {
str := "failed to delete unmined input spend"
return storeError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"deleteRawUnminedInput",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"outPointKey",
"[",
"]",
"byte",
",",
"targetSpendHash",
"chainhash",
".",
"Hash",
")",
"error",
"{",
"unminedInputs",
":=",
"ns",
".",
"NestedReadWriteBucket",
"(",
"bucketUnmine... | // 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",
version, latestVersion)
return storeError(ErrNeedsUpgrade, str, nil)
}
if version > latestVersion {
str := fmt.Sprintf("version recorded version %d is newer that "+
"latest understood version %d", version, latestVersion)
return storeError(ErrUnknownVersion, str, nil)
}
return nil
} | 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",
version, latestVersion)
return storeError(ErrNeedsUpgrade, str, nil)
}
if version > latestVersion {
str := fmt.Sprintf("version recorded version %d is newer that "+
"latest understood version %d", version, latestVersion)
return storeError(ErrUnknownVersion, str, nil)
}
return nil
} | [
"func",
"openStore",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
")",
"error",
"{",
"version",
",",
"err",
":=",
"fetchVersion",
"(",
"ns",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"latestVersion",
":=",
"getLatestVersion... | // 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 storeError(ErrDatabase, str, err)
}
if _, err := ns.CreateBucket(bucketCredits); err != nil {
str := "failed to create credits bucket"
return storeError(ErrDatabase, str, err)
}
if _, err := ns.CreateBucket(bucketDebits); err != nil {
str := "failed to create debits bucket"
return storeError(ErrDatabase, str, err)
}
if _, err := ns.CreateBucket(bucketUnspent); err != nil {
str := "failed to create unspent bucket"
return storeError(ErrDatabase, str, err)
}
if _, err := ns.CreateBucket(bucketUnmined); err != nil {
str := "failed to create unmined bucket"
return storeError(ErrDatabase, str, err)
}
if _, err := ns.CreateBucket(bucketUnminedCredits); err != nil {
str := "failed to create unmined credits bucket"
return storeError(ErrDatabase, str, err)
}
if _, err := ns.CreateBucket(bucketUnminedInputs); err != nil {
str := "failed to create unmined inputs bucket"
return storeError(ErrDatabase, str, err)
}
return nil
} | 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 storeError(ErrDatabase, str, err)
}
if _, err := ns.CreateBucket(bucketCredits); err != nil {
str := "failed to create credits bucket"
return storeError(ErrDatabase, str, err)
}
if _, err := ns.CreateBucket(bucketDebits); err != nil {
str := "failed to create debits bucket"
return storeError(ErrDatabase, str, err)
}
if _, err := ns.CreateBucket(bucketUnspent); err != nil {
str := "failed to create unspent bucket"
return storeError(ErrDatabase, str, err)
}
if _, err := ns.CreateBucket(bucketUnmined); err != nil {
str := "failed to create unmined bucket"
return storeError(ErrDatabase, str, err)
}
if _, err := ns.CreateBucket(bucketUnminedCredits); err != nil {
str := "failed to create unmined credits bucket"
return storeError(ErrDatabase, str, err)
}
if _, err := ns.CreateBucket(bucketUnminedInputs); err != nil {
str := "failed to create unmined inputs bucket"
return storeError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"createBuckets",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
")",
"error",
"{",
"if",
"_",
",",
"err",
":=",
"ns",
".",
"CreateBucket",
"(",
"bucketBlocks",
")",
";",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"failed to create blocks bucket\"",
"\n"... | // 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"
return storeError(ErrDatabase, str, err)
}
if err := ns.DeleteNestedBucket(bucketCredits); err != nil {
str := "failed to delete credits bucket"
return storeError(ErrDatabase, str, err)
}
if err := ns.DeleteNestedBucket(bucketDebits); err != nil {
str := "failed to delete debits bucket"
return storeError(ErrDatabase, str, err)
}
if err := ns.DeleteNestedBucket(bucketUnspent); err != nil {
str := "failed to delete unspent bucket"
return storeError(ErrDatabase, str, err)
}
if err := ns.DeleteNestedBucket(bucketUnmined); err != nil {
str := "failed to delete unmined bucket"
return storeError(ErrDatabase, str, err)
}
if err := ns.DeleteNestedBucket(bucketUnminedCredits); err != nil {
str := "failed to delete unmined credits bucket"
return storeError(ErrDatabase, str, err)
}
if err := ns.DeleteNestedBucket(bucketUnminedInputs); err != nil {
str := "failed to delete unmined inputs bucket"
return storeError(ErrDatabase, str, err)
}
return nil
} | 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"
return storeError(ErrDatabase, str, err)
}
if err := ns.DeleteNestedBucket(bucketCredits); err != nil {
str := "failed to delete credits bucket"
return storeError(ErrDatabase, str, err)
}
if err := ns.DeleteNestedBucket(bucketDebits); err != nil {
str := "failed to delete debits bucket"
return storeError(ErrDatabase, str, err)
}
if err := ns.DeleteNestedBucket(bucketUnspent); err != nil {
str := "failed to delete unspent bucket"
return storeError(ErrDatabase, str, err)
}
if err := ns.DeleteNestedBucket(bucketUnmined); err != nil {
str := "failed to delete unmined bucket"
return storeError(ErrDatabase, str, err)
}
if err := ns.DeleteNestedBucket(bucketUnminedCredits); err != nil {
str := "failed to delete unmined credits bucket"
return storeError(ErrDatabase, str, err)
}
if err := ns.DeleteNestedBucket(bucketUnminedInputs); err != nil {
str := "failed to delete unmined inputs bucket"
return storeError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"deleteBuckets",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
")",
"error",
"{",
"if",
"err",
":=",
"ns",
".",
"DeleteNestedBucket",
"(",
"bucketBlocks",
")",
";",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"failed to delete blocks bucket\"",
"\n",
"ret... | // 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",
":=",
"\"no transaction store... | // 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",
"(",
"\"session is closed\"",
")",
"\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",
"(",
"\"session is closed\"",
")",
"\n",
"}",
"\n",
"s",
".",
"writeMess... | // 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",
"(",
"\"session is already closed\"",
")",
"\n",
"}",
"\n",
"s",
".",
"writeMessage",
"(",
"&",
"envelope... | // 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: func(*Session, []byte) {},
messageHandlerBinary: func(*Session, []byte) {},
messageSentHandler: func(*Session, []byte) {},
messageSentHandlerBinary: func(*Session, []byte) {},
errorHandler: func(*Session, error) {},
closeHandler: nil,
connectHandler: func(*Session) {},
disconnectHandler: func(*Session) {},
pongHandler: func(*Session) {},
hub: hub,
}
} | 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(*Session, []byte) {},
messageHandlerBinary: func(*Session, []byte) {},
messageSentHandler: func(*Session, []byte) {},
messageSentHandlerBinary: func(*Session, []byte) {},
errorHandler: func(*Session, error) {},
closeHandler: nil,
connectHandler: func(*Session) {},
disconnectHandler: func(*Session) {},
pongHandler: func(*Session) {},
hub: hub,
}
} | [
"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 close messages as
// described in the section on Control Frames above.
//
// The connection read methods return a CloseError when a close frame is
// received. Most applications should handle close messages as part of their
// normal error handling. Applications should only set a close handler when the
// application must perform some action before sending a close frame back to
// the session. | [
"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: keys,
conn: conn,
output: make(chan *envelope, m.Config.MessageBufferSize),
melody: m,
open: true,
rwmutex: &sync.RWMutex{},
}
m.hub.register <- session
m.connectHandler(session)
go session.writePump()
session.readPump()
if !m.hub.closed() {
m.hub.unregister <- session
}
session.close()
m.disconnectHandler(session)
return nil
} | 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: keys,
conn: conn,
output: make(chan *envelope, m.Config.MessageBufferSize),
melody: m,
open: true,
rwmutex: &sync.RWMutex{},
}
m.hub.register <- session
m.connectHandler(session)
go session.writePump()
session.readPump()
if !m.hub.closed() {
m.hub.unregister <- session
}
session.close()
m.disconnectHandler(session)
return nil
} | [
"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",
"(",
"\"melody instance is closed\"",
")",
"\n",
"}",
"\n",
"me... | // 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",
"(",
"\"melody instance is closed\"",
")",
"\n",
"}",
"\n",... | // 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",
"(",
"\"melody instance is already closed\"",
")",
"\n",
"}",
"\n",
"m",
".",
"hub",
".",
"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(q)
}
fallthrough
default:
return nil
}
} | 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(q)
}
fallthrough
default:
return nil
}
} | [
"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,
},
Ptr: m.instanceAddr,
}
servRec := []dns.RR{rr}
// Get the instance records
instRecs := m.instanceRecords(dns.Question{
Name: m.instanceAddr,
Qtype: dns.TypeANY,
})
// Return the service record with the instance records
return append(servRec, instRecs...)
default:
return nil
}
} | 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,
},
Ptr: m.instanceAddr,
}
servRec := []dns.RR{rr}
// Get the instance records
instRecs := m.instanceRecords(dns.Question{
Name: m.instanceAddr,
Qtype: dns.TypeANY,
})
// Return the service record with the instance records
return append(servRec, instRecs...)
default:
return nil
}
} | [
"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{
Name: m.instanceAddr,
Qtype: dns.TypeTXT,
})...)
return recs
case dns.TypeA:
var rr []dns.RR
for _, ip := range m.IPs {
if ip4 := ip.To4(); ip4 != nil {
rr = append(rr, &dns.A{
Hdr: dns.RR_Header{
Name: m.HostName,
Rrtype: dns.TypeA,
Class: dns.ClassINET,
Ttl: defaultTTL,
},
A: ip4,
})
}
}
return rr
case dns.TypeAAAA:
var rr []dns.RR
for _, ip := range m.IPs {
if ip.To4() != nil {
// TODO(reddaly): IPv4 addresses could be encoded in IPv6 format and
// putinto AAAA records, but the current logic puts ipv4-encodable
// addresses into the A records exclusively. Perhaps this should be
// configurable?
continue
}
if ip16 := ip.To16(); ip16 != nil {
rr = append(rr, &dns.AAAA{
Hdr: dns.RR_Header{
Name: m.HostName,
Rrtype: dns.TypeAAAA,
Class: dns.ClassINET,
Ttl: defaultTTL,
},
AAAA: ip16,
})
}
}
return rr
case dns.TypeSRV:
// Create the SRV Record
srv := &dns.SRV{
Hdr: dns.RR_Header{
Name: q.Name,
Rrtype: dns.TypeSRV,
Class: dns.ClassINET,
Ttl: defaultTTL,
},
Priority: 10,
Weight: 1,
Port: uint16(m.Port),
Target: m.HostName,
}
recs := []dns.RR{srv}
// Add the A record
recs = append(recs, m.instanceRecords(dns.Question{
Name: m.instanceAddr,
Qtype: dns.TypeA,
})...)
// Add the AAAA record
recs = append(recs, m.instanceRecords(dns.Question{
Name: m.instanceAddr,
Qtype: dns.TypeAAAA,
})...)
return recs
case dns.TypeTXT:
txt := &dns.TXT{
Hdr: dns.RR_Header{
Name: q.Name,
Rrtype: dns.TypeTXT,
Class: dns.ClassINET,
Ttl: defaultTTL,
},
Txt: m.TXT,
}
return []dns.RR{txt}
}
return nil
} | 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{
Name: m.instanceAddr,
Qtype: dns.TypeTXT,
})...)
return recs
case dns.TypeA:
var rr []dns.RR
for _, ip := range m.IPs {
if ip4 := ip.To4(); ip4 != nil {
rr = append(rr, &dns.A{
Hdr: dns.RR_Header{
Name: m.HostName,
Rrtype: dns.TypeA,
Class: dns.ClassINET,
Ttl: defaultTTL,
},
A: ip4,
})
}
}
return rr
case dns.TypeAAAA:
var rr []dns.RR
for _, ip := range m.IPs {
if ip.To4() != nil {
// TODO(reddaly): IPv4 addresses could be encoded in IPv6 format and
// putinto AAAA records, but the current logic puts ipv4-encodable
// addresses into the A records exclusively. Perhaps this should be
// configurable?
continue
}
if ip16 := ip.To16(); ip16 != nil {
rr = append(rr, &dns.AAAA{
Hdr: dns.RR_Header{
Name: m.HostName,
Rrtype: dns.TypeAAAA,
Class: dns.ClassINET,
Ttl: defaultTTL,
},
AAAA: ip16,
})
}
}
return rr
case dns.TypeSRV:
// Create the SRV Record
srv := &dns.SRV{
Hdr: dns.RR_Header{
Name: q.Name,
Rrtype: dns.TypeSRV,
Class: dns.ClassINET,
Ttl: defaultTTL,
},
Priority: 10,
Weight: 1,
Port: uint16(m.Port),
Target: m.HostName,
}
recs := []dns.RR{srv}
// Add the A record
recs = append(recs, m.instanceRecords(dns.Question{
Name: m.instanceAddr,
Qtype: dns.TypeA,
})...)
// Add the AAAA record
recs = append(recs, m.instanceRecords(dns.Question{
Name: m.instanceAddr,
Qtype: dns.TypeAAAA,
})...)
return recs
case dns.TypeTXT:
txt := &dns.TXT{
Hdr: dns.RR_Header{
Name: q.Name,
Rrtype: dns.TypeTXT,
Class: dns.ClassINET,
Ttl: defaultTTL,
},
Txt: m.TXT,
}
return []dns.RR{txt}
}
return nil
} | [
"func",
"(",
"m",
"*",
"MDNSService",
")",
"instanceRecords",
"(",
"q",
"dns",
".",
"Question",
")",
"[",
"]",
"dns",
".",
"RR",
"{",
"switch",
"q",
".",
"Qtype",
"{",
"case",
"dns",
".",
"TypeANY",
":",
"recs",
":=",
"m",
".",
"instanceRecords",
"... | // 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("No multicast listeners could be started")
}
s := &Server{
config: config,
ipv4List: ipv4List,
ipv6List: ipv6List,
shutdownCh: make(chan struct{}),
}
if ipv4List != nil {
go s.recv(s.ipv4List)
}
if ipv6List != nil {
go s.recv(s.ipv6List)
}
return s, nil
} | 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("No multicast listeners could be started")
}
s := &Server{
config: config,
ipv4List: ipv4List,
ipv6List: ipv6List,
shutdownCh: make(chan struct{}),
}
if ipv4List != nil {
go s.recv(s.ipv4List)
}
if ipv6List != nil {
go s.recv(s.ipv6List)
}
return s, nil
} | [
"func",
"NewServer",
"(",
"config",
"*",
"Config",
")",
"(",
"*",
"Server",
",",
"error",
")",
"{",
"ipv4List",
",",
"_",
":=",
"net",
".",
"ListenMulticastUDP",
"(",
"\"udp4\"",
",",
"config",
".",
"Iface",
",",
"ipv4Addr",
")",
"\n",
"ipv6List",
",",... | // 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",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"close",
"(",
"s",
".",
"... | // 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 with RFC 6762. For example, the unicast bit should be
// ignored if the records in question are close to TTL expiration. For now,
// we just use the unicast bit to make the decision, as per the spec:
// RFC 6762, section 18.12. Repurposing of Top Bit of qclass in Question
// Section
//
// In the Question Section of a Multicast DNS query, the top bit of the
// qclass field is used to indicate that unicast responses are preferred
// for this particular question. (See Section 5.4.)
if q.Qclass&(1<<15) != 0 || forceUnicastResponses {
return nil, records
}
return records, nil
} | 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 with RFC 6762. For example, the unicast bit should be
// ignored if the records in question are close to TTL expiration. For now,
// we just use the unicast bit to make the decision, as per the spec:
// RFC 6762, section 18.12. Repurposing of Top Bit of qclass in Question
// Section
//
// In the Question Section of a Multicast DNS query, the top bit of the
// qclass field is used to indicate that unicast responses are preferred
// for this particular question. (See Section 5.4.)
if q.Qclass&(1<<15) != 0 || forceUnicastResponses {
return nil, records
}
return records, nil
} | [
"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() != nil {
_, err = s.ipv4List.WriteToUDP(buf, addr)
return err
} else {
_, err = s.ipv6List.WriteToUDP(buf, addr)
return err
}
} | 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() != nil {
_, err = s.ipv4List.WriteToUDP(buf, addr)
return err
} else {
_, err = s.ipv6List.WriteToUDP(buf, addr)
return err
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"sendResponse",
"(",
"resp",
"*",
"dns",
".",
"Msg",
",",
"from",
"net",
".",
"Addr",
",",
"unicast",
"bool",
")",
"error",
"{",
"buf",
",",
"err",
":=",
"resp",
".",
"Pack",
"(",
")",
"\n",
"if",
"err",
"!... | // 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",
":",
"\"local\"",
",",
"Timeout",
":",
"time",
".",
"Second",
",",
"Entries",
":",
"make",
"(",
"c... | // 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 set
if params.Domain == "" {
params.Domain = "local"
}
if params.Timeout == 0 {
params.Timeout = time.Second
}
// Run the query
return client.query(params)
} | 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 set
if params.Domain == "" {
params.Domain = "local"
}
if params.Timeout == 0 {
params.Timeout = time.Second
}
// Run the query
return client.query(params)
} | [
"func",
"Query",
"(",
"params",
"*",
"QueryParam",
")",
"error",
"{",
"client",
",",
"err",
":=",
"newClient",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"client",
".",
"Close",
"(",
")",
"\n",
"if",
... | // 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 := net.ListenUDP("udp6", &net.UDPAddr{IP: net.IPv6zero, Port: 0})
if err != nil {
log.Printf("[ERR] mdns: Failed to bind to udp6 port: %v", err)
}
if uconn4 == nil && uconn6 == nil {
return nil, fmt.Errorf("failed to bind to any unicast udp port")
}
mconn4, err := net.ListenMulticastUDP("udp4", nil, ipv4Addr)
if err != nil {
log.Printf("[ERR] mdns: Failed to bind to udp4 port: %v", err)
}
mconn6, err := net.ListenMulticastUDP("udp6", nil, ipv6Addr)
if err != nil {
log.Printf("[ERR] mdns: Failed to bind to udp6 port: %v", err)
}
if mconn4 == nil && mconn6 == nil {
return nil, fmt.Errorf("failed to bind to any multicast udp port")
}
c := &client{
ipv4MulticastConn: mconn4,
ipv6MulticastConn: mconn6,
ipv4UnicastConn: uconn4,
ipv6UnicastConn: uconn6,
closedCh: make(chan struct{}),
}
return c, nil
} | 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 := net.ListenUDP("udp6", &net.UDPAddr{IP: net.IPv6zero, Port: 0})
if err != nil {
log.Printf("[ERR] mdns: Failed to bind to udp6 port: %v", err)
}
if uconn4 == nil && uconn6 == nil {
return nil, fmt.Errorf("failed to bind to any unicast udp port")
}
mconn4, err := net.ListenMulticastUDP("udp4", nil, ipv4Addr)
if err != nil {
log.Printf("[ERR] mdns: Failed to bind to udp4 port: %v", err)
}
mconn6, err := net.ListenMulticastUDP("udp6", nil, ipv6Addr)
if err != nil {
log.Printf("[ERR] mdns: Failed to bind to udp6 port: %v", err)
}
if mconn4 == nil && mconn6 == nil {
return nil, fmt.Errorf("failed to bind to any multicast udp port")
}
c := &client{
ipv4MulticastConn: mconn4,
ipv6MulticastConn: mconn6,
ipv4UnicastConn: uconn4,
ipv6UnicastConn: uconn6,
closedCh: make(chan struct{}),
}
return c, nil
} | [
"func",
"newClient",
"(",
")",
"(",
"*",
"client",
",",
"error",
")",
"{",
"uconn4",
",",
"err",
":=",
"net",
".",
"ListenUDP",
"(",
"\"udp4\"",
",",
"&",
"net",
".",
"UDPAddr",
"{",
"IP",
":",
"net",
".",
"IPv4zero",
",",
"Port",
":",
"0",
"}",
... | // 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.ipv6UnicastConn.Close()
}
if c.ipv4MulticastConn != nil {
c.ipv4MulticastConn.Close()
}
if c.ipv6MulticastConn != nil {
c.ipv6MulticastConn.Close()
}
return nil
} | 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.ipv6UnicastConn.Close()
}
if c.ipv4MulticastConn != nil {
c.ipv4MulticastConn.Close()
}
if c.ipv6MulticastConn != nil {
c.ipv6MulticastConn.Close()
}
return nil
} | [
"func",
"(",
"c",
"*",
"client",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"!",
"atomic",
".",
"CompareAndSwapInt32",
"(",
"&",
"c",
".",
"closed",
",",
"0",
",",
"1",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"... | // 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.ipv4MulticastConn)
if err := p.SetMulticastInterface(iface); err != nil {
return err
}
p2 = ipv6.NewPacketConn(c.ipv6MulticastConn)
if err := p2.SetMulticastInterface(iface); err != nil {
return err
}
return nil
} | 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.ipv4MulticastConn)
if err := p.SetMulticastInterface(iface); err != nil {
return err
}
p2 = ipv6.NewPacketConn(c.ipv6MulticastConn)
if err := p2.SetMulticastInterface(iface); err != nil {
return err
}
return nil
} | [
"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)
continue
}
msg := new(dns.Msg)
if err := msg.Unpack(buf[:n]); err != nil {
log.Printf("[ERR] mdns: Failed to unpack packet: %v", err)
continue
}
select {
case msgCh <- msg:
case <-c.closedCh:
return
}
}
} | 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)
continue
}
msg := new(dns.Msg)
if err := msg.Unpack(buf[:n]); err != nil {
log.Printf("[ERR] mdns: Failed to unpack packet: %v", err)
continue
}
select {
case msgCh <- msg:
case <-c.closedCh:
return
}
}
} | [
"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",
")",
"{",
"C",
".",
"Clear",
"(",
"client",
".",
"api",
")",
"\n",
"C",
".",
"Free",
"(",
"client",
".",
"api",
")",
"\n",
"if",
"client",
".",
"pixImage",
"!=",... | // 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("cannot detect the stat of specified file: %v", err)
}
if client.pixImage != nil {
C.DestroyPixImage(client.pixImage)
client.pixImage = nil
}
p := C.CString(imagepath)
defer C.free(unsafe.Pointer(p))
img := C.CreatePixImageByFilePath(p)
client.pixImage = img
return nil
} | 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("cannot detect the stat of specified file: %v", err)
}
if client.pixImage != nil {
C.DestroyPixImage(client.pixImage)
client.pixImage = nil
}
p := C.CString(imagepath)
defer C.free(unsafe.Pointer(p))
img := C.CreatePixImageByFilePath(p)
client.pixImage = img
return nil
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"SetImage",
"(",
"imagepath",
"string",
")",
"error",
"{",
"if",
"client",
".",
"api",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"TessBaseAPI is not constructed, please use `gosseract.NewClient`\"",
")",
... | // 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)
client.pixImage = nil
}
img := C.CreatePixImageFromBytes((*C.uchar)(unsafe.Pointer(&data[0])), C.int(len(data)))
client.pixImage = img
return nil
} | 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)
client.pixImage = nil
}
img := C.CreatePixImageFromBytes((*C.uchar)(unsafe.Pointer(&data[0])), C.int(len(data)))
client.pixImage = img
return nil
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"SetImageFromBytes",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"client",
".",
"api",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"TessBaseAPI is not constructed, please use `gosseract.NewClien... | // 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",
"(",
"\"languages cannot be empty\"",
")",
"\n",
"}",
"\n",
"cli... | // 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(level))
length := int(boxArray.length)
defer C.free(unsafe.Pointer(boxArray.boxes))
defer C.free(unsafe.Pointer(boxArray))
for i := 0; i < length; i++ {
// cast to bounding_box: boxes + i*sizeof(box)
box := (*C.struct_bounding_box)(unsafe.Pointer(uintptr(unsafe.Pointer(boxArray.boxes)) + uintptr(i)*unsafe.Sizeof(C.struct_bounding_box{})))
out = append(out, BoundingBox{
Box: image.Rect(int(box.x1), int(box.y1), int(box.x2), int(box.y2)),
Word: C.GoString(box.word),
Confidence: float64(box.confidence),
})
}
return
} | 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(level))
length := int(boxArray.length)
defer C.free(unsafe.Pointer(boxArray.boxes))
defer C.free(unsafe.Pointer(boxArray))
for i := 0; i < length; i++ {
// cast to bounding_box: boxes + i*sizeof(box)
box := (*C.struct_bounding_box)(unsafe.Pointer(uintptr(unsafe.Pointer(boxArray.boxes)) + uintptr(i)*unsafe.Sizeof(C.struct_bounding_box{})))
out = append(out, BoundingBox{
Box: image.Rect(int(box.x1), int(box.y1), int(box.x2), int(box.y2)),
Word: C.GoString(box.word),
Confidence: float64(box.confidence),
})
}
return
} | [
"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()
runner := newQueryRunner(q)
return runner.Run(ctx, peers)
} | 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()
runner := newQueryRunner(q)
return runner.Run(ctx, peers)
} | [
"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",
")",
"{",
"s",
".",
"Close",
"(",
")",
"\n",
"}",
... | // 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()
rpmes, err := ms.SendRequest(ctx, pmes)
if err != nil {
stats.Record(ctx, metrics.SentRequestErrors.M(1))
return nil, err
}
// update the peer (on valid msgs only)
dht.updateFromMessage(ctx, p, rpmes)
stats.Record(
ctx,
metrics.SentRequests.M(1),
metrics.SentBytes.M(int64(pmes.Size())),
metrics.OutboundRequestLatency.M(
float64(time.Since(start))/float64(time.Millisecond),
),
)
dht.peerstore.RecordLatency(p, time.Since(start))
logger.Event(ctx, "dhtReceivedMessage", dht.self, p, rpmes)
return rpmes, nil
} | 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()
rpmes, err := ms.SendRequest(ctx, pmes)
if err != nil {
stats.Record(ctx, metrics.SentRequestErrors.M(1))
return nil, err
}
// update the peer (on valid msgs only)
dht.updateFromMessage(ctx, p, rpmes)
stats.Record(
ctx,
metrics.SentRequests.M(1),
metrics.SentBytes.M(int64(pmes.Size())),
metrics.OutboundRequestLatency.M(
float64(time.Since(start))/float64(time.Millisecond),
),
)
dht.peerstore.RecordLatency(p, time.Since(start))
logger.Event(ctx, "dhtReceivedMessage", dht.self, p, rpmes)
return rpmes, nil
} | [
"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 != nil {
stats.Record(ctx, metrics.SentMessageErrors.M(1))
return err
}
stats.Record(
ctx,
metrics.SentMessages.M(1),
metrics.SentBytes.M(int64(pmes.Size())),
)
logger.Event(ctx, "dhtSentMessage", dht.self, p, pmes)
return nil
} | 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 != nil {
stats.Record(ctx, metrics.SentMessageErrors.M(1))
return err
}
stats.Record(
ctx,
metrics.SentMessages.M(1),
metrics.SentBytes.M(int64(pmes.Size())),
)
logger.Event(ctx, "dhtSentMessage", dht.self, p, pmes)
return nil
} | [
"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 peer.ID, KValue)
// since the query doesnt actually pass our context down
// we have to hack this here. whyrusleeping isnt a huge fan of goprocess
parent := ctx
query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
// For DHT query command
notif.PublishQueryEvent(parent, ¬if.QueryEvent{
Type: notif.SendingQuery,
ID: p,
})
pmes, err := dht.findPeerSingle(ctx, p, peer.ID(key))
if err != nil {
logger.Debugf("error getting closer peers: %s", err)
return nil, err
}
peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())
// For DHT query command
notif.PublishQueryEvent(parent, ¬if.QueryEvent{
Type: notif.PeerResponse,
ID: p,
Responses: peers,
})
return &dhtQueryResult{closerPeers: peers}, nil
})
go func() {
defer close(out)
defer e.Done()
// run it!
res, err := query.Run(ctx, tablepeers)
if err != nil {
logger.Debugf("closestPeers query run error: %s", err)
}
if res != nil && res.queriedSet != nil {
sorted := kb.SortClosestPeers(res.queriedSet.Peers(), kb.ConvertKey(key))
if len(sorted) > KValue {
sorted = sorted[:KValue]
}
for _, p := range sorted {
out <- p
}
}
}()
return out, nil
} | 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 peer.ID, KValue)
// since the query doesnt actually pass our context down
// we have to hack this here. whyrusleeping isnt a huge fan of goprocess
parent := ctx
query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
// For DHT query command
notif.PublishQueryEvent(parent, ¬if.QueryEvent{
Type: notif.SendingQuery,
ID: p,
})
pmes, err := dht.findPeerSingle(ctx, p, peer.ID(key))
if err != nil {
logger.Debugf("error getting closer peers: %s", err)
return nil, err
}
peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())
// For DHT query command
notif.PublishQueryEvent(parent, ¬if.QueryEvent{
Type: notif.PeerResponse,
ID: p,
Responses: peers,
})
return &dhtQueryResult{closerPeers: peers}, nil
})
go func() {
defer close(out)
defer e.Done()
// run it!
res, err := query.Run(ctx, tablepeers)
if err != nil {
logger.Debugf("closestPeers query run error: %s", err)
}
if res != nil && res.queriedSet != nil {
sorted := kb.SortClosestPeers(res.queriedSet.Peers(), kb.ConvertKey(key))
if len(sorted) > KValue {
sorted = sorted[:KValue]
}
for _, p := range sorted {
out <- p
}
}
}()
return out, nil
} | [
"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 func() {
for {
err := dht.runBootstrap(ctx, cfg)
if err != nil {
logger.Warningf("error bootstrapping: %s", err)
}
select {
case <-time.After(cfg.Period):
case <-ctx.Done():
return
}
}
}()
return nil
} | 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 func() {
for {
err := dht.runBootstrap(ctx, cfg)
if err != nil {
logger.Warningf("error bootstrapping: %s", err)
}
select {
case <-time.After(cfg.Period):
case <-ctx.Done():
return
}
}
}()
return nil
} | [
"func",
"(",
"dht",
"*",
"IpfsDHT",
")",
"BootstrapWithConfig",
"(",
"ctx",
"context",
".",
"Context",
",",
"cfg",
"BootstrapConfig",
")",
"error",
"{",
"if",
"cfg",
".",
"Queries",
"<=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"invalid number of ... | // 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",
"(",
"\"invalid number of querie... | // 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",
")",
"{",
"return",
"dht",
".",
"FindPeer",
"(",
"ctx",
",",
"target",
")",... | // 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 peer: %s", id, p)
return nil
default:
return err
}
} | 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 peer: %s", id, p)
return nil
default:
return err
}
} | [
"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() {
logger.Infof("finished bootstrap query (%d/%d) to %s (routing table size is now %d)",
n, cfg.Queries, target, dht.routingTable.Size())
}()
queryCtx, cancel := context.WithTimeout(ctx, cfg.Timeout)
defer cancel()
err := f(queryCtx)
if err == context.DeadlineExceeded && queryCtx.Err() == context.DeadlineExceeded && ctx.Err() == nil {
return nil
}
return err
}
// Do all but one of the bootstrap queries as random walks.
for i := 0; i < cfg.Queries; i++ {
err := doQuery(i, "random ID", dht.randomWalk)
if err != nil {
return err
}
}
// Find self to distribute peer info to our neighbors.
return doQuery(cfg.Queries, fmt.Sprintf("self: %s", dht.self), dht.selfWalk)
} | 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() {
logger.Infof("finished bootstrap query (%d/%d) to %s (routing table size is now %d)",
n, cfg.Queries, target, dht.routingTable.Size())
}()
queryCtx, cancel := context.WithTimeout(ctx, cfg.Timeout)
defer cancel()
err := f(queryCtx)
if err == context.DeadlineExceeded && queryCtx.Err() == context.DeadlineExceeded && ctx.Err() == nil {
return nil
}
return err
}
// Do all but one of the bootstrap queries as random walks.
for i := 0; i < cfg.Queries; i++ {
err := doQuery(i, "random ID", dht.randomWalk)
if err != nil {
return err
}
}
// Find self to distribute peer info to our neighbors.
return doQuery(cfg.Queries, fmt.Sprintf("self: %s", dht.self), dht.selfWalk)
} | [
"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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.