id
int32
0
167k
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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
142,100
decred/dcrdata
exchanges/bot.go
Indices
func (bot *ExchangeBot) Indices(token string) FiatIndices { bot.mtx.RLock() defer bot.mtx.RUnlock() indices := make(FiatIndices) for code, price := range bot.indexMap[token] { indices[code] = price } return indices }
go
func (bot *ExchangeBot) Indices(token string) FiatIndices { bot.mtx.RLock() defer bot.mtx.RUnlock() indices := make(FiatIndices) for code, price := range bot.indexMap[token] { indices[code] = price } return indices }
[ "func", "(", "bot", "*", "ExchangeBot", ")", "Indices", "(", "token", "string", ")", "FiatIndices", "{", "bot", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "bot", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "indices", ":=", "make", "(", "FiatIndices", ")", "\n", "for", "code", ",", "price", ":=", "range", "bot", ".", "indexMap", "[", "token", "]", "{", "indices", "[", "code", "]", "=", "price", "\n", "}", "\n", "return", "indices", "\n", "}" ]
// Indices is the fiat indices for a given BTC index exchange.
[ "Indices", "is", "the", "fiat", "indices", "for", "a", "given", "BTC", "index", "exchange", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L625-L633
142,101
decred/dcrdata
exchanges/bot.go
processState
func (bot *ExchangeBot) processState(states map[string]*ExchangeState, volumeAveraged bool) (float64, float64) { var priceAccumulator, volSum float64 var deletions []string oldestValid := time.Now().Add(-bot.RequestExpiry) for token, state := range states { if bot.Exchanges[token].LastUpdate().Before(oldestValid) { deletions = append(deletions, token) continue } volume := 1.0 if volumeAveraged { volume = state.Volume } volSum += volume priceAccumulator += volume * state.Price } for _, token := range deletions { delete(states, token) } if volSum == 0 { return 0, 0 } return priceAccumulator / volSum, volSum }
go
func (bot *ExchangeBot) processState(states map[string]*ExchangeState, volumeAveraged bool) (float64, float64) { var priceAccumulator, volSum float64 var deletions []string oldestValid := time.Now().Add(-bot.RequestExpiry) for token, state := range states { if bot.Exchanges[token].LastUpdate().Before(oldestValid) { deletions = append(deletions, token) continue } volume := 1.0 if volumeAveraged { volume = state.Volume } volSum += volume priceAccumulator += volume * state.Price } for _, token := range deletions { delete(states, token) } if volSum == 0 { return 0, 0 } return priceAccumulator / volSum, volSum }
[ "func", "(", "bot", "*", "ExchangeBot", ")", "processState", "(", "states", "map", "[", "string", "]", "*", "ExchangeState", ",", "volumeAveraged", "bool", ")", "(", "float64", ",", "float64", ")", "{", "var", "priceAccumulator", ",", "volSum", "float64", "\n", "var", "deletions", "[", "]", "string", "\n", "oldestValid", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "-", "bot", ".", "RequestExpiry", ")", "\n", "for", "token", ",", "state", ":=", "range", "states", "{", "if", "bot", ".", "Exchanges", "[", "token", "]", ".", "LastUpdate", "(", ")", ".", "Before", "(", "oldestValid", ")", "{", "deletions", "=", "append", "(", "deletions", ",", "token", ")", "\n", "continue", "\n", "}", "\n", "volume", ":=", "1.0", "\n", "if", "volumeAveraged", "{", "volume", "=", "state", ".", "Volume", "\n", "}", "\n", "volSum", "+=", "volume", "\n", "priceAccumulator", "+=", "volume", "*", "state", ".", "Price", "\n", "}", "\n", "for", "_", ",", "token", ":=", "range", "deletions", "{", "delete", "(", "states", ",", "token", ")", "\n", "}", "\n", "if", "volSum", "==", "0", "{", "return", "0", ",", "0", "\n", "}", "\n", "return", "priceAccumulator", "/", "volSum", ",", "volSum", "\n", "}" ]
// processState is a helper function to process a slice of ExchangeState into // a price, and optionally a volume sum, and perform some cleanup along the way. // If volumeAveraged is false, all exchanges are given equal weight in the avg.
[ "processState", "is", "a", "helper", "function", "to", "process", "a", "slice", "of", "ExchangeState", "into", "a", "price", "and", "optionally", "a", "volume", "sum", "and", "perform", "some", "cleanup", "along", "the", "way", ".", "If", "volumeAveraged", "is", "false", "all", "exchanges", "are", "given", "equal", "weight", "in", "the", "avg", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L655-L678
142,102
decred/dcrdata
exchanges/bot.go
updateExchange
func (bot *ExchangeBot) updateExchange(update *ExchangeUpdate) error { bot.mtx.Lock() defer bot.mtx.Unlock() if update.State.Candlesticks != nil { for bin := range update.State.Candlesticks { bot.incrementChart(genCacheID(update.Token, string(bin))) } } if update.State.Depth != nil { bot.incrementChart(genCacheID(update.Token, "depth")) } bot.currentState.DcrBtc[update.Token] = update.State return bot.updateState() }
go
func (bot *ExchangeBot) updateExchange(update *ExchangeUpdate) error { bot.mtx.Lock() defer bot.mtx.Unlock() if update.State.Candlesticks != nil { for bin := range update.State.Candlesticks { bot.incrementChart(genCacheID(update.Token, string(bin))) } } if update.State.Depth != nil { bot.incrementChart(genCacheID(update.Token, "depth")) } bot.currentState.DcrBtc[update.Token] = update.State return bot.updateState() }
[ "func", "(", "bot", "*", "ExchangeBot", ")", "updateExchange", "(", "update", "*", "ExchangeUpdate", ")", "error", "{", "bot", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "bot", ".", "mtx", ".", "Unlock", "(", ")", "\n", "if", "update", ".", "State", ".", "Candlesticks", "!=", "nil", "{", "for", "bin", ":=", "range", "update", ".", "State", ".", "Candlesticks", "{", "bot", ".", "incrementChart", "(", "genCacheID", "(", "update", ".", "Token", ",", "string", "(", "bin", ")", ")", ")", "\n", "}", "\n", "}", "\n", "if", "update", ".", "State", ".", "Depth", "!=", "nil", "{", "bot", ".", "incrementChart", "(", "genCacheID", "(", "update", ".", "Token", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "bot", ".", "currentState", ".", "DcrBtc", "[", "update", ".", "Token", "]", "=", "update", ".", "State", "\n", "return", "bot", ".", "updateState", "(", ")", "\n", "}" ]
// updateExchange processes an update from a Decred-BTC Exchange.
[ "updateExchange", "processes", "an", "update", "from", "a", "Decred", "-", "BTC", "Exchange", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L681-L694
142,103
decred/dcrdata
exchanges/bot.go
updateIndices
func (bot *ExchangeBot) updateIndices(update *IndexUpdate) error { bot.mtx.Lock() defer bot.mtx.Unlock() bot.indexMap[update.Token] = update.Indices price, hasCode := update.Indices[bot.config.BtcIndex] if hasCode { bot.currentState.FiatIndices[update.Token] = &ExchangeState{ Price: price, Stamp: time.Now().Unix(), } return bot.updateState() } log.Warnf("Default currency code, %s, not contained in update from %s", bot.BtcIndex, update.Token) return nil }
go
func (bot *ExchangeBot) updateIndices(update *IndexUpdate) error { bot.mtx.Lock() defer bot.mtx.Unlock() bot.indexMap[update.Token] = update.Indices price, hasCode := update.Indices[bot.config.BtcIndex] if hasCode { bot.currentState.FiatIndices[update.Token] = &ExchangeState{ Price: price, Stamp: time.Now().Unix(), } return bot.updateState() } log.Warnf("Default currency code, %s, not contained in update from %s", bot.BtcIndex, update.Token) return nil }
[ "func", "(", "bot", "*", "ExchangeBot", ")", "updateIndices", "(", "update", "*", "IndexUpdate", ")", "error", "{", "bot", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "bot", ".", "mtx", ".", "Unlock", "(", ")", "\n", "bot", ".", "indexMap", "[", "update", ".", "Token", "]", "=", "update", ".", "Indices", "\n", "price", ",", "hasCode", ":=", "update", ".", "Indices", "[", "bot", ".", "config", ".", "BtcIndex", "]", "\n", "if", "hasCode", "{", "bot", ".", "currentState", ".", "FiatIndices", "[", "update", ".", "Token", "]", "=", "&", "ExchangeState", "{", "Price", ":", "price", ",", "Stamp", ":", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ",", "}", "\n", "return", "bot", ".", "updateState", "(", ")", "\n", "}", "\n", "log", ".", "Warnf", "(", "\"", "\"", ",", "bot", ".", "BtcIndex", ",", "update", ".", "Token", ")", "\n", "return", "nil", "\n", "}" ]
// updateIndices processes an update from an Bitcoin index source, essentially // a map pairing currency codes to bitcoin prices.
[ "updateIndices", "processes", "an", "update", "from", "an", "Bitcoin", "index", "source", "essentially", "a", "map", "pairing", "currency", "codes", "to", "bitcoin", "prices", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L698-L712
142,104
decred/dcrdata
exchanges/bot.go
nextTick
func (bot *ExchangeBot) nextTick() *time.Timer { tNow := time.Now() tOldest := tNow for _, xc := range bot.Exchanges { t := xc.LastTry() if t.Before(tOldest) { tOldest = t } } tSince := tNow.Sub(tOldest) tilNext := bot.DataExpiry - tSince if tilNext < bot.minTick { tilNext = bot.minTick } return time.NewTimer(tilNext) }
go
func (bot *ExchangeBot) nextTick() *time.Timer { tNow := time.Now() tOldest := tNow for _, xc := range bot.Exchanges { t := xc.LastTry() if t.Before(tOldest) { tOldest = t } } tSince := tNow.Sub(tOldest) tilNext := bot.DataExpiry - tSince if tilNext < bot.minTick { tilNext = bot.minTick } return time.NewTimer(tilNext) }
[ "func", "(", "bot", "*", "ExchangeBot", ")", "nextTick", "(", ")", "*", "time", ".", "Timer", "{", "tNow", ":=", "time", ".", "Now", "(", ")", "\n", "tOldest", ":=", "tNow", "\n", "for", "_", ",", "xc", ":=", "range", "bot", ".", "Exchanges", "{", "t", ":=", "xc", ".", "LastTry", "(", ")", "\n", "if", "t", ".", "Before", "(", "tOldest", ")", "{", "tOldest", "=", "t", "\n", "}", "\n", "}", "\n", "tSince", ":=", "tNow", ".", "Sub", "(", "tOldest", ")", "\n", "tilNext", ":=", "bot", ".", "DataExpiry", "-", "tSince", "\n", "if", "tilNext", "<", "bot", ".", "minTick", "{", "tilNext", "=", "bot", ".", "minTick", "\n", "}", "\n", "return", "time", ".", "NewTimer", "(", "tilNext", ")", "\n", "}" ]
// nextTick checks the exchanges' last update and fail times, and calculates // when the next Cycle should run.
[ "nextTick", "checks", "the", "exchanges", "last", "update", "and", "fail", "times", "and", "calculates", "when", "the", "next", "Cycle", "should", "run", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L756-L771
142,105
decred/dcrdata
exchanges/bot.go
Cycle
func (bot *ExchangeBot) Cycle() { tNow := time.Now() for _, xc := range bot.Exchanges { if tNow.Sub(xc.LastTry()) > bot.DataExpiry { go xc.Refresh() } } }
go
func (bot *ExchangeBot) Cycle() { tNow := time.Now() for _, xc := range bot.Exchanges { if tNow.Sub(xc.LastTry()) > bot.DataExpiry { go xc.Refresh() } } }
[ "func", "(", "bot", "*", "ExchangeBot", ")", "Cycle", "(", ")", "{", "tNow", ":=", "time", ".", "Now", "(", ")", "\n", "for", "_", ",", "xc", ":=", "range", "bot", ".", "Exchanges", "{", "if", "tNow", ".", "Sub", "(", "xc", ".", "LastTry", "(", ")", ")", ">", "bot", ".", "DataExpiry", "{", "go", "xc", ".", "Refresh", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Cycle refreshes all expired exchanges.
[ "Cycle", "refreshes", "all", "expired", "exchanges", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L774-L781
142,106
decred/dcrdata
exchanges/bot.go
TwoDecimals
func (c *Conversion) TwoDecimals() string { if c.Value == 0.0 { return "0.00" } else if c.Value < 1.0 && c.Value > -1.0 { return fmt.Sprintf("%3g", c.Value) } return fmt.Sprintf("%.2f", c.Value) }
go
func (c *Conversion) TwoDecimals() string { if c.Value == 0.0 { return "0.00" } else if c.Value < 1.0 && c.Value > -1.0 { return fmt.Sprintf("%3g", c.Value) } return fmt.Sprintf("%.2f", c.Value) }
[ "func", "(", "c", "*", "Conversion", ")", "TwoDecimals", "(", ")", "string", "{", "if", "c", ".", "Value", "==", "0.0", "{", "return", "\"", "\"", "\n", "}", "else", "if", "c", ".", "Value", "<", "1.0", "&&", "c", ".", "Value", ">", "-", "1.0", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "Value", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "Value", ")", "\n", "}" ]
// TwoDecimals is a string representation of the value with two digits after // the decimal point, but will show more to achieve at least three significant // digits.
[ "TwoDecimals", "is", "a", "string", "representation", "of", "the", "value", "with", "two", "digits", "after", "the", "decimal", "point", "but", "will", "show", "more", "to", "achieve", "at", "least", "three", "significant", "digits", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L799-L806
142,107
decred/dcrdata
exchanges/bot.go
Conversion
func (bot *ExchangeBot) Conversion(dcrVal float64) *Conversion { if bot == nil { return nil } xcState := bot.State() if xcState != nil { return &Conversion{ Value: xcState.Price * dcrVal, Index: xcState.BtcIndex, } } return nil }
go
func (bot *ExchangeBot) Conversion(dcrVal float64) *Conversion { if bot == nil { return nil } xcState := bot.State() if xcState != nil { return &Conversion{ Value: xcState.Price * dcrVal, Index: xcState.BtcIndex, } } return nil }
[ "func", "(", "bot", "*", "ExchangeBot", ")", "Conversion", "(", "dcrVal", "float64", ")", "*", "Conversion", "{", "if", "bot", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "xcState", ":=", "bot", ".", "State", "(", ")", "\n", "if", "xcState", "!=", "nil", "{", "return", "&", "Conversion", "{", "Value", ":", "xcState", ".", "Price", "*", "dcrVal", ",", "Index", ":", "xcState", ".", "BtcIndex", ",", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Conversion attempts to multiply the supplied float with the default index. // Nil pointer will be returned if there is no valid exchangeState.
[ "Conversion", "attempts", "to", "multiply", "the", "supplied", "float", "with", "the", "default", "index", ".", "Nil", "pointer", "will", "be", "returned", "if", "there", "is", "no", "valid", "exchangeState", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L810-L822
142,108
decred/dcrdata
exchanges/bot.go
QuickSticks
func (bot *ExchangeBot) QuickSticks(token string, rawBin string) ([]byte, error) { chartID := genCacheID(token, rawBin) bin := candlestickKey(rawBin) data, bestVersion, isGood := bot.fetchFromCache(chartID) if isGood { return data, nil } // No hit on cache. Re-encode. bot.mtx.Lock() defer bot.mtx.Unlock() state, found := bot.currentState.DcrBtc[token] if !found { return nil, fmt.Errorf("Failed to find DCR exchange state for %s", token) } if state.Candlesticks == nil { return nil, fmt.Errorf("Failed to find candlesticks for %s", token) } sticks, found := state.Candlesticks[bin] if !found { return nil, fmt.Errorf("Failed to find candlesticks for %s and bin %s", token, rawBin) } if len(sticks) == 0 { return nil, fmt.Errorf("Empty candlesticks for %s and bin %s", token, rawBin) } expiration := sticks[len(sticks)-1].Start.Add(2 * bin.duration()) chart, err := bot.jsonify(&candlestickResponse{ BtcIndex: bot.BtcIndex, Price: bot.currentState.Price, Sticks: sticks, Expiration: expiration.Unix(), }) if err != nil { return nil, fmt.Errorf("JSON encode error for %s and bin %s", token, rawBin) } vChart := &versionedChart{ chartID: chartID, dataID: bestVersion, time: expiration, chart: chart, } bot.versionedCharts[chartID] = vChart return vChart.chart, nil }
go
func (bot *ExchangeBot) QuickSticks(token string, rawBin string) ([]byte, error) { chartID := genCacheID(token, rawBin) bin := candlestickKey(rawBin) data, bestVersion, isGood := bot.fetchFromCache(chartID) if isGood { return data, nil } // No hit on cache. Re-encode. bot.mtx.Lock() defer bot.mtx.Unlock() state, found := bot.currentState.DcrBtc[token] if !found { return nil, fmt.Errorf("Failed to find DCR exchange state for %s", token) } if state.Candlesticks == nil { return nil, fmt.Errorf("Failed to find candlesticks for %s", token) } sticks, found := state.Candlesticks[bin] if !found { return nil, fmt.Errorf("Failed to find candlesticks for %s and bin %s", token, rawBin) } if len(sticks) == 0 { return nil, fmt.Errorf("Empty candlesticks for %s and bin %s", token, rawBin) } expiration := sticks[len(sticks)-1].Start.Add(2 * bin.duration()) chart, err := bot.jsonify(&candlestickResponse{ BtcIndex: bot.BtcIndex, Price: bot.currentState.Price, Sticks: sticks, Expiration: expiration.Unix(), }) if err != nil { return nil, fmt.Errorf("JSON encode error for %s and bin %s", token, rawBin) } vChart := &versionedChart{ chartID: chartID, dataID: bestVersion, time: expiration, chart: chart, } bot.versionedCharts[chartID] = vChart return vChart.chart, nil }
[ "func", "(", "bot", "*", "ExchangeBot", ")", "QuickSticks", "(", "token", "string", ",", "rawBin", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "chartID", ":=", "genCacheID", "(", "token", ",", "rawBin", ")", "\n", "bin", ":=", "candlestickKey", "(", "rawBin", ")", "\n", "data", ",", "bestVersion", ",", "isGood", ":=", "bot", ".", "fetchFromCache", "(", "chartID", ")", "\n", "if", "isGood", "{", "return", "data", ",", "nil", "\n", "}", "\n\n", "// No hit on cache. Re-encode.", "bot", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "bot", ".", "mtx", ".", "Unlock", "(", ")", "\n", "state", ",", "found", ":=", "bot", ".", "currentState", ".", "DcrBtc", "[", "token", "]", "\n", "if", "!", "found", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ")", "\n", "}", "\n", "if", "state", ".", "Candlesticks", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ")", "\n", "}", "\n\n", "sticks", ",", "found", ":=", "state", ".", "Candlesticks", "[", "bin", "]", "\n", "if", "!", "found", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ",", "rawBin", ")", "\n", "}", "\n", "if", "len", "(", "sticks", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ",", "rawBin", ")", "\n", "}", "\n\n", "expiration", ":=", "sticks", "[", "len", "(", "sticks", ")", "-", "1", "]", ".", "Start", ".", "Add", "(", "2", "*", "bin", ".", "duration", "(", ")", ")", "\n\n", "chart", ",", "err", ":=", "bot", ".", "jsonify", "(", "&", "candlestickResponse", "{", "BtcIndex", ":", "bot", ".", "BtcIndex", ",", "Price", ":", "bot", ".", "currentState", ".", "Price", ",", "Sticks", ":", "sticks", ",", "Expiration", ":", "expiration", ".", "Unix", "(", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ",", "rawBin", ")", "\n", "}", "\n\n", "vChart", ":=", "&", "versionedChart", "{", "chartID", ":", "chartID", ",", "dataID", ":", "bestVersion", ",", "time", ":", "expiration", ",", "chart", ":", "chart", ",", "}", "\n\n", "bot", ".", "versionedCharts", "[", "chartID", "]", "=", "vChart", "\n", "return", "vChart", ".", "chart", ",", "nil", "\n", "}" ]
// QuickSticks returns the up-to-date candlestick data for the specified // exchange and bin width, pulling from the cache if appropriate.
[ "QuickSticks", "returns", "the", "up", "-", "to", "-", "date", "candlestick", "data", "for", "the", "specified", "exchange", "and", "bin", "width", "pulling", "from", "the", "cache", "if", "appropriate", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L841-L890
142,109
decred/dcrdata
exchanges/bot.go
QuickDepth
func (bot *ExchangeBot) QuickDepth(token string) ([]byte, error) { chartID := genCacheID(token, "depth") data, bestVersion, isGood := bot.fetchFromCache(chartID) if isGood { return data, nil } // No hit on cache. Re-encode. bot.mtx.Lock() defer bot.mtx.Unlock() state, found := bot.currentState.DcrBtc[token] if !found { return []byte{}, fmt.Errorf("Failed to find DCR exchange state for %s", token) } if state.Depth == nil { return []byte{}, fmt.Errorf("Failed to find depth for %s", token) } chart, err := bot.jsonify(&depthResponse{ BtcIndex: bot.BtcIndex, Price: bot.currentState.Price, Data: state.Depth, Expiration: state.Depth.Time + int64(bot.RequestExpiry.Seconds()), }) if err != nil { return []byte{}, fmt.Errorf("JSON encode error for %s depth chart", token) } vChart := &versionedChart{ chartID: chartID, dataID: bestVersion, time: time.Unix(state.Depth.Time, 0), chart: chart, } bot.versionedCharts[chartID] = vChart return vChart.chart, nil }
go
func (bot *ExchangeBot) QuickDepth(token string) ([]byte, error) { chartID := genCacheID(token, "depth") data, bestVersion, isGood := bot.fetchFromCache(chartID) if isGood { return data, nil } // No hit on cache. Re-encode. bot.mtx.Lock() defer bot.mtx.Unlock() state, found := bot.currentState.DcrBtc[token] if !found { return []byte{}, fmt.Errorf("Failed to find DCR exchange state for %s", token) } if state.Depth == nil { return []byte{}, fmt.Errorf("Failed to find depth for %s", token) } chart, err := bot.jsonify(&depthResponse{ BtcIndex: bot.BtcIndex, Price: bot.currentState.Price, Data: state.Depth, Expiration: state.Depth.Time + int64(bot.RequestExpiry.Seconds()), }) if err != nil { return []byte{}, fmt.Errorf("JSON encode error for %s depth chart", token) } vChart := &versionedChart{ chartID: chartID, dataID: bestVersion, time: time.Unix(state.Depth.Time, 0), chart: chart, } bot.versionedCharts[chartID] = vChart return vChart.chart, nil }
[ "func", "(", "bot", "*", "ExchangeBot", ")", "QuickDepth", "(", "token", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "chartID", ":=", "genCacheID", "(", "token", ",", "\"", "\"", ")", "\n", "data", ",", "bestVersion", ",", "isGood", ":=", "bot", ".", "fetchFromCache", "(", "chartID", ")", "\n", "if", "isGood", "{", "return", "data", ",", "nil", "\n", "}", "\n\n", "// No hit on cache. Re-encode.", "bot", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "bot", ".", "mtx", ".", "Unlock", "(", ")", "\n", "state", ",", "found", ":=", "bot", ".", "currentState", ".", "DcrBtc", "[", "token", "]", "\n", "if", "!", "found", "{", "return", "[", "]", "byte", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ")", "\n", "}", "\n", "if", "state", ".", "Depth", "==", "nil", "{", "return", "[", "]", "byte", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ")", "\n", "}", "\n", "chart", ",", "err", ":=", "bot", ".", "jsonify", "(", "&", "depthResponse", "{", "BtcIndex", ":", "bot", ".", "BtcIndex", ",", "Price", ":", "bot", ".", "currentState", ".", "Price", ",", "Data", ":", "state", ".", "Depth", ",", "Expiration", ":", "state", ".", "Depth", ".", "Time", "+", "int64", "(", "bot", ".", "RequestExpiry", ".", "Seconds", "(", ")", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "byte", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ")", "\n", "}", "\n\n", "vChart", ":=", "&", "versionedChart", "{", "chartID", ":", "chartID", ",", "dataID", ":", "bestVersion", ",", "time", ":", "time", ".", "Unix", "(", "state", ".", "Depth", ".", "Time", ",", "0", ")", ",", "chart", ":", "chart", ",", "}", "\n\n", "bot", ".", "versionedCharts", "[", "chartID", "]", "=", "vChart", "\n", "return", "vChart", ".", "chart", ",", "nil", "\n", "}" ]
// QuickDepth returns the up-to-date depth chart data for the specified // exchange, pulling from the cache if appropriate.
[ "QuickDepth", "returns", "the", "up", "-", "to", "-", "date", "depth", "chart", "data", "for", "the", "specified", "exchange", "pulling", "from", "the", "cache", "if", "appropriate", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L894-L931
142,110
decred/dcrdata
middleware/apimiddleware.go
writeHTMLBadRequest
func writeHTMLBadRequest(w http.ResponseWriter, str string) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusBadRequest) io.WriteString(w, str) }
go
func writeHTMLBadRequest(w http.ResponseWriter, str string) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusBadRequest) io.WriteString(w, str) }
[ "func", "writeHTMLBadRequest", "(", "w", "http", ".", "ResponseWriter", ",", "str", "string", ")", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusBadRequest", ")", "\n", "io", ".", "WriteString", "(", "w", ",", "str", ")", "\n", "}" ]
// writeHTMLBadRequest is used for the Insight API error response for a BAD REQUEST. // This means the request was malformed in some way or the request HASH, // ADDRESS, BLOCK was not valid.
[ "writeHTMLBadRequest", "is", "used", "for", "the", "Insight", "API", "error", "response", "for", "a", "BAD", "REQUEST", ".", "This", "means", "the", "request", "was", "malformed", "in", "some", "way", "or", "the", "request", "HASH", "ADDRESS", "BLOCK", "was", "not", "valid", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L70-L74
142,111
decred/dcrdata
middleware/apimiddleware.go
GetBlockStepCtx
func GetBlockStepCtx(r *http.Request) int { step, ok := r.Context().Value(ctxBlockStep).(int) if !ok { apiLog.Error("block step is not set or is not an int") return -1 } return step }
go
func GetBlockStepCtx(r *http.Request) int { step, ok := r.Context().Value(ctxBlockStep).(int) if !ok { apiLog.Error("block step is not set or is not an int") return -1 } return step }
[ "func", "GetBlockStepCtx", "(", "r", "*", "http", ".", "Request", ")", "int", "{", "step", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxBlockStep", ")", ".", "(", "int", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "-", "1", "\n", "}", "\n", "return", "step", "\n", "}" ]
// GetBlockStepCtx retrieves the ctxBlockStep data from the request context. If // not set, the return value is -1.
[ "GetBlockStepCtx", "retrieves", "the", "ctxBlockStep", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "-", "1", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L88-L95
142,112
decred/dcrdata
middleware/apimiddleware.go
GetBlockIndex0Ctx
func GetBlockIndex0Ctx(r *http.Request) int { idx, ok := r.Context().Value(ctxBlockIndex0).(int) if !ok { apiLog.Error("block index0 is not set or is not an int") return -1 } return idx }
go
func GetBlockIndex0Ctx(r *http.Request) int { idx, ok := r.Context().Value(ctxBlockIndex0).(int) if !ok { apiLog.Error("block index0 is not set or is not an int") return -1 } return idx }
[ "func", "GetBlockIndex0Ctx", "(", "r", "*", "http", ".", "Request", ")", "int", "{", "idx", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxBlockIndex0", ")", ".", "(", "int", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "-", "1", "\n", "}", "\n", "return", "idx", "\n", "}" ]
// GetBlockIndex0Ctx retrieves the ctxBlockIndex0 data from the request context. // If not set, the return value is -1.
[ "GetBlockIndex0Ctx", "retrieves", "the", "ctxBlockIndex0", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "-", "1", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L99-L106
142,113
decred/dcrdata
middleware/apimiddleware.go
GetTxIOIndexCtx
func GetTxIOIndexCtx(r *http.Request) int { index, ok := r.Context().Value(ctxTxInOutIndex).(int) if !ok { apiLog.Warn("txinoutindex is not set or is not an int") return -1 } return index }
go
func GetTxIOIndexCtx(r *http.Request) int { index, ok := r.Context().Value(ctxTxInOutIndex).(int) if !ok { apiLog.Warn("txinoutindex is not set or is not an int") return -1 } return index }
[ "func", "GetTxIOIndexCtx", "(", "r", "*", "http", ".", "Request", ")", "int", "{", "index", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxTxInOutIndex", ")", ".", "(", "int", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "-", "1", "\n", "}", "\n", "return", "index", "\n", "}" ]
// GetTxIOIndexCtx retrieves the ctxTxInOutIndex data from the request context. // If not set, the return value is -1.
[ "GetTxIOIndexCtx", "retrieves", "the", "ctxTxInOutIndex", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "-", "1", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L110-L117
142,114
decred/dcrdata
middleware/apimiddleware.go
GetNCtx
func GetNCtx(r *http.Request) int { N, ok := r.Context().Value(ctxN).(int) if !ok { apiLog.Trace("N is not set or is not an int") return -1 } return N }
go
func GetNCtx(r *http.Request) int { N, ok := r.Context().Value(ctxN).(int) if !ok { apiLog.Trace("N is not set or is not an int") return -1 } return N }
[ "func", "GetNCtx", "(", "r", "*", "http", ".", "Request", ")", "int", "{", "N", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxN", ")", ".", "(", "int", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Trace", "(", "\"", "\"", ")", "\n", "return", "-", "1", "\n", "}", "\n", "return", "N", "\n", "}" ]
// GetNCtx retrieves the ctxN data from the request context. If not set, the // return value is -1.
[ "GetNCtx", "retrieves", "the", "ctxN", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "-", "1", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L121-L128
142,115
decred/dcrdata
middleware/apimiddleware.go
GetMCtx
func GetMCtx(r *http.Request) int { M, ok := r.Context().Value(ctxM).(int) if !ok { apiLog.Trace("M is not set or is not an int") return -1 } return M }
go
func GetMCtx(r *http.Request) int { M, ok := r.Context().Value(ctxM).(int) if !ok { apiLog.Trace("M is not set or is not an int") return -1 } return M }
[ "func", "GetMCtx", "(", "r", "*", "http", ".", "Request", ")", "int", "{", "M", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxM", ")", ".", "(", "int", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Trace", "(", "\"", "\"", ")", "\n", "return", "-", "1", "\n", "}", "\n", "return", "M", "\n", "}" ]
// GetMCtx retrieves the ctxM data from the request context. If not set, the // return value is -1.
[ "GetMCtx", "retrieves", "the", "ctxM", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "-", "1", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L132-L139
142,116
decred/dcrdata
middleware/apimiddleware.go
GetTpCtx
func GetTpCtx(r *http.Request) string { tp, ok := r.Context().Value(ctxTp).(string) if !ok { apiLog.Trace("ticket pool interval not set") return "" } return tp }
go
func GetTpCtx(r *http.Request) string { tp, ok := r.Context().Value(ctxTp).(string) if !ok { apiLog.Trace("ticket pool interval not set") return "" } return tp }
[ "func", "GetTpCtx", "(", "r", "*", "http", ".", "Request", ")", "string", "{", "tp", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxTp", ")", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Trace", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", "\n", "}", "\n", "return", "tp", "\n", "}" ]
// GetTpCtx retrieves the ctxTp data from the request context. // If the value is not set, an empty string is returned.
[ "GetTpCtx", "retrieves", "the", "ctxTp", "data", "from", "the", "request", "context", ".", "If", "the", "value", "is", "not", "set", "an", "empty", "string", "is", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L143-L150
142,117
decred/dcrdata
middleware/apimiddleware.go
GetProposalTokenCtx
func GetProposalTokenCtx(r *http.Request) string { tp, ok := r.Context().Value(ctxProposalToken).(string) if !ok { apiLog.Trace("proposal token hash not set") return "" } return tp }
go
func GetProposalTokenCtx(r *http.Request) string { tp, ok := r.Context().Value(ctxProposalToken).(string) if !ok { apiLog.Trace("proposal token hash not set") return "" } return tp }
[ "func", "GetProposalTokenCtx", "(", "r", "*", "http", ".", "Request", ")", "string", "{", "tp", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxProposalToken", ")", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Trace", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", "\n", "}", "\n", "return", "tp", "\n", "}" ]
// GetProposalTokenCtx retrieves the ctxProposalToken data from the request context. // If the value is not set, an empty string is returned.
[ "GetProposalTokenCtx", "retrieves", "the", "ctxProposalToken", "data", "from", "the", "request", "context", ".", "If", "the", "value", "is", "not", "set", "an", "empty", "string", "is", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L154-L161
142,118
decred/dcrdata
middleware/apimiddleware.go
GetRawHexTx
func GetRawHexTx(r *http.Request) (string, error) { rawHexTx, ok := r.Context().Value(ctxRawHexTx).(string) if !ok { apiLog.Trace("hex transaction id not set") return "", fmt.Errorf("hex transaction id not set") } msgtx := wire.NewMsgTx() err := msgtx.Deserialize(hex.NewDecoder(strings.NewReader(rawHexTx))) if err != nil { return "", fmt.Errorf("failed to deserialize tx: %v", err) } return rawHexTx, nil }
go
func GetRawHexTx(r *http.Request) (string, error) { rawHexTx, ok := r.Context().Value(ctxRawHexTx).(string) if !ok { apiLog.Trace("hex transaction id not set") return "", fmt.Errorf("hex transaction id not set") } msgtx := wire.NewMsgTx() err := msgtx.Deserialize(hex.NewDecoder(strings.NewReader(rawHexTx))) if err != nil { return "", fmt.Errorf("failed to deserialize tx: %v", err) } return rawHexTx, nil }
[ "func", "GetRawHexTx", "(", "r", "*", "http", ".", "Request", ")", "(", "string", ",", "error", ")", "{", "rawHexTx", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxRawHexTx", ")", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Trace", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "msgtx", ":=", "wire", ".", "NewMsgTx", "(", ")", "\n", "err", ":=", "msgtx", ".", "Deserialize", "(", "hex", ".", "NewDecoder", "(", "strings", ".", "NewReader", "(", "rawHexTx", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "rawHexTx", ",", "nil", "\n", "}" ]
// GetRawHexTx retrieves the ctxRawHexTx data from the request context. If not // set, the return value is an empty string.
[ "GetRawHexTx", "retrieves", "the", "ctxRawHexTx", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "an", "empty", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L165-L178
142,119
decred/dcrdata
middleware/apimiddleware.go
PostBroadcastTxCtx
func PostBroadcastTxCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req apitypes.InsightRawTx body, err := ioutil.ReadAll(r.Body) r.Body.Close() if err != nil { writeHTMLBadRequest(w, fmt.Sprintf("Error reading JSON message: %v", err)) return } err = json.Unmarshal(body, &req) if err != nil { writeHTMLBadRequest(w, fmt.Sprintf("Failed to parse request: %v", err)) return } // Successful extraction of Body JSON as long as the rawtx is not empty // string we should return it. if req.Rawtx == "" { writeHTMLBadRequest(w, fmt.Sprintf("rawtx cannot be an empty string.")) return } ctx := context.WithValue(r.Context(), ctxRawHexTx, req.Rawtx) next.ServeHTTP(w, r.WithContext(ctx)) }) }
go
func PostBroadcastTxCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req apitypes.InsightRawTx body, err := ioutil.ReadAll(r.Body) r.Body.Close() if err != nil { writeHTMLBadRequest(w, fmt.Sprintf("Error reading JSON message: %v", err)) return } err = json.Unmarshal(body, &req) if err != nil { writeHTMLBadRequest(w, fmt.Sprintf("Failed to parse request: %v", err)) return } // Successful extraction of Body JSON as long as the rawtx is not empty // string we should return it. if req.Rawtx == "" { writeHTMLBadRequest(w, fmt.Sprintf("rawtx cannot be an empty string.")) return } ctx := context.WithValue(r.Context(), ctxRawHexTx, req.Rawtx) next.ServeHTTP(w, r.WithContext(ctx)) }) }
[ "func", "PostBroadcastTxCtx", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "var", "req", "apitypes", ".", "InsightRawTx", "\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ".", "Body", ")", "\n", "r", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "writeHTMLBadRequest", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "writeHTMLBadRequest", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n\n", "// Successful extraction of Body JSON as long as the rawtx is not empty", "// string we should return it.", "if", "req", ".", "Rawtx", "==", "\"", "\"", "{", "writeHTMLBadRequest", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ")", ")", "\n", "return", "\n", "}", "\n\n", "ctx", ":=", "context", ".", "WithValue", "(", "r", ".", "Context", "(", ")", ",", "ctxRawHexTx", ",", "req", ".", "Rawtx", ")", "\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ".", "WithContext", "(", "ctx", ")", ")", "\n", "}", ")", "\n", "}" ]
// PostBroadcastTxCtx is middleware that checks for parameters given in POST // request body of the broadcast transaction endpoint.
[ "PostBroadcastTxCtx", "is", "middleware", "that", "checks", "for", "parameters", "given", "in", "POST", "request", "body", "of", "the", "broadcast", "transaction", "endpoint", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L182-L208
142,120
decred/dcrdata
middleware/apimiddleware.go
GetTxIDCtx
func GetTxIDCtx(r *http.Request) (*chainhash.Hash, error) { hashStr, ok := r.Context().Value(ctxTxHash).(string) if !ok { apiLog.Trace("txid not set") return nil, fmt.Errorf("txid not set") } hash, err := chainhash.NewHashFromStr(hashStr) if err != nil { apiLog.Trace("invalid hash '%s': %v", hashStr, err) return nil, fmt.Errorf("invalid hash '%s': %v", hashStr, err) } return hash, nil }
go
func GetTxIDCtx(r *http.Request) (*chainhash.Hash, error) { hashStr, ok := r.Context().Value(ctxTxHash).(string) if !ok { apiLog.Trace("txid not set") return nil, fmt.Errorf("txid not set") } hash, err := chainhash.NewHashFromStr(hashStr) if err != nil { apiLog.Trace("invalid hash '%s': %v", hashStr, err) return nil, fmt.Errorf("invalid hash '%s': %v", hashStr, err) } return hash, nil }
[ "func", "GetTxIDCtx", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "hashStr", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxTxHash", ")", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Trace", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "hash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "hashStr", ")", "\n", "if", "err", "!=", "nil", "{", "apiLog", ".", "Trace", "(", "\"", "\"", ",", "hashStr", ",", "err", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hashStr", ",", "err", ")", "\n", "}", "\n", "return", "hash", ",", "nil", "\n", "}" ]
// GetTxIDCtx retrieves the ctxTxHash data from the request context. If not set, // the return value is an empty string.
[ "GetTxIDCtx", "retrieves", "the", "ctxTxHash", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "an", "empty", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L212-L225
142,121
decred/dcrdata
middleware/apimiddleware.go
GetTxnsCtx
func GetTxnsCtx(r *http.Request) ([]*chainhash.Hash, error) { hashStrs, ok := r.Context().Value(ctxTxns).([]string) if !ok || len(hashStrs) == 0 { apiLog.Trace("ctxTxns not set") return nil, fmt.Errorf("ctxTxns not set") } var hashes []*chainhash.Hash for _, hashStr := range hashStrs { hash, err := chainhash.NewHashFromStr(hashStr) if err != nil { apiLog.Trace("invalid hash '%s': %v", hashStr, err) return nil, fmt.Errorf("invalid hash '%s': %v", hashStr, err) } hashes = append(hashes, hash) } return hashes, nil }
go
func GetTxnsCtx(r *http.Request) ([]*chainhash.Hash, error) { hashStrs, ok := r.Context().Value(ctxTxns).([]string) if !ok || len(hashStrs) == 0 { apiLog.Trace("ctxTxns not set") return nil, fmt.Errorf("ctxTxns not set") } var hashes []*chainhash.Hash for _, hashStr := range hashStrs { hash, err := chainhash.NewHashFromStr(hashStr) if err != nil { apiLog.Trace("invalid hash '%s': %v", hashStr, err) return nil, fmt.Errorf("invalid hash '%s': %v", hashStr, err) } hashes = append(hashes, hash) } return hashes, nil }
[ "func", "GetTxnsCtx", "(", "r", "*", "http", ".", "Request", ")", "(", "[", "]", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "hashStrs", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxTxns", ")", ".", "(", "[", "]", "string", ")", "\n", "if", "!", "ok", "||", "len", "(", "hashStrs", ")", "==", "0", "{", "apiLog", ".", "Trace", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "hashes", "[", "]", "*", "chainhash", ".", "Hash", "\n", "for", "_", ",", "hashStr", ":=", "range", "hashStrs", "{", "hash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "hashStr", ")", "\n", "if", "err", "!=", "nil", "{", "apiLog", ".", "Trace", "(", "\"", "\"", ",", "hashStr", ",", "err", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hashStr", ",", "err", ")", "\n", "}", "\n", "hashes", "=", "append", "(", "hashes", ",", "hash", ")", "\n", "}", "\n\n", "return", "hashes", ",", "nil", "\n", "}" ]
// GetTxnsCtx retrieves the ctxTxns data from the request context. If not set, // the return value is an empty string slice.
[ "GetTxnsCtx", "retrieves", "the", "ctxTxns", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "an", "empty", "string", "slice", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L229-L247
142,122
decred/dcrdata
middleware/apimiddleware.go
PostTxnsCtx
func PostTxnsCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { req := apitypes.Txns{} body, err := ioutil.ReadAll(r.Body) r.Body.Close() if err != nil { apiLog.Debugf("No/invalid txns: %v", err) http.Error(w, "error reading JSON message", http.StatusBadRequest) return } err = json.Unmarshal(body, &req) if err != nil { apiLog.Debugf("failed to unmarshal JSON request to apitypes.Txns: %v", err) http.Error(w, "failed to unmarshal JSON request", http.StatusBadRequest) return } // Successful extraction of body JSON ctx := context.WithValue(r.Context(), ctxTxns, req.Transactions) next.ServeHTTP(w, r.WithContext(ctx)) }) }
go
func PostTxnsCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { req := apitypes.Txns{} body, err := ioutil.ReadAll(r.Body) r.Body.Close() if err != nil { apiLog.Debugf("No/invalid txns: %v", err) http.Error(w, "error reading JSON message", http.StatusBadRequest) return } err = json.Unmarshal(body, &req) if err != nil { apiLog.Debugf("failed to unmarshal JSON request to apitypes.Txns: %v", err) http.Error(w, "failed to unmarshal JSON request", http.StatusBadRequest) return } // Successful extraction of body JSON ctx := context.WithValue(r.Context(), ctxTxns, req.Transactions) next.ServeHTTP(w, r.WithContext(ctx)) }) }
[ "func", "PostTxnsCtx", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "req", ":=", "apitypes", ".", "Txns", "{", "}", "\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ".", "Body", ")", "\n", "r", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "apiLog", ".", "Debugf", "(", "\"", "\"", ",", "err", ")", "\n", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "apiLog", ".", "Debugf", "(", "\"", "\"", ",", "err", ")", "\n", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n", "// Successful extraction of body JSON", "ctx", ":=", "context", ".", "WithValue", "(", "r", ".", "Context", "(", ")", ",", "ctxTxns", ",", "req", ".", "Transactions", ")", "\n\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ".", "WithContext", "(", "ctx", ")", ")", "\n", "}", ")", "\n", "}" ]
// PostTxnsCtx extract transaction IDs from the POST body
[ "PostTxnsCtx", "extract", "transaction", "IDs", "from", "the", "POST", "body" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L257-L278
142,123
decred/dcrdata
middleware/apimiddleware.go
ValidateTxnsPostCtx
func ValidateTxnsPostCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { contentLengthString := r.Header.Get("Content-Length") contentLength, err := strconv.Atoi(contentLengthString) if err != nil { http.Error(w, "Unable to parse Content-Length", http.StatusBadRequest) return } // Broadcast Tx has the largest possible body. maxPayload := 1 << 22 if contentLength > maxPayload { http.Error(w, fmt.Sprintf("Maximum Content-Length is %d", maxPayload), http.StatusBadRequest) return } next.ServeHTTP(w, r) }) }
go
func ValidateTxnsPostCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { contentLengthString := r.Header.Get("Content-Length") contentLength, err := strconv.Atoi(contentLengthString) if err != nil { http.Error(w, "Unable to parse Content-Length", http.StatusBadRequest) return } // Broadcast Tx has the largest possible body. maxPayload := 1 << 22 if contentLength > maxPayload { http.Error(w, fmt.Sprintf("Maximum Content-Length is %d", maxPayload), http.StatusBadRequest) return } next.ServeHTTP(w, r) }) }
[ "func", "ValidateTxnsPostCtx", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "contentLengthString", ":=", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "contentLength", ",", "err", ":=", "strconv", ".", "Atoi", "(", "contentLengthString", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n", "// Broadcast Tx has the largest possible body.", "maxPayload", ":=", "1", "<<", "22", "\n", "if", "contentLength", ">", "maxPayload", "{", "http", ".", "Error", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "maxPayload", ")", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", ")", "\n", "}" ]
// ValidateTxnsPostCtx will confirm Post content length is valid.
[ "ValidateTxnsPostCtx", "will", "confirm", "Post", "content", "length", "is", "valid", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L281-L297
142,124
decred/dcrdata
middleware/apimiddleware.go
GetBlockHashCtx
func GetBlockHashCtx(r *http.Request) (string, error) { hash, ok := r.Context().Value(ctxBlockHash).(string) if !ok { apiLog.Trace("block hash not set") return "", fmt.Errorf("block hash not set") } if _, err := chainhash.NewHashFromStr(hash); err != nil { apiLog.Trace("invalid hash '%s': %v", hash, err) return "", fmt.Errorf("invalid hash '%s': %v", hash, err) } return hash, nil }
go
func GetBlockHashCtx(r *http.Request) (string, error) { hash, ok := r.Context().Value(ctxBlockHash).(string) if !ok { apiLog.Trace("block hash not set") return "", fmt.Errorf("block hash not set") } if _, err := chainhash.NewHashFromStr(hash); err != nil { apiLog.Trace("invalid hash '%s': %v", hash, err) return "", fmt.Errorf("invalid hash '%s': %v", hash, err) } return hash, nil }
[ "func", "GetBlockHashCtx", "(", "r", "*", "http", ".", "Request", ")", "(", "string", ",", "error", ")", "{", "hash", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxBlockHash", ")", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Trace", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "hash", ")", ";", "err", "!=", "nil", "{", "apiLog", ".", "Trace", "(", "\"", "\"", ",", "hash", ",", "err", ")", "\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hash", ",", "err", ")", "\n", "}", "\n\n", "return", "hash", ",", "nil", "\n", "}" ]
// GetBlockHashCtx retrieves the ctxBlockHash data from the request context. If // not set, the return value is an empty string.
[ "GetBlockHashCtx", "retrieves", "the", "ctxBlockHash", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "an", "empty", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L301-L313
142,125
decred/dcrdata
middleware/apimiddleware.go
GetAddressCtx
func GetAddressCtx(r *http.Request, activeNetParams *chaincfg.Params, maxAddrs int) ([]string, error) { addressStr, ok := r.Context().Value(CtxAddress).(string) if !ok || len(addressStr) == 0 { apiLog.Trace("address not set") return nil, fmt.Errorf("address not set") } addressStrs := strings.Split(addressStr, ",") if len(addressStrs) > maxAddrs { return nil, fmt.Errorf("maximum of %d addresses allowed", maxAddrs) } strInSlice := func(sl []string, s string) bool { for i := range sl { if sl[i] == s { return true } } return false } var addrStrs []string for _, addrStr := range addressStrs { address, err := dcrutil.DecodeAddress(addrStr) if err != nil { return nil, fmt.Errorf("invalid address '%v': %v", addrStr, err) } if !address.IsForNet(activeNetParams) { return nil, fmt.Errorf("%v is invalid for this network", addrStr) } if strInSlice(addrStrs, addrStr) { continue } addrStrs = append(addrStrs, addrStr) } return addrStrs, nil }
go
func GetAddressCtx(r *http.Request, activeNetParams *chaincfg.Params, maxAddrs int) ([]string, error) { addressStr, ok := r.Context().Value(CtxAddress).(string) if !ok || len(addressStr) == 0 { apiLog.Trace("address not set") return nil, fmt.Errorf("address not set") } addressStrs := strings.Split(addressStr, ",") if len(addressStrs) > maxAddrs { return nil, fmt.Errorf("maximum of %d addresses allowed", maxAddrs) } strInSlice := func(sl []string, s string) bool { for i := range sl { if sl[i] == s { return true } } return false } var addrStrs []string for _, addrStr := range addressStrs { address, err := dcrutil.DecodeAddress(addrStr) if err != nil { return nil, fmt.Errorf("invalid address '%v': %v", addrStr, err) } if !address.IsForNet(activeNetParams) { return nil, fmt.Errorf("%v is invalid for this network", addrStr) } if strInSlice(addrStrs, addrStr) { continue } addrStrs = append(addrStrs, addrStr) } return addrStrs, nil }
[ "func", "GetAddressCtx", "(", "r", "*", "http", ".", "Request", ",", "activeNetParams", "*", "chaincfg", ".", "Params", ",", "maxAddrs", "int", ")", "(", "[", "]", "string", ",", "error", ")", "{", "addressStr", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "CtxAddress", ")", ".", "(", "string", ")", "\n", "if", "!", "ok", "||", "len", "(", "addressStr", ")", "==", "0", "{", "apiLog", ".", "Trace", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "addressStrs", ":=", "strings", ".", "Split", "(", "addressStr", ",", "\"", "\"", ")", "\n", "if", "len", "(", "addressStrs", ")", ">", "maxAddrs", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "maxAddrs", ")", "\n", "}", "\n\n", "strInSlice", ":=", "func", "(", "sl", "[", "]", "string", ",", "s", "string", ")", "bool", "{", "for", "i", ":=", "range", "sl", "{", "if", "sl", "[", "i", "]", "==", "s", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}", "\n\n", "var", "addrStrs", "[", "]", "string", "\n", "for", "_", ",", "addrStr", ":=", "range", "addressStrs", "{", "address", ",", "err", ":=", "dcrutil", ".", "DecodeAddress", "(", "addrStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "addrStr", ",", "err", ")", "\n", "}", "\n", "if", "!", "address", ".", "IsForNet", "(", "activeNetParams", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "addrStr", ")", "\n", "}", "\n", "if", "strInSlice", "(", "addrStrs", ",", "addrStr", ")", "{", "continue", "\n", "}", "\n", "addrStrs", "=", "append", "(", "addrStrs", ",", "addrStr", ")", "\n", "}", "\n", "return", "addrStrs", ",", "nil", "\n", "}" ]
// GetAddressCtx retrieves the CtxAddress data from the request context. If not // set, the return value is an empty string. The CtxAddress string data may be a // comma-separated list of addresses, subject to the provided maximum number of // addresses allowed. Duplicate addresses are removed, but the limit is enforced // prior to removal of duplicates.
[ "GetAddressCtx", "retrieves", "the", "CtxAddress", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "an", "empty", "string", ".", "The", "CtxAddress", "string", "data", "may", "be", "a", "comma", "-", "separated", "list", "of", "addresses", "subject", "to", "the", "provided", "maximum", "number", "of", "addresses", "allowed", ".", "Duplicate", "addresses", "are", "removed", "but", "the", "limit", "is", "enforced", "prior", "to", "removal", "of", "duplicates", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L320-L357
142,126
decred/dcrdata
middleware/apimiddleware.go
GetChartTypeCtx
func GetChartTypeCtx(r *http.Request) string { chartType, ok := r.Context().Value(ctxChartType).(string) if !ok { apiLog.Trace("chart type not set") return "" } return chartType }
go
func GetChartTypeCtx(r *http.Request) string { chartType, ok := r.Context().Value(ctxChartType).(string) if !ok { apiLog.Trace("chart type not set") return "" } return chartType }
[ "func", "GetChartTypeCtx", "(", "r", "*", "http", ".", "Request", ")", "string", "{", "chartType", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxChartType", ")", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Trace", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", "\n", "}", "\n", "return", "chartType", "\n", "}" ]
// GetChartTypeCtx retrieves the ctxChart data from the request context. // If not set, the return value is an empty string.
[ "GetChartTypeCtx", "retrieves", "the", "ctxChart", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "an", "empty", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L361-L368
142,127
decred/dcrdata
middleware/apimiddleware.go
GetChartGroupingCtx
func GetChartGroupingCtx(r *http.Request) string { chartType, ok := r.Context().Value(ctxChartGrouping).(string) if !ok { apiLog.Trace("chart grouping not set") return "" } return chartType }
go
func GetChartGroupingCtx(r *http.Request) string { chartType, ok := r.Context().Value(ctxChartGrouping).(string) if !ok { apiLog.Trace("chart grouping not set") return "" } return chartType }
[ "func", "GetChartGroupingCtx", "(", "r", "*", "http", ".", "Request", ")", "string", "{", "chartType", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxChartGrouping", ")", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Trace", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", "\n", "}", "\n", "return", "chartType", "\n", "}" ]
// GetChartGroupingCtx retrieves the ctxChart data from the request context. // If not set, the return value is an empty string.
[ "GetChartGroupingCtx", "retrieves", "the", "ctxChart", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "an", "empty", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L372-L379
142,128
decred/dcrdata
middleware/apimiddleware.go
GetBlockDateCtx
func GetBlockDateCtx(r *http.Request) string { blockDate, _ := r.Context().Value(CtxBlockDate).(string) return blockDate }
go
func GetBlockDateCtx(r *http.Request) string { blockDate, _ := r.Context().Value(CtxBlockDate).(string) return blockDate }
[ "func", "GetBlockDateCtx", "(", "r", "*", "http", ".", "Request", ")", "string", "{", "blockDate", ",", "_", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "CtxBlockDate", ")", ".", "(", "string", ")", "\n", "return", "blockDate", "\n", "}" ]
// GetBlockDateCtx retrieves the ctxBlockDate data from the request context. If // not set, the return value is an empty string.
[ "GetBlockDateCtx", "retrieves", "the", "ctxBlockDate", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "an", "empty", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L416-L419
142,129
decred/dcrdata
middleware/apimiddleware.go
GetBlockIndexCtx
func GetBlockIndexCtx(r *http.Request) int { idx, ok := r.Context().Value(ctxBlockIndex).(int) if !ok { apiLog.Warn("block index not set or is not an int") return -1 } return idx }
go
func GetBlockIndexCtx(r *http.Request) int { idx, ok := r.Context().Value(ctxBlockIndex).(int) if !ok { apiLog.Warn("block index not set or is not an int") return -1 } return idx }
[ "func", "GetBlockIndexCtx", "(", "r", "*", "http", ".", "Request", ")", "int", "{", "idx", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxBlockIndex", ")", ".", "(", "int", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "-", "1", "\n", "}", "\n", "return", "idx", "\n", "}" ]
// GetBlockIndexCtx retrieves the ctxBlockIndex data from the request context. // If not set, the return -1.
[ "GetBlockIndexCtx", "retrieves", "the", "ctxBlockIndex", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "-", "1", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L423-L430
142,130
decred/dcrdata
middleware/apimiddleware.go
apiDocs
func apiDocs(mux *chi.Mux) func(next http.Handler) http.Handler { var buf bytes.Buffer json.Indent(&buf, []byte(docgen.JSONRoutesDoc(mux)), "", "\t") docs := buf.String() return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := context.WithValue(r.Context(), ctxAPIDocs, docs) next.ServeHTTP(w, r.WithContext(ctx)) }) } }
go
func apiDocs(mux *chi.Mux) func(next http.Handler) http.Handler { var buf bytes.Buffer json.Indent(&buf, []byte(docgen.JSONRoutesDoc(mux)), "", "\t") docs := buf.String() return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := context.WithValue(r.Context(), ctxAPIDocs, docs) next.ServeHTTP(w, r.WithContext(ctx)) }) } }
[ "func", "apiDocs", "(", "mux", "*", "chi", ".", "Mux", ")", "func", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "json", ".", "Indent", "(", "&", "buf", ",", "[", "]", "byte", "(", "docgen", ".", "JSONRoutesDoc", "(", "mux", ")", ")", ",", "\"", "\"", ",", "\"", "\\t", "\"", ")", "\n", "docs", ":=", "buf", ".", "String", "(", ")", "\n", "return", "func", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "ctx", ":=", "context", ".", "WithValue", "(", "r", ".", "Context", "(", ")", ",", "ctxAPIDocs", ",", "docs", ")", "\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ".", "WithContext", "(", "ctx", ")", ")", "\n", "}", ")", "\n", "}", "\n", "}" ]
// apiDocs generates a middleware with a "docs" in the context containing a map // of the routers handlers, etc.
[ "apiDocs", "generates", "a", "middleware", "with", "a", "docs", "in", "the", "context", "containing", "a", "map", "of", "the", "routers", "handlers", "etc", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L632-L642
142,131
decred/dcrdata
middleware/apimiddleware.go
GetAgendaIdCtx
func GetAgendaIdCtx(r *http.Request) string { agendaId, ok := r.Context().Value(ctxAgendaId).(string) if !ok { apiLog.Error("agendaId not parsed") return "" } return agendaId }
go
func GetAgendaIdCtx(r *http.Request) string { agendaId, ok := r.Context().Value(ctxAgendaId).(string) if !ok { apiLog.Error("agendaId not parsed") return "" } return agendaId }
[ "func", "GetAgendaIdCtx", "(", "r", "*", "http", ".", "Request", ")", "string", "{", "agendaId", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxAgendaId", ")", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", "\n", "}", "\n", "return", "agendaId", "\n", "}" ]
// GetAgendaIdCtx retrieves the ctxAgendaId data from the request context. // If not set, the return value is an empty string.
[ "GetAgendaIdCtx", "retrieves", "the", "ctxAgendaId", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "an", "empty", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L739-L746
142,132
decred/dcrdata
middleware/apimiddleware.go
StatusInfoCtx
func StatusInfoCtx(r *http.Request, source DataSource) context.Context { idx := int64(-1) h, err := source.GetHeight() if h >= 0 && err == nil { idx = h } ctx := context.WithValue(r.Context(), ctxBlockIndex, int(idx)) // Must be int! q := r.FormValue("q") return context.WithValue(ctx, ctxGetStatus, q) }
go
func StatusInfoCtx(r *http.Request, source DataSource) context.Context { idx := int64(-1) h, err := source.GetHeight() if h >= 0 && err == nil { idx = h } ctx := context.WithValue(r.Context(), ctxBlockIndex, int(idx)) // Must be int! q := r.FormValue("q") return context.WithValue(ctx, ctxGetStatus, q) }
[ "func", "StatusInfoCtx", "(", "r", "*", "http", ".", "Request", ",", "source", "DataSource", ")", "context", ".", "Context", "{", "idx", ":=", "int64", "(", "-", "1", ")", "\n", "h", ",", "err", ":=", "source", ".", "GetHeight", "(", ")", "\n", "if", "h", ">=", "0", "&&", "err", "==", "nil", "{", "idx", "=", "h", "\n", "}", "\n", "ctx", ":=", "context", ".", "WithValue", "(", "r", ".", "Context", "(", ")", ",", "ctxBlockIndex", ",", "int", "(", "idx", ")", ")", "// Must be int!", "\n\n", "q", ":=", "r", ".", "FormValue", "(", "\"", "\"", ")", "\n", "return", "context", ".", "WithValue", "(", "ctx", ",", "ctxGetStatus", ",", "q", ")", "\n", "}" ]
// StatusInfoCtx embeds the best block index and the POST form data for // parameter "q" into a request context.
[ "StatusInfoCtx", "embeds", "the", "best", "block", "index", "and", "the", "POST", "form", "data", "for", "parameter", "q", "into", "a", "request", "context", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L762-L772
142,133
decred/dcrdata
middleware/apimiddleware.go
GetBlockHeightCtx
func GetBlockHeightCtx(r *http.Request, source DataSource) (int64, error) { idxI, ok := r.Context().Value(ctxBlockIndex).(int) idx := int64(idxI) if !ok || idx < 0 { hash, err := GetBlockHashCtx(r) if err != nil { return 0, err } idx, err = source.GetBlockHeight(hash) if err != nil { return 0, err } } return idx, nil }
go
func GetBlockHeightCtx(r *http.Request, source DataSource) (int64, error) { idxI, ok := r.Context().Value(ctxBlockIndex).(int) idx := int64(idxI) if !ok || idx < 0 { hash, err := GetBlockHashCtx(r) if err != nil { return 0, err } idx, err = source.GetBlockHeight(hash) if err != nil { return 0, err } } return idx, nil }
[ "func", "GetBlockHeightCtx", "(", "r", "*", "http", ".", "Request", ",", "source", "DataSource", ")", "(", "int64", ",", "error", ")", "{", "idxI", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxBlockIndex", ")", ".", "(", "int", ")", "\n", "idx", ":=", "int64", "(", "idxI", ")", "\n", "if", "!", "ok", "||", "idx", "<", "0", "{", "hash", ",", "err", ":=", "GetBlockHashCtx", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "idx", ",", "err", "=", "source", ".", "GetBlockHeight", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "}", "\n", "return", "idx", ",", "nil", "\n", "}" ]
// GetBlockHeightCtx returns the block height for the block index or hash // specified on the URL path.
[ "GetBlockHeightCtx", "returns", "the", "block", "height", "for", "the", "block", "index", "or", "hash", "specified", "on", "the", "URL", "path", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L818-L832
142,134
decred/dcrdata
middleware/apimiddleware.go
RetrieveExchangeTokenCtx
func RetrieveExchangeTokenCtx(r *http.Request) string { token, ok := r.Context().Value(ctxXcToken).(string) if !ok { apiLog.Error("non-string encountered in exchange token context") return "" } return token }
go
func RetrieveExchangeTokenCtx(r *http.Request) string { token, ok := r.Context().Value(ctxXcToken).(string) if !ok { apiLog.Error("non-string encountered in exchange token context") return "" } return token }
[ "func", "RetrieveExchangeTokenCtx", "(", "r", "*", "http", ".", "Request", ")", "string", "{", "token", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxXcToken", ")", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", "\n", "}", "\n", "return", "token", "\n", "}" ]
// RetrieveExchangeTokenCtx tries to fetch the exchange token from the request // context.
[ "RetrieveExchangeTokenCtx", "tries", "to", "fetch", "the", "exchange", "token", "from", "the", "request", "context", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L856-L863
142,135
decred/dcrdata
middleware/apimiddleware.go
StickWidthContext
func StickWidthContext(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { bin := chi.URLParam(r, "bin") ctx := context.WithValue(r.Context(), ctxStickWidth, bin) next.ServeHTTP(w, r.WithContext(ctx)) }) }
go
func StickWidthContext(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { bin := chi.URLParam(r, "bin") ctx := context.WithValue(r.Context(), ctxStickWidth, bin) next.ServeHTTP(w, r.WithContext(ctx)) }) }
[ "func", "StickWidthContext", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "bin", ":=", "chi", ".", "URLParam", "(", "r", ",", "\"", "\"", ")", "\n", "ctx", ":=", "context", ".", "WithValue", "(", "r", ".", "Context", "(", ")", ",", "ctxStickWidth", ",", "bin", ")", "\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ".", "WithContext", "(", "ctx", ")", ")", "\n", "}", ")", "\n", "}" ]
// ExchangeTokenContext pulls the bin width from the URL.
[ "ExchangeTokenContext", "pulls", "the", "bin", "width", "from", "the", "URL", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L866-L872
142,136
decred/dcrdata
middleware/apimiddleware.go
RetrieveStickWidthCtx
func RetrieveStickWidthCtx(r *http.Request) string { bin, ok := r.Context().Value(ctxStickWidth).(string) if !ok { apiLog.Error("non-string encountered in candlestick width context") return "" } return bin }
go
func RetrieveStickWidthCtx(r *http.Request) string { bin, ok := r.Context().Value(ctxStickWidth).(string) if !ok { apiLog.Error("non-string encountered in candlestick width context") return "" } return bin }
[ "func", "RetrieveStickWidthCtx", "(", "r", "*", "http", ".", "Request", ")", "string", "{", "bin", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxStickWidth", ")", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "apiLog", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", "\n", "}", "\n", "return", "bin", "\n", "}" ]
// RetrieveStickWidthCtx tries to fetch the candlestick width from the request // context.
[ "RetrieveStickWidthCtx", "tries", "to", "fetch", "the", "candlestick", "width", "from", "the", "request", "context", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L876-L883
142,137
decred/dcrdata
dcrrates/rateserver/tls.go
openRPCKeyPair
func openRPCKeyPair(cfg *config) (credentials.TransportCredentials, error) { // Generate a new keypair when the key is missing. _, e := os.Stat(cfg.KeyPath) keyExists := !os.IsNotExist(e) if !keyExists { cert, err := generateRPCKeyPair(cfg.CertificatePath, cfg.KeyPath, cfg.AltDNSNames, certWriter{}) if err != nil { return nil, fmt.Errorf("Unable to generate TLS Certificate: %v", err) } // The certificate generated by generateRPCKeyPair has a nil Leaf. The x509 // certificate must be parsed from the raw bytes to access DNSNames and // IPAddresses. if len(cert.Certificate) == 0 { return nil, fmt.Errorf("No raw certificate data found") } x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) if err != nil { return nil, fmt.Errorf("Could not parse x509 certificate: %v", err) } hosts := x509Cert.DNSNames for _, ip := range x509Cert.IPAddresses { hosts = append(hosts, ip.String()) } if len(hosts) > 0 { log.Infof("TLS certificate created for hosts %s", strings.Join(hosts, ", ")) } return credentials.NewServerTLSFromCert(&cert), nil } cert, err := tls.LoadX509KeyPair(cfg.CertificatePath, cfg.KeyPath) if err != nil { return nil, err } return credentials.NewServerTLSFromCert(&cert), nil }
go
func openRPCKeyPair(cfg *config) (credentials.TransportCredentials, error) { // Generate a new keypair when the key is missing. _, e := os.Stat(cfg.KeyPath) keyExists := !os.IsNotExist(e) if !keyExists { cert, err := generateRPCKeyPair(cfg.CertificatePath, cfg.KeyPath, cfg.AltDNSNames, certWriter{}) if err != nil { return nil, fmt.Errorf("Unable to generate TLS Certificate: %v", err) } // The certificate generated by generateRPCKeyPair has a nil Leaf. The x509 // certificate must be parsed from the raw bytes to access DNSNames and // IPAddresses. if len(cert.Certificate) == 0 { return nil, fmt.Errorf("No raw certificate data found") } x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) if err != nil { return nil, fmt.Errorf("Could not parse x509 certificate: %v", err) } hosts := x509Cert.DNSNames for _, ip := range x509Cert.IPAddresses { hosts = append(hosts, ip.String()) } if len(hosts) > 0 { log.Infof("TLS certificate created for hosts %s", strings.Join(hosts, ", ")) } return credentials.NewServerTLSFromCert(&cert), nil } cert, err := tls.LoadX509KeyPair(cfg.CertificatePath, cfg.KeyPath) if err != nil { return nil, err } return credentials.NewServerTLSFromCert(&cert), nil }
[ "func", "openRPCKeyPair", "(", "cfg", "*", "config", ")", "(", "credentials", ".", "TransportCredentials", ",", "error", ")", "{", "// Generate a new keypair when the key is missing.", "_", ",", "e", ":=", "os", ".", "Stat", "(", "cfg", ".", "KeyPath", ")", "\n", "keyExists", ":=", "!", "os", ".", "IsNotExist", "(", "e", ")", "\n", "if", "!", "keyExists", "{", "cert", ",", "err", ":=", "generateRPCKeyPair", "(", "cfg", ".", "CertificatePath", ",", "cfg", ".", "KeyPath", ",", "cfg", ".", "AltDNSNames", ",", "certWriter", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// The certificate generated by generateRPCKeyPair has a nil Leaf. The x509", "// certificate must be parsed from the raw bytes to access DNSNames and", "// IPAddresses.", "if", "len", "(", "cert", ".", "Certificate", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "x509Cert", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "cert", ".", "Certificate", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "hosts", ":=", "x509Cert", ".", "DNSNames", "\n", "for", "_", ",", "ip", ":=", "range", "x509Cert", ".", "IPAddresses", "{", "hosts", "=", "append", "(", "hosts", ",", "ip", ".", "String", "(", ")", ")", "\n", "}", "\n", "if", "len", "(", "hosts", ")", ">", "0", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "hosts", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "credentials", ".", "NewServerTLSFromCert", "(", "&", "cert", ")", ",", "nil", "\n", "}", "\n\n", "cert", ",", "err", ":=", "tls", ".", "LoadX509KeyPair", "(", "cfg", ".", "CertificatePath", ",", "cfg", ".", "KeyPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "credentials", ".", "NewServerTLSFromCert", "(", "&", "cert", ")", ",", "nil", "\n", "}" ]
// openRPCKeyPair creates or loads the RPC TLS keypair specified by the // application config.
[ "openRPCKeyPair", "creates", "or", "loads", "the", "RPC", "TLS", "keypair", "specified", "by", "the", "application", "config", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/dcrrates/rateserver/tls.go#L23-L58
142,138
decred/dcrdata
pubsub/psclient/client.go
Subscribe
func (c *Client) Subscribe(event string) (*pstypes.WebSocketMessage, error) { // Validate the event type. _, _, ok := pstypes.ValidateSubscription(event) if !ok { return nil, fmt.Errorf("invalid subscription %s", event) } // Send the subscribe message. msg := newSubscribeMsg(event) _ = c.SetWriteDeadline(time.Now().Add(c.WriteTimeout)) _, err := c.Write([]byte(msg)) if err != nil { return nil, fmt.Errorf("failed to send subscribe message: %v", err) } // Read the response. return c.ReceiveMsg() }
go
func (c *Client) Subscribe(event string) (*pstypes.WebSocketMessage, error) { // Validate the event type. _, _, ok := pstypes.ValidateSubscription(event) if !ok { return nil, fmt.Errorf("invalid subscription %s", event) } // Send the subscribe message. msg := newSubscribeMsg(event) _ = c.SetWriteDeadline(time.Now().Add(c.WriteTimeout)) _, err := c.Write([]byte(msg)) if err != nil { return nil, fmt.Errorf("failed to send subscribe message: %v", err) } // Read the response. return c.ReceiveMsg() }
[ "func", "(", "c", "*", "Client", ")", "Subscribe", "(", "event", "string", ")", "(", "*", "pstypes", ".", "WebSocketMessage", ",", "error", ")", "{", "// Validate the event type.", "_", ",", "_", ",", "ok", ":=", "pstypes", ".", "ValidateSubscription", "(", "event", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "event", ")", "\n", "}", "\n\n", "// Send the subscribe message.", "msg", ":=", "newSubscribeMsg", "(", "event", ")", "\n", "_", "=", "c", ".", "SetWriteDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "c", ".", "WriteTimeout", ")", ")", "\n", "_", ",", "err", ":=", "c", ".", "Write", "(", "[", "]", "byte", "(", "msg", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Read the response.", "return", "c", ".", "ReceiveMsg", "(", ")", "\n", "}" ]
// Subscribe sends a subscribe type WebSocketMessage for the given event name // after validating it. The response is returned.
[ "Subscribe", "sends", "a", "subscribe", "type", "WebSocketMessage", "for", "the", "given", "event", "name", "after", "validating", "it", ".", "The", "response", "is", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/psclient/client.go#L52-L69
142,139
decred/dcrdata
pubsub/psclient/client.go
ReceiveMsgTimeout
func (c *Client) ReceiveMsgTimeout(timeout time.Duration) (*pstypes.WebSocketMessage, error) { _ = c.SetReadDeadline(time.Now().Add(timeout)) msg := new(pstypes.WebSocketMessage) if err := websocket.JSON.Receive(c.Conn, &msg); err != nil { return nil, err } return msg, nil }
go
func (c *Client) ReceiveMsgTimeout(timeout time.Duration) (*pstypes.WebSocketMessage, error) { _ = c.SetReadDeadline(time.Now().Add(timeout)) msg := new(pstypes.WebSocketMessage) if err := websocket.JSON.Receive(c.Conn, &msg); err != nil { return nil, err } return msg, nil }
[ "func", "(", "c", "*", "Client", ")", "ReceiveMsgTimeout", "(", "timeout", "time", ".", "Duration", ")", "(", "*", "pstypes", ".", "WebSocketMessage", ",", "error", ")", "{", "_", "=", "c", ".", "SetReadDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "timeout", ")", ")", "\n", "msg", ":=", "new", "(", "pstypes", ".", "WebSocketMessage", ")", "\n", "if", "err", ":=", "websocket", ".", "JSON", ".", "Receive", "(", "c", ".", "Conn", ",", "&", "msg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "msg", ",", "nil", "\n", "}" ]
// ReceiveMsgTimeout waits for the specified time Duration for a message, // returned decoded into a WebSocketMessage.
[ "ReceiveMsgTimeout", "waits", "for", "the", "specified", "time", "Duration", "for", "a", "message", "returned", "decoded", "into", "a", "WebSocketMessage", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/psclient/client.go#L94-L101
142,140
decred/dcrdata
pubsub/psclient/client.go
ReceiveMsg
func (c *Client) ReceiveMsg() (*pstypes.WebSocketMessage, error) { return c.ReceiveMsgTimeout(c.ReadTimeout) }
go
func (c *Client) ReceiveMsg() (*pstypes.WebSocketMessage, error) { return c.ReceiveMsgTimeout(c.ReadTimeout) }
[ "func", "(", "c", "*", "Client", ")", "ReceiveMsg", "(", ")", "(", "*", "pstypes", ".", "WebSocketMessage", ",", "error", ")", "{", "return", "c", ".", "ReceiveMsgTimeout", "(", "c", ".", "ReadTimeout", ")", "\n", "}" ]
// ReceiveMsg waits for a message, returned decoded into a WebSocketMessage. The // Client's configured ReadTimeout is used.
[ "ReceiveMsg", "waits", "for", "a", "message", "returned", "decoded", "into", "a", "WebSocketMessage", ".", "The", "Client", "s", "configured", "ReadTimeout", "is", "used", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/psclient/client.go#L105-L107
142,141
decred/dcrdata
pubsub/psclient/client.go
ReceiveRaw
func (c *Client) ReceiveRaw() (message string, err error) { _ = c.SetReadDeadline(time.Now().Add(c.ReadTimeout)) err = websocket.Message.Receive(c.Conn, &message) return }
go
func (c *Client) ReceiveRaw() (message string, err error) { _ = c.SetReadDeadline(time.Now().Add(c.ReadTimeout)) err = websocket.Message.Receive(c.Conn, &message) return }
[ "func", "(", "c", "*", "Client", ")", "ReceiveRaw", "(", ")", "(", "message", "string", ",", "err", "error", ")", "{", "_", "=", "c", ".", "SetReadDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "c", ".", "ReadTimeout", ")", ")", "\n", "err", "=", "websocket", ".", "Message", ".", "Receive", "(", "c", ".", "Conn", ",", "&", "message", ")", "\n", "return", "\n", "}" ]
// ReceiveRaw for a message, returned undecoded as a string.
[ "ReceiveRaw", "for", "a", "message", "returned", "undecoded", "as", "a", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/psclient/client.go#L110-L114
142,142
decred/dcrdata
pubsub/psclient/client.go
DecodeMsgString
func DecodeMsgString(msg *pstypes.WebSocketMessage) (string, error) { s, err := DecodeMsg(msg) if err != nil { return "", err } str, ok := s.(string) if !ok { return "", fmt.Errorf("content of Message was not of type string") } return str, nil }
go
func DecodeMsgString(msg *pstypes.WebSocketMessage) (string, error) { s, err := DecodeMsg(msg) if err != nil { return "", err } str, ok := s.(string) if !ok { return "", fmt.Errorf("content of Message was not of type string") } return str, nil }
[ "func", "DecodeMsgString", "(", "msg", "*", "pstypes", ".", "WebSocketMessage", ")", "(", "string", ",", "error", ")", "{", "s", ",", "err", ":=", "DecodeMsg", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "str", ",", "ok", ":=", "s", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "str", ",", "nil", "\n", "}" ]
// DecodeMsgString attempts to decode the Message content of the given // WebSocketMessage as a string.
[ "DecodeMsgString", "attempts", "to", "decode", "the", "Message", "content", "of", "the", "given", "WebSocketMessage", "as", "a", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/psclient/client.go#L151-L161
142,143
decred/dcrdata
rpcutils/prefetcher.go
Stop
func (p *BlockPrefetchClient) Stop() { p.Lock() close(p.retargetChan) p.Unlock() }
go
func (p *BlockPrefetchClient) Stop() { p.Lock() close(p.retargetChan) p.Unlock() }
[ "func", "(", "p", "*", "BlockPrefetchClient", ")", "Stop", "(", ")", "{", "p", ".", "Lock", "(", ")", "\n", "close", "(", "p", ".", "retargetChan", ")", "\n", "p", ".", "Unlock", "(", ")", "\n", "}" ]
// Stop shuts down the fetcher goroutine. The BlockPrefetchClient may not be // used after this.
[ "Stop", "shuts", "down", "the", "fetcher", "goroutine", ".", "The", "BlockPrefetchClient", "may", "not", "be", "used", "after", "this", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L77-L81
142,144
decred/dcrdata
rpcutils/prefetcher.go
Hits
func (p *BlockPrefetchClient) Hits() uint64 { p.Lock() defer p.Unlock() return p.hits }
go
func (p *BlockPrefetchClient) Hits() uint64 { p.Lock() defer p.Unlock() return p.hits }
[ "func", "(", "p", "*", "BlockPrefetchClient", ")", "Hits", "(", ")", "uint64", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n", "return", "p", ".", "hits", "\n", "}" ]
// Hits safely returns the number of prefetch hits.
[ "Hits", "safely", "returns", "the", "number", "of", "prefetch", "hits", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L84-L88
142,145
decred/dcrdata
rpcutils/prefetcher.go
Misses
func (p *BlockPrefetchClient) Misses() uint64 { p.Lock() defer p.Unlock() return p.misses }
go
func (p *BlockPrefetchClient) Misses() uint64 { p.Lock() defer p.Unlock() return p.misses }
[ "func", "(", "p", "*", "BlockPrefetchClient", ")", "Misses", "(", ")", "uint64", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n", "return", "p", ".", "misses", "\n", "}" ]
// Misses safely returns the number of prefetch misses.
[ "Misses", "safely", "returns", "the", "number", "of", "prefetch", "misses", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L91-L95
142,146
decred/dcrdata
rpcutils/prefetcher.go
GetBestBlock
func (p *BlockPrefetchClient) GetBestBlock() (*chainhash.Hash, int64, error) { return p.f.GetBestBlock() }
go
func (p *BlockPrefetchClient) GetBestBlock() (*chainhash.Hash, int64, error) { return p.f.GetBestBlock() }
[ "func", "(", "p", "*", "BlockPrefetchClient", ")", "GetBestBlock", "(", ")", "(", "*", "chainhash", ".", "Hash", ",", "int64", ",", "error", ")", "{", "return", "p", ".", "f", ".", "GetBestBlock", "(", ")", "\n", "}" ]
// GetBestBlock is a passthrough to the client. It does not retarget the // prefetch range since it does not request the actual block, just the hash and // height of the best block.
[ "GetBestBlock", "is", "a", "passthrough", "to", "the", "client", ".", "It", "does", "not", "retarget", "the", "prefetch", "range", "since", "it", "does", "not", "request", "the", "actual", "block", "just", "the", "hash", "and", "height", "of", "the", "best", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L100-L102
142,147
decred/dcrdata
rpcutils/prefetcher.go
GetBlockData
func (p *BlockPrefetchClient) GetBlockData(hash *chainhash.Hash) (*wire.MsgBlock, *dcrjson.GetBlockHeaderVerboseResult, error) { p.Lock() retargetAndUnlock := func(nextHash string) { p.retarget(nextHash) p.Unlock() } // If the block is already fetched, and the current block, return it. Do not // retarget. if p.current.hash == *hash /*p.haveBlockHash(*hash)*/ { p.hits++ // Return the requested block. defer p.Unlock() return p.current.msgBlock, p.current.headerResult, nil } // If the block is already fetched, and next, return it and retarget with a // new range starting at this block's height. if p.next.hash == *hash /*p.haveBlockHash(*hash)*/ { // Grab the result before retarget() changes p.next (via fetcher -> // RetrieveAndStoreNext -> storeNext). msgBlock, headerResult := p.next.msgBlock, p.next.headerResult go retargetAndUnlock(p.next.headerResult.NextHash) p.hits++ // Return the requested block. return msgBlock, headerResult, nil } p.misses++ // Immediately retrieve msgBlock and header verbose result while fetcher is // blocked by the Mutex. msgBlock, headerResult, _, err := p.retrieveBlockAndHeaderResult(hash) if err != nil { p.Unlock() return nil, nil, err } // Leaving the mutex locked, fire off a goroutine to retarget to the next // block. The fetcher goroutine and other locking methods will stay blocked // until the mutex unlocks, but the msgBlock can be returned right away. go retargetAndUnlock(headerResult.NextHash) return msgBlock, headerResult, err }
go
func (p *BlockPrefetchClient) GetBlockData(hash *chainhash.Hash) (*wire.MsgBlock, *dcrjson.GetBlockHeaderVerboseResult, error) { p.Lock() retargetAndUnlock := func(nextHash string) { p.retarget(nextHash) p.Unlock() } // If the block is already fetched, and the current block, return it. Do not // retarget. if p.current.hash == *hash /*p.haveBlockHash(*hash)*/ { p.hits++ // Return the requested block. defer p.Unlock() return p.current.msgBlock, p.current.headerResult, nil } // If the block is already fetched, and next, return it and retarget with a // new range starting at this block's height. if p.next.hash == *hash /*p.haveBlockHash(*hash)*/ { // Grab the result before retarget() changes p.next (via fetcher -> // RetrieveAndStoreNext -> storeNext). msgBlock, headerResult := p.next.msgBlock, p.next.headerResult go retargetAndUnlock(p.next.headerResult.NextHash) p.hits++ // Return the requested block. return msgBlock, headerResult, nil } p.misses++ // Immediately retrieve msgBlock and header verbose result while fetcher is // blocked by the Mutex. msgBlock, headerResult, _, err := p.retrieveBlockAndHeaderResult(hash) if err != nil { p.Unlock() return nil, nil, err } // Leaving the mutex locked, fire off a goroutine to retarget to the next // block. The fetcher goroutine and other locking methods will stay blocked // until the mutex unlocks, but the msgBlock can be returned right away. go retargetAndUnlock(headerResult.NextHash) return msgBlock, headerResult, err }
[ "func", "(", "p", "*", "BlockPrefetchClient", ")", "GetBlockData", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "wire", ".", "MsgBlock", ",", "*", "dcrjson", ".", "GetBlockHeaderVerboseResult", ",", "error", ")", "{", "p", ".", "Lock", "(", ")", "\n\n", "retargetAndUnlock", ":=", "func", "(", "nextHash", "string", ")", "{", "p", ".", "retarget", "(", "nextHash", ")", "\n", "p", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "// If the block is already fetched, and the current block, return it. Do not", "// retarget.", "if", "p", ".", "current", ".", "hash", "==", "*", "hash", "/*p.haveBlockHash(*hash)*/", "{", "p", ".", "hits", "++", "\n", "// Return the requested block.", "defer", "p", ".", "Unlock", "(", ")", "\n", "return", "p", ".", "current", ".", "msgBlock", ",", "p", ".", "current", ".", "headerResult", ",", "nil", "\n", "}", "\n\n", "// If the block is already fetched, and next, return it and retarget with a", "// new range starting at this block's height.", "if", "p", ".", "next", ".", "hash", "==", "*", "hash", "/*p.haveBlockHash(*hash)*/", "{", "// Grab the result before retarget() changes p.next (via fetcher ->", "// RetrieveAndStoreNext -> storeNext).", "msgBlock", ",", "headerResult", ":=", "p", ".", "next", ".", "msgBlock", ",", "p", ".", "next", ".", "headerResult", "\n", "go", "retargetAndUnlock", "(", "p", ".", "next", ".", "headerResult", ".", "NextHash", ")", "\n", "p", ".", "hits", "++", "\n", "// Return the requested block.", "return", "msgBlock", ",", "headerResult", ",", "nil", "\n", "}", "\n\n", "p", ".", "misses", "++", "\n\n", "// Immediately retrieve msgBlock and header verbose result while fetcher is", "// blocked by the Mutex.", "msgBlock", ",", "headerResult", ",", "_", ",", "err", ":=", "p", ".", "retrieveBlockAndHeaderResult", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "Unlock", "(", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// Leaving the mutex locked, fire off a goroutine to retarget to the next", "// block. The fetcher goroutine and other locking methods will stay blocked", "// until the mutex unlocks, but the msgBlock can be returned right away.", "go", "retargetAndUnlock", "(", "headerResult", ".", "NextHash", ")", "\n\n", "return", "msgBlock", ",", "headerResult", ",", "err", "\n", "}" ]
// GetBlockData attempts to get the specified block and retargets the prefetcher // with the next block's hash. If the block was not already fetched, it is // retrieved immediately and stored following retargeting.
[ "GetBlockData", "attempts", "to", "get", "the", "specified", "block", "and", "retargets", "the", "prefetcher", "with", "the", "next", "block", "s", "hash", ".", "If", "the", "block", "was", "not", "already", "fetched", "it", "is", "retrieved", "immediately", "and", "stored", "following", "retargeting", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L107-L152
142,148
decred/dcrdata
rpcutils/prefetcher.go
GetBlock
func (p *BlockPrefetchClient) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error) { msgBlock, _, err := p.GetBlockData(hash) return msgBlock, err }
go
func (p *BlockPrefetchClient) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error) { msgBlock, _, err := p.GetBlockData(hash) return msgBlock, err }
[ "func", "(", "p", "*", "BlockPrefetchClient", ")", "GetBlock", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "wire", ".", "MsgBlock", ",", "error", ")", "{", "msgBlock", ",", "_", ",", "err", ":=", "p", ".", "GetBlockData", "(", "hash", ")", "\n", "return", "msgBlock", ",", "err", "\n", "}" ]
// GetBlock retrieves the wire.MsgBlock for the block with the specified hash. // See GetBlockData for details on how this interacts with the prefetcher.
[ "GetBlock", "retrieves", "the", "wire", ".", "MsgBlock", "for", "the", "block", "with", "the", "specified", "hash", ".", "See", "GetBlockData", "for", "details", "on", "how", "this", "interacts", "with", "the", "prefetcher", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L156-L159
142,149
decred/dcrdata
rpcutils/prefetcher.go
GetBlockHeaderVerbose
func (p *BlockPrefetchClient) GetBlockHeaderVerbose(hash *chainhash.Hash) (*dcrjson.GetBlockHeaderVerboseResult, error) { _, headerResult, err := p.GetBlockData(hash) return headerResult, err }
go
func (p *BlockPrefetchClient) GetBlockHeaderVerbose(hash *chainhash.Hash) (*dcrjson.GetBlockHeaderVerboseResult, error) { _, headerResult, err := p.GetBlockData(hash) return headerResult, err }
[ "func", "(", "p", "*", "BlockPrefetchClient", ")", "GetBlockHeaderVerbose", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "dcrjson", ".", "GetBlockHeaderVerboseResult", ",", "error", ")", "{", "_", ",", "headerResult", ",", "err", ":=", "p", ".", "GetBlockData", "(", "hash", ")", "\n", "return", "headerResult", ",", "err", "\n", "}" ]
// GetBlockHeaderVerbose retrieves the dcrjson.GetBlockHeaderVerboseResult for // the block with the specified hash. See GetBlockData for details on how this // interacts with the prefetcher
[ "GetBlockHeaderVerbose", "retrieves", "the", "dcrjson", ".", "GetBlockHeaderVerboseResult", "for", "the", "block", "with", "the", "specified", "hash", ".", "See", "GetBlockData", "for", "details", "on", "how", "this", "interacts", "with", "the", "prefetcher" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L164-L167
142,150
decred/dcrdata
rpcutils/prefetcher.go
storeNext
func (p *BlockPrefetchClient) storeNext(msgBlock *wire.MsgBlock, headerResult *dcrjson.GetBlockHeaderVerboseResult) { p.current = p.next p.next = &blockData{ height: msgBlock.Header.Height, hash: msgBlock.BlockHash(), msgBlock: msgBlock, headerResult: headerResult, } }
go
func (p *BlockPrefetchClient) storeNext(msgBlock *wire.MsgBlock, headerResult *dcrjson.GetBlockHeaderVerboseResult) { p.current = p.next p.next = &blockData{ height: msgBlock.Header.Height, hash: msgBlock.BlockHash(), msgBlock: msgBlock, headerResult: headerResult, } }
[ "func", "(", "p", "*", "BlockPrefetchClient", ")", "storeNext", "(", "msgBlock", "*", "wire", ".", "MsgBlock", ",", "headerResult", "*", "dcrjson", ".", "GetBlockHeaderVerboseResult", ")", "{", "p", ".", "current", "=", "p", ".", "next", "\n", "p", ".", "next", "=", "&", "blockData", "{", "height", ":", "msgBlock", ".", "Header", ".", "Height", ",", "hash", ":", "msgBlock", ".", "BlockHash", "(", ")", ",", "msgBlock", ":", "msgBlock", ",", "headerResult", ":", "headerResult", ",", "}", "\n", "}" ]
// storeNext stores the input data as the new "next" block. The existing "next" // becomes "current".
[ "storeNext", "stores", "the", "input", "data", "as", "the", "new", "next", "block", ".", "The", "existing", "next", "becomes", "current", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L192-L200
142,151
decred/dcrdata
rpcutils/prefetcher.go
RetrieveAndStoreNext
func (p *BlockPrefetchClient) RetrieveAndStoreNext(nextHash *chainhash.Hash) { p.Lock() defer p.Unlock() // Fetch the next block, if needed. if p.haveBlockHash(*nextHash) { return } msgBlock, headerResult, _, err := p.retrieveBlockAndHeaderResult(nextHash) if err != nil { if strings.HasPrefix(err.Error(), outOfRangeErr) { log.Errorf("retrieveBlockAndHeaderResult(%v): %v", nextHash, err) } return } // Store this block's data. p.storeNext(msgBlock, headerResult) }
go
func (p *BlockPrefetchClient) RetrieveAndStoreNext(nextHash *chainhash.Hash) { p.Lock() defer p.Unlock() // Fetch the next block, if needed. if p.haveBlockHash(*nextHash) { return } msgBlock, headerResult, _, err := p.retrieveBlockAndHeaderResult(nextHash) if err != nil { if strings.HasPrefix(err.Error(), outOfRangeErr) { log.Errorf("retrieveBlockAndHeaderResult(%v): %v", nextHash, err) } return } // Store this block's data. p.storeNext(msgBlock, headerResult) }
[ "func", "(", "p", "*", "BlockPrefetchClient", ")", "RetrieveAndStoreNext", "(", "nextHash", "*", "chainhash", ".", "Hash", ")", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "// Fetch the next block, if needed.", "if", "p", ".", "haveBlockHash", "(", "*", "nextHash", ")", "{", "return", "\n", "}", "\n\n", "msgBlock", ",", "headerResult", ",", "_", ",", "err", ":=", "p", ".", "retrieveBlockAndHeaderResult", "(", "nextHash", ")", "\n", "if", "err", "!=", "nil", "{", "if", "strings", ".", "HasPrefix", "(", "err", ".", "Error", "(", ")", ",", "outOfRangeErr", ")", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "nextHash", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n\n", "// Store this block's data.", "p", ".", "storeNext", "(", "msgBlock", ",", "headerResult", ")", "\n", "}" ]
// RetrieveAndStoreNext retrieves the next block specified by the Hash, if it is // not already the stored next block, and stores the block data. The existing // "next" becomes "current".
[ "RetrieveAndStoreNext", "retrieves", "the", "next", "block", "specified", "by", "the", "Hash", "if", "it", "is", "not", "already", "the", "stored", "next", "block", "and", "stores", "the", "block", "data", ".", "The", "existing", "next", "becomes", "current", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L220-L240
142,152
decred/dcrdata
rpcutils/prefetcher.go
HaveBlockHeight
func (p *BlockPrefetchClient) HaveBlockHeight(height uint32) bool { p.Lock() defer p.Unlock() return p.haveBlockHeight(height) }
go
func (p *BlockPrefetchClient) HaveBlockHeight(height uint32) bool { p.Lock() defer p.Unlock() return p.haveBlockHeight(height) }
[ "func", "(", "p", "*", "BlockPrefetchClient", ")", "HaveBlockHeight", "(", "height", "uint32", ")", "bool", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n", "return", "p", ".", "haveBlockHeight", "(", "height", ")", "\n", "}" ]
// HaveBlockHeight checks if the current or prefetched next block is for a block // with the specified height. Use HaveBlockHash to be sure it is the desired // block.
[ "HaveBlockHeight", "checks", "if", "the", "current", "or", "prefetched", "next", "block", "is", "for", "a", "block", "with", "the", "specified", "height", ".", "Use", "HaveBlockHash", "to", "be", "sure", "it", "is", "the", "desired", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L257-L261
142,153
decred/dcrdata
rpcutils/prefetcher.go
HaveBlockHash
func (p *BlockPrefetchClient) HaveBlockHash(hash chainhash.Hash) bool { p.Lock() defer p.Unlock() return p.haveBlockHash(hash) }
go
func (p *BlockPrefetchClient) HaveBlockHash(hash chainhash.Hash) bool { p.Lock() defer p.Unlock() return p.haveBlockHash(hash) }
[ "func", "(", "p", "*", "BlockPrefetchClient", ")", "HaveBlockHash", "(", "hash", "chainhash", ".", "Hash", ")", "bool", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n", "return", "p", ".", "haveBlockHash", "(", "hash", ")", "\n", "}" ]
// HaveBlockHash checks if the current or prefetched next block is for a block // with the specified hash.
[ "HaveBlockHash", "checks", "if", "the", "current", "or", "prefetched", "next", "block", "is", "for", "a", "block", "with", "the", "specified", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L269-L273
142,154
decred/dcrdata
gov/agendas/tracker.go
NewVoteTracker
func NewVoteTracker(params *chaincfg.Params, node VoteDataSource, counter voteCounter, activeVersions map[uint32][]chaincfg.ConsensusDeployment) (*VoteTracker, error) { var latestStakeVersion uint32 var starttime uint64 // Consensus deployments that share a stake version as the key should also // have matching starttime. for stakeVersion, val := range activeVersions { if latestStakeVersion == 0 { latestStakeVersion = stakeVersion starttime = val[0].StartTime } else if val[0].StartTime >= starttime { latestStakeVersion = stakeVersion starttime = val[0].StartTime } } tracker := &VoteTracker{ mtx: sync.RWMutex{}, node: node, voteCounter: counter, countCache: make(map[string]*voteCount), params: params, version: latestStakeVersion, ringIndex: -1, blockRing: make([]int32, params.BlockUpgradeNumToCheck), minerThreshold: float32(params.BlockRejectNumRequired) / float32(params.BlockUpgradeNumToCheck), voterThreshold: float32(params.RuleChangeActivationMultiplier) / float32(params.RuleChangeActivationDivisor), sviBlocks: uint32(params.StakeVersionInterval), rciBlocks: params.RuleChangeActivationInterval, blockTime: int64(params.TargetTimePerBlock.Seconds()), passThreshold: float32(params.RuleChangeActivationMultiplier) / float32(params.RuleChangeActivationDivisor), rciVotes: uint32(params.TicketsPerBlock) * params.RuleChangeActivationInterval, } // first sync has different error handling than Refresh. voteInfo, err := tracker.refreshRCI() if err != nil { return nil, err } blocksToAdd, stakeVersion, err := tracker.fetchBlocks(voteInfo) if err != nil { return nil, err } stakeInfo, err := tracker.refreshSVIs(voteInfo) if err != nil { return nil, err } tracker.update(voteInfo, blocksToAdd, stakeInfo, stakeVersion) return tracker, nil }
go
func NewVoteTracker(params *chaincfg.Params, node VoteDataSource, counter voteCounter, activeVersions map[uint32][]chaincfg.ConsensusDeployment) (*VoteTracker, error) { var latestStakeVersion uint32 var starttime uint64 // Consensus deployments that share a stake version as the key should also // have matching starttime. for stakeVersion, val := range activeVersions { if latestStakeVersion == 0 { latestStakeVersion = stakeVersion starttime = val[0].StartTime } else if val[0].StartTime >= starttime { latestStakeVersion = stakeVersion starttime = val[0].StartTime } } tracker := &VoteTracker{ mtx: sync.RWMutex{}, node: node, voteCounter: counter, countCache: make(map[string]*voteCount), params: params, version: latestStakeVersion, ringIndex: -1, blockRing: make([]int32, params.BlockUpgradeNumToCheck), minerThreshold: float32(params.BlockRejectNumRequired) / float32(params.BlockUpgradeNumToCheck), voterThreshold: float32(params.RuleChangeActivationMultiplier) / float32(params.RuleChangeActivationDivisor), sviBlocks: uint32(params.StakeVersionInterval), rciBlocks: params.RuleChangeActivationInterval, blockTime: int64(params.TargetTimePerBlock.Seconds()), passThreshold: float32(params.RuleChangeActivationMultiplier) / float32(params.RuleChangeActivationDivisor), rciVotes: uint32(params.TicketsPerBlock) * params.RuleChangeActivationInterval, } // first sync has different error handling than Refresh. voteInfo, err := tracker.refreshRCI() if err != nil { return nil, err } blocksToAdd, stakeVersion, err := tracker.fetchBlocks(voteInfo) if err != nil { return nil, err } stakeInfo, err := tracker.refreshSVIs(voteInfo) if err != nil { return nil, err } tracker.update(voteInfo, blocksToAdd, stakeInfo, stakeVersion) return tracker, nil }
[ "func", "NewVoteTracker", "(", "params", "*", "chaincfg", ".", "Params", ",", "node", "VoteDataSource", ",", "counter", "voteCounter", ",", "activeVersions", "map", "[", "uint32", "]", "[", "]", "chaincfg", ".", "ConsensusDeployment", ")", "(", "*", "VoteTracker", ",", "error", ")", "{", "var", "latestStakeVersion", "uint32", "\n", "var", "starttime", "uint64", "\n\n", "// Consensus deployments that share a stake version as the key should also", "// have matching starttime.", "for", "stakeVersion", ",", "val", ":=", "range", "activeVersions", "{", "if", "latestStakeVersion", "==", "0", "{", "latestStakeVersion", "=", "stakeVersion", "\n", "starttime", "=", "val", "[", "0", "]", ".", "StartTime", "\n", "}", "else", "if", "val", "[", "0", "]", ".", "StartTime", ">=", "starttime", "{", "latestStakeVersion", "=", "stakeVersion", "\n", "starttime", "=", "val", "[", "0", "]", ".", "StartTime", "\n", "}", "\n", "}", "\n\n", "tracker", ":=", "&", "VoteTracker", "{", "mtx", ":", "sync", ".", "RWMutex", "{", "}", ",", "node", ":", "node", ",", "voteCounter", ":", "counter", ",", "countCache", ":", "make", "(", "map", "[", "string", "]", "*", "voteCount", ")", ",", "params", ":", "params", ",", "version", ":", "latestStakeVersion", ",", "ringIndex", ":", "-", "1", ",", "blockRing", ":", "make", "(", "[", "]", "int32", ",", "params", ".", "BlockUpgradeNumToCheck", ")", ",", "minerThreshold", ":", "float32", "(", "params", ".", "BlockRejectNumRequired", ")", "/", "float32", "(", "params", ".", "BlockUpgradeNumToCheck", ")", ",", "voterThreshold", ":", "float32", "(", "params", ".", "RuleChangeActivationMultiplier", ")", "/", "float32", "(", "params", ".", "RuleChangeActivationDivisor", ")", ",", "sviBlocks", ":", "uint32", "(", "params", ".", "StakeVersionInterval", ")", ",", "rciBlocks", ":", "params", ".", "RuleChangeActivationInterval", ",", "blockTime", ":", "int64", "(", "params", ".", "TargetTimePerBlock", ".", "Seconds", "(", ")", ")", ",", "passThreshold", ":", "float32", "(", "params", ".", "RuleChangeActivationMultiplier", ")", "/", "float32", "(", "params", ".", "RuleChangeActivationDivisor", ")", ",", "rciVotes", ":", "uint32", "(", "params", ".", "TicketsPerBlock", ")", "*", "params", ".", "RuleChangeActivationInterval", ",", "}", "\n\n", "// first sync has different error handling than Refresh.", "voteInfo", ",", "err", ":=", "tracker", ".", "refreshRCI", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "blocksToAdd", ",", "stakeVersion", ",", "err", ":=", "tracker", ".", "fetchBlocks", "(", "voteInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "stakeInfo", ",", "err", ":=", "tracker", ".", "refreshSVIs", "(", "voteInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tracker", ".", "update", "(", "voteInfo", ",", "blocksToAdd", ",", "stakeInfo", ",", "stakeVersion", ")", "\n\n", "return", "tracker", ",", "nil", "\n", "}" ]
// NewVoteTracker is a constructor for a VoteTracker.
[ "NewVoteTracker", "is", "a", "constructor", "for", "a", "VoteTracker", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L130-L181
142,155
decred/dcrdata
gov/agendas/tracker.go
Refresh
func (tracker *VoteTracker) Refresh() { voteInfo, err := tracker.refreshRCI() if err != nil { log.Errorf("VoteTracker.Refresh -> refreshRCI: %v") return } blocksToAdd, stakeVersion, err := tracker.fetchBlocks(voteInfo) if err != nil { log.Errorf("VoteTracker.Refresh -> fetchBlocks: %v") return } stakeInfo, err := tracker.refreshSVIs(voteInfo) if err != nil { log.Errorf("VoteTracker.Refresh -> refreshSVIs: %v") return } tracker.update(voteInfo, blocksToAdd, stakeInfo, stakeVersion) }
go
func (tracker *VoteTracker) Refresh() { voteInfo, err := tracker.refreshRCI() if err != nil { log.Errorf("VoteTracker.Refresh -> refreshRCI: %v") return } blocksToAdd, stakeVersion, err := tracker.fetchBlocks(voteInfo) if err != nil { log.Errorf("VoteTracker.Refresh -> fetchBlocks: %v") return } stakeInfo, err := tracker.refreshSVIs(voteInfo) if err != nil { log.Errorf("VoteTracker.Refresh -> refreshSVIs: %v") return } tracker.update(voteInfo, blocksToAdd, stakeInfo, stakeVersion) }
[ "func", "(", "tracker", "*", "VoteTracker", ")", "Refresh", "(", ")", "{", "voteInfo", ",", "err", ":=", "tracker", ".", "refreshRCI", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "blocksToAdd", ",", "stakeVersion", ",", "err", ":=", "tracker", ".", "fetchBlocks", "(", "voteInfo", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "stakeInfo", ",", "err", ":=", "tracker", ".", "refreshSVIs", "(", "voteInfo", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "tracker", ".", "update", "(", "voteInfo", ",", "blocksToAdd", ",", "stakeInfo", ",", "stakeVersion", ")", "\n", "}" ]
// Refresh refreshes node version and vote data. It can be called as a // goroutine. All VoteTracker updating and mutex locking is handled within // VoteTracker.update.
[ "Refresh", "refreshes", "node", "version", "and", "vote", "data", ".", "It", "can", "be", "called", "as", "a", "goroutine", ".", "All", "VoteTracker", "updating", "and", "mutex", "locking", "is", "handled", "within", "VoteTracker", ".", "update", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L186-L203
142,156
decred/dcrdata
gov/agendas/tracker.go
Version
func (tracker *VoteTracker) Version() uint32 { tracker.mtx.RLock() defer tracker.mtx.RUnlock() return tracker.version }
go
func (tracker *VoteTracker) Version() uint32 { tracker.mtx.RLock() defer tracker.mtx.RUnlock() return tracker.version }
[ "func", "(", "tracker", "*", "VoteTracker", ")", "Version", "(", ")", "uint32", "{", "tracker", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "tracker", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "tracker", ".", "version", "\n", "}" ]
// Version returns the current best known vote version. // Since version could technically be updated without turning off dcrdata, // the field must be protected.
[ "Version", "returns", "the", "current", "best", "known", "vote", "version", ".", "Since", "version", "could", "technically", "be", "updated", "without", "turning", "off", "dcrdata", "the", "field", "must", "be", "protected", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L208-L212
142,157
decred/dcrdata
gov/agendas/tracker.go
refreshRCI
func (tracker *VoteTracker) refreshRCI() (*dcrjson.GetVoteInfoResult, error) { oldVersion := tracker.Version() v := oldVersion var err error var voteInfo, vinfo *dcrjson.GetVoteInfoResult // Retrieves the voteinfo for the last stake version supported. for { vinfo, err = tracker.node.GetVoteInfo(v) if err != nil { break } voteInfo = vinfo v++ } if voteInfo == nil { return nil, fmt.Errorf("Vote information not found: %v", err) } if v > oldVersion+1 { tracker.mtx.Lock() tracker.version = v tracker.mtx.Unlock() } return voteInfo, nil }
go
func (tracker *VoteTracker) refreshRCI() (*dcrjson.GetVoteInfoResult, error) { oldVersion := tracker.Version() v := oldVersion var err error var voteInfo, vinfo *dcrjson.GetVoteInfoResult // Retrieves the voteinfo for the last stake version supported. for { vinfo, err = tracker.node.GetVoteInfo(v) if err != nil { break } voteInfo = vinfo v++ } if voteInfo == nil { return nil, fmt.Errorf("Vote information not found: %v", err) } if v > oldVersion+1 { tracker.mtx.Lock() tracker.version = v tracker.mtx.Unlock() } return voteInfo, nil }
[ "func", "(", "tracker", "*", "VoteTracker", ")", "refreshRCI", "(", ")", "(", "*", "dcrjson", ".", "GetVoteInfoResult", ",", "error", ")", "{", "oldVersion", ":=", "tracker", ".", "Version", "(", ")", "\n", "v", ":=", "oldVersion", "\n", "var", "err", "error", "\n", "var", "voteInfo", ",", "vinfo", "*", "dcrjson", ".", "GetVoteInfoResult", "\n\n", "// Retrieves the voteinfo for the last stake version supported.", "for", "{", "vinfo", ",", "err", "=", "tracker", ".", "node", ".", "GetVoteInfo", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "voteInfo", "=", "vinfo", "\n", "v", "++", "\n", "}", "\n\n", "if", "voteInfo", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "v", ">", "oldVersion", "+", "1", "{", "tracker", ".", "mtx", ".", "Lock", "(", ")", "\n", "tracker", ".", "version", "=", "v", "\n", "tracker", ".", "mtx", ".", "Unlock", "(", ")", "\n", "}", "\n", "return", "voteInfo", ",", "nil", "\n", "}" ]
// Grab the getvoteinfo data. Do not update VoteTracker.voteInfo here, as it // will be updated with other fields under mutex lock in VoteTracker.update.
[ "Grab", "the", "getvoteinfo", "data", ".", "Do", "not", "update", "VoteTracker", ".", "voteInfo", "here", "as", "it", "will", "be", "updated", "with", "other", "fields", "under", "mutex", "lock", "in", "VoteTracker", ".", "update", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L216-L241
142,158
decred/dcrdata
gov/agendas/tracker.go
fetchBlocks
func (tracker *VoteTracker) fetchBlocks(voteInfo *dcrjson.GetVoteInfoResult) ([]int32, uint32, error) { blocksToRequest := 1 // If this isn't the next block, request them all again if voteInfo.CurrentHeight < 0 || voteInfo.CurrentHeight != tracker.ringHeight+1 { blocksToRequest = int(tracker.params.BlockUpgradeNumToCheck) } r, err := tracker.node.GetStakeVersions(voteInfo.Hash, int32(blocksToRequest)) if err != nil { return nil, 0, err } blockCount := len(r.StakeVersions) if blockCount != blocksToRequest { return nil, 0, fmt.Errorf("Unexpected number of blocks returns from GetStakeVersions. Asked for %d, received %d", blocksToRequest, blockCount) } blocks := make([]int32, blockCount) var block dcrjson.StakeVersions for i := 0; i < blockCount; i++ { block = r.StakeVersions[blockCount-i-1] // iterate backwards tracker.ringIndex = (tracker.ringIndex + 1) % blockCount blocks[i] = block.BlockVersion } return blocks, block.StakeVersion, nil }
go
func (tracker *VoteTracker) fetchBlocks(voteInfo *dcrjson.GetVoteInfoResult) ([]int32, uint32, error) { blocksToRequest := 1 // If this isn't the next block, request them all again if voteInfo.CurrentHeight < 0 || voteInfo.CurrentHeight != tracker.ringHeight+1 { blocksToRequest = int(tracker.params.BlockUpgradeNumToCheck) } r, err := tracker.node.GetStakeVersions(voteInfo.Hash, int32(blocksToRequest)) if err != nil { return nil, 0, err } blockCount := len(r.StakeVersions) if blockCount != blocksToRequest { return nil, 0, fmt.Errorf("Unexpected number of blocks returns from GetStakeVersions. Asked for %d, received %d", blocksToRequest, blockCount) } blocks := make([]int32, blockCount) var block dcrjson.StakeVersions for i := 0; i < blockCount; i++ { block = r.StakeVersions[blockCount-i-1] // iterate backwards tracker.ringIndex = (tracker.ringIndex + 1) % blockCount blocks[i] = block.BlockVersion } return blocks, block.StakeVersion, nil }
[ "func", "(", "tracker", "*", "VoteTracker", ")", "fetchBlocks", "(", "voteInfo", "*", "dcrjson", ".", "GetVoteInfoResult", ")", "(", "[", "]", "int32", ",", "uint32", ",", "error", ")", "{", "blocksToRequest", ":=", "1", "\n", "// If this isn't the next block, request them all again", "if", "voteInfo", ".", "CurrentHeight", "<", "0", "||", "voteInfo", ".", "CurrentHeight", "!=", "tracker", ".", "ringHeight", "+", "1", "{", "blocksToRequest", "=", "int", "(", "tracker", ".", "params", ".", "BlockUpgradeNumToCheck", ")", "\n", "}", "\n", "r", ",", "err", ":=", "tracker", ".", "node", ".", "GetStakeVersions", "(", "voteInfo", ".", "Hash", ",", "int32", "(", "blocksToRequest", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "blockCount", ":=", "len", "(", "r", ".", "StakeVersions", ")", "\n", "if", "blockCount", "!=", "blocksToRequest", "{", "return", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "blocksToRequest", ",", "blockCount", ")", "\n", "}", "\n", "blocks", ":=", "make", "(", "[", "]", "int32", ",", "blockCount", ")", "\n", "var", "block", "dcrjson", ".", "StakeVersions", "\n", "for", "i", ":=", "0", ";", "i", "<", "blockCount", ";", "i", "++", "{", "block", "=", "r", ".", "StakeVersions", "[", "blockCount", "-", "i", "-", "1", "]", "// iterate backwards", "\n", "tracker", ".", "ringIndex", "=", "(", "tracker", ".", "ringIndex", "+", "1", ")", "%", "blockCount", "\n", "blocks", "[", "i", "]", "=", "block", ".", "BlockVersion", "\n", "}", "\n", "return", "blocks", ",", "block", ".", "StakeVersion", ",", "nil", "\n", "}" ]
// Grab the block versions for up to the last BlockUpgradeNumToCheck blocks. // If the current block builds upon the last block, only request a single // block's data. Otherwise, request all BlockUpgradeNumToCheck.
[ "Grab", "the", "block", "versions", "for", "up", "to", "the", "last", "BlockUpgradeNumToCheck", "blocks", ".", "If", "the", "current", "block", "builds", "upon", "the", "last", "block", "only", "request", "a", "single", "block", "s", "data", ".", "Otherwise", "request", "all", "BlockUpgradeNumToCheck", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L251-L273
142,159
decred/dcrdata
gov/agendas/tracker.go
refreshSVIs
func (tracker *VoteTracker) refreshSVIs(voteInfo *dcrjson.GetVoteInfoResult) (*dcrjson.GetStakeVersionInfoResult, error) { blocksInCurrentRCI := rciBlocks(voteInfo) svis := int32(blocksInCurrentRCI / tracker.params.StakeVersionInterval) // blocksInCurrentSVI := int32(blocksInCurrentRCI % params.StakeVersionInterval) if blocksInCurrentRCI%tracker.params.StakeVersionInterval > 0 { svis++ } si, err := tracker.node.GetStakeVersionInfo(svis) if err != nil { return nil, fmt.Errorf("Error retrieving stake version info: %v", err) } return si, nil }
go
func (tracker *VoteTracker) refreshSVIs(voteInfo *dcrjson.GetVoteInfoResult) (*dcrjson.GetStakeVersionInfoResult, error) { blocksInCurrentRCI := rciBlocks(voteInfo) svis := int32(blocksInCurrentRCI / tracker.params.StakeVersionInterval) // blocksInCurrentSVI := int32(blocksInCurrentRCI % params.StakeVersionInterval) if blocksInCurrentRCI%tracker.params.StakeVersionInterval > 0 { svis++ } si, err := tracker.node.GetStakeVersionInfo(svis) if err != nil { return nil, fmt.Errorf("Error retrieving stake version info: %v", err) } return si, nil }
[ "func", "(", "tracker", "*", "VoteTracker", ")", "refreshSVIs", "(", "voteInfo", "*", "dcrjson", ".", "GetVoteInfoResult", ")", "(", "*", "dcrjson", ".", "GetStakeVersionInfoResult", ",", "error", ")", "{", "blocksInCurrentRCI", ":=", "rciBlocks", "(", "voteInfo", ")", "\n", "svis", ":=", "int32", "(", "blocksInCurrentRCI", "/", "tracker", ".", "params", ".", "StakeVersionInterval", ")", "\n", "// blocksInCurrentSVI := int32(blocksInCurrentRCI % params.StakeVersionInterval)", "if", "blocksInCurrentRCI", "%", "tracker", ".", "params", ".", "StakeVersionInterval", ">", "0", "{", "svis", "++", "\n", "}", "\n", "si", ",", "err", ":=", "tracker", ".", "node", ".", "GetStakeVersionInfo", "(", "svis", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "si", ",", "nil", "\n", "}" ]
// Get the info for the stake versions in the current rule change interval.
[ "Get", "the", "info", "for", "the", "stake", "versions", "in", "the", "current", "rule", "change", "interval", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L276-L288
142,160
decred/dcrdata
gov/agendas/tracker.go
cachedCounts
func (tracker *VoteTracker) cachedCounts(agendaID string) *voteCount { tracker.mtx.RLock() defer tracker.mtx.RUnlock() return tracker.countCache[agendaID] }
go
func (tracker *VoteTracker) cachedCounts(agendaID string) *voteCount { tracker.mtx.RLock() defer tracker.mtx.RUnlock() return tracker.countCache[agendaID] }
[ "func", "(", "tracker", "*", "VoteTracker", ")", "cachedCounts", "(", "agendaID", "string", ")", "*", "voteCount", "{", "tracker", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "tracker", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "tracker", ".", "countCache", "[", "agendaID", "]", "\n", "}" ]
// The cached voteCount for the given agenda, or nil if not found.
[ "The", "cached", "voteCount", "for", "the", "given", "agenda", "or", "nil", "if", "not", "found", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L291-L295
142,161
decred/dcrdata
gov/agendas/tracker.go
cacheVoteCounts
func (tracker *VoteTracker) cacheVoteCounts(agendaID string, counts *voteCount) { tracker.mtx.Lock() defer tracker.mtx.Unlock() tracker.countCache[agendaID] = counts }
go
func (tracker *VoteTracker) cacheVoteCounts(agendaID string, counts *voteCount) { tracker.mtx.Lock() defer tracker.mtx.Unlock() tracker.countCache[agendaID] = counts }
[ "func", "(", "tracker", "*", "VoteTracker", ")", "cacheVoteCounts", "(", "agendaID", "string", ",", "counts", "*", "voteCount", ")", "{", "tracker", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "tracker", ".", "mtx", ".", "Unlock", "(", ")", "\n", "tracker", ".", "countCache", "[", "agendaID", "]", "=", "counts", "\n", "}" ]
// Cache the voteCount for the given agenda.
[ "Cache", "the", "voteCount", "for", "the", "given", "agenda", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L298-L302
142,162
decred/dcrdata
gov/agendas/tracker.go
update
func (tracker *VoteTracker) update(voteInfo *dcrjson.GetVoteInfoResult, blocks []int32, stakeInfo *dcrjson.GetStakeVersionInfoResult, stakeVersion uint32) { // Check if voteCounts are needed for idx := range voteInfo.Agendas { agenda := &voteInfo.Agendas[idx] if agenda.Status != statusDefined && agenda.Status != statusStarted { // check the cache counts := tracker.cachedCounts(agenda.ID) if counts == nil { counts = new(voteCount) var err error counts.yes, counts.abstain, counts.no, err = tracker.voteCounter(agenda.ID) if err != nil { log.Errorf("Error counting votes for %s: %v", agenda.ID, err) continue } tracker.cacheVoteCounts(agenda.ID, counts) } for idx := range agenda.Choices { choice := &agenda.Choices[idx] if choice.ID == choiceYes { choice.Count = counts.yes } else if choice.ID == choiceNo { choice.Count = counts.no } else { choice.Count = counts.abstain } } } } tracker.mtx.Lock() defer tracker.mtx.Unlock() tracker.voteInfo = voteInfo tracker.stakeInfo = stakeInfo ringLen := int(tracker.params.BlockUpgradeNumToCheck) for idx := range blocks { tracker.ringIndex = (tracker.ringIndex + 1) % ringLen tracker.blockRing[tracker.ringIndex] = blocks[idx] } tracker.blockVersion = tracker.blockRing[tracker.ringIndex] tracker.stakeVersion = stakeVersion tracker.ringHeight = voteInfo.CurrentHeight tracker.summary = tracker.newVoteSummary() }
go
func (tracker *VoteTracker) update(voteInfo *dcrjson.GetVoteInfoResult, blocks []int32, stakeInfo *dcrjson.GetStakeVersionInfoResult, stakeVersion uint32) { // Check if voteCounts are needed for idx := range voteInfo.Agendas { agenda := &voteInfo.Agendas[idx] if agenda.Status != statusDefined && agenda.Status != statusStarted { // check the cache counts := tracker.cachedCounts(agenda.ID) if counts == nil { counts = new(voteCount) var err error counts.yes, counts.abstain, counts.no, err = tracker.voteCounter(agenda.ID) if err != nil { log.Errorf("Error counting votes for %s: %v", agenda.ID, err) continue } tracker.cacheVoteCounts(agenda.ID, counts) } for idx := range agenda.Choices { choice := &agenda.Choices[idx] if choice.ID == choiceYes { choice.Count = counts.yes } else if choice.ID == choiceNo { choice.Count = counts.no } else { choice.Count = counts.abstain } } } } tracker.mtx.Lock() defer tracker.mtx.Unlock() tracker.voteInfo = voteInfo tracker.stakeInfo = stakeInfo ringLen := int(tracker.params.BlockUpgradeNumToCheck) for idx := range blocks { tracker.ringIndex = (tracker.ringIndex + 1) % ringLen tracker.blockRing[tracker.ringIndex] = blocks[idx] } tracker.blockVersion = tracker.blockRing[tracker.ringIndex] tracker.stakeVersion = stakeVersion tracker.ringHeight = voteInfo.CurrentHeight tracker.summary = tracker.newVoteSummary() }
[ "func", "(", "tracker", "*", "VoteTracker", ")", "update", "(", "voteInfo", "*", "dcrjson", ".", "GetVoteInfoResult", ",", "blocks", "[", "]", "int32", ",", "stakeInfo", "*", "dcrjson", ".", "GetStakeVersionInfoResult", ",", "stakeVersion", "uint32", ")", "{", "// Check if voteCounts are needed", "for", "idx", ":=", "range", "voteInfo", ".", "Agendas", "{", "agenda", ":=", "&", "voteInfo", ".", "Agendas", "[", "idx", "]", "\n", "if", "agenda", ".", "Status", "!=", "statusDefined", "&&", "agenda", ".", "Status", "!=", "statusStarted", "{", "// check the cache", "counts", ":=", "tracker", ".", "cachedCounts", "(", "agenda", ".", "ID", ")", "\n", "if", "counts", "==", "nil", "{", "counts", "=", "new", "(", "voteCount", ")", "\n", "var", "err", "error", "\n", "counts", ".", "yes", ",", "counts", ".", "abstain", ",", "counts", ".", "no", ",", "err", "=", "tracker", ".", "voteCounter", "(", "agenda", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "agenda", ".", "ID", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "tracker", ".", "cacheVoteCounts", "(", "agenda", ".", "ID", ",", "counts", ")", "\n", "}", "\n", "for", "idx", ":=", "range", "agenda", ".", "Choices", "{", "choice", ":=", "&", "agenda", ".", "Choices", "[", "idx", "]", "\n", "if", "choice", ".", "ID", "==", "choiceYes", "{", "choice", ".", "Count", "=", "counts", ".", "yes", "\n", "}", "else", "if", "choice", ".", "ID", "==", "choiceNo", "{", "choice", ".", "Count", "=", "counts", ".", "no", "\n", "}", "else", "{", "choice", ".", "Count", "=", "counts", ".", "abstain", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "tracker", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "tracker", ".", "mtx", ".", "Unlock", "(", ")", "\n", "tracker", ".", "voteInfo", "=", "voteInfo", "\n", "tracker", ".", "stakeInfo", "=", "stakeInfo", "\n", "ringLen", ":=", "int", "(", "tracker", ".", "params", ".", "BlockUpgradeNumToCheck", ")", "\n", "for", "idx", ":=", "range", "blocks", "{", "tracker", ".", "ringIndex", "=", "(", "tracker", ".", "ringIndex", "+", "1", ")", "%", "ringLen", "\n", "tracker", ".", "blockRing", "[", "tracker", ".", "ringIndex", "]", "=", "blocks", "[", "idx", "]", "\n", "}", "\n", "tracker", ".", "blockVersion", "=", "tracker", ".", "blockRing", "[", "tracker", ".", "ringIndex", "]", "\n", "tracker", ".", "stakeVersion", "=", "stakeVersion", "\n", "tracker", ".", "ringHeight", "=", "voteInfo", ".", "CurrentHeight", "\n", "tracker", ".", "summary", "=", "tracker", ".", "newVoteSummary", "(", ")", "\n", "}" ]
// Once all resources have been retrieved from dcrd, update VoteTracker fields.
[ "Once", "all", "resources", "have", "been", "retrieved", "from", "dcrd", "update", "VoteTracker", "fields", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L305-L348
142,163
decred/dcrdata
gov/agendas/tracker.go
Summary
func (tracker *VoteTracker) Summary() *VoteSummary { tracker.mtx.RLock() defer tracker.mtx.RUnlock() return tracker.summary }
go
func (tracker *VoteTracker) Summary() *VoteSummary { tracker.mtx.RLock() defer tracker.mtx.RUnlock() return tracker.summary }
[ "func", "(", "tracker", "*", "VoteTracker", ")", "Summary", "(", ")", "*", "VoteSummary", "{", "tracker", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "tracker", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "tracker", ".", "summary", "\n", "}" ]
// Summary is a getter for the cached VoteSummary. The summary returned will // never be modified by VoteTracker, so can be used read-only by any number // of threads.
[ "Summary", "is", "a", "getter", "for", "the", "cached", "VoteSummary", ".", "The", "summary", "returned", "will", "never", "be", "modified", "by", "VoteTracker", "so", "can", "be", "used", "read", "-", "only", "by", "any", "number", "of", "threads", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L469-L473
142,164
decred/dcrdata
dcrrates/rateserver/log.go
initializeLogging
func initializeLogging(logFile, logLevel string) { log = backendLog.Logger("SRVR") exchanges.UseLogger(xcLogger) logDir, _ := filepath.Split(logFile) err := os.MkdirAll(logDir, 0700) if err != nil { log.Errorf("failed to create log directory: %v", err) os.Exit(1) } r, err := rotator.New(logFile, 10*1024, false, 3) if err != nil { log.Errorf("failed to create file rotator: %v\n", err) os.Exit(1) } logRotator = r if logLevel != "" { level, ok := slog.LevelFromString(logLevel) if ok { log.SetLevel(level) xcLogger.SetLevel(level) } else { log.Infof("Unable to assign logging level=%s. Falling back to level=info", logLevel) } } }
go
func initializeLogging(logFile, logLevel string) { log = backendLog.Logger("SRVR") exchanges.UseLogger(xcLogger) logDir, _ := filepath.Split(logFile) err := os.MkdirAll(logDir, 0700) if err != nil { log.Errorf("failed to create log directory: %v", err) os.Exit(1) } r, err := rotator.New(logFile, 10*1024, false, 3) if err != nil { log.Errorf("failed to create file rotator: %v\n", err) os.Exit(1) } logRotator = r if logLevel != "" { level, ok := slog.LevelFromString(logLevel) if ok { log.SetLevel(level) xcLogger.SetLevel(level) } else { log.Infof("Unable to assign logging level=%s. Falling back to level=info", logLevel) } } }
[ "func", "initializeLogging", "(", "logFile", ",", "logLevel", "string", ")", "{", "log", "=", "backendLog", ".", "Logger", "(", "\"", "\"", ")", "\n", "exchanges", ".", "UseLogger", "(", "xcLogger", ")", "\n", "logDir", ",", "_", ":=", "filepath", ".", "Split", "(", "logFile", ")", "\n", "err", ":=", "os", ".", "MkdirAll", "(", "logDir", ",", "0700", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "r", ",", "err", ":=", "rotator", ".", "New", "(", "logFile", ",", "10", "*", "1024", ",", "false", ",", "3", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "logRotator", "=", "r", "\n", "if", "logLevel", "!=", "\"", "\"", "{", "level", ",", "ok", ":=", "slog", ".", "LevelFromString", "(", "logLevel", ")", "\n", "if", "ok", "{", "log", ".", "SetLevel", "(", "level", ")", "\n", "xcLogger", ".", "SetLevel", "(", "level", ")", "\n", "}", "else", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "logLevel", ")", "\n", "}", "\n", "}", "\n", "}" ]
// initializeLogging initializes the logging rotater to write logs to logFile // and create roll files in the same directory. It must be called before the // package-global log rotater variables are used.
[ "initializeLogging", "initializes", "the", "logging", "rotater", "to", "write", "logs", "to", "logFile", "and", "create", "roll", "files", "in", "the", "same", "directory", ".", "It", "must", "be", "called", "before", "the", "package", "-", "global", "log", "rotater", "variables", "are", "used", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/dcrrates/rateserver/log.go#L36-L60
142,165
decred/dcrdata
db/dcrpg/chainmonitor.go
NewChainMonitor
func (pgb *ChainDBRPC) NewChainMonitor(ctx context.Context, wg *sync.WaitGroup, blockChan chan *chainhash.Hash, reorgChan chan *txhelpers.ReorgData) *ChainMonitor { if pgb == nil { return nil } return &ChainMonitor{ ctx: ctx, db: pgb, wg: wg, blockChan: blockChan, reorgChan: reorgChan, ConnectingLock: make(chan struct{}, 1), DoneConnecting: make(chan struct{}), } }
go
func (pgb *ChainDBRPC) NewChainMonitor(ctx context.Context, wg *sync.WaitGroup, blockChan chan *chainhash.Hash, reorgChan chan *txhelpers.ReorgData) *ChainMonitor { if pgb == nil { return nil } return &ChainMonitor{ ctx: ctx, db: pgb, wg: wg, blockChan: blockChan, reorgChan: reorgChan, ConnectingLock: make(chan struct{}, 1), DoneConnecting: make(chan struct{}), } }
[ "func", "(", "pgb", "*", "ChainDBRPC", ")", "NewChainMonitor", "(", "ctx", "context", ".", "Context", ",", "wg", "*", "sync", ".", "WaitGroup", ",", "blockChan", "chan", "*", "chainhash", ".", "Hash", ",", "reorgChan", "chan", "*", "txhelpers", ".", "ReorgData", ")", "*", "ChainMonitor", "{", "if", "pgb", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "&", "ChainMonitor", "{", "ctx", ":", "ctx", ",", "db", ":", "pgb", ",", "wg", ":", "wg", ",", "blockChan", ":", "blockChan", ",", "reorgChan", ":", "reorgChan", ",", "ConnectingLock", ":", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", ",", "DoneConnecting", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "}" ]
// NewChainMonitor creates a new ChainMonitor.
[ "NewChainMonitor", "creates", "a", "new", "ChainMonitor", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/chainmonitor.go#L30-L44
142,166
decred/dcrdata
rpcutils/rpcclient.go
ConnectNodeRPC
func ConnectNodeRPC(host, user, pass, cert string, disableTLS, disableReconnect bool, ntfnHandlers ...*rpcclient.NotificationHandlers) (*rpcclient.Client, semver.Semver, error) { var dcrdCerts []byte var err error var nodeVer semver.Semver if !disableTLS { dcrdCerts, err = ioutil.ReadFile(cert) if err != nil { log.Errorf("Failed to read dcrd cert file at %s: %s\n", cert, err.Error()) return nil, nodeVer, err } log.Debugf("Attempting to connect to dcrd RPC %s as user %s "+ "using certificate located in %s", host, user, cert) } else { log.Debugf("Attempting to connect to dcrd RPC %s as user %s (no TLS)", host, user) } connCfgDaemon := &rpcclient.ConnConfig{ Host: host, Endpoint: "ws", // websocket User: user, Pass: pass, Certificates: dcrdCerts, DisableTLS: disableTLS, DisableAutoReconnect: disableReconnect, } var ntfnHdlrs *rpcclient.NotificationHandlers if len(ntfnHandlers) > 0 { if len(ntfnHandlers) > 1 { return nil, nodeVer, fmt.Errorf("invalid notification handler argument") } ntfnHdlrs = ntfnHandlers[0] } dcrdClient, err := rpcclient.New(connCfgDaemon, ntfnHdlrs) if err != nil { return nil, nodeVer, fmt.Errorf("Failed to start dcrd RPC client: %s", err.Error()) } // Ensure the RPC server has a compatible API version. ver, err := dcrdClient.Version() if err != nil { log.Error("Unable to get RPC version: ", err) return nil, nodeVer, fmt.Errorf("unable to get node RPC version") } dcrdVer := ver["dcrdjsonrpcapi"] nodeVer = semver.NewSemver(dcrdVer.Major, dcrdVer.Minor, dcrdVer.Patch) // Check if the dcrd RPC API version is compatible with dcrdata. isApiCompat := semver.AnyCompatible(compatibleChainServerAPIs, nodeVer) if !isApiCompat { return nil, nodeVer, fmt.Errorf("Node JSON-RPC server does not have "+ "a compatible API version. Advertises %v but requires one of: %v", nodeVer, compatibleChainServerAPIs) } return dcrdClient, nodeVer, nil }
go
func ConnectNodeRPC(host, user, pass, cert string, disableTLS, disableReconnect bool, ntfnHandlers ...*rpcclient.NotificationHandlers) (*rpcclient.Client, semver.Semver, error) { var dcrdCerts []byte var err error var nodeVer semver.Semver if !disableTLS { dcrdCerts, err = ioutil.ReadFile(cert) if err != nil { log.Errorf("Failed to read dcrd cert file at %s: %s\n", cert, err.Error()) return nil, nodeVer, err } log.Debugf("Attempting to connect to dcrd RPC %s as user %s "+ "using certificate located in %s", host, user, cert) } else { log.Debugf("Attempting to connect to dcrd RPC %s as user %s (no TLS)", host, user) } connCfgDaemon := &rpcclient.ConnConfig{ Host: host, Endpoint: "ws", // websocket User: user, Pass: pass, Certificates: dcrdCerts, DisableTLS: disableTLS, DisableAutoReconnect: disableReconnect, } var ntfnHdlrs *rpcclient.NotificationHandlers if len(ntfnHandlers) > 0 { if len(ntfnHandlers) > 1 { return nil, nodeVer, fmt.Errorf("invalid notification handler argument") } ntfnHdlrs = ntfnHandlers[0] } dcrdClient, err := rpcclient.New(connCfgDaemon, ntfnHdlrs) if err != nil { return nil, nodeVer, fmt.Errorf("Failed to start dcrd RPC client: %s", err.Error()) } // Ensure the RPC server has a compatible API version. ver, err := dcrdClient.Version() if err != nil { log.Error("Unable to get RPC version: ", err) return nil, nodeVer, fmt.Errorf("unable to get node RPC version") } dcrdVer := ver["dcrdjsonrpcapi"] nodeVer = semver.NewSemver(dcrdVer.Major, dcrdVer.Minor, dcrdVer.Patch) // Check if the dcrd RPC API version is compatible with dcrdata. isApiCompat := semver.AnyCompatible(compatibleChainServerAPIs, nodeVer) if !isApiCompat { return nil, nodeVer, fmt.Errorf("Node JSON-RPC server does not have "+ "a compatible API version. Advertises %v but requires one of: %v", nodeVer, compatibleChainServerAPIs) } return dcrdClient, nodeVer, nil }
[ "func", "ConnectNodeRPC", "(", "host", ",", "user", ",", "pass", ",", "cert", "string", ",", "disableTLS", ",", "disableReconnect", "bool", ",", "ntfnHandlers", "...", "*", "rpcclient", ".", "NotificationHandlers", ")", "(", "*", "rpcclient", ".", "Client", ",", "semver", ".", "Semver", ",", "error", ")", "{", "var", "dcrdCerts", "[", "]", "byte", "\n", "var", "err", "error", "\n", "var", "nodeVer", "semver", ".", "Semver", "\n", "if", "!", "disableTLS", "{", "dcrdCerts", ",", "err", "=", "ioutil", ".", "ReadFile", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "cert", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "nil", ",", "nodeVer", ",", "err", "\n", "}", "\n", "log", ".", "Debugf", "(", "\"", "\"", "+", "\"", "\"", ",", "host", ",", "user", ",", "cert", ")", "\n", "}", "else", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "host", ",", "user", ")", "\n", "}", "\n\n", "connCfgDaemon", ":=", "&", "rpcclient", ".", "ConnConfig", "{", "Host", ":", "host", ",", "Endpoint", ":", "\"", "\"", ",", "// websocket", "User", ":", "user", ",", "Pass", ":", "pass", ",", "Certificates", ":", "dcrdCerts", ",", "DisableTLS", ":", "disableTLS", ",", "DisableAutoReconnect", ":", "disableReconnect", ",", "}", "\n\n", "var", "ntfnHdlrs", "*", "rpcclient", ".", "NotificationHandlers", "\n", "if", "len", "(", "ntfnHandlers", ")", ">", "0", "{", "if", "len", "(", "ntfnHandlers", ")", ">", "1", "{", "return", "nil", ",", "nodeVer", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "ntfnHdlrs", "=", "ntfnHandlers", "[", "0", "]", "\n", "}", "\n", "dcrdClient", ",", "err", ":=", "rpcclient", ".", "New", "(", "connCfgDaemon", ",", "ntfnHdlrs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nodeVer", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "// Ensure the RPC server has a compatible API version.", "ver", ",", "err", ":=", "dcrdClient", ".", "Version", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "nodeVer", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "dcrdVer", ":=", "ver", "[", "\"", "\"", "]", "\n", "nodeVer", "=", "semver", ".", "NewSemver", "(", "dcrdVer", ".", "Major", ",", "dcrdVer", ".", "Minor", ",", "dcrdVer", ".", "Patch", ")", "\n\n", "// Check if the dcrd RPC API version is compatible with dcrdata.", "isApiCompat", ":=", "semver", ".", "AnyCompatible", "(", "compatibleChainServerAPIs", ",", "nodeVer", ")", "\n", "if", "!", "isApiCompat", "{", "return", "nil", ",", "nodeVer", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "nodeVer", ",", "compatibleChainServerAPIs", ")", "\n", "}", "\n\n", "return", "dcrdClient", ",", "nodeVer", ",", "nil", "\n", "}" ]
// ConnectNodeRPC attempts to create a new websocket connection to a dcrd node, // with the given credentials and optional notification handlers.
[ "ConnectNodeRPC", "attempts", "to", "create", "a", "new", "websocket", "connection", "to", "a", "dcrd", "node", "with", "the", "given", "credentials", "and", "optional", "notification", "handlers", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L44-L105
142,167
decred/dcrdata
rpcutils/rpcclient.go
GetBlockByHash
func GetBlockByHash(blockhash *chainhash.Hash, client BlockFetcher) (*dcrutil.Block, error) { msgBlock, err := client.GetBlock(blockhash) if err != nil { return nil, fmt.Errorf("GetBlock failed (%s): %v", blockhash, err) } block := dcrutil.NewBlock(msgBlock) return block, nil }
go
func GetBlockByHash(blockhash *chainhash.Hash, client BlockFetcher) (*dcrutil.Block, error) { msgBlock, err := client.GetBlock(blockhash) if err != nil { return nil, fmt.Errorf("GetBlock failed (%s): %v", blockhash, err) } block := dcrutil.NewBlock(msgBlock) return block, nil }
[ "func", "GetBlockByHash", "(", "blockhash", "*", "chainhash", ".", "Hash", ",", "client", "BlockFetcher", ")", "(", "*", "dcrutil", ".", "Block", ",", "error", ")", "{", "msgBlock", ",", "err", ":=", "client", ".", "GetBlock", "(", "blockhash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "blockhash", ",", "err", ")", "\n", "}", "\n", "block", ":=", "dcrutil", ".", "NewBlock", "(", "msgBlock", ")", "\n\n", "return", "block", ",", "nil", "\n", "}" ]
// GetBlockByHash gets the block with the given hash from a chain server.
[ "GetBlockByHash", "gets", "the", "block", "with", "the", "given", "hash", "from", "a", "chain", "server", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L261-L269
142,168
decred/dcrdata
rpcutils/rpcclient.go
SideChains
func SideChains(client *rpcclient.Client) ([]dcrjson.GetChainTipsResult, error) { tips, err := client.GetChainTips() if err != nil { return nil, err } return sideChainTips(tips), nil }
go
func SideChains(client *rpcclient.Client) ([]dcrjson.GetChainTipsResult, error) { tips, err := client.GetChainTips() if err != nil { return nil, err } return sideChainTips(tips), nil }
[ "func", "SideChains", "(", "client", "*", "rpcclient", ".", "Client", ")", "(", "[", "]", "dcrjson", ".", "GetChainTipsResult", ",", "error", ")", "{", "tips", ",", "err", ":=", "client", ".", "GetChainTips", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "sideChainTips", "(", "tips", ")", ",", "nil", "\n", "}" ]
// SideChains gets a slice of known side chain tips. This corresponds to the // results of the getchaintips node RPC where the block tip "status" is either // "valid-headers" or "valid-fork".
[ "SideChains", "gets", "a", "slice", "of", "known", "side", "chain", "tips", ".", "This", "corresponds", "to", "the", "results", "of", "the", "getchaintips", "node", "RPC", "where", "the", "block", "tip", "status", "is", "either", "valid", "-", "headers", "or", "valid", "-", "fork", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L274-L281
142,169
decred/dcrdata
rpcutils/rpcclient.go
GetTransactionVerboseByID
func GetTransactionVerboseByID(client *rpcclient.Client, txhash *chainhash.Hash) (*dcrjson.TxRawResult, error) { txraw, err := client.GetRawTransactionVerbose(txhash) if err != nil { log.Errorf("GetRawTransactionVerbose failed for: %v", txhash) return nil, err } return txraw, nil }
go
func GetTransactionVerboseByID(client *rpcclient.Client, txhash *chainhash.Hash) (*dcrjson.TxRawResult, error) { txraw, err := client.GetRawTransactionVerbose(txhash) if err != nil { log.Errorf("GetRawTransactionVerbose failed for: %v", txhash) return nil, err } return txraw, nil }
[ "func", "GetTransactionVerboseByID", "(", "client", "*", "rpcclient", ".", "Client", ",", "txhash", "*", "chainhash", ".", "Hash", ")", "(", "*", "dcrjson", ".", "TxRawResult", ",", "error", ")", "{", "txraw", ",", "err", ":=", "client", ".", "GetRawTransactionVerbose", "(", "txhash", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "txhash", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "txraw", ",", "nil", "\n", "}" ]
// GetTransactionVerboseByID get a transaction by transaction id
[ "GetTransactionVerboseByID", "get", "a", "transaction", "by", "transaction", "id" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L341-L348
142,170
decred/dcrdata
rpcutils/rpcclient.go
SearchRawTransaction
func SearchRawTransaction(client *rpcclient.Client, count int, address string) ([]*dcrjson.SearchRawTransactionsResult, error) { addr, err := dcrutil.DecodeAddress(address) if err != nil { log.Infof("Invalid address %s: %v", address, err) return nil, err } //change the 1000 000 number demo for now txs, err := client.SearchRawTransactionsVerbose(addr, 0, count, true, true, nil) if err != nil { log.Warnf("SearchRawTransaction failed for address %s: %v", addr, err) } return txs, nil }
go
func SearchRawTransaction(client *rpcclient.Client, count int, address string) ([]*dcrjson.SearchRawTransactionsResult, error) { addr, err := dcrutil.DecodeAddress(address) if err != nil { log.Infof("Invalid address %s: %v", address, err) return nil, err } //change the 1000 000 number demo for now txs, err := client.SearchRawTransactionsVerbose(addr, 0, count, true, true, nil) if err != nil { log.Warnf("SearchRawTransaction failed for address %s: %v", addr, err) } return txs, nil }
[ "func", "SearchRawTransaction", "(", "client", "*", "rpcclient", ".", "Client", ",", "count", "int", ",", "address", "string", ")", "(", "[", "]", "*", "dcrjson", ".", "SearchRawTransactionsResult", ",", "error", ")", "{", "addr", ",", "err", ":=", "dcrutil", ".", "DecodeAddress", "(", "address", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "address", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "//change the 1000 000 number demo for now", "txs", ",", "err", ":=", "client", ".", "SearchRawTransactionsVerbose", "(", "addr", ",", "0", ",", "count", ",", "true", ",", "true", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "addr", ",", "err", ")", "\n", "}", "\n", "return", "txs", ",", "nil", "\n", "}" ]
// SearchRawTransaction fetch transactions the belong to an // address
[ "SearchRawTransaction", "fetch", "transactions", "the", "belong", "to", "an", "address" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L352-L365
142,171
decred/dcrdata
rpcutils/rpcclient.go
CommonAncestor
func CommonAncestor(client BlockFetcher, hashA, hashB chainhash.Hash) (*chainhash.Hash, []chainhash.Hash, []chainhash.Hash, error) { if client == nil { return nil, nil, nil, errors.New("nil RPC client") } var length int var chainA, chainB []chainhash.Hash for { if length >= maxAncestorChainLength { return nil, nil, nil, ErrAncestorMaxChainLength } // Chain A blockA, err := client.GetBlock(&hashA) if err != nil { return nil, nil, nil, fmt.Errorf("Failed to get block %v: %v", hashA, err) } heightA := blockA.Header.Height // Chain B blockB, err := client.GetBlock(&hashB) if err != nil { return nil, nil, nil, fmt.Errorf("Failed to get block %v: %v", hashB, err) } heightB := blockB.Header.Height // Reach the same height on both chains before checking the loop // termination condition. At least one previous block for each chain // must be used, so that a chain tip block will not be considered a // common ancestor and it will instead be added to a chain slice. if heightA > heightB { chainA = append([]chainhash.Hash{hashA}, chainA...) length++ hashA = blockA.Header.PrevBlock continue } if heightB > heightA { chainB = append([]chainhash.Hash{hashB}, chainB...) length++ hashB = blockB.Header.PrevBlock continue } // Assert heightB == heightA if heightB != heightA { panic("you broke the code") } chainA = append([]chainhash.Hash{hashA}, chainA...) chainB = append([]chainhash.Hash{hashB}, chainB...) length++ // We are at genesis if the previous block is the zero hash. if blockA.Header.PrevBlock == zeroHash { return nil, chainA, chainB, ErrAncestorAtGenesis // no common ancestor, but the same block } hashA = blockA.Header.PrevBlock hashB = blockB.Header.PrevBlock // break here rather than for condition so inputs with equal hashes get // handled properly (with ancestor as previous block and chains // including the input blocks.) if hashA == hashB { break // hashA(==hashB) is the common ancestor. } } // hashA == hashB return &hashA, chainA, chainB, nil }
go
func CommonAncestor(client BlockFetcher, hashA, hashB chainhash.Hash) (*chainhash.Hash, []chainhash.Hash, []chainhash.Hash, error) { if client == nil { return nil, nil, nil, errors.New("nil RPC client") } var length int var chainA, chainB []chainhash.Hash for { if length >= maxAncestorChainLength { return nil, nil, nil, ErrAncestorMaxChainLength } // Chain A blockA, err := client.GetBlock(&hashA) if err != nil { return nil, nil, nil, fmt.Errorf("Failed to get block %v: %v", hashA, err) } heightA := blockA.Header.Height // Chain B blockB, err := client.GetBlock(&hashB) if err != nil { return nil, nil, nil, fmt.Errorf("Failed to get block %v: %v", hashB, err) } heightB := blockB.Header.Height // Reach the same height on both chains before checking the loop // termination condition. At least one previous block for each chain // must be used, so that a chain tip block will not be considered a // common ancestor and it will instead be added to a chain slice. if heightA > heightB { chainA = append([]chainhash.Hash{hashA}, chainA...) length++ hashA = blockA.Header.PrevBlock continue } if heightB > heightA { chainB = append([]chainhash.Hash{hashB}, chainB...) length++ hashB = blockB.Header.PrevBlock continue } // Assert heightB == heightA if heightB != heightA { panic("you broke the code") } chainA = append([]chainhash.Hash{hashA}, chainA...) chainB = append([]chainhash.Hash{hashB}, chainB...) length++ // We are at genesis if the previous block is the zero hash. if blockA.Header.PrevBlock == zeroHash { return nil, chainA, chainB, ErrAncestorAtGenesis // no common ancestor, but the same block } hashA = blockA.Header.PrevBlock hashB = blockB.Header.PrevBlock // break here rather than for condition so inputs with equal hashes get // handled properly (with ancestor as previous block and chains // including the input blocks.) if hashA == hashB { break // hashA(==hashB) is the common ancestor. } } // hashA == hashB return &hashA, chainA, chainB, nil }
[ "func", "CommonAncestor", "(", "client", "BlockFetcher", ",", "hashA", ",", "hashB", "chainhash", ".", "Hash", ")", "(", "*", "chainhash", ".", "Hash", ",", "[", "]", "chainhash", ".", "Hash", ",", "[", "]", "chainhash", ".", "Hash", ",", "error", ")", "{", "if", "client", "==", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "length", "int", "\n", "var", "chainA", ",", "chainB", "[", "]", "chainhash", ".", "Hash", "\n", "for", "{", "if", "length", ">=", "maxAncestorChainLength", "{", "return", "nil", ",", "nil", ",", "nil", ",", "ErrAncestorMaxChainLength", "\n", "}", "\n\n", "// Chain A", "blockA", ",", "err", ":=", "client", ".", "GetBlock", "(", "&", "hashA", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hashA", ",", "err", ")", "\n", "}", "\n", "heightA", ":=", "blockA", ".", "Header", ".", "Height", "\n\n", "// Chain B", "blockB", ",", "err", ":=", "client", ".", "GetBlock", "(", "&", "hashB", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hashB", ",", "err", ")", "\n", "}", "\n", "heightB", ":=", "blockB", ".", "Header", ".", "Height", "\n\n", "// Reach the same height on both chains before checking the loop", "// termination condition. At least one previous block for each chain", "// must be used, so that a chain tip block will not be considered a", "// common ancestor and it will instead be added to a chain slice.", "if", "heightA", ">", "heightB", "{", "chainA", "=", "append", "(", "[", "]", "chainhash", ".", "Hash", "{", "hashA", "}", ",", "chainA", "...", ")", "\n", "length", "++", "\n", "hashA", "=", "blockA", ".", "Header", ".", "PrevBlock", "\n", "continue", "\n", "}", "\n", "if", "heightB", ">", "heightA", "{", "chainB", "=", "append", "(", "[", "]", "chainhash", ".", "Hash", "{", "hashB", "}", ",", "chainB", "...", ")", "\n", "length", "++", "\n", "hashB", "=", "blockB", ".", "Header", ".", "PrevBlock", "\n", "continue", "\n", "}", "\n\n", "// Assert heightB == heightA", "if", "heightB", "!=", "heightA", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "chainA", "=", "append", "(", "[", "]", "chainhash", ".", "Hash", "{", "hashA", "}", ",", "chainA", "...", ")", "\n", "chainB", "=", "append", "(", "[", "]", "chainhash", ".", "Hash", "{", "hashB", "}", ",", "chainB", "...", ")", "\n", "length", "++", "\n\n", "// We are at genesis if the previous block is the zero hash.", "if", "blockA", ".", "Header", ".", "PrevBlock", "==", "zeroHash", "{", "return", "nil", ",", "chainA", ",", "chainB", ",", "ErrAncestorAtGenesis", "// no common ancestor, but the same block", "\n", "}", "\n\n", "hashA", "=", "blockA", ".", "Header", ".", "PrevBlock", "\n", "hashB", "=", "blockB", ".", "Header", ".", "PrevBlock", "\n\n", "// break here rather than for condition so inputs with equal hashes get", "// handled properly (with ancestor as previous block and chains", "// including the input blocks.)", "if", "hashA", "==", "hashB", "{", "break", "// hashA(==hashB) is the common ancestor.", "\n", "}", "\n", "}", "\n\n", "// hashA == hashB", "return", "&", "hashA", ",", "chainA", ",", "chainB", ",", "nil", "\n", "}" ]
// CommonAncestor attempts to determine the common ancestor block for two chains // specified by the hash of the chain tip block. The full chains from the tips // back to but not including the common ancestor are also returned. The first // element in the chain slices is the lowest block following the common // ancestor, while the last element is the chain tip. The common ancestor will // never by one of the chain tips. Thus, if one of the chain tips is on the // other chain, that block will be shared between the two chains, and the common // ancestor will be the previous block. However, the intended use of this // function is to find a common ancestor for two chains with no common blocks.
[ "CommonAncestor", "attempts", "to", "determine", "the", "common", "ancestor", "block", "for", "two", "chains", "specified", "by", "the", "hash", "of", "the", "chain", "tip", "block", ".", "The", "full", "chains", "from", "the", "tips", "back", "to", "but", "not", "including", "the", "common", "ancestor", "are", "also", "returned", ".", "The", "first", "element", "in", "the", "chain", "slices", "is", "the", "lowest", "block", "following", "the", "common", "ancestor", "while", "the", "last", "element", "is", "the", "chain", "tip", ".", "The", "common", "ancestor", "will", "never", "by", "one", "of", "the", "chain", "tips", ".", "Thus", "if", "one", "of", "the", "chain", "tips", "is", "on", "the", "other", "chain", "that", "block", "will", "be", "shared", "between", "the", "two", "chains", "and", "the", "common", "ancestor", "will", "be", "the", "previous", "block", ".", "However", "the", "intended", "use", "of", "this", "function", "is", "to", "find", "a", "common", "ancestor", "for", "two", "chains", "with", "no", "common", "blocks", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L376-L446
142,172
decred/dcrdata
rpcutils/rpcclient.go
OrphanedTipLength
func OrphanedTipLength(ctx context.Context, client BlockHashGetter, tipHeight int64, hashFunc func(int64) (string, error)) (int64, error) { commonHeight := tipHeight var dbHash string var err error var dcrdHash *chainhash.Hash for { // Since there are no limits on the number of blocks scanned, allow // cancellation for a clean exit. select { case <-ctx.Done(): return 0, nil default: } dbHash, err = hashFunc(commonHeight) if err != nil { return -1, fmt.Errorf("Unable to retrieve block at height %d: %v", commonHeight, err) } dcrdHash, err = client.GetBlockHash(commonHeight) if err != nil { return -1, fmt.Errorf("Unable to retrive dcrd block at height %d: %v", commonHeight, err) } if dcrdHash.String() == dbHash { break } commonHeight-- if commonHeight < 0 { return -1, fmt.Errorf("Unable to find a common ancestor") } // Reorgs are soft-limited to depth 6 by dcrd. More than six blocks without // a match probably indicates an issue. if commonHeight-tipHeight == 7 { log.Warnf("No common ancestor within 6 blocks. This is abnormal") } } return tipHeight - commonHeight, nil }
go
func OrphanedTipLength(ctx context.Context, client BlockHashGetter, tipHeight int64, hashFunc func(int64) (string, error)) (int64, error) { commonHeight := tipHeight var dbHash string var err error var dcrdHash *chainhash.Hash for { // Since there are no limits on the number of blocks scanned, allow // cancellation for a clean exit. select { case <-ctx.Done(): return 0, nil default: } dbHash, err = hashFunc(commonHeight) if err != nil { return -1, fmt.Errorf("Unable to retrieve block at height %d: %v", commonHeight, err) } dcrdHash, err = client.GetBlockHash(commonHeight) if err != nil { return -1, fmt.Errorf("Unable to retrive dcrd block at height %d: %v", commonHeight, err) } if dcrdHash.String() == dbHash { break } commonHeight-- if commonHeight < 0 { return -1, fmt.Errorf("Unable to find a common ancestor") } // Reorgs are soft-limited to depth 6 by dcrd. More than six blocks without // a match probably indicates an issue. if commonHeight-tipHeight == 7 { log.Warnf("No common ancestor within 6 blocks. This is abnormal") } } return tipHeight - commonHeight, nil }
[ "func", "OrphanedTipLength", "(", "ctx", "context", ".", "Context", ",", "client", "BlockHashGetter", ",", "tipHeight", "int64", ",", "hashFunc", "func", "(", "int64", ")", "(", "string", ",", "error", ")", ")", "(", "int64", ",", "error", ")", "{", "commonHeight", ":=", "tipHeight", "\n", "var", "dbHash", "string", "\n", "var", "err", "error", "\n", "var", "dcrdHash", "*", "chainhash", ".", "Hash", "\n", "for", "{", "// Since there are no limits on the number of blocks scanned, allow", "// cancellation for a clean exit.", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "0", ",", "nil", "\n", "default", ":", "}", "\n\n", "dbHash", ",", "err", "=", "hashFunc", "(", "commonHeight", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "commonHeight", ",", "err", ")", "\n", "}", "\n", "dcrdHash", ",", "err", "=", "client", ".", "GetBlockHash", "(", "commonHeight", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "commonHeight", ",", "err", ")", "\n", "}", "\n", "if", "dcrdHash", ".", "String", "(", ")", "==", "dbHash", "{", "break", "\n", "}", "\n\n", "commonHeight", "--", "\n", "if", "commonHeight", "<", "0", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "// Reorgs are soft-limited to depth 6 by dcrd. More than six blocks without", "// a match probably indicates an issue.", "if", "commonHeight", "-", "tipHeight", "==", "7", "{", "log", ".", "Warnf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "}", "\n", "return", "tipHeight", "-", "commonHeight", ",", "nil", "\n", "}" ]
// OrphanedTipLength finds a common ancestor by iterating block heights // backwards until a common block hash is found. Unlike CommonAncestor, an // orphaned DB tip whose corresponding block is not known to dcrd will not cause // an error. The number of blocks that have been orphaned is returned. // Realistically, this should rarely be anything but 0 or 1, but no limits are // placed here on the number of blocks checked.
[ "OrphanedTipLength", "finds", "a", "common", "ancestor", "by", "iterating", "block", "heights", "backwards", "until", "a", "common", "block", "hash", "is", "found", ".", "Unlike", "CommonAncestor", "an", "orphaned", "DB", "tip", "whose", "corresponding", "block", "is", "not", "known", "to", "dcrd", "will", "not", "cause", "an", "error", ".", "The", "number", "of", "blocks", "that", "have", "been", "orphaned", "is", "returned", ".", "Realistically", "this", "should", "rarely", "be", "anything", "but", "0", "or", "1", "but", "no", "limits", "are", "placed", "here", "on", "the", "number", "of", "blocks", "checked", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L458-L497
142,173
decred/dcrdata
rpcutils/rpcclient.go
GetChainWork
func GetChainWork(client BlockFetcher, hash *chainhash.Hash) (string, error) { header, err := client.GetBlockHeaderVerbose(hash) if err != nil { return "", err } return header.ChainWork, nil }
go
func GetChainWork(client BlockFetcher, hash *chainhash.Hash) (string, error) { header, err := client.GetBlockHeaderVerbose(hash) if err != nil { return "", err } return header.ChainWork, nil }
[ "func", "GetChainWork", "(", "client", "BlockFetcher", ",", "hash", "*", "chainhash", ".", "Hash", ")", "(", "string", ",", "error", ")", "{", "header", ",", "err", ":=", "client", ".", "GetBlockHeaderVerbose", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "header", ".", "ChainWork", ",", "nil", "\n", "}" ]
// GetChainWork fetches the dcrjson.BlockHeaderVerbose and returns only the // ChainWork field as a string.
[ "GetChainWork", "fetches", "the", "dcrjson", ".", "BlockHeaderVerbose", "and", "returns", "only", "the", "ChainWork", "field", "as", "a", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L501-L507
142,174
decred/dcrdata
explorer/explorer.go
TicketStatusText
func TicketStatusText(s dbtypes.TicketSpendType, p dbtypes.TicketPoolStatus) string { switch p { case dbtypes.PoolStatusLive: return "In Live Ticket Pool" case dbtypes.PoolStatusVoted: return "Voted" case dbtypes.PoolStatusExpired: switch s { case dbtypes.TicketUnspent: return "Expired, Unrevoked" case dbtypes.TicketRevoked: return "Expired, Revoked" default: return "invalid ticket state" } case dbtypes.PoolStatusMissed: switch s { case dbtypes.TicketUnspent: return "Missed, Unrevoked" case dbtypes.TicketRevoked: return "Missed, Revoked" default: return "invalid ticket state" } default: return "Immature" } }
go
func TicketStatusText(s dbtypes.TicketSpendType, p dbtypes.TicketPoolStatus) string { switch p { case dbtypes.PoolStatusLive: return "In Live Ticket Pool" case dbtypes.PoolStatusVoted: return "Voted" case dbtypes.PoolStatusExpired: switch s { case dbtypes.TicketUnspent: return "Expired, Unrevoked" case dbtypes.TicketRevoked: return "Expired, Revoked" default: return "invalid ticket state" } case dbtypes.PoolStatusMissed: switch s { case dbtypes.TicketUnspent: return "Missed, Unrevoked" case dbtypes.TicketRevoked: return "Missed, Revoked" default: return "invalid ticket state" } default: return "Immature" } }
[ "func", "TicketStatusText", "(", "s", "dbtypes", ".", "TicketSpendType", ",", "p", "dbtypes", ".", "TicketPoolStatus", ")", "string", "{", "switch", "p", "{", "case", "dbtypes", ".", "PoolStatusLive", ":", "return", "\"", "\"", "\n", "case", "dbtypes", ".", "PoolStatusVoted", ":", "return", "\"", "\"", "\n", "case", "dbtypes", ".", "PoolStatusExpired", ":", "switch", "s", "{", "case", "dbtypes", ".", "TicketUnspent", ":", "return", "\"", "\"", "\n", "case", "dbtypes", ".", "TicketRevoked", ":", "return", "\"", "\"", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "case", "dbtypes", ".", "PoolStatusMissed", ":", "switch", "s", "{", "case", "dbtypes", ".", "TicketUnspent", ":", "return", "\"", "\"", "\n", "case", "dbtypes", ".", "TicketRevoked", ":", "return", "\"", "\"", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// TicketStatusText generates the text to display on the explorer's transaction // page for the "POOL STATUS" field.
[ "TicketStatusText", "generates", "the", "text", "to", "display", "on", "the", "explorer", "s", "transaction", "page", "for", "the", "POOL", "STATUS", "field", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorer.go#L159-L186
142,175
decred/dcrdata
explorer/explorer.go
SetDBsSyncing
func (exp *explorerUI) SetDBsSyncing(syncing bool) { exp.dbsSyncing.Store(syncing) exp.wsHub.SetDBsSyncing(syncing) }
go
func (exp *explorerUI) SetDBsSyncing(syncing bool) { exp.dbsSyncing.Store(syncing) exp.wsHub.SetDBsSyncing(syncing) }
[ "func", "(", "exp", "*", "explorerUI", ")", "SetDBsSyncing", "(", "syncing", "bool", ")", "{", "exp", ".", "dbsSyncing", ".", "Store", "(", "syncing", ")", "\n", "exp", ".", "wsHub", ".", "SetDBsSyncing", "(", "syncing", ")", "\n", "}" ]
// SetDBsSyncing is a thread-safe way to update dbsSyncing.
[ "SetDBsSyncing", "is", "a", "thread", "-", "safe", "way", "to", "update", "dbsSyncing", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorer.go#L230-L233
142,176
decred/dcrdata
explorer/explorer.go
StopWebsocketHub
func (exp *explorerUI) StopWebsocketHub() { if exp == nil { return } log.Info("Stopping websocket hub.") exp.wsHub.Stop() close(exp.xcDone) }
go
func (exp *explorerUI) StopWebsocketHub() { if exp == nil { return } log.Info("Stopping websocket hub.") exp.wsHub.Stop() close(exp.xcDone) }
[ "func", "(", "exp", "*", "explorerUI", ")", "StopWebsocketHub", "(", ")", "{", "if", "exp", "==", "nil", "{", "return", "\n", "}", "\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "exp", ".", "wsHub", ".", "Stop", "(", ")", "\n", "close", "(", "exp", ".", "xcDone", ")", "\n", "}" ]
// StopWebsocketHub stops the websocket hub
[ "StopWebsocketHub", "stops", "the", "websocket", "hub" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorer.go#L260-L267
142,177
decred/dcrdata
explorer/explorer.go
Height
func (exp *explorerUI) Height() int64 { exp.pageData.RLock() defer exp.pageData.RUnlock() if exp.pageData.BlockInfo.BlockBasic == nil { // If exp.pageData.BlockInfo.BlockBasic has not yet been set return: return -1 } return exp.pageData.BlockInfo.Height }
go
func (exp *explorerUI) Height() int64 { exp.pageData.RLock() defer exp.pageData.RUnlock() if exp.pageData.BlockInfo.BlockBasic == nil { // If exp.pageData.BlockInfo.BlockBasic has not yet been set return: return -1 } return exp.pageData.BlockInfo.Height }
[ "func", "(", "exp", "*", "explorerUI", ")", "Height", "(", ")", "int64", "{", "exp", ".", "pageData", ".", "RLock", "(", ")", "\n", "defer", "exp", ".", "pageData", ".", "RUnlock", "(", ")", "\n\n", "if", "exp", ".", "pageData", ".", "BlockInfo", ".", "BlockBasic", "==", "nil", "{", "// If exp.pageData.BlockInfo.BlockBasic has not yet been set return:", "return", "-", "1", "\n", "}", "\n\n", "return", "exp", ".", "pageData", ".", "BlockInfo", ".", "Height", "\n", "}" ]
// Height returns the height of the current block data.
[ "Height", "returns", "the", "height", "of", "the", "current", "block", "data", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorer.go#L375-L385
142,178
decred/dcrdata
explorer/explorer.go
LastBlock
func (exp *explorerUI) LastBlock() (lastBlockHash string, lastBlock int64, lastBlockTime int64) { exp.pageData.RLock() defer exp.pageData.RUnlock() if exp.pageData.BlockInfo.BlockBasic == nil { // If exp.pageData.BlockInfo.BlockBasic has not yet been set return: lastBlock, lastBlockTime = -1, -1 return } lastBlock = exp.pageData.BlockInfo.Height lastBlockTime = exp.pageData.BlockInfo.BlockTime.UNIX() lastBlockHash = exp.pageData.BlockInfo.Hash return }
go
func (exp *explorerUI) LastBlock() (lastBlockHash string, lastBlock int64, lastBlockTime int64) { exp.pageData.RLock() defer exp.pageData.RUnlock() if exp.pageData.BlockInfo.BlockBasic == nil { // If exp.pageData.BlockInfo.BlockBasic has not yet been set return: lastBlock, lastBlockTime = -1, -1 return } lastBlock = exp.pageData.BlockInfo.Height lastBlockTime = exp.pageData.BlockInfo.BlockTime.UNIX() lastBlockHash = exp.pageData.BlockInfo.Hash return }
[ "func", "(", "exp", "*", "explorerUI", ")", "LastBlock", "(", ")", "(", "lastBlockHash", "string", ",", "lastBlock", "int64", ",", "lastBlockTime", "int64", ")", "{", "exp", ".", "pageData", ".", "RLock", "(", ")", "\n", "defer", "exp", ".", "pageData", ".", "RUnlock", "(", ")", "\n\n", "if", "exp", ".", "pageData", ".", "BlockInfo", ".", "BlockBasic", "==", "nil", "{", "// If exp.pageData.BlockInfo.BlockBasic has not yet been set return:", "lastBlock", ",", "lastBlockTime", "=", "-", "1", ",", "-", "1", "\n", "return", "\n", "}", "\n\n", "lastBlock", "=", "exp", ".", "pageData", ".", "BlockInfo", ".", "Height", "\n", "lastBlockTime", "=", "exp", ".", "pageData", ".", "BlockInfo", ".", "BlockTime", ".", "UNIX", "(", ")", "\n", "lastBlockHash", "=", "exp", ".", "pageData", ".", "BlockInfo", ".", "Hash", "\n", "return", "\n", "}" ]
// LastBlock returns the last block hash, height and time.
[ "LastBlock", "returns", "the", "last", "block", "hash", "height", "and", "time", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorer.go#L388-L402
142,179
decred/dcrdata
explorer/explorer.go
MempoolID
func (exp *explorerUI) MempoolID() uint64 { exp.invsMtx.RLock() defer exp.invsMtx.RUnlock() return exp.invs.ID() }
go
func (exp *explorerUI) MempoolID() uint64 { exp.invsMtx.RLock() defer exp.invsMtx.RUnlock() return exp.invs.ID() }
[ "func", "(", "exp", "*", "explorerUI", ")", "MempoolID", "(", ")", "uint64", "{", "exp", ".", "invsMtx", ".", "RLock", "(", ")", "\n", "defer", "exp", ".", "invsMtx", ".", "RUnlock", "(", ")", "\n", "return", "exp", ".", "invs", ".", "ID", "(", ")", "\n", "}" ]
// MempoolID safely fetches the current mempool inventory ID.
[ "MempoolID", "safely", "fetches", "the", "current", "mempool", "inventory", "ID", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorer.go#L412-L416
142,180
decred/dcrdata
explorer/explorer.go
simulateASR
func (exp *explorerUI) simulateASR(StartingDCRBalance float64, IntegerTicketQty bool, CurrentStakePercent float64, ActualCoinbase float64, CurrentBlockNum float64, ActualTicketPrice float64) (ASR float64, ReturnTable string) { // Calculations are only useful on mainnet. Short circuit calculations if // on any other version of chain params. if exp.ChainParams.Name != "mainnet" { return 0, "" } BlocksPerDay := 86400 / exp.ChainParams.TargetTimePerBlock.Seconds() BlocksPerYear := 365 * BlocksPerDay TicketsPurchased := float64(0) StakeRewardAtBlock := func(blocknum float64) float64 { // Option 1: RPC Call Subsidy := exp.blockData.BlockSubsidy(int64(blocknum), 1) return dcrutil.Amount(Subsidy.PoS).ToCoin() // Option 2: Calculation // epoch := math.Floor(blocknum / float64(exp.ChainParams.SubsidyReductionInterval)) // RewardProportionPerVote := float64(exp.ChainParams.StakeRewardProportion) / (10 * float64(exp.ChainParams.TicketsPerBlock)) // return float64(RewardProportionPerVote) * dcrutil.Amount(exp.ChainParams.BaseSubsidy).ToCoin() * // math.Pow(float64(exp.ChainParams.MulSubsidy)/float64(exp.ChainParams.DivSubsidy), epoch) } MaxCoinSupplyAtBlock := func(blocknum float64) float64 { // 4th order poly best fit curve to Decred mainnet emissions plot. // Curve fit was done with 0 Y intercept and Pre-Mine added after. return (-9E-19*math.Pow(blocknum, 4) + 7E-12*math.Pow(blocknum, 3) - 2E-05*math.Pow(blocknum, 2) + 29.757*blocknum + 76963 + 1680000) // Premine 1.68M } CoinAdjustmentFactor := ActualCoinbase / MaxCoinSupplyAtBlock(CurrentBlockNum) TheoreticalTicketPrice := func(blocknum float64) float64 { ProjectedCoinsCirculating := MaxCoinSupplyAtBlock(blocknum) * CoinAdjustmentFactor * CurrentStakePercent TicketPoolSize := (float64(exp.MeanVotingBlocks) + float64(exp.ChainParams.TicketMaturity) + float64(exp.ChainParams.CoinbaseMaturity)) * float64(exp.ChainParams.TicketsPerBlock) return ProjectedCoinsCirculating / TicketPoolSize } TicketAdjustmentFactor := ActualTicketPrice / TheoreticalTicketPrice(CurrentBlockNum) // Prepare for simulation simblock := CurrentBlockNum TicketPrice := ActualTicketPrice DCRBalance := StartingDCRBalance ReturnTable += fmt.Sprintf("\n\nBLOCKNUM DCR TICKETS TKT_PRICE TKT_REWRD ACTION\n") ReturnTable += fmt.Sprintf("%8d %9.2f %8.1f %9.2f %9.2f INIT\n", int64(simblock), DCRBalance, TicketsPurchased, TicketPrice, StakeRewardAtBlock(simblock)) for simblock < (BlocksPerYear + CurrentBlockNum) { // Simulate a Purchase on simblock TicketPrice = TheoreticalTicketPrice(simblock) * TicketAdjustmentFactor if IntegerTicketQty { // Use this to simulate integer qtys of tickets up to max funds TicketsPurchased = math.Floor(DCRBalance / TicketPrice) } else { // Use this to simulate ALL funds used to buy tickets - even fractional tickets // which is actually not possible TicketsPurchased = (DCRBalance / TicketPrice) } DCRBalance -= (TicketPrice * TicketsPurchased) ReturnTable += fmt.Sprintf("%8d %9.2f %8.1f %9.2f %9.2f BUY\n", int64(simblock), DCRBalance, TicketsPurchased, TicketPrice, StakeRewardAtBlock(simblock)) // Move forward to average vote simblock += (float64(exp.ChainParams.TicketMaturity) + float64(exp.MeanVotingBlocks)) ReturnTable += fmt.Sprintf("%8d %9.2f %8.1f %9.2f %9.2f VOTE\n", int64(simblock), DCRBalance, TicketsPurchased, (TheoreticalTicketPrice(simblock) * TicketAdjustmentFactor), StakeRewardAtBlock(simblock)) // Simulate return of funds DCRBalance += (TicketPrice * TicketsPurchased) // Simulate reward DCRBalance += (StakeRewardAtBlock(simblock) * TicketsPurchased) TicketsPurchased = 0 // Move forward to coinbase maturity simblock += float64(exp.ChainParams.CoinbaseMaturity) ReturnTable += fmt.Sprintf("%8d %9.2f %8.1f %9.2f %9.2f REWARD\n", int64(simblock), DCRBalance, TicketsPurchased, (TheoreticalTicketPrice(simblock) * TicketAdjustmentFactor), StakeRewardAtBlock(simblock)) // Need to receive funds before we can use them again so add 1 block simblock++ } // Scale down to exactly 365 days SimulationReward := ((DCRBalance - StartingDCRBalance) / StartingDCRBalance) * 100 ASR = (BlocksPerYear / (simblock - CurrentBlockNum)) * SimulationReward ReturnTable += fmt.Sprintf("ASR over 365 Days is %.2f.\n", ASR) return }
go
func (exp *explorerUI) simulateASR(StartingDCRBalance float64, IntegerTicketQty bool, CurrentStakePercent float64, ActualCoinbase float64, CurrentBlockNum float64, ActualTicketPrice float64) (ASR float64, ReturnTable string) { // Calculations are only useful on mainnet. Short circuit calculations if // on any other version of chain params. if exp.ChainParams.Name != "mainnet" { return 0, "" } BlocksPerDay := 86400 / exp.ChainParams.TargetTimePerBlock.Seconds() BlocksPerYear := 365 * BlocksPerDay TicketsPurchased := float64(0) StakeRewardAtBlock := func(blocknum float64) float64 { // Option 1: RPC Call Subsidy := exp.blockData.BlockSubsidy(int64(blocknum), 1) return dcrutil.Amount(Subsidy.PoS).ToCoin() // Option 2: Calculation // epoch := math.Floor(blocknum / float64(exp.ChainParams.SubsidyReductionInterval)) // RewardProportionPerVote := float64(exp.ChainParams.StakeRewardProportion) / (10 * float64(exp.ChainParams.TicketsPerBlock)) // return float64(RewardProportionPerVote) * dcrutil.Amount(exp.ChainParams.BaseSubsidy).ToCoin() * // math.Pow(float64(exp.ChainParams.MulSubsidy)/float64(exp.ChainParams.DivSubsidy), epoch) } MaxCoinSupplyAtBlock := func(blocknum float64) float64 { // 4th order poly best fit curve to Decred mainnet emissions plot. // Curve fit was done with 0 Y intercept and Pre-Mine added after. return (-9E-19*math.Pow(blocknum, 4) + 7E-12*math.Pow(blocknum, 3) - 2E-05*math.Pow(blocknum, 2) + 29.757*blocknum + 76963 + 1680000) // Premine 1.68M } CoinAdjustmentFactor := ActualCoinbase / MaxCoinSupplyAtBlock(CurrentBlockNum) TheoreticalTicketPrice := func(blocknum float64) float64 { ProjectedCoinsCirculating := MaxCoinSupplyAtBlock(blocknum) * CoinAdjustmentFactor * CurrentStakePercent TicketPoolSize := (float64(exp.MeanVotingBlocks) + float64(exp.ChainParams.TicketMaturity) + float64(exp.ChainParams.CoinbaseMaturity)) * float64(exp.ChainParams.TicketsPerBlock) return ProjectedCoinsCirculating / TicketPoolSize } TicketAdjustmentFactor := ActualTicketPrice / TheoreticalTicketPrice(CurrentBlockNum) // Prepare for simulation simblock := CurrentBlockNum TicketPrice := ActualTicketPrice DCRBalance := StartingDCRBalance ReturnTable += fmt.Sprintf("\n\nBLOCKNUM DCR TICKETS TKT_PRICE TKT_REWRD ACTION\n") ReturnTable += fmt.Sprintf("%8d %9.2f %8.1f %9.2f %9.2f INIT\n", int64(simblock), DCRBalance, TicketsPurchased, TicketPrice, StakeRewardAtBlock(simblock)) for simblock < (BlocksPerYear + CurrentBlockNum) { // Simulate a Purchase on simblock TicketPrice = TheoreticalTicketPrice(simblock) * TicketAdjustmentFactor if IntegerTicketQty { // Use this to simulate integer qtys of tickets up to max funds TicketsPurchased = math.Floor(DCRBalance / TicketPrice) } else { // Use this to simulate ALL funds used to buy tickets - even fractional tickets // which is actually not possible TicketsPurchased = (DCRBalance / TicketPrice) } DCRBalance -= (TicketPrice * TicketsPurchased) ReturnTable += fmt.Sprintf("%8d %9.2f %8.1f %9.2f %9.2f BUY\n", int64(simblock), DCRBalance, TicketsPurchased, TicketPrice, StakeRewardAtBlock(simblock)) // Move forward to average vote simblock += (float64(exp.ChainParams.TicketMaturity) + float64(exp.MeanVotingBlocks)) ReturnTable += fmt.Sprintf("%8d %9.2f %8.1f %9.2f %9.2f VOTE\n", int64(simblock), DCRBalance, TicketsPurchased, (TheoreticalTicketPrice(simblock) * TicketAdjustmentFactor), StakeRewardAtBlock(simblock)) // Simulate return of funds DCRBalance += (TicketPrice * TicketsPurchased) // Simulate reward DCRBalance += (StakeRewardAtBlock(simblock) * TicketsPurchased) TicketsPurchased = 0 // Move forward to coinbase maturity simblock += float64(exp.ChainParams.CoinbaseMaturity) ReturnTable += fmt.Sprintf("%8d %9.2f %8.1f %9.2f %9.2f REWARD\n", int64(simblock), DCRBalance, TicketsPurchased, (TheoreticalTicketPrice(simblock) * TicketAdjustmentFactor), StakeRewardAtBlock(simblock)) // Need to receive funds before we can use them again so add 1 block simblock++ } // Scale down to exactly 365 days SimulationReward := ((DCRBalance - StartingDCRBalance) / StartingDCRBalance) * 100 ASR = (BlocksPerYear / (simblock - CurrentBlockNum)) * SimulationReward ReturnTable += fmt.Sprintf("ASR over 365 Days is %.2f.\n", ASR) return }
[ "func", "(", "exp", "*", "explorerUI", ")", "simulateASR", "(", "StartingDCRBalance", "float64", ",", "IntegerTicketQty", "bool", ",", "CurrentStakePercent", "float64", ",", "ActualCoinbase", "float64", ",", "CurrentBlockNum", "float64", ",", "ActualTicketPrice", "float64", ")", "(", "ASR", "float64", ",", "ReturnTable", "string", ")", "{", "// Calculations are only useful on mainnet. Short circuit calculations if", "// on any other version of chain params.", "if", "exp", ".", "ChainParams", ".", "Name", "!=", "\"", "\"", "{", "return", "0", ",", "\"", "\"", "\n", "}", "\n\n", "BlocksPerDay", ":=", "86400", "/", "exp", ".", "ChainParams", ".", "TargetTimePerBlock", ".", "Seconds", "(", ")", "\n", "BlocksPerYear", ":=", "365", "*", "BlocksPerDay", "\n", "TicketsPurchased", ":=", "float64", "(", "0", ")", "\n\n", "StakeRewardAtBlock", ":=", "func", "(", "blocknum", "float64", ")", "float64", "{", "// Option 1: RPC Call", "Subsidy", ":=", "exp", ".", "blockData", ".", "BlockSubsidy", "(", "int64", "(", "blocknum", ")", ",", "1", ")", "\n", "return", "dcrutil", ".", "Amount", "(", "Subsidy", ".", "PoS", ")", ".", "ToCoin", "(", ")", "\n\n", "// Option 2: Calculation", "// epoch := math.Floor(blocknum / float64(exp.ChainParams.SubsidyReductionInterval))", "// RewardProportionPerVote := float64(exp.ChainParams.StakeRewardProportion) / (10 * float64(exp.ChainParams.TicketsPerBlock))", "// return float64(RewardProportionPerVote) * dcrutil.Amount(exp.ChainParams.BaseSubsidy).ToCoin() *", "// \tmath.Pow(float64(exp.ChainParams.MulSubsidy)/float64(exp.ChainParams.DivSubsidy), epoch)", "}", "\n\n", "MaxCoinSupplyAtBlock", ":=", "func", "(", "blocknum", "float64", ")", "float64", "{", "// 4th order poly best fit curve to Decred mainnet emissions plot.", "// Curve fit was done with 0 Y intercept and Pre-Mine added after.", "return", "(", "-", "9E-19", "*", "math", ".", "Pow", "(", "blocknum", ",", "4", ")", "+", "7E-12", "*", "math", ".", "Pow", "(", "blocknum", ",", "3", ")", "-", "2E-05", "*", "math", ".", "Pow", "(", "blocknum", ",", "2", ")", "+", "29.757", "*", "blocknum", "+", "76963", "+", "1680000", ")", "// Premine 1.68M", "\n\n", "}", "\n\n", "CoinAdjustmentFactor", ":=", "ActualCoinbase", "/", "MaxCoinSupplyAtBlock", "(", "CurrentBlockNum", ")", "\n\n", "TheoreticalTicketPrice", ":=", "func", "(", "blocknum", "float64", ")", "float64", "{", "ProjectedCoinsCirculating", ":=", "MaxCoinSupplyAtBlock", "(", "blocknum", ")", "*", "CoinAdjustmentFactor", "*", "CurrentStakePercent", "\n", "TicketPoolSize", ":=", "(", "float64", "(", "exp", ".", "MeanVotingBlocks", ")", "+", "float64", "(", "exp", ".", "ChainParams", ".", "TicketMaturity", ")", "+", "float64", "(", "exp", ".", "ChainParams", ".", "CoinbaseMaturity", ")", ")", "*", "float64", "(", "exp", ".", "ChainParams", ".", "TicketsPerBlock", ")", "\n", "return", "ProjectedCoinsCirculating", "/", "TicketPoolSize", "\n\n", "}", "\n", "TicketAdjustmentFactor", ":=", "ActualTicketPrice", "/", "TheoreticalTicketPrice", "(", "CurrentBlockNum", ")", "\n\n", "// Prepare for simulation", "simblock", ":=", "CurrentBlockNum", "\n", "TicketPrice", ":=", "ActualTicketPrice", "\n", "DCRBalance", ":=", "StartingDCRBalance", "\n\n", "ReturnTable", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\\n", "\"", ")", "\n", "ReturnTable", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "int64", "(", "simblock", ")", ",", "DCRBalance", ",", "TicketsPurchased", ",", "TicketPrice", ",", "StakeRewardAtBlock", "(", "simblock", ")", ")", "\n\n", "for", "simblock", "<", "(", "BlocksPerYear", "+", "CurrentBlockNum", ")", "{", "// Simulate a Purchase on simblock", "TicketPrice", "=", "TheoreticalTicketPrice", "(", "simblock", ")", "*", "TicketAdjustmentFactor", "\n\n", "if", "IntegerTicketQty", "{", "// Use this to simulate integer qtys of tickets up to max funds", "TicketsPurchased", "=", "math", ".", "Floor", "(", "DCRBalance", "/", "TicketPrice", ")", "\n", "}", "else", "{", "// Use this to simulate ALL funds used to buy tickets - even fractional tickets", "// which is actually not possible", "TicketsPurchased", "=", "(", "DCRBalance", "/", "TicketPrice", ")", "\n", "}", "\n\n", "DCRBalance", "-=", "(", "TicketPrice", "*", "TicketsPurchased", ")", "\n", "ReturnTable", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "int64", "(", "simblock", ")", ",", "DCRBalance", ",", "TicketsPurchased", ",", "TicketPrice", ",", "StakeRewardAtBlock", "(", "simblock", ")", ")", "\n\n", "// Move forward to average vote", "simblock", "+=", "(", "float64", "(", "exp", ".", "ChainParams", ".", "TicketMaturity", ")", "+", "float64", "(", "exp", ".", "MeanVotingBlocks", ")", ")", "\n", "ReturnTable", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "int64", "(", "simblock", ")", ",", "DCRBalance", ",", "TicketsPurchased", ",", "(", "TheoreticalTicketPrice", "(", "simblock", ")", "*", "TicketAdjustmentFactor", ")", ",", "StakeRewardAtBlock", "(", "simblock", ")", ")", "\n\n", "// Simulate return of funds", "DCRBalance", "+=", "(", "TicketPrice", "*", "TicketsPurchased", ")", "\n\n", "// Simulate reward", "DCRBalance", "+=", "(", "StakeRewardAtBlock", "(", "simblock", ")", "*", "TicketsPurchased", ")", "\n", "TicketsPurchased", "=", "0", "\n\n", "// Move forward to coinbase maturity", "simblock", "+=", "float64", "(", "exp", ".", "ChainParams", ".", "CoinbaseMaturity", ")", "\n\n", "ReturnTable", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "int64", "(", "simblock", ")", ",", "DCRBalance", ",", "TicketsPurchased", ",", "(", "TheoreticalTicketPrice", "(", "simblock", ")", "*", "TicketAdjustmentFactor", ")", ",", "StakeRewardAtBlock", "(", "simblock", ")", ")", "\n\n", "// Need to receive funds before we can use them again so add 1 block", "simblock", "++", "\n", "}", "\n\n", "// Scale down to exactly 365 days", "SimulationReward", ":=", "(", "(", "DCRBalance", "-", "StartingDCRBalance", ")", "/", "StartingDCRBalance", ")", "*", "100", "\n", "ASR", "=", "(", "BlocksPerYear", "/", "(", "simblock", "-", "CurrentBlockNum", ")", ")", "*", "SimulationReward", "\n", "ReturnTable", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "ASR", ")", "\n", "return", "\n", "}" ]
// Simulate ticket purchase and re-investment over a full year for a given // starting amount of DCR and calculation parameters. Generate a TEXT table of // the simulation results that can optionally be used for future expansion of // dcrdata functionality.
[ "Simulate", "ticket", "purchase", "and", "re", "-", "investment", "over", "a", "full", "year", "for", "a", "given", "starting", "amount", "of", "DCR", "and", "calculation", "parameters", ".", "Generate", "a", "TEXT", "table", "of", "the", "simulation", "results", "that", "can", "optionally", "be", "used", "for", "future", "expansion", "of", "dcrdata", "functionality", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorer.go#L629-L736
142,181
decred/dcrdata
explorer/explorer.go
mempoolTime
func (exp *explorerUI) mempoolTime(txid string) types.TimeDef { exp.invsMtx.RLock() defer exp.invsMtx.RUnlock() tx, found := exp.invs.Tx(txid) if !found { return types.NewTimeDefFromUNIX(0) } return types.NewTimeDefFromUNIX(tx.Time) }
go
func (exp *explorerUI) mempoolTime(txid string) types.TimeDef { exp.invsMtx.RLock() defer exp.invsMtx.RUnlock() tx, found := exp.invs.Tx(txid) if !found { return types.NewTimeDefFromUNIX(0) } return types.NewTimeDefFromUNIX(tx.Time) }
[ "func", "(", "exp", "*", "explorerUI", ")", "mempoolTime", "(", "txid", "string", ")", "types", ".", "TimeDef", "{", "exp", ".", "invsMtx", ".", "RLock", "(", ")", "\n", "defer", "exp", ".", "invsMtx", ".", "RUnlock", "(", ")", "\n", "tx", ",", "found", ":=", "exp", ".", "invs", ".", "Tx", "(", "txid", ")", "\n", "if", "!", "found", "{", "return", "types", ".", "NewTimeDefFromUNIX", "(", "0", ")", "\n", "}", "\n", "return", "types", ".", "NewTimeDefFromUNIX", "(", "tx", ".", "Time", ")", "\n", "}" ]
// mempoolTime is the TimeDef that the transaction was received in DCRData, or // else a zero-valued TimeDef if no transaction is found.
[ "mempoolTime", "is", "the", "TimeDef", "that", "the", "transaction", "was", "received", "in", "DCRData", "or", "else", "a", "zero", "-", "valued", "TimeDef", "if", "no", "transaction", "is", "found", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/explorer.go#L795-L803
142,182
decred/dcrdata
semver/semver.go
NewSemver
func NewSemver(major, minor, patch uint32) Semver { return Semver{major, minor, patch} }
go
func NewSemver(major, minor, patch uint32) Semver { return Semver{major, minor, patch} }
[ "func", "NewSemver", "(", "major", ",", "minor", ",", "patch", "uint32", ")", "Semver", "{", "return", "Semver", "{", "major", ",", "minor", ",", "patch", "}", "\n", "}" ]
// NewSemver returns a new Semver with the version major.minor.patch
[ "NewSemver", "returns", "a", "new", "Semver", "with", "the", "version", "major", ".", "minor", ".", "patch" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/semver/semver.go#L14-L16
142,183
decred/dcrdata
semver/semver.go
Compatible
func Compatible(required, actual Semver) bool { switch { case required.major != actual.major: return false case required.minor > actual.minor: return false case required.minor == actual.minor && required.patch > actual.patch: return false default: return true } }
go
func Compatible(required, actual Semver) bool { switch { case required.major != actual.major: return false case required.minor > actual.minor: return false case required.minor == actual.minor && required.patch > actual.patch: return false default: return true } }
[ "func", "Compatible", "(", "required", ",", "actual", "Semver", ")", "bool", "{", "switch", "{", "case", "required", ".", "major", "!=", "actual", ".", "major", ":", "return", "false", "\n", "case", "required", ".", "minor", ">", "actual", ".", "minor", ":", "return", "false", "\n", "case", "required", ".", "minor", "==", "actual", ".", "minor", "&&", "required", ".", "patch", ">", "actual", ".", "patch", ":", "return", "false", "\n", "default", ":", "return", "true", "\n", "}", "\n", "}" ]
// Compatible decides if the actual version is compatible with the required one.
[ "Compatible", "decides", "if", "the", "actual", "version", "is", "compatible", "with", "the", "required", "one", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/semver/semver.go#L24-L35
142,184
decred/dcrdata
semver/semver.go
AnyCompatible
func AnyCompatible(compatible []Semver, actual Semver) (isApiCompat bool) { for _, v := range compatible { if Compatible(v, actual) { isApiCompat = true break } } return }
go
func AnyCompatible(compatible []Semver, actual Semver) (isApiCompat bool) { for _, v := range compatible { if Compatible(v, actual) { isApiCompat = true break } } return }
[ "func", "AnyCompatible", "(", "compatible", "[", "]", "Semver", ",", "actual", "Semver", ")", "(", "isApiCompat", "bool", ")", "{", "for", "_", ",", "v", ":=", "range", "compatible", "{", "if", "Compatible", "(", "v", ",", "actual", ")", "{", "isApiCompat", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// AnyCompatible checks if the version is compatible with any versions in a // slice of versions.
[ "AnyCompatible", "checks", "if", "the", "version", "is", "compatible", "with", "any", "versions", "in", "a", "slice", "of", "versions", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/semver/semver.go#L39-L47
142,185
decred/dcrdata
semver/semver.go
Split
func (s *Semver) Split() (uint32, uint32, uint32) { return s.major, s.minor, s.patch }
go
func (s *Semver) Split() (uint32, uint32, uint32) { return s.major, s.minor, s.patch }
[ "func", "(", "s", "*", "Semver", ")", "Split", "(", ")", "(", "uint32", ",", "uint32", ",", "uint32", ")", "{", "return", "s", ".", "major", ",", "s", ".", "minor", ",", "s", ".", "patch", "\n", "}" ]
// Split returns the major, minor and patch version.
[ "Split", "returns", "the", "major", "minor", "and", "patch", "version", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/semver/semver.go#L54-L56
142,186
decred/dcrdata
gov/politeia/proposals.go
NewProposalsDB
func NewProposalsDB(politeiaURL, dbPath string) (*ProposalDB, error) { if politeiaURL == "" { return nil, fmt.Errorf("missing politeia API URL") } if dbPath == "" { return nil, fmt.Errorf("missing db path") } _, err := os.Stat(dbPath) if err != nil && !os.IsNotExist(err) { return nil, err } db, err := storm.Open(dbPath) if err != nil { return nil, err } // Checks if the correct db version has been set. var version string err = db.Get(dbinfo, "version", &version) if err != nil && err != storm.ErrNotFound { return nil, err } if version != dbVersion.String() { // Attempt to delete the ProposalInfo bucket. if err = db.Drop(&pitypes.ProposalInfo{}); err != nil { // If error due bucket not found was returned, ignore it. if !strings.Contains(err.Error(), "not found") { return nil, fmt.Errorf("delete bucket struct failed: %v", err) } } // Set the required db version. err = db.Set(dbinfo, "version", dbVersion.String()) if err != nil { return nil, err } log.Infof("proposals.db version %v was set", dbVersion) } // Create the http client used to query the API endpoints. c := &http.Client{ Transport: &http.Transport{ MaxIdleConns: 10, IdleConnTimeout: 5 * time.Second, DisableCompression: false, }, Timeout: 30 * time.Second, } // politeiaURL should just be the domain part of the url without the API versioning. versionedPath := fmt.Sprintf("%s/api/v%d", politeiaURL, piapi.PoliteiaWWWAPIVersion) proposalDB := &ProposalDB{ dbP: db, client: c, APIURLpath: versionedPath, } return proposalDB, nil }
go
func NewProposalsDB(politeiaURL, dbPath string) (*ProposalDB, error) { if politeiaURL == "" { return nil, fmt.Errorf("missing politeia API URL") } if dbPath == "" { return nil, fmt.Errorf("missing db path") } _, err := os.Stat(dbPath) if err != nil && !os.IsNotExist(err) { return nil, err } db, err := storm.Open(dbPath) if err != nil { return nil, err } // Checks if the correct db version has been set. var version string err = db.Get(dbinfo, "version", &version) if err != nil && err != storm.ErrNotFound { return nil, err } if version != dbVersion.String() { // Attempt to delete the ProposalInfo bucket. if err = db.Drop(&pitypes.ProposalInfo{}); err != nil { // If error due bucket not found was returned, ignore it. if !strings.Contains(err.Error(), "not found") { return nil, fmt.Errorf("delete bucket struct failed: %v", err) } } // Set the required db version. err = db.Set(dbinfo, "version", dbVersion.String()) if err != nil { return nil, err } log.Infof("proposals.db version %v was set", dbVersion) } // Create the http client used to query the API endpoints. c := &http.Client{ Transport: &http.Transport{ MaxIdleConns: 10, IdleConnTimeout: 5 * time.Second, DisableCompression: false, }, Timeout: 30 * time.Second, } // politeiaURL should just be the domain part of the url without the API versioning. versionedPath := fmt.Sprintf("%s/api/v%d", politeiaURL, piapi.PoliteiaWWWAPIVersion) proposalDB := &ProposalDB{ dbP: db, client: c, APIURLpath: versionedPath, } return proposalDB, nil }
[ "func", "NewProposalsDB", "(", "politeiaURL", ",", "dbPath", "string", ")", "(", "*", "ProposalDB", ",", "error", ")", "{", "if", "politeiaURL", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "dbPath", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "_", ",", "err", ":=", "os", ".", "Stat", "(", "dbPath", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "db", ",", "err", ":=", "storm", ".", "Open", "(", "dbPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Checks if the correct db version has been set.", "var", "version", "string", "\n", "err", "=", "db", ".", "Get", "(", "dbinfo", ",", "\"", "\"", ",", "&", "version", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "storm", ".", "ErrNotFound", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "version", "!=", "dbVersion", ".", "String", "(", ")", "{", "// Attempt to delete the ProposalInfo bucket.", "if", "err", "=", "db", ".", "Drop", "(", "&", "pitypes", ".", "ProposalInfo", "{", "}", ")", ";", "err", "!=", "nil", "{", "// If error due bucket not found was returned, ignore it.", "if", "!", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Set the required db version.", "err", "=", "db", ".", "Set", "(", "dbinfo", ",", "\"", "\"", ",", "dbVersion", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "dbVersion", ")", "\n", "}", "\n\n", "// Create the http client used to query the API endpoints.", "c", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "&", "http", ".", "Transport", "{", "MaxIdleConns", ":", "10", ",", "IdleConnTimeout", ":", "5", "*", "time", ".", "Second", ",", "DisableCompression", ":", "false", ",", "}", ",", "Timeout", ":", "30", "*", "time", ".", "Second", ",", "}", "\n\n", "// politeiaURL should just be the domain part of the url without the API versioning.", "versionedPath", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "politeiaURL", ",", "piapi", ".", "PoliteiaWWWAPIVersion", ")", "\n\n", "proposalDB", ":=", "&", "ProposalDB", "{", "dbP", ":", "db", ",", "client", ":", "c", ",", "APIURLpath", ":", "versionedPath", ",", "}", "\n\n", "return", "proposalDB", ",", "nil", "\n", "}" ]
// NewProposalsDB opens an exiting database or creates a new DB instance with // the provided file name. Returns an initialized instance of proposals DB, http // client and the formatted politeia API URL path to be used. It also checks the // db version, Reindexes the db if need be and sets the required db version.
[ "NewProposalsDB", "opens", "an", "exiting", "database", "or", "creates", "a", "new", "DB", "instance", "with", "the", "provided", "file", "name", ".", "Returns", "an", "initialized", "instance", "of", "proposals", "DB", "http", "client", "and", "the", "formatted", "politeia", "API", "URL", "path", "to", "be", "used", ".", "It", "also", "checks", "the", "db", "version", "Reindexes", "the", "db", "if", "need", "be", "and", "sets", "the", "required", "db", "version", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/proposals.go#L51-L114
142,187
decred/dcrdata
gov/politeia/proposals.go
Close
func (db *ProposalDB) Close() error { if db == nil || db.dbP == nil { return nil } return db.dbP.Close() }
go
func (db *ProposalDB) Close() error { if db == nil || db.dbP == nil { return nil } return db.dbP.Close() }
[ "func", "(", "db", "*", "ProposalDB", ")", "Close", "(", ")", "error", "{", "if", "db", "==", "nil", "||", "db", ".", "dbP", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "db", ".", "dbP", ".", "Close", "(", ")", "\n", "}" ]
// Close closes the proposal DB instance created passed if it not nil.
[ "Close", "closes", "the", "proposal", "DB", "instance", "created", "passed", "if", "it", "not", "nil", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/proposals.go#L117-L123
142,188
decred/dcrdata
gov/politeia/proposals.go
generateCustomID
func generateCustomID(title string) (string, error) { if title == "" { return "", fmt.Errorf("ID not generated: invalid title found") } // regex selects only the alphanumeric characters. reg, err := regexp.Compile("[^a-zA-Z0-9]+") if err != nil { return "", err } // Replace all punctuation marks with a hyphen and make it lower case. return reg.ReplaceAllString(strings.ToLower(title), "-"), nil }
go
func generateCustomID(title string) (string, error) { if title == "" { return "", fmt.Errorf("ID not generated: invalid title found") } // regex selects only the alphanumeric characters. reg, err := regexp.Compile("[^a-zA-Z0-9]+") if err != nil { return "", err } // Replace all punctuation marks with a hyphen and make it lower case. return reg.ReplaceAllString(strings.ToLower(title), "-"), nil }
[ "func", "generateCustomID", "(", "title", "string", ")", "(", "string", ",", "error", ")", "{", "if", "title", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "// regex selects only the alphanumeric characters.", "reg", ",", "err", ":=", "regexp", ".", "Compile", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Replace all punctuation marks with a hyphen and make it lower case.", "return", "reg", ".", "ReplaceAllString", "(", "strings", ".", "ToLower", "(", "title", ")", ",", "\"", "\"", ")", ",", "nil", "\n", "}" ]
// generateCustomID generates a custom ID that is used to reference the proposals // from the frontend. The ID generated from the title by having all its // punctuation marks replaced with a hyphen and the string converted to lowercase. // According to Politeia, a proposal title has a max length of 80 characters thus // the new ID should have a max length of 80 characters.
[ "generateCustomID", "generates", "a", "custom", "ID", "that", "is", "used", "to", "reference", "the", "proposals", "from", "the", "frontend", ".", "The", "ID", "generated", "from", "the", "title", "by", "having", "all", "its", "punctuation", "marks", "replaced", "with", "a", "hyphen", "and", "the", "string", "converted", "to", "lowercase", ".", "According", "to", "Politeia", "a", "proposal", "title", "has", "a", "max", "length", "of", "80", "characters", "thus", "the", "new", "ID", "should", "have", "a", "max", "length", "of", "80", "characters", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/proposals.go#L130-L142
142,189
decred/dcrdata
gov/politeia/proposals.go
saveProposals
func (db *ProposalDB) saveProposals(URLParams string) (int, error) { copyURLParams := URLParams pageSize := int(piapi.ProposalListPageSize) var publicProposals pitypes.Proposals // Since Politeia sets page the limit as piapi.ProposalListPageSize, keep // fetching the proposals till the count of fetched proposals is less than // piapi.ProposalListPageSize. for { data, err := piclient.RetrieveAllProposals(db.client, db.APIURLpath, copyURLParams) if err != nil { return 0, err } // Break if no valid data was found. if data == nil || data.Data == nil { // Should help detect when API changes are effected on Politeia's end. log.Warn("invalid or empty data entries were returned") break } if len(data.Data) == 0 { // No updates found. break } publicProposals.Data = append(publicProposals.Data, data.Data...) // Break the loop when number the proposals returned are not equal to // piapi.ProposalListPageSize in count. if len(data.Data) != pageSize { break } copyURLParams = fmt.Sprintf("%s?after=%v", URLParams, data.Data[pageSize-1].TokenVal) } // Save all the proposals for i, val := range publicProposals.Data { var err error if val.RefID, err = generateCustomID(val.Name); err != nil { return 0, err } err = db.dbP.Save(val) // In the rare case scenario that the current proposal has a duplicate refID // append an integer value to it till it becomes unique. if err == storm.ErrAlreadyExists { c := 1 for { val.RefID += strconv.Itoa(c) err = db.dbP.Save(val) if err == nil || err != storm.ErrAlreadyExists { break } c++ } } if err != nil { return i, fmt.Errorf("save operation failed: %v", err) } } return len(publicProposals.Data), nil }
go
func (db *ProposalDB) saveProposals(URLParams string) (int, error) { copyURLParams := URLParams pageSize := int(piapi.ProposalListPageSize) var publicProposals pitypes.Proposals // Since Politeia sets page the limit as piapi.ProposalListPageSize, keep // fetching the proposals till the count of fetched proposals is less than // piapi.ProposalListPageSize. for { data, err := piclient.RetrieveAllProposals(db.client, db.APIURLpath, copyURLParams) if err != nil { return 0, err } // Break if no valid data was found. if data == nil || data.Data == nil { // Should help detect when API changes are effected on Politeia's end. log.Warn("invalid or empty data entries were returned") break } if len(data.Data) == 0 { // No updates found. break } publicProposals.Data = append(publicProposals.Data, data.Data...) // Break the loop when number the proposals returned are not equal to // piapi.ProposalListPageSize in count. if len(data.Data) != pageSize { break } copyURLParams = fmt.Sprintf("%s?after=%v", URLParams, data.Data[pageSize-1].TokenVal) } // Save all the proposals for i, val := range publicProposals.Data { var err error if val.RefID, err = generateCustomID(val.Name); err != nil { return 0, err } err = db.dbP.Save(val) // In the rare case scenario that the current proposal has a duplicate refID // append an integer value to it till it becomes unique. if err == storm.ErrAlreadyExists { c := 1 for { val.RefID += strconv.Itoa(c) err = db.dbP.Save(val) if err == nil || err != storm.ErrAlreadyExists { break } c++ } } if err != nil { return i, fmt.Errorf("save operation failed: %v", err) } } return len(publicProposals.Data), nil }
[ "func", "(", "db", "*", "ProposalDB", ")", "saveProposals", "(", "URLParams", "string", ")", "(", "int", ",", "error", ")", "{", "copyURLParams", ":=", "URLParams", "\n", "pageSize", ":=", "int", "(", "piapi", ".", "ProposalListPageSize", ")", "\n", "var", "publicProposals", "pitypes", ".", "Proposals", "\n\n", "// Since Politeia sets page the limit as piapi.ProposalListPageSize, keep", "// fetching the proposals till the count of fetched proposals is less than", "// piapi.ProposalListPageSize.", "for", "{", "data", ",", "err", ":=", "piclient", ".", "RetrieveAllProposals", "(", "db", ".", "client", ",", "db", ".", "APIURLpath", ",", "copyURLParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "// Break if no valid data was found.", "if", "data", "==", "nil", "||", "data", ".", "Data", "==", "nil", "{", "// Should help detect when API changes are effected on Politeia's end.", "log", ".", "Warn", "(", "\"", "\"", ")", "\n", "break", "\n", "}", "\n\n", "if", "len", "(", "data", ".", "Data", ")", "==", "0", "{", "// No updates found.", "break", "\n", "}", "\n\n", "publicProposals", ".", "Data", "=", "append", "(", "publicProposals", ".", "Data", ",", "data", ".", "Data", "...", ")", "\n\n", "// Break the loop when number the proposals returned are not equal to", "// piapi.ProposalListPageSize in count.", "if", "len", "(", "data", ".", "Data", ")", "!=", "pageSize", "{", "break", "\n", "}", "\n\n", "copyURLParams", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "URLParams", ",", "data", ".", "Data", "[", "pageSize", "-", "1", "]", ".", "TokenVal", ")", "\n", "}", "\n\n", "// Save all the proposals", "for", "i", ",", "val", ":=", "range", "publicProposals", ".", "Data", "{", "var", "err", "error", "\n", "if", "val", ".", "RefID", ",", "err", "=", "generateCustomID", "(", "val", ".", "Name", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "err", "=", "db", ".", "dbP", ".", "Save", "(", "val", ")", "\n\n", "// In the rare case scenario that the current proposal has a duplicate refID", "// append an integer value to it till it becomes unique.", "if", "err", "==", "storm", ".", "ErrAlreadyExists", "{", "c", ":=", "1", "\n", "for", "{", "val", ".", "RefID", "+=", "strconv", ".", "Itoa", "(", "c", ")", "\n", "err", "=", "db", ".", "dbP", ".", "Save", "(", "val", ")", "\n", "if", "err", "==", "nil", "||", "err", "!=", "storm", ".", "ErrAlreadyExists", "{", "break", "\n", "}", "\n", "c", "++", "\n", "}", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "i", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "len", "(", "publicProposals", ".", "Data", ")", ",", "nil", "\n", "}" ]
// saveProposals adds the proposals data to the db.
[ "saveProposals", "adds", "the", "proposals", "data", "to", "the", "db", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/proposals.go#L145-L211
142,190
decred/dcrdata
gov/politeia/proposals.go
AllProposals
func (db *ProposalDB) AllProposals(offset, rowsCount int, filterByVoteStatus ...int) (proposals []*pitypes.ProposalInfo, totalCount int, err error) { if db == nil || db.dbP == nil { return nil, 0, errDef } db.mtx.RLock() defer db.mtx.RUnlock() query := db.dbP.Select() if len(filterByVoteStatus) > 0 { // Filter by the votes status query = db.dbP.Select(q.Eq("VoteStatus", pitypes.VoteStatusType(filterByVoteStatus[0]))) } // Count the proposals based on the query created above. totalCount, err = query.Count(&pitypes.ProposalInfo{}) if err != nil { return } // Return the proposals listing starting with the newest. err = query.Skip(offset).Limit(rowsCount).Reverse().OrderBy("Timestamp"). Find(&proposals) if err != nil && err != storm.ErrNotFound { log.Errorf("Failed to fetch data from Proposals DB: %v", err) } else { err = nil } return }
go
func (db *ProposalDB) AllProposals(offset, rowsCount int, filterByVoteStatus ...int) (proposals []*pitypes.ProposalInfo, totalCount int, err error) { if db == nil || db.dbP == nil { return nil, 0, errDef } db.mtx.RLock() defer db.mtx.RUnlock() query := db.dbP.Select() if len(filterByVoteStatus) > 0 { // Filter by the votes status query = db.dbP.Select(q.Eq("VoteStatus", pitypes.VoteStatusType(filterByVoteStatus[0]))) } // Count the proposals based on the query created above. totalCount, err = query.Count(&pitypes.ProposalInfo{}) if err != nil { return } // Return the proposals listing starting with the newest. err = query.Skip(offset).Limit(rowsCount).Reverse().OrderBy("Timestamp"). Find(&proposals) if err != nil && err != storm.ErrNotFound { log.Errorf("Failed to fetch data from Proposals DB: %v", err) } else { err = nil } return }
[ "func", "(", "db", "*", "ProposalDB", ")", "AllProposals", "(", "offset", ",", "rowsCount", "int", ",", "filterByVoteStatus", "...", "int", ")", "(", "proposals", "[", "]", "*", "pitypes", ".", "ProposalInfo", ",", "totalCount", "int", ",", "err", "error", ")", "{", "if", "db", "==", "nil", "||", "db", ".", "dbP", "==", "nil", "{", "return", "nil", ",", "0", ",", "errDef", "\n", "}", "\n\n", "db", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "query", ":=", "db", ".", "dbP", ".", "Select", "(", ")", "\n", "if", "len", "(", "filterByVoteStatus", ")", ">", "0", "{", "// Filter by the votes status", "query", "=", "db", ".", "dbP", ".", "Select", "(", "q", ".", "Eq", "(", "\"", "\"", ",", "pitypes", ".", "VoteStatusType", "(", "filterByVoteStatus", "[", "0", "]", ")", ")", ")", "\n", "}", "\n\n", "// Count the proposals based on the query created above.", "totalCount", ",", "err", "=", "query", ".", "Count", "(", "&", "pitypes", ".", "ProposalInfo", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "// Return the proposals listing starting with the newest.", "err", "=", "query", ".", "Skip", "(", "offset", ")", ".", "Limit", "(", "rowsCount", ")", ".", "Reverse", "(", ")", ".", "OrderBy", "(", "\"", "\"", ")", ".", "Find", "(", "&", "proposals", ")", "\n\n", "if", "err", "!=", "nil", "&&", "err", "!=", "storm", ".", "ErrNotFound", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "err", "=", "nil", "\n", "}", "\n\n", "return", "\n", "}" ]
// AllProposals fetches all the proposals data saved to the db.
[ "AllProposals", "fetches", "all", "the", "proposals", "data", "saved", "to", "the", "db", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/proposals.go#L214-L248
142,191
decred/dcrdata
gov/politeia/proposals.go
ProposalByToken
func (db *ProposalDB) ProposalByToken(proposalToken string) (*pitypes.ProposalInfo, error) { if db == nil || db.dbP == nil { return nil, errDef } db.mtx.RLock() defer db.mtx.RUnlock() return db.proposal("TokenVal", proposalToken) }
go
func (db *ProposalDB) ProposalByToken(proposalToken string) (*pitypes.ProposalInfo, error) { if db == nil || db.dbP == nil { return nil, errDef } db.mtx.RLock() defer db.mtx.RUnlock() return db.proposal("TokenVal", proposalToken) }
[ "func", "(", "db", "*", "ProposalDB", ")", "ProposalByToken", "(", "proposalToken", "string", ")", "(", "*", "pitypes", ".", "ProposalInfo", ",", "error", ")", "{", "if", "db", "==", "nil", "||", "db", ".", "dbP", "==", "nil", "{", "return", "nil", ",", "errDef", "\n", "}", "\n\n", "db", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "return", "db", ".", "proposal", "(", "\"", "\"", ",", "proposalToken", ")", "\n", "}" ]
// ProposalByToken returns the single proposal identified by the provided token.
[ "ProposalByToken", "returns", "the", "single", "proposal", "identified", "by", "the", "provided", "token", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/proposals.go#L251-L260
142,192
decred/dcrdata
gov/politeia/proposals.go
ProposalByRefID
func (db *ProposalDB) ProposalByRefID(RefID string) (*pitypes.ProposalInfo, error) { if db == nil || db.dbP == nil { return nil, errDef } db.mtx.RLock() defer db.mtx.RUnlock() return db.proposal("RefID", RefID) }
go
func (db *ProposalDB) ProposalByRefID(RefID string) (*pitypes.ProposalInfo, error) { if db == nil || db.dbP == nil { return nil, errDef } db.mtx.RLock() defer db.mtx.RUnlock() return db.proposal("RefID", RefID) }
[ "func", "(", "db", "*", "ProposalDB", ")", "ProposalByRefID", "(", "RefID", "string", ")", "(", "*", "pitypes", ".", "ProposalInfo", ",", "error", ")", "{", "if", "db", "==", "nil", "||", "db", ".", "dbP", "==", "nil", "{", "return", "nil", ",", "errDef", "\n", "}", "\n\n", "db", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "return", "db", ".", "proposal", "(", "\"", "\"", ",", "RefID", ")", "\n", "}" ]
// ProposalByRefID returns the single proposal identified by the provided refID. // RefID is generated from the proposal name and used as the descriptive part of // the URL to proposal details page on the
[ "ProposalByRefID", "returns", "the", "single", "proposal", "identified", "by", "the", "provided", "refID", ".", "RefID", "is", "generated", "from", "the", "proposal", "name", "and", "used", "as", "the", "descriptive", "part", "of", "the", "URL", "to", "proposal", "details", "page", "on", "the" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/proposals.go#L265-L274
142,193
decred/dcrdata
gov/politeia/proposals.go
proposal
func (db *ProposalDB) proposal(searchBy, searchTerm string) (*pitypes.ProposalInfo, error) { var pInfo pitypes.ProposalInfo err := db.dbP.Select(q.Eq(searchBy, searchTerm)).Limit(1).First(&pInfo) if err != nil { log.Errorf("Failed to fetch data from Proposals DB: %v", err) return nil, err } return &pInfo, nil }
go
func (db *ProposalDB) proposal(searchBy, searchTerm string) (*pitypes.ProposalInfo, error) { var pInfo pitypes.ProposalInfo err := db.dbP.Select(q.Eq(searchBy, searchTerm)).Limit(1).First(&pInfo) if err != nil { log.Errorf("Failed to fetch data from Proposals DB: %v", err) return nil, err } return &pInfo, nil }
[ "func", "(", "db", "*", "ProposalDB", ")", "proposal", "(", "searchBy", ",", "searchTerm", "string", ")", "(", "*", "pitypes", ".", "ProposalInfo", ",", "error", ")", "{", "var", "pInfo", "pitypes", ".", "ProposalInfo", "\n", "err", ":=", "db", ".", "dbP", ".", "Select", "(", "q", ".", "Eq", "(", "searchBy", ",", "searchTerm", ")", ")", ".", "Limit", "(", "1", ")", ".", "First", "(", "&", "pInfo", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "pInfo", ",", "nil", "\n", "}" ]
// proposal runs the query with searchBy and searchTerm parameters provided and // returns the result.
[ "proposal", "runs", "the", "query", "with", "searchBy", "and", "searchTerm", "parameters", "provided", "and", "returns", "the", "result", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/proposals.go#L278-L287
142,194
decred/dcrdata
gov/politeia/proposals.go
LastProposalsSync
func (db *ProposalDB) LastProposalsSync() int64 { db.mtx.Lock() defer db.mtx.Unlock() return db.lastSync }
go
func (db *ProposalDB) LastProposalsSync() int64 { db.mtx.Lock() defer db.mtx.Unlock() return db.lastSync }
[ "func", "(", "db", "*", "ProposalDB", ")", "LastProposalsSync", "(", ")", "int64", "{", "db", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "return", "db", ".", "lastSync", "\n", "}" ]
// LastProposalsSync returns the last time a sync to update the proposals was run // but not necessarily the last time updates were synced in proposals.db.
[ "LastProposalsSync", "returns", "the", "last", "time", "a", "sync", "to", "update", "the", "proposals", "was", "run", "but", "not", "necessarily", "the", "last", "time", "updates", "were", "synced", "in", "proposals", ".", "db", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/proposals.go#L291-L296
142,195
decred/dcrdata
gov/politeia/proposals.go
CheckProposalsUpdates
func (db *ProposalDB) CheckProposalsUpdates() error { if db == nil || db.dbP == nil { return errDef } db.mtx.Lock() defer func() { // Update the lastSync before the function exits. db.lastSync = time.Now().UTC().Unix() db.mtx.Unlock() }() // Retrieve and update all current proposals whose vote statuses is either // NotAuthorized, Authorized and Started numRecords, err := db.updateInProgressProposals() if err != nil { return err } // Retrieve and update any new proposals created since the previous // proposals were stored in the db. lastProposal, err := db.lastSavedProposal() if err != nil { return fmt.Errorf("lastSavedProposal failed: %v", err) } var queryParam string if len(lastProposal) > 0 && lastProposal[0].TokenVal != "" { queryParam = fmt.Sprintf("?after=%s", lastProposal[0].TokenVal) } n, err := db.saveProposals(queryParam) if err != nil { return err } // Add the sum of the newly added proposals. numRecords += n log.Infof("%d proposal records (politeia proposals-storm) were updated", numRecords) return nil }
go
func (db *ProposalDB) CheckProposalsUpdates() error { if db == nil || db.dbP == nil { return errDef } db.mtx.Lock() defer func() { // Update the lastSync before the function exits. db.lastSync = time.Now().UTC().Unix() db.mtx.Unlock() }() // Retrieve and update all current proposals whose vote statuses is either // NotAuthorized, Authorized and Started numRecords, err := db.updateInProgressProposals() if err != nil { return err } // Retrieve and update any new proposals created since the previous // proposals were stored in the db. lastProposal, err := db.lastSavedProposal() if err != nil { return fmt.Errorf("lastSavedProposal failed: %v", err) } var queryParam string if len(lastProposal) > 0 && lastProposal[0].TokenVal != "" { queryParam = fmt.Sprintf("?after=%s", lastProposal[0].TokenVal) } n, err := db.saveProposals(queryParam) if err != nil { return err } // Add the sum of the newly added proposals. numRecords += n log.Infof("%d proposal records (politeia proposals-storm) were updated", numRecords) return nil }
[ "func", "(", "db", "*", "ProposalDB", ")", "CheckProposalsUpdates", "(", ")", "error", "{", "if", "db", "==", "nil", "||", "db", ".", "dbP", "==", "nil", "{", "return", "errDef", "\n", "}", "\n\n", "db", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "func", "(", ")", "{", "// Update the lastSync before the function exits.", "db", ".", "lastSync", "=", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "Unix", "(", ")", "\n", "db", ".", "mtx", ".", "Unlock", "(", ")", "\n", "}", "(", ")", "\n\n", "// Retrieve and update all current proposals whose vote statuses is either", "// NotAuthorized, Authorized and Started", "numRecords", ",", "err", ":=", "db", ".", "updateInProgressProposals", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Retrieve and update any new proposals created since the previous", "// proposals were stored in the db.", "lastProposal", ",", "err", ":=", "db", ".", "lastSavedProposal", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "var", "queryParam", "string", "\n", "if", "len", "(", "lastProposal", ")", ">", "0", "&&", "lastProposal", "[", "0", "]", ".", "TokenVal", "!=", "\"", "\"", "{", "queryParam", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "lastProposal", "[", "0", "]", ".", "TokenVal", ")", "\n", "}", "\n\n", "n", ",", "err", ":=", "db", ".", "saveProposals", "(", "queryParam", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Add the sum of the newly added proposals.", "numRecords", "+=", "n", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "numRecords", ")", "\n\n", "return", "nil", "\n", "}" ]
// CheckProposalsUpdates updates the proposal changes if they exist and updates // them to the proposal db.
[ "CheckProposalsUpdates", "updates", "the", "proposal", "changes", "if", "they", "exist", "and", "updates", "them", "to", "the", "proposal", "db", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/proposals.go#L300-L343
142,196
decred/dcrdata
gov/politeia/proposals.go
updateInProgressProposals
func (db *ProposalDB) updateInProgressProposals() (int, error) { // statuses defines a list of vote statuses whose proposals may need an update. statuses := []pitypes.VoteStatusType{ pitypes.VoteStatusType(piapi.PropVoteStatusNotAuthorized), pitypes.VoteStatusType(piapi.PropVoteStatusAuthorized), pitypes.VoteStatusType(piapi.PropVoteStatusStarted), } var inProgress []*pitypes.ProposalInfo err := db.dbP.Select( q.Or( q.Eq("VoteStatus", statuses[0]), q.Eq("VoteStatus", statuses[1]), q.Eq("VoteStatus", statuses[2]), ), ).Find(&inProgress) // Return an error only if the said error is not 'not found' error. if err != nil && err != storm.ErrNotFound { return 0, err } // count defines the number of total updated records. var count int for _, val := range inProgress { proposal, err := piclient.RetrieveProposalByToken(db.client, db.APIURLpath, val.TokenVal) // Do not update if: // 1. piclient.RetrieveProposalByToken returned an error if err != nil { // Since the proposal tokens bieng updated here are already in the // proposals.db. Do not return errors found since they will still be // updated when the data is available. log.Errorf("RetrieveProposalByToken failed: %v ", err) continue } proposal.Data.ID = val.ID proposal.Data.RefID = val.RefID // 2. The new proposal data has not changed. if val.IsEqual(proposal.Data) { continue } // 4. Some or all data returned was empty or invalid. if proposal.Data.TokenVal == "" || proposal.Data.TotalVotes < val.TotalVotes { // Should help detect when API changes are effected on Politeia's end. log.Warnf("invalid or empty data entries were returned for %v", val.TokenVal) continue } err = db.dbP.Update(proposal.Data) if err != nil { return 0, fmt.Errorf("Update for %s failed with error: %v ", val.TokenVal, err) } count++ } return count, nil }
go
func (db *ProposalDB) updateInProgressProposals() (int, error) { // statuses defines a list of vote statuses whose proposals may need an update. statuses := []pitypes.VoteStatusType{ pitypes.VoteStatusType(piapi.PropVoteStatusNotAuthorized), pitypes.VoteStatusType(piapi.PropVoteStatusAuthorized), pitypes.VoteStatusType(piapi.PropVoteStatusStarted), } var inProgress []*pitypes.ProposalInfo err := db.dbP.Select( q.Or( q.Eq("VoteStatus", statuses[0]), q.Eq("VoteStatus", statuses[1]), q.Eq("VoteStatus", statuses[2]), ), ).Find(&inProgress) // Return an error only if the said error is not 'not found' error. if err != nil && err != storm.ErrNotFound { return 0, err } // count defines the number of total updated records. var count int for _, val := range inProgress { proposal, err := piclient.RetrieveProposalByToken(db.client, db.APIURLpath, val.TokenVal) // Do not update if: // 1. piclient.RetrieveProposalByToken returned an error if err != nil { // Since the proposal tokens bieng updated here are already in the // proposals.db. Do not return errors found since they will still be // updated when the data is available. log.Errorf("RetrieveProposalByToken failed: %v ", err) continue } proposal.Data.ID = val.ID proposal.Data.RefID = val.RefID // 2. The new proposal data has not changed. if val.IsEqual(proposal.Data) { continue } // 4. Some or all data returned was empty or invalid. if proposal.Data.TokenVal == "" || proposal.Data.TotalVotes < val.TotalVotes { // Should help detect when API changes are effected on Politeia's end. log.Warnf("invalid or empty data entries were returned for %v", val.TokenVal) continue } err = db.dbP.Update(proposal.Data) if err != nil { return 0, fmt.Errorf("Update for %s failed with error: %v ", val.TokenVal, err) } count++ } return count, nil }
[ "func", "(", "db", "*", "ProposalDB", ")", "updateInProgressProposals", "(", ")", "(", "int", ",", "error", ")", "{", "// statuses defines a list of vote statuses whose proposals may need an update.", "statuses", ":=", "[", "]", "pitypes", ".", "VoteStatusType", "{", "pitypes", ".", "VoteStatusType", "(", "piapi", ".", "PropVoteStatusNotAuthorized", ")", ",", "pitypes", ".", "VoteStatusType", "(", "piapi", ".", "PropVoteStatusAuthorized", ")", ",", "pitypes", ".", "VoteStatusType", "(", "piapi", ".", "PropVoteStatusStarted", ")", ",", "}", "\n\n", "var", "inProgress", "[", "]", "*", "pitypes", ".", "ProposalInfo", "\n", "err", ":=", "db", ".", "dbP", ".", "Select", "(", "q", ".", "Or", "(", "q", ".", "Eq", "(", "\"", "\"", ",", "statuses", "[", "0", "]", ")", ",", "q", ".", "Eq", "(", "\"", "\"", ",", "statuses", "[", "1", "]", ")", ",", "q", ".", "Eq", "(", "\"", "\"", ",", "statuses", "[", "2", "]", ")", ",", ")", ",", ")", ".", "Find", "(", "&", "inProgress", ")", "\n", "// Return an error only if the said error is not 'not found' error.", "if", "err", "!=", "nil", "&&", "err", "!=", "storm", ".", "ErrNotFound", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "// count defines the number of total updated records.", "var", "count", "int", "\n\n", "for", "_", ",", "val", ":=", "range", "inProgress", "{", "proposal", ",", "err", ":=", "piclient", ".", "RetrieveProposalByToken", "(", "db", ".", "client", ",", "db", ".", "APIURLpath", ",", "val", ".", "TokenVal", ")", "\n", "// Do not update if:", "// 1. piclient.RetrieveProposalByToken returned an error", "if", "err", "!=", "nil", "{", "// Since the proposal tokens bieng updated here are already in the", "// proposals.db. Do not return errors found since they will still be", "// updated when the data is available.", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "proposal", ".", "Data", ".", "ID", "=", "val", ".", "ID", "\n", "proposal", ".", "Data", ".", "RefID", "=", "val", ".", "RefID", "\n\n", "// 2. The new proposal data has not changed.", "if", "val", ".", "IsEqual", "(", "proposal", ".", "Data", ")", "{", "continue", "\n", "}", "\n\n", "// 4. Some or all data returned was empty or invalid.", "if", "proposal", ".", "Data", ".", "TokenVal", "==", "\"", "\"", "||", "proposal", ".", "Data", ".", "TotalVotes", "<", "val", ".", "TotalVotes", "{", "// Should help detect when API changes are effected on Politeia's end.", "log", ".", "Warnf", "(", "\"", "\"", ",", "val", ".", "TokenVal", ")", "\n", "continue", "\n", "}", "\n\n", "err", "=", "db", ".", "dbP", ".", "Update", "(", "proposal", ".", "Data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "val", ".", "TokenVal", ",", "err", ")", "\n", "}", "\n\n", "count", "++", "\n", "}", "\n", "return", "count", ",", "nil", "\n", "}" ]
// Proposals whose vote statuses are either NotAuthorized, Authorized or Started // are considered to be in progress. Data for the in progress proposals is // fetched from Politeia API. From the newly fetched proposals data, db update // is only made for the vote statuses without NotAuthorized status out of all // the new votes statuses fetched.
[ "Proposals", "whose", "vote", "statuses", "are", "either", "NotAuthorized", "Authorized", "or", "Started", "are", "considered", "to", "be", "in", "progress", ".", "Data", "for", "the", "in", "progress", "proposals", "is", "fetched", "from", "Politeia", "API", ".", "From", "the", "newly", "fetched", "proposals", "data", "db", "update", "is", "only", "made", "for", "the", "vote", "statuses", "without", "NotAuthorized", "status", "out", "of", "all", "the", "new", "votes", "statuses", "fetched", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/proposals.go#L355-L414
142,197
decred/dcrdata
db/dcrpg/system.go
parseUnit
func parseUnit(unit string) (multiple float64, baseUnit string, err error) { // This regular expression is defined so that it will match any input. re := regexp.MustCompile(`([-\d\.]*)\s*(.*)`) matches := re.FindStringSubmatch(unit) // One or more of the matched substrings may be "", but the base unit // substring (matches[2]) will match anything. if len(matches) != 3 { panic("inconceivable!") } // The regexp eats leading spaces, but there may be trailing spaces // remaining that should be removed. baseUnit = strings.TrimSuffix(matches[2], " ") // The numeric component is processed by strconv.ParseFloat except in the // cases of an empty string or a single "-", which is interpreted as a // negative sign. switch matches[1] { case "": multiple = 1 case "-": multiple = -1 default: multiple, err = strconv.ParseFloat(matches[1], 64) if err != nil { // If the numeric part does not parse as a valid number (e.g. // "3.2.1-"), reset the base unit and return the non-nil error. baseUnit = "" } } return }
go
func parseUnit(unit string) (multiple float64, baseUnit string, err error) { // This regular expression is defined so that it will match any input. re := regexp.MustCompile(`([-\d\.]*)\s*(.*)`) matches := re.FindStringSubmatch(unit) // One or more of the matched substrings may be "", but the base unit // substring (matches[2]) will match anything. if len(matches) != 3 { panic("inconceivable!") } // The regexp eats leading spaces, but there may be trailing spaces // remaining that should be removed. baseUnit = strings.TrimSuffix(matches[2], " ") // The numeric component is processed by strconv.ParseFloat except in the // cases of an empty string or a single "-", which is interpreted as a // negative sign. switch matches[1] { case "": multiple = 1 case "-": multiple = -1 default: multiple, err = strconv.ParseFloat(matches[1], 64) if err != nil { // If the numeric part does not parse as a valid number (e.g. // "3.2.1-"), reset the base unit and return the non-nil error. baseUnit = "" } } return }
[ "func", "parseUnit", "(", "unit", "string", ")", "(", "multiple", "float64", ",", "baseUnit", "string", ",", "err", "error", ")", "{", "// This regular expression is defined so that it will match any input.", "re", ":=", "regexp", ".", "MustCompile", "(", "`([-\\d\\.]*)\\s*(.*)`", ")", "\n", "matches", ":=", "re", ".", "FindStringSubmatch", "(", "unit", ")", "\n", "// One or more of the matched substrings may be \"\", but the base unit", "// substring (matches[2]) will match anything.", "if", "len", "(", "matches", ")", "!=", "3", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// The regexp eats leading spaces, but there may be trailing spaces", "// remaining that should be removed.", "baseUnit", "=", "strings", ".", "TrimSuffix", "(", "matches", "[", "2", "]", ",", "\"", "\"", ")", "\n\n", "// The numeric component is processed by strconv.ParseFloat except in the", "// cases of an empty string or a single \"-\", which is interpreted as a", "// negative sign.", "switch", "matches", "[", "1", "]", "{", "case", "\"", "\"", ":", "multiple", "=", "1", "\n", "case", "\"", "\"", ":", "multiple", "=", "-", "1", "\n", "default", ":", "multiple", ",", "err", "=", "strconv", ".", "ParseFloat", "(", "matches", "[", "1", "]", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "// If the numeric part does not parse as a valid number (e.g.", "// \"3.2.1-\"), reset the base unit and return the non-nil error.", "baseUnit", "=", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// parseUnit is used to separate a "unit" from pg_settings such as "8kB" into a // numeric component and a base unit string.
[ "parseUnit", "is", "used", "to", "separate", "a", "unit", "from", "pg_settings", "such", "as", "8kB", "into", "a", "numeric", "component", "and", "a", "base", "unit", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/system.go#L19-L51
142,198
decred/dcrdata
db/dcrpg/system.go
RetrievePGVersion
func RetrievePGVersion(db *sql.DB) (ver string, err error) { err = db.QueryRow(internal.RetrievePGVersion).Scan(&ver) return }
go
func RetrievePGVersion(db *sql.DB) (ver string, err error) { err = db.QueryRow(internal.RetrievePGVersion).Scan(&ver) return }
[ "func", "RetrievePGVersion", "(", "db", "*", "sql", ".", "DB", ")", "(", "ver", "string", ",", "err", "error", ")", "{", "err", "=", "db", ".", "QueryRow", "(", "internal", ".", "RetrievePGVersion", ")", ".", "Scan", "(", "&", "ver", ")", "\n", "return", "\n", "}" ]
// RetrievePGVersion retrieves the version of the connected PostgreSQL server.
[ "RetrievePGVersion", "retrieves", "the", "version", "of", "the", "connected", "PostgreSQL", "server", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/system.go#L145-L148
142,199
decred/dcrdata
db/dcrpg/system.go
RetrieveSysSettingsPerformance
func RetrieveSysSettingsPerformance(db *sql.DB) (PGSettings, error) { return retrieveSysSettings(internal.RetrieveSysSettingsPerformance, db) }
go
func RetrieveSysSettingsPerformance(db *sql.DB) (PGSettings, error) { return retrieveSysSettings(internal.RetrieveSysSettingsPerformance, db) }
[ "func", "RetrieveSysSettingsPerformance", "(", "db", "*", "sql", ".", "DB", ")", "(", "PGSettings", ",", "error", ")", "{", "return", "retrieveSysSettings", "(", "internal", ".", "RetrieveSysSettingsPerformance", ",", "db", ")", "\n", "}" ]
// RetrieveSysSettingsPerformance retrieves performance-related settings.
[ "RetrieveSysSettingsPerformance", "retrieves", "performance", "-", "related", "settings", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/system.go#L207-L209