repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
decred/dcrdata
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
decred/dcrdata
db/dcrpg/system.go
RetrieveSysSettingSyncCommit
func RetrieveSysSettingSyncCommit(db *sql.DB) (syncCommit string, err error) { err = db.QueryRow(internal.RetrieveSyncCommitSetting).Scan(&syncCommit) return }
go
func RetrieveSysSettingSyncCommit(db *sql.DB) (syncCommit string, err error) { err = db.QueryRow(internal.RetrieveSyncCommitSetting).Scan(&syncCommit) return }
[ "func", "RetrieveSysSettingSyncCommit", "(", "db", "*", "sql", ".", "DB", ")", "(", "syncCommit", "string", ",", "err", "error", ")", "{", "err", "=", "db", ".", "QueryRow", "(", "internal", ".", "RetrieveSyncCommitSetting", ")", ".", "Scan", "(", "&", "syncCommit", ")", "\n", "return", "\n", "}" ]
// RetrieveSysSettingSyncCommit retrieves the synchronous_commit setting.
[ "RetrieveSysSettingSyncCommit", "retrieves", "the", "synchronous_commit", "setting", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/system.go#L220-L223
train
decred/dcrdata
db/dcrpg/system.go
SetSynchronousCommit
func SetSynchronousCommit(db *sql.DB, syncCommit string) error { _, err := db.Exec(fmt.Sprintf(`SET synchronous_commit TO %s;`, syncCommit)) return err }
go
func SetSynchronousCommit(db *sql.DB, syncCommit string) error { _, err := db.Exec(fmt.Sprintf(`SET synchronous_commit TO %s;`, syncCommit)) return err }
[ "func", "SetSynchronousCommit", "(", "db", "*", "sql", ".", "DB", ",", "syncCommit", "string", ")", "error", "{", "_", ",", "err", ":=", "db", ".", "Exec", "(", "fmt", ".", "Sprintf", "(", "`SET synchronous_commit TO %s;`", ",", "syncCommit", ")", ")", "\n", "return", "err", "\n", "}" ]
// SetSynchronousCommit sets the synchronous_commit setting.
[ "SetSynchronousCommit", "sets", "the", "synchronous_commit", "setting", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/system.go#L226-L229
train
decred/dcrdata
db/dcrpg/system.go
CheckCurrentTimeZone
func CheckCurrentTimeZone(db *sql.DB) (currentTZ string, err error) { if err = db.QueryRow(`SHOW TIME ZONE`).Scan(&currentTZ); err != nil { err = fmt.Errorf("unable to query current time zone: %v", err) } return }
go
func CheckCurrentTimeZone(db *sql.DB) (currentTZ string, err error) { if err = db.QueryRow(`SHOW TIME ZONE`).Scan(&currentTZ); err != nil { err = fmt.Errorf("unable to query current time zone: %v", err) } return }
[ "func", "CheckCurrentTimeZone", "(", "db", "*", "sql", ".", "DB", ")", "(", "currentTZ", "string", ",", "err", "error", ")", "{", "if", "err", "=", "db", ".", "QueryRow", "(", "`SHOW TIME ZONE`", ")", ".", "Scan", "(", "&", "currentTZ", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}" ]
// CheckCurrentTimeZone queries for the currently set postgres time zone.
[ "CheckCurrentTimeZone", "queries", "for", "the", "currently", "set", "postgres", "time", "zone", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/system.go#L232-L237
train
decred/dcrdata
db/dcrpg/system.go
CheckDefaultTimeZone
func CheckDefaultTimeZone(db *sql.DB) (defaultTZ, currentTZ string, err error) { // Remember the current time zone before switching to default. currentTZ, err = CheckCurrentTimeZone(db) if err != nil { return } // Switch to DEFAULT/LOCAL. _, err = db.Exec(`SET TIME ZONE DEFAULT`) if err != nil { err = fmt.Errorf("failed to set time zone to UTC: %v", err) return } // Get the default time zone now that it is current. defaultTZ, err = CheckCurrentTimeZone(db) if err != nil { return } // Switch back to initial time zone. _, err = db.Exec(fmt.Sprintf(`SET TIME ZONE %s`, currentTZ)) if err != nil { err = fmt.Errorf("failed to set time zone back to %s: %v", currentTZ, err) } return }
go
func CheckDefaultTimeZone(db *sql.DB) (defaultTZ, currentTZ string, err error) { // Remember the current time zone before switching to default. currentTZ, err = CheckCurrentTimeZone(db) if err != nil { return } // Switch to DEFAULT/LOCAL. _, err = db.Exec(`SET TIME ZONE DEFAULT`) if err != nil { err = fmt.Errorf("failed to set time zone to UTC: %v", err) return } // Get the default time zone now that it is current. defaultTZ, err = CheckCurrentTimeZone(db) if err != nil { return } // Switch back to initial time zone. _, err = db.Exec(fmt.Sprintf(`SET TIME ZONE %s`, currentTZ)) if err != nil { err = fmt.Errorf("failed to set time zone back to %s: %v", currentTZ, err) } return }
[ "func", "CheckDefaultTimeZone", "(", "db", "*", "sql", ".", "DB", ")", "(", "defaultTZ", ",", "currentTZ", "string", ",", "err", "error", ")", "{", "// Remember the current time zone before switching to default.", "currentTZ", ",", "err", "=", "CheckCurrentTimeZone", "(", "db", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "// Switch to DEFAULT/LOCAL.", "_", ",", "err", "=", "db", ".", "Exec", "(", "`SET TIME ZONE DEFAULT`", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "// Get the default time zone now that it is current.", "defaultTZ", ",", "err", "=", "CheckCurrentTimeZone", "(", "db", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "// Switch back to initial time zone.", "_", ",", "err", "=", "db", ".", "Exec", "(", "fmt", ".", "Sprintf", "(", "`SET TIME ZONE %s`", ",", "currentTZ", ")", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "currentTZ", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}" ]
// CheckDefaultTimeZone queries for the default postgres time zone. This is the // value that would be observed if postgres were restarted using its current // configuration. The currently set time zone is also returned.
[ "CheckDefaultTimeZone", "queries", "for", "the", "default", "postgres", "time", "zone", ".", "This", "is", "the", "value", "that", "would", "be", "observed", "if", "postgres", "were", "restarted", "using", "its", "current", "configuration", ".", "The", "currently", "set", "time", "zone", "is", "also", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/system.go#L242-L268
train
decred/dcrdata
signal.go
withShutdownCancel
func withShutdownCancel(ctx context.Context) context.Context { ctx, cancel := context.WithCancel(ctx) go func() { <-shutdownSignal cancel() }() return ctx }
go
func withShutdownCancel(ctx context.Context) context.Context { ctx, cancel := context.WithCancel(ctx) go func() { <-shutdownSignal cancel() }() return ctx }
[ "func", "withShutdownCancel", "(", "ctx", "context", ".", "Context", ")", "context", ".", "Context", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "go", "func", "(", ")", "{", "<-", "shutdownSignal", "\n", "cancel", "(", ")", "\n", "}", "(", ")", "\n", "return", "ctx", "\n", "}" ]
// withShutdownCancel creates a copy of a context that is cancelled whenever // shutdown is invoked through an interrupt signal or from an JSON-RPC stop // request.
[ "withShutdownCancel", "creates", "a", "copy", "of", "a", "context", "that", "is", "cancelled", "whenever", "shutdown", "is", "invoked", "through", "an", "interrupt", "signal", "or", "from", "an", "JSON", "-", "RPC", "stop", "request", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/signal.go#L43-L50
train
decred/dcrdata
signal.go
shutdownListener
func shutdownListener() { interruptChannel := make(chan os.Signal, 1) signal.Notify(interruptChannel, signals...) // Listen for the initial shutdown signal select { case sig := <-interruptChannel: log.Infof("Received signal (%s). Shutting down...", sig) case <-shutdownRequest: log.Info("Shutdown requested. Shutting down...") } // Cancel all contexts created from withShutdownCancel. close(shutdownSignal) // Listen for any more shutdown signals and log that shutdown has already // been signaled. for { select { case <-interruptChannel: case <-shutdownRequest: } log.Info("Shutdown signaled. Already shutting down...") } }
go
func shutdownListener() { interruptChannel := make(chan os.Signal, 1) signal.Notify(interruptChannel, signals...) // Listen for the initial shutdown signal select { case sig := <-interruptChannel: log.Infof("Received signal (%s). Shutting down...", sig) case <-shutdownRequest: log.Info("Shutdown requested. Shutting down...") } // Cancel all contexts created from withShutdownCancel. close(shutdownSignal) // Listen for any more shutdown signals and log that shutdown has already // been signaled. for { select { case <-interruptChannel: case <-shutdownRequest: } log.Info("Shutdown signaled. Already shutting down...") } }
[ "func", "shutdownListener", "(", ")", "{", "interruptChannel", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "signal", ".", "Notify", "(", "interruptChannel", ",", "signals", "...", ")", "\n\n", "// Listen for the initial shutdown signal", "select", "{", "case", "sig", ":=", "<-", "interruptChannel", ":", "log", ".", "Infof", "(", "\"", "\"", ",", "sig", ")", "\n", "case", "<-", "shutdownRequest", ":", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Cancel all contexts created from withShutdownCancel.", "close", "(", "shutdownSignal", ")", "\n\n", "// Listen for any more shutdown signals and log that shutdown has already", "// been signaled.", "for", "{", "select", "{", "case", "<-", "interruptChannel", ":", "case", "<-", "shutdownRequest", ":", "}", "\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// shutdownListener listens for shutdown requests and cancels all contexts // created from withShutdownCancel. This function never returns and is intended // to be spawned in a new goroutine.
[ "shutdownListener", "listens", "for", "shutdown", "requests", "and", "cancels", "all", "contexts", "created", "from", "withShutdownCancel", ".", "This", "function", "never", "returns", "and", "is", "intended", "to", "be", "spawned", "in", "a", "new", "goroutine", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/signal.go#L61-L85
train
decred/dcrdata
pubsub/types/pubsub_types.go
IsWSClosedErr
func IsWSClosedErr(err error) (closedErr bool) { // Must use strings.Contains to catch errors like "write tcp // 127.0.0.1:7777->127.0.0.1:39196: use of closed network connection". return err != nil && strings.Contains(err.Error(), ErrWsClosed) }
go
func IsWSClosedErr(err error) (closedErr bool) { // Must use strings.Contains to catch errors like "write tcp // 127.0.0.1:7777->127.0.0.1:39196: use of closed network connection". return err != nil && strings.Contains(err.Error(), ErrWsClosed) }
[ "func", "IsWSClosedErr", "(", "err", "error", ")", "(", "closedErr", "bool", ")", "{", "// Must use strings.Contains to catch errors like \"write tcp", "// 127.0.0.1:7777->127.0.0.1:39196: use of closed network connection\".", "return", "err", "!=", "nil", "&&", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "ErrWsClosed", ")", "\n", "}" ]
// IsWSClosedErr checks if the passed error indicates a closed websocket // connection.
[ "IsWSClosedErr", "checks", "if", "the", "passed", "error", "indicates", "a", "closed", "websocket", "connection", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/types/pubsub_types.go#L20-L24
train
decred/dcrdata
pubsub/types/pubsub_types.go
IsTemporaryErr
func IsTemporaryErr(err error) bool { t, ok := err.(net.Error) return ok && t.Temporary() }
go
func IsTemporaryErr(err error) bool { t, ok := err.(net.Error) return ok && t.Temporary() }
[ "func", "IsTemporaryErr", "(", "err", "error", ")", "bool", "{", "t", ",", "ok", ":=", "err", ".", "(", "net", ".", "Error", ")", "\n", "return", "ok", "&&", "t", ".", "Temporary", "(", ")", "\n", "}" ]
// IsTemporaryErr checks if the passed error indicates a transient error.
[ "IsTemporaryErr", "checks", "if", "the", "passed", "error", "indicates", "a", "transient", "error", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/types/pubsub_types.go#L33-L36
train
decred/dcrdata
mempool/mptypes.go
Swap
func (tix TicketsDetails) Swap(i, j int) { tix[i], tix[j] = tix[j], tix[i] }
go
func (tix TicketsDetails) Swap(i, j int) { tix[i], tix[j] = tix[j], tix[i] }
[ "func", "(", "tix", "TicketsDetails", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "tix", "[", "i", "]", ",", "tix", "[", "j", "]", "=", "tix", "[", "j", "]", ",", "tix", "[", "i", "]", "\n", "}" ]
// Swap swaps TicketsDetails elements at i and j
[ "Swap", "swaps", "TicketsDetails", "elements", "at", "i", "and", "j" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/mptypes.go#L55-L57
train
decred/dcrdata
mempool/mptypes.go
Less
func (tix ByFeeRate) Less(i, j int) bool { return tix.TicketsDetails[i].FeeRate < tix.TicketsDetails[j].FeeRate }
go
func (tix ByFeeRate) Less(i, j int) bool { return tix.TicketsDetails[i].FeeRate < tix.TicketsDetails[j].FeeRate }
[ "func", "(", "tix", "ByFeeRate", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "tix", ".", "TicketsDetails", "[", "i", "]", ".", "FeeRate", "<", "tix", ".", "TicketsDetails", "[", "j", "]", ".", "FeeRate", "\n", "}" ]
// Less compares fee rates by rate_i < rate_j
[ "Less", "compares", "fee", "rates", "by", "rate_i", "<", "rate_j" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/mptypes.go#L65-L67
train
decred/dcrdata
mempool/mptypes.go
Less
func (tix ByAbsoluteFee) Less(i, j int) bool { return tix.TicketsDetails[i].Fee < tix.TicketsDetails[j].Fee }
go
func (tix ByAbsoluteFee) Less(i, j int) bool { return tix.TicketsDetails[i].Fee < tix.TicketsDetails[j].Fee }
[ "func", "(", "tix", "ByAbsoluteFee", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "tix", ".", "TicketsDetails", "[", "i", "]", ".", "Fee", "<", "tix", ".", "TicketsDetails", "[", "j", "]", ".", "Fee", "\n", "}" ]
// Less compares fee rates by fee_i < fee_j
[ "Less", "compares", "fee", "rates", "by", "fee_i", "<", "fee_j" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/mptypes.go#L75-L77
train
decred/dcrdata
db/dcrsqlite/sqlite.go
InitDB
func InitDB(dbInfo *DBInfo, shutdown func()) (*DB, error) { dbPath, err := filepath.Abs(dbInfo.FileName) if err != nil { return nil, err } // Ensures target DB-file has a parent folder parent := filepath.Dir(dbPath) err = os.MkdirAll(parent, 0755) if err != nil { return nil, err } // "shared-cache" mode has multiple connections share a single data and // schema cache. _busy_timeout helps prevent SQLITE_BUSY ("database is // locked") errors by sleeping for a certain amount of time when the // database is locked. See https://www.sqlite.org/c3ref/busy_timeout.html. dbPath = dbPath + "?cache=shared&_busy_timeout=" + DBBusyTimeout db, err := sql.Open("sqlite3", dbPath) if err != nil || db == nil { return nil, err } // Historically, SQLite did not handle concurrent writes internally, // necessitating a limitation of just 1 open connecton. With a busy_timeout // set, this is less important. With go-sqlite 1.10, this is not needed at // all since the library started compiling sqlite3 for // thread-safe/"serialized" operation (SQLITE_THREADSAFE=1). For details, // see https://sqlite.org/threadsafe.html and // https://sqlite.org/c3ref/c_config_covering_index_scan.html#sqliteconfigserialized. // The change to go-sqlite3 is // github.com/mattn/go-sqlite3@acfa60124032040b9f5a9406f5a772ee16fe845e // // db.SetMaxOpenConns(1) // These are db-wide settings that persist for the entire session. _, err = db.Exec(SetCacheSizeSQL) if err != nil { log.Error("Error setting SQLite Cache size") return nil, err } _, err = db.Exec(SetSynchrounousOffSQL) if err != nil { log.Error("Error setting SQLite synchrounous off") return nil, err } rawCreateBlockSummaryStmt := ` create table if not exists %s( hash TEXT PRIMARY KEY, height INTEGER, size INTEGER, diff FLOAT, sdiff FLOAT, time INTEGER, poolsize INTEGER, poolval FLOAT, poolavg FLOAT, winners TEXT, is_mainchain BOOL, is_valid BOOL );` createBlockSummaryStmt := fmt.Sprintf(rawCreateBlockSummaryStmt, TableNameSummaries) _, err = db.Exec(createBlockSummaryStmt) if err != nil { log.Errorf("%q: %s\n", err, createBlockSummaryStmt) return nil, err } rawCreateStakeInfoExtendedStmt := ` create table if not exists %s( hash TEXT PRIMARY KEY, height INTEGER, num_tickets INTEGER, fee_min FLOAT, fee_max FLOAT, fee_mean FLOAT, fee_med FLOAT, fee_std FLOAT, sdiff FLOAT, window_num INTEGER, window_ind INTEGER, pool_size INTEGER, pool_val FLOAT, pool_valavg FLOAT, winners TEXT );` createStakeInfoExtendedStmt := fmt.Sprintf(rawCreateStakeInfoExtendedStmt, TableNameStakeInfo) _, err = db.Exec(createStakeInfoExtendedStmt) if err != nil { log.Errorf("%q: %s\n", err, createStakeInfoExtendedStmt) return nil, err } if err = db.Ping(); err != nil { return nil, err } dataBase, err := NewDB(db, shutdown) if err != nil { return nil, err } // Table creation string are used in JustifyTableStructures // Eventually won't be needed. dataBase.rawCreateBlockSummaryStmt = rawCreateBlockSummaryStmt dataBase.rawCreateStakeInfoExtendedStmt = rawCreateStakeInfoExtendedStmt if err = dataBase.JustifyTableStructures(dbInfo); err != nil { return nil, err } return dataBase, err }
go
func InitDB(dbInfo *DBInfo, shutdown func()) (*DB, error) { dbPath, err := filepath.Abs(dbInfo.FileName) if err != nil { return nil, err } // Ensures target DB-file has a parent folder parent := filepath.Dir(dbPath) err = os.MkdirAll(parent, 0755) if err != nil { return nil, err } // "shared-cache" mode has multiple connections share a single data and // schema cache. _busy_timeout helps prevent SQLITE_BUSY ("database is // locked") errors by sleeping for a certain amount of time when the // database is locked. See https://www.sqlite.org/c3ref/busy_timeout.html. dbPath = dbPath + "?cache=shared&_busy_timeout=" + DBBusyTimeout db, err := sql.Open("sqlite3", dbPath) if err != nil || db == nil { return nil, err } // Historically, SQLite did not handle concurrent writes internally, // necessitating a limitation of just 1 open connecton. With a busy_timeout // set, this is less important. With go-sqlite 1.10, this is not needed at // all since the library started compiling sqlite3 for // thread-safe/"serialized" operation (SQLITE_THREADSAFE=1). For details, // see https://sqlite.org/threadsafe.html and // https://sqlite.org/c3ref/c_config_covering_index_scan.html#sqliteconfigserialized. // The change to go-sqlite3 is // github.com/mattn/go-sqlite3@acfa60124032040b9f5a9406f5a772ee16fe845e // // db.SetMaxOpenConns(1) // These are db-wide settings that persist for the entire session. _, err = db.Exec(SetCacheSizeSQL) if err != nil { log.Error("Error setting SQLite Cache size") return nil, err } _, err = db.Exec(SetSynchrounousOffSQL) if err != nil { log.Error("Error setting SQLite synchrounous off") return nil, err } rawCreateBlockSummaryStmt := ` create table if not exists %s( hash TEXT PRIMARY KEY, height INTEGER, size INTEGER, diff FLOAT, sdiff FLOAT, time INTEGER, poolsize INTEGER, poolval FLOAT, poolavg FLOAT, winners TEXT, is_mainchain BOOL, is_valid BOOL );` createBlockSummaryStmt := fmt.Sprintf(rawCreateBlockSummaryStmt, TableNameSummaries) _, err = db.Exec(createBlockSummaryStmt) if err != nil { log.Errorf("%q: %s\n", err, createBlockSummaryStmt) return nil, err } rawCreateStakeInfoExtendedStmt := ` create table if not exists %s( hash TEXT PRIMARY KEY, height INTEGER, num_tickets INTEGER, fee_min FLOAT, fee_max FLOAT, fee_mean FLOAT, fee_med FLOAT, fee_std FLOAT, sdiff FLOAT, window_num INTEGER, window_ind INTEGER, pool_size INTEGER, pool_val FLOAT, pool_valavg FLOAT, winners TEXT );` createStakeInfoExtendedStmt := fmt.Sprintf(rawCreateStakeInfoExtendedStmt, TableNameStakeInfo) _, err = db.Exec(createStakeInfoExtendedStmt) if err != nil { log.Errorf("%q: %s\n", err, createStakeInfoExtendedStmt) return nil, err } if err = db.Ping(); err != nil { return nil, err } dataBase, err := NewDB(db, shutdown) if err != nil { return nil, err } // Table creation string are used in JustifyTableStructures // Eventually won't be needed. dataBase.rawCreateBlockSummaryStmt = rawCreateBlockSummaryStmt dataBase.rawCreateStakeInfoExtendedStmt = rawCreateStakeInfoExtendedStmt if err = dataBase.JustifyTableStructures(dbInfo); err != nil { return nil, err } return dataBase, err }
[ "func", "InitDB", "(", "dbInfo", "*", "DBInfo", ",", "shutdown", "func", "(", ")", ")", "(", "*", "DB", ",", "error", ")", "{", "dbPath", ",", "err", ":=", "filepath", ".", "Abs", "(", "dbInfo", ".", "FileName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Ensures target DB-file has a parent folder", "parent", ":=", "filepath", ".", "Dir", "(", "dbPath", ")", "\n", "err", "=", "os", ".", "MkdirAll", "(", "parent", ",", "0755", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// \"shared-cache\" mode has multiple connections share a single data and", "// schema cache. _busy_timeout helps prevent SQLITE_BUSY (\"database is", "// locked\") errors by sleeping for a certain amount of time when the", "// database is locked. See https://www.sqlite.org/c3ref/busy_timeout.html.", "dbPath", "=", "dbPath", "+", "\"", "\"", "+", "DBBusyTimeout", "\n", "db", ",", "err", ":=", "sql", ".", "Open", "(", "\"", "\"", ",", "dbPath", ")", "\n", "if", "err", "!=", "nil", "||", "db", "==", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Historically, SQLite did not handle concurrent writes internally,", "// necessitating a limitation of just 1 open connecton. With a busy_timeout", "// set, this is less important. With go-sqlite 1.10, this is not needed at", "// all since the library started compiling sqlite3 for", "// thread-safe/\"serialized\" operation (SQLITE_THREADSAFE=1). For details,", "// see https://sqlite.org/threadsafe.html and", "// https://sqlite.org/c3ref/c_config_covering_index_scan.html#sqliteconfigserialized.", "// The change to go-sqlite3 is", "// github.com/mattn/go-sqlite3@acfa60124032040b9f5a9406f5a772ee16fe845e", "//", "// db.SetMaxOpenConns(1)", "// These are db-wide settings that persist for the entire session.", "_", ",", "err", "=", "db", ".", "Exec", "(", "SetCacheSizeSQL", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "_", ",", "err", "=", "db", ".", "Exec", "(", "SetSynchrounousOffSQL", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "rawCreateBlockSummaryStmt", ":=", "`\n \tcreate table if not exists %s(\n \thash TEXT PRIMARY KEY,\n \theight INTEGER,\n \tsize INTEGER,\n \tdiff FLOAT,\n \tsdiff FLOAT,\n \ttime INTEGER,\n \tpoolsize INTEGER,\n \tpoolval FLOAT,\n \tpoolavg FLOAT,\n \twinners TEXT,\n \tis_mainchain BOOL,\n \tis_valid BOOL\n \t);`", "\n\n", "createBlockSummaryStmt", ":=", "fmt", ".", "Sprintf", "(", "rawCreateBlockSummaryStmt", ",", "TableNameSummaries", ")", "\n\n", "_", ",", "err", "=", "db", ".", "Exec", "(", "createBlockSummaryStmt", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "err", ",", "createBlockSummaryStmt", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "rawCreateStakeInfoExtendedStmt", ":=", "`\n \tcreate table if not exists %s(\n \thash TEXT PRIMARY KEY,\n \theight INTEGER,\n \tnum_tickets INTEGER,\n \tfee_min FLOAT, fee_max FLOAT, fee_mean FLOAT,\n \tfee_med FLOAT, fee_std FLOAT,\n \tsdiff FLOAT, window_num INTEGER, window_ind INTEGER,\n \tpool_size INTEGER, pool_val FLOAT, pool_valavg FLOAT,\n \twinners TEXT\n \t);`", "\n\n", "createStakeInfoExtendedStmt", ":=", "fmt", ".", "Sprintf", "(", "rawCreateStakeInfoExtendedStmt", ",", "TableNameStakeInfo", ")", "\n\n", "_", ",", "err", "=", "db", ".", "Exec", "(", "createStakeInfoExtendedStmt", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "err", ",", "createStakeInfoExtendedStmt", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", "=", "db", ".", "Ping", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "dataBase", ",", "err", ":=", "NewDB", "(", "db", ",", "shutdown", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Table creation string are used in JustifyTableStructures", "// Eventually won't be needed.", "dataBase", ".", "rawCreateBlockSummaryStmt", "=", "rawCreateBlockSummaryStmt", "\n", "dataBase", ".", "rawCreateStakeInfoExtendedStmt", "=", "rawCreateStakeInfoExtendedStmt", "\n", "if", "err", "=", "dataBase", ".", "JustifyTableStructures", "(", "dbInfo", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "dataBase", ",", "err", "\n", "}" ]
// InitDB creates a new DB instance from a DBInfo containing the name of the // file used to back the underlying sql database.
[ "InitDB", "creates", "a", "new", "DB", "instance", "from", "a", "DBInfo", "containing", "the", "name", "of", "the", "file", "used", "to", "back", "the", "underlying", "sql", "database", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L324-L433
train
decred/dcrdata
db/dcrsqlite/sqlite.go
Store
func (db *DBDataSaver) Store(data *blockdata.BlockData, msgBlock *wire.MsgBlock) error { summary := data.ToBlockSummary() var err error // Store is assumed to be called with a mainchain block lastIsValid := msgBlock.Header.VoteBits&1 != 0 if !lastIsValid { // Update the is_valid flag in the blocks table. // Need to check whether to invalidate previous block lastBlockHash := msgBlock.Header.PrevBlock log.Infof("Setting last block %s as INVALID", lastBlockHash) // Check for genesis block isSecondBlock := lastBlockHash != chainhash.Hash{} if isSecondBlock { var lastIsMain bool lastIsMain, err = db.DB.getMainchainStatus(lastBlockHash.String()) if err != nil { return err } if lastIsMain { lastIsValid := msgBlock.Header.VoteBits&1 != 0 if !lastIsValid { err = db.DB.invalidateBlock(lastBlockHash.String()) if err != nil { return err } } } } } // Store the main chain block data, flagging any other blocks at this height // as side chain. err = db.DB.StoreBlockSummary(&summary) if err != nil { return err } select { case db.updateStatusChan <- summary.Height: default: } stakeInfoExtended := data.ToStakeInfoExtended() return db.DB.StoreStakeInfoExtended(&stakeInfoExtended) }
go
func (db *DBDataSaver) Store(data *blockdata.BlockData, msgBlock *wire.MsgBlock) error { summary := data.ToBlockSummary() var err error // Store is assumed to be called with a mainchain block lastIsValid := msgBlock.Header.VoteBits&1 != 0 if !lastIsValid { // Update the is_valid flag in the blocks table. // Need to check whether to invalidate previous block lastBlockHash := msgBlock.Header.PrevBlock log.Infof("Setting last block %s as INVALID", lastBlockHash) // Check for genesis block isSecondBlock := lastBlockHash != chainhash.Hash{} if isSecondBlock { var lastIsMain bool lastIsMain, err = db.DB.getMainchainStatus(lastBlockHash.String()) if err != nil { return err } if lastIsMain { lastIsValid := msgBlock.Header.VoteBits&1 != 0 if !lastIsValid { err = db.DB.invalidateBlock(lastBlockHash.String()) if err != nil { return err } } } } } // Store the main chain block data, flagging any other blocks at this height // as side chain. err = db.DB.StoreBlockSummary(&summary) if err != nil { return err } select { case db.updateStatusChan <- summary.Height: default: } stakeInfoExtended := data.ToStakeInfoExtended() return db.DB.StoreStakeInfoExtended(&stakeInfoExtended) }
[ "func", "(", "db", "*", "DBDataSaver", ")", "Store", "(", "data", "*", "blockdata", ".", "BlockData", ",", "msgBlock", "*", "wire", ".", "MsgBlock", ")", "error", "{", "summary", ":=", "data", ".", "ToBlockSummary", "(", ")", "\n", "var", "err", "error", "\n\n", "// Store is assumed to be called with a mainchain block", "lastIsValid", ":=", "msgBlock", ".", "Header", ".", "VoteBits", "&", "1", "!=", "0", "\n", "if", "!", "lastIsValid", "{", "// Update the is_valid flag in the blocks table.", "// Need to check whether to invalidate previous block", "lastBlockHash", ":=", "msgBlock", ".", "Header", ".", "PrevBlock", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "lastBlockHash", ")", "\n\n", "// Check for genesis block", "isSecondBlock", ":=", "lastBlockHash", "!=", "chainhash", ".", "Hash", "{", "}", "\n", "if", "isSecondBlock", "{", "var", "lastIsMain", "bool", "\n", "lastIsMain", ",", "err", "=", "db", ".", "DB", ".", "getMainchainStatus", "(", "lastBlockHash", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "lastIsMain", "{", "lastIsValid", ":=", "msgBlock", ".", "Header", ".", "VoteBits", "&", "1", "!=", "0", "\n", "if", "!", "lastIsValid", "{", "err", "=", "db", ".", "DB", ".", "invalidateBlock", "(", "lastBlockHash", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Store the main chain block data, flagging any other blocks at this height", "// as side chain.", "err", "=", "db", ".", "DB", ".", "StoreBlockSummary", "(", "&", "summary", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "select", "{", "case", "db", ".", "updateStatusChan", "<-", "summary", ".", "Height", ":", "default", ":", "}", "\n\n", "stakeInfoExtended", ":=", "data", ".", "ToStakeInfoExtended", "(", ")", "\n", "return", "db", ".", "DB", ".", "StoreStakeInfoExtended", "(", "&", "stakeInfoExtended", ")", "\n", "}" ]
// Store satisfies the blockdata.BlockDataSaver interface. This function is only // to be used for storing main chain block data. Use StoreSideBlock or // StoreBlock directly to store side chain block data.
[ "Store", "satisfies", "the", "blockdata", ".", "BlockDataSaver", "interface", ".", "This", "function", "is", "only", "to", "be", "used", "for", "storing", "main", "chain", "block", "data", ".", "Use", "StoreSideBlock", "or", "StoreBlock", "directly", "to", "store", "side", "chain", "block", "data", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L459-L505
train
decred/dcrdata
db/dcrsqlite/sqlite.go
DeleteBlock
func (db *DB) DeleteBlock(blockhash string) (NSummaryRows, NStakeInfoRows int64, err error) { // Attempt to purge the block data. NSummaryRows, NStakeInfoRows, err = db.deleteBlock(blockhash) if err != nil { return } err = db.updateHeights() return }
go
func (db *DB) DeleteBlock(blockhash string) (NSummaryRows, NStakeInfoRows int64, err error) { // Attempt to purge the block data. NSummaryRows, NStakeInfoRows, err = db.deleteBlock(blockhash) if err != nil { return } err = db.updateHeights() return }
[ "func", "(", "db", "*", "DB", ")", "DeleteBlock", "(", "blockhash", "string", ")", "(", "NSummaryRows", ",", "NStakeInfoRows", "int64", ",", "err", "error", ")", "{", "// Attempt to purge the block data.", "NSummaryRows", ",", "NStakeInfoRows", ",", "err", "=", "db", ".", "deleteBlock", "(", "blockhash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "db", ".", "updateHeights", "(", ")", "\n", "return", "\n", "}" ]
// DeleteBlock purges the summary data and stake info for the block with the // given hash. The number of rows deleted is returned.
[ "DeleteBlock", "purges", "the", "summary", "data", "and", "stake", "info", "for", "the", "block", "with", "the", "given", "hash", ".", "The", "number", "of", "rows", "deleted", "is", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L565-L574
train
decred/dcrdata
db/dcrsqlite/sqlite.go
DeleteBlocksAboveHeight
func (db *DB) DeleteBlocksAboveHeight(height int64) (NSummaryRows, NStakeInfoRows int64, err error) { // Attempt to purge the block data. NSummaryRows, NStakeInfoRows, err = db.deleteBlocksAboveHeight(height) if err != nil { return } err = db.updateHeights() return }
go
func (db *DB) DeleteBlocksAboveHeight(height int64) (NSummaryRows, NStakeInfoRows int64, err error) { // Attempt to purge the block data. NSummaryRows, NStakeInfoRows, err = db.deleteBlocksAboveHeight(height) if err != nil { return } err = db.updateHeights() return }
[ "func", "(", "db", "*", "DB", ")", "DeleteBlocksAboveHeight", "(", "height", "int64", ")", "(", "NSummaryRows", ",", "NStakeInfoRows", "int64", ",", "err", "error", ")", "{", "// Attempt to purge the block data.", "NSummaryRows", ",", "NStakeInfoRows", ",", "err", "=", "db", ".", "deleteBlocksAboveHeight", "(", "height", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "db", ".", "updateHeights", "(", ")", "\n", "return", "\n", "}" ]
// DeleteBlocksAboveHeight purges the summary data and stake info for the blocks // above the given height, including side chain blocks.
[ "DeleteBlocksAboveHeight", "purges", "the", "summary", "data", "and", "stake", "info", "for", "the", "blocks", "above", "the", "given", "height", "including", "side", "chain", "blocks", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L610-L619
train
decred/dcrdata
db/dcrsqlite/sqlite.go
invalidateBlock
func (db *DB) invalidateBlock(blockhash string) error { _, err := db.Exec(db.invalidateBlockSQL, blockhash) return db.filterError(err) }
go
func (db *DB) invalidateBlock(blockhash string) error { _, err := db.Exec(db.invalidateBlockSQL, blockhash) return db.filterError(err) }
[ "func", "(", "db", "*", "DB", ")", "invalidateBlock", "(", "blockhash", "string", ")", "error", "{", "_", ",", "err", ":=", "db", ".", "Exec", "(", "db", ".", "invalidateBlockSQL", ",", "blockhash", ")", "\n", "return", "db", ".", "filterError", "(", "err", ")", "\n", "}" ]
// Invalidate block with the given hash.
[ "Invalidate", "block", "with", "the", "given", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L632-L635
train
decred/dcrdata
db/dcrsqlite/sqlite.go
setHeightToSideChain
func (db *DB) setHeightToSideChain(height int64) error { _, err := db.Exec(db.setHeightToSideChainSQL, height) return db.filterError(err) }
go
func (db *DB) setHeightToSideChain(height int64) error { _, err := db.Exec(db.setHeightToSideChainSQL, height) return db.filterError(err) }
[ "func", "(", "db", "*", "DB", ")", "setHeightToSideChain", "(", "height", "int64", ")", "error", "{", "_", ",", "err", ":=", "db", ".", "Exec", "(", "db", ".", "setHeightToSideChainSQL", ",", "height", ")", "\n", "return", "db", ".", "filterError", "(", "err", ")", "\n", "}" ]
// Sets the is_mainchain field to false for the given block in the database.
[ "Sets", "the", "is_mainchain", "field", "to", "false", "for", "the", "given", "block", "in", "the", "database", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L638-L641
train
decred/dcrdata
db/dcrsqlite/sqlite.go
getMainchainStatus
func (db *DB) getMainchainStatus(blockhash string) (bool, error) { var isMainchain bool err := db.QueryRow(db.getMainchainStatusSQL, blockhash).Scan(&isMainchain) return isMainchain, err }
go
func (db *DB) getMainchainStatus(blockhash string) (bool, error) { var isMainchain bool err := db.QueryRow(db.getMainchainStatusSQL, blockhash).Scan(&isMainchain) return isMainchain, err }
[ "func", "(", "db", "*", "DB", ")", "getMainchainStatus", "(", "blockhash", "string", ")", "(", "bool", ",", "error", ")", "{", "var", "isMainchain", "bool", "\n", "err", ":=", "db", ".", "QueryRow", "(", "db", ".", "getMainchainStatusSQL", ",", "blockhash", ")", ".", "Scan", "(", "&", "isMainchain", ")", "\n", "return", "isMainchain", ",", "err", "\n", "}" ]
// Returns the is_mainchain value from the database for the given hash.
[ "Returns", "the", "is_mainchain", "value", "from", "the", "database", "for", "the", "given", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L644-L648
train
decred/dcrdata
db/dcrsqlite/sqlite.go
StoreBlock
func (db *DB) StoreBlock(bd *apitypes.BlockDataBasic, isMainchain bool, isValid bool) error { // Cache mainchain blocks. if isMainchain && db.BlockCache != nil && db.BlockCache.IsEnabled() { if err := db.BlockCache.StoreBlockSummary(bd); err != nil { return fmt.Errorf("APICache failed to store block: %v", err) } } stmt, err := db.Prepare(db.insertBlockSQL) if err != nil { return err } defer stmt.Close() // If input block data lacks non-nil PoolInfo, set to a zero-value // TicketPoolInfo. if bd.PoolInfo == nil { bd.PoolInfo = new(apitypes.TicketPoolInfo) } // Insert the block. winners := strings.Join(bd.PoolInfo.Winners, ";") res, err := stmt.Exec(&bd.Hash, &bd.Height, &bd.Size, &bd.Difficulty, &bd.StakeDiff, bd.Time.S.UNIX(), &bd.PoolInfo.Size, &bd.PoolInfo.Value, &bd.PoolInfo.ValAvg, &winners, &isMainchain, &isValid) if err != nil { return db.filterError(err) } // Update the DB block summary height. db.mtx.Lock() defer db.mtx.Unlock() if err = logDBResult(res); err == nil { height := int64(bd.Height) if height > db.dbSummaryHeight { db.dbSummaryHeight = height } if db.lastStoredBlock == nil || bd.Height >= db.lastStoredBlock.Height { db.lastStoredBlock = new(apitypes.BlockDataBasic) *db.lastStoredBlock = *bd } } return err }
go
func (db *DB) StoreBlock(bd *apitypes.BlockDataBasic, isMainchain bool, isValid bool) error { // Cache mainchain blocks. if isMainchain && db.BlockCache != nil && db.BlockCache.IsEnabled() { if err := db.BlockCache.StoreBlockSummary(bd); err != nil { return fmt.Errorf("APICache failed to store block: %v", err) } } stmt, err := db.Prepare(db.insertBlockSQL) if err != nil { return err } defer stmt.Close() // If input block data lacks non-nil PoolInfo, set to a zero-value // TicketPoolInfo. if bd.PoolInfo == nil { bd.PoolInfo = new(apitypes.TicketPoolInfo) } // Insert the block. winners := strings.Join(bd.PoolInfo.Winners, ";") res, err := stmt.Exec(&bd.Hash, &bd.Height, &bd.Size, &bd.Difficulty, &bd.StakeDiff, bd.Time.S.UNIX(), &bd.PoolInfo.Size, &bd.PoolInfo.Value, &bd.PoolInfo.ValAvg, &winners, &isMainchain, &isValid) if err != nil { return db.filterError(err) } // Update the DB block summary height. db.mtx.Lock() defer db.mtx.Unlock() if err = logDBResult(res); err == nil { height := int64(bd.Height) if height > db.dbSummaryHeight { db.dbSummaryHeight = height } if db.lastStoredBlock == nil || bd.Height >= db.lastStoredBlock.Height { db.lastStoredBlock = new(apitypes.BlockDataBasic) *db.lastStoredBlock = *bd } } return err }
[ "func", "(", "db", "*", "DB", ")", "StoreBlock", "(", "bd", "*", "apitypes", ".", "BlockDataBasic", ",", "isMainchain", "bool", ",", "isValid", "bool", ")", "error", "{", "// Cache mainchain blocks.", "if", "isMainchain", "&&", "db", ".", "BlockCache", "!=", "nil", "&&", "db", ".", "BlockCache", ".", "IsEnabled", "(", ")", "{", "if", "err", ":=", "db", ".", "BlockCache", ".", "StoreBlockSummary", "(", "bd", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "stmt", ",", "err", ":=", "db", ".", "Prepare", "(", "db", ".", "insertBlockSQL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "stmt", ".", "Close", "(", ")", "\n\n", "// If input block data lacks non-nil PoolInfo, set to a zero-value", "// TicketPoolInfo.", "if", "bd", ".", "PoolInfo", "==", "nil", "{", "bd", ".", "PoolInfo", "=", "new", "(", "apitypes", ".", "TicketPoolInfo", ")", "\n", "}", "\n\n", "// Insert the block.", "winners", ":=", "strings", ".", "Join", "(", "bd", ".", "PoolInfo", ".", "Winners", ",", "\"", "\"", ")", "\n", "res", ",", "err", ":=", "stmt", ".", "Exec", "(", "&", "bd", ".", "Hash", ",", "&", "bd", ".", "Height", ",", "&", "bd", ".", "Size", ",", "&", "bd", ".", "Difficulty", ",", "&", "bd", ".", "StakeDiff", ",", "bd", ".", "Time", ".", "S", ".", "UNIX", "(", ")", ",", "&", "bd", ".", "PoolInfo", ".", "Size", ",", "&", "bd", ".", "PoolInfo", ".", "Value", ",", "&", "bd", ".", "PoolInfo", ".", "ValAvg", ",", "&", "winners", ",", "&", "isMainchain", ",", "&", "isValid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "db", ".", "filterError", "(", "err", ")", "\n", "}", "\n\n", "// Update the DB block summary height.", "db", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mtx", ".", "Unlock", "(", ")", "\n", "if", "err", "=", "logDBResult", "(", "res", ")", ";", "err", "==", "nil", "{", "height", ":=", "int64", "(", "bd", ".", "Height", ")", "\n", "if", "height", ">", "db", ".", "dbSummaryHeight", "{", "db", ".", "dbSummaryHeight", "=", "height", "\n", "}", "\n", "if", "db", ".", "lastStoredBlock", "==", "nil", "||", "bd", ".", "Height", ">=", "db", ".", "lastStoredBlock", ".", "Height", "{", "db", ".", "lastStoredBlock", "=", "new", "(", "apitypes", ".", "BlockDataBasic", ")", "\n", "*", "db", ".", "lastStoredBlock", "=", "*", "bd", "\n", "}", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// StoreBlock attempts to store the block data in the database, and // returns an error on failure.
[ "StoreBlock", "attempts", "to", "store", "the", "block", "data", "in", "the", "database", "and", "returns", "an", "error", "on", "failure", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L652-L696
train
decred/dcrdata
db/dcrsqlite/sqlite.go
StoreBlockSummary
func (db *DB) StoreBlockSummary(bd *apitypes.BlockDataBasic) error { return db.StoreBlock(bd, true, true) }
go
func (db *DB) StoreBlockSummary(bd *apitypes.BlockDataBasic) error { return db.StoreBlock(bd, true, true) }
[ "func", "(", "db", "*", "DB", ")", "StoreBlockSummary", "(", "bd", "*", "apitypes", ".", "BlockDataBasic", ")", "error", "{", "return", "db", ".", "StoreBlock", "(", "bd", ",", "true", ",", "true", ")", "\n", "}" ]
// StoreBlockSummary is called with new mainchain blocks.
[ "StoreBlockSummary", "is", "called", "with", "new", "mainchain", "blocks", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L699-L701
train
decred/dcrdata
db/dcrsqlite/sqlite.go
StoreSideBlockSummary
func (db *DB) StoreSideBlockSummary(bd *apitypes.BlockDataBasic) error { return db.StoreBlock(bd, false, true) }
go
func (db *DB) StoreSideBlockSummary(bd *apitypes.BlockDataBasic) error { return db.StoreBlock(bd, false, true) }
[ "func", "(", "db", "*", "DB", ")", "StoreSideBlockSummary", "(", "bd", "*", "apitypes", ".", "BlockDataBasic", ")", "error", "{", "return", "db", ".", "StoreBlock", "(", "bd", ",", "false", ",", "true", ")", "\n", "}" ]
// StoreSideBlockSummary is for storing side chain.
[ "StoreSideBlockSummary", "is", "for", "storing", "side", "chain", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L704-L706
train
decred/dcrdata
db/dcrsqlite/sqlite.go
GetBestBlockHash
func (db *DB) GetBestBlockHash() string { hash, err := db.RetrieveBestBlockHash() if err != nil { log.Errorf("RetrieveBestBlockHash failed: %v", err) return "" } return hash }
go
func (db *DB) GetBestBlockHash() string { hash, err := db.RetrieveBestBlockHash() if err != nil { log.Errorf("RetrieveBestBlockHash failed: %v", err) return "" } return hash }
[ "func", "(", "db", "*", "DB", ")", "GetBestBlockHash", "(", ")", "string", "{", "hash", ",", "err", ":=", "db", ".", "RetrieveBestBlockHash", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\"", "\"", "\n", "}", "\n", "return", "hash", "\n", "}" ]
// GetBestBlockHash returns the hash of the best block.
[ "GetBestBlockHash", "returns", "the", "hash", "of", "the", "best", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L709-L716
train
decred/dcrdata
db/dcrsqlite/sqlite.go
GetBlockSummaryHeight
func (db *DB) GetBlockSummaryHeight() (int64, error) { db.mtx.RLock() defer db.mtx.RUnlock() if db.dbSummaryHeight < 0 { h, err := db.getBlockSummaryHeight() if err == nil { db.dbSummaryHeight = h } return h, err } return db.dbSummaryHeight, nil }
go
func (db *DB) GetBlockSummaryHeight() (int64, error) { db.mtx.RLock() defer db.mtx.RUnlock() if db.dbSummaryHeight < 0 { h, err := db.getBlockSummaryHeight() if err == nil { db.dbSummaryHeight = h } return h, err } return db.dbSummaryHeight, nil }
[ "func", "(", "db", "*", "DB", ")", "GetBlockSummaryHeight", "(", ")", "(", "int64", ",", "error", ")", "{", "db", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "if", "db", ".", "dbSummaryHeight", "<", "0", "{", "h", ",", "err", ":=", "db", ".", "getBlockSummaryHeight", "(", ")", "\n", "if", "err", "==", "nil", "{", "db", ".", "dbSummaryHeight", "=", "h", "\n", "}", "\n", "return", "h", ",", "err", "\n", "}", "\n", "return", "db", ".", "dbSummaryHeight", ",", "nil", "\n", "}" ]
// GetBlockSummaryHeight returns the largest block height for which the database // can provide a block summary. A cached best block summary height will be // returned when available to avoid unnecessary DB queries.
[ "GetBlockSummaryHeight", "returns", "the", "largest", "block", "height", "for", "which", "the", "database", "can", "provide", "a", "block", "summary", ".", "A", "cached", "best", "block", "summary", "height", "will", "be", "returned", "when", "available", "to", "avoid", "unnecessary", "DB", "queries", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L765-L776
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrievePoolInfoRange
func (db *DB) RetrievePoolInfoRange(ind0, ind1 int64) ([]apitypes.TicketPoolInfo, []string, error) { N := ind1 - ind0 + 1 if N == 0 { return []apitypes.TicketPoolInfo{}, []string{}, nil } if N < 0 { return nil, nil, fmt.Errorf("Cannot retrieve pool info range (%d>%d)", ind0, ind1) } db.mtx.RLock() if ind1 > db.dbSummaryHeight || ind0 < 0 { defer db.mtx.RUnlock() return nil, nil, fmt.Errorf("Cannot retrieve pool info range [%d,%d], have height %d", ind0, ind1, db.dbSummaryHeight) } db.mtx.RUnlock() tpis := make([]apitypes.TicketPoolInfo, 0, N) hashes := make([]string, 0, N) stmt, err := db.Prepare(db.getPoolRangeSQL) if err != nil { return nil, nil, err } defer stmt.Close() rows, err := stmt.Query(ind0, ind1) if err != nil { log.Errorf("Query failed: %v", err) return nil, nil, err } defer rows.Close() for rows.Next() { var tpi apitypes.TicketPoolInfo var hash, winners string if err = rows.Scan(&tpi.Height, &hash, &tpi.Size, &tpi.Value, &tpi.ValAvg, &winners); err != nil { log.Errorf("Unable to scan for TicketPoolInfo fields: %v", err) } tpi.Winners = splitToArray(winners) tpis = append(tpis, tpi) hashes = append(hashes, hash) } if err = rows.Err(); err != nil { log.Error(err) } return tpis, hashes, nil }
go
func (db *DB) RetrievePoolInfoRange(ind0, ind1 int64) ([]apitypes.TicketPoolInfo, []string, error) { N := ind1 - ind0 + 1 if N == 0 { return []apitypes.TicketPoolInfo{}, []string{}, nil } if N < 0 { return nil, nil, fmt.Errorf("Cannot retrieve pool info range (%d>%d)", ind0, ind1) } db.mtx.RLock() if ind1 > db.dbSummaryHeight || ind0 < 0 { defer db.mtx.RUnlock() return nil, nil, fmt.Errorf("Cannot retrieve pool info range [%d,%d], have height %d", ind0, ind1, db.dbSummaryHeight) } db.mtx.RUnlock() tpis := make([]apitypes.TicketPoolInfo, 0, N) hashes := make([]string, 0, N) stmt, err := db.Prepare(db.getPoolRangeSQL) if err != nil { return nil, nil, err } defer stmt.Close() rows, err := stmt.Query(ind0, ind1) if err != nil { log.Errorf("Query failed: %v", err) return nil, nil, err } defer rows.Close() for rows.Next() { var tpi apitypes.TicketPoolInfo var hash, winners string if err = rows.Scan(&tpi.Height, &hash, &tpi.Size, &tpi.Value, &tpi.ValAvg, &winners); err != nil { log.Errorf("Unable to scan for TicketPoolInfo fields: %v", err) } tpi.Winners = splitToArray(winners) tpis = append(tpis, tpi) hashes = append(hashes, hash) } if err = rows.Err(); err != nil { log.Error(err) } return tpis, hashes, nil }
[ "func", "(", "db", "*", "DB", ")", "RetrievePoolInfoRange", "(", "ind0", ",", "ind1", "int64", ")", "(", "[", "]", "apitypes", ".", "TicketPoolInfo", ",", "[", "]", "string", ",", "error", ")", "{", "N", ":=", "ind1", "-", "ind0", "+", "1", "\n", "if", "N", "==", "0", "{", "return", "[", "]", "apitypes", ".", "TicketPoolInfo", "{", "}", ",", "[", "]", "string", "{", "}", ",", "nil", "\n", "}", "\n", "if", "N", "<", "0", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ind0", ",", "ind1", ")", "\n", "}", "\n", "db", ".", "mtx", ".", "RLock", "(", ")", "\n", "if", "ind1", ">", "db", ".", "dbSummaryHeight", "||", "ind0", "<", "0", "{", "defer", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ind0", ",", "ind1", ",", "db", ".", "dbSummaryHeight", ")", "\n", "}", "\n", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "tpis", ":=", "make", "(", "[", "]", "apitypes", ".", "TicketPoolInfo", ",", "0", ",", "N", ")", "\n", "hashes", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "N", ")", "\n\n", "stmt", ",", "err", ":=", "db", ".", "Prepare", "(", "db", ".", "getPoolRangeSQL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "defer", "stmt", ".", "Close", "(", ")", "\n\n", "rows", ",", "err", ":=", "stmt", ".", "Query", "(", "ind0", ",", "ind1", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n\n", "for", "rows", ".", "Next", "(", ")", "{", "var", "tpi", "apitypes", ".", "TicketPoolInfo", "\n", "var", "hash", ",", "winners", "string", "\n", "if", "err", "=", "rows", ".", "Scan", "(", "&", "tpi", ".", "Height", ",", "&", "hash", ",", "&", "tpi", ".", "Size", ",", "&", "tpi", ".", "Value", ",", "&", "tpi", ".", "ValAvg", ",", "&", "winners", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "tpi", ".", "Winners", "=", "splitToArray", "(", "winners", ")", "\n", "tpis", "=", "append", "(", "tpis", ",", "tpi", ")", "\n", "hashes", "=", "append", "(", "hashes", ",", "hash", ")", "\n", "}", "\n", "if", "err", "=", "rows", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Error", "(", "err", ")", "\n", "}", "\n\n", "return", "tpis", ",", "hashes", ",", "nil", "\n", "}" ]
// RetrievePoolInfoRange returns an array of apitypes.TicketPoolInfo for block // range ind0 to ind1 and a non-nil error on success
[ "RetrievePoolInfoRange", "returns", "an", "array", "of", "apitypes", ".", "TicketPoolInfo", "for", "block", "range", "ind0", "to", "ind1", "and", "a", "non", "-", "nil", "error", "on", "success" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L834-L883
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrievePoolInfo
func (db *DB) RetrievePoolInfo(ind int64) (*apitypes.TicketPoolInfo, error) { tpi := &apitypes.TicketPoolInfo{ Height: uint32(ind), } var hash, winners string err := db.QueryRow(db.getPoolSQL, ind).Scan(&hash, &tpi.Size, &tpi.Value, &tpi.ValAvg, &winners) tpi.Winners = splitToArray(winners) return tpi, err }
go
func (db *DB) RetrievePoolInfo(ind int64) (*apitypes.TicketPoolInfo, error) { tpi := &apitypes.TicketPoolInfo{ Height: uint32(ind), } var hash, winners string err := db.QueryRow(db.getPoolSQL, ind).Scan(&hash, &tpi.Size, &tpi.Value, &tpi.ValAvg, &winners) tpi.Winners = splitToArray(winners) return tpi, err }
[ "func", "(", "db", "*", "DB", ")", "RetrievePoolInfo", "(", "ind", "int64", ")", "(", "*", "apitypes", ".", "TicketPoolInfo", ",", "error", ")", "{", "tpi", ":=", "&", "apitypes", ".", "TicketPoolInfo", "{", "Height", ":", "uint32", "(", "ind", ")", ",", "}", "\n", "var", "hash", ",", "winners", "string", "\n", "err", ":=", "db", ".", "QueryRow", "(", "db", ".", "getPoolSQL", ",", "ind", ")", ".", "Scan", "(", "&", "hash", ",", "&", "tpi", ".", "Size", ",", "&", "tpi", ".", "Value", ",", "&", "tpi", ".", "ValAvg", ",", "&", "winners", ")", "\n", "tpi", ".", "Winners", "=", "splitToArray", "(", "winners", ")", "\n", "return", "tpi", ",", "err", "\n", "}" ]
// RetrievePoolInfo returns ticket pool info for block height ind
[ "RetrievePoolInfo", "returns", "ticket", "pool", "info", "for", "block", "height", "ind" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L886-L895
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrieveWinnersByHash
func (db *DB) RetrieveWinnersByHash(hash string) ([]string, uint32, error) { var winners string var height uint32 err := db.QueryRow(db.getWinnersByHashSQL, hash).Scan(&height, &winners) if err != nil { return nil, 0, err } return splitToArray(winners), height, err }
go
func (db *DB) RetrieveWinnersByHash(hash string) ([]string, uint32, error) { var winners string var height uint32 err := db.QueryRow(db.getWinnersByHashSQL, hash).Scan(&height, &winners) if err != nil { return nil, 0, err } return splitToArray(winners), height, err }
[ "func", "(", "db", "*", "DB", ")", "RetrieveWinnersByHash", "(", "hash", "string", ")", "(", "[", "]", "string", ",", "uint32", ",", "error", ")", "{", "var", "winners", "string", "\n", "var", "height", "uint32", "\n", "err", ":=", "db", ".", "QueryRow", "(", "db", ".", "getWinnersByHashSQL", ",", "hash", ")", ".", "Scan", "(", "&", "height", ",", "&", "winners", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "return", "splitToArray", "(", "winners", ")", ",", "height", ",", "err", "\n", "}" ]
// RetrieveWinnersByHash returns the winning ticket tx IDs drawn after // connecting the block with the given hash. The block height corresponding to // the input block hash is also returned.
[ "RetrieveWinnersByHash", "returns", "the", "winning", "ticket", "tx", "IDs", "drawn", "after", "connecting", "the", "block", "with", "the", "given", "hash", ".", "The", "block", "height", "corresponding", "to", "the", "input", "block", "hash", "is", "also", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L912-L920
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrievePoolInfoByHash
func (db *DB) RetrievePoolInfoByHash(hash string) (*apitypes.TicketPoolInfo, error) { tpi := new(apitypes.TicketPoolInfo) var winners string err := db.QueryRow(db.getPoolByHashSQL, hash).Scan(&tpi.Height, &tpi.Size, &tpi.Value, &tpi.ValAvg, &winners) tpi.Winners = splitToArray(winners) return tpi, err }
go
func (db *DB) RetrievePoolInfoByHash(hash string) (*apitypes.TicketPoolInfo, error) { tpi := new(apitypes.TicketPoolInfo) var winners string err := db.QueryRow(db.getPoolByHashSQL, hash).Scan(&tpi.Height, &tpi.Size, &tpi.Value, &tpi.ValAvg, &winners) tpi.Winners = splitToArray(winners) return tpi, err }
[ "func", "(", "db", "*", "DB", ")", "RetrievePoolInfoByHash", "(", "hash", "string", ")", "(", "*", "apitypes", ".", "TicketPoolInfo", ",", "error", ")", "{", "tpi", ":=", "new", "(", "apitypes", ".", "TicketPoolInfo", ")", "\n", "var", "winners", "string", "\n", "err", ":=", "db", ".", "QueryRow", "(", "db", ".", "getPoolByHashSQL", ",", "hash", ")", ".", "Scan", "(", "&", "tpi", ".", "Height", ",", "&", "tpi", ".", "Size", ",", "&", "tpi", ".", "Value", ",", "&", "tpi", ".", "ValAvg", ",", "&", "winners", ")", "\n", "tpi", ".", "Winners", "=", "splitToArray", "(", "winners", ")", "\n", "return", "tpi", ",", "err", "\n", "}" ]
// RetrievePoolInfoByHash returns ticket pool info for blockhash hash.
[ "RetrievePoolInfoByHash", "returns", "ticket", "pool", "info", "for", "blockhash", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L923-L930
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrievePoolValAndSizeRange
func (db *DB) RetrievePoolValAndSizeRange(ind0, ind1 int64) ([]float64, []float64, error) { N := ind1 - ind0 + 1 if N == 0 { return []float64{}, []float64{}, nil } if N < 0 { return nil, nil, fmt.Errorf("Cannot retrieve pool val and size range (%d>%d)", ind0, ind1) } db.mtx.RLock() if ind1 > db.dbSummaryHeight || ind0 < 0 { defer db.mtx.RUnlock() return nil, nil, fmt.Errorf("Cannot retrieve pool val and size range [%d,%d], have height %d", ind0, ind1, db.dbSummaryHeight) } db.mtx.RUnlock() poolvals := make([]float64, 0, N) poolsizes := make([]float64, 0, N) stmt, err := db.Prepare(db.getPoolValSizeRangeSQL) if err != nil { return nil, nil, err } defer stmt.Close() rows, err := stmt.Query(ind0, ind1) if err != nil { log.Errorf("Query failed: %v", err) return nil, nil, err } defer rows.Close() for rows.Next() { var pval, psize float64 if err = rows.Scan(&psize, &pval); err != nil { log.Errorf("Unable to scan for TicketPoolInfo fields: %v", err) } poolvals = append(poolvals, pval) poolsizes = append(poolsizes, psize) } if err = rows.Err(); err != nil { log.Error(err) } if len(poolsizes) != int(N) { log.Warnf("RetrievePoolValAndSizeRange: Retrieved pool values (%d) not expected number (%d)", len(poolsizes), N) } return poolvals, poolsizes, nil }
go
func (db *DB) RetrievePoolValAndSizeRange(ind0, ind1 int64) ([]float64, []float64, error) { N := ind1 - ind0 + 1 if N == 0 { return []float64{}, []float64{}, nil } if N < 0 { return nil, nil, fmt.Errorf("Cannot retrieve pool val and size range (%d>%d)", ind0, ind1) } db.mtx.RLock() if ind1 > db.dbSummaryHeight || ind0 < 0 { defer db.mtx.RUnlock() return nil, nil, fmt.Errorf("Cannot retrieve pool val and size range [%d,%d], have height %d", ind0, ind1, db.dbSummaryHeight) } db.mtx.RUnlock() poolvals := make([]float64, 0, N) poolsizes := make([]float64, 0, N) stmt, err := db.Prepare(db.getPoolValSizeRangeSQL) if err != nil { return nil, nil, err } defer stmt.Close() rows, err := stmt.Query(ind0, ind1) if err != nil { log.Errorf("Query failed: %v", err) return nil, nil, err } defer rows.Close() for rows.Next() { var pval, psize float64 if err = rows.Scan(&psize, &pval); err != nil { log.Errorf("Unable to scan for TicketPoolInfo fields: %v", err) } poolvals = append(poolvals, pval) poolsizes = append(poolsizes, psize) } if err = rows.Err(); err != nil { log.Error(err) } if len(poolsizes) != int(N) { log.Warnf("RetrievePoolValAndSizeRange: Retrieved pool values (%d) not expected number (%d)", len(poolsizes), N) } return poolvals, poolsizes, nil }
[ "func", "(", "db", "*", "DB", ")", "RetrievePoolValAndSizeRange", "(", "ind0", ",", "ind1", "int64", ")", "(", "[", "]", "float64", ",", "[", "]", "float64", ",", "error", ")", "{", "N", ":=", "ind1", "-", "ind0", "+", "1", "\n", "if", "N", "==", "0", "{", "return", "[", "]", "float64", "{", "}", ",", "[", "]", "float64", "{", "}", ",", "nil", "\n", "}", "\n", "if", "N", "<", "0", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ind0", ",", "ind1", ")", "\n", "}", "\n", "db", ".", "mtx", ".", "RLock", "(", ")", "\n", "if", "ind1", ">", "db", ".", "dbSummaryHeight", "||", "ind0", "<", "0", "{", "defer", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ind0", ",", "ind1", ",", "db", ".", "dbSummaryHeight", ")", "\n", "}", "\n", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "poolvals", ":=", "make", "(", "[", "]", "float64", ",", "0", ",", "N", ")", "\n", "poolsizes", ":=", "make", "(", "[", "]", "float64", ",", "0", ",", "N", ")", "\n\n", "stmt", ",", "err", ":=", "db", ".", "Prepare", "(", "db", ".", "getPoolValSizeRangeSQL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "defer", "stmt", ".", "Close", "(", ")", "\n\n", "rows", ",", "err", ":=", "stmt", ".", "Query", "(", "ind0", ",", "ind1", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n\n", "for", "rows", ".", "Next", "(", ")", "{", "var", "pval", ",", "psize", "float64", "\n", "if", "err", "=", "rows", ".", "Scan", "(", "&", "psize", ",", "&", "pval", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "poolvals", "=", "append", "(", "poolvals", ",", "pval", ")", "\n", "poolsizes", "=", "append", "(", "poolsizes", ",", "psize", ")", "\n", "}", "\n", "if", "err", "=", "rows", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Error", "(", "err", ")", "\n", "}", "\n\n", "if", "len", "(", "poolsizes", ")", "!=", "int", "(", "N", ")", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "len", "(", "poolsizes", ")", ",", "N", ")", "\n", "}", "\n\n", "return", "poolvals", ",", "poolsizes", ",", "nil", "\n", "}" ]
// RetrievePoolValAndSizeRange returns an array each of the pool values and // sizes for block range ind0 to ind1.
[ "RetrievePoolValAndSizeRange", "returns", "an", "array", "each", "of", "the", "pool", "values", "and", "sizes", "for", "block", "range", "ind0", "to", "ind1", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L934-L985
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrievePoolAllValueAndSize
func (db *DB) RetrievePoolAllValueAndSize(charts *cache.ChartData) (*sql.Rows, func(), error) { stmt, err := db.Prepare(db.getAllPoolValSize) if err != nil { return nil, dummyCancel, err } defer stmt.Close() rows, err := stmt.Query(charts.PoolSizeTip()) if err != nil { log.Errorf("Query failed: %v", err) return nil, dummyCancel, err } return rows, dummyCancel, nil }
go
func (db *DB) RetrievePoolAllValueAndSize(charts *cache.ChartData) (*sql.Rows, func(), error) { stmt, err := db.Prepare(db.getAllPoolValSize) if err != nil { return nil, dummyCancel, err } defer stmt.Close() rows, err := stmt.Query(charts.PoolSizeTip()) if err != nil { log.Errorf("Query failed: %v", err) return nil, dummyCancel, err } return rows, dummyCancel, nil }
[ "func", "(", "db", "*", "DB", ")", "RetrievePoolAllValueAndSize", "(", "charts", "*", "cache", ".", "ChartData", ")", "(", "*", "sql", ".", "Rows", ",", "func", "(", ")", ",", "error", ")", "{", "stmt", ",", "err", ":=", "db", ".", "Prepare", "(", "db", ".", "getAllPoolValSize", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "dummyCancel", ",", "err", "\n", "}", "\n", "defer", "stmt", ".", "Close", "(", ")", "\n\n", "rows", ",", "err", ":=", "stmt", ".", "Query", "(", "charts", ".", "PoolSizeTip", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "dummyCancel", ",", "err", "\n", "}", "\n", "return", "rows", ",", "dummyCancel", ",", "nil", "\n", "}" ]
// RetrievePoolAllValueAndSize returns all the pool value and the pool size // charts data needed to plot ticket-pool-size and ticket-pool value charts on // the charts page. This is the Fetcher half of a pair that make up a // cache.ChartUpdater.
[ "RetrievePoolAllValueAndSize", "returns", "all", "the", "pool", "value", "and", "the", "pool", "size", "charts", "data", "needed", "to", "plot", "ticket", "-", "pool", "-", "size", "and", "ticket", "-", "pool", "value", "charts", "on", "the", "charts", "page", ".", "This", "is", "the", "Fetcher", "half", "of", "a", "pair", "that", "make", "up", "a", "cache", ".", "ChartUpdater", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L993-L1006
train
decred/dcrdata
db/dcrsqlite/sqlite.go
AppendPoolAllValueAndSize
func (db *DB) AppendPoolAllValueAndSize(charts *cache.ChartData, rows *sql.Rows) error { defer rows.Close() blocks := charts.Blocks for rows.Next() { var pval, psize float64 var timestamp int64 if err := rows.Scan(&psize, &pval, &timestamp); err != nil { log.Errorf("Unable to scan for TicketPoolInfo fields: %v", err) return err } if timestamp == 0 { continue } blocks.PoolSize = append(blocks.PoolSize, uint64(psize)) blocks.PoolValue = append(blocks.PoolValue, pval) } return nil }
go
func (db *DB) AppendPoolAllValueAndSize(charts *cache.ChartData, rows *sql.Rows) error { defer rows.Close() blocks := charts.Blocks for rows.Next() { var pval, psize float64 var timestamp int64 if err := rows.Scan(&psize, &pval, &timestamp); err != nil { log.Errorf("Unable to scan for TicketPoolInfo fields: %v", err) return err } if timestamp == 0 { continue } blocks.PoolSize = append(blocks.PoolSize, uint64(psize)) blocks.PoolValue = append(blocks.PoolValue, pval) } return nil }
[ "func", "(", "db", "*", "DB", ")", "AppendPoolAllValueAndSize", "(", "charts", "*", "cache", ".", "ChartData", ",", "rows", "*", "sql", ".", "Rows", ")", "error", "{", "defer", "rows", ".", "Close", "(", ")", "\n", "blocks", ":=", "charts", ".", "Blocks", "\n", "for", "rows", ".", "Next", "(", ")", "{", "var", "pval", ",", "psize", "float64", "\n", "var", "timestamp", "int64", "\n", "if", "err", ":=", "rows", ".", "Scan", "(", "&", "psize", ",", "&", "pval", ",", "&", "timestamp", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "if", "timestamp", "==", "0", "{", "continue", "\n", "}", "\n\n", "blocks", ".", "PoolSize", "=", "append", "(", "blocks", ".", "PoolSize", ",", "uint64", "(", "psize", ")", ")", "\n", "blocks", ".", "PoolValue", "=", "append", "(", "blocks", ".", "PoolValue", ",", "pval", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Append the result from RetrievePoolAllValueAndSize to the provided ChartData. // This is the Appender half of a pair that make up a cache.ChartUpdater.
[ "Append", "the", "result", "from", "RetrievePoolAllValueAndSize", "to", "the", "provided", "ChartData", ".", "This", "is", "the", "Appender", "half", "of", "a", "pair", "that", "make", "up", "a", "cache", ".", "ChartUpdater", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1010-L1030
train
decred/dcrdata
db/dcrsqlite/sqlite.go
AppendBlockFeeRows
func (db *DB) AppendBlockFeeRows(charts *cache.ChartData, rows *sql.Rows) error { defer rows.Close() blocks := charts.Blocks for rows.Next() { var feeMed float64 var blockHeight uint64 if err := rows.Scan(&blockHeight, &feeMed); err != nil { log.Errorf("Unable to scan for FeeInfoPerBlock fields: %v", err) return err } // Converting to atoms. blocks.Fees = append(blocks.Fees, uint64(feeMed*1e8)) } return nil }
go
func (db *DB) AppendBlockFeeRows(charts *cache.ChartData, rows *sql.Rows) error { defer rows.Close() blocks := charts.Blocks for rows.Next() { var feeMed float64 var blockHeight uint64 if err := rows.Scan(&blockHeight, &feeMed); err != nil { log.Errorf("Unable to scan for FeeInfoPerBlock fields: %v", err) return err } // Converting to atoms. blocks.Fees = append(blocks.Fees, uint64(feeMed*1e8)) } return nil }
[ "func", "(", "db", "*", "DB", ")", "AppendBlockFeeRows", "(", "charts", "*", "cache", ".", "ChartData", ",", "rows", "*", "sql", ".", "Rows", ")", "error", "{", "defer", "rows", ".", "Close", "(", ")", "\n", "blocks", ":=", "charts", ".", "Blocks", "\n", "for", "rows", ".", "Next", "(", ")", "{", "var", "feeMed", "float64", "\n", "var", "blockHeight", "uint64", "\n", "if", "err", ":=", "rows", ".", "Scan", "(", "&", "blockHeight", ",", "&", "feeMed", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "// Converting to atoms.", "blocks", ".", "Fees", "=", "append", "(", "blocks", ".", "Fees", ",", "uint64", "(", "feeMed", "*", "1e8", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Append the result from RetrieveBlockFeeRows to the provided ChartData. This // is the Appender half of a pair that make up a cache.ChartUpdater.
[ "Append", "the", "result", "from", "RetrieveBlockFeeRows", "to", "the", "provided", "ChartData", ".", "This", "is", "the", "Appender", "half", "of", "a", "pair", "that", "make", "up", "a", "cache", ".", "ChartUpdater", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1053-L1069
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrieveSDiffRange
func (db *DB) RetrieveSDiffRange(ind0, ind1 int64) ([]float64, error) { N := ind1 - ind0 + 1 if N == 0 { return []float64{}, nil } if N < 0 { return nil, fmt.Errorf("Cannot retrieve sdiff range (%d>%d)", ind0, ind1) } db.mtx.RLock() if ind1 > db.dbSummaryHeight || ind0 < 0 { defer db.mtx.RUnlock() return nil, fmt.Errorf("Cannot retrieve sdiff range [%d,%d], have height %d", ind0, ind1, db.dbSummaryHeight) } db.mtx.RUnlock() sdiffs := make([]float64, 0, N) stmt, err := db.Prepare(db.getSDiffRangeSQL) if err != nil { return nil, err } defer stmt.Close() rows, err := stmt.Query(ind0, ind1) if err != nil { log.Errorf("Query failed: %v", err) return nil, err } defer rows.Close() for rows.Next() { var sdiff float64 if err = rows.Scan(&sdiff); err != nil { log.Errorf("Unable to scan for sdiff fields: %v", err) } sdiffs = append(sdiffs, sdiff) } if err = rows.Err(); err != nil { log.Error(err) } return sdiffs, nil }
go
func (db *DB) RetrieveSDiffRange(ind0, ind1 int64) ([]float64, error) { N := ind1 - ind0 + 1 if N == 0 { return []float64{}, nil } if N < 0 { return nil, fmt.Errorf("Cannot retrieve sdiff range (%d>%d)", ind0, ind1) } db.mtx.RLock() if ind1 > db.dbSummaryHeight || ind0 < 0 { defer db.mtx.RUnlock() return nil, fmt.Errorf("Cannot retrieve sdiff range [%d,%d], have height %d", ind0, ind1, db.dbSummaryHeight) } db.mtx.RUnlock() sdiffs := make([]float64, 0, N) stmt, err := db.Prepare(db.getSDiffRangeSQL) if err != nil { return nil, err } defer stmt.Close() rows, err := stmt.Query(ind0, ind1) if err != nil { log.Errorf("Query failed: %v", err) return nil, err } defer rows.Close() for rows.Next() { var sdiff float64 if err = rows.Scan(&sdiff); err != nil { log.Errorf("Unable to scan for sdiff fields: %v", err) } sdiffs = append(sdiffs, sdiff) } if err = rows.Err(); err != nil { log.Error(err) } return sdiffs, nil }
[ "func", "(", "db", "*", "DB", ")", "RetrieveSDiffRange", "(", "ind0", ",", "ind1", "int64", ")", "(", "[", "]", "float64", ",", "error", ")", "{", "N", ":=", "ind1", "-", "ind0", "+", "1", "\n", "if", "N", "==", "0", "{", "return", "[", "]", "float64", "{", "}", ",", "nil", "\n", "}", "\n", "if", "N", "<", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ind0", ",", "ind1", ")", "\n", "}", "\n", "db", ".", "mtx", ".", "RLock", "(", ")", "\n", "if", "ind1", ">", "db", ".", "dbSummaryHeight", "||", "ind0", "<", "0", "{", "defer", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ind0", ",", "ind1", ",", "db", ".", "dbSummaryHeight", ")", "\n", "}", "\n", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "sdiffs", ":=", "make", "(", "[", "]", "float64", ",", "0", ",", "N", ")", "\n\n", "stmt", ",", "err", ":=", "db", ".", "Prepare", "(", "db", ".", "getSDiffRangeSQL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "stmt", ".", "Close", "(", ")", "\n\n", "rows", ",", "err", ":=", "stmt", ".", "Query", "(", "ind0", ",", "ind1", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n\n", "for", "rows", ".", "Next", "(", ")", "{", "var", "sdiff", "float64", "\n", "if", "err", "=", "rows", ".", "Scan", "(", "&", "sdiff", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "sdiffs", "=", "append", "(", "sdiffs", ",", "sdiff", ")", "\n", "}", "\n", "if", "err", "=", "rows", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Error", "(", "err", ")", "\n", "}", "\n\n", "return", "sdiffs", ",", "nil", "\n", "}" ]
// RetrieveSDiffRange returns an array of stake difficulties for block range ind0 to // ind1
[ "RetrieveSDiffRange", "returns", "an", "array", "of", "stake", "difficulties", "for", "block", "range", "ind0", "to", "ind1" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1073-L1117
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrieveDiff
func (db *DB) RetrieveDiff(timestamp int64) (float64, error) { var diff float64 err := db.QueryRow(db.getDifficulty, timestamp).Scan(&diff) return diff, err }
go
func (db *DB) RetrieveDiff(timestamp int64) (float64, error) { var diff float64 err := db.QueryRow(db.getDifficulty, timestamp).Scan(&diff) return diff, err }
[ "func", "(", "db", "*", "DB", ")", "RetrieveDiff", "(", "timestamp", "int64", ")", "(", "float64", ",", "error", ")", "{", "var", "diff", "float64", "\n", "err", ":=", "db", ".", "QueryRow", "(", "db", ".", "getDifficulty", ",", "timestamp", ")", ".", "Scan", "(", "&", "diff", ")", "\n", "return", "diff", ",", "err", "\n", "}" ]
// RetrieveDiff returns the difficulty in the last 24hrs or immediately after // 24hrs.
[ "RetrieveDiff", "returns", "the", "difficulty", "in", "the", "last", "24hrs", "or", "immediately", "after", "24hrs", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1157-L1161
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrieveSDiff
func (db *DB) RetrieveSDiff(ind int64) (float64, error) { var sdiff float64 err := db.QueryRow(db.getSDiffSQL, ind).Scan(&sdiff) return sdiff, err }
go
func (db *DB) RetrieveSDiff(ind int64) (float64, error) { var sdiff float64 err := db.QueryRow(db.getSDiffSQL, ind).Scan(&sdiff) return sdiff, err }
[ "func", "(", "db", "*", "DB", ")", "RetrieveSDiff", "(", "ind", "int64", ")", "(", "float64", ",", "error", ")", "{", "var", "sdiff", "float64", "\n", "err", ":=", "db", ".", "QueryRow", "(", "db", ".", "getSDiffSQL", ",", "ind", ")", ".", "Scan", "(", "&", "sdiff", ")", "\n", "return", "sdiff", ",", "err", "\n", "}" ]
// RetrieveSDiff returns the stake difficulty for block at the specified chain // height.
[ "RetrieveSDiff", "returns", "the", "stake", "difficulty", "for", "block", "at", "the", "specified", "chain", "height", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1165-L1169
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrieveBlockHash
func (db *DB) RetrieveBlockHash(ind int64) (string, error) { // First try the block summary cache. usingBlockCache := db.BlockCache != nil && db.BlockCache.IsEnabled() if usingBlockCache { hash := db.BlockCache.GetBlockHash(ind) if hash != "" { // Cache hit! return hash, nil } // Cache miss necessitates a DB query. } var blockHash string err := db.QueryRow(db.getBlockHashSQL, ind).Scan(&blockHash) return blockHash, err }
go
func (db *DB) RetrieveBlockHash(ind int64) (string, error) { // First try the block summary cache. usingBlockCache := db.BlockCache != nil && db.BlockCache.IsEnabled() if usingBlockCache { hash := db.BlockCache.GetBlockHash(ind) if hash != "" { // Cache hit! return hash, nil } // Cache miss necessitates a DB query. } var blockHash string err := db.QueryRow(db.getBlockHashSQL, ind).Scan(&blockHash) return blockHash, err }
[ "func", "(", "db", "*", "DB", ")", "RetrieveBlockHash", "(", "ind", "int64", ")", "(", "string", ",", "error", ")", "{", "// First try the block summary cache.", "usingBlockCache", ":=", "db", ".", "BlockCache", "!=", "nil", "&&", "db", ".", "BlockCache", ".", "IsEnabled", "(", ")", "\n", "if", "usingBlockCache", "{", "hash", ":=", "db", ".", "BlockCache", ".", "GetBlockHash", "(", "ind", ")", "\n", "if", "hash", "!=", "\"", "\"", "{", "// Cache hit!", "return", "hash", ",", "nil", "\n", "}", "\n", "// Cache miss necessitates a DB query.", "}", "\n\n", "var", "blockHash", "string", "\n", "err", ":=", "db", ".", "QueryRow", "(", "db", ".", "getBlockHashSQL", ",", "ind", ")", ".", "Scan", "(", "&", "blockHash", ")", "\n", "return", "blockHash", ",", "err", "\n", "}" ]
// RetrieveBlockHash returns the block hash for block ind
[ "RetrieveBlockHash", "returns", "the", "block", "hash", "for", "block", "ind" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1191-L1206
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrieveBlockHeight
func (db *DB) RetrieveBlockHeight(hash string) (int64, error) { var blockHeight int64 err := db.QueryRow(db.getBlockHeightSQL, hash).Scan(&blockHeight) return blockHeight, err }
go
func (db *DB) RetrieveBlockHeight(hash string) (int64, error) { var blockHeight int64 err := db.QueryRow(db.getBlockHeightSQL, hash).Scan(&blockHeight) return blockHeight, err }
[ "func", "(", "db", "*", "DB", ")", "RetrieveBlockHeight", "(", "hash", "string", ")", "(", "int64", ",", "error", ")", "{", "var", "blockHeight", "int64", "\n", "err", ":=", "db", ".", "QueryRow", "(", "db", ".", "getBlockHeightSQL", ",", "hash", ")", ".", "Scan", "(", "&", "blockHeight", ")", "\n", "return", "blockHeight", ",", "err", "\n", "}" ]
// RetrieveBlockHeight returns the block height for blockhash hash
[ "RetrieveBlockHeight", "returns", "the", "block", "height", "for", "blockhash", "hash" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1209-L1213
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrieveHighestBlockHash
func (db *DB) RetrieveHighestBlockHash() (string, error) { var blockHash string err := db.QueryRow(db.getHighestBlockHashSQL).Scan(&blockHash) return blockHash, err }
go
func (db *DB) RetrieveHighestBlockHash() (string, error) { var blockHash string err := db.QueryRow(db.getHighestBlockHashSQL).Scan(&blockHash) return blockHash, err }
[ "func", "(", "db", "*", "DB", ")", "RetrieveHighestBlockHash", "(", ")", "(", "string", ",", "error", ")", "{", "var", "blockHash", "string", "\n", "err", ":=", "db", ".", "QueryRow", "(", "db", ".", "getHighestBlockHashSQL", ")", ".", "Scan", "(", "&", "blockHash", ")", "\n", "return", "blockHash", ",", "err", "\n", "}" ]
// RetrieveHighestBlockHash returns the block hash for the highest block, // regardless of mainchain status.
[ "RetrieveHighestBlockHash", "returns", "the", "block", "hash", "for", "the", "highest", "block", "regardless", "of", "mainchain", "status", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1224-L1228
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrieveBestBlockHeight
func (db *DB) RetrieveBestBlockHeight() (int64, error) { var blockHeight int64 err := db.QueryRow(db.getBestBlockHeightSQL).Scan(&blockHeight) return blockHeight, err }
go
func (db *DB) RetrieveBestBlockHeight() (int64, error) { var blockHeight int64 err := db.QueryRow(db.getBestBlockHeightSQL).Scan(&blockHeight) return blockHeight, err }
[ "func", "(", "db", "*", "DB", ")", "RetrieveBestBlockHeight", "(", ")", "(", "int64", ",", "error", ")", "{", "var", "blockHeight", "int64", "\n", "err", ":=", "db", ".", "QueryRow", "(", "db", ".", "getBestBlockHeightSQL", ")", ".", "Scan", "(", "&", "blockHeight", ")", "\n", "return", "blockHeight", ",", "err", "\n", "}" ]
// RetrieveBestBlockHeight returns the block height for the best block
[ "RetrieveBestBlockHeight", "returns", "the", "block", "height", "for", "the", "best", "block" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1231-L1235
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrieveHighestBlockHeight
func (db *DB) RetrieveHighestBlockHeight() (int64, error) { var blockHeight int64 err := db.QueryRow(db.getHighestBlockHeightSQL).Scan(&blockHeight) return blockHeight, err }
go
func (db *DB) RetrieveHighestBlockHeight() (int64, error) { var blockHeight int64 err := db.QueryRow(db.getHighestBlockHeightSQL).Scan(&blockHeight) return blockHeight, err }
[ "func", "(", "db", "*", "DB", ")", "RetrieveHighestBlockHeight", "(", ")", "(", "int64", ",", "error", ")", "{", "var", "blockHeight", "int64", "\n", "err", ":=", "db", ".", "QueryRow", "(", "db", ".", "getHighestBlockHeightSQL", ")", ".", "Scan", "(", "&", "blockHeight", ")", "\n", "return", "blockHeight", ",", "err", "\n", "}" ]
// RetrieveHighestBlockHeight returns the block height for the highest block, // regardless of mainchain status.
[ "RetrieveHighestBlockHeight", "returns", "the", "block", "height", "for", "the", "highest", "block", "regardless", "of", "mainchain", "status", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1239-L1243
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrieveBlockSummaryByHash
func (db *DB) RetrieveBlockSummaryByHash(hash string) (*apitypes.BlockDataBasic, error) { // First try the block summary cache. usingBlockCache := db.BlockCache != nil && db.BlockCache.IsEnabled() if usingBlockCache { if bd := db.BlockCache.GetBlockSummaryByHash(hash); bd != nil { // Cache hit! return bd, nil } // Cache miss necessitates a DB query. } bd := apitypes.NewBlockDataBasic() var winners string var isMainchain, isValid bool var timestamp int64 err := db.QueryRow(db.getBlockByHashSQL, hash).Scan(&bd.Hash, &bd.Height, &bd.Size, &bd.Difficulty, &bd.StakeDiff, &timestamp, &bd.PoolInfo.Size, &bd.PoolInfo.Value, &bd.PoolInfo.ValAvg, &winners, &isMainchain, &isValid) if err != nil { return nil, err } bd.Time = apitypes.TimeAPI{S: dbtypes.NewTimeDefFromUNIX(timestamp)} bd.PoolInfo.Winners = splitToArray(winners) if usingBlockCache { // This is a cache miss since hits return early. err = db.BlockCache.StoreBlockSummary(bd) if err != nil { log.Warnf("Failed to cache summary for block %s: %v", hash, err) // Do not return the error. } } return bd, nil }
go
func (db *DB) RetrieveBlockSummaryByHash(hash string) (*apitypes.BlockDataBasic, error) { // First try the block summary cache. usingBlockCache := db.BlockCache != nil && db.BlockCache.IsEnabled() if usingBlockCache { if bd := db.BlockCache.GetBlockSummaryByHash(hash); bd != nil { // Cache hit! return bd, nil } // Cache miss necessitates a DB query. } bd := apitypes.NewBlockDataBasic() var winners string var isMainchain, isValid bool var timestamp int64 err := db.QueryRow(db.getBlockByHashSQL, hash).Scan(&bd.Hash, &bd.Height, &bd.Size, &bd.Difficulty, &bd.StakeDiff, &timestamp, &bd.PoolInfo.Size, &bd.PoolInfo.Value, &bd.PoolInfo.ValAvg, &winners, &isMainchain, &isValid) if err != nil { return nil, err } bd.Time = apitypes.TimeAPI{S: dbtypes.NewTimeDefFromUNIX(timestamp)} bd.PoolInfo.Winners = splitToArray(winners) if usingBlockCache { // This is a cache miss since hits return early. err = db.BlockCache.StoreBlockSummary(bd) if err != nil { log.Warnf("Failed to cache summary for block %s: %v", hash, err) // Do not return the error. } } return bd, nil }
[ "func", "(", "db", "*", "DB", ")", "RetrieveBlockSummaryByHash", "(", "hash", "string", ")", "(", "*", "apitypes", ".", "BlockDataBasic", ",", "error", ")", "{", "// First try the block summary cache.", "usingBlockCache", ":=", "db", ".", "BlockCache", "!=", "nil", "&&", "db", ".", "BlockCache", ".", "IsEnabled", "(", ")", "\n", "if", "usingBlockCache", "{", "if", "bd", ":=", "db", ".", "BlockCache", ".", "GetBlockSummaryByHash", "(", "hash", ")", ";", "bd", "!=", "nil", "{", "// Cache hit!", "return", "bd", ",", "nil", "\n", "}", "\n", "// Cache miss necessitates a DB query.", "}", "\n\n", "bd", ":=", "apitypes", ".", "NewBlockDataBasic", "(", ")", "\n\n", "var", "winners", "string", "\n", "var", "isMainchain", ",", "isValid", "bool", "\n", "var", "timestamp", "int64", "\n", "err", ":=", "db", ".", "QueryRow", "(", "db", ".", "getBlockByHashSQL", ",", "hash", ")", ".", "Scan", "(", "&", "bd", ".", "Hash", ",", "&", "bd", ".", "Height", ",", "&", "bd", ".", "Size", ",", "&", "bd", ".", "Difficulty", ",", "&", "bd", ".", "StakeDiff", ",", "&", "timestamp", ",", "&", "bd", ".", "PoolInfo", ".", "Size", ",", "&", "bd", ".", "PoolInfo", ".", "Value", ",", "&", "bd", ".", "PoolInfo", ".", "ValAvg", ",", "&", "winners", ",", "&", "isMainchain", ",", "&", "isValid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "bd", ".", "Time", "=", "apitypes", ".", "TimeAPI", "{", "S", ":", "dbtypes", ".", "NewTimeDefFromUNIX", "(", "timestamp", ")", "}", "\n", "bd", ".", "PoolInfo", ".", "Winners", "=", "splitToArray", "(", "winners", ")", "\n\n", "if", "usingBlockCache", "{", "// This is a cache miss since hits return early.", "err", "=", "db", ".", "BlockCache", ".", "StoreBlockSummary", "(", "bd", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "hash", ",", "err", ")", "\n", "// Do not return the error.", "}", "\n", "}", "\n\n", "return", "bd", ",", "nil", "\n", "}" ]
// RetrieveBlockSummaryByHash returns basic block data for a block given its hash
[ "RetrieveBlockSummaryByHash", "returns", "basic", "block", "data", "for", "a", "block", "given", "its", "hash" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1246-L1282
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrieveBlockSize
func (db *DB) RetrieveBlockSize(ind int64) (int32, error) { // First try the block summary cache. usingBlockCache := db.BlockCache != nil && db.BlockCache.IsEnabled() if usingBlockCache { sz := db.BlockCache.GetBlockSize(ind) if sz != -1 { // Cache hit! return sz, nil } // Cache miss necessitates a DB query. } db.mtx.RLock() if ind > db.dbSummaryHeight || ind < 0 { defer db.mtx.RUnlock() return -1, fmt.Errorf("Cannot retrieve block size %d, have height %d", ind, db.dbSummaryHeight) } db.mtx.RUnlock() var blockSize int32 err := db.QueryRow(db.getBlockSizeSQL, ind).Scan(&blockSize) if err != nil { return -1, fmt.Errorf("unable to scan for block size: %v", err) } return blockSize, nil }
go
func (db *DB) RetrieveBlockSize(ind int64) (int32, error) { // First try the block summary cache. usingBlockCache := db.BlockCache != nil && db.BlockCache.IsEnabled() if usingBlockCache { sz := db.BlockCache.GetBlockSize(ind) if sz != -1 { // Cache hit! return sz, nil } // Cache miss necessitates a DB query. } db.mtx.RLock() if ind > db.dbSummaryHeight || ind < 0 { defer db.mtx.RUnlock() return -1, fmt.Errorf("Cannot retrieve block size %d, have height %d", ind, db.dbSummaryHeight) } db.mtx.RUnlock() var blockSize int32 err := db.QueryRow(db.getBlockSizeSQL, ind).Scan(&blockSize) if err != nil { return -1, fmt.Errorf("unable to scan for block size: %v", err) } return blockSize, nil }
[ "func", "(", "db", "*", "DB", ")", "RetrieveBlockSize", "(", "ind", "int64", ")", "(", "int32", ",", "error", ")", "{", "// First try the block summary cache.", "usingBlockCache", ":=", "db", ".", "BlockCache", "!=", "nil", "&&", "db", ".", "BlockCache", ".", "IsEnabled", "(", ")", "\n", "if", "usingBlockCache", "{", "sz", ":=", "db", ".", "BlockCache", ".", "GetBlockSize", "(", "ind", ")", "\n", "if", "sz", "!=", "-", "1", "{", "// Cache hit!", "return", "sz", ",", "nil", "\n", "}", "\n", "// Cache miss necessitates a DB query.", "}", "\n\n", "db", ".", "mtx", ".", "RLock", "(", ")", "\n", "if", "ind", ">", "db", ".", "dbSummaryHeight", "||", "ind", "<", "0", "{", "defer", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ind", ",", "db", ".", "dbSummaryHeight", ")", "\n", "}", "\n", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "var", "blockSize", "int32", "\n", "err", ":=", "db", ".", "QueryRow", "(", "db", ".", "getBlockSizeSQL", ",", "ind", ")", ".", "Scan", "(", "&", "blockSize", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "blockSize", ",", "nil", "\n", "}" ]
// RetrieveBlockSize return the size of block at height ind.
[ "RetrieveBlockSize", "return", "the", "size", "of", "block", "at", "height", "ind", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1359-L1386
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrieveBlockSizeRange
func (db *DB) RetrieveBlockSizeRange(ind0, ind1 int64) ([]int32, error) { N := ind1 - ind0 + 1 if N == 0 { return []int32{}, nil } if N < 0 { return nil, fmt.Errorf("Cannot retrieve block size range (%d>%d)", ind0, ind1) } db.mtx.RLock() if ind1 > db.dbSummaryHeight || ind0 < 0 { defer db.mtx.RUnlock() return nil, fmt.Errorf("Cannot retrieve block size range [%d,%d], have height %d", ind0, ind1, db.dbSummaryHeight) } db.mtx.RUnlock() blockSizes := make([]int32, 0, N) stmt, err := db.Prepare(db.getBlockSizeRangeSQL) if err != nil { return nil, err } defer stmt.Close() rows, err := stmt.Query(ind0, ind1) if err != nil { log.Errorf("Query failed: %v", err) return nil, err } defer rows.Close() for rows.Next() { var blockSize int32 if err = rows.Scan(&blockSize); err != nil { log.Errorf("Unable to scan for block size field: %v", err) } blockSizes = append(blockSizes, blockSize) } if err = rows.Err(); err != nil { log.Error(err) } return blockSizes, nil }
go
func (db *DB) RetrieveBlockSizeRange(ind0, ind1 int64) ([]int32, error) { N := ind1 - ind0 + 1 if N == 0 { return []int32{}, nil } if N < 0 { return nil, fmt.Errorf("Cannot retrieve block size range (%d>%d)", ind0, ind1) } db.mtx.RLock() if ind1 > db.dbSummaryHeight || ind0 < 0 { defer db.mtx.RUnlock() return nil, fmt.Errorf("Cannot retrieve block size range [%d,%d], have height %d", ind0, ind1, db.dbSummaryHeight) } db.mtx.RUnlock() blockSizes := make([]int32, 0, N) stmt, err := db.Prepare(db.getBlockSizeRangeSQL) if err != nil { return nil, err } defer stmt.Close() rows, err := stmt.Query(ind0, ind1) if err != nil { log.Errorf("Query failed: %v", err) return nil, err } defer rows.Close() for rows.Next() { var blockSize int32 if err = rows.Scan(&blockSize); err != nil { log.Errorf("Unable to scan for block size field: %v", err) } blockSizes = append(blockSizes, blockSize) } if err = rows.Err(); err != nil { log.Error(err) } return blockSizes, nil }
[ "func", "(", "db", "*", "DB", ")", "RetrieveBlockSizeRange", "(", "ind0", ",", "ind1", "int64", ")", "(", "[", "]", "int32", ",", "error", ")", "{", "N", ":=", "ind1", "-", "ind0", "+", "1", "\n", "if", "N", "==", "0", "{", "return", "[", "]", "int32", "{", "}", ",", "nil", "\n", "}", "\n", "if", "N", "<", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ind0", ",", "ind1", ")", "\n", "}", "\n", "db", ".", "mtx", ".", "RLock", "(", ")", "\n", "if", "ind1", ">", "db", ".", "dbSummaryHeight", "||", "ind0", "<", "0", "{", "defer", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ind0", ",", "ind1", ",", "db", ".", "dbSummaryHeight", ")", "\n", "}", "\n", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "blockSizes", ":=", "make", "(", "[", "]", "int32", ",", "0", ",", "N", ")", "\n\n", "stmt", ",", "err", ":=", "db", ".", "Prepare", "(", "db", ".", "getBlockSizeRangeSQL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "stmt", ".", "Close", "(", ")", "\n\n", "rows", ",", "err", ":=", "stmt", ".", "Query", "(", "ind0", ",", "ind1", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n\n", "for", "rows", ".", "Next", "(", ")", "{", "var", "blockSize", "int32", "\n", "if", "err", "=", "rows", ".", "Scan", "(", "&", "blockSize", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "blockSizes", "=", "append", "(", "blockSizes", ",", "blockSize", ")", "\n", "}", "\n", "if", "err", "=", "rows", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Error", "(", "err", ")", "\n", "}", "\n\n", "return", "blockSizes", ",", "nil", "\n", "}" ]
// RetrieveBlockSizeRange returns an array of block sizes for block range ind0 to ind1
[ "RetrieveBlockSizeRange", "returns", "an", "array", "of", "block", "sizes", "for", "block", "range", "ind0", "to", "ind1" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1389-L1433
train
decred/dcrdata
db/dcrsqlite/sqlite.go
StoreStakeInfoExtended
func (db *DB) StoreStakeInfoExtended(si *apitypes.StakeInfoExtended) error { if db.BlockCache != nil && db.BlockCache.IsEnabled() { if err := db.BlockCache.StoreStakeInfo(si); err != nil { return fmt.Errorf("APICache failed to store stake info: %v", err) } } stmt, err := db.Prepare(db.insertStakeInfoExtendedSQL) if err != nil { return err } defer stmt.Close() // If input block data lacks non-nil PoolInfo, set to a zero-value // TicketPoolInfo. if si.PoolInfo == nil { si.PoolInfo = new(apitypes.TicketPoolInfo) } winners := strings.Join(si.PoolInfo.Winners, ";") res, err := stmt.Exec(&si.Hash, &si.Feeinfo.Height, &si.Feeinfo.Number, &si.Feeinfo.Min, &si.Feeinfo.Max, &si.Feeinfo.Mean, &si.Feeinfo.Median, &si.Feeinfo.StdDev, &si.StakeDiff, // no next or estimates &si.PriceWindowNum, &si.IdxBlockInWindow, &si.PoolInfo.Size, &si.PoolInfo.Value, &si.PoolInfo.ValAvg, &winners) if err != nil { return db.filterError(err) } db.mtx.Lock() defer db.mtx.Unlock() if err = logDBResult(res); err == nil { height := int64(si.Feeinfo.Height) if height > db.dbStakeInfoHeight { db.dbStakeInfoHeight = height } } return err }
go
func (db *DB) StoreStakeInfoExtended(si *apitypes.StakeInfoExtended) error { if db.BlockCache != nil && db.BlockCache.IsEnabled() { if err := db.BlockCache.StoreStakeInfo(si); err != nil { return fmt.Errorf("APICache failed to store stake info: %v", err) } } stmt, err := db.Prepare(db.insertStakeInfoExtendedSQL) if err != nil { return err } defer stmt.Close() // If input block data lacks non-nil PoolInfo, set to a zero-value // TicketPoolInfo. if si.PoolInfo == nil { si.PoolInfo = new(apitypes.TicketPoolInfo) } winners := strings.Join(si.PoolInfo.Winners, ";") res, err := stmt.Exec(&si.Hash, &si.Feeinfo.Height, &si.Feeinfo.Number, &si.Feeinfo.Min, &si.Feeinfo.Max, &si.Feeinfo.Mean, &si.Feeinfo.Median, &si.Feeinfo.StdDev, &si.StakeDiff, // no next or estimates &si.PriceWindowNum, &si.IdxBlockInWindow, &si.PoolInfo.Size, &si.PoolInfo.Value, &si.PoolInfo.ValAvg, &winners) if err != nil { return db.filterError(err) } db.mtx.Lock() defer db.mtx.Unlock() if err = logDBResult(res); err == nil { height := int64(si.Feeinfo.Height) if height > db.dbStakeInfoHeight { db.dbStakeInfoHeight = height } } return err }
[ "func", "(", "db", "*", "DB", ")", "StoreStakeInfoExtended", "(", "si", "*", "apitypes", ".", "StakeInfoExtended", ")", "error", "{", "if", "db", ".", "BlockCache", "!=", "nil", "&&", "db", ".", "BlockCache", ".", "IsEnabled", "(", ")", "{", "if", "err", ":=", "db", ".", "BlockCache", ".", "StoreStakeInfo", "(", "si", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "stmt", ",", "err", ":=", "db", ".", "Prepare", "(", "db", ".", "insertStakeInfoExtendedSQL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "stmt", ".", "Close", "(", ")", "\n\n", "// If input block data lacks non-nil PoolInfo, set to a zero-value", "// TicketPoolInfo.", "if", "si", ".", "PoolInfo", "==", "nil", "{", "si", ".", "PoolInfo", "=", "new", "(", "apitypes", ".", "TicketPoolInfo", ")", "\n", "}", "\n\n", "winners", ":=", "strings", ".", "Join", "(", "si", ".", "PoolInfo", ".", "Winners", ",", "\"", "\"", ")", "\n\n", "res", ",", "err", ":=", "stmt", ".", "Exec", "(", "&", "si", ".", "Hash", ",", "&", "si", ".", "Feeinfo", ".", "Height", ",", "&", "si", ".", "Feeinfo", ".", "Number", ",", "&", "si", ".", "Feeinfo", ".", "Min", ",", "&", "si", ".", "Feeinfo", ".", "Max", ",", "&", "si", ".", "Feeinfo", ".", "Mean", ",", "&", "si", ".", "Feeinfo", ".", "Median", ",", "&", "si", ".", "Feeinfo", ".", "StdDev", ",", "&", "si", ".", "StakeDiff", ",", "// no next or estimates", "&", "si", ".", "PriceWindowNum", ",", "&", "si", ".", "IdxBlockInWindow", ",", "&", "si", ".", "PoolInfo", ".", "Size", ",", "&", "si", ".", "PoolInfo", ".", "Value", ",", "&", "si", ".", "PoolInfo", ".", "ValAvg", ",", "&", "winners", ")", "\n", "if", "err", "!=", "nil", "{", "return", "db", ".", "filterError", "(", "err", ")", "\n", "}", "\n\n", "db", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mtx", ".", "Unlock", "(", ")", "\n", "if", "err", "=", "logDBResult", "(", "res", ")", ";", "err", "==", "nil", "{", "height", ":=", "int64", "(", "si", ".", "Feeinfo", ".", "Height", ")", "\n", "if", "height", ">", "db", ".", "dbStakeInfoHeight", "{", "db", ".", "dbStakeInfoHeight", "=", "height", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// StoreStakeInfoExtended stores the extended stake info in the database.
[ "StoreStakeInfoExtended", "stores", "the", "extended", "stake", "info", "in", "the", "database", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1436-L1476
train
decred/dcrdata
db/dcrsqlite/sqlite.go
deleteStakeInfo
func (db *DB) deleteStakeInfo(blockhash string) (int64, error) { res, err := db.Exec(db.deleteBlockByHashSQL, blockhash) if err != nil { return 0, db.filterError(err) } return res.RowsAffected() }
go
func (db *DB) deleteStakeInfo(blockhash string) (int64, error) { res, err := db.Exec(db.deleteBlockByHashSQL, blockhash) if err != nil { return 0, db.filterError(err) } return res.RowsAffected() }
[ "func", "(", "db", "*", "DB", ")", "deleteStakeInfo", "(", "blockhash", "string", ")", "(", "int64", ",", "error", ")", "{", "res", ",", "err", ":=", "db", ".", "Exec", "(", "db", ".", "deleteBlockByHashSQL", ",", "blockhash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "db", ".", "filterError", "(", "err", ")", "\n", "}", "\n", "return", "res", ".", "RowsAffected", "(", ")", "\n", "}" ]
// Delete stake info for block with the given hash. The number of rows deleted // is returned.
[ "Delete", "stake", "info", "for", "block", "with", "the", "given", "hash", ".", "The", "number", "of", "rows", "deleted", "is", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1480-L1486
train
decred/dcrdata
db/dcrsqlite/sqlite.go
deleteStakeInfoHeightMainchain
func (db *DB) deleteStakeInfoHeightMainchain(height int64) (int64, error) { res, err := db.Exec(db.deleteBlockByHeightMainChainSQL, height) if err != nil { return 0, db.filterError(err) } return res.RowsAffected() }
go
func (db *DB) deleteStakeInfoHeightMainchain(height int64) (int64, error) { res, err := db.Exec(db.deleteBlockByHeightMainChainSQL, height) if err != nil { return 0, db.filterError(err) } return res.RowsAffected() }
[ "func", "(", "db", "*", "DB", ")", "deleteStakeInfoHeightMainchain", "(", "height", "int64", ")", "(", "int64", ",", "error", ")", "{", "res", ",", "err", ":=", "db", ".", "Exec", "(", "db", ".", "deleteBlockByHeightMainChainSQL", ",", "height", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "db", ".", "filterError", "(", "err", ")", "\n", "}", "\n", "return", "res", ".", "RowsAffected", "(", ")", "\n", "}" ]
// Delete stake info for block at the given height on the main chain. The number // of rows deleted is returned.
[ "Delete", "stake", "info", "for", "block", "at", "the", "given", "height", "on", "the", "main", "chain", ".", "The", "number", "of", "rows", "deleted", "is", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1490-L1496
train
decred/dcrdata
db/dcrsqlite/sqlite.go
RetrieveHighestStakeHeight
func (db *DB) RetrieveHighestStakeHeight() (int64, error) { var height int64 err := db.QueryRow(db.getHighestStakeHeightSQL).Scan(&height) if err != nil { return -1, err } return height, nil }
go
func (db *DB) RetrieveHighestStakeHeight() (int64, error) { var height int64 err := db.QueryRow(db.getHighestStakeHeightSQL).Scan(&height) if err != nil { return -1, err } return height, nil }
[ "func", "(", "db", "*", "DB", ")", "RetrieveHighestStakeHeight", "(", ")", "(", "int64", ",", "error", ")", "{", "var", "height", "int64", "\n", "err", ":=", "db", ".", "QueryRow", "(", "db", ".", "getHighestStakeHeightSQL", ")", ".", "Scan", "(", "&", "height", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "return", "height", ",", "nil", "\n", "}" ]
// RetrieveHighestStakeHeight retrieves the height of the highest block in the // stake table without regard to mainchain status.
[ "RetrieveHighestStakeHeight", "retrieves", "the", "height", "of", "the", "highest", "block", "in", "the", "stake", "table", "without", "regard", "to", "mainchain", "status", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1545-L1552
train
decred/dcrdata
db/dcrsqlite/sqlite.go
getTip
func (db *DB) getTip() (*apitypes.BlockDataBasic, error) { db.mtx.RLock() defer db.mtx.RUnlock() if db.lastStoredBlock != nil { return db.lastStoredBlock, nil } return db.RetrieveLatestBlockSummary() }
go
func (db *DB) getTip() (*apitypes.BlockDataBasic, error) { db.mtx.RLock() defer db.mtx.RUnlock() if db.lastStoredBlock != nil { return db.lastStoredBlock, nil } return db.RetrieveLatestBlockSummary() }
[ "func", "(", "db", "*", "DB", ")", "getTip", "(", ")", "(", "*", "apitypes", ".", "BlockDataBasic", ",", "error", ")", "{", "db", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "db", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "if", "db", ".", "lastStoredBlock", "!=", "nil", "{", "return", "db", ".", "lastStoredBlock", ",", "nil", "\n", "}", "\n", "return", "db", ".", "RetrieveLatestBlockSummary", "(", ")", "\n", "}" ]
// getTip returns the last block stored using StoreBlockSummary. // If no block has been stored yet, it returns the best block in the database.
[ "getTip", "returns", "the", "last", "block", "stored", "using", "StoreBlockSummary", ".", "If", "no", "block", "has", "been", "stored", "yet", "it", "returns", "the", "best", "block", "in", "the", "database", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sqlite.go#L1783-L1790
train
decred/dcrdata
stakedb/stakedb.go
NewPoolInfoCache
func NewPoolInfoCache(size int) (*PoolInfoCache, error) { if size < 2 { return nil, fmt.Errorf("size %d is less than 2", size) } return &PoolInfoCache{ poolInfo: make(map[chainhash.Hash]*apitypes.TicketPoolInfo, size), expireQueue: make([]chainhash.Hash, 0, size), maxSize: size, }, nil }
go
func NewPoolInfoCache(size int) (*PoolInfoCache, error) { if size < 2 { return nil, fmt.Errorf("size %d is less than 2", size) } return &PoolInfoCache{ poolInfo: make(map[chainhash.Hash]*apitypes.TicketPoolInfo, size), expireQueue: make([]chainhash.Hash, 0, size), maxSize: size, }, nil }
[ "func", "NewPoolInfoCache", "(", "size", "int", ")", "(", "*", "PoolInfoCache", ",", "error", ")", "{", "if", "size", "<", "2", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "size", ")", "\n", "}", "\n", "return", "&", "PoolInfoCache", "{", "poolInfo", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "*", "apitypes", ".", "TicketPoolInfo", ",", "size", ")", ",", "expireQueue", ":", "make", "(", "[", "]", "chainhash", ".", "Hash", ",", "0", ",", "size", ")", ",", "maxSize", ":", "size", ",", "}", ",", "nil", "\n", "}" ]
// NewPoolInfoCache constructs a new PoolInfoCache, and is needed to initialize // the internal map.
[ "NewPoolInfoCache", "constructs", "a", "new", "PoolInfoCache", "and", "is", "needed", "to", "initialize", "the", "internal", "map", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L39-L48
train
decred/dcrdata
stakedb/stakedb.go
Set
func (c *PoolInfoCache) Set(hash chainhash.Hash, p *apitypes.TicketPoolInfo) { c.mtx.Lock() defer c.mtx.Unlock() c.poolInfo[hash] = p if len(c.expireQueue)+1 >= c.maxSize { expireHash := c.expireQueue[0] c.expireQueue = c.expireQueue[1:] delete(c.poolInfo, expireHash) } c.expireQueue = append(c.expireQueue, hash) }
go
func (c *PoolInfoCache) Set(hash chainhash.Hash, p *apitypes.TicketPoolInfo) { c.mtx.Lock() defer c.mtx.Unlock() c.poolInfo[hash] = p if len(c.expireQueue)+1 >= c.maxSize { expireHash := c.expireQueue[0] c.expireQueue = c.expireQueue[1:] delete(c.poolInfo, expireHash) } c.expireQueue = append(c.expireQueue, hash) }
[ "func", "(", "c", "*", "PoolInfoCache", ")", "Set", "(", "hash", "chainhash", ".", "Hash", ",", "p", "*", "apitypes", ".", "TicketPoolInfo", ")", "{", "c", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "Unlock", "(", ")", "\n", "c", ".", "poolInfo", "[", "hash", "]", "=", "p", "\n", "if", "len", "(", "c", ".", "expireQueue", ")", "+", "1", ">=", "c", ".", "maxSize", "{", "expireHash", ":=", "c", ".", "expireQueue", "[", "0", "]", "\n", "c", ".", "expireQueue", "=", "c", ".", "expireQueue", "[", "1", ":", "]", "\n", "delete", "(", "c", ".", "poolInfo", ",", "expireHash", ")", "\n", "}", "\n", "c", ".", "expireQueue", "=", "append", "(", "c", ".", "expireQueue", ",", "hash", ")", "\n", "}" ]
// Set stores the ticket pool info for the given hash in the pool info cache.
[ "Set", "stores", "the", "ticket", "pool", "info", "for", "the", "given", "hash", "in", "the", "pool", "info", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L61-L71
train
decred/dcrdata
stakedb/stakedb.go
SetCapacity
func (c *PoolInfoCache) SetCapacity(size int) error { if size < 2 { return fmt.Errorf("size %d is less than 2", size) } c.mtx.Lock() defer c.mtx.Unlock() c.maxSize = size for len(c.expireQueue) >= c.maxSize { expireHash := c.expireQueue[0] c.expireQueue = c.expireQueue[1:] delete(c.poolInfo, expireHash) } return nil }
go
func (c *PoolInfoCache) SetCapacity(size int) error { if size < 2 { return fmt.Errorf("size %d is less than 2", size) } c.mtx.Lock() defer c.mtx.Unlock() c.maxSize = size for len(c.expireQueue) >= c.maxSize { expireHash := c.expireQueue[0] c.expireQueue = c.expireQueue[1:] delete(c.poolInfo, expireHash) } return nil }
[ "func", "(", "c", "*", "PoolInfoCache", ")", "SetCapacity", "(", "size", "int", ")", "error", "{", "if", "size", "<", "2", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "size", ")", "\n", "}", "\n\n", "c", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "Unlock", "(", ")", "\n", "c", ".", "maxSize", "=", "size", "\n", "for", "len", "(", "c", ".", "expireQueue", ")", ">=", "c", ".", "maxSize", "{", "expireHash", ":=", "c", ".", "expireQueue", "[", "0", "]", "\n", "c", ".", "expireQueue", "=", "c", ".", "expireQueue", "[", "1", ":", "]", "\n", "delete", "(", "c", ".", "poolInfo", ",", "expireHash", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetCapacity sets the cache capacity to the specified number of elements. If // the new capacity is smaller than the current cache size, elements are // automatically evicted until the desired size is reached.
[ "SetCapacity", "sets", "the", "cache", "capacity", "to", "the", "specified", "number", "of", "elements", ".", "If", "the", "new", "capacity", "is", "smaller", "than", "the", "current", "cache", "size", "elements", "are", "automatically", "evicted", "until", "the", "desired", "size", "is", "reached", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L76-L90
train
decred/dcrdata
stakedb/stakedb.go
PopulateLiveTicketCache
func (db *StakeDatabase) PopulateLiveTicketCache() error { var err error // Live tickets from dcrdata's stake Node's perspective liveTickets := db.BestNode.LiveTickets() log.Info("Pre-populating live ticket cache and computing pool value...") // Send all the live ticket requests type promiseGetRawTransaction struct { result rpcclient.FutureGetRawTransactionResult ticket chainhash.Hash } promisesGetRawTransaction := make([]promiseGetRawTransaction, 0, len(liveTickets)) // Send all the live ticket requests for _, hash := range liveTickets { promisesGetRawTransaction = append(promisesGetRawTransaction, promiseGetRawTransaction{ result: db.NodeClient.GetRawTransactionAsync(&hash), ticket: hash, }) } // reset ticket cache db.liveTicketMtx.Lock() db.poolValue = 0 db.liveTicketCache = make(map[chainhash.Hash]int64, db.params.TicketPoolSize*(db.params.TicketsPerBlock+1)) // Receive the live ticket tx results for _, p := range promisesGetRawTransaction { ticketTx, err0 := p.result.Receive() if err0 != nil { log.Errorf("RPC error: %v", err) err = err0 continue } if !ticketTx.Hash().IsEqual(&p.ticket) { panic(fmt.Sprintf("Failed to receive Tx details for requested ticket hash: %v, %v", p.ticket, ticketTx.Hash())) } value := ticketTx.MsgTx().TxOut[0].Value db.poolValue += value db.liveTicketCache[p.ticket] = value } db.liveTicketMtx.Unlock() return err }
go
func (db *StakeDatabase) PopulateLiveTicketCache() error { var err error // Live tickets from dcrdata's stake Node's perspective liveTickets := db.BestNode.LiveTickets() log.Info("Pre-populating live ticket cache and computing pool value...") // Send all the live ticket requests type promiseGetRawTransaction struct { result rpcclient.FutureGetRawTransactionResult ticket chainhash.Hash } promisesGetRawTransaction := make([]promiseGetRawTransaction, 0, len(liveTickets)) // Send all the live ticket requests for _, hash := range liveTickets { promisesGetRawTransaction = append(promisesGetRawTransaction, promiseGetRawTransaction{ result: db.NodeClient.GetRawTransactionAsync(&hash), ticket: hash, }) } // reset ticket cache db.liveTicketMtx.Lock() db.poolValue = 0 db.liveTicketCache = make(map[chainhash.Hash]int64, db.params.TicketPoolSize*(db.params.TicketsPerBlock+1)) // Receive the live ticket tx results for _, p := range promisesGetRawTransaction { ticketTx, err0 := p.result.Receive() if err0 != nil { log.Errorf("RPC error: %v", err) err = err0 continue } if !ticketTx.Hash().IsEqual(&p.ticket) { panic(fmt.Sprintf("Failed to receive Tx details for requested ticket hash: %v, %v", p.ticket, ticketTx.Hash())) } value := ticketTx.MsgTx().TxOut[0].Value db.poolValue += value db.liveTicketCache[p.ticket] = value } db.liveTicketMtx.Unlock() return err }
[ "func", "(", "db", "*", "StakeDatabase", ")", "PopulateLiveTicketCache", "(", ")", "error", "{", "var", "err", "error", "\n", "// Live tickets from dcrdata's stake Node's perspective", "liveTickets", ":=", "db", ".", "BestNode", ".", "LiveTickets", "(", ")", "\n\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n\n", "// Send all the live ticket requests", "type", "promiseGetRawTransaction", "struct", "{", "result", "rpcclient", ".", "FutureGetRawTransactionResult", "\n", "ticket", "chainhash", ".", "Hash", "\n", "}", "\n", "promisesGetRawTransaction", ":=", "make", "(", "[", "]", "promiseGetRawTransaction", ",", "0", ",", "len", "(", "liveTickets", ")", ")", "\n\n", "// Send all the live ticket requests", "for", "_", ",", "hash", ":=", "range", "liveTickets", "{", "promisesGetRawTransaction", "=", "append", "(", "promisesGetRawTransaction", ",", "promiseGetRawTransaction", "{", "result", ":", "db", ".", "NodeClient", ".", "GetRawTransactionAsync", "(", "&", "hash", ")", ",", "ticket", ":", "hash", ",", "}", ")", "\n", "}", "\n\n", "// reset ticket cache", "db", ".", "liveTicketMtx", ".", "Lock", "(", ")", "\n", "db", ".", "poolValue", "=", "0", "\n", "db", ".", "liveTicketCache", "=", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "int64", ",", "db", ".", "params", ".", "TicketPoolSize", "*", "(", "db", ".", "params", ".", "TicketsPerBlock", "+", "1", ")", ")", "\n\n", "// Receive the live ticket tx results", "for", "_", ",", "p", ":=", "range", "promisesGetRawTransaction", "{", "ticketTx", ",", "err0", ":=", "p", ".", "result", ".", "Receive", "(", ")", "\n", "if", "err0", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "err", "=", "err0", "\n", "continue", "\n", "}", "\n", "if", "!", "ticketTx", ".", "Hash", "(", ")", ".", "IsEqual", "(", "&", "p", ".", "ticket", ")", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "ticket", ",", "ticketTx", ".", "Hash", "(", ")", ")", ")", "\n", "}", "\n\n", "value", ":=", "ticketTx", ".", "MsgTx", "(", ")", ".", "TxOut", "[", "0", "]", ".", "Value", "\n", "db", ".", "poolValue", "+=", "value", "\n", "db", ".", "liveTicketCache", "[", "p", ".", "ticket", "]", "=", "value", "\n", "}", "\n", "db", ".", "liveTicketMtx", ".", "Unlock", "(", ")", "\n\n", "return", "err", "\n", "}" ]
// PopulateLiveTicketCache loads the hashes of all tickets in BestNode into the // cache and computes the internally-stored pool value.
[ "PopulateLiveTicketCache", "loads", "the", "hashes", "of", "all", "tickets", "in", "BestNode", "into", "the", "cache", "and", "computes", "the", "internally", "-", "stored", "pool", "value", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L327-L373
train
decred/dcrdata
stakedb/stakedb.go
Rewind
func (db *StakeDatabase) Rewind(to int64, neglectCache bool) error { var heightTicketPool int64 heightStakeDB := int64(db.Height()) for to < heightStakeDB { if err := db.DisconnectBlock(neglectCache); err != nil { return fmt.Errorf("failed to disconnect block: %v", err) } heightStakeDB, heightTicketPool = int64(db.Height()), db.PoolDB.Tip() if heightTicketPool != heightStakeDB { return fmt.Errorf("failed to disconnect block: "+ "stake DB height (%d) != ticket pool height (%d)", heightStakeDB, heightTicketPool) } } return nil }
go
func (db *StakeDatabase) Rewind(to int64, neglectCache bool) error { var heightTicketPool int64 heightStakeDB := int64(db.Height()) for to < heightStakeDB { if err := db.DisconnectBlock(neglectCache); err != nil { return fmt.Errorf("failed to disconnect block: %v", err) } heightStakeDB, heightTicketPool = int64(db.Height()), db.PoolDB.Tip() if heightTicketPool != heightStakeDB { return fmt.Errorf("failed to disconnect block: "+ "stake DB height (%d) != ticket pool height (%d)", heightStakeDB, heightTicketPool) } } return nil }
[ "func", "(", "db", "*", "StakeDatabase", ")", "Rewind", "(", "to", "int64", ",", "neglectCache", "bool", ")", "error", "{", "var", "heightTicketPool", "int64", "\n", "heightStakeDB", ":=", "int64", "(", "db", ".", "Height", "(", ")", ")", "\n", "for", "to", "<", "heightStakeDB", "{", "if", "err", ":=", "db", ".", "DisconnectBlock", "(", "neglectCache", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "heightStakeDB", ",", "heightTicketPool", "=", "int64", "(", "db", ".", "Height", "(", ")", ")", ",", "db", ".", "PoolDB", ".", "Tip", "(", ")", "\n", "if", "heightTicketPool", "!=", "heightStakeDB", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "heightStakeDB", ",", "heightTicketPool", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Rewind disconnects blocks until the new height is the specified height. // During disconnect, the ticket pool cache and value are kept accurate, unless // neglectCache is true.
[ "Rewind", "disconnects", "blocks", "until", "the", "new", "height", "is", "the", "specified", "height", ".", "During", "disconnect", "the", "ticket", "pool", "cache", "and", "value", "are", "kept", "accurate", "unless", "neglectCache", "is", "true", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L378-L393
train
decred/dcrdata
stakedb/stakedb.go
WaitForHeight
func (db *StakeDatabase) WaitForHeight(height int64) chan *chainhash.Hash { dbHeight := int64(db.Height()) waitChan := make(chan *chainhash.Hash, 1) if dbHeight > height { defer func() { waitChan <- nil }() return waitChan } else if dbHeight == height { block, _ := db.block(height) if block == nil { panic("broken StakeDatabase") } defer func() { go db.signalWaiters(height, block.Hash()) }() } db.waitMtx.Lock() db.heightWaiters[height] = append(db.heightWaiters[height], waitChan) db.waitMtx.Unlock() return waitChan }
go
func (db *StakeDatabase) WaitForHeight(height int64) chan *chainhash.Hash { dbHeight := int64(db.Height()) waitChan := make(chan *chainhash.Hash, 1) if dbHeight > height { defer func() { waitChan <- nil }() return waitChan } else if dbHeight == height { block, _ := db.block(height) if block == nil { panic("broken StakeDatabase") } defer func() { go db.signalWaiters(height, block.Hash()) }() } db.waitMtx.Lock() db.heightWaiters[height] = append(db.heightWaiters[height], waitChan) db.waitMtx.Unlock() return waitChan }
[ "func", "(", "db", "*", "StakeDatabase", ")", "WaitForHeight", "(", "height", "int64", ")", "chan", "*", "chainhash", ".", "Hash", "{", "dbHeight", ":=", "int64", "(", "db", ".", "Height", "(", ")", ")", "\n", "waitChan", ":=", "make", "(", "chan", "*", "chainhash", ".", "Hash", ",", "1", ")", "\n", "if", "dbHeight", ">", "height", "{", "defer", "func", "(", ")", "{", "waitChan", "<-", "nil", "}", "(", ")", "\n", "return", "waitChan", "\n", "}", "else", "if", "dbHeight", "==", "height", "{", "block", ",", "_", ":=", "db", ".", "block", "(", "height", ")", "\n", "if", "block", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "go", "db", ".", "signalWaiters", "(", "height", ",", "block", ".", "Hash", "(", ")", ")", "}", "(", ")", "\n", "}", "\n", "db", ".", "waitMtx", ".", "Lock", "(", ")", "\n", "db", ".", "heightWaiters", "[", "height", "]", "=", "append", "(", "db", ".", "heightWaiters", "[", "height", "]", ",", "waitChan", ")", "\n", "db", ".", "waitMtx", ".", "Unlock", "(", ")", "\n", "return", "waitChan", "\n", "}" ]
// WaitForHeight provides a notification channel to which the hash of the block // at the requested height will be sent when it becomes available.
[ "WaitForHeight", "provides", "a", "notification", "channel", "to", "which", "the", "hash", "of", "the", "block", "at", "the", "requested", "height", "will", "be", "sent", "when", "it", "becomes", "available", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L407-L424
train
decred/dcrdata
stakedb/stakedb.go
BlockCached
func (db *StakeDatabase) BlockCached(ind int64) (*dcrutil.Block, bool) { db.blkMtx.RLock() defer db.blkMtx.RUnlock() block, found := db.blockCache[ind] return block, found }
go
func (db *StakeDatabase) BlockCached(ind int64) (*dcrutil.Block, bool) { db.blkMtx.RLock() defer db.blkMtx.RUnlock() block, found := db.blockCache[ind] return block, found }
[ "func", "(", "db", "*", "StakeDatabase", ")", "BlockCached", "(", "ind", "int64", ")", "(", "*", "dcrutil", ".", "Block", ",", "bool", ")", "{", "db", ".", "blkMtx", ".", "RLock", "(", ")", "\n", "defer", "db", ".", "blkMtx", ".", "RUnlock", "(", ")", "\n", "block", ",", "found", ":=", "db", ".", "blockCache", "[", "ind", "]", "\n", "return", "block", ",", "found", "\n", "}" ]
// BlockCached attempts to find the block at the specified height in the block // cache. The returned boolean indicates if it was found.
[ "BlockCached", "attempts", "to", "find", "the", "block", "at", "the", "specified", "height", "in", "the", "block", "cache", ".", "The", "returned", "boolean", "indicates", "if", "it", "was", "found", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L456-L461
train
decred/dcrdata
stakedb/stakedb.go
block
func (db *StakeDatabase) block(ind int64) (*dcrutil.Block, bool) { block, ok := db.BlockCached(ind) if !ok { var err error block, _, err = rpcutils.GetBlock(ind, db.NodeClient) if err != nil { log.Error(err) return nil, false } } return block, ok }
go
func (db *StakeDatabase) block(ind int64) (*dcrutil.Block, bool) { block, ok := db.BlockCached(ind) if !ok { var err error block, _, err = rpcutils.GetBlock(ind, db.NodeClient) if err != nil { log.Error(err) return nil, false } } return block, ok }
[ "func", "(", "db", "*", "StakeDatabase", ")", "block", "(", "ind", "int64", ")", "(", "*", "dcrutil", ".", "Block", ",", "bool", ")", "{", "block", ",", "ok", ":=", "db", ".", "BlockCached", "(", "ind", ")", "\n", "if", "!", "ok", "{", "var", "err", "error", "\n", "block", ",", "_", ",", "err", "=", "rpcutils", ".", "GetBlock", "(", "ind", ",", "db", ".", "NodeClient", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Error", "(", "err", ")", "\n", "return", "nil", ",", "false", "\n", "}", "\n", "}", "\n", "return", "block", ",", "ok", "\n", "}" ]
// block first tries to find the block at the input height in cache, and if that // fails it will request it from the node RPC client. Don't use this casually // since reorganization may redefine a block at a given height.
[ "block", "first", "tries", "to", "find", "the", "block", "at", "the", "input", "height", "in", "cache", "and", "if", "that", "fails", "it", "will", "request", "it", "from", "the", "node", "RPC", "client", ".", "Don", "t", "use", "this", "casually", "since", "reorganization", "may", "redefine", "a", "block", "at", "a", "given", "height", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L466-L477
train
decred/dcrdata
stakedb/stakedb.go
ForgetBlock
func (db *StakeDatabase) ForgetBlock(ind int64) { db.blkMtx.Lock() defer db.blkMtx.Unlock() delete(db.blockCache, ind) }
go
func (db *StakeDatabase) ForgetBlock(ind int64) { db.blkMtx.Lock() defer db.blkMtx.Unlock() delete(db.blockCache, ind) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "ForgetBlock", "(", "ind", "int64", ")", "{", "db", ".", "blkMtx", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "blkMtx", ".", "Unlock", "(", ")", "\n", "delete", "(", "db", ".", "blockCache", ",", "ind", ")", "\n", "}" ]
// ForgetBlock deletes the block with the input height from the block cache.
[ "ForgetBlock", "deletes", "the", "block", "with", "the", "input", "height", "from", "the", "block", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L480-L484
train
decred/dcrdata
stakedb/stakedb.go
ConnectBlockHash
func (db *StakeDatabase) ConnectBlockHash(hash *chainhash.Hash) (*dcrutil.Block, error) { msgBlock, err := db.NodeClient.GetBlock(hash) if err != nil { return nil, err } block := dcrutil.NewBlock(msgBlock) return block, db.ConnectBlock(block) }
go
func (db *StakeDatabase) ConnectBlockHash(hash *chainhash.Hash) (*dcrutil.Block, error) { msgBlock, err := db.NodeClient.GetBlock(hash) if err != nil { return nil, err } block := dcrutil.NewBlock(msgBlock) return block, db.ConnectBlock(block) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "ConnectBlockHash", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "dcrutil", ".", "Block", ",", "error", ")", "{", "msgBlock", ",", "err", ":=", "db", ".", "NodeClient", ".", "GetBlock", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "block", ":=", "dcrutil", ".", "NewBlock", "(", "msgBlock", ")", "\n", "return", "block", ",", "db", ".", "ConnectBlock", "(", "block", ")", "\n", "}" ]
// ConnectBlockHash is a wrapper for ConnectBlock. For the input block hash, it // gets the block from the node RPC client and calls ConnectBlock.
[ "ConnectBlockHash", "is", "a", "wrapper", "for", "ConnectBlock", ".", "For", "the", "input", "block", "hash", "it", "gets", "the", "block", "from", "the", "node", "RPC", "client", "and", "calls", "ConnectBlock", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L488-L495
train
decred/dcrdata
stakedb/stakedb.go
ConnectBlock
func (db *StakeDatabase) ConnectBlock(block *dcrutil.Block) error { height := block.Height() maturingHeight := height - int64(db.params.TicketMaturity) var maturingTickets []chainhash.Hash if maturingHeight >= 0 { maturingBlock, wasCached := db.block(maturingHeight) if wasCached { db.ForgetBlock(maturingHeight) } maturingTickets, _ = txhelpers.TicketsInBlock(maturingBlock) } db.blkMtx.Lock() db.blockCache[height] = block db.blkMtx.Unlock() revokedTickets := txhelpers.RevokedTicketsInBlock(block) votedTickets := txhelpers.TicketsSpentInBlock(block) db.nodeMtx.Lock() defer db.nodeMtx.Unlock() bestNodeHeight := int64(db.BestNode.Height()) if height <= bestNodeHeight { return fmt.Errorf("cannot connect block height %d at height %d", height, bestNodeHeight) } // Who is supposed to vote in the block we are about to connect winners := db.BestNode.Winners() // connect it, updating BestNode err := db.connectBlock(block, votedTickets, revokedTickets, maturingTickets) if err != nil { return err } // Expiring tickets expiring := db.BestNode.ExpiredByBlock() // Tickets leaving the live ticket pool = winners + expires liveOut := append(winners, expiring...) // Tickets entering the pool = maturing tickets poolDiff := &PoolDiff{ In: maturingTickets, Out: liveOut, } defer func() { go db.signalWaiters(height, block.Hash()) }() // update liveTicketCache and poolValue db.applyDiff(*poolDiff) // Some sanity checks // db.liveTicketMtx.RLock() // liveTickets := make([]chainhash.Hash, 0, len(db.liveTicketCache)) // for h := range db.liveTicketCache { // liveTickets = append(liveTickets, h) // } // db.liveTicketMtx.RUnlock() // Get ticket pool info at current best (just connected in stakedb) block, // and store it in the StakeDatabase's PoolInfoCache. // liveTicketsX := db.BestNode.LiveTickets() // if len(db.liveTicketCache) != len(liveTicketsX) { // log.Errorf("%d != %d", len(db.liveTicketCache), len(liveTicketsX)) // } // Store TicketPoolInfo in the PoolInfoCache poolSize := int64(db.BestNode.PoolSize()) winningTickets := db.BestNode.Winners() pib := db.makePoolInfo(db.poolValue, poolSize, winningTickets, uint32(height)) db.poolInfo.Set(*block.Hash(), pib) // Append this ticket pool diff return db.PoolDB.Append(poolDiff, bestNodeHeight+1) }
go
func (db *StakeDatabase) ConnectBlock(block *dcrutil.Block) error { height := block.Height() maturingHeight := height - int64(db.params.TicketMaturity) var maturingTickets []chainhash.Hash if maturingHeight >= 0 { maturingBlock, wasCached := db.block(maturingHeight) if wasCached { db.ForgetBlock(maturingHeight) } maturingTickets, _ = txhelpers.TicketsInBlock(maturingBlock) } db.blkMtx.Lock() db.blockCache[height] = block db.blkMtx.Unlock() revokedTickets := txhelpers.RevokedTicketsInBlock(block) votedTickets := txhelpers.TicketsSpentInBlock(block) db.nodeMtx.Lock() defer db.nodeMtx.Unlock() bestNodeHeight := int64(db.BestNode.Height()) if height <= bestNodeHeight { return fmt.Errorf("cannot connect block height %d at height %d", height, bestNodeHeight) } // Who is supposed to vote in the block we are about to connect winners := db.BestNode.Winners() // connect it, updating BestNode err := db.connectBlock(block, votedTickets, revokedTickets, maturingTickets) if err != nil { return err } // Expiring tickets expiring := db.BestNode.ExpiredByBlock() // Tickets leaving the live ticket pool = winners + expires liveOut := append(winners, expiring...) // Tickets entering the pool = maturing tickets poolDiff := &PoolDiff{ In: maturingTickets, Out: liveOut, } defer func() { go db.signalWaiters(height, block.Hash()) }() // update liveTicketCache and poolValue db.applyDiff(*poolDiff) // Some sanity checks // db.liveTicketMtx.RLock() // liveTickets := make([]chainhash.Hash, 0, len(db.liveTicketCache)) // for h := range db.liveTicketCache { // liveTickets = append(liveTickets, h) // } // db.liveTicketMtx.RUnlock() // Get ticket pool info at current best (just connected in stakedb) block, // and store it in the StakeDatabase's PoolInfoCache. // liveTicketsX := db.BestNode.LiveTickets() // if len(db.liveTicketCache) != len(liveTicketsX) { // log.Errorf("%d != %d", len(db.liveTicketCache), len(liveTicketsX)) // } // Store TicketPoolInfo in the PoolInfoCache poolSize := int64(db.BestNode.PoolSize()) winningTickets := db.BestNode.Winners() pib := db.makePoolInfo(db.poolValue, poolSize, winningTickets, uint32(height)) db.poolInfo.Set(*block.Hash(), pib) // Append this ticket pool diff return db.PoolDB.Append(poolDiff, bestNodeHeight+1) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "ConnectBlock", "(", "block", "*", "dcrutil", ".", "Block", ")", "error", "{", "height", ":=", "block", ".", "Height", "(", ")", "\n", "maturingHeight", ":=", "height", "-", "int64", "(", "db", ".", "params", ".", "TicketMaturity", ")", "\n\n", "var", "maturingTickets", "[", "]", "chainhash", ".", "Hash", "\n", "if", "maturingHeight", ">=", "0", "{", "maturingBlock", ",", "wasCached", ":=", "db", ".", "block", "(", "maturingHeight", ")", "\n", "if", "wasCached", "{", "db", ".", "ForgetBlock", "(", "maturingHeight", ")", "\n", "}", "\n", "maturingTickets", ",", "_", "=", "txhelpers", ".", "TicketsInBlock", "(", "maturingBlock", ")", "\n", "}", "\n\n", "db", ".", "blkMtx", ".", "Lock", "(", ")", "\n", "db", ".", "blockCache", "[", "height", "]", "=", "block", "\n", "db", ".", "blkMtx", ".", "Unlock", "(", ")", "\n\n", "revokedTickets", ":=", "txhelpers", ".", "RevokedTicketsInBlock", "(", "block", ")", "\n", "votedTickets", ":=", "txhelpers", ".", "TicketsSpentInBlock", "(", "block", ")", "\n\n", "db", ".", "nodeMtx", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "nodeMtx", ".", "Unlock", "(", ")", "\n", "bestNodeHeight", ":=", "int64", "(", "db", ".", "BestNode", ".", "Height", "(", ")", ")", "\n", "if", "height", "<=", "bestNodeHeight", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "height", ",", "bestNodeHeight", ")", "\n", "}", "\n\n", "// Who is supposed to vote in the block we are about to connect", "winners", ":=", "db", ".", "BestNode", ".", "Winners", "(", ")", "\n\n", "// connect it, updating BestNode", "err", ":=", "db", ".", "connectBlock", "(", "block", ",", "votedTickets", ",", "revokedTickets", ",", "maturingTickets", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Expiring tickets", "expiring", ":=", "db", ".", "BestNode", ".", "ExpiredByBlock", "(", ")", "\n\n", "// Tickets leaving the live ticket pool = winners + expires", "liveOut", ":=", "append", "(", "winners", ",", "expiring", "...", ")", "\n", "// Tickets entering the pool = maturing tickets", "poolDiff", ":=", "&", "PoolDiff", "{", "In", ":", "maturingTickets", ",", "Out", ":", "liveOut", ",", "}", "\n\n", "defer", "func", "(", ")", "{", "go", "db", ".", "signalWaiters", "(", "height", ",", "block", ".", "Hash", "(", ")", ")", "}", "(", ")", "\n\n", "// update liveTicketCache and poolValue", "db", ".", "applyDiff", "(", "*", "poolDiff", ")", "\n\n", "// Some sanity checks", "// db.liveTicketMtx.RLock()", "// liveTickets := make([]chainhash.Hash, 0, len(db.liveTicketCache))", "// for h := range db.liveTicketCache {", "// \tliveTickets = append(liveTickets, h)", "// }", "// db.liveTicketMtx.RUnlock()", "// Get ticket pool info at current best (just connected in stakedb) block,", "// and store it in the StakeDatabase's PoolInfoCache.", "// liveTicketsX := db.BestNode.LiveTickets()", "// if len(db.liveTicketCache) != len(liveTicketsX) {", "// \tlog.Errorf(\"%d != %d\", len(db.liveTicketCache), len(liveTicketsX))", "// }", "// Store TicketPoolInfo in the PoolInfoCache", "poolSize", ":=", "int64", "(", "db", ".", "BestNode", ".", "PoolSize", "(", ")", ")", "\n", "winningTickets", ":=", "db", ".", "BestNode", ".", "Winners", "(", ")", "\n", "pib", ":=", "db", ".", "makePoolInfo", "(", "db", ".", "poolValue", ",", "poolSize", ",", "winningTickets", ",", "uint32", "(", "height", ")", ")", "\n", "db", ".", "poolInfo", ".", "Set", "(", "*", "block", ".", "Hash", "(", ")", ",", "pib", ")", "\n\n", "// Append this ticket pool diff", "return", "db", ".", "PoolDB", ".", "Append", "(", "poolDiff", ",", "bestNodeHeight", "+", "1", ")", "\n", "}" ]
// ConnectBlock connects the input block to the tip of the stake DB and updates // the best stake node. This exported function gets any revoked and spend // tickets from the input block, and any maturing tickets from the past block in // which those tickets would be found, and passes them to connectBlock.
[ "ConnectBlock", "connects", "the", "input", "block", "to", "the", "tip", "of", "the", "stake", "DB", "and", "updates", "the", "best", "stake", "node", ".", "This", "exported", "function", "gets", "any", "revoked", "and", "spend", "tickets", "from", "the", "input", "block", "and", "any", "maturing", "tickets", "from", "the", "past", "block", "in", "which", "those", "tickets", "would", "be", "found", "and", "passes", "them", "to", "connectBlock", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L501-L576
train
decred/dcrdata
stakedb/stakedb.go
applyDiff
func (db *StakeDatabase) applyDiff(poolDiff PoolDiff) { db.liveTicketMtx.Lock() for _, hash := range poolDiff.In { _, ok := db.liveTicketCache[hash] if ok { log.Warnf("Just tried to add a ticket (%v) to the pool, but it was already there!", hash) continue } tx, err := db.NodeClient.GetRawTransaction(&hash) if err != nil { log.Errorf("Unable to get transaction %v: %v\n", hash, err) continue } // This isn't quite right for pool tickets where the small // pool fees are included in vout[0], but it's close. val := tx.MsgTx().TxOut[0].Value db.liveTicketCache[hash] = val db.poolValue += val } for _, h := range poolDiff.Out { valOut, ok := db.liveTicketCache[h] if !ok { log.Debugf("Didn't find %v in live ticket cache, cannot remove it.", h) continue } db.poolValue -= valOut delete(db.liveTicketCache, h) } db.liveTicketMtx.Unlock() }
go
func (db *StakeDatabase) applyDiff(poolDiff PoolDiff) { db.liveTicketMtx.Lock() for _, hash := range poolDiff.In { _, ok := db.liveTicketCache[hash] if ok { log.Warnf("Just tried to add a ticket (%v) to the pool, but it was already there!", hash) continue } tx, err := db.NodeClient.GetRawTransaction(&hash) if err != nil { log.Errorf("Unable to get transaction %v: %v\n", hash, err) continue } // This isn't quite right for pool tickets where the small // pool fees are included in vout[0], but it's close. val := tx.MsgTx().TxOut[0].Value db.liveTicketCache[hash] = val db.poolValue += val } for _, h := range poolDiff.Out { valOut, ok := db.liveTicketCache[h] if !ok { log.Debugf("Didn't find %v in live ticket cache, cannot remove it.", h) continue } db.poolValue -= valOut delete(db.liveTicketCache, h) } db.liveTicketMtx.Unlock() }
[ "func", "(", "db", "*", "StakeDatabase", ")", "applyDiff", "(", "poolDiff", "PoolDiff", ")", "{", "db", ".", "liveTicketMtx", ".", "Lock", "(", ")", "\n", "for", "_", ",", "hash", ":=", "range", "poolDiff", ".", "In", "{", "_", ",", "ok", ":=", "db", ".", "liveTicketCache", "[", "hash", "]", "\n", "if", "ok", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "hash", ")", "\n", "continue", "\n", "}", "\n\n", "tx", ",", "err", ":=", "db", ".", "NodeClient", ".", "GetRawTransaction", "(", "&", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "hash", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "// This isn't quite right for pool tickets where the small", "// pool fees are included in vout[0], but it's close.", "val", ":=", "tx", ".", "MsgTx", "(", ")", ".", "TxOut", "[", "0", "]", ".", "Value", "\n", "db", ".", "liveTicketCache", "[", "hash", "]", "=", "val", "\n", "db", ".", "poolValue", "+=", "val", "\n", "}", "\n\n", "for", "_", ",", "h", ":=", "range", "poolDiff", ".", "Out", "{", "valOut", ",", "ok", ":=", "db", ".", "liveTicketCache", "[", "h", "]", "\n", "if", "!", "ok", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "h", ")", "\n", "continue", "\n", "}", "\n", "db", ".", "poolValue", "-=", "valOut", "\n", "delete", "(", "db", ".", "liveTicketCache", ",", "h", ")", "\n", "}", "\n", "db", ".", "liveTicketMtx", ".", "Unlock", "(", ")", "\n", "}" ]
// applyDiff updates liveTicketCache and poolValue for the given PoolDiff.
[ "applyDiff", "updates", "liveTicketCache", "and", "poolValue", "for", "the", "given", "PoolDiff", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L601-L632
train
decred/dcrdata
stakedb/stakedb.go
undoDiff
func (db *StakeDatabase) undoDiff(poolDiff PoolDiff) { db.applyDiff(PoolDiff{ In: poolDiff.Out, Out: poolDiff.In, }) }
go
func (db *StakeDatabase) undoDiff(poolDiff PoolDiff) { db.applyDiff(PoolDiff{ In: poolDiff.Out, Out: poolDiff.In, }) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "undoDiff", "(", "poolDiff", "PoolDiff", ")", "{", "db", ".", "applyDiff", "(", "PoolDiff", "{", "In", ":", "poolDiff", ".", "Out", ",", "Out", ":", "poolDiff", ".", "In", ",", "}", ")", "\n", "}" ]
// undoDiff is like applyDiff except it swaps In and Out in the specified // PoolDiff.
[ "undoDiff", "is", "like", "applyDiff", "except", "it", "swaps", "In", "and", "Out", "in", "the", "specified", "PoolDiff", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L636-L641
train
decred/dcrdata
stakedb/stakedb.go
SetPoolInfo
func (db *StakeDatabase) SetPoolInfo(blockHash chainhash.Hash, tpi *apitypes.TicketPoolInfo) { db.poolInfo.Set(blockHash, tpi) }
go
func (db *StakeDatabase) SetPoolInfo(blockHash chainhash.Hash, tpi *apitypes.TicketPoolInfo) { db.poolInfo.Set(blockHash, tpi) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "SetPoolInfo", "(", "blockHash", "chainhash", ".", "Hash", ",", "tpi", "*", "apitypes", ".", "TicketPoolInfo", ")", "{", "db", ".", "poolInfo", ".", "Set", "(", "blockHash", ",", "tpi", ")", "\n", "}" ]
// SetPoolInfo stores the ticket pool info for the given hash in the pool info // cache.
[ "SetPoolInfo", "stores", "the", "ticket", "pool", "info", "for", "the", "given", "hash", "in", "the", "pool", "info", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L645-L647
train
decred/dcrdata
stakedb/stakedb.go
SetPoolCacheCapacity
func (db *StakeDatabase) SetPoolCacheCapacity(cap int) error { return db.poolInfo.SetCapacity(cap) }
go
func (db *StakeDatabase) SetPoolCacheCapacity(cap int) error { return db.poolInfo.SetCapacity(cap) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "SetPoolCacheCapacity", "(", "cap", "int", ")", "error", "{", "return", "db", ".", "poolInfo", ".", "SetCapacity", "(", "cap", ")", "\n", "}" ]
// SetPoolCacheCapacity sets the pool info cache capacity to the specified // number of elements.
[ "SetPoolCacheCapacity", "sets", "the", "pool", "info", "cache", "capacity", "to", "the", "specified", "number", "of", "elements", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L651-L653
train
decred/dcrdata
stakedb/stakedb.go
DisconnectBlock
func (db *StakeDatabase) DisconnectBlock(neglectCache bool) error { db.nodeMtx.Lock() defer db.nodeMtx.Unlock() return db.disconnectBlock(neglectCache) }
go
func (db *StakeDatabase) DisconnectBlock(neglectCache bool) error { db.nodeMtx.Lock() defer db.nodeMtx.Unlock() return db.disconnectBlock(neglectCache) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "DisconnectBlock", "(", "neglectCache", "bool", ")", "error", "{", "db", ".", "nodeMtx", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "nodeMtx", ".", "Unlock", "(", ")", "\n\n", "return", "db", ".", "disconnectBlock", "(", "neglectCache", ")", "\n", "}" ]
// DisconnectBlock attempts to disconnect the current best block from the stake // DB and updates the best stake node. If the ticket pool db is advanced to the // tip, it is trimmed, and the cache and pool value are updated. If neglectCache // is true, the trim is performed, but cache and pool value are not updated. // Only use neglectCache=true if you plan to
[ "DisconnectBlock", "attempts", "to", "disconnect", "the", "current", "best", "block", "from", "the", "stake", "DB", "and", "updates", "the", "best", "stake", "node", ".", "If", "the", "ticket", "pool", "db", "is", "advanced", "to", "the", "tip", "it", "is", "trimmed", "and", "the", "cache", "and", "pool", "value", "are", "updated", ".", "If", "neglectCache", "is", "true", "the", "trim", "is", "performed", "but", "cache", "and", "pool", "value", "are", "not", "updated", ".", "Only", "use", "neglectCache", "=", "true", "if", "you", "plan", "to" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L660-L665
train
decred/dcrdata
stakedb/stakedb.go
disconnectBlock
func (db *StakeDatabase) disconnectBlock(neglectCache bool) error { childHeight := db.BestNode.Height() parentBlock, err := db.dbPrevBlock() if err != nil { return err } if parentBlock.Height() != int64(childHeight)-1 { panic("BestNode and stake DB are inconsistent") } // Trim the ticket pool db to the same height as stake.Node var undoDiffs []PoolDiff poolDBTip := db.PoolDB.tip for poolDBTip > parentBlock.Height() { newTip, undoDiff := db.PoolDB.Trim() undoDiffs = append(undoDiffs, undoDiff) if newTip >= poolDBTip { panic("unable to trim pool DB!") } poolDBTip = newTip } // Update liveTicketCache and poolValue if !neglectCache { for i := range undoDiffs { db.undoDiff(undoDiffs[i]) } } log.Tracef("Disconnecting block %d.", childHeight) childUndoData := append(stake.UndoTicketDataSlice(nil), db.BestNode.UndoData()...) // previous best node hB, errx := parentBlock.BlockHeaderBytes() if errx != nil { return fmt.Errorf("unable to serialize block header: %v", errx) } parentIV := stake.CalcHash256PRNGIV(hB) var parentStakeNode *stake.Node err = db.StakeDB.View(func(dbTx database.Tx) error { var errLocal error parentStakeNode, errLocal = db.BestNode.DisconnectNode(parentIV, nil, nil, dbTx) return errLocal }) if err != nil { return err } if parentStakeNode == nil { return fmt.Errorf("failed to DisconnectNode at BestNode") } db.BestNode = parentStakeNode return db.StakeDB.Update(func(dbTx database.Tx) error { return stake.WriteDisconnectedBestNode(dbTx, parentStakeNode, *parentBlock.Hash(), childUndoData) }) }
go
func (db *StakeDatabase) disconnectBlock(neglectCache bool) error { childHeight := db.BestNode.Height() parentBlock, err := db.dbPrevBlock() if err != nil { return err } if parentBlock.Height() != int64(childHeight)-1 { panic("BestNode and stake DB are inconsistent") } // Trim the ticket pool db to the same height as stake.Node var undoDiffs []PoolDiff poolDBTip := db.PoolDB.tip for poolDBTip > parentBlock.Height() { newTip, undoDiff := db.PoolDB.Trim() undoDiffs = append(undoDiffs, undoDiff) if newTip >= poolDBTip { panic("unable to trim pool DB!") } poolDBTip = newTip } // Update liveTicketCache and poolValue if !neglectCache { for i := range undoDiffs { db.undoDiff(undoDiffs[i]) } } log.Tracef("Disconnecting block %d.", childHeight) childUndoData := append(stake.UndoTicketDataSlice(nil), db.BestNode.UndoData()...) // previous best node hB, errx := parentBlock.BlockHeaderBytes() if errx != nil { return fmt.Errorf("unable to serialize block header: %v", errx) } parentIV := stake.CalcHash256PRNGIV(hB) var parentStakeNode *stake.Node err = db.StakeDB.View(func(dbTx database.Tx) error { var errLocal error parentStakeNode, errLocal = db.BestNode.DisconnectNode(parentIV, nil, nil, dbTx) return errLocal }) if err != nil { return err } if parentStakeNode == nil { return fmt.Errorf("failed to DisconnectNode at BestNode") } db.BestNode = parentStakeNode return db.StakeDB.Update(func(dbTx database.Tx) error { return stake.WriteDisconnectedBestNode(dbTx, parentStakeNode, *parentBlock.Hash(), childUndoData) }) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "disconnectBlock", "(", "neglectCache", "bool", ")", "error", "{", "childHeight", ":=", "db", ".", "BestNode", ".", "Height", "(", ")", "\n", "parentBlock", ",", "err", ":=", "db", ".", "dbPrevBlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "parentBlock", ".", "Height", "(", ")", "!=", "int64", "(", "childHeight", ")", "-", "1", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Trim the ticket pool db to the same height as stake.Node", "var", "undoDiffs", "[", "]", "PoolDiff", "\n", "poolDBTip", ":=", "db", ".", "PoolDB", ".", "tip", "\n", "for", "poolDBTip", ">", "parentBlock", ".", "Height", "(", ")", "{", "newTip", ",", "undoDiff", ":=", "db", ".", "PoolDB", ".", "Trim", "(", ")", "\n", "undoDiffs", "=", "append", "(", "undoDiffs", ",", "undoDiff", ")", "\n", "if", "newTip", ">=", "poolDBTip", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "poolDBTip", "=", "newTip", "\n", "}", "\n\n", "// Update liveTicketCache and poolValue", "if", "!", "neglectCache", "{", "for", "i", ":=", "range", "undoDiffs", "{", "db", ".", "undoDiff", "(", "undoDiffs", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "childHeight", ")", "\n", "childUndoData", ":=", "append", "(", "stake", ".", "UndoTicketDataSlice", "(", "nil", ")", ",", "db", ".", "BestNode", ".", "UndoData", "(", ")", "...", ")", "\n\n", "// previous best node", "hB", ",", "errx", ":=", "parentBlock", ".", "BlockHeaderBytes", "(", ")", "\n", "if", "errx", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "errx", ")", "\n", "}", "\n", "parentIV", ":=", "stake", ".", "CalcHash256PRNGIV", "(", "hB", ")", "\n\n", "var", "parentStakeNode", "*", "stake", ".", "Node", "\n", "err", "=", "db", ".", "StakeDB", ".", "View", "(", "func", "(", "dbTx", "database", ".", "Tx", ")", "error", "{", "var", "errLocal", "error", "\n", "parentStakeNode", ",", "errLocal", "=", "db", ".", "BestNode", ".", "DisconnectNode", "(", "parentIV", ",", "nil", ",", "nil", ",", "dbTx", ")", "\n", "return", "errLocal", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "parentStakeNode", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "db", ".", "BestNode", "=", "parentStakeNode", "\n\n", "return", "db", ".", "StakeDB", ".", "Update", "(", "func", "(", "dbTx", "database", ".", "Tx", ")", "error", "{", "return", "stake", ".", "WriteDisconnectedBestNode", "(", "dbTx", ",", "parentStakeNode", ",", "*", "parentBlock", ".", "Hash", "(", ")", ",", "childUndoData", ")", "\n", "}", ")", "\n", "}" ]
// disconnectBlock is the non-thread-safe version of DisconnectBlock.
[ "disconnectBlock", "is", "the", "non", "-", "thread", "-", "safe", "version", "of", "DisconnectBlock", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L668-L725
train
decred/dcrdata
stakedb/stakedb.go
DisconnectBlocks
func (db *StakeDatabase) DisconnectBlocks(count int64) error { db.nodeMtx.Lock() defer db.nodeMtx.Unlock() for i := int64(0); i < count; i++ { if err := db.disconnectBlock(false); err != nil { return err } } return nil }
go
func (db *StakeDatabase) DisconnectBlocks(count int64) error { db.nodeMtx.Lock() defer db.nodeMtx.Unlock() for i := int64(0); i < count; i++ { if err := db.disconnectBlock(false); err != nil { return err } } return nil }
[ "func", "(", "db", "*", "StakeDatabase", ")", "DisconnectBlocks", "(", "count", "int64", ")", "error", "{", "db", ".", "nodeMtx", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "nodeMtx", ".", "Unlock", "(", ")", "\n\n", "for", "i", ":=", "int64", "(", "0", ")", ";", "i", "<", "count", ";", "i", "++", "{", "if", "err", ":=", "db", ".", "disconnectBlock", "(", "false", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// DisconnectBlocks disconnects N blocks from the head of the chain.
[ "DisconnectBlocks", "disconnects", "N", "blocks", "from", "the", "head", "of", "the", "chain", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L728-L739
train
decred/dcrdata
stakedb/stakedb.go
Open
func (db *StakeDatabase) Open(dbName string) error { db.nodeMtx.Lock() defer db.nodeMtx.Unlock() // Create a new database to store the accepted stake node data into. var isFreshDB bool var err error db.StakeDB, err = database.Open(dbType, dbName, db.params.Net) if err != nil { if strings.Contains(err.Error(), "resource temporarily unavailable") || strings.Contains(err.Error(), "is being used by another process") { return fmt.Errorf("Stake DB already opened. dcrdata running?") } if strings.Contains(err.Error(), "does not exist") { log.Info("Creating new stake DB.") } else { log.Infof("Unable to open stake DB (%v). Removing and creating new.", err) _ = os.RemoveAll(dbName) } db.StakeDB, err = database.Create(dbType, dbName, db.params.Net) if err != nil { // do not return nil interface, but interface of nil DB return fmt.Errorf("error creating database.DB: %v", err) } isFreshDB = true } // Load the best block from stake db err = db.StakeDB.View(func(dbTx database.Tx) error { v := dbTx.Metadata().Get([]byte("stakechainstate")) if v == nil { return fmt.Errorf("missing key for chain state data") } var stakeDBHash chainhash.Hash copy(stakeDBHash[:], v[:chainhash.HashSize]) offset := chainhash.HashSize stakeDBHeight := binary.LittleEndian.Uint32(v[offset : offset+4]) var errLocal error msgBlock, errLocal := db.NodeClient.GetBlock(&stakeDBHash) if errLocal != nil { return fmt.Errorf("GetBlock failed (%s): %v", stakeDBHash, errLocal) } header := msgBlock.Header db.BestNode, errLocal = stake.LoadBestNode(dbTx, stakeDBHeight, stakeDBHash, header, db.params) return errLocal }) if err != nil { if !isFreshDB { log.Errorf("Error reading from database (%v). Reinitializing.", err) } err = db.StakeDB.Update(func(dbTx database.Tx) error { var errLocal error db.BestNode, errLocal = stake.InitDatabaseState(dbTx, db.params) return errLocal }) log.Debug("Initialized new stake db.") } else { log.Debug("Opened existing stake db.") } return err }
go
func (db *StakeDatabase) Open(dbName string) error { db.nodeMtx.Lock() defer db.nodeMtx.Unlock() // Create a new database to store the accepted stake node data into. var isFreshDB bool var err error db.StakeDB, err = database.Open(dbType, dbName, db.params.Net) if err != nil { if strings.Contains(err.Error(), "resource temporarily unavailable") || strings.Contains(err.Error(), "is being used by another process") { return fmt.Errorf("Stake DB already opened. dcrdata running?") } if strings.Contains(err.Error(), "does not exist") { log.Info("Creating new stake DB.") } else { log.Infof("Unable to open stake DB (%v). Removing and creating new.", err) _ = os.RemoveAll(dbName) } db.StakeDB, err = database.Create(dbType, dbName, db.params.Net) if err != nil { // do not return nil interface, but interface of nil DB return fmt.Errorf("error creating database.DB: %v", err) } isFreshDB = true } // Load the best block from stake db err = db.StakeDB.View(func(dbTx database.Tx) error { v := dbTx.Metadata().Get([]byte("stakechainstate")) if v == nil { return fmt.Errorf("missing key for chain state data") } var stakeDBHash chainhash.Hash copy(stakeDBHash[:], v[:chainhash.HashSize]) offset := chainhash.HashSize stakeDBHeight := binary.LittleEndian.Uint32(v[offset : offset+4]) var errLocal error msgBlock, errLocal := db.NodeClient.GetBlock(&stakeDBHash) if errLocal != nil { return fmt.Errorf("GetBlock failed (%s): %v", stakeDBHash, errLocal) } header := msgBlock.Header db.BestNode, errLocal = stake.LoadBestNode(dbTx, stakeDBHeight, stakeDBHash, header, db.params) return errLocal }) if err != nil { if !isFreshDB { log.Errorf("Error reading from database (%v). Reinitializing.", err) } err = db.StakeDB.Update(func(dbTx database.Tx) error { var errLocal error db.BestNode, errLocal = stake.InitDatabaseState(dbTx, db.params) return errLocal }) log.Debug("Initialized new stake db.") } else { log.Debug("Opened existing stake db.") } return err }
[ "func", "(", "db", "*", "StakeDatabase", ")", "Open", "(", "dbName", "string", ")", "error", "{", "db", ".", "nodeMtx", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "nodeMtx", ".", "Unlock", "(", ")", "\n\n", "// Create a new database to store the accepted stake node data into.", "var", "isFreshDB", "bool", "\n", "var", "err", "error", "\n", "db", ".", "StakeDB", ",", "err", "=", "database", ".", "Open", "(", "dbType", ",", "dbName", ",", "db", ".", "params", ".", "Net", ")", "\n", "if", "err", "!=", "nil", "{", "if", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "||", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "else", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "err", ")", "\n", "_", "=", "os", ".", "RemoveAll", "(", "dbName", ")", "\n", "}", "\n\n", "db", ".", "StakeDB", ",", "err", "=", "database", ".", "Create", "(", "dbType", ",", "dbName", ",", "db", ".", "params", ".", "Net", ")", "\n", "if", "err", "!=", "nil", "{", "// do not return nil interface, but interface of nil DB", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "isFreshDB", "=", "true", "\n", "}", "\n\n", "// Load the best block from stake db", "err", "=", "db", ".", "StakeDB", ".", "View", "(", "func", "(", "dbTx", "database", ".", "Tx", ")", "error", "{", "v", ":=", "dbTx", ".", "Metadata", "(", ")", ".", "Get", "(", "[", "]", "byte", "(", "\"", "\"", ")", ")", "\n", "if", "v", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "stakeDBHash", "chainhash", ".", "Hash", "\n", "copy", "(", "stakeDBHash", "[", ":", "]", ",", "v", "[", ":", "chainhash", ".", "HashSize", "]", ")", "\n", "offset", ":=", "chainhash", ".", "HashSize", "\n", "stakeDBHeight", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "v", "[", "offset", ":", "offset", "+", "4", "]", ")", "\n\n", "var", "errLocal", "error", "\n", "msgBlock", ",", "errLocal", ":=", "db", ".", "NodeClient", ".", "GetBlock", "(", "&", "stakeDBHash", ")", "\n", "if", "errLocal", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "stakeDBHash", ",", "errLocal", ")", "\n", "}", "\n", "header", ":=", "msgBlock", ".", "Header", "\n\n", "db", ".", "BestNode", ",", "errLocal", "=", "stake", ".", "LoadBestNode", "(", "dbTx", ",", "stakeDBHeight", ",", "stakeDBHash", ",", "header", ",", "db", ".", "params", ")", "\n", "return", "errLocal", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "isFreshDB", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "db", ".", "StakeDB", ".", "Update", "(", "func", "(", "dbTx", "database", ".", "Tx", ")", "error", "{", "var", "errLocal", "error", "\n", "db", ".", "BestNode", ",", "errLocal", "=", "stake", ".", "InitDatabaseState", "(", "dbTx", ",", "db", ".", "params", ")", "\n", "return", "errLocal", "\n", "}", ")", "\n", "log", ".", "Debug", "(", "\"", "\"", ")", "\n", "}", "else", "{", "log", ".", "Debug", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// Open attempts to open an existing stake database, and will create a new one // if one does not exist.
[ "Open", "attempts", "to", "open", "an", "existing", "stake", "database", "and", "will", "create", "a", "new", "one", "if", "one", "does", "not", "exist", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L743-L809
train
decred/dcrdata
stakedb/stakedb.go
Close
func (db *StakeDatabase) Close() error { db.nodeMtx.Lock() defer db.nodeMtx.Unlock() err1 := db.PoolDB.Close() err2 := db.StakeDB.Close() if err1 == nil { return err2 } if err2 == nil { return err1 } return fmt.Errorf("%v + %v", err1, err2) }
go
func (db *StakeDatabase) Close() error { db.nodeMtx.Lock() defer db.nodeMtx.Unlock() err1 := db.PoolDB.Close() err2 := db.StakeDB.Close() if err1 == nil { return err2 } if err2 == nil { return err1 } return fmt.Errorf("%v + %v", err1, err2) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "Close", "(", ")", "error", "{", "db", ".", "nodeMtx", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "nodeMtx", ".", "Unlock", "(", ")", "\n", "err1", ":=", "db", ".", "PoolDB", ".", "Close", "(", ")", "\n", "err2", ":=", "db", ".", "StakeDB", ".", "Close", "(", ")", "\n", "if", "err1", "==", "nil", "{", "return", "err2", "\n", "}", "\n", "if", "err2", "==", "nil", "{", "return", "err1", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err1", ",", "err2", ")", "\n", "}" ]
// Close will close the ticket pool and stake databases.
[ "Close", "will", "close", "the", "ticket", "pool", "and", "stake", "databases", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L812-L824
train
decred/dcrdata
stakedb/stakedb.go
PoolInfoBest
func (db *StakeDatabase) PoolInfoBest() *apitypes.TicketPoolInfo { db.nodeMtx.RLock() if db.BestNode == nil { db.nodeMtx.RUnlock() log.Errorf("PoolInfoBest: BestNode is nil!") return nil } poolSize := db.BestNode.PoolSize() //liveTickets := db.BestNode.LiveTickets() winningTickets := db.BestNode.Winners() height := db.BestNode.Height() // expiredTickets, expireRevoked := db.expires() db.nodeMtx.RUnlock() return db.makePoolInfo(db.poolValue, int64(poolSize), winningTickets, height) // db.calcPoolInfo(liveTickets, winningTickets, height) }
go
func (db *StakeDatabase) PoolInfoBest() *apitypes.TicketPoolInfo { db.nodeMtx.RLock() if db.BestNode == nil { db.nodeMtx.RUnlock() log.Errorf("PoolInfoBest: BestNode is nil!") return nil } poolSize := db.BestNode.PoolSize() //liveTickets := db.BestNode.LiveTickets() winningTickets := db.BestNode.Winners() height := db.BestNode.Height() // expiredTickets, expireRevoked := db.expires() db.nodeMtx.RUnlock() return db.makePoolInfo(db.poolValue, int64(poolSize), winningTickets, height) // db.calcPoolInfo(liveTickets, winningTickets, height) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "PoolInfoBest", "(", ")", "*", "apitypes", ".", "TicketPoolInfo", "{", "db", ".", "nodeMtx", ".", "RLock", "(", ")", "\n", "if", "db", ".", "BestNode", "==", "nil", "{", "db", ".", "nodeMtx", ".", "RUnlock", "(", ")", "\n", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n", "poolSize", ":=", "db", ".", "BestNode", ".", "PoolSize", "(", ")", "\n", "//liveTickets := db.BestNode.LiveTickets()", "winningTickets", ":=", "db", ".", "BestNode", ".", "Winners", "(", ")", "\n", "height", ":=", "db", ".", "BestNode", ".", "Height", "(", ")", "\n", "// expiredTickets, expireRevoked := db.expires()", "db", ".", "nodeMtx", ".", "RUnlock", "(", ")", "\n\n", "return", "db", ".", "makePoolInfo", "(", "db", ".", "poolValue", ",", "int64", "(", "poolSize", ")", ",", "winningTickets", ",", "height", ")", "// db.calcPoolInfo(liveTickets, winningTickets, height)", "\n", "}" ]
// PoolInfoBest computes ticket pool value using the database and, if needed, the // node RPC client to fetch ticket values that are not cached. Returned are a // structure including ticket pool value, size, and average value.
[ "PoolInfoBest", "computes", "ticket", "pool", "value", "using", "the", "database", "and", "if", "needed", "the", "node", "RPC", "client", "to", "fetch", "ticket", "values", "that", "are", "not", "cached", ".", "Returned", "are", "a", "structure", "including", "ticket", "pool", "value", "size", "and", "average", "value", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L852-L867
train
decred/dcrdata
stakedb/stakedb.go
PoolInfo
func (db *StakeDatabase) PoolInfo(hash chainhash.Hash) (*apitypes.TicketPoolInfo, bool) { return db.poolInfo.Get(hash) }
go
func (db *StakeDatabase) PoolInfo(hash chainhash.Hash) (*apitypes.TicketPoolInfo, bool) { return db.poolInfo.Get(hash) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "PoolInfo", "(", "hash", "chainhash", ".", "Hash", ")", "(", "*", "apitypes", ".", "TicketPoolInfo", ",", "bool", ")", "{", "return", "db", ".", "poolInfo", ".", "Get", "(", "hash", ")", "\n", "}" ]
// PoolInfo attempts to fetch the ticket pool info for the specified block hash // from an internal pool info cache. If it is not found, you should attempt to // use PoolInfoBest if the target block is at the tip of the chain.
[ "PoolInfo", "attempts", "to", "fetch", "the", "ticket", "pool", "info", "for", "the", "specified", "block", "hash", "from", "an", "internal", "pool", "info", "cache", ".", "If", "it", "is", "not", "found", "you", "should", "attempt", "to", "use", "PoolInfoBest", "if", "the", "target", "block", "is", "at", "the", "tip", "of", "the", "chain", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L935-L937
train
decred/dcrdata
stakedb/stakedb.go
PoolSize
func (db *StakeDatabase) PoolSize() int { db.nodeMtx.Lock() defer db.nodeMtx.Unlock() return db.BestNode.PoolSize() }
go
func (db *StakeDatabase) PoolSize() int { db.nodeMtx.Lock() defer db.nodeMtx.Unlock() return db.BestNode.PoolSize() }
[ "func", "(", "db", "*", "StakeDatabase", ")", "PoolSize", "(", ")", "int", "{", "db", ".", "nodeMtx", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "nodeMtx", ".", "Unlock", "(", ")", "\n", "return", "db", ".", "BestNode", ".", "PoolSize", "(", ")", "\n", "}" ]
// PoolSize returns the ticket pool size in the best node of the stake database
[ "PoolSize", "returns", "the", "ticket", "pool", "size", "in", "the", "best", "node", "of", "the", "stake", "database" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L940-L944
train
decred/dcrdata
stakedb/stakedb.go
PoolAtHeight
func (db *StakeDatabase) PoolAtHeight(height int64) ([]chainhash.Hash, error) { return db.PoolDB.Pool(height) }
go
func (db *StakeDatabase) PoolAtHeight(height int64) ([]chainhash.Hash, error) { return db.PoolDB.Pool(height) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "PoolAtHeight", "(", "height", "int64", ")", "(", "[", "]", "chainhash", ".", "Hash", ",", "error", ")", "{", "return", "db", ".", "PoolDB", ".", "Pool", "(", "height", ")", "\n", "}" ]
// PoolAtHeight gets the entire list of live tickets at the given chain height.
[ "PoolAtHeight", "gets", "the", "entire", "list", "of", "live", "tickets", "at", "the", "given", "chain", "height", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L947-L949
train
decred/dcrdata
stakedb/stakedb.go
PoolAtHash
func (db *StakeDatabase) PoolAtHash(hash chainhash.Hash) ([]chainhash.Hash, error) { header, err := db.NodeClient.GetBlockHeader(&hash) if err != nil { return nil, fmt.Errorf("GetBlockHeader failed: %v", err) } return db.PoolDB.Pool(int64(header.Height)) }
go
func (db *StakeDatabase) PoolAtHash(hash chainhash.Hash) ([]chainhash.Hash, error) { header, err := db.NodeClient.GetBlockHeader(&hash) if err != nil { return nil, fmt.Errorf("GetBlockHeader failed: %v", err) } return db.PoolDB.Pool(int64(header.Height)) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "PoolAtHash", "(", "hash", "chainhash", ".", "Hash", ")", "(", "[", "]", "chainhash", ".", "Hash", ",", "error", ")", "{", "header", ",", "err", ":=", "db", ".", "NodeClient", ".", "GetBlockHeader", "(", "&", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "db", ".", "PoolDB", ".", "Pool", "(", "int64", "(", "header", ".", "Height", ")", ")", "\n", "}" ]
// PoolAtHash gets the entire list of live tickets at the given block hash.
[ "PoolAtHash", "gets", "the", "entire", "list", "of", "live", "tickets", "at", "the", "given", "block", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L952-L958
train
decred/dcrdata
stakedb/stakedb.go
DBState
func (db *StakeDatabase) DBState() (uint32, *chainhash.Hash, error) { db.nodeMtx.RLock() defer db.nodeMtx.RUnlock() return db.dbState() }
go
func (db *StakeDatabase) DBState() (uint32, *chainhash.Hash, error) { db.nodeMtx.RLock() defer db.nodeMtx.RUnlock() return db.dbState() }
[ "func", "(", "db", "*", "StakeDatabase", ")", "DBState", "(", ")", "(", "uint32", ",", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "db", ".", "nodeMtx", ".", "RLock", "(", ")", "\n", "defer", "db", ".", "nodeMtx", ".", "RUnlock", "(", ")", "\n\n", "return", "db", ".", "dbState", "(", ")", "\n", "}" ]
// DBState queries the stake database for the best block height and hash.
[ "DBState", "queries", "the", "stake", "database", "for", "the", "best", "block", "height", "and", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L961-L966
train