repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
decred/dcrdata
txhelpers/txhelpers.go
Update
func (a *AddressOutpoints) Update(txns []*TxWithBlockData, outpoints []*wire.OutPoint, prevOutpoint []PrevOut) { // Relevant outpoints a.Outpoints = append(a.Outpoints, outpoints...) // Previous outpoints (inputs) a.PrevOuts = append(a.PrevOuts, prevOutpoint...) // Referenced transactions for _, t := range txns { a.TxnsStore[t.Hash()] = t } }
go
func (a *AddressOutpoints) Update(txns []*TxWithBlockData, outpoints []*wire.OutPoint, prevOutpoint []PrevOut) { // Relevant outpoints a.Outpoints = append(a.Outpoints, outpoints...) // Previous outpoints (inputs) a.PrevOuts = append(a.PrevOuts, prevOutpoint...) // Referenced transactions for _, t := range txns { a.TxnsStore[t.Hash()] = t } }
[ "func", "(", "a", "*", "AddressOutpoints", ")", "Update", "(", "txns", "[", "]", "*", "TxWithBlockData", ",", "outpoints", "[", "]", "*", "wire", ".", "OutPoint", ",", "prevOutpoint", "[", "]", "PrevOut", ")", "{", "// Relevant outpoints", "a", ".", "Outpoints", "=", "append", "(", "a", ".", "Outpoints", ",", "outpoints", "...", ")", "\n\n", "// Previous outpoints (inputs)", "a", ".", "PrevOuts", "=", "append", "(", "a", ".", "PrevOuts", ",", "prevOutpoint", "...", ")", "\n\n", "// Referenced transactions", "for", "_", ",", "t", ":=", "range", "txns", "{", "a", ".", "TxnsStore", "[", "t", ".", "Hash", "(", ")", "]", "=", "t", "\n", "}", "\n", "}" ]
// Update appends the provided outpoints, and merges the transactions.
[ "Update", "appends", "the", "provided", "outpoints", "and", "merges", "the", "transactions", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L209-L221
train
decred/dcrdata
txhelpers/txhelpers.go
Merge
func (a *AddressOutpoints) Merge(ao *AddressOutpoints) { // Relevant outpoints a.Outpoints = append(a.Outpoints, ao.Outpoints...) // Previous outpoints (inputs) a.PrevOuts = append(a.PrevOuts, ao.PrevOuts...) // Referenced transactions for h, t := range ao.TxnsStore { a.TxnsStore[h] = t } }
go
func (a *AddressOutpoints) Merge(ao *AddressOutpoints) { // Relevant outpoints a.Outpoints = append(a.Outpoints, ao.Outpoints...) // Previous outpoints (inputs) a.PrevOuts = append(a.PrevOuts, ao.PrevOuts...) // Referenced transactions for h, t := range ao.TxnsStore { a.TxnsStore[h] = t } }
[ "func", "(", "a", "*", "AddressOutpoints", ")", "Merge", "(", "ao", "*", "AddressOutpoints", ")", "{", "// Relevant outpoints", "a", ".", "Outpoints", "=", "append", "(", "a", ".", "Outpoints", ",", "ao", ".", "Outpoints", "...", ")", "\n\n", "// Previous outpoints (inputs)", "a", ".", "PrevOuts", "=", "append", "(", "a", ".", "PrevOuts", ",", "ao", ".", "PrevOuts", "...", ")", "\n\n", "// Referenced transactions", "for", "h", ",", "t", ":=", "range", "ao", ".", "TxnsStore", "{", "a", ".", "TxnsStore", "[", "h", "]", "=", "t", "\n", "}", "\n", "}" ]
// Merge concatenates the outpoints of two AddressOutpoints, and merges the // transactions.
[ "Merge", "concatenates", "the", "outpoints", "of", "two", "AddressOutpoints", "and", "merges", "the", "transactions", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L225-L236
train
decred/dcrdata
txhelpers/txhelpers.go
TxInvolvesAddress
func TxInvolvesAddress(msgTx *wire.MsgTx, addr string, c VerboseTransactionGetter, params *chaincfg.Params) (outpoints []*wire.OutPoint, prevOuts []PrevOut, prevTxs []*TxWithBlockData) { // The outpoints of this transaction paying to the address outpoints = TxPaysToAddress(msgTx, addr, params) // The inputs of this transaction funded by outpoints of previous // transactions paying to the address. prevOuts, prevTxs = TxConsumesOutpointWithAddress(msgTx, addr, c, params) return }
go
func TxInvolvesAddress(msgTx *wire.MsgTx, addr string, c VerboseTransactionGetter, params *chaincfg.Params) (outpoints []*wire.OutPoint, prevOuts []PrevOut, prevTxs []*TxWithBlockData) { // The outpoints of this transaction paying to the address outpoints = TxPaysToAddress(msgTx, addr, params) // The inputs of this transaction funded by outpoints of previous // transactions paying to the address. prevOuts, prevTxs = TxConsumesOutpointWithAddress(msgTx, addr, c, params) return }
[ "func", "TxInvolvesAddress", "(", "msgTx", "*", "wire", ".", "MsgTx", ",", "addr", "string", ",", "c", "VerboseTransactionGetter", ",", "params", "*", "chaincfg", ".", "Params", ")", "(", "outpoints", "[", "]", "*", "wire", ".", "OutPoint", ",", "prevOuts", "[", "]", "PrevOut", ",", "prevTxs", "[", "]", "*", "TxWithBlockData", ")", "{", "// The outpoints of this transaction paying to the address", "outpoints", "=", "TxPaysToAddress", "(", "msgTx", ",", "addr", ",", "params", ")", "\n", "// The inputs of this transaction funded by outpoints of previous", "// transactions paying to the address.", "prevOuts", ",", "prevTxs", "=", "TxConsumesOutpointWithAddress", "(", "msgTx", ",", "addr", ",", "c", ",", "params", ")", "\n", "return", "\n", "}" ]
// TxInvolvesAddress checks the inputs and outputs of a transaction for // involvement of the given address.
[ "TxInvolvesAddress", "checks", "the", "inputs", "and", "outputs", "of", "a", "transaction", "for", "involvement", "of", "the", "given", "address", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L240-L249
train
decred/dcrdata
txhelpers/txhelpers.go
TxOutpointsByAddr
func TxOutpointsByAddr(txAddrOuts MempoolAddressStore, msgTx *wire.MsgTx, params *chaincfg.Params) (newOuts int, addrs map[string]bool) { if txAddrOuts == nil { panic("TxAddressOutpoints: input map must be initialized: map[string]*AddressOutpoints") } // Check the addresses associated with the PkScript of each TxOut. txTree := TxTree(msgTx) hash := msgTx.TxHash() addrs = make(map[string]bool) for outIndex, txOut := range msgTx.TxOut { _, txOutAddrs, _, err := txscript.ExtractPkScriptAddrs(txOut.Version, txOut.PkScript, params) if err != nil { fmt.Printf("ExtractPkScriptAddrs: %v", err.Error()) continue } if len(txOutAddrs) == 0 { continue } newOuts++ // Check if we are watching any address for this TxOut. for _, txAddr := range txOutAddrs { addr := txAddr.EncodeAddress() op := wire.NewOutPoint(&hash, uint32(outIndex), txTree) addrOuts := txAddrOuts[addr] if addrOuts == nil { addrOuts = &AddressOutpoints{ Address: addr, Outpoints: []*wire.OutPoint{op}, } txAddrOuts[addr] = addrOuts addrs[addr] = true // new continue } if _, found := addrs[addr]; !found { addrs[addr] = false // not new to the address store } addrOuts.Outpoints = append(addrOuts.Outpoints, op) } } return }
go
func TxOutpointsByAddr(txAddrOuts MempoolAddressStore, msgTx *wire.MsgTx, params *chaincfg.Params) (newOuts int, addrs map[string]bool) { if txAddrOuts == nil { panic("TxAddressOutpoints: input map must be initialized: map[string]*AddressOutpoints") } // Check the addresses associated with the PkScript of each TxOut. txTree := TxTree(msgTx) hash := msgTx.TxHash() addrs = make(map[string]bool) for outIndex, txOut := range msgTx.TxOut { _, txOutAddrs, _, err := txscript.ExtractPkScriptAddrs(txOut.Version, txOut.PkScript, params) if err != nil { fmt.Printf("ExtractPkScriptAddrs: %v", err.Error()) continue } if len(txOutAddrs) == 0 { continue } newOuts++ // Check if we are watching any address for this TxOut. for _, txAddr := range txOutAddrs { addr := txAddr.EncodeAddress() op := wire.NewOutPoint(&hash, uint32(outIndex), txTree) addrOuts := txAddrOuts[addr] if addrOuts == nil { addrOuts = &AddressOutpoints{ Address: addr, Outpoints: []*wire.OutPoint{op}, } txAddrOuts[addr] = addrOuts addrs[addr] = true // new continue } if _, found := addrs[addr]; !found { addrs[addr] = false // not new to the address store } addrOuts.Outpoints = append(addrOuts.Outpoints, op) } } return }
[ "func", "TxOutpointsByAddr", "(", "txAddrOuts", "MempoolAddressStore", ",", "msgTx", "*", "wire", ".", "MsgTx", ",", "params", "*", "chaincfg", ".", "Params", ")", "(", "newOuts", "int", ",", "addrs", "map", "[", "string", "]", "bool", ")", "{", "if", "txAddrOuts", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Check the addresses associated with the PkScript of each TxOut.", "txTree", ":=", "TxTree", "(", "msgTx", ")", "\n", "hash", ":=", "msgTx", ".", "TxHash", "(", ")", "\n", "addrs", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "outIndex", ",", "txOut", ":=", "range", "msgTx", ".", "TxOut", "{", "_", ",", "txOutAddrs", ",", "_", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "txOut", ".", "Version", ",", "txOut", ".", "PkScript", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n", "if", "len", "(", "txOutAddrs", ")", "==", "0", "{", "continue", "\n", "}", "\n", "newOuts", "++", "\n\n", "// Check if we are watching any address for this TxOut.", "for", "_", ",", "txAddr", ":=", "range", "txOutAddrs", "{", "addr", ":=", "txAddr", ".", "EncodeAddress", "(", ")", "\n\n", "op", ":=", "wire", ".", "NewOutPoint", "(", "&", "hash", ",", "uint32", "(", "outIndex", ")", ",", "txTree", ")", "\n\n", "addrOuts", ":=", "txAddrOuts", "[", "addr", "]", "\n", "if", "addrOuts", "==", "nil", "{", "addrOuts", "=", "&", "AddressOutpoints", "{", "Address", ":", "addr", ",", "Outpoints", ":", "[", "]", "*", "wire", ".", "OutPoint", "{", "op", "}", ",", "}", "\n", "txAddrOuts", "[", "addr", "]", "=", "addrOuts", "\n", "addrs", "[", "addr", "]", "=", "true", "// new", "\n", "continue", "\n", "}", "\n", "if", "_", ",", "found", ":=", "addrs", "[", "addr", "]", ";", "!", "found", "{", "addrs", "[", "addr", "]", "=", "false", "// not new to the address store", "\n", "}", "\n", "addrOuts", ".", "Outpoints", "=", "append", "(", "addrOuts", ".", "Outpoints", ",", "op", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// TxOutpointsByAddr sets the Outpoints field for the AddressOutpoints stored in // the input MempoolAddressStore. For addresses not yet present in the // MempoolAddressStore, a new AddressOutpoints is added to the store. The // provided MempoolAddressStore must be initialized. The number of msgTx outputs // that pay to any address are counted and returned. The addresses paid to by // the transaction are listed in the output addrs map, where the value of the // stored bool indicates the address is new to the MempoolAddressStore.
[ "TxOutpointsByAddr", "sets", "the", "Outpoints", "field", "for", "the", "AddressOutpoints", "stored", "in", "the", "input", "MempoolAddressStore", ".", "For", "addresses", "not", "yet", "present", "in", "the", "MempoolAddressStore", "a", "new", "AddressOutpoints", "is", "added", "to", "the", "store", ".", "The", "provided", "MempoolAddressStore", "must", "be", "initialized", ".", "The", "number", "of", "msgTx", "outputs", "that", "pay", "to", "any", "address", "are", "counted", "and", "returned", ".", "The", "addresses", "paid", "to", "by", "the", "transaction", "are", "listed", "in", "the", "output", "addrs", "map", "where", "the", "value", "of", "the", "stored", "bool", "indicates", "the", "address", "is", "new", "to", "the", "MempoolAddressStore", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L264-L308
train
decred/dcrdata
txhelpers/txhelpers.go
TxPrevOutsByAddr
func TxPrevOutsByAddr(txAddrOuts MempoolAddressStore, txnsStore TxnsStore, msgTx *wire.MsgTx, c VerboseTransactionGetter, params *chaincfg.Params) (newPrevOuts int, addrs map[string]bool) { if txAddrOuts == nil { panic("TxPrevOutAddresses: input map must be initialized: map[string]*AddressOutpoints") } if txnsStore == nil { panic("TxPrevOutAddresses: input map must be initialized: map[string]*AddressOutpoints") } // Send all the raw transaction requests type promiseGetRawTransaction struct { result rpcclient.FutureGetRawTransactionVerboseResult inIdx int } promisesGetRawTransaction := make([]promiseGetRawTransaction, 0, len(msgTx.TxIn)) for inIdx, txIn := range msgTx.TxIn { hash := &txIn.PreviousOutPoint.Hash if zeroHash.IsEqual(hash) { continue // coinbase or stakebase } promisesGetRawTransaction = append(promisesGetRawTransaction, promiseGetRawTransaction{ result: c.GetRawTransactionVerboseAsync(hash), inIdx: inIdx, }) } addrs = make(map[string]bool) // For each TxIn of this transaction, inspect the previous outpoint. for i := range promisesGetRawTransaction { // Previous outpoint for this TxIn inIdx := promisesGetRawTransaction[i].inIdx prevOut := &msgTx.TxIn[inIdx].PreviousOutPoint hash := prevOut.Hash prevTxRaw, err := promisesGetRawTransaction[i].result.Receive() if err != nil { fmt.Printf("Unable to get raw transaction for %v: %v\n", hash, err) return } if prevTxRaw.Txid != hash.String() { fmt.Printf("TxPrevOutsByAddr error: %v != %v", prevTxRaw.Txid, hash.String()) continue } prevTx, err := MsgTxFromHex(prevTxRaw.Hex) if err != nil { fmt.Printf("TxPrevOutsByAddr: MsgTxFromHex failed: %s\n", err) continue } // prevOut.Index indicates which output. txOut := prevTx.TxOut[prevOut.Index] // Extract the addresses from this output's PkScript. _, txAddrs, _, err := txscript.ExtractPkScriptAddrs( txOut.Version, txOut.PkScript, params) if err != nil { fmt.Printf("TxPrevOutsByAddr: ExtractPkScriptAddrs: %v\n", err.Error()) continue } if len(txAddrs) == 0 { fmt.Printf("pkScript of a previous transaction output "+ "(%v:%d) unexpectedly encoded no addresses.", prevOut.Hash, prevOut.Index) continue } newPrevOuts++ // Put the previous outpoint's transaction in the txnsStore. txnsStore[hash] = &TxWithBlockData{ Tx: prevTx, BlockHeight: prevTxRaw.BlockHeight, BlockHash: prevTxRaw.BlockHash, } outpoint := wire.NewOutPoint(&hash, prevOut.Index, TxTree(prevTx)) prevOutExtended := PrevOut{ TxSpending: msgTx.TxHash(), InputIndex: inIdx, PreviousOutpoint: outpoint, } // For each address paid to by this previous outpoint, record the // previous outpoint and the containing transactions. for _, txAddr := range txAddrs { addr := txAddr.EncodeAddress() // Check if it is already in the address store. addrOuts := txAddrOuts[addr] if addrOuts == nil { // Insert into affected address map. addrs[addr] = true // new // Insert into the address store. txAddrOuts[addr] = &AddressOutpoints{ Address: addr, PrevOuts: []PrevOut{prevOutExtended}, } continue } // Address already in the address store, append the prevout. addrOuts.PrevOuts = append(addrOuts.PrevOuts, prevOutExtended) // See if the address was new before processing this transaction or // if it was added by a different prevout consumed by this // transaction. Only set new=false if this is the first occurrence // of this address in a prevout of this transaction. if _, found := addrs[addr]; !found { addrs[addr] = false // not new to the address store } } } return }
go
func TxPrevOutsByAddr(txAddrOuts MempoolAddressStore, txnsStore TxnsStore, msgTx *wire.MsgTx, c VerboseTransactionGetter, params *chaincfg.Params) (newPrevOuts int, addrs map[string]bool) { if txAddrOuts == nil { panic("TxPrevOutAddresses: input map must be initialized: map[string]*AddressOutpoints") } if txnsStore == nil { panic("TxPrevOutAddresses: input map must be initialized: map[string]*AddressOutpoints") } // Send all the raw transaction requests type promiseGetRawTransaction struct { result rpcclient.FutureGetRawTransactionVerboseResult inIdx int } promisesGetRawTransaction := make([]promiseGetRawTransaction, 0, len(msgTx.TxIn)) for inIdx, txIn := range msgTx.TxIn { hash := &txIn.PreviousOutPoint.Hash if zeroHash.IsEqual(hash) { continue // coinbase or stakebase } promisesGetRawTransaction = append(promisesGetRawTransaction, promiseGetRawTransaction{ result: c.GetRawTransactionVerboseAsync(hash), inIdx: inIdx, }) } addrs = make(map[string]bool) // For each TxIn of this transaction, inspect the previous outpoint. for i := range promisesGetRawTransaction { // Previous outpoint for this TxIn inIdx := promisesGetRawTransaction[i].inIdx prevOut := &msgTx.TxIn[inIdx].PreviousOutPoint hash := prevOut.Hash prevTxRaw, err := promisesGetRawTransaction[i].result.Receive() if err != nil { fmt.Printf("Unable to get raw transaction for %v: %v\n", hash, err) return } if prevTxRaw.Txid != hash.String() { fmt.Printf("TxPrevOutsByAddr error: %v != %v", prevTxRaw.Txid, hash.String()) continue } prevTx, err := MsgTxFromHex(prevTxRaw.Hex) if err != nil { fmt.Printf("TxPrevOutsByAddr: MsgTxFromHex failed: %s\n", err) continue } // prevOut.Index indicates which output. txOut := prevTx.TxOut[prevOut.Index] // Extract the addresses from this output's PkScript. _, txAddrs, _, err := txscript.ExtractPkScriptAddrs( txOut.Version, txOut.PkScript, params) if err != nil { fmt.Printf("TxPrevOutsByAddr: ExtractPkScriptAddrs: %v\n", err.Error()) continue } if len(txAddrs) == 0 { fmt.Printf("pkScript of a previous transaction output "+ "(%v:%d) unexpectedly encoded no addresses.", prevOut.Hash, prevOut.Index) continue } newPrevOuts++ // Put the previous outpoint's transaction in the txnsStore. txnsStore[hash] = &TxWithBlockData{ Tx: prevTx, BlockHeight: prevTxRaw.BlockHeight, BlockHash: prevTxRaw.BlockHash, } outpoint := wire.NewOutPoint(&hash, prevOut.Index, TxTree(prevTx)) prevOutExtended := PrevOut{ TxSpending: msgTx.TxHash(), InputIndex: inIdx, PreviousOutpoint: outpoint, } // For each address paid to by this previous outpoint, record the // previous outpoint and the containing transactions. for _, txAddr := range txAddrs { addr := txAddr.EncodeAddress() // Check if it is already in the address store. addrOuts := txAddrOuts[addr] if addrOuts == nil { // Insert into affected address map. addrs[addr] = true // new // Insert into the address store. txAddrOuts[addr] = &AddressOutpoints{ Address: addr, PrevOuts: []PrevOut{prevOutExtended}, } continue } // Address already in the address store, append the prevout. addrOuts.PrevOuts = append(addrOuts.PrevOuts, prevOutExtended) // See if the address was new before processing this transaction or // if it was added by a different prevout consumed by this // transaction. Only set new=false if this is the first occurrence // of this address in a prevout of this transaction. if _, found := addrs[addr]; !found { addrs[addr] = false // not new to the address store } } } return }
[ "func", "TxPrevOutsByAddr", "(", "txAddrOuts", "MempoolAddressStore", ",", "txnsStore", "TxnsStore", ",", "msgTx", "*", "wire", ".", "MsgTx", ",", "c", "VerboseTransactionGetter", ",", "params", "*", "chaincfg", ".", "Params", ")", "(", "newPrevOuts", "int", ",", "addrs", "map", "[", "string", "]", "bool", ")", "{", "if", "txAddrOuts", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "txnsStore", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Send all the raw transaction requests", "type", "promiseGetRawTransaction", "struct", "{", "result", "rpcclient", ".", "FutureGetRawTransactionVerboseResult", "\n", "inIdx", "int", "\n", "}", "\n", "promisesGetRawTransaction", ":=", "make", "(", "[", "]", "promiseGetRawTransaction", ",", "0", ",", "len", "(", "msgTx", ".", "TxIn", ")", ")", "\n\n", "for", "inIdx", ",", "txIn", ":=", "range", "msgTx", ".", "TxIn", "{", "hash", ":=", "&", "txIn", ".", "PreviousOutPoint", ".", "Hash", "\n", "if", "zeroHash", ".", "IsEqual", "(", "hash", ")", "{", "continue", "// coinbase or stakebase", "\n", "}", "\n", "promisesGetRawTransaction", "=", "append", "(", "promisesGetRawTransaction", ",", "promiseGetRawTransaction", "{", "result", ":", "c", ".", "GetRawTransactionVerboseAsync", "(", "hash", ")", ",", "inIdx", ":", "inIdx", ",", "}", ")", "\n", "}", "\n\n", "addrs", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n\n", "// For each TxIn of this transaction, inspect the previous outpoint.", "for", "i", ":=", "range", "promisesGetRawTransaction", "{", "// Previous outpoint for this TxIn", "inIdx", ":=", "promisesGetRawTransaction", "[", "i", "]", ".", "inIdx", "\n", "prevOut", ":=", "&", "msgTx", ".", "TxIn", "[", "inIdx", "]", ".", "PreviousOutPoint", "\n", "hash", ":=", "prevOut", ".", "Hash", "\n\n", "prevTxRaw", ",", "err", ":=", "promisesGetRawTransaction", "[", "i", "]", ".", "result", ".", "Receive", "(", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "hash", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "prevTxRaw", ".", "Txid", "!=", "hash", ".", "String", "(", ")", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "prevTxRaw", ".", "Txid", ",", "hash", ".", "String", "(", ")", ")", "\n", "continue", "\n", "}", "\n\n", "prevTx", ",", "err", ":=", "MsgTxFromHex", "(", "prevTxRaw", ".", "Hex", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "// prevOut.Index indicates which output.", "txOut", ":=", "prevTx", ".", "TxOut", "[", "prevOut", ".", "Index", "]", "\n", "// Extract the addresses from this output's PkScript.", "_", ",", "txAddrs", ",", "_", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "txOut", ".", "Version", ",", "txOut", ".", "PkScript", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n\n", "if", "len", "(", "txAddrs", ")", "==", "0", "{", "fmt", ".", "Printf", "(", "\"", "\"", "+", "\"", "\"", ",", "prevOut", ".", "Hash", ",", "prevOut", ".", "Index", ")", "\n", "continue", "\n", "}", "\n\n", "newPrevOuts", "++", "\n\n", "// Put the previous outpoint's transaction in the txnsStore.", "txnsStore", "[", "hash", "]", "=", "&", "TxWithBlockData", "{", "Tx", ":", "prevTx", ",", "BlockHeight", ":", "prevTxRaw", ".", "BlockHeight", ",", "BlockHash", ":", "prevTxRaw", ".", "BlockHash", ",", "}", "\n\n", "outpoint", ":=", "wire", ".", "NewOutPoint", "(", "&", "hash", ",", "prevOut", ".", "Index", ",", "TxTree", "(", "prevTx", ")", ")", "\n", "prevOutExtended", ":=", "PrevOut", "{", "TxSpending", ":", "msgTx", ".", "TxHash", "(", ")", ",", "InputIndex", ":", "inIdx", ",", "PreviousOutpoint", ":", "outpoint", ",", "}", "\n\n", "// For each address paid to by this previous outpoint, record the", "// previous outpoint and the containing transactions.", "for", "_", ",", "txAddr", ":=", "range", "txAddrs", "{", "addr", ":=", "txAddr", ".", "EncodeAddress", "(", ")", "\n\n", "// Check if it is already in the address store.", "addrOuts", ":=", "txAddrOuts", "[", "addr", "]", "\n", "if", "addrOuts", "==", "nil", "{", "// Insert into affected address map.", "addrs", "[", "addr", "]", "=", "true", "// new", "\n", "// Insert into the address store.", "txAddrOuts", "[", "addr", "]", "=", "&", "AddressOutpoints", "{", "Address", ":", "addr", ",", "PrevOuts", ":", "[", "]", "PrevOut", "{", "prevOutExtended", "}", ",", "}", "\n", "continue", "\n", "}", "\n\n", "// Address already in the address store, append the prevout.", "addrOuts", ".", "PrevOuts", "=", "append", "(", "addrOuts", ".", "PrevOuts", ",", "prevOutExtended", ")", "\n\n", "// See if the address was new before processing this transaction or", "// if it was added by a different prevout consumed by this", "// transaction. Only set new=false if this is the first occurrence", "// of this address in a prevout of this transaction.", "if", "_", ",", "found", ":=", "addrs", "[", "addr", "]", ";", "!", "found", "{", "addrs", "[", "addr", "]", "=", "false", "// not new to the address store", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// TxPrevOutsByAddr sets the PrevOuts field for the AddressOutpoints stored in // the MempoolAddressStore. For addresses not yet present in the // MempoolAddressStore, a new AddressOutpoints is added to the store. The // provided MempoolAddressStore must be initialized. A VerboseTransactionGetter // is required to retrieve the pkScripts for the previous outpoints. The number // of consumed previous outpoints that paid addresses in the provided // transaction are counted and returned. The addresses in the previous outpoints // are listed in the output addrs map, where the value of the stored bool // indicates the address is new to the MempoolAddressStore.
[ "TxPrevOutsByAddr", "sets", "the", "PrevOuts", "field", "for", "the", "AddressOutpoints", "stored", "in", "the", "MempoolAddressStore", ".", "For", "addresses", "not", "yet", "present", "in", "the", "MempoolAddressStore", "a", "new", "AddressOutpoints", "is", "added", "to", "the", "store", ".", "The", "provided", "MempoolAddressStore", "must", "be", "initialized", ".", "A", "VerboseTransactionGetter", "is", "required", "to", "retrieve", "the", "pkScripts", "for", "the", "previous", "outpoints", ".", "The", "number", "of", "consumed", "previous", "outpoints", "that", "paid", "addresses", "in", "the", "provided", "transaction", "are", "counted", "and", "returned", ".", "The", "addresses", "in", "the", "previous", "outpoints", "are", "listed", "in", "the", "output", "addrs", "map", "where", "the", "value", "of", "the", "stored", "bool", "indicates", "the", "address", "is", "new", "to", "the", "MempoolAddressStore", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L319-L436
train
decred/dcrdata
txhelpers/txhelpers.go
TxConsumesOutpointWithAddress
func TxConsumesOutpointWithAddress(msgTx *wire.MsgTx, addr string, c VerboseTransactionGetter, params *chaincfg.Params) (prevOuts []PrevOut, prevTxs []*TxWithBlockData) { // Send all the raw transaction requests type promiseGetRawTransaction struct { result rpcclient.FutureGetRawTransactionVerboseResult inIdx int } numPrevOut := len(msgTx.TxIn) promisesGetRawTransaction := make([]promiseGetRawTransaction, 0, numPrevOut) for inIdx, txIn := range msgTx.TxIn { hash := &txIn.PreviousOutPoint.Hash if zeroHash.IsEqual(hash) { continue // coinbase or stakebase } promisesGetRawTransaction = append(promisesGetRawTransaction, promiseGetRawTransaction{ result: c.GetRawTransactionVerboseAsync(hash), inIdx: inIdx, }) } // For each TxIn of this transaction, inspect the previous outpoint. for i := range promisesGetRawTransaction { // Previous outpoint for this TxIn inIdx := promisesGetRawTransaction[i].inIdx prevOut := &msgTx.TxIn[inIdx].PreviousOutPoint hash := prevOut.Hash prevTxRaw, err := promisesGetRawTransaction[i].result.Receive() if err != nil { fmt.Printf("Unable to get raw transaction for %v: %v\n", hash, err) return nil, nil } if prevTxRaw.Txid != hash.String() { fmt.Printf("%v != %v", prevTxRaw.Txid, hash.String()) return nil, nil } prevTx, err := MsgTxFromHex(prevTxRaw.Hex) if err != nil { fmt.Printf("MsgTxFromHex failed: %s\n", err) continue } // prevOut.Index indicates which output. txOut := prevTx.TxOut[prevOut.Index] // Extract the addresses from this output's PkScript. _, txAddrs, _, err := txscript.ExtractPkScriptAddrs( txOut.Version, txOut.PkScript, params) if err != nil { fmt.Printf("ExtractPkScriptAddrs: %v\n", err.Error()) continue } // For each address that matches the address of interest, record this // previous outpoint and the containing transactions. for _, txAddr := range txAddrs { addrstr := txAddr.EncodeAddress() if addr == addrstr { outpoint := wire.NewOutPoint(&hash, prevOut.Index, TxTree(prevTx)) prevOuts = append(prevOuts, PrevOut{ TxSpending: msgTx.TxHash(), InputIndex: inIdx, PreviousOutpoint: outpoint, }) prevTxs = append(prevTxs, &TxWithBlockData{ Tx: prevTx, BlockHeight: prevTxRaw.BlockHeight, BlockHash: prevTxRaw.BlockHash, }) } } } return }
go
func TxConsumesOutpointWithAddress(msgTx *wire.MsgTx, addr string, c VerboseTransactionGetter, params *chaincfg.Params) (prevOuts []PrevOut, prevTxs []*TxWithBlockData) { // Send all the raw transaction requests type promiseGetRawTransaction struct { result rpcclient.FutureGetRawTransactionVerboseResult inIdx int } numPrevOut := len(msgTx.TxIn) promisesGetRawTransaction := make([]promiseGetRawTransaction, 0, numPrevOut) for inIdx, txIn := range msgTx.TxIn { hash := &txIn.PreviousOutPoint.Hash if zeroHash.IsEqual(hash) { continue // coinbase or stakebase } promisesGetRawTransaction = append(promisesGetRawTransaction, promiseGetRawTransaction{ result: c.GetRawTransactionVerboseAsync(hash), inIdx: inIdx, }) } // For each TxIn of this transaction, inspect the previous outpoint. for i := range promisesGetRawTransaction { // Previous outpoint for this TxIn inIdx := promisesGetRawTransaction[i].inIdx prevOut := &msgTx.TxIn[inIdx].PreviousOutPoint hash := prevOut.Hash prevTxRaw, err := promisesGetRawTransaction[i].result.Receive() if err != nil { fmt.Printf("Unable to get raw transaction for %v: %v\n", hash, err) return nil, nil } if prevTxRaw.Txid != hash.String() { fmt.Printf("%v != %v", prevTxRaw.Txid, hash.String()) return nil, nil } prevTx, err := MsgTxFromHex(prevTxRaw.Hex) if err != nil { fmt.Printf("MsgTxFromHex failed: %s\n", err) continue } // prevOut.Index indicates which output. txOut := prevTx.TxOut[prevOut.Index] // Extract the addresses from this output's PkScript. _, txAddrs, _, err := txscript.ExtractPkScriptAddrs( txOut.Version, txOut.PkScript, params) if err != nil { fmt.Printf("ExtractPkScriptAddrs: %v\n", err.Error()) continue } // For each address that matches the address of interest, record this // previous outpoint and the containing transactions. for _, txAddr := range txAddrs { addrstr := txAddr.EncodeAddress() if addr == addrstr { outpoint := wire.NewOutPoint(&hash, prevOut.Index, TxTree(prevTx)) prevOuts = append(prevOuts, PrevOut{ TxSpending: msgTx.TxHash(), InputIndex: inIdx, PreviousOutpoint: outpoint, }) prevTxs = append(prevTxs, &TxWithBlockData{ Tx: prevTx, BlockHeight: prevTxRaw.BlockHeight, BlockHash: prevTxRaw.BlockHash, }) } } } return }
[ "func", "TxConsumesOutpointWithAddress", "(", "msgTx", "*", "wire", ".", "MsgTx", ",", "addr", "string", ",", "c", "VerboseTransactionGetter", ",", "params", "*", "chaincfg", ".", "Params", ")", "(", "prevOuts", "[", "]", "PrevOut", ",", "prevTxs", "[", "]", "*", "TxWithBlockData", ")", "{", "// Send all the raw transaction requests", "type", "promiseGetRawTransaction", "struct", "{", "result", "rpcclient", ".", "FutureGetRawTransactionVerboseResult", "\n", "inIdx", "int", "\n", "}", "\n", "numPrevOut", ":=", "len", "(", "msgTx", ".", "TxIn", ")", "\n", "promisesGetRawTransaction", ":=", "make", "(", "[", "]", "promiseGetRawTransaction", ",", "0", ",", "numPrevOut", ")", "\n\n", "for", "inIdx", ",", "txIn", ":=", "range", "msgTx", ".", "TxIn", "{", "hash", ":=", "&", "txIn", ".", "PreviousOutPoint", ".", "Hash", "\n", "if", "zeroHash", ".", "IsEqual", "(", "hash", ")", "{", "continue", "// coinbase or stakebase", "\n", "}", "\n", "promisesGetRawTransaction", "=", "append", "(", "promisesGetRawTransaction", ",", "promiseGetRawTransaction", "{", "result", ":", "c", ".", "GetRawTransactionVerboseAsync", "(", "hash", ")", ",", "inIdx", ":", "inIdx", ",", "}", ")", "\n", "}", "\n\n", "// For each TxIn of this transaction, inspect the previous outpoint.", "for", "i", ":=", "range", "promisesGetRawTransaction", "{", "// Previous outpoint for this TxIn", "inIdx", ":=", "promisesGetRawTransaction", "[", "i", "]", ".", "inIdx", "\n", "prevOut", ":=", "&", "msgTx", ".", "TxIn", "[", "inIdx", "]", ".", "PreviousOutPoint", "\n", "hash", ":=", "prevOut", ".", "Hash", "\n\n", "prevTxRaw", ",", "err", ":=", "promisesGetRawTransaction", "[", "i", "]", ".", "result", ".", "Receive", "(", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "hash", ",", "err", ")", "\n", "return", "nil", ",", "nil", "\n", "}", "\n\n", "if", "prevTxRaw", ".", "Txid", "!=", "hash", ".", "String", "(", ")", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "prevTxRaw", ".", "Txid", ",", "hash", ".", "String", "(", ")", ")", "\n", "return", "nil", ",", "nil", "\n", "}", "\n\n", "prevTx", ",", "err", ":=", "MsgTxFromHex", "(", "prevTxRaw", ".", "Hex", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "// prevOut.Index indicates which output.", "txOut", ":=", "prevTx", ".", "TxOut", "[", "prevOut", ".", "Index", "]", "\n", "// Extract the addresses from this output's PkScript.", "_", ",", "txAddrs", ",", "_", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "txOut", ".", "Version", ",", "txOut", ".", "PkScript", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n\n", "// For each address that matches the address of interest, record this", "// previous outpoint and the containing transactions.", "for", "_", ",", "txAddr", ":=", "range", "txAddrs", "{", "addrstr", ":=", "txAddr", ".", "EncodeAddress", "(", ")", "\n", "if", "addr", "==", "addrstr", "{", "outpoint", ":=", "wire", ".", "NewOutPoint", "(", "&", "hash", ",", "prevOut", ".", "Index", ",", "TxTree", "(", "prevTx", ")", ")", "\n", "prevOuts", "=", "append", "(", "prevOuts", ",", "PrevOut", "{", "TxSpending", ":", "msgTx", ".", "TxHash", "(", ")", ",", "InputIndex", ":", "inIdx", ",", "PreviousOutpoint", ":", "outpoint", ",", "}", ")", "\n", "prevTxs", "=", "append", "(", "prevTxs", ",", "&", "TxWithBlockData", "{", "Tx", ":", "prevTx", ",", "BlockHeight", ":", "prevTxRaw", ".", "BlockHeight", ",", "BlockHash", ":", "prevTxRaw", ".", "BlockHash", ",", "}", ")", "\n", "}", "\n", "}", "\n\n", "}", "\n", "return", "\n", "}" ]
// TxConsumesOutpointWithAddress checks a transaction for inputs that spend an // outpoint paying to the given address. Returned are the identified input // indexes and the corresponding previous outpoints determined.
[ "TxConsumesOutpointWithAddress", "checks", "a", "transaction", "for", "inputs", "that", "spend", "an", "outpoint", "paying", "to", "the", "given", "address", ".", "Returned", "are", "the", "identified", "input", "indexes", "and", "the", "corresponding", "previous", "outpoints", "determined", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L441-L518
train
decred/dcrdata
txhelpers/txhelpers.go
BlockConsumesOutpointWithAddresses
func BlockConsumesOutpointWithAddresses(block *dcrutil.Block, addrs map[string]TxAction, c RawTransactionGetter, params *chaincfg.Params) map[string][]*dcrutil.Tx { addrMap := make(map[string][]*dcrutil.Tx) checkForOutpointAddr := func(blockTxs []*dcrutil.Tx) { for _, tx := range blockTxs { for _, txIn := range tx.MsgTx().TxIn { prevOut := &txIn.PreviousOutPoint if bytes.Equal(zeroHash[:], prevOut.Hash[:]) { continue } // For each TxIn, check the indicated vout index in the txid of the // previous outpoint. // txrr, err := c.GetRawTransactionVerbose(&prevOut.Hash) prevTx, err := c.GetRawTransaction(&prevOut.Hash) if err != nil { fmt.Printf("Unable to get raw transaction for %s\n", prevOut.Hash.String()) continue } // prevOut.Index should tell us which one, but check all anyway for _, txOut := range prevTx.MsgTx().TxOut { _, txAddrs, _, err := txscript.ExtractPkScriptAddrs( txOut.Version, txOut.PkScript, params) if err != nil { fmt.Printf("ExtractPkScriptAddrs: %v\n", err.Error()) continue } for _, txAddr := range txAddrs { addrstr := txAddr.EncodeAddress() if _, ok := addrs[addrstr]; ok { if addrMap[addrstr] == nil { addrMap[addrstr] = make([]*dcrutil.Tx, 0) } addrMap[addrstr] = append(addrMap[addrstr], prevTx) } } } } } } checkForOutpointAddr(block.Transactions()) checkForOutpointAddr(block.STransactions()) return addrMap }
go
func BlockConsumesOutpointWithAddresses(block *dcrutil.Block, addrs map[string]TxAction, c RawTransactionGetter, params *chaincfg.Params) map[string][]*dcrutil.Tx { addrMap := make(map[string][]*dcrutil.Tx) checkForOutpointAddr := func(blockTxs []*dcrutil.Tx) { for _, tx := range blockTxs { for _, txIn := range tx.MsgTx().TxIn { prevOut := &txIn.PreviousOutPoint if bytes.Equal(zeroHash[:], prevOut.Hash[:]) { continue } // For each TxIn, check the indicated vout index in the txid of the // previous outpoint. // txrr, err := c.GetRawTransactionVerbose(&prevOut.Hash) prevTx, err := c.GetRawTransaction(&prevOut.Hash) if err != nil { fmt.Printf("Unable to get raw transaction for %s\n", prevOut.Hash.String()) continue } // prevOut.Index should tell us which one, but check all anyway for _, txOut := range prevTx.MsgTx().TxOut { _, txAddrs, _, err := txscript.ExtractPkScriptAddrs( txOut.Version, txOut.PkScript, params) if err != nil { fmt.Printf("ExtractPkScriptAddrs: %v\n", err.Error()) continue } for _, txAddr := range txAddrs { addrstr := txAddr.EncodeAddress() if _, ok := addrs[addrstr]; ok { if addrMap[addrstr] == nil { addrMap[addrstr] = make([]*dcrutil.Tx, 0) } addrMap[addrstr] = append(addrMap[addrstr], prevTx) } } } } } } checkForOutpointAddr(block.Transactions()) checkForOutpointAddr(block.STransactions()) return addrMap }
[ "func", "BlockConsumesOutpointWithAddresses", "(", "block", "*", "dcrutil", ".", "Block", ",", "addrs", "map", "[", "string", "]", "TxAction", ",", "c", "RawTransactionGetter", ",", "params", "*", "chaincfg", ".", "Params", ")", "map", "[", "string", "]", "[", "]", "*", "dcrutil", ".", "Tx", "{", "addrMap", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "dcrutil", ".", "Tx", ")", "\n\n", "checkForOutpointAddr", ":=", "func", "(", "blockTxs", "[", "]", "*", "dcrutil", ".", "Tx", ")", "{", "for", "_", ",", "tx", ":=", "range", "blockTxs", "{", "for", "_", ",", "txIn", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxIn", "{", "prevOut", ":=", "&", "txIn", ".", "PreviousOutPoint", "\n", "if", "bytes", ".", "Equal", "(", "zeroHash", "[", ":", "]", ",", "prevOut", ".", "Hash", "[", ":", "]", ")", "{", "continue", "\n", "}", "\n", "// For each TxIn, check the indicated vout index in the txid of the", "// previous outpoint.", "// txrr, err := c.GetRawTransactionVerbose(&prevOut.Hash)", "prevTx", ",", "err", ":=", "c", ".", "GetRawTransaction", "(", "&", "prevOut", ".", "Hash", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "prevOut", ".", "Hash", ".", "String", "(", ")", ")", "\n", "continue", "\n", "}", "\n\n", "// prevOut.Index should tell us which one, but check all anyway", "for", "_", ",", "txOut", ":=", "range", "prevTx", ".", "MsgTx", "(", ")", ".", "TxOut", "{", "_", ",", "txAddrs", ",", "_", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "txOut", ".", "Version", ",", "txOut", ".", "PkScript", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n\n", "for", "_", ",", "txAddr", ":=", "range", "txAddrs", "{", "addrstr", ":=", "txAddr", ".", "EncodeAddress", "(", ")", "\n", "if", "_", ",", "ok", ":=", "addrs", "[", "addrstr", "]", ";", "ok", "{", "if", "addrMap", "[", "addrstr", "]", "==", "nil", "{", "addrMap", "[", "addrstr", "]", "=", "make", "(", "[", "]", "*", "dcrutil", ".", "Tx", ",", "0", ")", "\n", "}", "\n", "addrMap", "[", "addrstr", "]", "=", "append", "(", "addrMap", "[", "addrstr", "]", ",", "prevTx", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "checkForOutpointAddr", "(", "block", ".", "Transactions", "(", ")", ")", "\n", "checkForOutpointAddr", "(", "block", ".", "STransactions", "(", ")", ")", "\n\n", "return", "addrMap", "\n", "}" ]
// BlockConsumesOutpointWithAddresses checks the specified block to see if it // includes transactions that spend from outputs created using any of the // addresses in addrs. The TxAction for each address is not important, but it // would logically be TxMined. Both regular and stake transactions are checked. // The RPC client is used to get the PreviousOutPoint for each TxIn of each // transaction in the block, from which the address is obtained from the // PkScript of that output. chaincfg Params is required to decode the script.
[ "BlockConsumesOutpointWithAddresses", "checks", "the", "specified", "block", "to", "see", "if", "it", "includes", "transactions", "that", "spend", "from", "outputs", "created", "using", "any", "of", "the", "addresses", "in", "addrs", ".", "The", "TxAction", "for", "each", "address", "is", "not", "important", "but", "it", "would", "logically", "be", "TxMined", ".", "Both", "regular", "and", "stake", "transactions", "are", "checked", ".", "The", "RPC", "client", "is", "used", "to", "get", "the", "PreviousOutPoint", "for", "each", "TxIn", "of", "each", "transaction", "in", "the", "block", "from", "which", "the", "address", "is", "obtained", "from", "the", "PkScript", "of", "that", "output", ".", "chaincfg", "Params", "is", "required", "to", "decode", "the", "script", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L527-L574
train
decred/dcrdata
txhelpers/txhelpers.go
TxPaysToAddress
func TxPaysToAddress(msgTx *wire.MsgTx, addr string, params *chaincfg.Params) (outpoints []*wire.OutPoint) { // Check the addresses associated with the PkScript of each TxOut txTree := TxTree(msgTx) hash := msgTx.TxHash() for outIndex, txOut := range msgTx.TxOut { _, txOutAddrs, _, err := txscript.ExtractPkScriptAddrs(txOut.Version, txOut.PkScript, params) if err != nil { fmt.Printf("ExtractPkScriptAddrs: %v", err.Error()) continue } // Check if we are watching any address for this TxOut for _, txAddr := range txOutAddrs { addrstr := txAddr.EncodeAddress() if addr == addrstr { outpoints = append(outpoints, wire.NewOutPoint(&hash, uint32(outIndex), txTree)) } } } return }
go
func TxPaysToAddress(msgTx *wire.MsgTx, addr string, params *chaincfg.Params) (outpoints []*wire.OutPoint) { // Check the addresses associated with the PkScript of each TxOut txTree := TxTree(msgTx) hash := msgTx.TxHash() for outIndex, txOut := range msgTx.TxOut { _, txOutAddrs, _, err := txscript.ExtractPkScriptAddrs(txOut.Version, txOut.PkScript, params) if err != nil { fmt.Printf("ExtractPkScriptAddrs: %v", err.Error()) continue } // Check if we are watching any address for this TxOut for _, txAddr := range txOutAddrs { addrstr := txAddr.EncodeAddress() if addr == addrstr { outpoints = append(outpoints, wire.NewOutPoint(&hash, uint32(outIndex), txTree)) } } } return }
[ "func", "TxPaysToAddress", "(", "msgTx", "*", "wire", ".", "MsgTx", ",", "addr", "string", ",", "params", "*", "chaincfg", ".", "Params", ")", "(", "outpoints", "[", "]", "*", "wire", ".", "OutPoint", ")", "{", "// Check the addresses associated with the PkScript of each TxOut", "txTree", ":=", "TxTree", "(", "msgTx", ")", "\n", "hash", ":=", "msgTx", ".", "TxHash", "(", ")", "\n", "for", "outIndex", ",", "txOut", ":=", "range", "msgTx", ".", "TxOut", "{", "_", ",", "txOutAddrs", ",", "_", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "txOut", ".", "Version", ",", "txOut", ".", "PkScript", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n\n", "// Check if we are watching any address for this TxOut", "for", "_", ",", "txAddr", ":=", "range", "txOutAddrs", "{", "addrstr", ":=", "txAddr", ".", "EncodeAddress", "(", ")", "\n", "if", "addr", "==", "addrstr", "{", "outpoints", "=", "append", "(", "outpoints", ",", "wire", ".", "NewOutPoint", "(", "&", "hash", ",", "uint32", "(", "outIndex", ")", ",", "txTree", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// TxPaysToAddress returns a slice of outpoints of a transaction which pay to // specified address.
[ "TxPaysToAddress", "returns", "a", "slice", "of", "outpoints", "of", "a", "transaction", "which", "pay", "to", "specified", "address", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L578-L601
train
decred/dcrdata
txhelpers/txhelpers.go
BlockReceivesToAddresses
func BlockReceivesToAddresses(block *dcrutil.Block, addrs map[string]TxAction, params *chaincfg.Params) map[string][]*dcrutil.Tx { addrMap := make(map[string][]*dcrutil.Tx) checkForAddrOut := func(blockTxs []*dcrutil.Tx) { for _, tx := range blockTxs { // Check the addresses associated with the PkScript of each TxOut for _, txOut := range tx.MsgTx().TxOut { _, txOutAddrs, _, err := txscript.ExtractPkScriptAddrs(txOut.Version, txOut.PkScript, params) if err != nil { fmt.Printf("ExtractPkScriptAddrs: %v", err.Error()) continue } // Check if we are watching any address for this TxOut for _, txAddr := range txOutAddrs { addrstr := txAddr.EncodeAddress() if _, ok := addrs[addrstr]; ok { if _, gotSlice := addrMap[addrstr]; !gotSlice { addrMap[addrstr] = make([]*dcrutil.Tx, 0) // nil } addrMap[addrstr] = append(addrMap[addrstr], tx) } } } } } checkForAddrOut(block.Transactions()) checkForAddrOut(block.STransactions()) return addrMap }
go
func BlockReceivesToAddresses(block *dcrutil.Block, addrs map[string]TxAction, params *chaincfg.Params) map[string][]*dcrutil.Tx { addrMap := make(map[string][]*dcrutil.Tx) checkForAddrOut := func(blockTxs []*dcrutil.Tx) { for _, tx := range blockTxs { // Check the addresses associated with the PkScript of each TxOut for _, txOut := range tx.MsgTx().TxOut { _, txOutAddrs, _, err := txscript.ExtractPkScriptAddrs(txOut.Version, txOut.PkScript, params) if err != nil { fmt.Printf("ExtractPkScriptAddrs: %v", err.Error()) continue } // Check if we are watching any address for this TxOut for _, txAddr := range txOutAddrs { addrstr := txAddr.EncodeAddress() if _, ok := addrs[addrstr]; ok { if _, gotSlice := addrMap[addrstr]; !gotSlice { addrMap[addrstr] = make([]*dcrutil.Tx, 0) // nil } addrMap[addrstr] = append(addrMap[addrstr], tx) } } } } } checkForAddrOut(block.Transactions()) checkForAddrOut(block.STransactions()) return addrMap }
[ "func", "BlockReceivesToAddresses", "(", "block", "*", "dcrutil", ".", "Block", ",", "addrs", "map", "[", "string", "]", "TxAction", ",", "params", "*", "chaincfg", ".", "Params", ")", "map", "[", "string", "]", "[", "]", "*", "dcrutil", ".", "Tx", "{", "addrMap", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "dcrutil", ".", "Tx", ")", "\n\n", "checkForAddrOut", ":=", "func", "(", "blockTxs", "[", "]", "*", "dcrutil", ".", "Tx", ")", "{", "for", "_", ",", "tx", ":=", "range", "blockTxs", "{", "// Check the addresses associated with the PkScript of each TxOut", "for", "_", ",", "txOut", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxOut", "{", "_", ",", "txOutAddrs", ",", "_", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "txOut", ".", "Version", ",", "txOut", ".", "PkScript", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n\n", "// Check if we are watching any address for this TxOut", "for", "_", ",", "txAddr", ":=", "range", "txOutAddrs", "{", "addrstr", ":=", "txAddr", ".", "EncodeAddress", "(", ")", "\n", "if", "_", ",", "ok", ":=", "addrs", "[", "addrstr", "]", ";", "ok", "{", "if", "_", ",", "gotSlice", ":=", "addrMap", "[", "addrstr", "]", ";", "!", "gotSlice", "{", "addrMap", "[", "addrstr", "]", "=", "make", "(", "[", "]", "*", "dcrutil", ".", "Tx", ",", "0", ")", "// nil", "\n", "}", "\n", "addrMap", "[", "addrstr", "]", "=", "append", "(", "addrMap", "[", "addrstr", "]", ",", "tx", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "checkForAddrOut", "(", "block", ".", "Transactions", "(", ")", ")", "\n", "checkForAddrOut", "(", "block", ".", "STransactions", "(", ")", ")", "\n\n", "return", "addrMap", "\n", "}" ]
// BlockReceivesToAddresses checks a block for transactions paying to the // specified addresses, and creates a map of addresses to a slice of dcrutil.Tx // involving the address.
[ "BlockReceivesToAddresses", "checks", "a", "block", "for", "transactions", "paying", "to", "the", "specified", "addresses", "and", "creates", "a", "map", "of", "addresses", "to", "a", "slice", "of", "dcrutil", ".", "Tx", "involving", "the", "address", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L606-L639
train
decred/dcrdata
txhelpers/txhelpers.go
OutPointAddresses
func OutPointAddresses(outPoint *wire.OutPoint, c RawTransactionGetter, params *chaincfg.Params) ([]string, dcrutil.Amount, error) { // The addresses are encoded in the pkScript, so we need to get the // raw transaction, and the TxOut that contains the pkScript. prevTx, err := c.GetRawTransaction(&outPoint.Hash) if err != nil { return nil, 0, fmt.Errorf("unable to get raw transaction for %s", outPoint.Hash.String()) } txOuts := prevTx.MsgTx().TxOut if len(txOuts) <= int(outPoint.Index) { return nil, 0, fmt.Errorf("PrevOut index (%d) is beyond the TxOuts slice (length %d)", outPoint.Index, len(txOuts)) } // For the TxOut of interest, extract the list of addresses txOut := txOuts[outPoint.Index] _, txAddrs, _, err := txscript.ExtractPkScriptAddrs( txOut.Version, txOut.PkScript, params) if err != nil { return nil, 0, fmt.Errorf("ExtractPkScriptAddrs: %v", err.Error()) } value := dcrutil.Amount(txOut.Value) addresses := make([]string, 0, len(txAddrs)) for _, txAddr := range txAddrs { addr := txAddr.EncodeAddress() addresses = append(addresses, addr) } return addresses, value, nil }
go
func OutPointAddresses(outPoint *wire.OutPoint, c RawTransactionGetter, params *chaincfg.Params) ([]string, dcrutil.Amount, error) { // The addresses are encoded in the pkScript, so we need to get the // raw transaction, and the TxOut that contains the pkScript. prevTx, err := c.GetRawTransaction(&outPoint.Hash) if err != nil { return nil, 0, fmt.Errorf("unable to get raw transaction for %s", outPoint.Hash.String()) } txOuts := prevTx.MsgTx().TxOut if len(txOuts) <= int(outPoint.Index) { return nil, 0, fmt.Errorf("PrevOut index (%d) is beyond the TxOuts slice (length %d)", outPoint.Index, len(txOuts)) } // For the TxOut of interest, extract the list of addresses txOut := txOuts[outPoint.Index] _, txAddrs, _, err := txscript.ExtractPkScriptAddrs( txOut.Version, txOut.PkScript, params) if err != nil { return nil, 0, fmt.Errorf("ExtractPkScriptAddrs: %v", err.Error()) } value := dcrutil.Amount(txOut.Value) addresses := make([]string, 0, len(txAddrs)) for _, txAddr := range txAddrs { addr := txAddr.EncodeAddress() addresses = append(addresses, addr) } return addresses, value, nil }
[ "func", "OutPointAddresses", "(", "outPoint", "*", "wire", ".", "OutPoint", ",", "c", "RawTransactionGetter", ",", "params", "*", "chaincfg", ".", "Params", ")", "(", "[", "]", "string", ",", "dcrutil", ".", "Amount", ",", "error", ")", "{", "// The addresses are encoded in the pkScript, so we need to get the", "// raw transaction, and the TxOut that contains the pkScript.", "prevTx", ",", "err", ":=", "c", ".", "GetRawTransaction", "(", "&", "outPoint", ".", "Hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "outPoint", ".", "Hash", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "txOuts", ":=", "prevTx", ".", "MsgTx", "(", ")", ".", "TxOut", "\n", "if", "len", "(", "txOuts", ")", "<=", "int", "(", "outPoint", ".", "Index", ")", "{", "return", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "outPoint", ".", "Index", ",", "len", "(", "txOuts", ")", ")", "\n", "}", "\n\n", "// For the TxOut of interest, extract the list of addresses", "txOut", ":=", "txOuts", "[", "outPoint", ".", "Index", "]", "\n", "_", ",", "txAddrs", ",", "_", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "txOut", ".", "Version", ",", "txOut", ".", "PkScript", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "value", ":=", "dcrutil", ".", "Amount", "(", "txOut", ".", "Value", ")", "\n", "addresses", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "txAddrs", ")", ")", "\n", "for", "_", ",", "txAddr", ":=", "range", "txAddrs", "{", "addr", ":=", "txAddr", ".", "EncodeAddress", "(", ")", "\n", "addresses", "=", "append", "(", "addresses", ",", "addr", ")", "\n", "}", "\n", "return", "addresses", ",", "value", ",", "nil", "\n", "}" ]
// OutPointAddresses gets the addresses paid to by a transaction output.
[ "OutPointAddresses", "gets", "the", "addresses", "paid", "to", "by", "a", "transaction", "output", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L642-L671
train
decred/dcrdata
txhelpers/txhelpers.go
OutPointAddressesFromString
func OutPointAddressesFromString(txid string, index uint32, tree int8, c RawTransactionGetter, params *chaincfg.Params) ([]string, error) { hash, err := chainhash.NewHashFromStr(txid) if err != nil { return nil, fmt.Errorf("Invalid hash %s", txid) } outPoint := wire.NewOutPoint(hash, index, tree) outPointAddress, _, err := OutPointAddresses(outPoint, c, params) return outPointAddress, err }
go
func OutPointAddressesFromString(txid string, index uint32, tree int8, c RawTransactionGetter, params *chaincfg.Params) ([]string, error) { hash, err := chainhash.NewHashFromStr(txid) if err != nil { return nil, fmt.Errorf("Invalid hash %s", txid) } outPoint := wire.NewOutPoint(hash, index, tree) outPointAddress, _, err := OutPointAddresses(outPoint, c, params) return outPointAddress, err }
[ "func", "OutPointAddressesFromString", "(", "txid", "string", ",", "index", "uint32", ",", "tree", "int8", ",", "c", "RawTransactionGetter", ",", "params", "*", "chaincfg", ".", "Params", ")", "(", "[", "]", "string", ",", "error", ")", "{", "hash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "txid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "txid", ")", "\n", "}", "\n\n", "outPoint", ":=", "wire", ".", "NewOutPoint", "(", "hash", ",", "index", ",", "tree", ")", "\n", "outPointAddress", ",", "_", ",", "err", ":=", "OutPointAddresses", "(", "outPoint", ",", "c", ",", "params", ")", "\n", "return", "outPointAddress", ",", "err", "\n", "}" ]
// OutPointAddressesFromString is the same as OutPointAddresses, but it takes // the outpoint as the tx string, vout index, and tree.
[ "OutPointAddressesFromString", "is", "the", "same", "as", "OutPointAddresses", "but", "it", "takes", "the", "outpoint", "as", "the", "tx", "string", "vout", "index", "and", "tree", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L675-L685
train
decred/dcrdata
txhelpers/txhelpers.go
MedianAmount
func MedianAmount(s []dcrutil.Amount) dcrutil.Amount { if len(s) == 0 { return 0 } sort.Sort(dcrutil.AmountSorter(s)) middle := len(s) / 2 if len(s) == 0 { return 0 } else if (len(s) % 2) != 0 { return s[middle] } return (s[middle] + s[middle-1]) / 2 }
go
func MedianAmount(s []dcrutil.Amount) dcrutil.Amount { if len(s) == 0 { return 0 } sort.Sort(dcrutil.AmountSorter(s)) middle := len(s) / 2 if len(s) == 0 { return 0 } else if (len(s) % 2) != 0 { return s[middle] } return (s[middle] + s[middle-1]) / 2 }
[ "func", "MedianAmount", "(", "s", "[", "]", "dcrutil", ".", "Amount", ")", "dcrutil", ".", "Amount", "{", "if", "len", "(", "s", ")", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "sort", ".", "Sort", "(", "dcrutil", ".", "AmountSorter", "(", "s", ")", ")", "\n\n", "middle", ":=", "len", "(", "s", ")", "/", "2", "\n\n", "if", "len", "(", "s", ")", "==", "0", "{", "return", "0", "\n", "}", "else", "if", "(", "len", "(", "s", ")", "%", "2", ")", "!=", "0", "{", "return", "s", "[", "middle", "]", "\n", "}", "\n", "return", "(", "s", "[", "middle", "]", "+", "s", "[", "middle", "-", "1", "]", ")", "/", "2", "\n", "}" ]
// MedianAmount gets the median Amount from a slice of Amounts
[ "MedianAmount", "gets", "the", "median", "Amount", "from", "a", "slice", "of", "Amounts" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L688-L703
train
decred/dcrdata
txhelpers/txhelpers.go
MedianCoin
func MedianCoin(s []float64) float64 { if len(s) == 0 { return 0 } sort.Float64s(s) middle := len(s) / 2 if len(s) == 0 { return 0 } else if (len(s) % 2) != 0 { return s[middle] } return (s[middle] + s[middle-1]) / 2 }
go
func MedianCoin(s []float64) float64 { if len(s) == 0 { return 0 } sort.Float64s(s) middle := len(s) / 2 if len(s) == 0 { return 0 } else if (len(s) % 2) != 0 { return s[middle] } return (s[middle] + s[middle-1]) / 2 }
[ "func", "MedianCoin", "(", "s", "[", "]", "float64", ")", "float64", "{", "if", "len", "(", "s", ")", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "sort", ".", "Float64s", "(", "s", ")", "\n\n", "middle", ":=", "len", "(", "s", ")", "/", "2", "\n\n", "if", "len", "(", "s", ")", "==", "0", "{", "return", "0", "\n", "}", "else", "if", "(", "len", "(", "s", ")", "%", "2", ")", "!=", "0", "{", "return", "s", "[", "middle", "]", "\n", "}", "\n", "return", "(", "s", "[", "middle", "]", "+", "s", "[", "middle", "-", "1", "]", ")", "/", "2", "\n", "}" ]
// MedianCoin gets the median DCR from a slice of float64s
[ "MedianCoin", "gets", "the", "median", "DCR", "from", "a", "slice", "of", "float64s" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L706-L721
train
decred/dcrdata
txhelpers/txhelpers.go
GetDifficultyRatio
func GetDifficultyRatio(bits uint32, params *chaincfg.Params) float64 { // The minimum difficulty is the max possible proof-of-work limit bits // converted back to a number. Note this is not the same as the proof of // work limit directly because the block difficulty is encoded in a block // with the compact form which loses precision. max := blockchain.CompactToBig(params.PowLimitBits) target := blockchain.CompactToBig(bits) difficulty := new(big.Rat).SetFrac(max, target) outString := difficulty.FloatString(8) diff, err := strconv.ParseFloat(outString, 64) if err != nil { fmt.Printf("Cannot get difficulty: %v", err) return 0 } return diff }
go
func GetDifficultyRatio(bits uint32, params *chaincfg.Params) float64 { // The minimum difficulty is the max possible proof-of-work limit bits // converted back to a number. Note this is not the same as the proof of // work limit directly because the block difficulty is encoded in a block // with the compact form which loses precision. max := blockchain.CompactToBig(params.PowLimitBits) target := blockchain.CompactToBig(bits) difficulty := new(big.Rat).SetFrac(max, target) outString := difficulty.FloatString(8) diff, err := strconv.ParseFloat(outString, 64) if err != nil { fmt.Printf("Cannot get difficulty: %v", err) return 0 } return diff }
[ "func", "GetDifficultyRatio", "(", "bits", "uint32", ",", "params", "*", "chaincfg", ".", "Params", ")", "float64", "{", "// The minimum difficulty is the max possible proof-of-work limit bits", "// converted back to a number. Note this is not the same as the proof of", "// work limit directly because the block difficulty is encoded in a block", "// with the compact form which loses precision.", "max", ":=", "blockchain", ".", "CompactToBig", "(", "params", ".", "PowLimitBits", ")", "\n", "target", ":=", "blockchain", ".", "CompactToBig", "(", "bits", ")", "\n\n", "difficulty", ":=", "new", "(", "big", ".", "Rat", ")", ".", "SetFrac", "(", "max", ",", "target", ")", "\n", "outString", ":=", "difficulty", ".", "FloatString", "(", "8", ")", "\n", "diff", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "outString", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "0", "\n", "}", "\n", "return", "diff", "\n", "}" ]
// GetDifficultyRatio returns the proof-of-work difficulty as a multiple of the // minimum difficulty using the passed bits field from the header of a block.
[ "GetDifficultyRatio", "returns", "the", "proof", "-", "of", "-", "work", "difficulty", "as", "a", "multiple", "of", "the", "minimum", "difficulty", "using", "the", "passed", "bits", "field", "from", "the", "header", "of", "a", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L725-L741
train
decred/dcrdata
txhelpers/txhelpers.go
SSTXInBlock
func SSTXInBlock(block *dcrutil.Block) []*dcrutil.Tx { _, txns := TicketTxnsInBlock(block) return txns }
go
func SSTXInBlock(block *dcrutil.Block) []*dcrutil.Tx { _, txns := TicketTxnsInBlock(block) return txns }
[ "func", "SSTXInBlock", "(", "block", "*", "dcrutil", ".", "Block", ")", "[", "]", "*", "dcrutil", ".", "Tx", "{", "_", ",", "txns", ":=", "TicketTxnsInBlock", "(", "block", ")", "\n", "return", "txns", "\n", "}" ]
// SSTXInBlock gets a slice containing all of the SSTX mined in a block
[ "SSTXInBlock", "gets", "a", "slice", "containing", "all", "of", "the", "SSTX", "mined", "in", "a", "block" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L744-L747
train
decred/dcrdata
txhelpers/txhelpers.go
VoteBitsInBlock
func VoteBitsInBlock(block *dcrutil.Block) []stake.VoteVersionTuple { var voteBits []stake.VoteVersionTuple for _, stx := range block.MsgBlock().STransactions { if !stake.IsSSGen(stx) { continue } voteBits = append(voteBits, stake.VoteVersionTuple{ Version: stake.SSGenVersion(stx), Bits: stake.SSGenVoteBits(stx), }) } return voteBits }
go
func VoteBitsInBlock(block *dcrutil.Block) []stake.VoteVersionTuple { var voteBits []stake.VoteVersionTuple for _, stx := range block.MsgBlock().STransactions { if !stake.IsSSGen(stx) { continue } voteBits = append(voteBits, stake.VoteVersionTuple{ Version: stake.SSGenVersion(stx), Bits: stake.SSGenVoteBits(stx), }) } return voteBits }
[ "func", "VoteBitsInBlock", "(", "block", "*", "dcrutil", ".", "Block", ")", "[", "]", "stake", ".", "VoteVersionTuple", "{", "var", "voteBits", "[", "]", "stake", ".", "VoteVersionTuple", "\n", "for", "_", ",", "stx", ":=", "range", "block", ".", "MsgBlock", "(", ")", ".", "STransactions", "{", "if", "!", "stake", ".", "IsSSGen", "(", "stx", ")", "{", "continue", "\n", "}", "\n\n", "voteBits", "=", "append", "(", "voteBits", ",", "stake", ".", "VoteVersionTuple", "{", "Version", ":", "stake", ".", "SSGenVersion", "(", "stx", ")", ",", "Bits", ":", "stake", ".", "SSGenVoteBits", "(", "stx", ")", ",", "}", ")", "\n", "}", "\n\n", "return", "voteBits", "\n", "}" ]
// VoteBitsInBlock returns a list of vote bits for the votes in a block
[ "VoteBitsInBlock", "returns", "a", "list", "of", "vote", "bits", "for", "the", "votes", "in", "a", "block" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L769-L783
train
decred/dcrdata
txhelpers/txhelpers.go
VoteVersion
func VoteVersion(pkScript []byte) uint32 { if len(pkScript) < 8 { return stake.VoteConsensusVersionAbsent } return binary.LittleEndian.Uint32(pkScript[4:8]) }
go
func VoteVersion(pkScript []byte) uint32 { if len(pkScript) < 8 { return stake.VoteConsensusVersionAbsent } return binary.LittleEndian.Uint32(pkScript[4:8]) }
[ "func", "VoteVersion", "(", "pkScript", "[", "]", "byte", ")", "uint32", "{", "if", "len", "(", "pkScript", ")", "<", "8", "{", "return", "stake", ".", "VoteConsensusVersionAbsent", "\n", "}", "\n\n", "return", "binary", ".", "LittleEndian", ".", "Uint32", "(", "pkScript", "[", "4", ":", "8", "]", ")", "\n", "}" ]
// VoteVersion extracts the vote version from the input pubkey script.
[ "VoteVersion", "extracts", "the", "vote", "version", "from", "the", "input", "pubkey", "script", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L840-L846
train
decred/dcrdata
txhelpers/txhelpers.go
FeeInfoBlock
func FeeInfoBlock(block *dcrutil.Block) *dcrjson.FeeInfoBlock { feeInfo := new(dcrjson.FeeInfoBlock) _, sstxMsgTxns := TicketsInBlock(block) feeInfo.Height = uint32(block.Height()) feeInfo.Number = uint32(len(sstxMsgTxns)) var minFee, maxFee, meanFee float64 minFee = math.MaxFloat64 fees := make([]float64, feeInfo.Number) for it, msgTx := range sstxMsgTxns { var amtIn int64 for iv := range msgTx.TxIn { amtIn += msgTx.TxIn[iv].ValueIn } var amtOut int64 for iv := range msgTx.TxOut { amtOut += msgTx.TxOut[iv].Value } fee := dcrutil.Amount(amtIn - amtOut).ToCoin() if fee < minFee { minFee = fee } if fee > maxFee { maxFee = fee } meanFee += fee fees[it] = fee } if feeInfo.Number > 0 { N := float64(feeInfo.Number) meanFee /= N feeInfo.Mean = meanFee feeInfo.Median = MedianCoin(fees) feeInfo.Min = minFee feeInfo.Max = maxFee if N > 1 { var variance float64 for _, f := range fees { variance += (f - meanFee) * (f - meanFee) } variance /= (N - 1) feeInfo.StdDev = math.Sqrt(variance) } } return feeInfo }
go
func FeeInfoBlock(block *dcrutil.Block) *dcrjson.FeeInfoBlock { feeInfo := new(dcrjson.FeeInfoBlock) _, sstxMsgTxns := TicketsInBlock(block) feeInfo.Height = uint32(block.Height()) feeInfo.Number = uint32(len(sstxMsgTxns)) var minFee, maxFee, meanFee float64 minFee = math.MaxFloat64 fees := make([]float64, feeInfo.Number) for it, msgTx := range sstxMsgTxns { var amtIn int64 for iv := range msgTx.TxIn { amtIn += msgTx.TxIn[iv].ValueIn } var amtOut int64 for iv := range msgTx.TxOut { amtOut += msgTx.TxOut[iv].Value } fee := dcrutil.Amount(amtIn - amtOut).ToCoin() if fee < minFee { minFee = fee } if fee > maxFee { maxFee = fee } meanFee += fee fees[it] = fee } if feeInfo.Number > 0 { N := float64(feeInfo.Number) meanFee /= N feeInfo.Mean = meanFee feeInfo.Median = MedianCoin(fees) feeInfo.Min = minFee feeInfo.Max = maxFee if N > 1 { var variance float64 for _, f := range fees { variance += (f - meanFee) * (f - meanFee) } variance /= (N - 1) feeInfo.StdDev = math.Sqrt(variance) } } return feeInfo }
[ "func", "FeeInfoBlock", "(", "block", "*", "dcrutil", ".", "Block", ")", "*", "dcrjson", ".", "FeeInfoBlock", "{", "feeInfo", ":=", "new", "(", "dcrjson", ".", "FeeInfoBlock", ")", "\n", "_", ",", "sstxMsgTxns", ":=", "TicketsInBlock", "(", "block", ")", "\n\n", "feeInfo", ".", "Height", "=", "uint32", "(", "block", ".", "Height", "(", ")", ")", "\n", "feeInfo", ".", "Number", "=", "uint32", "(", "len", "(", "sstxMsgTxns", ")", ")", "\n\n", "var", "minFee", ",", "maxFee", ",", "meanFee", "float64", "\n", "minFee", "=", "math", ".", "MaxFloat64", "\n", "fees", ":=", "make", "(", "[", "]", "float64", ",", "feeInfo", ".", "Number", ")", "\n", "for", "it", ",", "msgTx", ":=", "range", "sstxMsgTxns", "{", "var", "amtIn", "int64", "\n", "for", "iv", ":=", "range", "msgTx", ".", "TxIn", "{", "amtIn", "+=", "msgTx", ".", "TxIn", "[", "iv", "]", ".", "ValueIn", "\n", "}", "\n", "var", "amtOut", "int64", "\n", "for", "iv", ":=", "range", "msgTx", ".", "TxOut", "{", "amtOut", "+=", "msgTx", ".", "TxOut", "[", "iv", "]", ".", "Value", "\n", "}", "\n", "fee", ":=", "dcrutil", ".", "Amount", "(", "amtIn", "-", "amtOut", ")", ".", "ToCoin", "(", ")", "\n", "if", "fee", "<", "minFee", "{", "minFee", "=", "fee", "\n", "}", "\n", "if", "fee", ">", "maxFee", "{", "maxFee", "=", "fee", "\n", "}", "\n", "meanFee", "+=", "fee", "\n", "fees", "[", "it", "]", "=", "fee", "\n", "}", "\n\n", "if", "feeInfo", ".", "Number", ">", "0", "{", "N", ":=", "float64", "(", "feeInfo", ".", "Number", ")", "\n", "meanFee", "/=", "N", "\n", "feeInfo", ".", "Mean", "=", "meanFee", "\n", "feeInfo", ".", "Median", "=", "MedianCoin", "(", "fees", ")", "\n", "feeInfo", ".", "Min", "=", "minFee", "\n", "feeInfo", ".", "Max", "=", "maxFee", "\n\n", "if", "N", ">", "1", "{", "var", "variance", "float64", "\n", "for", "_", ",", "f", ":=", "range", "fees", "{", "variance", "+=", "(", "f", "-", "meanFee", ")", "*", "(", "f", "-", "meanFee", ")", "\n", "}", "\n", "variance", "/=", "(", "N", "-", "1", ")", "\n", "feeInfo", ".", "StdDev", "=", "math", ".", "Sqrt", "(", "variance", ")", "\n", "}", "\n", "}", "\n\n", "return", "feeInfo", "\n", "}" ]
// FeeInfoBlock computes ticket fee statistics for the tickets included in the // specified block.
[ "FeeInfoBlock", "computes", "ticket", "fee", "statistics", "for", "the", "tickets", "included", "in", "the", "specified", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L889-L938
train
decred/dcrdata
txhelpers/txhelpers.go
MsgTxFromHex
func MsgTxFromHex(txhex string) (*wire.MsgTx, error) { msgTx := wire.NewMsgTx() if err := msgTx.Deserialize(hex.NewDecoder(strings.NewReader(txhex))); err != nil { return nil, err } return msgTx, nil }
go
func MsgTxFromHex(txhex string) (*wire.MsgTx, error) { msgTx := wire.NewMsgTx() if err := msgTx.Deserialize(hex.NewDecoder(strings.NewReader(txhex))); err != nil { return nil, err } return msgTx, nil }
[ "func", "MsgTxFromHex", "(", "txhex", "string", ")", "(", "*", "wire", ".", "MsgTx", ",", "error", ")", "{", "msgTx", ":=", "wire", ".", "NewMsgTx", "(", ")", "\n", "if", "err", ":=", "msgTx", ".", "Deserialize", "(", "hex", ".", "NewDecoder", "(", "strings", ".", "NewReader", "(", "txhex", ")", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "msgTx", ",", "nil", "\n", "}" ]
// MsgTxFromHex returns a wire.MsgTx struct built from the transaction hex string.
[ "MsgTxFromHex", "returns", "a", "wire", ".", "MsgTx", "struct", "built", "from", "the", "transaction", "hex", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L993-L999
train
decred/dcrdata
txhelpers/txhelpers.go
DetermineTxTypeString
func DetermineTxTypeString(msgTx *wire.MsgTx) string { switch stake.DetermineTxType(msgTx) { case stake.TxTypeSSGen: return "Vote" case stake.TxTypeSStx: return "Ticket" case stake.TxTypeSSRtx: return "Revocation" default: return "Regular" } }
go
func DetermineTxTypeString(msgTx *wire.MsgTx) string { switch stake.DetermineTxType(msgTx) { case stake.TxTypeSSGen: return "Vote" case stake.TxTypeSStx: return "Ticket" case stake.TxTypeSSRtx: return "Revocation" default: return "Regular" } }
[ "func", "DetermineTxTypeString", "(", "msgTx", "*", "wire", ".", "MsgTx", ")", "string", "{", "switch", "stake", ".", "DetermineTxType", "(", "msgTx", ")", "{", "case", "stake", ".", "TxTypeSSGen", ":", "return", "\"", "\"", "\n", "case", "stake", ".", "TxTypeSStx", ":", "return", "\"", "\"", "\n", "case", "stake", ".", "TxTypeSSRtx", ":", "return", "\"", "\"", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// DetermineTxTypeString returns a string representing the transaction type given // a wire.MsgTx struct
[ "DetermineTxTypeString", "returns", "a", "string", "representing", "the", "transaction", "type", "given", "a", "wire", ".", "MsgTx", "struct" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L1003-L1014
train
decred/dcrdata
txhelpers/txhelpers.go
TxTypeToString
func TxTypeToString(txType int) string { switch stake.TxType(txType) { case stake.TxTypeSSGen: return "Vote" case stake.TxTypeSStx: return "Ticket" case stake.TxTypeSSRtx: return "Revocation" default: return "Regular" } }
go
func TxTypeToString(txType int) string { switch stake.TxType(txType) { case stake.TxTypeSSGen: return "Vote" case stake.TxTypeSStx: return "Ticket" case stake.TxTypeSSRtx: return "Revocation" default: return "Regular" } }
[ "func", "TxTypeToString", "(", "txType", "int", ")", "string", "{", "switch", "stake", ".", "TxType", "(", "txType", ")", "{", "case", "stake", ".", "TxTypeSSGen", ":", "return", "\"", "\"", "\n", "case", "stake", ".", "TxTypeSStx", ":", "return", "\"", "\"", "\n", "case", "stake", ".", "TxTypeSSRtx", ":", "return", "\"", "\"", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// TxTypeToString returns a string representation of the provided transaction // type, which corresponds to the txn types defined for stake.TxType type.
[ "TxTypeToString", "returns", "a", "string", "representation", "of", "the", "provided", "transaction", "type", "which", "corresponds", "to", "the", "txn", "types", "defined", "for", "stake", ".", "TxType", "type", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L1018-L1029
train
decred/dcrdata
txhelpers/txhelpers.go
IsStakeTx
func IsStakeTx(msgTx *wire.MsgTx) bool { switch stake.DetermineTxType(msgTx) { case stake.TxTypeSSGen: fallthrough case stake.TxTypeSStx: fallthrough case stake.TxTypeSSRtx: return true default: return false } }
go
func IsStakeTx(msgTx *wire.MsgTx) bool { switch stake.DetermineTxType(msgTx) { case stake.TxTypeSSGen: fallthrough case stake.TxTypeSStx: fallthrough case stake.TxTypeSSRtx: return true default: return false } }
[ "func", "IsStakeTx", "(", "msgTx", "*", "wire", ".", "MsgTx", ")", "bool", "{", "switch", "stake", ".", "DetermineTxType", "(", "msgTx", ")", "{", "case", "stake", ".", "TxTypeSSGen", ":", "fallthrough", "\n", "case", "stake", ".", "TxTypeSStx", ":", "fallthrough", "\n", "case", "stake", ".", "TxTypeSSRtx", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// IsStakeTx indicates if the input MsgTx is a stake transaction.
[ "IsStakeTx", "indicates", "if", "the", "input", "MsgTx", "is", "a", "stake", "transaction", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L1053-L1064
train
decred/dcrdata
txhelpers/txhelpers.go
TxTree
func TxTree(msgTx *wire.MsgTx) int8 { if IsStakeTx(msgTx) { return wire.TxTreeStake } return wire.TxTreeRegular }
go
func TxTree(msgTx *wire.MsgTx) int8 { if IsStakeTx(msgTx) { return wire.TxTreeStake } return wire.TxTreeRegular }
[ "func", "TxTree", "(", "msgTx", "*", "wire", ".", "MsgTx", ")", "int8", "{", "if", "IsStakeTx", "(", "msgTx", ")", "{", "return", "wire", ".", "TxTreeStake", "\n", "}", "\n", "return", "wire", ".", "TxTreeRegular", "\n", "}" ]
// TxTree returns for a wire.MsgTx either wire.TxTreeStake or wire.TxTreeRegular // depending on the type of transaction.
[ "TxTree", "returns", "for", "a", "wire", ".", "MsgTx", "either", "wire", ".", "TxTreeStake", "or", "wire", ".", "TxTreeRegular", "depending", "on", "the", "type", "of", "transaction", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L1068-L1073
train
decred/dcrdata
txhelpers/txhelpers.go
TxFee
func TxFee(msgTx *wire.MsgTx) dcrutil.Amount { var amtIn int64 for iv := range msgTx.TxIn { amtIn += msgTx.TxIn[iv].ValueIn } var amtOut int64 for iv := range msgTx.TxOut { amtOut += msgTx.TxOut[iv].Value } return dcrutil.Amount(amtIn - amtOut) }
go
func TxFee(msgTx *wire.MsgTx) dcrutil.Amount { var amtIn int64 for iv := range msgTx.TxIn { amtIn += msgTx.TxIn[iv].ValueIn } var amtOut int64 for iv := range msgTx.TxOut { amtOut += msgTx.TxOut[iv].Value } return dcrutil.Amount(amtIn - amtOut) }
[ "func", "TxFee", "(", "msgTx", "*", "wire", ".", "MsgTx", ")", "dcrutil", ".", "Amount", "{", "var", "amtIn", "int64", "\n", "for", "iv", ":=", "range", "msgTx", ".", "TxIn", "{", "amtIn", "+=", "msgTx", ".", "TxIn", "[", "iv", "]", ".", "ValueIn", "\n", "}", "\n", "var", "amtOut", "int64", "\n", "for", "iv", ":=", "range", "msgTx", ".", "TxOut", "{", "amtOut", "+=", "msgTx", ".", "TxOut", "[", "iv", "]", ".", "Value", "\n", "}", "\n", "return", "dcrutil", ".", "Amount", "(", "amtIn", "-", "amtOut", ")", "\n", "}" ]
// TxFee computes and returns the fee for a given tx
[ "TxFee", "computes", "and", "returns", "the", "fee", "for", "a", "given", "tx" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L1076-L1086
train
decred/dcrdata
txhelpers/txhelpers.go
TotalOutFromMsgTx
func TotalOutFromMsgTx(msgTx *wire.MsgTx) dcrutil.Amount { var amtOut int64 for _, v := range msgTx.TxOut { amtOut += v.Value } return dcrutil.Amount(amtOut) }
go
func TotalOutFromMsgTx(msgTx *wire.MsgTx) dcrutil.Amount { var amtOut int64 for _, v := range msgTx.TxOut { amtOut += v.Value } return dcrutil.Amount(amtOut) }
[ "func", "TotalOutFromMsgTx", "(", "msgTx", "*", "wire", ".", "MsgTx", ")", "dcrutil", ".", "Amount", "{", "var", "amtOut", "int64", "\n", "for", "_", ",", "v", ":=", "range", "msgTx", ".", "TxOut", "{", "amtOut", "+=", "v", ".", "Value", "\n", "}", "\n", "return", "dcrutil", ".", "Amount", "(", "amtOut", ")", "\n", "}" ]
// TotalOutFromMsgTx computes the total value out of a MsgTx
[ "TotalOutFromMsgTx", "computes", "the", "total", "value", "out", "of", "a", "MsgTx" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L1115-L1121
train
decred/dcrdata
txhelpers/txhelpers.go
TotalVout
func TotalVout(vouts []dcrjson.Vout) dcrutil.Amount { var total dcrutil.Amount for _, v := range vouts { a, err := dcrutil.NewAmount(v.Value) if err != nil { continue } total += a } return total }
go
func TotalVout(vouts []dcrjson.Vout) dcrutil.Amount { var total dcrutil.Amount for _, v := range vouts { a, err := dcrutil.NewAmount(v.Value) if err != nil { continue } total += a } return total }
[ "func", "TotalVout", "(", "vouts", "[", "]", "dcrjson", ".", "Vout", ")", "dcrutil", ".", "Amount", "{", "var", "total", "dcrutil", ".", "Amount", "\n", "for", "_", ",", "v", ":=", "range", "vouts", "{", "a", ",", "err", ":=", "dcrutil", ".", "NewAmount", "(", "v", ".", "Value", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "total", "+=", "a", "\n", "}", "\n", "return", "total", "\n", "}" ]
// TotalVout computes the total value of a slice of dcrjson.Vout
[ "TotalVout", "computes", "the", "total", "value", "of", "a", "slice", "of", "dcrjson", ".", "Vout" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L1124-L1134
train
decred/dcrdata
txhelpers/txhelpers.go
GenesisTxHash
func GenesisTxHash(params *chaincfg.Params) chainhash.Hash { return params.GenesisBlock.Transactions[0].TxHash() }
go
func GenesisTxHash(params *chaincfg.Params) chainhash.Hash { return params.GenesisBlock.Transactions[0].TxHash() }
[ "func", "GenesisTxHash", "(", "params", "*", "chaincfg", ".", "Params", ")", "chainhash", ".", "Hash", "{", "return", "params", ".", "GenesisBlock", ".", "Transactions", "[", "0", "]", ".", "TxHash", "(", ")", "\n", "}" ]
// GenesisTxHash returns the hash of the single coinbase transaction in the // genesis block of the specified network. This transaction is hard coded, and // the pubkey script for its one output only decodes for simnet.
[ "GenesisTxHash", "returns", "the", "hash", "of", "the", "single", "coinbase", "transaction", "in", "the", "genesis", "block", "of", "the", "specified", "network", ".", "This", "transaction", "is", "hard", "coded", "and", "the", "pubkey", "script", "for", "its", "one", "output", "only", "decodes", "for", "simnet", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L1139-L1141
train
decred/dcrdata
txhelpers/txhelpers.go
ValidateNetworkAddress
func ValidateNetworkAddress(address dcrutil.Address, p *chaincfg.Params) bool { return address.IsForNet(p) }
go
func ValidateNetworkAddress(address dcrutil.Address, p *chaincfg.Params) bool { return address.IsForNet(p) }
[ "func", "ValidateNetworkAddress", "(", "address", "dcrutil", ".", "Address", ",", "p", "*", "chaincfg", ".", "Params", ")", "bool", "{", "return", "address", ".", "IsForNet", "(", "p", ")", "\n", "}" ]
// ValidateNetworkAddress checks if the given address is valid on the given // network.
[ "ValidateNetworkAddress", "checks", "if", "the", "given", "address", "is", "valid", "on", "the", "given", "network", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L1168-L1170
train
decred/dcrdata
txhelpers/txhelpers.go
AddressValidation
func AddressValidation(address string, params *chaincfg.Params) (dcrutil.Address, AddressType, AddressError) { // Decode and validate the address. addr, err := dcrutil.DecodeAddress(address) if err != nil { return nil, AddressTypeUnknown, AddressErrorDecodeFailed } // Detect when an address belonging to a different Decred network. if !ValidateNetworkAddress(addr, params) { return addr, AddressTypeUnknown, AddressErrorWrongNet } // Determine address type for this valid Decred address. Ignore the error // since DecodeAddress succeeded. _, netID, _ := base58.CheckDecode(address) var addrType AddressType switch netID { case params.PubKeyAddrID: addrType = AddressTypeP2PK case params.PubKeyHashAddrID: addrType = AddressTypeP2PKH case params.ScriptHashAddrID: addrType = AddressTypeP2SH case params.PKHEdwardsAddrID, params.PKHSchnorrAddrID: addrType = AddressTypeOther default: addrType = AddressTypeUnknown } // Check if the address is the zero pubkey hash address commonly used for // zero value sstxchange-tagged outputs. Return a special error value, but // the decoded address and address type are valid. if IsZeroHashP2PHKAddress(address, params) { return addr, addrType, AddressErrorZeroAddress } return addr, addrType, AddressErrorNoError }
go
func AddressValidation(address string, params *chaincfg.Params) (dcrutil.Address, AddressType, AddressError) { // Decode and validate the address. addr, err := dcrutil.DecodeAddress(address) if err != nil { return nil, AddressTypeUnknown, AddressErrorDecodeFailed } // Detect when an address belonging to a different Decred network. if !ValidateNetworkAddress(addr, params) { return addr, AddressTypeUnknown, AddressErrorWrongNet } // Determine address type for this valid Decred address. Ignore the error // since DecodeAddress succeeded. _, netID, _ := base58.CheckDecode(address) var addrType AddressType switch netID { case params.PubKeyAddrID: addrType = AddressTypeP2PK case params.PubKeyHashAddrID: addrType = AddressTypeP2PKH case params.ScriptHashAddrID: addrType = AddressTypeP2SH case params.PKHEdwardsAddrID, params.PKHSchnorrAddrID: addrType = AddressTypeOther default: addrType = AddressTypeUnknown } // Check if the address is the zero pubkey hash address commonly used for // zero value sstxchange-tagged outputs. Return a special error value, but // the decoded address and address type are valid. if IsZeroHashP2PHKAddress(address, params) { return addr, addrType, AddressErrorZeroAddress } return addr, addrType, AddressErrorNoError }
[ "func", "AddressValidation", "(", "address", "string", ",", "params", "*", "chaincfg", ".", "Params", ")", "(", "dcrutil", ".", "Address", ",", "AddressType", ",", "AddressError", ")", "{", "// Decode and validate the address.", "addr", ",", "err", ":=", "dcrutil", ".", "DecodeAddress", "(", "address", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "AddressTypeUnknown", ",", "AddressErrorDecodeFailed", "\n", "}", "\n\n", "// Detect when an address belonging to a different Decred network.", "if", "!", "ValidateNetworkAddress", "(", "addr", ",", "params", ")", "{", "return", "addr", ",", "AddressTypeUnknown", ",", "AddressErrorWrongNet", "\n", "}", "\n\n", "// Determine address type for this valid Decred address. Ignore the error", "// since DecodeAddress succeeded.", "_", ",", "netID", ",", "_", ":=", "base58", ".", "CheckDecode", "(", "address", ")", "\n\n", "var", "addrType", "AddressType", "\n", "switch", "netID", "{", "case", "params", ".", "PubKeyAddrID", ":", "addrType", "=", "AddressTypeP2PK", "\n", "case", "params", ".", "PubKeyHashAddrID", ":", "addrType", "=", "AddressTypeP2PKH", "\n", "case", "params", ".", "ScriptHashAddrID", ":", "addrType", "=", "AddressTypeP2SH", "\n", "case", "params", ".", "PKHEdwardsAddrID", ",", "params", ".", "PKHSchnorrAddrID", ":", "addrType", "=", "AddressTypeOther", "\n", "default", ":", "addrType", "=", "AddressTypeUnknown", "\n", "}", "\n\n", "// Check if the address is the zero pubkey hash address commonly used for", "// zero value sstxchange-tagged outputs. Return a special error value, but", "// the decoded address and address type are valid.", "if", "IsZeroHashP2PHKAddress", "(", "address", ",", "params", ")", "{", "return", "addr", ",", "addrType", ",", "AddressErrorZeroAddress", "\n", "}", "\n\n", "return", "addr", ",", "addrType", ",", "AddressErrorNoError", "\n", "}" ]
// AddressValidation performs several validation checks on the given address // string. Initially, decoding as a Decred address is attempted. If it fails to // decode, AddressErrorDecodeFailed is returned with AddressTypeUnknown. // If the address decoded successfully as a Decred address, it is checked // against the specified network. If it is the wrong network, // AddressErrorWrongNet is returned with AddressTypeUnknown. If the address is // the correct network, the address type is obtained. A final check is performed // to determine if the address is the zero pubkey hash address, in which case // AddressErrorZeroAddress is returned with the determined address type. If it // is another address, AddressErrorNoError is returned with the determined // address type.
[ "AddressValidation", "performs", "several", "validation", "checks", "on", "the", "given", "address", "string", ".", "Initially", "decoding", "as", "a", "Decred", "address", "is", "attempted", ".", "If", "it", "fails", "to", "decode", "AddressErrorDecodeFailed", "is", "returned", "with", "AddressTypeUnknown", ".", "If", "the", "address", "decoded", "successfully", "as", "a", "Decred", "address", "it", "is", "checked", "against", "the", "specified", "network", ".", "If", "it", "is", "the", "wrong", "network", "AddressErrorWrongNet", "is", "returned", "with", "AddressTypeUnknown", ".", "If", "the", "address", "is", "the", "correct", "network", "the", "address", "type", "is", "obtained", ".", "A", "final", "check", "is", "performed", "to", "determine", "if", "the", "address", "is", "the", "zero", "pubkey", "hash", "address", "in", "which", "case", "AddressErrorZeroAddress", "is", "returned", "with", "the", "determined", "address", "type", ".", "If", "it", "is", "another", "address", "AddressErrorNoError", "is", "returned", "with", "the", "determined", "address", "type", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L1205-L1243
train
decred/dcrdata
db/dcrpg/internal/stakestmts.go
MakeVoteInsertStatement
func MakeVoteInsertStatement(checked, updateOnConflict bool) string { if !checked { return InsertVoteRow } if updateOnConflict { return UpsertVoteRow } return InsertVoteRowOnConflictDoNothing }
go
func MakeVoteInsertStatement(checked, updateOnConflict bool) string { if !checked { return InsertVoteRow } if updateOnConflict { return UpsertVoteRow } return InsertVoteRowOnConflictDoNothing }
[ "func", "MakeVoteInsertStatement", "(", "checked", ",", "updateOnConflict", "bool", ")", "string", "{", "if", "!", "checked", "{", "return", "InsertVoteRow", "\n", "}", "\n", "if", "updateOnConflict", "{", "return", "UpsertVoteRow", "\n", "}", "\n", "return", "InsertVoteRowOnConflictDoNothing", "\n", "}" ]
// MakeVoteInsertStatement returns the appropriate votes insert statement for // the desired conflict checking and handling behavior. See the description of // MakeTicketInsertStatement for details.
[ "MakeVoteInsertStatement", "returns", "the", "appropriate", "votes", "insert", "statement", "for", "the", "desired", "conflict", "checking", "and", "handling", "behavior", ".", "See", "the", "description", "of", "MakeTicketInsertStatement", "for", "details", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/internal/stakestmts.go#L532-L540
train
decred/dcrdata
db/dcrpg/internal/stakestmts.go
MakeMissInsertStatement
func MakeMissInsertStatement(checked, updateOnConflict bool) string { if !checked { return InsertMissRow } if updateOnConflict { return UpsertMissRow } return InsertMissRowOnConflictDoNothing }
go
func MakeMissInsertStatement(checked, updateOnConflict bool) string { if !checked { return InsertMissRow } if updateOnConflict { return UpsertMissRow } return InsertMissRowOnConflictDoNothing }
[ "func", "MakeMissInsertStatement", "(", "checked", ",", "updateOnConflict", "bool", ")", "string", "{", "if", "!", "checked", "{", "return", "InsertMissRow", "\n", "}", "\n", "if", "updateOnConflict", "{", "return", "UpsertMissRow", "\n", "}", "\n", "return", "InsertMissRowOnConflictDoNothing", "\n", "}" ]
// MakeMissInsertStatement returns the appropriate misses insert statement for // the desired conflict checking and handling behavior. See the description of // MakeTicketInsertStatement for details.
[ "MakeMissInsertStatement", "returns", "the", "appropriate", "misses", "insert", "statement", "for", "the", "desired", "conflict", "checking", "and", "handling", "behavior", ".", "See", "the", "description", "of", "MakeTicketInsertStatement", "for", "details", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/internal/stakestmts.go#L545-L553
train
nanomsg/mangos-v1
examples/websocket/subclient.go
subClient
func subClient(port int) { sock, err := sub.NewSocket() if err != nil { die("cannot make req socket: %v", err) } sock.AddTransport(ws.NewTransport()) if err = sock.SetOption(mangos.OptionSubscribe, []byte{}); err != nil { die("cannot set subscription: %v", err) } url := fmt.Sprintf("ws://127.0.0.1:%d/sub", port) if err = sock.Dial(url); err != nil { die("cannot dial req url: %v", err) } if m, err := sock.Recv(); err != nil { die("Cannot recv sub: %v", err) } else { fmt.Printf("%s\n", string(m)) } }
go
func subClient(port int) { sock, err := sub.NewSocket() if err != nil { die("cannot make req socket: %v", err) } sock.AddTransport(ws.NewTransport()) if err = sock.SetOption(mangos.OptionSubscribe, []byte{}); err != nil { die("cannot set subscription: %v", err) } url := fmt.Sprintf("ws://127.0.0.1:%d/sub", port) if err = sock.Dial(url); err != nil { die("cannot dial req url: %v", err) } if m, err := sock.Recv(); err != nil { die("Cannot recv sub: %v", err) } else { fmt.Printf("%s\n", string(m)) } }
[ "func", "subClient", "(", "port", "int", ")", "{", "sock", ",", "err", ":=", "sub", ".", "NewSocket", "(", ")", "\n", "if", "err", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "sock", ".", "AddTransport", "(", "ws", ".", "NewTransport", "(", ")", ")", "\n", "if", "err", "=", "sock", ".", "SetOption", "(", "mangos", ".", "OptionSubscribe", ",", "[", "]", "byte", "{", "}", ")", ";", "err", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "url", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "port", ")", "\n", "if", "err", "=", "sock", ".", "Dial", "(", "url", ")", ";", "err", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "m", ",", "err", ":=", "sock", ".", "Recv", "(", ")", ";", "err", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "string", "(", "m", ")", ")", "\n", "}", "\n", "}" ]
// subClient implements the client for SUB.
[ "subClient", "implements", "the", "client", "for", "SUB", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/examples/websocket/subclient.go#L26-L44
train
nanomsg/mangos-v1
protocol.go
ProtocolName
func ProtocolName(number uint16) string { names := map[uint16]string{ ProtoPair: "pair", ProtoPub: "pub", ProtoSub: "sub", ProtoReq: "req", ProtoRep: "rep", ProtoPush: "push", ProtoPull: "pull", ProtoSurveyor: "surveyor", ProtoRespondent: "respondent", ProtoBus: "bus"} return names[number] }
go
func ProtocolName(number uint16) string { names := map[uint16]string{ ProtoPair: "pair", ProtoPub: "pub", ProtoSub: "sub", ProtoReq: "req", ProtoRep: "rep", ProtoPush: "push", ProtoPull: "pull", ProtoSurveyor: "surveyor", ProtoRespondent: "respondent", ProtoBus: "bus"} return names[number] }
[ "func", "ProtocolName", "(", "number", "uint16", ")", "string", "{", "names", ":=", "map", "[", "uint16", "]", "string", "{", "ProtoPair", ":", "\"", "\"", ",", "ProtoPub", ":", "\"", "\"", ",", "ProtoSub", ":", "\"", "\"", ",", "ProtoReq", ":", "\"", "\"", ",", "ProtoRep", ":", "\"", "\"", ",", "ProtoPush", ":", "\"", "\"", ",", "ProtoPull", ":", "\"", "\"", ",", "ProtoSurveyor", ":", "\"", "\"", ",", "ProtoRespondent", ":", "\"", "\"", ",", "ProtoBus", ":", "\"", "\"", "}", "\n", "return", "names", "[", "number", "]", "\n", "}" ]
// ProtocolName returns the name corresponding to a given protocol number. // This is useful for transports like WebSocket, which use a text name // rather than the number in the handshake.
[ "ProtocolName", "returns", "the", "name", "corresponding", "to", "a", "given", "protocol", "number", ".", "This", "is", "useful", "for", "transports", "like", "WebSocket", "which", "use", "a", "text", "name", "rather", "than", "the", "number", "in", "the", "handshake", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol.go#L180-L193
train
nanomsg/mangos-v1
protocol.go
ValidPeers
func ValidPeers(p1, p2 Protocol) bool { if p1.Number() != p2.PeerNumber() { return false } if p2.Number() != p1.PeerNumber() { return false } return true }
go
func ValidPeers(p1, p2 Protocol) bool { if p1.Number() != p2.PeerNumber() { return false } if p2.Number() != p1.PeerNumber() { return false } return true }
[ "func", "ValidPeers", "(", "p1", ",", "p2", "Protocol", ")", "bool", "{", "if", "p1", ".", "Number", "(", ")", "!=", "p2", ".", "PeerNumber", "(", ")", "{", "return", "false", "\n", "}", "\n", "if", "p2", ".", "Number", "(", ")", "!=", "p1", ".", "PeerNumber", "(", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// ValidPeers returns true if the two sockets are capable of // peering to one another. For example, REQ can peer with REP, // but not with BUS.
[ "ValidPeers", "returns", "true", "if", "the", "two", "sockets", "are", "capable", "of", "peering", "to", "one", "another", ".", "For", "example", "REQ", "can", "peer", "with", "REP", "but", "not", "with", "BUS", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol.go#L198-L206
train
nanomsg/mangos-v1
transport/all/all.go
AddTransports
func AddTransports(sock mangos.Socket) { sock.AddTransport(tcp.NewTransport()) sock.AddTransport(inproc.NewTransport()) sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tlstcp.NewTransport()) sock.AddTransport(ws.NewTransport()) sock.AddTransport(wss.NewTransport()) }
go
func AddTransports(sock mangos.Socket) { sock.AddTransport(tcp.NewTransport()) sock.AddTransport(inproc.NewTransport()) sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tlstcp.NewTransport()) sock.AddTransport(ws.NewTransport()) sock.AddTransport(wss.NewTransport()) }
[ "func", "AddTransports", "(", "sock", "mangos", ".", "Socket", ")", "{", "sock", ".", "AddTransport", "(", "tcp", ".", "NewTransport", "(", ")", ")", "\n", "sock", ".", "AddTransport", "(", "inproc", ".", "NewTransport", "(", ")", ")", "\n", "sock", ".", "AddTransport", "(", "ipc", ".", "NewTransport", "(", ")", ")", "\n", "sock", ".", "AddTransport", "(", "tlstcp", ".", "NewTransport", "(", ")", ")", "\n", "sock", ".", "AddTransport", "(", "ws", ".", "NewTransport", "(", ")", ")", "\n", "sock", ".", "AddTransport", "(", "wss", ".", "NewTransport", "(", ")", ")", "\n", "}" ]
// AddTransports adds all known transports to the given socket.
[ "AddTransports", "adds", "all", "known", "transports", "to", "the", "given", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/all/all.go#L31-L38
train
nanomsg/mangos-v1
transport/tcp/tcp.go
get
func (o options) get(name string) (interface{}, error) { v, ok := o[name] if !ok { return nil, mangos.ErrBadOption } return v, nil }
go
func (o options) get(name string) (interface{}, error) { v, ok := o[name] if !ok { return nil, mangos.ErrBadOption } return v, nil }
[ "func", "(", "o", "options", ")", "get", "(", "name", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "v", ",", "ok", ":=", "o", "[", "name", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "mangos", ".", "ErrBadOption", "\n", "}", "\n", "return", "v", ",", "nil", "\n", "}" ]
// GetOption retrieves an option value.
[ "GetOption", "retrieves", "an", "option", "value", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/tcp/tcp.go#L29-L35
train
nanomsg/mangos-v1
transport/ws/ws.go
set
func (o options) set(name string, val interface{}) error { switch name { case mangos.OptionNoDelay: fallthrough case mangos.OptionKeepAlive: switch v := val.(type) { case bool: o[name] = v return nil default: return mangos.ErrBadValue } case mangos.OptionTLSConfig: switch v := val.(type) { case *tls.Config: o[name] = v return nil default: return mangos.ErrBadValue } case OptionWebSocketCheckOrigin: switch v := val.(type) { case bool: o[name] = v return nil default: return mangos.ErrBadValue } } return mangos.ErrBadOption }
go
func (o options) set(name string, val interface{}) error { switch name { case mangos.OptionNoDelay: fallthrough case mangos.OptionKeepAlive: switch v := val.(type) { case bool: o[name] = v return nil default: return mangos.ErrBadValue } case mangos.OptionTLSConfig: switch v := val.(type) { case *tls.Config: o[name] = v return nil default: return mangos.ErrBadValue } case OptionWebSocketCheckOrigin: switch v := val.(type) { case bool: o[name] = v return nil default: return mangos.ErrBadValue } } return mangos.ErrBadOption }
[ "func", "(", "o", "options", ")", "set", "(", "name", "string", ",", "val", "interface", "{", "}", ")", "error", "{", "switch", "name", "{", "case", "mangos", ".", "OptionNoDelay", ":", "fallthrough", "\n", "case", "mangos", ".", "OptionKeepAlive", ":", "switch", "v", ":=", "val", ".", "(", "type", ")", "{", "case", "bool", ":", "o", "[", "name", "]", "=", "v", "\n", "return", "nil", "\n", "default", ":", "return", "mangos", ".", "ErrBadValue", "\n", "}", "\n", "case", "mangos", ".", "OptionTLSConfig", ":", "switch", "v", ":=", "val", ".", "(", "type", ")", "{", "case", "*", "tls", ".", "Config", ":", "o", "[", "name", "]", "=", "v", "\n", "return", "nil", "\n", "default", ":", "return", "mangos", ".", "ErrBadValue", "\n", "}", "\n", "case", "OptionWebSocketCheckOrigin", ":", "switch", "v", ":=", "val", ".", "(", "type", ")", "{", "case", "bool", ":", "o", "[", "name", "]", "=", "v", "\n", "return", "nil", "\n", "default", ":", "return", "mangos", ".", "ErrBadValue", "\n", "}", "\n", "}", "\n", "return", "mangos", ".", "ErrBadOption", "\n", "}" ]
// SetOption sets an option. We have none, so just ErrBadOption.
[ "SetOption", "sets", "an", "option", ".", "We", "have", "none", "so", "just", "ErrBadOption", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/ws/ws.go#L91-L121
train
nanomsg/mangos-v1
protocol/req/req.go
nextID
func (r *req) nextID() uint32 { // The high order bit is "special", and must always be set. (This is // how the peer will detect the end of the backtrace.) v := r.nextid | 0x80000000 r.nextid++ return v }
go
func (r *req) nextID() uint32 { // The high order bit is "special", and must always be set. (This is // how the peer will detect the end of the backtrace.) v := r.nextid | 0x80000000 r.nextid++ return v }
[ "func", "(", "r", "*", "req", ")", "nextID", "(", ")", "uint32", "{", "// The high order bit is \"special\", and must always be set. (This is", "// how the peer will detect the end of the backtrace.)", "v", ":=", "r", ".", "nextid", "|", "0x80000000", "\n", "r", ".", "nextid", "++", "\n", "return", "v", "\n", "}" ]
// nextID returns the next request ID.
[ "nextID", "returns", "the", "next", "request", "ID", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol/req/req.go#L68-L74
train
nanomsg/mangos-v1
protocol/req/req.go
resender
func (r *req) resender() { defer r.w.Done() cq := r.sock.CloseChannel() for { select { case <-r.waker.C: case <-cq: return } r.Lock() m := r.reqmsg if m == nil { r.Unlock() continue } m = m.Dup() r.Unlock() r.resend <- m r.Lock() if r.retry > 0 { r.waker.Reset(r.retry) } else { r.waker.Stop() } r.Unlock() } }
go
func (r *req) resender() { defer r.w.Done() cq := r.sock.CloseChannel() for { select { case <-r.waker.C: case <-cq: return } r.Lock() m := r.reqmsg if m == nil { r.Unlock() continue } m = m.Dup() r.Unlock() r.resend <- m r.Lock() if r.retry > 0 { r.waker.Reset(r.retry) } else { r.waker.Stop() } r.Unlock() } }
[ "func", "(", "r", "*", "req", ")", "resender", "(", ")", "{", "defer", "r", ".", "w", ".", "Done", "(", ")", "\n", "cq", ":=", "r", ".", "sock", ".", "CloseChannel", "(", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "r", ".", "waker", ".", "C", ":", "case", "<-", "cq", ":", "return", "\n", "}", "\n\n", "r", ".", "Lock", "(", ")", "\n", "m", ":=", "r", ".", "reqmsg", "\n", "if", "m", "==", "nil", "{", "r", ".", "Unlock", "(", ")", "\n", "continue", "\n", "}", "\n", "m", "=", "m", ".", "Dup", "(", ")", "\n", "r", ".", "Unlock", "(", ")", "\n\n", "r", ".", "resend", "<-", "m", "\n", "r", ".", "Lock", "(", ")", "\n", "if", "r", ".", "retry", ">", "0", "{", "r", ".", "waker", ".", "Reset", "(", "r", ".", "retry", ")", "\n", "}", "else", "{", "r", ".", "waker", ".", "Stop", "(", ")", "\n", "}", "\n", "r", ".", "Unlock", "(", ")", "\n", "}", "\n", "}" ]
// resend sends the request message again, after a timer has expired.
[ "resend", "sends", "the", "request", "message", "again", "after", "a", "timer", "has", "expired", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol/req/req.go#L77-L107
train
nanomsg/mangos-v1
protocol/bus/bus.go
Init
func (x *bus) Init(sock mangos.ProtocolSocket) { x.sock = sock x.peers = make(map[uint32]*busEp) x.w.Init() x.w.Add() go x.sender() }
go
func (x *bus) Init(sock mangos.ProtocolSocket) { x.sock = sock x.peers = make(map[uint32]*busEp) x.w.Init() x.w.Add() go x.sender() }
[ "func", "(", "x", "*", "bus", ")", "Init", "(", "sock", "mangos", ".", "ProtocolSocket", ")", "{", "x", ".", "sock", "=", "sock", "\n", "x", ".", "peers", "=", "make", "(", "map", "[", "uint32", "]", "*", "busEp", ")", "\n", "x", ".", "w", ".", "Init", "(", ")", "\n", "x", ".", "w", ".", "Add", "(", ")", "\n", "go", "x", ".", "sender", "(", ")", "\n", "}" ]
// Init implements the Protocol Init method.
[ "Init", "implements", "the", "Protocol", "Init", "method", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol/bus/bus.go#L44-L50
train
nanomsg/mangos-v1
protocol/bus/bus.go
peerSender
func (pe *busEp) peerSender() { for { m := <-pe.q if m == nil { return } if pe.ep.SendMsg(m) != nil { m.Free() return } } }
go
func (pe *busEp) peerSender() { for { m := <-pe.q if m == nil { return } if pe.ep.SendMsg(m) != nil { m.Free() return } } }
[ "func", "(", "pe", "*", "busEp", ")", "peerSender", "(", ")", "{", "for", "{", "m", ":=", "<-", "pe", ".", "q", "\n", "if", "m", "==", "nil", "{", "return", "\n", "}", "\n", "if", "pe", ".", "ep", ".", "SendMsg", "(", "m", ")", "!=", "nil", "{", "m", ".", "Free", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Bottom sender.
[ "Bottom", "sender", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol/bus/bus.go#L69-L80
train
nanomsg/mangos-v1
compat/compat.go
NewSocket
func NewSocket(d Domain, p Protocol) (*Socket, error) { var s Socket var err error s.proto = p s.dom = d switch p { case PUB: s.sock, err = pub.NewSocket() case SUB: s.sock, err = sub.NewSocket() case PUSH: s.sock, err = push.NewSocket() case PULL: s.sock, err = pull.NewSocket() case REQ: s.sock, err = req.NewSocket() case REP: s.sock, err = rep.NewSocket() case SURVEYOR: s.sock, err = surveyor.NewSocket() case RESPONDENT: s.sock, err = respondent.NewSocket() case PAIR: s.sock, err = pair.NewSocket() case BUS: s.sock, err = bus.NewSocket() default: err = mangos.ErrBadProto } if err != nil { return nil, err } switch d { case AF_SP: case AF_SP_RAW: err = s.sock.SetOption(mangos.OptionRaw, true) default: err = errBadDomain } if err != nil { s.sock.Close() return nil, err } // Compat mode sockets should timeout on send if we don't have any pipes if err = s.sock.SetOption(mangos.OptionWriteQLen, 0); err != nil { s.sock.Close() return nil, err } s.rto = -1 s.sto = -1 all.AddTransports(s.sock) return &s, nil }
go
func NewSocket(d Domain, p Protocol) (*Socket, error) { var s Socket var err error s.proto = p s.dom = d switch p { case PUB: s.sock, err = pub.NewSocket() case SUB: s.sock, err = sub.NewSocket() case PUSH: s.sock, err = push.NewSocket() case PULL: s.sock, err = pull.NewSocket() case REQ: s.sock, err = req.NewSocket() case REP: s.sock, err = rep.NewSocket() case SURVEYOR: s.sock, err = surveyor.NewSocket() case RESPONDENT: s.sock, err = respondent.NewSocket() case PAIR: s.sock, err = pair.NewSocket() case BUS: s.sock, err = bus.NewSocket() default: err = mangos.ErrBadProto } if err != nil { return nil, err } switch d { case AF_SP: case AF_SP_RAW: err = s.sock.SetOption(mangos.OptionRaw, true) default: err = errBadDomain } if err != nil { s.sock.Close() return nil, err } // Compat mode sockets should timeout on send if we don't have any pipes if err = s.sock.SetOption(mangos.OptionWriteQLen, 0); err != nil { s.sock.Close() return nil, err } s.rto = -1 s.sto = -1 all.AddTransports(s.sock) return &s, nil }
[ "func", "NewSocket", "(", "d", "Domain", ",", "p", "Protocol", ")", "(", "*", "Socket", ",", "error", ")", "{", "var", "s", "Socket", "\n", "var", "err", "error", "\n\n", "s", ".", "proto", "=", "p", "\n", "s", ".", "dom", "=", "d", "\n\n", "switch", "p", "{", "case", "PUB", ":", "s", ".", "sock", ",", "err", "=", "pub", ".", "NewSocket", "(", ")", "\n", "case", "SUB", ":", "s", ".", "sock", ",", "err", "=", "sub", ".", "NewSocket", "(", ")", "\n", "case", "PUSH", ":", "s", ".", "sock", ",", "err", "=", "push", ".", "NewSocket", "(", ")", "\n", "case", "PULL", ":", "s", ".", "sock", ",", "err", "=", "pull", ".", "NewSocket", "(", ")", "\n", "case", "REQ", ":", "s", ".", "sock", ",", "err", "=", "req", ".", "NewSocket", "(", ")", "\n", "case", "REP", ":", "s", ".", "sock", ",", "err", "=", "rep", ".", "NewSocket", "(", ")", "\n", "case", "SURVEYOR", ":", "s", ".", "sock", ",", "err", "=", "surveyor", ".", "NewSocket", "(", ")", "\n", "case", "RESPONDENT", ":", "s", ".", "sock", ",", "err", "=", "respondent", ".", "NewSocket", "(", ")", "\n", "case", "PAIR", ":", "s", ".", "sock", ",", "err", "=", "pair", ".", "NewSocket", "(", ")", "\n", "case", "BUS", ":", "s", ".", "sock", ",", "err", "=", "bus", ".", "NewSocket", "(", ")", "\n", "default", ":", "err", "=", "mangos", ".", "ErrBadProto", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "switch", "d", "{", "case", "AF_SP", ":", "case", "AF_SP_RAW", ":", "err", "=", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionRaw", ",", "true", ")", "\n", "default", ":", "err", "=", "errBadDomain", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "s", ".", "sock", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Compat mode sockets should timeout on send if we don't have any pipes", "if", "err", "=", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionWriteQLen", ",", "0", ")", ";", "err", "!=", "nil", "{", "s", ".", "sock", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "s", ".", "rto", "=", "-", "1", "\n", "s", ".", "sto", "=", "-", "1", "\n", "all", ".", "AddTransports", "(", "s", ".", "sock", ")", "\n", "return", "&", "s", ",", "nil", "\n", "}" ]
// NewSocket allocates a new Socket. The Socket is the handle used to // access the underlying library.
[ "NewSocket", "allocates", "a", "new", "Socket", ".", "The", "Socket", "is", "the", "handle", "used", "to", "access", "the", "underlying", "library", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L113-L172
train
nanomsg/mangos-v1
compat/compat.go
Close
func (s *Socket) Close() error { if s.sock != nil { s.sock.Close() } return nil }
go
func (s *Socket) Close() error { if s.sock != nil { s.sock.Close() } return nil }
[ "func", "(", "s", "*", "Socket", ")", "Close", "(", ")", "error", "{", "if", "s", ".", "sock", "!=", "nil", "{", "s", ".", "sock", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close shuts down the socket.
[ "Close", "shuts", "down", "the", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L175-L180
train
nanomsg/mangos-v1
compat/compat.go
Send
func (s *Socket) Send(b []byte, flags int) (int, error) { if flags != 0 { return -1, errNoFlag } m := mangos.NewMessage(len(b)) m.Body = append(m.Body, b...) // Legacy nanomsg uses the opposite semantic for negative and // zero values than mangos. A bit unfortunate. switch { case s.sto > 0: s.sock.SetOption(mangos.OptionSendDeadline, s.sto) case s.sto == 0: s.sock.SetOption(mangos.OptionSendDeadline, -1) case s.sto < 0: s.sock.SetOption(mangos.OptionSendDeadline, 0) } return len(b), s.sock.SendMsg(m) }
go
func (s *Socket) Send(b []byte, flags int) (int, error) { if flags != 0 { return -1, errNoFlag } m := mangos.NewMessage(len(b)) m.Body = append(m.Body, b...) // Legacy nanomsg uses the opposite semantic for negative and // zero values than mangos. A bit unfortunate. switch { case s.sto > 0: s.sock.SetOption(mangos.OptionSendDeadline, s.sto) case s.sto == 0: s.sock.SetOption(mangos.OptionSendDeadline, -1) case s.sto < 0: s.sock.SetOption(mangos.OptionSendDeadline, 0) } return len(b), s.sock.SendMsg(m) }
[ "func", "(", "s", "*", "Socket", ")", "Send", "(", "b", "[", "]", "byte", ",", "flags", "int", ")", "(", "int", ",", "error", ")", "{", "if", "flags", "!=", "0", "{", "return", "-", "1", ",", "errNoFlag", "\n", "}", "\n\n", "m", ":=", "mangos", ".", "NewMessage", "(", "len", "(", "b", ")", ")", "\n", "m", ".", "Body", "=", "append", "(", "m", ".", "Body", ",", "b", "...", ")", "\n\n", "// Legacy nanomsg uses the opposite semantic for negative and", "// zero values than mangos. A bit unfortunate.", "switch", "{", "case", "s", ".", "sto", ">", "0", ":", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionSendDeadline", ",", "s", ".", "sto", ")", "\n", "case", "s", ".", "sto", "==", "0", ":", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionSendDeadline", ",", "-", "1", ")", "\n", "case", "s", ".", "sto", "<", "0", ":", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionSendDeadline", ",", "0", ")", "\n", "}", "\n\n", "return", "len", "(", "b", ")", ",", "s", ".", "sock", ".", "SendMsg", "(", "m", ")", "\n", "}" ]
// Send sends a message. For AF_SP_RAW messages the header must be // included in the argument. At this time, no flags are supported.
[ "Send", "sends", "a", "message", ".", "For", "AF_SP_RAW", "messages", "the", "header", "must", "be", "included", "in", "the", "argument", ".", "At", "this", "time", "no", "flags", "are", "supported", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L247-L268
train
nanomsg/mangos-v1
compat/compat.go
Linger
func (s *Socket) Linger() (time.Duration, error) { var t time.Duration return t, errNotSup }
go
func (s *Socket) Linger() (time.Duration, error) { var t time.Duration return t, errNotSup }
[ "func", "(", "s", "*", "Socket", ")", "Linger", "(", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "var", "t", "time", ".", "Duration", "\n", "return", "t", ",", "errNotSup", "\n", "}" ]
// Linger should set the TCP linger time, but at present is not supported.
[ "Linger", "should", "set", "the", "TCP", "linger", "time", "but", "at", "present", "is", "not", "supported", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L303-L306
train
nanomsg/mangos-v1
compat/compat.go
NewBusSocket
func NewBusSocket() (*BusSocket, error) { s, err := NewSocket(AF_SP, BUS) return &BusSocket{s}, err }
go
func NewBusSocket() (*BusSocket, error) { s, err := NewSocket(AF_SP, BUS) return &BusSocket{s}, err }
[ "func", "NewBusSocket", "(", ")", "(", "*", "BusSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "BUS", ")", "\n", "return", "&", "BusSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewBusSocket creates a BUS socket.
[ "NewBusSocket", "creates", "a", "BUS", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L352-L355
train
nanomsg/mangos-v1
compat/compat.go
NewPairSocket
func NewPairSocket() (*PairSocket, error) { s, err := NewSocket(AF_SP, PAIR) return &PairSocket{s}, err }
go
func NewPairSocket() (*PairSocket, error) { s, err := NewSocket(AF_SP, PAIR) return &PairSocket{s}, err }
[ "func", "NewPairSocket", "(", ")", "(", "*", "PairSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "PAIR", ")", "\n", "return", "&", "PairSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewPairSocket creates a PAIR socket.
[ "NewPairSocket", "creates", "a", "PAIR", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L363-L366
train
nanomsg/mangos-v1
compat/compat.go
NewPubSocket
func NewPubSocket() (*PubSocket, error) { s, err := NewSocket(AF_SP, PUB) return &PubSocket{s}, err }
go
func NewPubSocket() (*PubSocket, error) { s, err := NewSocket(AF_SP, PUB) return &PubSocket{s}, err }
[ "func", "NewPubSocket", "(", ")", "(", "*", "PubSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "PUB", ")", "\n", "return", "&", "PubSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewPubSocket creates a PUB socket.
[ "NewPubSocket", "creates", "a", "PUB", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L374-L377
train
nanomsg/mangos-v1
compat/compat.go
NewPullSocket
func NewPullSocket() (*PullSocket, error) { s, err := NewSocket(AF_SP, PULL) return &PullSocket{s}, err }
go
func NewPullSocket() (*PullSocket, error) { s, err := NewSocket(AF_SP, PULL) return &PullSocket{s}, err }
[ "func", "NewPullSocket", "(", ")", "(", "*", "PullSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "PULL", ")", "\n", "return", "&", "PullSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewPullSocket creates a PULL socket.
[ "NewPullSocket", "creates", "a", "PULL", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L385-L388
train
nanomsg/mangos-v1
compat/compat.go
NewPushSocket
func NewPushSocket() (*PushSocket, error) { s, err := NewSocket(AF_SP, PUSH) return &PushSocket{s}, err }
go
func NewPushSocket() (*PushSocket, error) { s, err := NewSocket(AF_SP, PUSH) return &PushSocket{s}, err }
[ "func", "NewPushSocket", "(", ")", "(", "*", "PushSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "PUSH", ")", "\n", "return", "&", "PushSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewPushSocket creates a PUSH socket.
[ "NewPushSocket", "creates", "a", "PUSH", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L396-L399
train
nanomsg/mangos-v1
compat/compat.go
NewRepSocket
func NewRepSocket() (*RepSocket, error) { s, err := NewSocket(AF_SP, REP) return &RepSocket{s}, err }
go
func NewRepSocket() (*RepSocket, error) { s, err := NewSocket(AF_SP, REP) return &RepSocket{s}, err }
[ "func", "NewRepSocket", "(", ")", "(", "*", "RepSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "REP", ")", "\n", "return", "&", "RepSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewRepSocket creates a REP socket.
[ "NewRepSocket", "creates", "a", "REP", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L407-L410
train
nanomsg/mangos-v1
compat/compat.go
NewReqSocket
func NewReqSocket() (*ReqSocket, error) { s, err := NewSocket(AF_SP, REQ) return &ReqSocket{s}, err }
go
func NewReqSocket() (*ReqSocket, error) { s, err := NewSocket(AF_SP, REQ) return &ReqSocket{s}, err }
[ "func", "NewReqSocket", "(", ")", "(", "*", "ReqSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "REQ", ")", "\n", "return", "&", "ReqSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewReqSocket creates a REQ socket.
[ "NewReqSocket", "creates", "a", "REQ", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L418-L421
train
nanomsg/mangos-v1
compat/compat.go
NewRespondentSocket
func NewRespondentSocket() (*RespondentSocket, error) { s, err := NewSocket(AF_SP, RESPONDENT) return &RespondentSocket{s}, err }
go
func NewRespondentSocket() (*RespondentSocket, error) { s, err := NewSocket(AF_SP, RESPONDENT) return &RespondentSocket{s}, err }
[ "func", "NewRespondentSocket", "(", ")", "(", "*", "RespondentSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "RESPONDENT", ")", "\n", "return", "&", "RespondentSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewRespondentSocket creates a RESPONDENT socket.
[ "NewRespondentSocket", "creates", "a", "RESPONDENT", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L429-L432
train
nanomsg/mangos-v1
compat/compat.go
Subscribe
func (s *SubSocket) Subscribe(topic string) error { return s.sock.SetOption(mangos.OptionSubscribe, topic) }
go
func (s *SubSocket) Subscribe(topic string) error { return s.sock.SetOption(mangos.OptionSubscribe, topic) }
[ "func", "(", "s", "*", "SubSocket", ")", "Subscribe", "(", "topic", "string", ")", "error", "{", "return", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionSubscribe", ",", "topic", ")", "\n", "}" ]
// Subscribe registers interest in a topic.
[ "Subscribe", "registers", "interest", "in", "a", "topic", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L440-L442
train
nanomsg/mangos-v1
compat/compat.go
Unsubscribe
func (s *SubSocket) Unsubscribe(topic string) error { return s.sock.SetOption(mangos.OptionUnsubscribe, topic) }
go
func (s *SubSocket) Unsubscribe(topic string) error { return s.sock.SetOption(mangos.OptionUnsubscribe, topic) }
[ "func", "(", "s", "*", "SubSocket", ")", "Unsubscribe", "(", "topic", "string", ")", "error", "{", "return", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionUnsubscribe", ",", "topic", ")", "\n", "}" ]
// Unsubscribe unregisters interest in a topic.
[ "Unsubscribe", "unregisters", "interest", "in", "a", "topic", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L445-L447
train
nanomsg/mangos-v1
compat/compat.go
NewSubSocket
func NewSubSocket() (*SubSocket, error) { s, err := NewSocket(AF_SP, SUB) return &SubSocket{s}, err }
go
func NewSubSocket() (*SubSocket, error) { s, err := NewSocket(AF_SP, SUB) return &SubSocket{s}, err }
[ "func", "NewSubSocket", "(", ")", "(", "*", "SubSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "SUB", ")", "\n", "return", "&", "SubSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewSubSocket creates a SUB socket.
[ "NewSubSocket", "creates", "a", "SUB", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L450-L453
train
nanomsg/mangos-v1
compat/compat.go
Deadline
func (s *SurveyorSocket) Deadline() (time.Duration, error) { var d time.Duration v, err := s.sock.GetOption(mangos.OptionSurveyTime) if err == nil { d = v.(time.Duration) } return d, err }
go
func (s *SurveyorSocket) Deadline() (time.Duration, error) { var d time.Duration v, err := s.sock.GetOption(mangos.OptionSurveyTime) if err == nil { d = v.(time.Duration) } return d, err }
[ "func", "(", "s", "*", "SurveyorSocket", ")", "Deadline", "(", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "var", "d", "time", ".", "Duration", "\n", "v", ",", "err", ":=", "s", ".", "sock", ".", "GetOption", "(", "mangos", ".", "OptionSurveyTime", ")", "\n", "if", "err", "==", "nil", "{", "d", "=", "v", ".", "(", "time", ".", "Duration", ")", "\n", "}", "\n", "return", "d", ",", "err", "\n", "}" ]
// Deadline returns the survey deadline on the socket. After this time, // responses from a survey will be discarded.
[ "Deadline", "returns", "the", "survey", "deadline", "on", "the", "socket", ".", "After", "this", "time", "responses", "from", "a", "survey", "will", "be", "discarded", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L462-L469
train
nanomsg/mangos-v1
compat/compat.go
SetDeadline
func (s *SurveyorSocket) SetDeadline(d time.Duration) error { return s.sock.SetOption(mangos.OptionSurveyTime, d) }
go
func (s *SurveyorSocket) SetDeadline(d time.Duration) error { return s.sock.SetOption(mangos.OptionSurveyTime, d) }
[ "func", "(", "s", "*", "SurveyorSocket", ")", "SetDeadline", "(", "d", "time", ".", "Duration", ")", "error", "{", "return", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionSurveyTime", ",", "d", ")", "\n", "}" ]
// SetDeadline sets the survey deadline on the socket. After this time, // responses from a survey will be discarded.
[ "SetDeadline", "sets", "the", "survey", "deadline", "on", "the", "socket", ".", "After", "this", "time", "responses", "from", "a", "survey", "will", "be", "discarded", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L473-L475
train
nanomsg/mangos-v1
compat/compat.go
NewSurveyorSocket
func NewSurveyorSocket() (*SurveyorSocket, error) { s, err := NewSocket(AF_SP, SURVEYOR) return &SurveyorSocket{s}, err }
go
func NewSurveyorSocket() (*SurveyorSocket, error) { s, err := NewSocket(AF_SP, SURVEYOR) return &SurveyorSocket{s}, err }
[ "func", "NewSurveyorSocket", "(", ")", "(", "*", "SurveyorSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "SURVEYOR", ")", "\n", "return", "&", "SurveyorSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewSurveyorSocket creates a SURVEYOR socket.
[ "NewSurveyorSocket", "creates", "a", "SURVEYOR", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L478-L481
train
nanomsg/mangos-v1
transport/ipc/ipc_unix.go
Dial
func (d *dialer) Dial() (mangos.Pipe, error) { conn, err := net.DialUnix("unix", nil, d.addr) if err != nil { return nil, err } return mangos.NewConnPipeIPC(conn, d.sock) }
go
func (d *dialer) Dial() (mangos.Pipe, error) { conn, err := net.DialUnix("unix", nil, d.addr) if err != nil { return nil, err } return mangos.NewConnPipeIPC(conn, d.sock) }
[ "func", "(", "d", "*", "dialer", ")", "Dial", "(", ")", "(", "mangos", ".", "Pipe", ",", "error", ")", "{", "conn", ",", "err", ":=", "net", ".", "DialUnix", "(", "\"", "\"", ",", "nil", ",", "d", ".", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "mangos", ".", "NewConnPipeIPC", "(", "conn", ",", "d", ".", "sock", ")", "\n", "}" ]
// Dial implements the PipeDialer Dial method
[ "Dial", "implements", "the", "PipeDialer", "Dial", "method" ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/ipc/ipc_unix.go#L53-L60
train
nanomsg/mangos-v1
core.go
SendChannel
func (sock *socket) SendChannel() <-chan *Message { sock.Lock() defer sock.Unlock() return sock.uwq }
go
func (sock *socket) SendChannel() <-chan *Message { sock.Lock() defer sock.Unlock() return sock.uwq }
[ "func", "(", "sock", "*", "socket", ")", "SendChannel", "(", ")", "<-", "chan", "*", "Message", "{", "sock", ".", "Lock", "(", ")", "\n", "defer", "sock", ".", "Unlock", "(", ")", "\n", "return", "sock", ".", "uwq", "\n", "}" ]
// Implementation of ProtocolSocket bits on socket. This is the middle // API presented to Protocol implementations.
[ "Implementation", "of", "ProtocolSocket", "bits", "on", "socket", ".", "This", "is", "the", "middle", "API", "presented", "to", "Protocol", "implementations", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/core.go#L149-L153
train
nanomsg/mangos-v1
core.go
Close
func (sock *socket) Close() error { fin := time.Now().Add(sock.linger) DrainChannel(sock.uwq, fin) sock.Lock() if sock.closing { sock.Unlock() return ErrClosed } sock.closing = true close(sock.closeq) for _, l := range sock.listeners { l.l.Close() } pipes := sock.pipes sock.pipes = nil sock.Unlock() // A second drain, just to be sure. (We could have had device or // forwarded messages arrive since the last one.) DrainChannel(sock.uwq, fin) // And tell the protocol to shutdown and drain its pipes too. sock.proto.Shutdown(fin) for p := range pipes { p.Close() } return nil }
go
func (sock *socket) Close() error { fin := time.Now().Add(sock.linger) DrainChannel(sock.uwq, fin) sock.Lock() if sock.closing { sock.Unlock() return ErrClosed } sock.closing = true close(sock.closeq) for _, l := range sock.listeners { l.l.Close() } pipes := sock.pipes sock.pipes = nil sock.Unlock() // A second drain, just to be sure. (We could have had device or // forwarded messages arrive since the last one.) DrainChannel(sock.uwq, fin) // And tell the protocol to shutdown and drain its pipes too. sock.proto.Shutdown(fin) for p := range pipes { p.Close() } return nil }
[ "func", "(", "sock", "*", "socket", ")", "Close", "(", ")", "error", "{", "fin", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "sock", ".", "linger", ")", "\n\n", "DrainChannel", "(", "sock", ".", "uwq", ",", "fin", ")", "\n\n", "sock", ".", "Lock", "(", ")", "\n", "if", "sock", ".", "closing", "{", "sock", ".", "Unlock", "(", ")", "\n", "return", "ErrClosed", "\n", "}", "\n", "sock", ".", "closing", "=", "true", "\n", "close", "(", "sock", ".", "closeq", ")", "\n\n", "for", "_", ",", "l", ":=", "range", "sock", ".", "listeners", "{", "l", ".", "l", ".", "Close", "(", ")", "\n", "}", "\n", "pipes", ":=", "sock", ".", "pipes", "\n", "sock", ".", "pipes", "=", "nil", "\n", "sock", ".", "Unlock", "(", ")", "\n\n", "// A second drain, just to be sure. (We could have had device or", "// forwarded messages arrive since the last one.)", "DrainChannel", "(", "sock", ".", "uwq", ",", "fin", ")", "\n\n", "// And tell the protocol to shutdown and drain its pipes too.", "sock", ".", "proto", ".", "Shutdown", "(", "fin", ")", "\n\n", "for", "p", ":=", "range", "pipes", "{", "p", ".", "Close", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// // Implementation of Socket bits on socket. This is the upper API // presented to applications. //
[ "Implementation", "of", "Socket", "bits", "on", "socket", ".", "This", "is", "the", "upper", "API", "presented", "to", "applications", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/core.go#L186-L219
train
nanomsg/mangos-v1
core.go
String
func (sock *socket) String() string { return fmt.Sprintf("SOCKET[%s](%p)", sock.proto.Name(), sock) }
go
func (sock *socket) String() string { return fmt.Sprintf("SOCKET[%s](%p)", sock.proto.Name(), sock) }
[ "func", "(", "sock", "*", "socket", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "sock", ".", "proto", ".", "Name", "(", ")", ",", "sock", ")", "\n", "}" ]
// String just emits a very high level debug. This avoids // triggering race conditions from trying to print %v without // holding locks on structure members.
[ "String", "just", "emits", "a", "very", "high", "level", "debug", ".", "This", "avoids", "triggering", "race", "conditions", "from", "trying", "to", "print", "%v", "without", "holding", "locks", "on", "structure", "members", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/core.go#L280-L282
train
nanomsg/mangos-v1
core.go
dialer
func (d *dialer) dialer() { rtime := d.sock.reconntime rtmax := d.sock.reconnmax for { p, err := d.d.Dial() if err == nil { // reset retry time rtime = d.sock.reconntime d.sock.Lock() if d.closed { d.sock.Unlock() p.Close() return } d.sock.Unlock() if cp := d.sock.addPipe(p, d, nil); cp != nil { select { case <-d.sock.closeq: // parent socket closed case <-cp.closeq: // disconnect event case <-d.closeq: // dialer closed } } } // we're redialing here select { case <-d.closeq: // dialer closed if p != nil { p.Close() } return case <-d.sock.closeq: // exit if parent socket closed if p != nil { p.Close() } return case <-time.After(rtime): if rtmax > 0 { rtime *= 2 if rtime > rtmax { rtime = rtmax } } continue } } }
go
func (d *dialer) dialer() { rtime := d.sock.reconntime rtmax := d.sock.reconnmax for { p, err := d.d.Dial() if err == nil { // reset retry time rtime = d.sock.reconntime d.sock.Lock() if d.closed { d.sock.Unlock() p.Close() return } d.sock.Unlock() if cp := d.sock.addPipe(p, d, nil); cp != nil { select { case <-d.sock.closeq: // parent socket closed case <-cp.closeq: // disconnect event case <-d.closeq: // dialer closed } } } // we're redialing here select { case <-d.closeq: // dialer closed if p != nil { p.Close() } return case <-d.sock.closeq: // exit if parent socket closed if p != nil { p.Close() } return case <-time.After(rtime): if rtmax > 0 { rtime *= 2 if rtime > rtmax { rtime = rtmax } } continue } } }
[ "func", "(", "d", "*", "dialer", ")", "dialer", "(", ")", "{", "rtime", ":=", "d", ".", "sock", ".", "reconntime", "\n", "rtmax", ":=", "d", ".", "sock", ".", "reconnmax", "\n", "for", "{", "p", ",", "err", ":=", "d", ".", "d", ".", "Dial", "(", ")", "\n", "if", "err", "==", "nil", "{", "// reset retry time", "rtime", "=", "d", ".", "sock", ".", "reconntime", "\n", "d", ".", "sock", ".", "Lock", "(", ")", "\n", "if", "d", ".", "closed", "{", "d", ".", "sock", ".", "Unlock", "(", ")", "\n", "p", ".", "Close", "(", ")", "\n", "return", "\n", "}", "\n", "d", ".", "sock", ".", "Unlock", "(", ")", "\n", "if", "cp", ":=", "d", ".", "sock", ".", "addPipe", "(", "p", ",", "d", ",", "nil", ")", ";", "cp", "!=", "nil", "{", "select", "{", "case", "<-", "d", ".", "sock", ".", "closeq", ":", "// parent socket closed", "case", "<-", "cp", ".", "closeq", ":", "// disconnect event", "case", "<-", "d", ".", "closeq", ":", "// dialer closed", "}", "\n", "}", "\n", "}", "\n\n", "// we're redialing here", "select", "{", "case", "<-", "d", ".", "closeq", ":", "// dialer closed", "if", "p", "!=", "nil", "{", "p", ".", "Close", "(", ")", "\n", "}", "\n", "return", "\n", "case", "<-", "d", ".", "sock", ".", "closeq", ":", "// exit if parent socket closed", "if", "p", "!=", "nil", "{", "p", ".", "Close", "(", ")", "\n", "}", "\n", "return", "\n", "case", "<-", "time", ".", "After", "(", "rtime", ")", ":", "if", "rtmax", ">", "0", "{", "rtime", "*=", "2", "\n", "if", "rtime", ">", "rtmax", "{", "rtime", "=", "rtmax", "\n", "}", "\n", "}", "\n", "continue", "\n", "}", "\n", "}", "\n", "}" ]
// dialer is used to dial or redial from a goroutine.
[ "dialer", "is", "used", "to", "dial", "or", "redial", "from", "a", "goroutine", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/core.go#L614-L660
train
nanomsg/mangos-v1
core.go
serve
func (l *listener) serve() { for { select { case <-l.sock.closeq: return default: } // If the underlying PipeListener is closed, or not // listening, we expect to return back with an error. if pipe, err := l.l.Accept(); err == nil { l.sock.addPipe(pipe, nil, l) } else if err == ErrClosed { return } } }
go
func (l *listener) serve() { for { select { case <-l.sock.closeq: return default: } // If the underlying PipeListener is closed, or not // listening, we expect to return back with an error. if pipe, err := l.l.Accept(); err == nil { l.sock.addPipe(pipe, nil, l) } else if err == ErrClosed { return } } }
[ "func", "(", "l", "*", "listener", ")", "serve", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "l", ".", "sock", ".", "closeq", ":", "return", "\n", "default", ":", "}", "\n\n", "// If the underlying PipeListener is closed, or not", "// listening, we expect to return back with an error.", "if", "pipe", ",", "err", ":=", "l", ".", "l", ".", "Accept", "(", ")", ";", "err", "==", "nil", "{", "l", ".", "sock", ".", "addPipe", "(", "pipe", ",", "nil", ",", "l", ")", "\n", "}", "else", "if", "err", "==", "ErrClosed", "{", "return", "\n", "}", "\n", "}", "\n", "}" ]
// serve spins in a loop, calling the accepter's Accept routine.
[ "serve", "spins", "in", "a", "loop", "calling", "the", "accepter", "s", "Accept", "routine", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/core.go#L677-L693
train
nanomsg/mangos-v1
protocol/pub/pub.go
sender
func (p *pub) sender() { defer p.w.Done() cq := p.sock.CloseChannel() sq := p.sock.SendChannel() for { select { case <-cq: return case m := <-sq: if m == nil { sq = p.sock.SendChannel() continue } p.Lock() for _, peer := range p.eps { m := m.Dup() select { case peer.q <- m: default: m.Free() } } p.Unlock() m.Free() } } }
go
func (p *pub) sender() { defer p.w.Done() cq := p.sock.CloseChannel() sq := p.sock.SendChannel() for { select { case <-cq: return case m := <-sq: if m == nil { sq = p.sock.SendChannel() continue } p.Lock() for _, peer := range p.eps { m := m.Dup() select { case peer.q <- m: default: m.Free() } } p.Unlock() m.Free() } } }
[ "func", "(", "p", "*", "pub", ")", "sender", "(", ")", "{", "defer", "p", ".", "w", ".", "Done", "(", ")", "\n\n", "cq", ":=", "p", ".", "sock", ".", "CloseChannel", "(", ")", "\n", "sq", ":=", "p", ".", "sock", ".", "SendChannel", "(", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "cq", ":", "return", "\n\n", "case", "m", ":=", "<-", "sq", ":", "if", "m", "==", "nil", "{", "sq", "=", "p", ".", "sock", ".", "SendChannel", "(", ")", "\n", "continue", "\n", "}", "\n\n", "p", ".", "Lock", "(", ")", "\n", "for", "_", ",", "peer", ":=", "range", "p", ".", "eps", "{", "m", ":=", "m", ".", "Dup", "(", ")", "\n", "select", "{", "case", "peer", ".", "q", "<-", "m", ":", "default", ":", "m", ".", "Free", "(", ")", "\n", "}", "\n", "}", "\n", "p", ".", "Unlock", "(", ")", "\n", "m", ".", "Free", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Top sender.
[ "Top", "sender", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol/pub/pub.go#L85-L115
train
nanomsg/mangos-v1
message.go
Free
func (m *Message) Free() { if v := atomic.AddInt32(&m.refcnt, -1); v > 0 { return } for i := range messageCache { if m.bsize == messageCache[i].maxbody { messageCache[i].pool.Put(m) return } } }
go
func (m *Message) Free() { if v := atomic.AddInt32(&m.refcnt, -1); v > 0 { return } for i := range messageCache { if m.bsize == messageCache[i].maxbody { messageCache[i].pool.Put(m) return } } }
[ "func", "(", "m", "*", "Message", ")", "Free", "(", ")", "{", "if", "v", ":=", "atomic", ".", "AddInt32", "(", "&", "m", ".", "refcnt", ",", "-", "1", ")", ";", "v", ">", "0", "{", "return", "\n", "}", "\n", "for", "i", ":=", "range", "messageCache", "{", "if", "m", ".", "bsize", "==", "messageCache", "[", "i", "]", ".", "maxbody", "{", "messageCache", "[", "i", "]", ".", "pool", ".", "Put", "(", "m", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Free decrements the reference count on a message, and releases its // resources if no further references remain. While this is not // strictly necessary thanks to GC, doing so allows for the resources to // be recycled without engaging GC. This can have rather substantial // benefits for performance.
[ "Free", "decrements", "the", "reference", "count", "on", "a", "message", "and", "releases", "its", "resources", "if", "no", "further", "references", "remain", ".", "While", "this", "is", "not", "strictly", "necessary", "thanks", "to", "GC", "doing", "so", "allows", "for", "the", "resources", "to", "be", "recycled", "without", "engaging", "GC", ".", "This", "can", "have", "rather", "substantial", "benefits", "for", "performance", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/message.go#L115-L125
train
nanomsg/mangos-v1
message.go
Expired
func (m *Message) Expired() bool { if m.expire.IsZero() { return false } if m.expire.After(time.Now()) { return false } return true }
go
func (m *Message) Expired() bool { if m.expire.IsZero() { return false } if m.expire.After(time.Now()) { return false } return true }
[ "func", "(", "m", "*", "Message", ")", "Expired", "(", ")", "bool", "{", "if", "m", ".", "expire", ".", "IsZero", "(", ")", "{", "return", "false", "\n", "}", "\n", "if", "m", ".", "expire", ".", "After", "(", "time", ".", "Now", "(", ")", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Expired returns true if the message has "expired". This is used by // transport implementations to discard messages that have been // stuck in the write queue for too long, and should be discarded rather // than delivered across the transport. This is only used on the TX // path, there is no sense of "expiration" on the RX path.
[ "Expired", "returns", "true", "if", "the", "message", "has", "expired", ".", "This", "is", "used", "by", "transport", "implementations", "to", "discard", "messages", "that", "have", "been", "stuck", "in", "the", "write", "queue", "for", "too", "long", "and", "should", "be", "discarded", "rather", "than", "delivered", "across", "the", "transport", ".", "This", "is", "only", "used", "on", "the", "TX", "path", "there", "is", "no", "sense", "of", "expiration", "on", "the", "RX", "path", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/message.go#L144-L152
train
nanomsg/mangos-v1
message.go
NewMessage
func NewMessage(sz int) *Message { var m *Message for i := range messageCache { if sz < messageCache[i].maxbody { m = messageCache[i].pool.Get().(*Message) break } } if m == nil { m = newMsg(sz) } m.refcnt = 1 m.Body = m.bbuf m.Header = m.hbuf return m }
go
func NewMessage(sz int) *Message { var m *Message for i := range messageCache { if sz < messageCache[i].maxbody { m = messageCache[i].pool.Get().(*Message) break } } if m == nil { m = newMsg(sz) } m.refcnt = 1 m.Body = m.bbuf m.Header = m.hbuf return m }
[ "func", "NewMessage", "(", "sz", "int", ")", "*", "Message", "{", "var", "m", "*", "Message", "\n", "for", "i", ":=", "range", "messageCache", "{", "if", "sz", "<", "messageCache", "[", "i", "]", ".", "maxbody", "{", "m", "=", "messageCache", "[", "i", "]", ".", "pool", ".", "Get", "(", ")", ".", "(", "*", "Message", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "m", "==", "nil", "{", "m", "=", "newMsg", "(", "sz", ")", "\n", "}", "\n\n", "m", ".", "refcnt", "=", "1", "\n", "m", ".", "Body", "=", "m", ".", "bbuf", "\n", "m", ".", "Header", "=", "m", ".", "hbuf", "\n", "return", "m", "\n", "}" ]
// NewMessage is the supported way to obtain a new Message. This makes // use of a "cache" which greatly reduces the load on the garbage collector.
[ "NewMessage", "is", "the", "supported", "way", "to", "obtain", "a", "new", "Message", ".", "This", "makes", "use", "of", "a", "cache", "which", "greatly", "reduces", "the", "load", "on", "the", "garbage", "collector", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/message.go#L156-L172
train
nanomsg/mangos-v1
examples/websocket/reqclient.go
reqClient
func reqClient(port int) { sock, e := req.NewSocket() if e != nil { die("cannot make req socket: %v", e) } sock.AddTransport(ws.NewTransport()) url := fmt.Sprintf("ws://127.0.0.1:%d/req", port) if e = sock.Dial(url); e != nil { die("cannot dial req url: %v", e) } // Time for TCP connection set up time.Sleep(time.Millisecond * 10) if e = sock.Send([]byte("Hello")); e != nil { die("Cannot send req: %v", e) } if m, e := sock.Recv(); e != nil { die("Cannot recv reply: %v", e) } else { fmt.Printf("%s\n", string(m)) } }
go
func reqClient(port int) { sock, e := req.NewSocket() if e != nil { die("cannot make req socket: %v", e) } sock.AddTransport(ws.NewTransport()) url := fmt.Sprintf("ws://127.0.0.1:%d/req", port) if e = sock.Dial(url); e != nil { die("cannot dial req url: %v", e) } // Time for TCP connection set up time.Sleep(time.Millisecond * 10) if e = sock.Send([]byte("Hello")); e != nil { die("Cannot send req: %v", e) } if m, e := sock.Recv(); e != nil { die("Cannot recv reply: %v", e) } else { fmt.Printf("%s\n", string(m)) } }
[ "func", "reqClient", "(", "port", "int", ")", "{", "sock", ",", "e", ":=", "req", ".", "NewSocket", "(", ")", "\n", "if", "e", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "e", ")", "\n", "}", "\n", "sock", ".", "AddTransport", "(", "ws", ".", "NewTransport", "(", ")", ")", "\n", "url", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "port", ")", "\n", "if", "e", "=", "sock", ".", "Dial", "(", "url", ")", ";", "e", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "e", ")", "\n", "}", "\n", "// Time for TCP connection set up", "time", ".", "Sleep", "(", "time", ".", "Millisecond", "*", "10", ")", "\n", "if", "e", "=", "sock", ".", "Send", "(", "[", "]", "byte", "(", "\"", "\"", ")", ")", ";", "e", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "e", ")", "\n", "}", "\n", "if", "m", ",", "e", ":=", "sock", ".", "Recv", "(", ")", ";", "e", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "e", ")", "\n", "}", "else", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "string", "(", "m", ")", ")", "\n", "}", "\n", "}" ]
// reqClient implements the client for REQ.
[ "reqClient", "implements", "the", "client", "for", "REQ", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/examples/websocket/reqclient.go#L26-L46
train
nanomsg/mangos-v1
waiter.go
WaitAbsTimeout
func (cv *CondTimed) WaitAbsTimeout(when time.Time) bool { now := time.Now() if when.After(now) { return cv.WaitRelTimeout(when.Sub(now)) } return cv.WaitRelTimeout(time.Duration(0)) }
go
func (cv *CondTimed) WaitAbsTimeout(when time.Time) bool { now := time.Now() if when.After(now) { return cv.WaitRelTimeout(when.Sub(now)) } return cv.WaitRelTimeout(time.Duration(0)) }
[ "func", "(", "cv", "*", "CondTimed", ")", "WaitAbsTimeout", "(", "when", "time", ".", "Time", ")", "bool", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "if", "when", ".", "After", "(", "now", ")", "{", "return", "cv", ".", "WaitRelTimeout", "(", "when", ".", "Sub", "(", "now", ")", ")", "\n", "}", "\n", "return", "cv", ".", "WaitRelTimeout", "(", "time", ".", "Duration", "(", "0", ")", ")", "\n", "}" ]
// WaitAbsTimeout is like WaitRelTimeout, but expires on an absolute time // instead of a relative one.
[ "WaitAbsTimeout", "is", "like", "WaitRelTimeout", "but", "expires", "on", "an", "absolute", "time", "instead", "of", "a", "relative", "one", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/waiter.go#L43-L49
train
nanomsg/mangos-v1
waiter.go
Wait
func (w *Waiter) Wait() { w.Lock() for w.cnt != 0 { w.cv.Wait() } w.Unlock() }
go
func (w *Waiter) Wait() { w.Lock() for w.cnt != 0 { w.cv.Wait() } w.Unlock() }
[ "func", "(", "w", "*", "Waiter", ")", "Wait", "(", ")", "{", "w", ".", "Lock", "(", ")", "\n", "for", "w", ".", "cnt", "!=", "0", "{", "w", ".", "cv", ".", "Wait", "(", ")", "\n", "}", "\n", "w", ".", "Unlock", "(", ")", "\n", "}" ]
// Wait waits without a timeout. It only completes when the count drops // to zero.
[ "Wait", "waits", "without", "a", "timeout", ".", "It", "only", "completes", "when", "the", "count", "drops", "to", "zero", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/waiter.go#L91-L97
train
nanomsg/mangos-v1
waiter.go
WaitRelTimeout
func (w *Waiter) WaitRelTimeout(d time.Duration) bool { w.Lock() for w.cnt != 0 { if !w.cv.WaitRelTimeout(d) { break } } done := w.cnt == 0 w.Unlock() return done }
go
func (w *Waiter) WaitRelTimeout(d time.Duration) bool { w.Lock() for w.cnt != 0 { if !w.cv.WaitRelTimeout(d) { break } } done := w.cnt == 0 w.Unlock() return done }
[ "func", "(", "w", "*", "Waiter", ")", "WaitRelTimeout", "(", "d", "time", ".", "Duration", ")", "bool", "{", "w", ".", "Lock", "(", ")", "\n", "for", "w", ".", "cnt", "!=", "0", "{", "if", "!", "w", ".", "cv", ".", "WaitRelTimeout", "(", "d", ")", "{", "break", "\n", "}", "\n", "}", "\n", "done", ":=", "w", ".", "cnt", "==", "0", "\n", "w", ".", "Unlock", "(", ")", "\n", "return", "done", "\n", "}" ]
// WaitRelTimeout waits until either the count drops to zero, or the timeout // expires. It returns true if the count is zero, false otherwise.
[ "WaitRelTimeout", "waits", "until", "either", "the", "count", "drops", "to", "zero", "or", "the", "timeout", "expires", ".", "It", "returns", "true", "if", "the", "count", "is", "zero", "false", "otherwise", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/waiter.go#L101-L111
train
nanomsg/mangos-v1
waiter.go
WaitAbsTimeout
func (w *Waiter) WaitAbsTimeout(t time.Time) bool { w.Lock() for w.cnt != 0 { if !w.cv.WaitAbsTimeout(t) { break } } done := w.cnt == 0 w.Unlock() return done }
go
func (w *Waiter) WaitAbsTimeout(t time.Time) bool { w.Lock() for w.cnt != 0 { if !w.cv.WaitAbsTimeout(t) { break } } done := w.cnt == 0 w.Unlock() return done }
[ "func", "(", "w", "*", "Waiter", ")", "WaitAbsTimeout", "(", "t", "time", ".", "Time", ")", "bool", "{", "w", ".", "Lock", "(", ")", "\n", "for", "w", ".", "cnt", "!=", "0", "{", "if", "!", "w", ".", "cv", ".", "WaitAbsTimeout", "(", "t", ")", "{", "break", "\n", "}", "\n", "}", "\n", "done", ":=", "w", ".", "cnt", "==", "0", "\n", "w", ".", "Unlock", "(", ")", "\n", "return", "done", "\n", "}" ]
// WaitAbsTimeout is like WaitRelTimeout, but waits until an absolute time.
[ "WaitAbsTimeout", "is", "like", "WaitRelTimeout", "but", "waits", "until", "an", "absolute", "time", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/waiter.go#L114-L124
train
nanomsg/mangos-v1
transport.go
ResolveTCPAddr
func ResolveTCPAddr(addr string) (*net.TCPAddr, error) { if strings.HasPrefix(addr, "*") { addr = addr[1:] } return net.ResolveTCPAddr("tcp", addr) }
go
func ResolveTCPAddr(addr string) (*net.TCPAddr, error) { if strings.HasPrefix(addr, "*") { addr = addr[1:] } return net.ResolveTCPAddr("tcp", addr) }
[ "func", "ResolveTCPAddr", "(", "addr", "string", ")", "(", "*", "net", ".", "TCPAddr", ",", "error", ")", "{", "if", "strings", ".", "HasPrefix", "(", "addr", ",", "\"", "\"", ")", "{", "addr", "=", "addr", "[", "1", ":", "]", "\n", "}", "\n", "return", "net", ".", "ResolveTCPAddr", "(", "\"", "\"", ",", "addr", ")", "\n", "}" ]
// ResolveTCPAddr is like net.ResolveTCPAddr, but it handles the // wildcard used in nanomsg URLs, replacing it with an empty // string to indicate that all local interfaces be used.
[ "ResolveTCPAddr", "is", "like", "net", ".", "ResolveTCPAddr", "but", "it", "handles", "the", "wildcard", "used", "in", "nanomsg", "URLs", "replacing", "it", "with", "an", "empty", "string", "to", "indicate", "that", "all", "local", "interfaces", "be", "used", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport.go#L157-L162
train
nanomsg/mangos-v1
conn.go
Close
func (p *conn) Close() error { p.Lock() defer p.Unlock() if p.IsOpen() { p.open = false return p.c.Close() } return nil }
go
func (p *conn) Close() error { p.Lock() defer p.Unlock() if p.IsOpen() { p.open = false return p.c.Close() } return nil }
[ "func", "(", "p", "*", "conn", ")", "Close", "(", ")", "error", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n", "if", "p", ".", "IsOpen", "(", ")", "{", "p", ".", "open", "=", "false", "\n", "return", "p", ".", "c", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close implements the Pipe Close method.
[ "Close", "implements", "the", "Pipe", "Close", "method", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/conn.go#L107-L115
train
nanomsg/mangos-v1
conn.go
NewConnPipe
func NewConnPipe(c net.Conn, sock Socket, props ...interface{}) (Pipe, error) { p := &conn{c: c, proto: sock.GetProtocol(), sock: sock} if err := p.handshake(props); err != nil { return nil, err } return p, nil }
go
func NewConnPipe(c net.Conn, sock Socket, props ...interface{}) (Pipe, error) { p := &conn{c: c, proto: sock.GetProtocol(), sock: sock} if err := p.handshake(props); err != nil { return nil, err } return p, nil }
[ "func", "NewConnPipe", "(", "c", "net", ".", "Conn", ",", "sock", "Socket", ",", "props", "...", "interface", "{", "}", ")", "(", "Pipe", ",", "error", ")", "{", "p", ":=", "&", "conn", "{", "c", ":", "c", ",", "proto", ":", "sock", ".", "GetProtocol", "(", ")", ",", "sock", ":", "sock", "}", "\n\n", "if", "err", ":=", "p", ".", "handshake", "(", "props", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "p", ",", "nil", "\n", "}" ]
// NewConnPipe allocates a new Pipe using the supplied net.Conn, and // initializes it. It performs the handshake required at the SP layer, // only returning the Pipe once the SP layer negotiation is complete. // // Stream oriented transports can utilize this to implement a Transport. // The implementation will also need to implement PipeDialer, PipeAccepter, // and the Transport enclosing structure. Using this layered interface, // the implementation needn't bother concerning itself with passing actual // SP messages once the lower layer connection is established.
[ "NewConnPipe", "allocates", "a", "new", "Pipe", "using", "the", "supplied", "net", ".", "Conn", "and", "initializes", "it", ".", "It", "performs", "the", "handshake", "required", "at", "the", "SP", "layer", "only", "returning", "the", "Pipe", "once", "the", "SP", "layer", "negotiation", "is", "complete", ".", "Stream", "oriented", "transports", "can", "utilize", "this", "to", "implement", "a", "Transport", ".", "The", "implementation", "will", "also", "need", "to", "implement", "PipeDialer", "PipeAccepter", "and", "the", "Transport", "enclosing", "structure", ".", "Using", "this", "layered", "interface", "the", "implementation", "needn", "t", "bother", "concerning", "itself", "with", "passing", "actual", "SP", "messages", "once", "the", "lower", "layer", "connection", "is", "established", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/conn.go#L138-L146
train
nanomsg/mangos-v1
conn.go
handshake
func (p *conn) handshake(props []interface{}) error { var err error p.props = make(map[string]interface{}) p.props[PropLocalAddr] = p.c.LocalAddr() p.props[PropRemoteAddr] = p.c.RemoteAddr() for len(props) >= 2 { switch name := props[0].(type) { case string: p.props[name] = props[1] default: return ErrBadProperty } props = props[2:] } if v, e := p.sock.GetOption(OptionMaxRecvSize); e == nil { // socket guarantees this is an integer p.maxrx = int64(v.(int)) } h := connHeader{S: 'S', P: 'P', Proto: p.proto.Number()} if err = binary.Write(p.c, binary.BigEndian, &h); err != nil { return err } if err = binary.Read(p.c, binary.BigEndian, &h); err != nil { p.c.Close() return err } if h.Zero != 0 || h.S != 'S' || h.P != 'P' || h.Rsvd != 0 { p.c.Close() return ErrBadHeader } // The only version number we support at present is "0", at offset 3. if h.Version != 0 { p.c.Close() return ErrBadVersion } // The protocol number lives as 16-bits (big-endian) at offset 4. if h.Proto != p.proto.PeerNumber() { p.c.Close() return ErrBadProto } p.open = true return nil }
go
func (p *conn) handshake(props []interface{}) error { var err error p.props = make(map[string]interface{}) p.props[PropLocalAddr] = p.c.LocalAddr() p.props[PropRemoteAddr] = p.c.RemoteAddr() for len(props) >= 2 { switch name := props[0].(type) { case string: p.props[name] = props[1] default: return ErrBadProperty } props = props[2:] } if v, e := p.sock.GetOption(OptionMaxRecvSize); e == nil { // socket guarantees this is an integer p.maxrx = int64(v.(int)) } h := connHeader{S: 'S', P: 'P', Proto: p.proto.Number()} if err = binary.Write(p.c, binary.BigEndian, &h); err != nil { return err } if err = binary.Read(p.c, binary.BigEndian, &h); err != nil { p.c.Close() return err } if h.Zero != 0 || h.S != 'S' || h.P != 'P' || h.Rsvd != 0 { p.c.Close() return ErrBadHeader } // The only version number we support at present is "0", at offset 3. if h.Version != 0 { p.c.Close() return ErrBadVersion } // The protocol number lives as 16-bits (big-endian) at offset 4. if h.Proto != p.proto.PeerNumber() { p.c.Close() return ErrBadProto } p.open = true return nil }
[ "func", "(", "p", "*", "conn", ")", "handshake", "(", "props", "[", "]", "interface", "{", "}", ")", "error", "{", "var", "err", "error", "\n\n", "p", ".", "props", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "p", ".", "props", "[", "PropLocalAddr", "]", "=", "p", ".", "c", ".", "LocalAddr", "(", ")", "\n", "p", ".", "props", "[", "PropRemoteAddr", "]", "=", "p", ".", "c", ".", "RemoteAddr", "(", ")", "\n\n", "for", "len", "(", "props", ")", ">=", "2", "{", "switch", "name", ":=", "props", "[", "0", "]", ".", "(", "type", ")", "{", "case", "string", ":", "p", ".", "props", "[", "name", "]", "=", "props", "[", "1", "]", "\n", "default", ":", "return", "ErrBadProperty", "\n", "}", "\n", "props", "=", "props", "[", "2", ":", "]", "\n", "}", "\n\n", "if", "v", ",", "e", ":=", "p", ".", "sock", ".", "GetOption", "(", "OptionMaxRecvSize", ")", ";", "e", "==", "nil", "{", "// socket guarantees this is an integer", "p", ".", "maxrx", "=", "int64", "(", "v", ".", "(", "int", ")", ")", "\n", "}", "\n\n", "h", ":=", "connHeader", "{", "S", ":", "'S'", ",", "P", ":", "'P'", ",", "Proto", ":", "p", ".", "proto", ".", "Number", "(", ")", "}", "\n", "if", "err", "=", "binary", ".", "Write", "(", "p", ".", "c", ",", "binary", ".", "BigEndian", ",", "&", "h", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "binary", ".", "Read", "(", "p", ".", "c", ",", "binary", ".", "BigEndian", ",", "&", "h", ")", ";", "err", "!=", "nil", "{", "p", ".", "c", ".", "Close", "(", ")", "\n", "return", "err", "\n", "}", "\n", "if", "h", ".", "Zero", "!=", "0", "||", "h", ".", "S", "!=", "'S'", "||", "h", ".", "P", "!=", "'P'", "||", "h", ".", "Rsvd", "!=", "0", "{", "p", ".", "c", ".", "Close", "(", ")", "\n", "return", "ErrBadHeader", "\n", "}", "\n", "// The only version number we support at present is \"0\", at offset 3.", "if", "h", ".", "Version", "!=", "0", "{", "p", ".", "c", ".", "Close", "(", ")", "\n", "return", "ErrBadVersion", "\n", "}", "\n\n", "// The protocol number lives as 16-bits (big-endian) at offset 4.", "if", "h", ".", "Proto", "!=", "p", ".", "proto", ".", "PeerNumber", "(", ")", "{", "p", ".", "c", ".", "Close", "(", ")", "\n", "return", "ErrBadProto", "\n", "}", "\n", "p", ".", "open", "=", "true", "\n", "return", "nil", "\n", "}" ]
// handshake establishes an SP connection between peers. Both sides must // send the header, then both sides must wait for the peer's header. // As a side effect, the peer's protocol number is stored in the conn. // Also, various properties are initialized.
[ "handshake", "establishes", "an", "SP", "connection", "between", "peers", ".", "Both", "sides", "must", "send", "the", "header", "then", "both", "sides", "must", "wait", "for", "the", "peer", "s", "header", ".", "As", "a", "side", "effect", "the", "peer", "s", "protocol", "number", "is", "stored", "in", "the", "conn", ".", "Also", "various", "properties", "are", "initialized", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/conn.go#L162-L209
train
nanomsg/mangos-v1
util.go
mkTimer
func mkTimer(deadline time.Duration) <-chan time.Time { if deadline == 0 { return nil } return time.After(deadline) }
go
func mkTimer(deadline time.Duration) <-chan time.Time { if deadline == 0 { return nil } return time.After(deadline) }
[ "func", "mkTimer", "(", "deadline", "time", ".", "Duration", ")", "<-", "chan", "time", ".", "Time", "{", "if", "deadline", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "return", "time", ".", "After", "(", "deadline", ")", "\n", "}" ]
// mkTimer creates a timer based upon a duration. If however // a zero valued duration is passed, then a nil channel is passed // i.e. never selectable. This allows the output to be readily used // with deadlines in network connections, etc.
[ "mkTimer", "creates", "a", "timer", "based", "upon", "a", "duration", ".", "If", "however", "a", "zero", "valued", "duration", "is", "passed", "then", "a", "nil", "channel", "is", "passed", "i", ".", "e", ".", "never", "selectable", ".", "This", "allows", "the", "output", "to", "be", "readily", "used", "with", "deadlines", "in", "network", "connections", "etc", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/util.go#L28-L35
train
nanomsg/mangos-v1
perf/throughput.go
ThroughputClient
func ThroughputClient(addr string, msgSize int, count int) { s, err := pair.NewSocket() if err != nil { log.Fatalf("Failed to make new pair socket: %v", err) } defer s.Close() all.AddTransports(s) d, err := s.NewDialer(addr, nil) if err != nil { log.Fatalf("Failed to make new dialer: %v", err) } // Disable TCP no delay, please! d.SetOption(mangos.OptionNoDelay, false) // Make sure we linger a bit on close... err = s.SetOption(mangos.OptionLinger, time.Second) if err != nil { log.Fatalf("Failed set Linger: %v", err) } err = d.Dial() if err != nil { log.Fatalf("Failed to dial: %v", err) } // 100 milliseconds to give TCP a chance to establish time.Sleep(time.Millisecond * 100) body := make([]byte, msgSize) for i := 0; i < msgSize; i++ { body[i] = 111 } // send the start message s.Send([]byte{}) for i := 0; i < count; i++ { if err = s.Send(body); err != nil { log.Fatalf("Failed SendMsg: %v", err) } } }
go
func ThroughputClient(addr string, msgSize int, count int) { s, err := pair.NewSocket() if err != nil { log.Fatalf("Failed to make new pair socket: %v", err) } defer s.Close() all.AddTransports(s) d, err := s.NewDialer(addr, nil) if err != nil { log.Fatalf("Failed to make new dialer: %v", err) } // Disable TCP no delay, please! d.SetOption(mangos.OptionNoDelay, false) // Make sure we linger a bit on close... err = s.SetOption(mangos.OptionLinger, time.Second) if err != nil { log.Fatalf("Failed set Linger: %v", err) } err = d.Dial() if err != nil { log.Fatalf("Failed to dial: %v", err) } // 100 milliseconds to give TCP a chance to establish time.Sleep(time.Millisecond * 100) body := make([]byte, msgSize) for i := 0; i < msgSize; i++ { body[i] = 111 } // send the start message s.Send([]byte{}) for i := 0; i < count; i++ { if err = s.Send(body); err != nil { log.Fatalf("Failed SendMsg: %v", err) } } }
[ "func", "ThroughputClient", "(", "addr", "string", ",", "msgSize", "int", ",", "count", "int", ")", "{", "s", ",", "err", ":=", "pair", ".", "NewSocket", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "s", ".", "Close", "(", ")", "\n\n", "all", ".", "AddTransports", "(", "s", ")", "\n", "d", ",", "err", ":=", "s", ".", "NewDialer", "(", "addr", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Disable TCP no delay, please!", "d", ".", "SetOption", "(", "mangos", ".", "OptionNoDelay", ",", "false", ")", "\n\n", "// Make sure we linger a bit on close...", "err", "=", "s", ".", "SetOption", "(", "mangos", ".", "OptionLinger", ",", "time", ".", "Second", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "err", "=", "d", ".", "Dial", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// 100 milliseconds to give TCP a chance to establish", "time", ".", "Sleep", "(", "time", ".", "Millisecond", "*", "100", ")", "\n\n", "body", ":=", "make", "(", "[", "]", "byte", ",", "msgSize", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "msgSize", ";", "i", "++", "{", "body", "[", "i", "]", "=", "111", "\n", "}", "\n\n", "// send the start message", "s", ".", "Send", "(", "[", "]", "byte", "{", "}", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "count", ";", "i", "++", "{", "if", "err", "=", "s", ".", "Send", "(", "body", ")", ";", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// ThroughputClient is the client side of the latency test. It simply sends // the requested number of packets of given size to the server. It corresponds // to remote_thr.
[ "ThroughputClient", "is", "the", "client", "side", "of", "the", "latency", "test", ".", "It", "simply", "sends", "the", "requested", "number", "of", "packets", "of", "given", "size", "to", "the", "server", ".", "It", "corresponds", "to", "remote_thr", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/perf/throughput.go#L94-L137
train
nanomsg/mangos-v1
protocol/respondent/respondent.go
sender
func (peer *respPeer) sender() { for { m := <-peer.q if m == nil { break } if peer.ep.SendMsg(m) != nil { m.Free() break } } }
go
func (peer *respPeer) sender() { for { m := <-peer.q if m == nil { break } if peer.ep.SendMsg(m) != nil { m.Free() break } } }
[ "func", "(", "peer", "*", "respPeer", ")", "sender", "(", ")", "{", "for", "{", "m", ":=", "<-", "peer", ".", "q", "\n", "if", "m", "==", "nil", "{", "break", "\n", "}", "\n", "if", "peer", ".", "ep", ".", "SendMsg", "(", "m", ")", "!=", "nil", "{", "m", ".", "Free", "(", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}" ]
// When sending, we should have the survey ID in the header.
[ "When", "sending", "we", "should", "have", "the", "survey", "ID", "in", "the", "header", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol/respondent/respondent.go#L120-L131
train
nanomsg/mangos-v1
transport/ipc/ipc_windows.go
Dial
func (d *dialer) Dial() (mangos.Pipe, error) { conn, err := winio.DialPipe("\\\\.\\pipe\\"+d.path, nil) if err != nil { return nil, err } addr := pipeAddr(d.path) return mangos.NewConnPipeIPC(conn, d.sock, mangos.PropLocalAddr, addr, mangos.PropRemoteAddr, addr) }
go
func (d *dialer) Dial() (mangos.Pipe, error) { conn, err := winio.DialPipe("\\\\.\\pipe\\"+d.path, nil) if err != nil { return nil, err } addr := pipeAddr(d.path) return mangos.NewConnPipeIPC(conn, d.sock, mangos.PropLocalAddr, addr, mangos.PropRemoteAddr, addr) }
[ "func", "(", "d", "*", "dialer", ")", "Dial", "(", ")", "(", "mangos", ".", "Pipe", ",", "error", ")", "{", "conn", ",", "err", ":=", "winio", ".", "DialPipe", "(", "\"", "\\\\", "\\\\", "\\\\", "\\\\", "\"", "+", "d", ".", "path", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "addr", ":=", "pipeAddr", "(", "d", ".", "path", ")", "\n", "return", "mangos", ".", "NewConnPipeIPC", "(", "conn", ",", "d", ".", "sock", ",", "mangos", ".", "PropLocalAddr", ",", "addr", ",", "mangos", ".", "PropRemoteAddr", ",", "addr", ")", "\n", "}" ]
// Dial implements the PipeDialer Dial method.
[ "Dial", "implements", "the", "PipeDialer", "Dial", "method", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/ipc/ipc_windows.go#L65-L74
train
nanomsg/mangos-v1
transport/ipc/ipc_windows.go
Close
func (l *listener) Close() error { if l.listener != nil { l.listener.Close() } return nil }
go
func (l *listener) Close() error { if l.listener != nil { l.listener.Close() } return nil }
[ "func", "(", "l", "*", "listener", ")", "Close", "(", ")", "error", "{", "if", "l", ".", "listener", "!=", "nil", "{", "l", ".", "listener", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close implements the PipeListener Close method.
[ "Close", "implements", "the", "PipeListener", "Close", "method", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/ipc/ipc_windows.go#L141-L146
train
nanomsg/mangos-v1
transport/ipc/ipc_windows.go
SetOption
func (l *listener) SetOption(name string, val interface{}) error { switch name { case OptionInputBufferSize: switch v := val.(type) { case int32: l.config.InputBufferSize = v return nil default: return mangos.ErrBadValue } case OptionOutputBufferSize: switch v := val.(type) { case int32: l.config.OutputBufferSize = v return nil default: return mangos.ErrBadValue } case OptionSecurityDescriptor: switch v := val.(type) { case string: l.config.SecurityDescriptor = v return nil default: return mangos.ErrBadValue } default: return mangos.ErrBadOption } }
go
func (l *listener) SetOption(name string, val interface{}) error { switch name { case OptionInputBufferSize: switch v := val.(type) { case int32: l.config.InputBufferSize = v return nil default: return mangos.ErrBadValue } case OptionOutputBufferSize: switch v := val.(type) { case int32: l.config.OutputBufferSize = v return nil default: return mangos.ErrBadValue } case OptionSecurityDescriptor: switch v := val.(type) { case string: l.config.SecurityDescriptor = v return nil default: return mangos.ErrBadValue } default: return mangos.ErrBadOption } }
[ "func", "(", "l", "*", "listener", ")", "SetOption", "(", "name", "string", ",", "val", "interface", "{", "}", ")", "error", "{", "switch", "name", "{", "case", "OptionInputBufferSize", ":", "switch", "v", ":=", "val", ".", "(", "type", ")", "{", "case", "int32", ":", "l", ".", "config", ".", "InputBufferSize", "=", "v", "\n", "return", "nil", "\n", "default", ":", "return", "mangos", ".", "ErrBadValue", "\n", "}", "\n", "case", "OptionOutputBufferSize", ":", "switch", "v", ":=", "val", ".", "(", "type", ")", "{", "case", "int32", ":", "l", ".", "config", ".", "OutputBufferSize", "=", "v", "\n", "return", "nil", "\n", "default", ":", "return", "mangos", ".", "ErrBadValue", "\n", "}", "\n", "case", "OptionSecurityDescriptor", ":", "switch", "v", ":=", "val", ".", "(", "type", ")", "{", "case", "string", ":", "l", ".", "config", ".", "SecurityDescriptor", "=", "v", "\n", "return", "nil", "\n", "default", ":", "return", "mangos", ".", "ErrBadValue", "\n", "}", "\n", "default", ":", "return", "mangos", ".", "ErrBadOption", "\n", "}", "\n", "}" ]
// SetOption implements a stub PipeListener SetOption method.
[ "SetOption", "implements", "a", "stub", "PipeListener", "SetOption", "method", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/ipc/ipc_windows.go#L149-L178
train
nanomsg/mangos-v1
transport/ipc/ipc_windows.go
GetOption
func (l *listener) GetOption(name string) (interface{}, error) { switch name { case OptionInputBufferSize: return l.config.InputBufferSize, nil case OptionOutputBufferSize: return l.config.OutputBufferSize, nil case OptionSecurityDescriptor: return l.config.SecurityDescriptor, nil } return nil, mangos.ErrBadOption }
go
func (l *listener) GetOption(name string) (interface{}, error) { switch name { case OptionInputBufferSize: return l.config.InputBufferSize, nil case OptionOutputBufferSize: return l.config.OutputBufferSize, nil case OptionSecurityDescriptor: return l.config.SecurityDescriptor, nil } return nil, mangos.ErrBadOption }
[ "func", "(", "l", "*", "listener", ")", "GetOption", "(", "name", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "switch", "name", "{", "case", "OptionInputBufferSize", ":", "return", "l", ".", "config", ".", "InputBufferSize", ",", "nil", "\n", "case", "OptionOutputBufferSize", ":", "return", "l", ".", "config", ".", "OutputBufferSize", ",", "nil", "\n", "case", "OptionSecurityDescriptor", ":", "return", "l", ".", "config", ".", "SecurityDescriptor", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "mangos", ".", "ErrBadOption", "\n", "}" ]
// GetOption implements a stub PipeListener GetOption method.
[ "GetOption", "implements", "a", "stub", "PipeListener", "GetOption", "method", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/ipc/ipc_windows.go#L181-L191
train
nanomsg/mangos-v1
device.go
forwarder
func forwarder(fromSock Socket, toSock Socket) { for { m, err := fromSock.RecvMsg() if err != nil { // Probably closed socket, nothing else we can do. return } err = toSock.SendMsg(m) if err != nil { return } } }
go
func forwarder(fromSock Socket, toSock Socket) { for { m, err := fromSock.RecvMsg() if err != nil { // Probably closed socket, nothing else we can do. return } err = toSock.SendMsg(m) if err != nil { return } } }
[ "func", "forwarder", "(", "fromSock", "Socket", ",", "toSock", "Socket", ")", "{", "for", "{", "m", ",", "err", ":=", "fromSock", ".", "RecvMsg", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// Probably closed socket, nothing else we can do.", "return", "\n", "}", "\n\n", "err", "=", "toSock", ".", "SendMsg", "(", "m", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Forwarder takes messages from one socket, and sends them to the other. // The sockets must be of compatible types, and must be in Raw mode.
[ "Forwarder", "takes", "messages", "from", "one", "socket", "and", "sends", "them", "to", "the", "other", ".", "The", "sockets", "must", "be", "of", "compatible", "types", "and", "must", "be", "in", "Raw", "mode", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/device.go#L64-L77
train
trivago/gollum
producer/scribe.go
Produce
func (prod *Scribe) Produce(workers *sync.WaitGroup) { prod.AddMainWorker(workers) prod.BatchMessageLoop(workers, prod.sendBatch) }
go
func (prod *Scribe) Produce(workers *sync.WaitGroup) { prod.AddMainWorker(workers) prod.BatchMessageLoop(workers, prod.sendBatch) }
[ "func", "(", "prod", "*", "Scribe", ")", "Produce", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "prod", ".", "AddMainWorker", "(", "workers", ")", "\n", "prod", ".", "BatchMessageLoop", "(", "workers", ",", "prod", ".", "sendBatch", ")", "\n", "}" ]
// Produce writes to a buffer that is sent to scribe.
[ "Produce", "writes", "to", "a", "buffer", "that", "is", "sent", "to", "scribe", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/scribe.go#L279-L282
train
trivago/gollum
core/components/awsMultiClient.go
NewSessionWithOptions
func (client *AwsMultiClient) NewSessionWithOptions() (*session.Session, error) { sess, err := session.NewSessionWithOptions(session.Options{ Config: *client.config, SharedConfigState: session.SharedConfigEnable, }) if err != nil { return nil, err } if client.Credentials.assumeRole != "" { credentials := stscreds.NewCredentials(sess, client.Credentials.assumeRole) client.config.WithCredentials(credentials) } return sess, err }
go
func (client *AwsMultiClient) NewSessionWithOptions() (*session.Session, error) { sess, err := session.NewSessionWithOptions(session.Options{ Config: *client.config, SharedConfigState: session.SharedConfigEnable, }) if err != nil { return nil, err } if client.Credentials.assumeRole != "" { credentials := stscreds.NewCredentials(sess, client.Credentials.assumeRole) client.config.WithCredentials(credentials) } return sess, err }
[ "func", "(", "client", "*", "AwsMultiClient", ")", "NewSessionWithOptions", "(", ")", "(", "*", "session", ".", "Session", ",", "error", ")", "{", "sess", ",", "err", ":=", "session", ".", "NewSessionWithOptions", "(", "session", ".", "Options", "{", "Config", ":", "*", "client", ".", "config", ",", "SharedConfigState", ":", "session", ".", "SharedConfigEnable", ",", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "client", ".", "Credentials", ".", "assumeRole", "!=", "\"", "\"", "{", "credentials", ":=", "stscreds", ".", "NewCredentials", "(", "sess", ",", "client", ".", "Credentials", ".", "assumeRole", ")", "\n", "client", ".", "config", ".", "WithCredentials", "(", "credentials", ")", "\n", "}", "\n\n", "return", "sess", ",", "err", "\n", "}" ]
// NewSessionWithOptions returns a instantiated asw session
[ "NewSessionWithOptions", "returns", "a", "instantiated", "asw", "session" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/awsMultiClient.go#L79-L95
train
trivago/gollum
core/components/awsMultiClient.go
CreateAwsCredentials
func (cred *AwsCredentials) CreateAwsCredentials() (*credentials.Credentials, error) { switch cred.credentialType { case credentialTypeEnv: return credentials.NewEnvCredentials(), nil case credentialTypeStatic: return credentials.NewStaticCredentials(cred.staticID, cred.staticSecret, cred.staticToken), nil case credentialTypeShared: return credentials.NewSharedCredentials(cred.sharedFile, cred.sharedProfile), nil case credentialTypeNone: return credentials.AnonymousCredentials, nil default: return credentials.AnonymousCredentials, fmt.Errorf("unknown CredentialType: %s", cred.credentialType) } }
go
func (cred *AwsCredentials) CreateAwsCredentials() (*credentials.Credentials, error) { switch cred.credentialType { case credentialTypeEnv: return credentials.NewEnvCredentials(), nil case credentialTypeStatic: return credentials.NewStaticCredentials(cred.staticID, cred.staticSecret, cred.staticToken), nil case credentialTypeShared: return credentials.NewSharedCredentials(cred.sharedFile, cred.sharedProfile), nil case credentialTypeNone: return credentials.AnonymousCredentials, nil default: return credentials.AnonymousCredentials, fmt.Errorf("unknown CredentialType: %s", cred.credentialType) } }
[ "func", "(", "cred", "*", "AwsCredentials", ")", "CreateAwsCredentials", "(", ")", "(", "*", "credentials", ".", "Credentials", ",", "error", ")", "{", "switch", "cred", ".", "credentialType", "{", "case", "credentialTypeEnv", ":", "return", "credentials", ".", "NewEnvCredentials", "(", ")", ",", "nil", "\n\n", "case", "credentialTypeStatic", ":", "return", "credentials", ".", "NewStaticCredentials", "(", "cred", ".", "staticID", ",", "cred", ".", "staticSecret", ",", "cred", ".", "staticToken", ")", ",", "nil", "\n\n", "case", "credentialTypeShared", ":", "return", "credentials", ".", "NewSharedCredentials", "(", "cred", ".", "sharedFile", ",", "cred", ".", "sharedProfile", ")", ",", "nil", "\n\n", "case", "credentialTypeNone", ":", "return", "credentials", ".", "AnonymousCredentials", ",", "nil", "\n\n", "default", ":", "return", "credentials", ".", "AnonymousCredentials", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cred", ".", "credentialType", ")", "\n", "}", "\n", "}" ]
// CreateAwsCredentials returns aws credentials.Credentials for active settings
[ "CreateAwsCredentials", "returns", "aws", "credentials", ".", "Credentials", "for", "active", "settings" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/awsMultiClient.go#L136-L153
train
trivago/gollum
docs/generator/definition.go
add
func (list *DefinitionList) add(def *Definition) { list.slice = append(list.slice, def) }
go
func (list *DefinitionList) add(def *Definition) { list.slice = append(list.slice, def) }
[ "func", "(", "list", "*", "DefinitionList", ")", "add", "(", "def", "*", "Definition", ")", "{", "list", ".", "slice", "=", "append", "(", "list", ".", "slice", ",", "def", ")", "\n", "}" ]
// add appends the definition pointed to by `def` to this list
[ "add", "appends", "the", "definition", "pointed", "to", "by", "def", "to", "this", "list" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/definition.go#L123-L125
train
trivago/gollum
docs/generator/definition.go
getRST
func (list DefinitionList) getRST(paramFields bool, depth int) string { result := "" if len(list.desc) > 0 { result = fmt.Sprintf("%s\n", list.desc) } for _, def := range list.slice { // Heading if strings.Trim(def.name, " \t") != "" { result += indentLines("**"+def.name+"**", 2*depth) } else { // Nameless definition // FIXME: bullet lists or something result += "** (unnamed) **" } // Optional default value and unit if paramFields && (def.unit != "" || def.dfl != "") { // TODO: cleaner formatting result += " (" if def.dfl != "" { result += fmt.Sprintf("default: %s", def.dfl) } if def.dfl != "" && def.unit != "" { result += ", " } if def.unit != "" { result += fmt.Sprintf("unit: %s", def.unit) } result += ")" } result += "\n\n" // Body result += indentLines(docBulletsToRstBullets(def.desc), 2*(depth+1)) //result += def.desc result += "\n\n" // Children result += def.children.getRST(paramFields, depth+1) } //return indentLines(result, 2 * (depth + 1)) return result }
go
func (list DefinitionList) getRST(paramFields bool, depth int) string { result := "" if len(list.desc) > 0 { result = fmt.Sprintf("%s\n", list.desc) } for _, def := range list.slice { // Heading if strings.Trim(def.name, " \t") != "" { result += indentLines("**"+def.name+"**", 2*depth) } else { // Nameless definition // FIXME: bullet lists or something result += "** (unnamed) **" } // Optional default value and unit if paramFields && (def.unit != "" || def.dfl != "") { // TODO: cleaner formatting result += " (" if def.dfl != "" { result += fmt.Sprintf("default: %s", def.dfl) } if def.dfl != "" && def.unit != "" { result += ", " } if def.unit != "" { result += fmt.Sprintf("unit: %s", def.unit) } result += ")" } result += "\n\n" // Body result += indentLines(docBulletsToRstBullets(def.desc), 2*(depth+1)) //result += def.desc result += "\n\n" // Children result += def.children.getRST(paramFields, depth+1) } //return indentLines(result, 2 * (depth + 1)) return result }
[ "func", "(", "list", "DefinitionList", ")", "getRST", "(", "paramFields", "bool", ",", "depth", "int", ")", "string", "{", "result", ":=", "\"", "\"", "\n\n", "if", "len", "(", "list", ".", "desc", ")", ">", "0", "{", "result", "=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "list", ".", "desc", ")", "\n", "}", "\n\n", "for", "_", ",", "def", ":=", "range", "list", ".", "slice", "{", "// Heading", "if", "strings", ".", "Trim", "(", "def", ".", "name", ",", "\"", "\\t", "\"", ")", "!=", "\"", "\"", "{", "result", "+=", "indentLines", "(", "\"", "\"", "+", "def", ".", "name", "+", "\"", "\"", ",", "2", "*", "depth", ")", "\n\n", "}", "else", "{", "// Nameless definition", "// FIXME: bullet lists or something", "result", "+=", "\"", "\"", "\n", "}", "\n\n", "// Optional default value and unit", "if", "paramFields", "&&", "(", "def", ".", "unit", "!=", "\"", "\"", "||", "def", ".", "dfl", "!=", "\"", "\"", ")", "{", "// TODO: cleaner formatting", "result", "+=", "\"", "\"", "\n", "if", "def", ".", "dfl", "!=", "\"", "\"", "{", "result", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "def", ".", "dfl", ")", "\n", "}", "\n", "if", "def", ".", "dfl", "!=", "\"", "\"", "&&", "def", ".", "unit", "!=", "\"", "\"", "{", "result", "+=", "\"", "\"", "\n", "}", "\n", "if", "def", ".", "unit", "!=", "\"", "\"", "{", "result", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "def", ".", "unit", ")", "\n", "}", "\n", "result", "+=", "\"", "\"", "\n", "}", "\n", "result", "+=", "\"", "\\n", "\\n", "\"", "\n\n", "// Body", "result", "+=", "indentLines", "(", "docBulletsToRstBullets", "(", "def", ".", "desc", ")", ",", "2", "*", "(", "depth", "+", "1", ")", ")", "\n", "//result += def.desc", "result", "+=", "\"", "\\n", "\\n", "\"", "\n\n", "// Children", "result", "+=", "def", ".", "children", ".", "getRST", "(", "paramFields", ",", "depth", "+", "1", ")", "\n", "}", "\n\n", "//return indentLines(result, 2 * (depth + 1))", "return", "result", "\n", "}" ]
// getRST formats the DefinitionList as ReStructuredText
[ "getRST", "formats", "the", "DefinitionList", "as", "ReStructuredText" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/definition.go#L165-L211
train
trivago/gollum
docs/generator/definition.go
indentLines
func indentLines(source string, level int) string { return regexp.MustCompile("(?m:(^))").ReplaceAllString(source, strings.Repeat(" ", level)) }
go
func indentLines(source string, level int) string { return regexp.MustCompile("(?m:(^))").ReplaceAllString(source, strings.Repeat(" ", level)) }
[ "func", "indentLines", "(", "source", "string", ",", "level", "int", ")", "string", "{", "return", "regexp", ".", "MustCompile", "(", "\"", "\"", ")", ".", "ReplaceAllString", "(", "source", ",", "strings", ".", "Repeat", "(", "\"", "\"", ",", "level", ")", ")", "\n", "}" ]
// Inserts two spaces at the beginning of each line, making the string a blockquote in RST
[ "Inserts", "two", "spaces", "at", "the", "beginning", "of", "each", "line", "making", "the", "string", "a", "blockquote", "in", "RST" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/definition.go#L214-L216
train
trivago/gollum
core/filter.go
ApplyFilter
func (filters FilterArray) ApplyFilter(msg *Message) (FilterResult, error) { for _, filter := range filters { result, err := filter.ApplyFilter(msg) if err != nil { return result, err } if result != FilterResultMessageAccept { return result, nil } } return FilterResultMessageAccept, nil }
go
func (filters FilterArray) ApplyFilter(msg *Message) (FilterResult, error) { for _, filter := range filters { result, err := filter.ApplyFilter(msg) if err != nil { return result, err } if result != FilterResultMessageAccept { return result, nil } } return FilterResultMessageAccept, nil }
[ "func", "(", "filters", "FilterArray", ")", "ApplyFilter", "(", "msg", "*", "Message", ")", "(", "FilterResult", ",", "error", ")", "{", "for", "_", ",", "filter", ":=", "range", "filters", "{", "result", ",", "err", ":=", "filter", ".", "ApplyFilter", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n\n", "if", "result", "!=", "FilterResultMessageAccept", "{", "return", "result", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "FilterResultMessageAccept", ",", "nil", "\n", "}" ]
// ApplyFilter calls ApplyFilter on every filter // Return FilterResultMessageReject in case of an error or if one filter rejects
[ "ApplyFilter", "calls", "ApplyFilter", "on", "every", "filter", "Return", "FilterResultMessageReject", "in", "case", "of", "an", "error", "or", "if", "one", "filter", "rejects" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/filter.go#L28-L40
train
trivago/gollum
core/errors.go
NewModulateResultError
func NewModulateResultError(message string, values ...interface{}) ModulateResultError { return ModulateResultError{ message: fmt.Sprintf(message, values...), } }
go
func NewModulateResultError(message string, values ...interface{}) ModulateResultError { return ModulateResultError{ message: fmt.Sprintf(message, values...), } }
[ "func", "NewModulateResultError", "(", "message", "string", ",", "values", "...", "interface", "{", "}", ")", "ModulateResultError", "{", "return", "ModulateResultError", "{", "message", ":", "fmt", ".", "Sprintf", "(", "message", ",", "values", "...", ")", ",", "}", "\n", "}" ]
// NewModulateResultError creates a new ModulateResultError with the given // message.
[ "NewModulateResultError", "creates", "a", "new", "ModulateResultError", "with", "the", "given", "message", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/errors.go#L34-L38
train
trivago/gollum
producer/InfluxDB.go
sendBatch
func (prod *InfluxDB) sendBatch() core.AssemblyFunc { if prod.writer.isConnectionUp() { return prod.assembly.Write } else if prod.IsStopping() { return prod.assembly.Flush } return nil }
go
func (prod *InfluxDB) sendBatch() core.AssemblyFunc { if prod.writer.isConnectionUp() { return prod.assembly.Write } else if prod.IsStopping() { return prod.assembly.Flush } return nil }
[ "func", "(", "prod", "*", "InfluxDB", ")", "sendBatch", "(", ")", "core", ".", "AssemblyFunc", "{", "if", "prod", ".", "writer", ".", "isConnectionUp", "(", ")", "{", "return", "prod", ".", "assembly", ".", "Write", "\n", "}", "else", "if", "prod", ".", "IsStopping", "(", ")", "{", "return", "prod", ".", "assembly", ".", "Flush", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// sendBatch returns core.AssemblyFunc to flush batch
[ "sendBatch", "returns", "core", ".", "AssemblyFunc", "to", "flush", "batch" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/InfluxDB.go#L109-L117
train
trivago/gollum
producer/InfluxDB.go
Produce
func (prod *InfluxDB) Produce(workers *sync.WaitGroup) { prod.BatchMessageLoop(workers, prod.sendBatch) }
go
func (prod *InfluxDB) Produce(workers *sync.WaitGroup) { prod.BatchMessageLoop(workers, prod.sendBatch) }
[ "func", "(", "prod", "*", "InfluxDB", ")", "Produce", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "prod", ".", "BatchMessageLoop", "(", "workers", ",", "prod", ".", "sendBatch", ")", "\n", "}" ]
// Produce starts a bulk producer which will collect datapoints until either the buffer is full or a timeout has been reached. // The buffer limit does not describe the number of messages received from kafka but the size of the buffer content in KB.
[ "Produce", "starts", "a", "bulk", "producer", "which", "will", "collect", "datapoints", "until", "either", "the", "buffer", "is", "full", "or", "a", "timeout", "has", "been", "reached", ".", "The", "buffer", "limit", "does", "not", "describe", "the", "number", "of", "messages", "received", "from", "kafka", "but", "the", "size", "of", "the", "buffer", "content", "in", "KB", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/InfluxDB.go#L121-L123
train
trivago/gollum
docs/generator/gollumplugin.go
findGollumPlugins
func findGollumPlugins(pkgRoot *ast.Package) []GollumPlugin { // Generate a tree structure from the parse results returned by AST tree := NewTree(pkgRoot) // The tree looks like this: /** *ast.Package *ast.File *ast.Ident *ast.GenDecl *ast.ImportSpec *ast.BasicLit [....] *ast.GenDecl *ast.CommentGroup *ast.Comment *ast.TypeSpec *ast.Ident *ast.StructType *ast.FieldList *ast.Field *ast.Ident *ast.Ident [....[ **/ // Search pattern pattern := PatternNode{ Comparison: "*ast.GenDecl", Children: []PatternNode{ { Comparison: "*ast.CommentGroup", // Note: there are N pcs of "*ast.Comment" children // here but we don't need to match them }, { Comparison: "*ast.TypeSpec", Children: []PatternNode{ { Comparison: "*ast.Ident", Callback: func(astNode ast.Node) bool { // Checks that the name starts with a capital letter return ast.IsExported(astNode.(*ast.Ident).Name) }, }, { Comparison: "*ast.StructType", Children: []PatternNode{ { Comparison: "*ast.FieldList", // There are N pcs of "*ast.Field" children here }, }, }, }, }, }, } // Search the tree results := []GollumPlugin{} for _, genDecl := range tree.Search(pattern) { pst := GollumPlugin{ Pkg: pkgRoot.Name, // Indexes assumed based on the search pattern above Name: genDecl.Children[1].Children[0].AstNode.(*ast.Ident).Name, Comment: genDecl.Children[0].AstNode.(*ast.CommentGroup).Text(), Embeds: getGollumPluginEmbedList(pkgRoot.Name, genDecl.Children[1].Children[1].Children[0].AstNode.(*ast.FieldList), ), StructTagParams: getGollumPluginConfigParams( genDecl.Children[1].Children[1].Children[0].AstNode.(*ast.FieldList), ), } results = append(results, pst) } return results }
go
func findGollumPlugins(pkgRoot *ast.Package) []GollumPlugin { // Generate a tree structure from the parse results returned by AST tree := NewTree(pkgRoot) // The tree looks like this: /** *ast.Package *ast.File *ast.Ident *ast.GenDecl *ast.ImportSpec *ast.BasicLit [....] *ast.GenDecl *ast.CommentGroup *ast.Comment *ast.TypeSpec *ast.Ident *ast.StructType *ast.FieldList *ast.Field *ast.Ident *ast.Ident [....[ **/ // Search pattern pattern := PatternNode{ Comparison: "*ast.GenDecl", Children: []PatternNode{ { Comparison: "*ast.CommentGroup", // Note: there are N pcs of "*ast.Comment" children // here but we don't need to match them }, { Comparison: "*ast.TypeSpec", Children: []PatternNode{ { Comparison: "*ast.Ident", Callback: func(astNode ast.Node) bool { // Checks that the name starts with a capital letter return ast.IsExported(astNode.(*ast.Ident).Name) }, }, { Comparison: "*ast.StructType", Children: []PatternNode{ { Comparison: "*ast.FieldList", // There are N pcs of "*ast.Field" children here }, }, }, }, }, }, } // Search the tree results := []GollumPlugin{} for _, genDecl := range tree.Search(pattern) { pst := GollumPlugin{ Pkg: pkgRoot.Name, // Indexes assumed based on the search pattern above Name: genDecl.Children[1].Children[0].AstNode.(*ast.Ident).Name, Comment: genDecl.Children[0].AstNode.(*ast.CommentGroup).Text(), Embeds: getGollumPluginEmbedList(pkgRoot.Name, genDecl.Children[1].Children[1].Children[0].AstNode.(*ast.FieldList), ), StructTagParams: getGollumPluginConfigParams( genDecl.Children[1].Children[1].Children[0].AstNode.(*ast.FieldList), ), } results = append(results, pst) } return results }
[ "func", "findGollumPlugins", "(", "pkgRoot", "*", "ast", ".", "Package", ")", "[", "]", "GollumPlugin", "{", "// Generate a tree structure from the parse results returned by AST", "tree", ":=", "NewTree", "(", "pkgRoot", ")", "\n\n", "// The tree looks like this:", "/**\n\t\t*ast.Package\n\t\t *ast.File\n\t\t *ast.Ident\n\t\t *ast.GenDecl\n\t\t *ast.ImportSpec\n\t\t *ast.BasicLit\n\t\t [....]\n\t\t *ast.GenDecl\n\t\t *ast.CommentGroup\n\t\t *ast.Comment\n\t\t *ast.TypeSpec\n\t\t *ast.Ident\n\t\t *ast.StructType\n\t\t *ast.FieldList\n\t\t *ast.Field\n\t\t *ast.Ident\n\t\t *ast.Ident\n\t\t [....[\n\t**/", "// Search pattern", "pattern", ":=", "PatternNode", "{", "Comparison", ":", "\"", "\"", ",", "Children", ":", "[", "]", "PatternNode", "{", "{", "Comparison", ":", "\"", "\"", ",", "// Note: there are N pcs of \"*ast.Comment\" children", "// here but we don't need to match them", "}", ",", "{", "Comparison", ":", "\"", "\"", ",", "Children", ":", "[", "]", "PatternNode", "{", "{", "Comparison", ":", "\"", "\"", ",", "Callback", ":", "func", "(", "astNode", "ast", ".", "Node", ")", "bool", "{", "// Checks that the name starts with a capital letter", "return", "ast", ".", "IsExported", "(", "astNode", ".", "(", "*", "ast", ".", "Ident", ")", ".", "Name", ")", "\n", "}", ",", "}", ",", "{", "Comparison", ":", "\"", "\"", ",", "Children", ":", "[", "]", "PatternNode", "{", "{", "Comparison", ":", "\"", "\"", ",", "// There are N pcs of \"*ast.Field\" children here", "}", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", "\n\n", "// Search the tree", "results", ":=", "[", "]", "GollumPlugin", "{", "}", "\n", "for", "_", ",", "genDecl", ":=", "range", "tree", ".", "Search", "(", "pattern", ")", "{", "pst", ":=", "GollumPlugin", "{", "Pkg", ":", "pkgRoot", ".", "Name", ",", "// Indexes assumed based on the search pattern above", "Name", ":", "genDecl", ".", "Children", "[", "1", "]", ".", "Children", "[", "0", "]", ".", "AstNode", ".", "(", "*", "ast", ".", "Ident", ")", ".", "Name", ",", "Comment", ":", "genDecl", ".", "Children", "[", "0", "]", ".", "AstNode", ".", "(", "*", "ast", ".", "CommentGroup", ")", ".", "Text", "(", ")", ",", "Embeds", ":", "getGollumPluginEmbedList", "(", "pkgRoot", ".", "Name", ",", "genDecl", ".", "Children", "[", "1", "]", ".", "Children", "[", "1", "]", ".", "Children", "[", "0", "]", ".", "AstNode", ".", "(", "*", "ast", ".", "FieldList", ")", ",", ")", ",", "StructTagParams", ":", "getGollumPluginConfigParams", "(", "genDecl", ".", "Children", "[", "1", "]", ".", "Children", "[", "1", "]", ".", "Children", "[", "0", "]", ".", "AstNode", ".", "(", "*", "ast", ".", "FieldList", ")", ",", ")", ",", "}", "\n\n", "results", "=", "append", "(", "results", ",", "pst", ")", "\n", "}", "\n\n", "return", "results", "\n", "}" ]
// Searches the AST rooted at `pkgRoot` for struct types representing Gollum plugins
[ "Searches", "the", "AST", "rooted", "at", "pkgRoot", "for", "struct", "types", "representing", "Gollum", "plugins" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/gollumplugin.go#L27-L106
train
trivago/gollum
logger/console_formatter.go
NewConsoleFormatter
func NewConsoleFormatter() *prefixed.TextFormatter { f := prefixed.TextFormatter{} f.ForceColors = true f.FullTimestamp = true f.ForceFormatting = true f.TimestampFormat = "2006-01-02 15:04:05 MST" f.SetColorScheme(&prefixed.ColorScheme{ PrefixStyle: "blue+h", InfoLevelStyle: "white+h", DebugLevelStyle: "cyan", }) return &f }
go
func NewConsoleFormatter() *prefixed.TextFormatter { f := prefixed.TextFormatter{} f.ForceColors = true f.FullTimestamp = true f.ForceFormatting = true f.TimestampFormat = "2006-01-02 15:04:05 MST" f.SetColorScheme(&prefixed.ColorScheme{ PrefixStyle: "blue+h", InfoLevelStyle: "white+h", DebugLevelStyle: "cyan", }) return &f }
[ "func", "NewConsoleFormatter", "(", ")", "*", "prefixed", ".", "TextFormatter", "{", "f", ":=", "prefixed", ".", "TextFormatter", "{", "}", "\n\n", "f", ".", "ForceColors", "=", "true", "\n", "f", ".", "FullTimestamp", "=", "true", "\n", "f", ".", "ForceFormatting", "=", "true", "\n", "f", ".", "TimestampFormat", "=", "\"", "\"", "\n\n", "f", ".", "SetColorScheme", "(", "&", "prefixed", ".", "ColorScheme", "{", "PrefixStyle", ":", "\"", "\"", ",", "InfoLevelStyle", ":", "\"", "\"", ",", "DebugLevelStyle", ":", "\"", "\"", ",", "}", ")", "\n\n", "return", "&", "f", "\n", "}" ]
// NewConsoleFormatter returns a a ConsoleFormatter reference
[ "NewConsoleFormatter", "returns", "a", "a", "ConsoleFormatter", "reference" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/logger/console_formatter.go#L22-L37
train
trivago/gollum
core/formatter.go
ApplyFormatter
func (formatters FormatterArray) ApplyFormatter(msg *Message) error { for _, formatter := range formatters { if formatter.CanBeApplied(msg) { if err := formatter.ApplyFormatter(msg); err != nil { return err } } } return nil }
go
func (formatters FormatterArray) ApplyFormatter(msg *Message) error { for _, formatter := range formatters { if formatter.CanBeApplied(msg) { if err := formatter.ApplyFormatter(msg); err != nil { return err } } } return nil }
[ "func", "(", "formatters", "FormatterArray", ")", "ApplyFormatter", "(", "msg", "*", "Message", ")", "error", "{", "for", "_", ",", "formatter", ":=", "range", "formatters", "{", "if", "formatter", ".", "CanBeApplied", "(", "msg", ")", "{", "if", "err", ":=", "formatter", ".", "ApplyFormatter", "(", "msg", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ApplyFormatter calls ApplyFormatter on every formatter
[ "ApplyFormatter", "calls", "ApplyFormatter", "on", "every", "formatter" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/formatter.go#L33-L42
train
trivago/gollum
coordinator.go
NewCoordinator
func NewCoordinator() Coordinator { return Coordinator{ consumerWorker: new(sync.WaitGroup), producerWorker: new(sync.WaitGroup), state: coordinatorStateConfigure, } }
go
func NewCoordinator() Coordinator { return Coordinator{ consumerWorker: new(sync.WaitGroup), producerWorker: new(sync.WaitGroup), state: coordinatorStateConfigure, } }
[ "func", "NewCoordinator", "(", ")", "Coordinator", "{", "return", "Coordinator", "{", "consumerWorker", ":", "new", "(", "sync", ".", "WaitGroup", ")", ",", "producerWorker", ":", "new", "(", "sync", ".", "WaitGroup", ")", ",", "state", ":", "coordinatorStateConfigure", ",", "}", "\n", "}" ]
// NewCoordinator creates a new multplexer
[ "NewCoordinator", "creates", "a", "new", "multplexer" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/coordinator.go#L64-L70
train