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
dcrrates/rateserver/types.go
deleteClient
func (server *RateServer) deleteClient(sid StreamID) { server.clientLock.Lock() defer server.clientLock.Unlock() delete(server.clients, sid) }
go
func (server *RateServer) deleteClient(sid StreamID) { server.clientLock.Lock() defer server.clientLock.Unlock() delete(server.clients, sid) }
[ "func", "(", "server", "*", "RateServer", ")", "deleteClient", "(", "sid", "StreamID", ")", "{", "server", ".", "clientLock", ".", "Lock", "(", ")", "\n", "defer", "server", ".", "clientLock", ".", "Unlock", "(", ")", "\n", "delete", "(", "server", ".", "clients", ",", "sid", ")", "\n", "}" ]
// deleteClient deletes the client from the map.
[ "deleteClient", "deletes", "the", "client", "from", "the", "map", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/dcrrates/rateserver/types.go#L135-L139
train
decred/dcrdata
dcrrates/rateserver/types.go
NewRateClient
func NewRateClient(stream GRPCStream, exchanges []string) RateClient { return &rateClient{ stream: stream, exchanges: exchanges, } }
go
func NewRateClient(stream GRPCStream, exchanges []string) RateClient { return &rateClient{ stream: stream, exchanges: exchanges, } }
[ "func", "NewRateClient", "(", "stream", "GRPCStream", ",", "exchanges", "[", "]", "string", ")", "RateClient", "{", "return", "&", "rateClient", "{", "stream", ":", "stream", ",", "exchanges", ":", "exchanges", ",", "}", "\n", "}" ]
// NewRateClient is a constructor for rate client. It returns the RateClient // interface rather than rateClient itself.
[ "NewRateClient", "is", "a", "constructor", "for", "rate", "client", ".", "It", "returns", "the", "RateClient", "interface", "rather", "than", "rateClient", "itself", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/dcrrates/rateserver/types.go#L150-L155
train
decred/dcrdata
dcrrates/rateserver/types.go
makeExchangeRateUpdate
func makeExchangeRateUpdate(update *exchanges.ExchangeUpdate) *dcrrates.ExchangeRateUpdate { state := update.State protoUpdate := &dcrrates.ExchangeRateUpdate{ Token: update.Token, Price: state.Price, BaseVolume: state.BaseVolume, Volume: state.Volume, Change: state.Change, Stamp: state.Stamp, } if state.Candlesticks != nil { protoUpdate.Candlesticks = make([]*dcrrates.ExchangeRateUpdate_Candlesticks, 0, len(state.Candlesticks)) for bin, sticks := range state.Candlesticks { candlesticks := &dcrrates.ExchangeRateUpdate_Candlesticks{ Bin: string(bin), Sticks: make([]*dcrrates.ExchangeRateUpdate_Candlestick, 0, len(sticks)), } for _, stick := range sticks { candlesticks.Sticks = append(candlesticks.Sticks, &dcrrates.ExchangeRateUpdate_Candlestick{ High: stick.High, Low: stick.Low, Open: stick.Open, Close: stick.Close, Volume: stick.Volume, Start: stick.Start.Unix(), }) } protoUpdate.Candlesticks = append(protoUpdate.Candlesticks, candlesticks) } } if state.Depth != nil { depth := &dcrrates.ExchangeRateUpdate_DepthData{ Time: state.Depth.Time, Bids: make([]*dcrrates.ExchangeRateUpdate_DepthPoint, 0, len(state.Depth.Bids)), Asks: make([]*dcrrates.ExchangeRateUpdate_DepthPoint, 0, len(state.Depth.Asks)), } for _, pt := range state.Depth.Bids { depth.Bids = append(depth.Bids, &dcrrates.ExchangeRateUpdate_DepthPoint{ Quantity: pt.Quantity, Price: pt.Price, }) } for _, pt := range state.Depth.Asks { depth.Asks = append(depth.Asks, &dcrrates.ExchangeRateUpdate_DepthPoint{ Quantity: pt.Quantity, Price: pt.Price, }) } protoUpdate.Depth = depth } return protoUpdate }
go
func makeExchangeRateUpdate(update *exchanges.ExchangeUpdate) *dcrrates.ExchangeRateUpdate { state := update.State protoUpdate := &dcrrates.ExchangeRateUpdate{ Token: update.Token, Price: state.Price, BaseVolume: state.BaseVolume, Volume: state.Volume, Change: state.Change, Stamp: state.Stamp, } if state.Candlesticks != nil { protoUpdate.Candlesticks = make([]*dcrrates.ExchangeRateUpdate_Candlesticks, 0, len(state.Candlesticks)) for bin, sticks := range state.Candlesticks { candlesticks := &dcrrates.ExchangeRateUpdate_Candlesticks{ Bin: string(bin), Sticks: make([]*dcrrates.ExchangeRateUpdate_Candlestick, 0, len(sticks)), } for _, stick := range sticks { candlesticks.Sticks = append(candlesticks.Sticks, &dcrrates.ExchangeRateUpdate_Candlestick{ High: stick.High, Low: stick.Low, Open: stick.Open, Close: stick.Close, Volume: stick.Volume, Start: stick.Start.Unix(), }) } protoUpdate.Candlesticks = append(protoUpdate.Candlesticks, candlesticks) } } if state.Depth != nil { depth := &dcrrates.ExchangeRateUpdate_DepthData{ Time: state.Depth.Time, Bids: make([]*dcrrates.ExchangeRateUpdate_DepthPoint, 0, len(state.Depth.Bids)), Asks: make([]*dcrrates.ExchangeRateUpdate_DepthPoint, 0, len(state.Depth.Asks)), } for _, pt := range state.Depth.Bids { depth.Bids = append(depth.Bids, &dcrrates.ExchangeRateUpdate_DepthPoint{ Quantity: pt.Quantity, Price: pt.Price, }) } for _, pt := range state.Depth.Asks { depth.Asks = append(depth.Asks, &dcrrates.ExchangeRateUpdate_DepthPoint{ Quantity: pt.Quantity, Price: pt.Price, }) } protoUpdate.Depth = depth } return protoUpdate }
[ "func", "makeExchangeRateUpdate", "(", "update", "*", "exchanges", ".", "ExchangeUpdate", ")", "*", "dcrrates", ".", "ExchangeRateUpdate", "{", "state", ":=", "update", ".", "State", "\n", "protoUpdate", ":=", "&", "dcrrates", ".", "ExchangeRateUpdate", "{", "Token", ":", "update", ".", "Token", ",", "Price", ":", "state", ".", "Price", ",", "BaseVolume", ":", "state", ".", "BaseVolume", ",", "Volume", ":", "state", ".", "Volume", ",", "Change", ":", "state", ".", "Change", ",", "Stamp", ":", "state", ".", "Stamp", ",", "}", "\n", "if", "state", ".", "Candlesticks", "!=", "nil", "{", "protoUpdate", ".", "Candlesticks", "=", "make", "(", "[", "]", "*", "dcrrates", ".", "ExchangeRateUpdate_Candlesticks", ",", "0", ",", "len", "(", "state", ".", "Candlesticks", ")", ")", "\n", "for", "bin", ",", "sticks", ":=", "range", "state", ".", "Candlesticks", "{", "candlesticks", ":=", "&", "dcrrates", ".", "ExchangeRateUpdate_Candlesticks", "{", "Bin", ":", "string", "(", "bin", ")", ",", "Sticks", ":", "make", "(", "[", "]", "*", "dcrrates", ".", "ExchangeRateUpdate_Candlestick", ",", "0", ",", "len", "(", "sticks", ")", ")", ",", "}", "\n", "for", "_", ",", "stick", ":=", "range", "sticks", "{", "candlesticks", ".", "Sticks", "=", "append", "(", "candlesticks", ".", "Sticks", ",", "&", "dcrrates", ".", "ExchangeRateUpdate_Candlestick", "{", "High", ":", "stick", ".", "High", ",", "Low", ":", "stick", ".", "Low", ",", "Open", ":", "stick", ".", "Open", ",", "Close", ":", "stick", ".", "Close", ",", "Volume", ":", "stick", ".", "Volume", ",", "Start", ":", "stick", ".", "Start", ".", "Unix", "(", ")", ",", "}", ")", "\n", "}", "\n", "protoUpdate", ".", "Candlesticks", "=", "append", "(", "protoUpdate", ".", "Candlesticks", ",", "candlesticks", ")", "\n", "}", "\n", "}", "\n\n", "if", "state", ".", "Depth", "!=", "nil", "{", "depth", ":=", "&", "dcrrates", ".", "ExchangeRateUpdate_DepthData", "{", "Time", ":", "state", ".", "Depth", ".", "Time", ",", "Bids", ":", "make", "(", "[", "]", "*", "dcrrates", ".", "ExchangeRateUpdate_DepthPoint", ",", "0", ",", "len", "(", "state", ".", "Depth", ".", "Bids", ")", ")", ",", "Asks", ":", "make", "(", "[", "]", "*", "dcrrates", ".", "ExchangeRateUpdate_DepthPoint", ",", "0", ",", "len", "(", "state", ".", "Depth", ".", "Asks", ")", ")", ",", "}", "\n", "for", "_", ",", "pt", ":=", "range", "state", ".", "Depth", ".", "Bids", "{", "depth", ".", "Bids", "=", "append", "(", "depth", ".", "Bids", ",", "&", "dcrrates", ".", "ExchangeRateUpdate_DepthPoint", "{", "Quantity", ":", "pt", ".", "Quantity", ",", "Price", ":", "pt", ".", "Price", ",", "}", ")", "\n", "}", "\n", "for", "_", ",", "pt", ":=", "range", "state", ".", "Depth", ".", "Asks", "{", "depth", ".", "Asks", "=", "append", "(", "depth", ".", "Asks", ",", "&", "dcrrates", ".", "ExchangeRateUpdate_DepthPoint", "{", "Quantity", ":", "pt", ".", "Quantity", ",", "Price", ":", "pt", ".", "Price", ",", "}", ")", "\n", "}", "\n", "protoUpdate", ".", "Depth", "=", "depth", "\n", "}", "\n\n", "return", "protoUpdate", "\n", "}" ]
// Translate from the ExchangeBot's type to the gRPC type.
[ "Translate", "from", "the", "ExchangeBot", "s", "type", "to", "the", "gRPC", "type", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/dcrrates/rateserver/types.go#L158-L211
train
decred/dcrdata
dcrrates/rateserver/types.go
SendExchangeUpdate
func (client *rateClient) SendExchangeUpdate(update *dcrrates.ExchangeRateUpdate) (err error) { for i := range client.exchanges { if client.exchanges[i] == update.Token { err = client.stream.Send(update) return } } return }
go
func (client *rateClient) SendExchangeUpdate(update *dcrrates.ExchangeRateUpdate) (err error) { for i := range client.exchanges { if client.exchanges[i] == update.Token { err = client.stream.Send(update) return } } return }
[ "func", "(", "client", "*", "rateClient", ")", "SendExchangeUpdate", "(", "update", "*", "dcrrates", ".", "ExchangeRateUpdate", ")", "(", "err", "error", ")", "{", "for", "i", ":=", "range", "client", ".", "exchanges", "{", "if", "client", ".", "exchanges", "[", "i", "]", "==", "update", ".", "Token", "{", "err", "=", "client", ".", "stream", ".", "Send", "(", "update", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// SendExchangeUpdate sends the update if the client is subscribed to the exchange.
[ "SendExchangeUpdate", "sends", "the", "update", "if", "the", "client", "is", "subscribed", "to", "the", "exchange", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/dcrrates/rateserver/types.go#L214-L222
train
decred/dcrdata
blockdata/datasaver.go
NewBlockDataToSummaryStdOut
func NewBlockDataToSummaryStdOut(sdiffWinSize int64, m ...*sync.Mutex) *BlockDataToSummaryStdOut { if len(m) > 1 { panic("Too many inputs.") } if len(m) > 0 { return &BlockDataToSummaryStdOut{m[0], sdiffWinSize} } return &BlockDataToSummaryStdOut{sdiffWinSize: sdiffWinSize} }
go
func NewBlockDataToSummaryStdOut(sdiffWinSize int64, m ...*sync.Mutex) *BlockDataToSummaryStdOut { if len(m) > 1 { panic("Too many inputs.") } if len(m) > 0 { return &BlockDataToSummaryStdOut{m[0], sdiffWinSize} } return &BlockDataToSummaryStdOut{sdiffWinSize: sdiffWinSize} }
[ "func", "NewBlockDataToSummaryStdOut", "(", "sdiffWinSize", "int64", ",", "m", "...", "*", "sync", ".", "Mutex", ")", "*", "BlockDataToSummaryStdOut", "{", "if", "len", "(", "m", ")", ">", "1", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "m", ")", ">", "0", "{", "return", "&", "BlockDataToSummaryStdOut", "{", "m", "[", "0", "]", ",", "sdiffWinSize", "}", "\n", "}", "\n", "return", "&", "BlockDataToSummaryStdOut", "{", "sdiffWinSize", ":", "sdiffWinSize", "}", "\n", "}" ]
// NewBlockDataToSummaryStdOut creates a new BlockDataToSummaryStdOut with // optional existing mutex
[ "NewBlockDataToSummaryStdOut", "creates", "a", "new", "BlockDataToSummaryStdOut", "with", "optional", "existing", "mutex" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/datasaver.go#L77-L85
train
decred/dcrdata
blockdata/datasaver.go
NewBlockDataToJSONFiles
func NewBlockDataToJSONFiles(folder string, fileBase string, m ...*sync.Mutex) *BlockDataToJSONFiles { if len(m) > 1 { panic("Too many inputs.") } var mtx *sync.Mutex if len(m) > 0 { mtx = m[0] } else { mtx = new(sync.Mutex) } return &BlockDataToJSONFiles{ fileSaver: fileSaver{ folder: folder, nameBase: fileBase, file: os.File{}, mtx: mtx, }, } }
go
func NewBlockDataToJSONFiles(folder string, fileBase string, m ...*sync.Mutex) *BlockDataToJSONFiles { if len(m) > 1 { panic("Too many inputs.") } var mtx *sync.Mutex if len(m) > 0 { mtx = m[0] } else { mtx = new(sync.Mutex) } return &BlockDataToJSONFiles{ fileSaver: fileSaver{ folder: folder, nameBase: fileBase, file: os.File{}, mtx: mtx, }, } }
[ "func", "NewBlockDataToJSONFiles", "(", "folder", "string", ",", "fileBase", "string", ",", "m", "...", "*", "sync", ".", "Mutex", ")", "*", "BlockDataToJSONFiles", "{", "if", "len", "(", "m", ")", ">", "1", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "mtx", "*", "sync", ".", "Mutex", "\n", "if", "len", "(", "m", ")", ">", "0", "{", "mtx", "=", "m", "[", "0", "]", "\n", "}", "else", "{", "mtx", "=", "new", "(", "sync", ".", "Mutex", ")", "\n", "}", "\n\n", "return", "&", "BlockDataToJSONFiles", "{", "fileSaver", ":", "fileSaver", "{", "folder", ":", "folder", ",", "nameBase", ":", "fileBase", ",", "file", ":", "os", ".", "File", "{", "}", ",", "mtx", ":", "mtx", ",", "}", ",", "}", "\n", "}" ]
// NewBlockDataToJSONFiles creates a new BlockDataToJSONFiles with optional // existing mutex
[ "NewBlockDataToJSONFiles", "creates", "a", "new", "BlockDataToJSONFiles", "with", "optional", "existing", "mutex" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/datasaver.go#L89-L110
train
decred/dcrdata
blockdata/datasaver.go
Store
func (s *BlockDataToJSONStdOut) Store(data *BlockData, _ *wire.MsgBlock) error { if s.mtx != nil { s.mtx.Lock() defer s.mtx.Unlock() } // Marshall all the block data results in to a single JSON object, indented jsonConcat, err := JSONFormatBlockData(data) if err != nil { return err } // Write JSON to stdout with guards to delimit the object from other text fmt.Printf("\n--- BEGIN BlockData JSON ---\n") _, err = writeFormattedJSONBlockData(jsonConcat, os.Stdout) fmt.Printf("--- END BlockData JSON ---\n\n") return err }
go
func (s *BlockDataToJSONStdOut) Store(data *BlockData, _ *wire.MsgBlock) error { if s.mtx != nil { s.mtx.Lock() defer s.mtx.Unlock() } // Marshall all the block data results in to a single JSON object, indented jsonConcat, err := JSONFormatBlockData(data) if err != nil { return err } // Write JSON to stdout with guards to delimit the object from other text fmt.Printf("\n--- BEGIN BlockData JSON ---\n") _, err = writeFormattedJSONBlockData(jsonConcat, os.Stdout) fmt.Printf("--- END BlockData JSON ---\n\n") return err }
[ "func", "(", "s", "*", "BlockDataToJSONStdOut", ")", "Store", "(", "data", "*", "BlockData", ",", "_", "*", "wire", ".", "MsgBlock", ")", "error", "{", "if", "s", ".", "mtx", "!=", "nil", "{", "s", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mtx", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "// Marshall all the block data results in to a single JSON object, indented", "jsonConcat", ",", "err", ":=", "JSONFormatBlockData", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Write JSON to stdout with guards to delimit the object from other text", "fmt", ".", "Printf", "(", "\"", "\\n", "\\n", "\"", ")", "\n", "_", ",", "err", "=", "writeFormattedJSONBlockData", "(", "jsonConcat", ",", "os", ".", "Stdout", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\\n", "\"", ")", "\n\n", "return", "err", "\n", "}" ]
// Store writes BlockData to stdout in JSON format
[ "Store", "writes", "BlockData", "to", "stdout", "in", "JSON", "format" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/datasaver.go#L113-L131
train
decred/dcrdata
blockdata/datasaver.go
Store
func (s *BlockDataToSummaryStdOut) Store(data *BlockData, _ *wire.MsgBlock) error { if s.mtx != nil { s.mtx.Lock() defer s.mtx.Unlock() } fmt.Printf("\nBlock %v:\n", data.Header.Height) fmt.Printf(" Stake difficulty: %9.3f -> %.3f (current -> next block)\n", data.CurrentStakeDiff.CurrentStakeDifficulty, data.CurrentStakeDiff.NextStakeDifficulty) fmt.Printf(" Estimated price in next window: %9.3f / [%.2f, %.2f] ([min, max])\n", data.EstStakeDiff.Expected, data.EstStakeDiff.Min, data.EstStakeDiff.Max) fmt.Printf(" Window progress: %3d / %3d in price window number %v\n", data.IdxBlockInWindow, s.sdiffWinSize, data.PriceWindowNum) fmt.Printf(" Ticket fees: %.4f, %.4f, %.4f (mean, median, std), n=%d\n", data.FeeInfo.Mean, data.FeeInfo.Median, data.FeeInfo.StdDev, data.FeeInfo.Number) if data.PoolInfo != nil && data.PoolInfo.Value >= 0 { fmt.Printf(" Ticket pool: %v (size), %.3f (avg. price), %.2f (total DCR locked)\n", data.PoolInfo.Size, data.PoolInfo.ValAvg, data.PoolInfo.Value) } fmt.Printf(" Node connections: %d\n", data.Connections) return nil }
go
func (s *BlockDataToSummaryStdOut) Store(data *BlockData, _ *wire.MsgBlock) error { if s.mtx != nil { s.mtx.Lock() defer s.mtx.Unlock() } fmt.Printf("\nBlock %v:\n", data.Header.Height) fmt.Printf(" Stake difficulty: %9.3f -> %.3f (current -> next block)\n", data.CurrentStakeDiff.CurrentStakeDifficulty, data.CurrentStakeDiff.NextStakeDifficulty) fmt.Printf(" Estimated price in next window: %9.3f / [%.2f, %.2f] ([min, max])\n", data.EstStakeDiff.Expected, data.EstStakeDiff.Min, data.EstStakeDiff.Max) fmt.Printf(" Window progress: %3d / %3d in price window number %v\n", data.IdxBlockInWindow, s.sdiffWinSize, data.PriceWindowNum) fmt.Printf(" Ticket fees: %.4f, %.4f, %.4f (mean, median, std), n=%d\n", data.FeeInfo.Mean, data.FeeInfo.Median, data.FeeInfo.StdDev, data.FeeInfo.Number) if data.PoolInfo != nil && data.PoolInfo.Value >= 0 { fmt.Printf(" Ticket pool: %v (size), %.3f (avg. price), %.2f (total DCR locked)\n", data.PoolInfo.Size, data.PoolInfo.ValAvg, data.PoolInfo.Value) } fmt.Printf(" Node connections: %d\n", data.Connections) return nil }
[ "func", "(", "s", "*", "BlockDataToSummaryStdOut", ")", "Store", "(", "data", "*", "BlockData", ",", "_", "*", "wire", ".", "MsgBlock", ")", "error", "{", "if", "s", ".", "mtx", "!=", "nil", "{", "s", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mtx", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\\n", "\"", ",", "data", ".", "Header", ".", "Height", ")", "\n\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "data", ".", "CurrentStakeDiff", ".", "CurrentStakeDifficulty", ",", "data", ".", "CurrentStakeDiff", ".", "NextStakeDifficulty", ")", "\n\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "data", ".", "EstStakeDiff", ".", "Expected", ",", "data", ".", "EstStakeDiff", ".", "Min", ",", "data", ".", "EstStakeDiff", ".", "Max", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "data", ".", "IdxBlockInWindow", ",", "s", ".", "sdiffWinSize", ",", "data", ".", "PriceWindowNum", ")", "\n\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "data", ".", "FeeInfo", ".", "Mean", ",", "data", ".", "FeeInfo", ".", "Median", ",", "data", ".", "FeeInfo", ".", "StdDev", ",", "data", ".", "FeeInfo", ".", "Number", ")", "\n\n", "if", "data", ".", "PoolInfo", "!=", "nil", "&&", "data", ".", "PoolInfo", ".", "Value", ">=", "0", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "data", ".", "PoolInfo", ".", "Size", ",", "data", ".", "PoolInfo", ".", "ValAvg", ",", "data", ".", "PoolInfo", ".", "Value", ")", "\n", "}", "\n\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "data", ".", "Connections", ")", "\n\n", "return", "nil", "\n", "}" ]
// Store writes BlockData to stdout as plain text summary
[ "Store", "writes", "BlockData", "to", "stdout", "as", "plain", "text", "summary" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/datasaver.go#L134-L163
train
decred/dcrdata
blockdata/datasaver.go
Store
func (s *BlockDataToJSONFiles) Store(data *BlockData, _ *wire.MsgBlock) error { if s.mtx != nil { s.mtx.Lock() defer s.mtx.Unlock() } // Marshall all the block data results in to a single JSON object, indented jsonConcat, err := JSONFormatBlockData(data) if err != nil { return err } // Write JSON to a file with block height in the name height := data.Header.Height fname := fmt.Sprintf("%s%d.json", s.nameBase, height) fullfile := filepath.Join(s.folder, fname) fp, err := os.Create(fullfile) if err != nil { log.Errorf("Unable to open file %v for writing.", fullfile) return err } defer fp.Close() s.file = *fp _, err = writeFormattedJSONBlockData(jsonConcat, &s.file) return err }
go
func (s *BlockDataToJSONFiles) Store(data *BlockData, _ *wire.MsgBlock) error { if s.mtx != nil { s.mtx.Lock() defer s.mtx.Unlock() } // Marshall all the block data results in to a single JSON object, indented jsonConcat, err := JSONFormatBlockData(data) if err != nil { return err } // Write JSON to a file with block height in the name height := data.Header.Height fname := fmt.Sprintf("%s%d.json", s.nameBase, height) fullfile := filepath.Join(s.folder, fname) fp, err := os.Create(fullfile) if err != nil { log.Errorf("Unable to open file %v for writing.", fullfile) return err } defer fp.Close() s.file = *fp _, err = writeFormattedJSONBlockData(jsonConcat, &s.file) return err }
[ "func", "(", "s", "*", "BlockDataToJSONFiles", ")", "Store", "(", "data", "*", "BlockData", ",", "_", "*", "wire", ".", "MsgBlock", ")", "error", "{", "if", "s", ".", "mtx", "!=", "nil", "{", "s", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mtx", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "// Marshall all the block data results in to a single JSON object, indented", "jsonConcat", ",", "err", ":=", "JSONFormatBlockData", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Write JSON to a file with block height in the name", "height", ":=", "data", ".", "Header", ".", "Height", "\n", "fname", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "nameBase", ",", "height", ")", "\n", "fullfile", ":=", "filepath", ".", "Join", "(", "s", ".", "folder", ",", "fname", ")", "\n", "fp", ",", "err", ":=", "os", ".", "Create", "(", "fullfile", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "fullfile", ")", "\n", "return", "err", "\n", "}", "\n", "defer", "fp", ".", "Close", "(", ")", "\n\n", "s", ".", "file", "=", "*", "fp", "\n", "_", ",", "err", "=", "writeFormattedJSONBlockData", "(", "jsonConcat", ",", "&", "s", ".", "file", ")", "\n\n", "return", "err", "\n", "}" ]
// Store writes BlockData to a file in JSON format // The file name is nameBase+height+".json".
[ "Store", "writes", "BlockData", "to", "a", "file", "in", "JSON", "format", "The", "file", "name", "is", "nameBase", "+", "height", "+", ".", "json", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/datasaver.go#L167-L194
train
decred/dcrdata
blockdata/datasaver.go
JSONFormatBlockData
func JSONFormatBlockData(data *BlockData) (*bytes.Buffer, error) { var jsonAll bytes.Buffer jsonAll.WriteString("{\"estimatestakediff\": ") stakeDiffEstJSON, err := json.Marshal(data.EstStakeDiff) if err != nil { return nil, err } jsonAll.Write(stakeDiffEstJSON) //stakeDiffEstJSON, err := json.MarshalIndent(data.eststakediff, "", " ") //fmt.Println(string(stakeDiffEstJSON)) jsonAll.WriteString(",\"currentstakediff\": ") stakeDiffJSON, err := json.Marshal(data.CurrentStakeDiff) if err != nil { return nil, err } jsonAll.Write(stakeDiffJSON) jsonAll.WriteString(",\"ticketfeeinfo_block\": ") feeInfoJSON, err := json.Marshal(data.FeeInfo) if err != nil { return nil, err } jsonAll.Write(feeInfoJSON) jsonAll.WriteString(",\"block_header\": ") blockHeaderJSON, err := json.Marshal(data.Header) if err != nil { return nil, err } jsonAll.Write(blockHeaderJSON) jsonAll.WriteString(",\"ticket_pool_info\": ") poolInfoJSON, err := json.Marshal(data.PoolInfo) if err != nil { return nil, err } jsonAll.Write(poolInfoJSON) jsonAll.WriteString("}") var jsonAllIndented bytes.Buffer err = json.Indent(&jsonAllIndented, jsonAll.Bytes(), "", " ") if err != nil { return nil, err } return &jsonAllIndented, err }
go
func JSONFormatBlockData(data *BlockData) (*bytes.Buffer, error) { var jsonAll bytes.Buffer jsonAll.WriteString("{\"estimatestakediff\": ") stakeDiffEstJSON, err := json.Marshal(data.EstStakeDiff) if err != nil { return nil, err } jsonAll.Write(stakeDiffEstJSON) //stakeDiffEstJSON, err := json.MarshalIndent(data.eststakediff, "", " ") //fmt.Println(string(stakeDiffEstJSON)) jsonAll.WriteString(",\"currentstakediff\": ") stakeDiffJSON, err := json.Marshal(data.CurrentStakeDiff) if err != nil { return nil, err } jsonAll.Write(stakeDiffJSON) jsonAll.WriteString(",\"ticketfeeinfo_block\": ") feeInfoJSON, err := json.Marshal(data.FeeInfo) if err != nil { return nil, err } jsonAll.Write(feeInfoJSON) jsonAll.WriteString(",\"block_header\": ") blockHeaderJSON, err := json.Marshal(data.Header) if err != nil { return nil, err } jsonAll.Write(blockHeaderJSON) jsonAll.WriteString(",\"ticket_pool_info\": ") poolInfoJSON, err := json.Marshal(data.PoolInfo) if err != nil { return nil, err } jsonAll.Write(poolInfoJSON) jsonAll.WriteString("}") var jsonAllIndented bytes.Buffer err = json.Indent(&jsonAllIndented, jsonAll.Bytes(), "", " ") if err != nil { return nil, err } return &jsonAllIndented, err }
[ "func", "JSONFormatBlockData", "(", "data", "*", "BlockData", ")", "(", "*", "bytes", ".", "Buffer", ",", "error", ")", "{", "var", "jsonAll", "bytes", ".", "Buffer", "\n\n", "jsonAll", ".", "WriteString", "(", "\"", "\\\"", "\\\"", "\"", ")", "\n", "stakeDiffEstJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "data", ".", "EstStakeDiff", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "jsonAll", ".", "Write", "(", "stakeDiffEstJSON", ")", "\n", "//stakeDiffEstJSON, err := json.MarshalIndent(data.eststakediff, \"\", \" \")", "//fmt.Println(string(stakeDiffEstJSON))", "jsonAll", ".", "WriteString", "(", "\"", "\\\"", "\\\"", "\"", ")", "\n", "stakeDiffJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "data", ".", "CurrentStakeDiff", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "jsonAll", ".", "Write", "(", "stakeDiffJSON", ")", "\n\n", "jsonAll", ".", "WriteString", "(", "\"", "\\\"", "\\\"", "\"", ")", "\n", "feeInfoJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "data", ".", "FeeInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "jsonAll", ".", "Write", "(", "feeInfoJSON", ")", "\n\n", "jsonAll", ".", "WriteString", "(", "\"", "\\\"", "\\\"", "\"", ")", "\n", "blockHeaderJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "data", ".", "Header", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "jsonAll", ".", "Write", "(", "blockHeaderJSON", ")", "\n\n", "jsonAll", ".", "WriteString", "(", "\"", "\\\"", "\\\"", "\"", ")", "\n", "poolInfoJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "data", ".", "PoolInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "jsonAll", ".", "Write", "(", "poolInfoJSON", ")", "\n\n", "jsonAll", ".", "WriteString", "(", "\"", "\"", ")", "\n\n", "var", "jsonAllIndented", "bytes", ".", "Buffer", "\n", "err", "=", "json", ".", "Indent", "(", "&", "jsonAllIndented", ",", "jsonAll", ".", "Bytes", "(", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "jsonAllIndented", ",", "err", "\n", "}" ]
// JSONFormatBlockData concatenates block data results into a single JSON // object with primary keys for the result type
[ "JSONFormatBlockData", "concatenates", "block", "data", "results", "into", "a", "single", "JSON", "object", "with", "primary", "keys", "for", "the", "result", "type" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/datasaver.go#L204-L253
train
decred/dcrdata
blockdata/datasaver.go
Store
func (s BlockTrigger) Store(bd *BlockData, _ *wire.MsgBlock) error { s.Saver(bd.Header.Hash, bd.Header.Height) return nil }
go
func (s BlockTrigger) Store(bd *BlockData, _ *wire.MsgBlock) error { s.Saver(bd.Header.Hash, bd.Header.Height) return nil }
[ "func", "(", "s", "BlockTrigger", ")", "Store", "(", "bd", "*", "BlockData", ",", "_", "*", "wire", ".", "MsgBlock", ")", "error", "{", "s", ".", "Saver", "(", "bd", ".", "Header", ".", "Hash", ",", "bd", ".", "Header", ".", "Height", ")", "\n", "return", "nil", "\n", "}" ]
// Store reduces the block data to the hash and height in builtin types, // and passes the data to the saver.
[ "Store", "reduces", "the", "block", "data", "to", "the", "hash", "and", "height", "in", "builtin", "types", "and", "passes", "the", "data", "to", "the", "saver", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/datasaver.go#L263-L266
train
decred/dcrdata
blockdata/blockdata.go
ToStakeInfoExtended
func (b *BlockData) ToStakeInfoExtended() apitypes.StakeInfoExtended { return apitypes.StakeInfoExtended{ Hash: b.Header.Hash, Feeinfo: b.FeeInfo, StakeDiff: b.CurrentStakeDiff.CurrentStakeDifficulty, PriceWindowNum: b.PriceWindowNum, IdxBlockInWindow: b.IdxBlockInWindow, PoolInfo: b.PoolInfo, } }
go
func (b *BlockData) ToStakeInfoExtended() apitypes.StakeInfoExtended { return apitypes.StakeInfoExtended{ Hash: b.Header.Hash, Feeinfo: b.FeeInfo, StakeDiff: b.CurrentStakeDiff.CurrentStakeDifficulty, PriceWindowNum: b.PriceWindowNum, IdxBlockInWindow: b.IdxBlockInWindow, PoolInfo: b.PoolInfo, } }
[ "func", "(", "b", "*", "BlockData", ")", "ToStakeInfoExtended", "(", ")", "apitypes", ".", "StakeInfoExtended", "{", "return", "apitypes", ".", "StakeInfoExtended", "{", "Hash", ":", "b", ".", "Header", ".", "Hash", ",", "Feeinfo", ":", "b", ".", "FeeInfo", ",", "StakeDiff", ":", "b", ".", "CurrentStakeDiff", ".", "CurrentStakeDifficulty", ",", "PriceWindowNum", ":", "b", ".", "PriceWindowNum", ",", "IdxBlockInWindow", ":", "b", ".", "IdxBlockInWindow", ",", "PoolInfo", ":", "b", ".", "PoolInfo", ",", "}", "\n", "}" ]
// ToStakeInfoExtended returns an apitypes.StakeInfoExtended object from the // blockdata
[ "ToStakeInfoExtended", "returns", "an", "apitypes", ".", "StakeInfoExtended", "object", "from", "the", "blockdata" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/blockdata.go#L42-L51
train
decred/dcrdata
blockdata/blockdata.go
ToStakeInfoExtendedEstimates
func (b *BlockData) ToStakeInfoExtendedEstimates() apitypes.StakeInfoExtendedEstimates { return apitypes.StakeInfoExtendedEstimates{ Hash: b.Header.Hash, Feeinfo: b.FeeInfo, StakeDiff: apitypes.StakeDiff{ GetStakeDifficultyResult: b.CurrentStakeDiff, Estimates: b.EstStakeDiff, IdxBlockInWindow: b.IdxBlockInWindow, PriceWindowNum: b.PriceWindowNum, }, // PriceWindowNum and Idx... are repeated here since this is a kludge PriceWindowNum: b.PriceWindowNum, IdxBlockInWindow: b.IdxBlockInWindow, PoolInfo: b.PoolInfo, } }
go
func (b *BlockData) ToStakeInfoExtendedEstimates() apitypes.StakeInfoExtendedEstimates { return apitypes.StakeInfoExtendedEstimates{ Hash: b.Header.Hash, Feeinfo: b.FeeInfo, StakeDiff: apitypes.StakeDiff{ GetStakeDifficultyResult: b.CurrentStakeDiff, Estimates: b.EstStakeDiff, IdxBlockInWindow: b.IdxBlockInWindow, PriceWindowNum: b.PriceWindowNum, }, // PriceWindowNum and Idx... are repeated here since this is a kludge PriceWindowNum: b.PriceWindowNum, IdxBlockInWindow: b.IdxBlockInWindow, PoolInfo: b.PoolInfo, } }
[ "func", "(", "b", "*", "BlockData", ")", "ToStakeInfoExtendedEstimates", "(", ")", "apitypes", ".", "StakeInfoExtendedEstimates", "{", "return", "apitypes", ".", "StakeInfoExtendedEstimates", "{", "Hash", ":", "b", ".", "Header", ".", "Hash", ",", "Feeinfo", ":", "b", ".", "FeeInfo", ",", "StakeDiff", ":", "apitypes", ".", "StakeDiff", "{", "GetStakeDifficultyResult", ":", "b", ".", "CurrentStakeDiff", ",", "Estimates", ":", "b", ".", "EstStakeDiff", ",", "IdxBlockInWindow", ":", "b", ".", "IdxBlockInWindow", ",", "PriceWindowNum", ":", "b", ".", "PriceWindowNum", ",", "}", ",", "// PriceWindowNum and Idx... are repeated here since this is a kludge", "PriceWindowNum", ":", "b", ".", "PriceWindowNum", ",", "IdxBlockInWindow", ":", "b", ".", "IdxBlockInWindow", ",", "PoolInfo", ":", "b", ".", "PoolInfo", ",", "}", "\n", "}" ]
// ToStakeInfoExtendedEstimates returns an apitypes.StakeInfoExtendedEstimates // object from the blockdata
[ "ToStakeInfoExtendedEstimates", "returns", "an", "apitypes", ".", "StakeInfoExtendedEstimates", "object", "from", "the", "blockdata" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/blockdata.go#L55-L70
train
decred/dcrdata
blockdata/blockdata.go
ToBlockSummary
func (b *BlockData) ToBlockSummary() apitypes.BlockDataBasic { t := dbtypes.NewTimeDefFromUNIX(b.Header.Time) return apitypes.BlockDataBasic{ Height: b.Header.Height, Size: b.Header.Size, Hash: b.Header.Hash, Difficulty: b.Header.Difficulty, StakeDiff: b.Header.SBits, Time: apitypes.TimeAPI{S: t}, PoolInfo: b.PoolInfo, } }
go
func (b *BlockData) ToBlockSummary() apitypes.BlockDataBasic { t := dbtypes.NewTimeDefFromUNIX(b.Header.Time) return apitypes.BlockDataBasic{ Height: b.Header.Height, Size: b.Header.Size, Hash: b.Header.Hash, Difficulty: b.Header.Difficulty, StakeDiff: b.Header.SBits, Time: apitypes.TimeAPI{S: t}, PoolInfo: b.PoolInfo, } }
[ "func", "(", "b", "*", "BlockData", ")", "ToBlockSummary", "(", ")", "apitypes", ".", "BlockDataBasic", "{", "t", ":=", "dbtypes", ".", "NewTimeDefFromUNIX", "(", "b", ".", "Header", ".", "Time", ")", "\n", "return", "apitypes", ".", "BlockDataBasic", "{", "Height", ":", "b", ".", "Header", ".", "Height", ",", "Size", ":", "b", ".", "Header", ".", "Size", ",", "Hash", ":", "b", ".", "Header", ".", "Hash", ",", "Difficulty", ":", "b", ".", "Header", ".", "Difficulty", ",", "StakeDiff", ":", "b", ".", "Header", ".", "SBits", ",", "Time", ":", "apitypes", ".", "TimeAPI", "{", "S", ":", "t", "}", ",", "PoolInfo", ":", "b", ".", "PoolInfo", ",", "}", "\n", "}" ]
// ToBlockSummary returns an apitypes.BlockDataBasic object from the blockdata
[ "ToBlockSummary", "returns", "an", "apitypes", ".", "BlockDataBasic", "object", "from", "the", "blockdata" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/blockdata.go#L73-L84
train
decred/dcrdata
blockdata/blockdata.go
ToBlockExplorerSummary
func (b *BlockData) ToBlockExplorerSummary() apitypes.BlockExplorerBasic { extra := b.ExtraInfo t := dbtypes.NewTimeDefFromUNIX(b.Header.Time) return apitypes.BlockExplorerBasic{ Height: b.Header.Height, Size: b.Header.Size, Voters: b.Header.Voters, Revocations: b.Header.Revocations, FreshStake: b.Header.FreshStake, StakeDiff: b.Header.SBits, BlockExplorerExtraInfo: extra, Time: t, } }
go
func (b *BlockData) ToBlockExplorerSummary() apitypes.BlockExplorerBasic { extra := b.ExtraInfo t := dbtypes.NewTimeDefFromUNIX(b.Header.Time) return apitypes.BlockExplorerBasic{ Height: b.Header.Height, Size: b.Header.Size, Voters: b.Header.Voters, Revocations: b.Header.Revocations, FreshStake: b.Header.FreshStake, StakeDiff: b.Header.SBits, BlockExplorerExtraInfo: extra, Time: t, } }
[ "func", "(", "b", "*", "BlockData", ")", "ToBlockExplorerSummary", "(", ")", "apitypes", ".", "BlockExplorerBasic", "{", "extra", ":=", "b", ".", "ExtraInfo", "\n", "t", ":=", "dbtypes", ".", "NewTimeDefFromUNIX", "(", "b", ".", "Header", ".", "Time", ")", "\n", "return", "apitypes", ".", "BlockExplorerBasic", "{", "Height", ":", "b", ".", "Header", ".", "Height", ",", "Size", ":", "b", ".", "Header", ".", "Size", ",", "Voters", ":", "b", ".", "Header", ".", "Voters", ",", "Revocations", ":", "b", ".", "Header", ".", "Revocations", ",", "FreshStake", ":", "b", ".", "Header", ".", "FreshStake", ",", "StakeDiff", ":", "b", ".", "Header", ".", "SBits", ",", "BlockExplorerExtraInfo", ":", "extra", ",", "Time", ":", "t", ",", "}", "\n", "}" ]
// ToBlockExplorerSummary returns a BlockExplorerBasic
[ "ToBlockExplorerSummary", "returns", "a", "BlockExplorerBasic" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/blockdata.go#L87-L100
train
decred/dcrdata
blockdata/blockdata.go
NewCollector
func NewCollector(dcrdChainSvr *rpcclient.Client, params *chaincfg.Params, stakeDB *stakedb.StakeDatabase) *Collector { return &Collector{ dcrdChainSvr: dcrdChainSvr, netParams: params, stakeDB: stakeDB, } }
go
func NewCollector(dcrdChainSvr *rpcclient.Client, params *chaincfg.Params, stakeDB *stakedb.StakeDatabase) *Collector { return &Collector{ dcrdChainSvr: dcrdChainSvr, netParams: params, stakeDB: stakeDB, } }
[ "func", "NewCollector", "(", "dcrdChainSvr", "*", "rpcclient", ".", "Client", ",", "params", "*", "chaincfg", ".", "Params", ",", "stakeDB", "*", "stakedb", ".", "StakeDatabase", ")", "*", "Collector", "{", "return", "&", "Collector", "{", "dcrdChainSvr", ":", "dcrdChainSvr", ",", "netParams", ":", "params", ",", "stakeDB", ":", "stakeDB", ",", "}", "\n", "}" ]
// NewCollector creates a new Collector.
[ "NewCollector", "creates", "a", "new", "Collector", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/blockdata.go#L111-L118
train
decred/dcrdata
blockdata/blockdata.go
CollectAPITypes
func (t *Collector) CollectAPITypes(hash *chainhash.Hash) (*apitypes.BlockDataBasic, *apitypes.StakeInfoExtended) { blockDataBasic, feeInfoBlock, _, _, _, err := t.CollectBlockInfo(hash) if err != nil { return nil, nil } height := int64(blockDataBasic.Height) winSize := t.netParams.StakeDiffWindowSize stakeInfoExtended := &apitypes.StakeInfoExtended{ Hash: blockDataBasic.Hash, Feeinfo: *feeInfoBlock, StakeDiff: blockDataBasic.StakeDiff, PriceWindowNum: int(height / winSize), IdxBlockInWindow: int(height%winSize) + 1, PoolInfo: blockDataBasic.PoolInfo, } return blockDataBasic, stakeInfoExtended }
go
func (t *Collector) CollectAPITypes(hash *chainhash.Hash) (*apitypes.BlockDataBasic, *apitypes.StakeInfoExtended) { blockDataBasic, feeInfoBlock, _, _, _, err := t.CollectBlockInfo(hash) if err != nil { return nil, nil } height := int64(blockDataBasic.Height) winSize := t.netParams.StakeDiffWindowSize stakeInfoExtended := &apitypes.StakeInfoExtended{ Hash: blockDataBasic.Hash, Feeinfo: *feeInfoBlock, StakeDiff: blockDataBasic.StakeDiff, PriceWindowNum: int(height / winSize), IdxBlockInWindow: int(height%winSize) + 1, PoolInfo: blockDataBasic.PoolInfo, } return blockDataBasic, stakeInfoExtended }
[ "func", "(", "t", "*", "Collector", ")", "CollectAPITypes", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "apitypes", ".", "BlockDataBasic", ",", "*", "apitypes", ".", "StakeInfoExtended", ")", "{", "blockDataBasic", ",", "feeInfoBlock", ",", "_", ",", "_", ",", "_", ",", "err", ":=", "t", ".", "CollectBlockInfo", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "height", ":=", "int64", "(", "blockDataBasic", ".", "Height", ")", "\n", "winSize", ":=", "t", ".", "netParams", ".", "StakeDiffWindowSize", "\n\n", "stakeInfoExtended", ":=", "&", "apitypes", ".", "StakeInfoExtended", "{", "Hash", ":", "blockDataBasic", ".", "Hash", ",", "Feeinfo", ":", "*", "feeInfoBlock", ",", "StakeDiff", ":", "blockDataBasic", ".", "StakeDiff", ",", "PriceWindowNum", ":", "int", "(", "height", "/", "winSize", ")", ",", "IdxBlockInWindow", ":", "int", "(", "height", "%", "winSize", ")", "+", "1", ",", "PoolInfo", ":", "blockDataBasic", ".", "PoolInfo", ",", "}", "\n\n", "return", "blockDataBasic", ",", "stakeInfoExtended", "\n", "}" ]
// CollectAPITypes uses CollectBlockInfo to collect block data, then organizes // it into the BlockDataBasic and StakeInfoExtended and dcrdataapi types.
[ "CollectAPITypes", "uses", "CollectBlockInfo", "to", "collect", "block", "data", "then", "organizes", "it", "into", "the", "BlockDataBasic", "and", "StakeInfoExtended", "and", "dcrdataapi", "types", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/blockdata.go#L122-L141
train
decred/dcrdata
blockdata/blockdata.go
CollectHash
func (t *Collector) CollectHash(hash *chainhash.Hash) (*BlockData, *wire.MsgBlock, error) { // In case of a very fast block, make sure previous call to collect is not // still running, or dcrd may be mad. t.mtx.Lock() defer t.mtx.Unlock() // Time this function defer func(start time.Time) { log.Debugf("Collector.CollectHash() completed in %v", time.Since(start)) }(time.Now()) // Info specific to the block hash blockDataBasic, feeInfoBlock, blockHeaderVerbose, extra, msgBlock, err := t.CollectBlockInfo(hash) if err != nil { return nil, nil, err } // Number of peer connection to chain server numConn, err := t.dcrdChainSvr.GetConnectionCount() if err != nil { log.Warn("Unable to get connection count: ", err) } // Blockchain info (e.g. syncheight, verificationprogress, chainwork, // bestblockhash, initialblockdownload, maxblocksize, deployments, etc.). chainInfo, err := t.dcrdChainSvr.GetBlockChainInfo() if err != nil { log.Warn("Unable to get blockchain info: ", err) } // GetBlockChainInfo is only valid for for chain tip. if chainInfo.BestBlockHash != hash.String() { chainInfo = nil } // Output height := int64(blockDataBasic.Height) winSize := t.netParams.StakeDiffWindowSize blockdata := &BlockData{ Header: *blockHeaderVerbose, Connections: int32(numConn), FeeInfo: *feeInfoBlock, CurrentStakeDiff: dcrjson.GetStakeDifficultyResult{CurrentStakeDifficulty: blockDataBasic.StakeDiff}, EstStakeDiff: dcrjson.EstimateStakeDiffResult{}, PoolInfo: blockDataBasic.PoolInfo, ExtraInfo: *extra, BlockchainInfo: chainInfo, PriceWindowNum: int(height / winSize), IdxBlockInWindow: int(height%winSize) + 1, } return blockdata, msgBlock, err }
go
func (t *Collector) CollectHash(hash *chainhash.Hash) (*BlockData, *wire.MsgBlock, error) { // In case of a very fast block, make sure previous call to collect is not // still running, or dcrd may be mad. t.mtx.Lock() defer t.mtx.Unlock() // Time this function defer func(start time.Time) { log.Debugf("Collector.CollectHash() completed in %v", time.Since(start)) }(time.Now()) // Info specific to the block hash blockDataBasic, feeInfoBlock, blockHeaderVerbose, extra, msgBlock, err := t.CollectBlockInfo(hash) if err != nil { return nil, nil, err } // Number of peer connection to chain server numConn, err := t.dcrdChainSvr.GetConnectionCount() if err != nil { log.Warn("Unable to get connection count: ", err) } // Blockchain info (e.g. syncheight, verificationprogress, chainwork, // bestblockhash, initialblockdownload, maxblocksize, deployments, etc.). chainInfo, err := t.dcrdChainSvr.GetBlockChainInfo() if err != nil { log.Warn("Unable to get blockchain info: ", err) } // GetBlockChainInfo is only valid for for chain tip. if chainInfo.BestBlockHash != hash.String() { chainInfo = nil } // Output height := int64(blockDataBasic.Height) winSize := t.netParams.StakeDiffWindowSize blockdata := &BlockData{ Header: *blockHeaderVerbose, Connections: int32(numConn), FeeInfo: *feeInfoBlock, CurrentStakeDiff: dcrjson.GetStakeDifficultyResult{CurrentStakeDifficulty: blockDataBasic.StakeDiff}, EstStakeDiff: dcrjson.EstimateStakeDiffResult{}, PoolInfo: blockDataBasic.PoolInfo, ExtraInfo: *extra, BlockchainInfo: chainInfo, PriceWindowNum: int(height / winSize), IdxBlockInWindow: int(height%winSize) + 1, } return blockdata, msgBlock, err }
[ "func", "(", "t", "*", "Collector", ")", "CollectHash", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "BlockData", ",", "*", "wire", ".", "MsgBlock", ",", "error", ")", "{", "// In case of a very fast block, make sure previous call to collect is not", "// still running, or dcrd may be mad.", "t", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// Time this function", "defer", "func", "(", "start", "time", ".", "Time", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "time", ".", "Since", "(", "start", ")", ")", "\n", "}", "(", "time", ".", "Now", "(", ")", ")", "\n\n", "// Info specific to the block hash", "blockDataBasic", ",", "feeInfoBlock", ",", "blockHeaderVerbose", ",", "extra", ",", "msgBlock", ",", "err", ":=", "t", ".", "CollectBlockInfo", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// Number of peer connection to chain server", "numConn", ",", "err", ":=", "t", ".", "dcrdChainSvr", ".", "GetConnectionCount", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warn", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Blockchain info (e.g. syncheight, verificationprogress, chainwork,", "// bestblockhash, initialblockdownload, maxblocksize, deployments, etc.).", "chainInfo", ",", "err", ":=", "t", ".", "dcrdChainSvr", ".", "GetBlockChainInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warn", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// GetBlockChainInfo is only valid for for chain tip.", "if", "chainInfo", ".", "BestBlockHash", "!=", "hash", ".", "String", "(", ")", "{", "chainInfo", "=", "nil", "\n", "}", "\n\n", "// Output", "height", ":=", "int64", "(", "blockDataBasic", ".", "Height", ")", "\n", "winSize", ":=", "t", ".", "netParams", ".", "StakeDiffWindowSize", "\n", "blockdata", ":=", "&", "BlockData", "{", "Header", ":", "*", "blockHeaderVerbose", ",", "Connections", ":", "int32", "(", "numConn", ")", ",", "FeeInfo", ":", "*", "feeInfoBlock", ",", "CurrentStakeDiff", ":", "dcrjson", ".", "GetStakeDifficultyResult", "{", "CurrentStakeDifficulty", ":", "blockDataBasic", ".", "StakeDiff", "}", ",", "EstStakeDiff", ":", "dcrjson", ".", "EstimateStakeDiffResult", "{", "}", ",", "PoolInfo", ":", "blockDataBasic", ".", "PoolInfo", ",", "ExtraInfo", ":", "*", "extra", ",", "BlockchainInfo", ":", "chainInfo", ",", "PriceWindowNum", ":", "int", "(", "height", "/", "winSize", ")", ",", "IdxBlockInWindow", ":", "int", "(", "height", "%", "winSize", ")", "+", "1", ",", "}", "\n\n", "return", "blockdata", ",", "msgBlock", ",", "err", "\n", "}" ]
// CollectHash collects chain data at the block with the specified hash.
[ "CollectHash", "collects", "chain", "data", "at", "the", "block", "with", "the", "specified", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/blockdata.go#L225-L277
train
decred/dcrdata
blockdata/blockdata.go
Collect
func (t *Collector) Collect() (*BlockData, *wire.MsgBlock, error) { // In case of a very fast block, make sure previous call to collect is not // still running, or dcrd may be mad. t.mtx.Lock() defer t.mtx.Unlock() // Time this function defer func(start time.Time) { log.Debugf("Collector.Collect() completed in %v", time.Since(start)) }(time.Now()) // Run first client call with a timeout. type bciRes struct { err error blockchainInfo *dcrjson.GetBlockChainInfoResult } toch := make(chan bciRes) // Pull and store relevant data about the blockchain (e.g. syncheight, // verificationprogress, chainwork, bestblockhash, initialblockdownload, // maxblocksize, deployments, etc.). go func() { blockchainInfo, err := t.dcrdChainSvr.GetBlockChainInfo() toch <- bciRes{err, blockchainInfo} }() var bci bciRes select { case bci = <-toch: case <-time.After(time.Second * 10): log.Errorf("Timeout waiting for dcrd.") return nil, nil, errors.New("Timeout") } if bci.err != nil { return nil, nil, fmt.Errorf("unable to get blockchain info: %v", bci.err) } hash, err := chainhash.NewHashFromStr(bci.blockchainInfo.BestBlockHash) if err != nil { return nil, nil, fmt.Errorf("invalid best block hash from getblockchaininfo: %v", err) } // Stake difficulty stakeDiff, err := t.dcrdChainSvr.GetStakeDifficulty() if err != nil { return nil, nil, err } // estimatestakediff estStakeDiff, err := t.dcrdChainSvr.EstimateStakeDiff(nil) if err != nil { log.Warn("estimatestakediff is broken: ", err) estStakeDiff = &dcrjson.EstimateStakeDiffResult{} } // Info specific to the block hash blockDataBasic, feeInfoBlock, blockHeaderVerbose, extra, msgBlock, err := t.CollectBlockInfo(hash) if err != nil { return nil, nil, err } // Number of peer connection to chain server numConn, err := t.dcrdChainSvr.GetConnectionCount() if err != nil { log.Warn("Unable to get connection count: ", err) } // Output height := int64(blockDataBasic.Height) winSize := t.netParams.StakeDiffWindowSize blockdata := &BlockData{ Header: *blockHeaderVerbose, Connections: int32(numConn), FeeInfo: *feeInfoBlock, CurrentStakeDiff: *stakeDiff, EstStakeDiff: *estStakeDiff, ExtraInfo: *extra, BlockchainInfo: bci.blockchainInfo, PoolInfo: blockDataBasic.PoolInfo, PriceWindowNum: int(height / winSize), IdxBlockInWindow: int(height%winSize) + 1, } return blockdata, msgBlock, err }
go
func (t *Collector) Collect() (*BlockData, *wire.MsgBlock, error) { // In case of a very fast block, make sure previous call to collect is not // still running, or dcrd may be mad. t.mtx.Lock() defer t.mtx.Unlock() // Time this function defer func(start time.Time) { log.Debugf("Collector.Collect() completed in %v", time.Since(start)) }(time.Now()) // Run first client call with a timeout. type bciRes struct { err error blockchainInfo *dcrjson.GetBlockChainInfoResult } toch := make(chan bciRes) // Pull and store relevant data about the blockchain (e.g. syncheight, // verificationprogress, chainwork, bestblockhash, initialblockdownload, // maxblocksize, deployments, etc.). go func() { blockchainInfo, err := t.dcrdChainSvr.GetBlockChainInfo() toch <- bciRes{err, blockchainInfo} }() var bci bciRes select { case bci = <-toch: case <-time.After(time.Second * 10): log.Errorf("Timeout waiting for dcrd.") return nil, nil, errors.New("Timeout") } if bci.err != nil { return nil, nil, fmt.Errorf("unable to get blockchain info: %v", bci.err) } hash, err := chainhash.NewHashFromStr(bci.blockchainInfo.BestBlockHash) if err != nil { return nil, nil, fmt.Errorf("invalid best block hash from getblockchaininfo: %v", err) } // Stake difficulty stakeDiff, err := t.dcrdChainSvr.GetStakeDifficulty() if err != nil { return nil, nil, err } // estimatestakediff estStakeDiff, err := t.dcrdChainSvr.EstimateStakeDiff(nil) if err != nil { log.Warn("estimatestakediff is broken: ", err) estStakeDiff = &dcrjson.EstimateStakeDiffResult{} } // Info specific to the block hash blockDataBasic, feeInfoBlock, blockHeaderVerbose, extra, msgBlock, err := t.CollectBlockInfo(hash) if err != nil { return nil, nil, err } // Number of peer connection to chain server numConn, err := t.dcrdChainSvr.GetConnectionCount() if err != nil { log.Warn("Unable to get connection count: ", err) } // Output height := int64(blockDataBasic.Height) winSize := t.netParams.StakeDiffWindowSize blockdata := &BlockData{ Header: *blockHeaderVerbose, Connections: int32(numConn), FeeInfo: *feeInfoBlock, CurrentStakeDiff: *stakeDiff, EstStakeDiff: *estStakeDiff, ExtraInfo: *extra, BlockchainInfo: bci.blockchainInfo, PoolInfo: blockDataBasic.PoolInfo, PriceWindowNum: int(height / winSize), IdxBlockInWindow: int(height%winSize) + 1, } return blockdata, msgBlock, err }
[ "func", "(", "t", "*", "Collector", ")", "Collect", "(", ")", "(", "*", "BlockData", ",", "*", "wire", ".", "MsgBlock", ",", "error", ")", "{", "// In case of a very fast block, make sure previous call to collect is not", "// still running, or dcrd may be mad.", "t", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// Time this function", "defer", "func", "(", "start", "time", ".", "Time", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "time", ".", "Since", "(", "start", ")", ")", "\n", "}", "(", "time", ".", "Now", "(", ")", ")", "\n\n", "// Run first client call with a timeout.", "type", "bciRes", "struct", "{", "err", "error", "\n", "blockchainInfo", "*", "dcrjson", ".", "GetBlockChainInfoResult", "\n", "}", "\n", "toch", ":=", "make", "(", "chan", "bciRes", ")", "\n\n", "// Pull and store relevant data about the blockchain (e.g. syncheight,", "// verificationprogress, chainwork, bestblockhash, initialblockdownload,", "// maxblocksize, deployments, etc.).", "go", "func", "(", ")", "{", "blockchainInfo", ",", "err", ":=", "t", ".", "dcrdChainSvr", ".", "GetBlockChainInfo", "(", ")", "\n", "toch", "<-", "bciRes", "{", "err", ",", "blockchainInfo", "}", "\n", "}", "(", ")", "\n\n", "var", "bci", "bciRes", "\n", "select", "{", "case", "bci", "=", "<-", "toch", ":", "case", "<-", "time", ".", "After", "(", "time", ".", "Second", "*", "10", ")", ":", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "bci", ".", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "bci", ".", "err", ")", "\n", "}", "\n\n", "hash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "bci", ".", "blockchainInfo", ".", "BestBlockHash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Stake difficulty", "stakeDiff", ",", "err", ":=", "t", ".", "dcrdChainSvr", ".", "GetStakeDifficulty", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// estimatestakediff", "estStakeDiff", ",", "err", ":=", "t", ".", "dcrdChainSvr", ".", "EstimateStakeDiff", "(", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warn", "(", "\"", "\"", ",", "err", ")", "\n", "estStakeDiff", "=", "&", "dcrjson", ".", "EstimateStakeDiffResult", "{", "}", "\n", "}", "\n\n", "// Info specific to the block hash", "blockDataBasic", ",", "feeInfoBlock", ",", "blockHeaderVerbose", ",", "extra", ",", "msgBlock", ",", "err", ":=", "t", ".", "CollectBlockInfo", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// Number of peer connection to chain server", "numConn", ",", "err", ":=", "t", ".", "dcrdChainSvr", ".", "GetConnectionCount", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warn", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Output", "height", ":=", "int64", "(", "blockDataBasic", ".", "Height", ")", "\n", "winSize", ":=", "t", ".", "netParams", ".", "StakeDiffWindowSize", "\n", "blockdata", ":=", "&", "BlockData", "{", "Header", ":", "*", "blockHeaderVerbose", ",", "Connections", ":", "int32", "(", "numConn", ")", ",", "FeeInfo", ":", "*", "feeInfoBlock", ",", "CurrentStakeDiff", ":", "*", "stakeDiff", ",", "EstStakeDiff", ":", "*", "estStakeDiff", ",", "ExtraInfo", ":", "*", "extra", ",", "BlockchainInfo", ":", "bci", ".", "blockchainInfo", ",", "PoolInfo", ":", "blockDataBasic", ".", "PoolInfo", ",", "PriceWindowNum", ":", "int", "(", "height", "/", "winSize", ")", ",", "IdxBlockInWindow", ":", "int", "(", "height", "%", "winSize", ")", "+", "1", ",", "}", "\n\n", "return", "blockdata", ",", "msgBlock", ",", "err", "\n", "}" ]
// Collect collects chain data at the current best block.
[ "Collect", "collects", "chain", "data", "at", "the", "current", "best", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/blockdata.go#L280-L367
train
decred/dcrdata
explorer/websocket.go
NewWebsocketHub
func NewWebsocketHub() *WebsocketHub { return &WebsocketHub{ clients: make(map[*hubSpoke]*clientHubSpoke), Register: make(chan *clientHubSpoke), Unregister: make(chan *hubSpoke), HubRelay: make(chan hubMessage), newTxBuffer: make([]*types.MempoolTx, 0, newTxBufferSize), bufferTickerChan: make(chan int, clientSignalSize), sendBufferChan: make(chan int, clientSignalSize), quitWSHandler: make(chan struct{}), xcChan: make(exchangeChannel, 16), } }
go
func NewWebsocketHub() *WebsocketHub { return &WebsocketHub{ clients: make(map[*hubSpoke]*clientHubSpoke), Register: make(chan *clientHubSpoke), Unregister: make(chan *hubSpoke), HubRelay: make(chan hubMessage), newTxBuffer: make([]*types.MempoolTx, 0, newTxBufferSize), bufferTickerChan: make(chan int, clientSignalSize), sendBufferChan: make(chan int, clientSignalSize), quitWSHandler: make(chan struct{}), xcChan: make(exchangeChannel, 16), } }
[ "func", "NewWebsocketHub", "(", ")", "*", "WebsocketHub", "{", "return", "&", "WebsocketHub", "{", "clients", ":", "make", "(", "map", "[", "*", "hubSpoke", "]", "*", "clientHubSpoke", ")", ",", "Register", ":", "make", "(", "chan", "*", "clientHubSpoke", ")", ",", "Unregister", ":", "make", "(", "chan", "*", "hubSpoke", ")", ",", "HubRelay", ":", "make", "(", "chan", "hubMessage", ")", ",", "newTxBuffer", ":", "make", "(", "[", "]", "*", "types", ".", "MempoolTx", ",", "0", ",", "newTxBufferSize", ")", ",", "bufferTickerChan", ":", "make", "(", "chan", "int", ",", "clientSignalSize", ")", ",", "sendBufferChan", ":", "make", "(", "chan", "int", ",", "clientSignalSize", ")", ",", "quitWSHandler", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "xcChan", ":", "make", "(", "exchangeChannel", ",", "16", ")", ",", "}", "\n", "}" ]
// NewWebsocketHub creates a new WebsocketHub
[ "NewWebsocketHub", "creates", "a", "new", "WebsocketHub" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/websocket.go#L90-L102
train
decred/dcrdata
explorer/websocket.go
NumClients
func (wsh *WebsocketHub) NumClients() int { // Swallow any type assertion error since the default int of 0 is OK. n, _ := wsh.numClients.Load().(int) return n }
go
func (wsh *WebsocketHub) NumClients() int { // Swallow any type assertion error since the default int of 0 is OK. n, _ := wsh.numClients.Load().(int) return n }
[ "func", "(", "wsh", "*", "WebsocketHub", ")", "NumClients", "(", ")", "int", "{", "// Swallow any type assertion error since the default int of 0 is OK.", "n", ",", "_", ":=", "wsh", ".", "numClients", ".", "Load", "(", ")", ".", "(", "int", ")", "\n", "return", "n", "\n", "}" ]
// NumClients returns the number of clients connected to the websocket hub.
[ "NumClients", "returns", "the", "number", "of", "clients", "connected", "to", "the", "websocket", "hub", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/websocket.go#L111-L115
train
decred/dcrdata
explorer/websocket.go
RegisterClient
func (wsh *WebsocketHub) RegisterClient(c *hubSpoke, xcChan exchangeChannel) *client { cl := new(client) wsh.Register <- &clientHubSpoke{cl, c, xcChan} return cl }
go
func (wsh *WebsocketHub) RegisterClient(c *hubSpoke, xcChan exchangeChannel) *client { cl := new(client) wsh.Register <- &clientHubSpoke{cl, c, xcChan} return cl }
[ "func", "(", "wsh", "*", "WebsocketHub", ")", "RegisterClient", "(", "c", "*", "hubSpoke", ",", "xcChan", "exchangeChannel", ")", "*", "client", "{", "cl", ":=", "new", "(", "client", ")", "\n", "wsh", ".", "Register", "<-", "&", "clientHubSpoke", "{", "cl", ",", "c", ",", "xcChan", "}", "\n", "return", "cl", "\n", "}" ]
// RegisterClient registers a websocket connection with the hub, and returns a // pointer to the new client data object.
[ "RegisterClient", "registers", "a", "websocket", "connection", "with", "the", "hub", "and", "returns", "a", "pointer", "to", "the", "new", "client", "data", "object", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/websocket.go#L123-L127
train
decred/dcrdata
explorer/websocket.go
pingClients
func (wsh *WebsocketHub) pingClients() chan<- struct{} { stopPing := make(chan struct{}) go func() { // start the client ping ticker ticker := time.NewTicker(pingInterval) defer ticker.Stop() for { select { case <-ticker.C: wsh.HubRelay <- pstypes.HubMessage{Signal: sigPingAndUserCount} case _, ok := <-stopPing: if !ok { log.Errorf("Do not send on stopPing channel, only close it.") } return } } }() return stopPing }
go
func (wsh *WebsocketHub) pingClients() chan<- struct{} { stopPing := make(chan struct{}) go func() { // start the client ping ticker ticker := time.NewTicker(pingInterval) defer ticker.Stop() for { select { case <-ticker.C: wsh.HubRelay <- pstypes.HubMessage{Signal: sigPingAndUserCount} case _, ok := <-stopPing: if !ok { log.Errorf("Do not send on stopPing channel, only close it.") } return } } }() return stopPing }
[ "func", "(", "wsh", "*", "WebsocketHub", ")", "pingClients", "(", ")", "chan", "<-", "struct", "{", "}", "{", "stopPing", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n\n", "go", "func", "(", ")", "{", "// start the client ping ticker", "ticker", ":=", "time", ".", "NewTicker", "(", "pingInterval", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "ticker", ".", "C", ":", "wsh", ".", "HubRelay", "<-", "pstypes", ".", "HubMessage", "{", "Signal", ":", "sigPingAndUserCount", "}", "\n", "case", "_", ",", "ok", ":=", "<-", "stopPing", ":", "if", "!", "ok", "{", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "stopPing", "\n", "}" ]
// Periodically ping clients over websocket connection. Stop the ping loop by // closing the returned channel.
[ "Periodically", "ping", "clients", "over", "websocket", "connection", ".", "Stop", "the", "ping", "loop", "by", "closing", "the", "returned", "channel", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/websocket.go#L171-L193
train
decred/dcrdata
explorer/websocket.go
addTxToBuffer
func (wsh *WebsocketHub) addTxToBuffer(tx *types.MempoolTx) bool { wsh.bufferMtx.Lock() defer wsh.bufferMtx.Unlock() wsh.newTxBuffer = append(wsh.newTxBuffer, tx) return len(wsh.newTxBuffer) >= newTxBufferSize }
go
func (wsh *WebsocketHub) addTxToBuffer(tx *types.MempoolTx) bool { wsh.bufferMtx.Lock() defer wsh.bufferMtx.Unlock() wsh.newTxBuffer = append(wsh.newTxBuffer, tx) return len(wsh.newTxBuffer) >= newTxBufferSize }
[ "func", "(", "wsh", "*", "WebsocketHub", ")", "addTxToBuffer", "(", "tx", "*", "types", ".", "MempoolTx", ")", "bool", "{", "wsh", ".", "bufferMtx", ".", "Lock", "(", ")", "\n", "defer", "wsh", ".", "bufferMtx", ".", "Unlock", "(", ")", "\n\n", "wsh", ".", "newTxBuffer", "=", "append", "(", "wsh", ".", "newTxBuffer", ",", "tx", ")", "\n\n", "return", "len", "(", "wsh", ".", "newTxBuffer", ")", ">=", "newTxBufferSize", "\n", "}" ]
// addTxToBuffer adds a tx to the buffer, then returns if the buffer is full
[ "addTxToBuffer", "adds", "a", "tx", "to", "the", "buffer", "then", "returns", "if", "the", "buffer", "is", "full" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/websocket.go#L358-L365
train
decred/dcrdata
explorer/websocket.go
periodicBufferSend
func (wsh *WebsocketHub) periodicBufferSend() { ticker := time.NewTicker(bufferTickerInterval * time.Second) for { select { case <-ticker.C: wsh.sendBufferChan <- bufferSend case sig := <-wsh.bufferTickerChan: switch sig { case tickerSigReset: ticker.Stop() ticker = time.NewTicker(bufferTickerInterval * time.Second) case tickerSigStop: close(wsh.bufferTickerChan) return } } } }
go
func (wsh *WebsocketHub) periodicBufferSend() { ticker := time.NewTicker(bufferTickerInterval * time.Second) for { select { case <-ticker.C: wsh.sendBufferChan <- bufferSend case sig := <-wsh.bufferTickerChan: switch sig { case tickerSigReset: ticker.Stop() ticker = time.NewTicker(bufferTickerInterval * time.Second) case tickerSigStop: close(wsh.bufferTickerChan) return } } } }
[ "func", "(", "wsh", "*", "WebsocketHub", ")", "periodicBufferSend", "(", ")", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "bufferTickerInterval", "*", "time", ".", "Second", ")", "\n", "for", "{", "select", "{", "case", "<-", "ticker", ".", "C", ":", "wsh", ".", "sendBufferChan", "<-", "bufferSend", "\n", "case", "sig", ":=", "<-", "wsh", ".", "bufferTickerChan", ":", "switch", "sig", "{", "case", "tickerSigReset", ":", "ticker", ".", "Stop", "(", ")", "\n", "ticker", "=", "time", ".", "NewTicker", "(", "bufferTickerInterval", "*", "time", ".", "Second", ")", "\n", "case", "tickerSigStop", ":", "close", "(", "wsh", ".", "bufferTickerChan", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// periodicBufferSend initiates a buffer send every bufferTickerInterval seconds
[ "periodicBufferSend", "initiates", "a", "buffer", "send", "every", "bufferTickerInterval", "seconds" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/websocket.go#L368-L385
train
decred/dcrdata
blockdata/chainmonitor.go
NewChainMonitor
func NewChainMonitor(ctx context.Context, collector *Collector, savers []BlockDataSaver, reorgSavers []BlockDataSaver, wg *sync.WaitGroup, addrs map[string]txhelpers.TxAction, recvTxBlockChan chan *txhelpers.BlockWatchedTx, reorgChan chan *txhelpers.ReorgData) *chainMonitor { return &chainMonitor{ ctx: ctx, collector: collector, dataSavers: savers, reorgDataSavers: reorgSavers, wg: wg, watchaddrs: addrs, recvTxBlockChan: recvTxBlockChan, reorgChan: reorgChan, } }
go
func NewChainMonitor(ctx context.Context, collector *Collector, savers []BlockDataSaver, reorgSavers []BlockDataSaver, wg *sync.WaitGroup, addrs map[string]txhelpers.TxAction, recvTxBlockChan chan *txhelpers.BlockWatchedTx, reorgChan chan *txhelpers.ReorgData) *chainMonitor { return &chainMonitor{ ctx: ctx, collector: collector, dataSavers: savers, reorgDataSavers: reorgSavers, wg: wg, watchaddrs: addrs, recvTxBlockChan: recvTxBlockChan, reorgChan: reorgChan, } }
[ "func", "NewChainMonitor", "(", "ctx", "context", ".", "Context", ",", "collector", "*", "Collector", ",", "savers", "[", "]", "BlockDataSaver", ",", "reorgSavers", "[", "]", "BlockDataSaver", ",", "wg", "*", "sync", ".", "WaitGroup", ",", "addrs", "map", "[", "string", "]", "txhelpers", ".", "TxAction", ",", "recvTxBlockChan", "chan", "*", "txhelpers", ".", "BlockWatchedTx", ",", "reorgChan", "chan", "*", "txhelpers", ".", "ReorgData", ")", "*", "chainMonitor", "{", "return", "&", "chainMonitor", "{", "ctx", ":", "ctx", ",", "collector", ":", "collector", ",", "dataSavers", ":", "savers", ",", "reorgDataSavers", ":", "reorgSavers", ",", "wg", ":", "wg", ",", "watchaddrs", ":", "addrs", ",", "recvTxBlockChan", ":", "recvTxBlockChan", ",", "reorgChan", ":", "reorgChan", ",", "}", "\n", "}" ]
// NewChainMonitor creates a new chainMonitor.
[ "NewChainMonitor", "creates", "a", "new", "chainMonitor", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/blockdata/chainmonitor.go#L34-L47
train
decred/dcrdata
db/dcrpg/pgblockchain.go
TicketPoolData
func TicketPoolData(interval dbtypes.TimeBasedGrouping, height int64) (timeGraph *dbtypes.PoolTicketsData, priceGraph *dbtypes.PoolTicketsData, donutChart *dbtypes.PoolTicketsData, actualHeight int64, intervalFound, isStale bool) { ticketPoolGraphsCache.RLock() defer ticketPoolGraphsCache.RUnlock() var tFound, pFound, dFound bool timeGraph, tFound = ticketPoolGraphsCache.TimeGraphCache[interval] priceGraph, pFound = ticketPoolGraphsCache.PriceGraphCache[interval] donutChart, dFound = ticketPoolGraphsCache.DonutGraphCache[interval] intervalFound = tFound && pFound && dFound actualHeight = ticketPoolGraphsCache.Height[interval] isStale = ticketPoolGraphsCache.Height[interval] != height return }
go
func TicketPoolData(interval dbtypes.TimeBasedGrouping, height int64) (timeGraph *dbtypes.PoolTicketsData, priceGraph *dbtypes.PoolTicketsData, donutChart *dbtypes.PoolTicketsData, actualHeight int64, intervalFound, isStale bool) { ticketPoolGraphsCache.RLock() defer ticketPoolGraphsCache.RUnlock() var tFound, pFound, dFound bool timeGraph, tFound = ticketPoolGraphsCache.TimeGraphCache[interval] priceGraph, pFound = ticketPoolGraphsCache.PriceGraphCache[interval] donutChart, dFound = ticketPoolGraphsCache.DonutGraphCache[interval] intervalFound = tFound && pFound && dFound actualHeight = ticketPoolGraphsCache.Height[interval] isStale = ticketPoolGraphsCache.Height[interval] != height return }
[ "func", "TicketPoolData", "(", "interval", "dbtypes", ".", "TimeBasedGrouping", ",", "height", "int64", ")", "(", "timeGraph", "*", "dbtypes", ".", "PoolTicketsData", ",", "priceGraph", "*", "dbtypes", ".", "PoolTicketsData", ",", "donutChart", "*", "dbtypes", ".", "PoolTicketsData", ",", "actualHeight", "int64", ",", "intervalFound", ",", "isStale", "bool", ")", "{", "ticketPoolGraphsCache", ".", "RLock", "(", ")", "\n", "defer", "ticketPoolGraphsCache", ".", "RUnlock", "(", ")", "\n\n", "var", "tFound", ",", "pFound", ",", "dFound", "bool", "\n", "timeGraph", ",", "tFound", "=", "ticketPoolGraphsCache", ".", "TimeGraphCache", "[", "interval", "]", "\n", "priceGraph", ",", "pFound", "=", "ticketPoolGraphsCache", ".", "PriceGraphCache", "[", "interval", "]", "\n", "donutChart", ",", "dFound", "=", "ticketPoolGraphsCache", ".", "DonutGraphCache", "[", "interval", "]", "\n", "intervalFound", "=", "tFound", "&&", "pFound", "&&", "dFound", "\n\n", "actualHeight", "=", "ticketPoolGraphsCache", ".", "Height", "[", "interval", "]", "\n", "isStale", "=", "ticketPoolGraphsCache", ".", "Height", "[", "interval", "]", "!=", "height", "\n\n", "return", "\n", "}" ]
// TicketPoolData is a thread-safe way to access the ticketpool graphs data // stored in the cache.
[ "TicketPoolData", "is", "a", "thread", "-", "safe", "way", "to", "access", "the", "ticketpool", "graphs", "data", "stored", "in", "the", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L81-L96
train
decred/dcrdata
db/dcrpg/pgblockchain.go
UpdateTicketPoolData
func UpdateTicketPoolData(interval dbtypes.TimeBasedGrouping, timeGraph *dbtypes.PoolTicketsData, priceGraph *dbtypes.PoolTicketsData, donutcharts *dbtypes.PoolTicketsData, height int64) { ticketPoolGraphsCache.Lock() defer ticketPoolGraphsCache.Unlock() ticketPoolGraphsCache.Height[interval] = height ticketPoolGraphsCache.TimeGraphCache[interval] = timeGraph ticketPoolGraphsCache.PriceGraphCache[interval] = priceGraph ticketPoolGraphsCache.DonutGraphCache[interval] = donutcharts }
go
func UpdateTicketPoolData(interval dbtypes.TimeBasedGrouping, timeGraph *dbtypes.PoolTicketsData, priceGraph *dbtypes.PoolTicketsData, donutcharts *dbtypes.PoolTicketsData, height int64) { ticketPoolGraphsCache.Lock() defer ticketPoolGraphsCache.Unlock() ticketPoolGraphsCache.Height[interval] = height ticketPoolGraphsCache.TimeGraphCache[interval] = timeGraph ticketPoolGraphsCache.PriceGraphCache[interval] = priceGraph ticketPoolGraphsCache.DonutGraphCache[interval] = donutcharts }
[ "func", "UpdateTicketPoolData", "(", "interval", "dbtypes", ".", "TimeBasedGrouping", ",", "timeGraph", "*", "dbtypes", ".", "PoolTicketsData", ",", "priceGraph", "*", "dbtypes", ".", "PoolTicketsData", ",", "donutcharts", "*", "dbtypes", ".", "PoolTicketsData", ",", "height", "int64", ")", "{", "ticketPoolGraphsCache", ".", "Lock", "(", ")", "\n", "defer", "ticketPoolGraphsCache", ".", "Unlock", "(", ")", "\n\n", "ticketPoolGraphsCache", ".", "Height", "[", "interval", "]", "=", "height", "\n", "ticketPoolGraphsCache", ".", "TimeGraphCache", "[", "interval", "]", "=", "timeGraph", "\n", "ticketPoolGraphsCache", ".", "PriceGraphCache", "[", "interval", "]", "=", "priceGraph", "\n", "ticketPoolGraphsCache", ".", "DonutGraphCache", "[", "interval", "]", "=", "donutcharts", "\n", "}" ]
// UpdateTicketPoolData updates the ticket pool cache with the latest data fetched. // This is a thread-safe way to update ticket pool cache data. TryLock helps avoid // stacking calls to update the cache.
[ "UpdateTicketPoolData", "updates", "the", "ticket", "pool", "cache", "with", "the", "latest", "data", "fetched", ".", "This", "is", "a", "thread", "-", "safe", "way", "to", "update", "ticket", "pool", "cache", "data", ".", "TryLock", "helps", "avoid", "stacking", "calls", "to", "update", "the", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L101-L110
train
decred/dcrdata
db/dcrpg/pgblockchain.go
newUtxoStore
func newUtxoStore(prealloc int) utxoStore { return utxoStore{ c: make(map[string]map[uint32]*dbtypes.UTXOData, prealloc), } }
go
func newUtxoStore(prealloc int) utxoStore { return utxoStore{ c: make(map[string]map[uint32]*dbtypes.UTXOData, prealloc), } }
[ "func", "newUtxoStore", "(", "prealloc", "int", ")", "utxoStore", "{", "return", "utxoStore", "{", "c", ":", "make", "(", "map", "[", "string", "]", "map", "[", "uint32", "]", "*", "dbtypes", ".", "UTXOData", ",", "prealloc", ")", ",", "}", "\n", "}" ]
// newUtxoStore constructs a new utxoStore.
[ "newUtxoStore", "constructs", "a", "new", "utxoStore", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L119-L123
train
decred/dcrdata
db/dcrpg/pgblockchain.go
Get
func (u *utxoStore) Get(txHash string, txIndex uint32) (*dbtypes.UTXOData, bool) { u.Lock() defer u.Unlock() utxoData, ok := u.c[txHash][txIndex] if ok { u.c[txHash][txIndex] = nil delete(u.c[txHash], txIndex) if len(u.c[txHash]) == 0 { delete(u.c, txHash) } } return utxoData, ok }
go
func (u *utxoStore) Get(txHash string, txIndex uint32) (*dbtypes.UTXOData, bool) { u.Lock() defer u.Unlock() utxoData, ok := u.c[txHash][txIndex] if ok { u.c[txHash][txIndex] = nil delete(u.c[txHash], txIndex) if len(u.c[txHash]) == 0 { delete(u.c, txHash) } } return utxoData, ok }
[ "func", "(", "u", "*", "utxoStore", ")", "Get", "(", "txHash", "string", ",", "txIndex", "uint32", ")", "(", "*", "dbtypes", ".", "UTXOData", ",", "bool", ")", "{", "u", ".", "Lock", "(", ")", "\n", "defer", "u", ".", "Unlock", "(", ")", "\n", "utxoData", ",", "ok", ":=", "u", ".", "c", "[", "txHash", "]", "[", "txIndex", "]", "\n", "if", "ok", "{", "u", ".", "c", "[", "txHash", "]", "[", "txIndex", "]", "=", "nil", "\n", "delete", "(", "u", ".", "c", "[", "txHash", "]", ",", "txIndex", ")", "\n", "if", "len", "(", "u", ".", "c", "[", "txHash", "]", ")", "==", "0", "{", "delete", "(", "u", ".", "c", ",", "txHash", ")", "\n", "}", "\n", "}", "\n", "return", "utxoData", ",", "ok", "\n", "}" ]
// Get attempts to locate UTXOData for the specified outpoint. If the data is // not in the cache, a nil pointer and false are returned. If the data is // located, the data and true are returned, and the data is evicted from cache.
[ "Get", "attempts", "to", "locate", "UTXOData", "for", "the", "specified", "outpoint", ".", "If", "the", "data", "is", "not", "in", "the", "cache", "a", "nil", "pointer", "and", "false", "are", "returned", ".", "If", "the", "data", "is", "located", "the", "data", "and", "true", "are", "returned", "and", "the", "data", "is", "evicted", "from", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L128-L140
train
decred/dcrdata
db/dcrpg/pgblockchain.go
Set
func (u *utxoStore) Set(txHash string, txIndex uint32, addrs []string, val int64) { u.Lock() defer u.Unlock() u.set(txHash, txIndex, addrs, val) }
go
func (u *utxoStore) Set(txHash string, txIndex uint32, addrs []string, val int64) { u.Lock() defer u.Unlock() u.set(txHash, txIndex, addrs, val) }
[ "func", "(", "u", "*", "utxoStore", ")", "Set", "(", "txHash", "string", ",", "txIndex", "uint32", ",", "addrs", "[", "]", "string", ",", "val", "int64", ")", "{", "u", ".", "Lock", "(", ")", "\n", "defer", "u", ".", "Unlock", "(", ")", "\n", "u", ".", "set", "(", "txHash", ",", "txIndex", ",", "addrs", ",", "val", ")", "\n", "}" ]
// Set stores the addresses and amount in a UTXOData entry in the cache for the // given outpoint.
[ "Set", "stores", "the", "addresses", "and", "amount", "in", "a", "UTXOData", "entry", "in", "the", "cache", "for", "the", "given", "outpoint", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L161-L165
train
decred/dcrdata
db/dcrpg/pgblockchain.go
Reinit
func (u *utxoStore) Reinit(utxos []dbtypes.UTXO) { u.Lock() defer u.Unlock() // Pre-allocate the transaction hash map assuming the number of unique // transaction hashes in input is roughly 2/3 of the number of UTXOs. prealloc := 2 * len(utxos) / 3 u.c = make(map[string]map[uint32]*dbtypes.UTXOData, prealloc) for i := range utxos { u.set(utxos[i].TxHash, utxos[i].TxIndex, utxos[i].Addresses, utxos[i].Value) } }
go
func (u *utxoStore) Reinit(utxos []dbtypes.UTXO) { u.Lock() defer u.Unlock() // Pre-allocate the transaction hash map assuming the number of unique // transaction hashes in input is roughly 2/3 of the number of UTXOs. prealloc := 2 * len(utxos) / 3 u.c = make(map[string]map[uint32]*dbtypes.UTXOData, prealloc) for i := range utxos { u.set(utxos[i].TxHash, utxos[i].TxIndex, utxos[i].Addresses, utxos[i].Value) } }
[ "func", "(", "u", "*", "utxoStore", ")", "Reinit", "(", "utxos", "[", "]", "dbtypes", ".", "UTXO", ")", "{", "u", ".", "Lock", "(", ")", "\n", "defer", "u", ".", "Unlock", "(", ")", "\n", "// Pre-allocate the transaction hash map assuming the number of unique", "// transaction hashes in input is roughly 2/3 of the number of UTXOs.", "prealloc", ":=", "2", "*", "len", "(", "utxos", ")", "/", "3", "\n", "u", ".", "c", "=", "make", "(", "map", "[", "string", "]", "map", "[", "uint32", "]", "*", "dbtypes", ".", "UTXOData", ",", "prealloc", ")", "\n", "for", "i", ":=", "range", "utxos", "{", "u", ".", "set", "(", "utxos", "[", "i", "]", ".", "TxHash", ",", "utxos", "[", "i", "]", ".", "TxIndex", ",", "utxos", "[", "i", "]", ".", "Addresses", ",", "utxos", "[", "i", "]", ".", "Value", ")", "\n", "}", "\n", "}" ]
// Reinit re-initializes the utxoStore with the given UTXOs.
[ "Reinit", "re", "-", "initializes", "the", "utxoStore", "with", "the", "given", "UTXOs", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L168-L178
train
decred/dcrdata
db/dcrpg/pgblockchain.go
Size
func (u *utxoStore) Size() (sz int) { u.Lock() defer u.Unlock() for _, m := range u.c { sz += len(m) } return }
go
func (u *utxoStore) Size() (sz int) { u.Lock() defer u.Unlock() for _, m := range u.c { sz += len(m) } return }
[ "func", "(", "u", "*", "utxoStore", ")", "Size", "(", ")", "(", "sz", "int", ")", "{", "u", ".", "Lock", "(", ")", "\n", "defer", "u", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "m", ":=", "range", "u", ".", "c", "{", "sz", "+=", "len", "(", "m", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Size returns the size of the utxo cache in number of UTXOs.
[ "Size", "returns", "the", "size", "of", "the", "utxo", "cache", "in", "number", "of", "UTXOs", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L181-L188
train
decred/dcrdata
db/dcrpg/pgblockchain.go
NewChainDBRPC
func NewChainDBRPC(chaindb *ChainDB, cl *rpcclient.Client) (*ChainDBRPC, error) { return &ChainDBRPC{chaindb, cl}, nil }
go
func NewChainDBRPC(chaindb *ChainDB, cl *rpcclient.Client) (*ChainDBRPC, error) { return &ChainDBRPC{chaindb, cl}, nil }
[ "func", "NewChainDBRPC", "(", "chaindb", "*", "ChainDB", ",", "cl", "*", "rpcclient", ".", "Client", ")", "(", "*", "ChainDBRPC", ",", "error", ")", "{", "return", "&", "ChainDBRPC", "{", "chaindb", ",", "cl", "}", ",", "nil", "\n", "}" ]
// NewChainDBRPC contains ChainDB and RPC client parameters. By default, // duplicate row checks on insertion are enabled. also enables rpc client
[ "NewChainDBRPC", "contains", "ChainDB", "and", "RPC", "client", "parameters", ".", "By", "default", "duplicate", "row", "checks", "on", "insertion", "are", "enabled", ".", "also", "enables", "rpc", "client" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L288-L290
train
decred/dcrdata
db/dcrpg/pgblockchain.go
MissingSideChainBlocks
func (pgb *ChainDBRPC) MissingSideChainBlocks() ([]dbtypes.SideChain, int, error) { // First get the side chain tips (head blocks). tips, err := rpcutils.SideChains(pgb.Client) if err != nil { return nil, 0, fmt.Errorf("unable to get chain tips from node: %v", err) } nSideChains := len(tips) // Build a list of all the blocks in each side chain that are not // already in the database. blocksToStore := make([]dbtypes.SideChain, nSideChains) var nSideChainBlocks int for it := range tips { sideHeight := tips[it].Height log.Tracef("Getting full side chain with tip %s at %d.", tips[it].Hash, sideHeight) sideChain, err := rpcutils.SideChainFull(pgb.Client, tips[it].Hash) if err != nil { return nil, 0, fmt.Errorf("unable to get side chain blocks for chain tip %s: %v", tips[it].Hash, err) } // Starting height is the lowest block in the side chain. sideHeight -= int64(len(sideChain)) - 1 // For each block in the side chain, check if it already stored. for is := range sideChain { // Check for the block hash in the DB. sideHeightDB, err := pgb.BlockHeight(sideChain[is]) if err == sql.ErrNoRows { // This block is NOT already in the DB. blocksToStore[it].Hashes = append(blocksToStore[it].Hashes, sideChain[is]) blocksToStore[it].Heights = append(blocksToStore[it].Heights, sideHeight) nSideChainBlocks++ } else if err == nil { // This block is already in the DB. log.Tracef("Found block %s in postgres at height %d.", sideChain[is], sideHeightDB) if sideHeight != sideHeightDB { log.Errorf("Side chain block height %d, expected %d.", sideHeightDB, sideHeight) } } else /* err != nil && err != sql.ErrNoRows */ { // Unexpected error log.Errorf("Failed to retrieve block %s: %v", sideChain[is], err) } // Next block sideHeight++ } } return blocksToStore, nSideChainBlocks, nil }
go
func (pgb *ChainDBRPC) MissingSideChainBlocks() ([]dbtypes.SideChain, int, error) { // First get the side chain tips (head blocks). tips, err := rpcutils.SideChains(pgb.Client) if err != nil { return nil, 0, fmt.Errorf("unable to get chain tips from node: %v", err) } nSideChains := len(tips) // Build a list of all the blocks in each side chain that are not // already in the database. blocksToStore := make([]dbtypes.SideChain, nSideChains) var nSideChainBlocks int for it := range tips { sideHeight := tips[it].Height log.Tracef("Getting full side chain with tip %s at %d.", tips[it].Hash, sideHeight) sideChain, err := rpcutils.SideChainFull(pgb.Client, tips[it].Hash) if err != nil { return nil, 0, fmt.Errorf("unable to get side chain blocks for chain tip %s: %v", tips[it].Hash, err) } // Starting height is the lowest block in the side chain. sideHeight -= int64(len(sideChain)) - 1 // For each block in the side chain, check if it already stored. for is := range sideChain { // Check for the block hash in the DB. sideHeightDB, err := pgb.BlockHeight(sideChain[is]) if err == sql.ErrNoRows { // This block is NOT already in the DB. blocksToStore[it].Hashes = append(blocksToStore[it].Hashes, sideChain[is]) blocksToStore[it].Heights = append(blocksToStore[it].Heights, sideHeight) nSideChainBlocks++ } else if err == nil { // This block is already in the DB. log.Tracef("Found block %s in postgres at height %d.", sideChain[is], sideHeightDB) if sideHeight != sideHeightDB { log.Errorf("Side chain block height %d, expected %d.", sideHeightDB, sideHeight) } } else /* err != nil && err != sql.ErrNoRows */ { // Unexpected error log.Errorf("Failed to retrieve block %s: %v", sideChain[is], err) } // Next block sideHeight++ } } return blocksToStore, nSideChainBlocks, nil }
[ "func", "(", "pgb", "*", "ChainDBRPC", ")", "MissingSideChainBlocks", "(", ")", "(", "[", "]", "dbtypes", ".", "SideChain", ",", "int", ",", "error", ")", "{", "// First get the side chain tips (head blocks).", "tips", ",", "err", ":=", "rpcutils", ".", "SideChains", "(", "pgb", ".", "Client", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "nSideChains", ":=", "len", "(", "tips", ")", "\n\n", "// Build a list of all the blocks in each side chain that are not", "// already in the database.", "blocksToStore", ":=", "make", "(", "[", "]", "dbtypes", ".", "SideChain", ",", "nSideChains", ")", "\n", "var", "nSideChainBlocks", "int", "\n", "for", "it", ":=", "range", "tips", "{", "sideHeight", ":=", "tips", "[", "it", "]", ".", "Height", "\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "tips", "[", "it", "]", ".", "Hash", ",", "sideHeight", ")", "\n\n", "sideChain", ",", "err", ":=", "rpcutils", ".", "SideChainFull", "(", "pgb", ".", "Client", ",", "tips", "[", "it", "]", ".", "Hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tips", "[", "it", "]", ".", "Hash", ",", "err", ")", "\n", "}", "\n", "// Starting height is the lowest block in the side chain.", "sideHeight", "-=", "int64", "(", "len", "(", "sideChain", ")", ")", "-", "1", "\n\n", "// For each block in the side chain, check if it already stored.", "for", "is", ":=", "range", "sideChain", "{", "// Check for the block hash in the DB.", "sideHeightDB", ",", "err", ":=", "pgb", ".", "BlockHeight", "(", "sideChain", "[", "is", "]", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "// This block is NOT already in the DB.", "blocksToStore", "[", "it", "]", ".", "Hashes", "=", "append", "(", "blocksToStore", "[", "it", "]", ".", "Hashes", ",", "sideChain", "[", "is", "]", ")", "\n", "blocksToStore", "[", "it", "]", ".", "Heights", "=", "append", "(", "blocksToStore", "[", "it", "]", ".", "Heights", ",", "sideHeight", ")", "\n", "nSideChainBlocks", "++", "\n", "}", "else", "if", "err", "==", "nil", "{", "// This block is already in the DB.", "log", ".", "Tracef", "(", "\"", "\"", ",", "sideChain", "[", "is", "]", ",", "sideHeightDB", ")", "\n", "if", "sideHeight", "!=", "sideHeightDB", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "sideHeightDB", ",", "sideHeight", ")", "\n", "}", "\n", "}", "else", "/* err != nil && err != sql.ErrNoRows */", "{", "// Unexpected error", "log", ".", "Errorf", "(", "\"", "\"", ",", "sideChain", "[", "is", "]", ",", "err", ")", "\n", "}", "\n\n", "// Next block", "sideHeight", "++", "\n", "}", "\n", "}", "\n\n", "return", "blocksToStore", ",", "nSideChainBlocks", ",", "nil", "\n", "}" ]
// MissingSideChainBlocks identifies side chain blocks that are missing from the // DB. Side chains known to dcrd are listed via the getchaintips RPC. Each block // presence in the postgres DB is checked, and any missing block is returned in // a SideChain along with a count of the total number of missing blocks.
[ "MissingSideChainBlocks", "identifies", "side", "chain", "blocks", "that", "are", "missing", "from", "the", "DB", ".", "Side", "chains", "known", "to", "dcrd", "are", "listed", "via", "the", "getchaintips", "RPC", ".", "Each", "block", "presence", "in", "the", "postgres", "DB", "is", "checked", "and", "any", "missing", "block", "is", "returned", "in", "a", "SideChain", "along", "with", "a", "count", "of", "the", "total", "number", "of", "missing", "blocks", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L337-L389
train
decred/dcrdata
db/dcrpg/pgblockchain.go
TxnDbID
func (t *TicketTxnIDGetter) TxnDbID(txid string, expire bool) (uint64, error) { if t == nil { panic("You're using an uninitialized TicketTxnIDGetter") } t.mtx.RLock() dbID, ok := t.idCache[txid] t.mtx.RUnlock() if ok { if expire { t.mtx.Lock() delete(t.idCache, txid) t.mtx.Unlock() } return dbID, nil } // Cache miss. Get the row id by hash from the tickets table. log.Tracef("Cache miss for %s.", txid) return RetrieveTicketIDByHashNoCancel(t.db, txid) }
go
func (t *TicketTxnIDGetter) TxnDbID(txid string, expire bool) (uint64, error) { if t == nil { panic("You're using an uninitialized TicketTxnIDGetter") } t.mtx.RLock() dbID, ok := t.idCache[txid] t.mtx.RUnlock() if ok { if expire { t.mtx.Lock() delete(t.idCache, txid) t.mtx.Unlock() } return dbID, nil } // Cache miss. Get the row id by hash from the tickets table. log.Tracef("Cache miss for %s.", txid) return RetrieveTicketIDByHashNoCancel(t.db, txid) }
[ "func", "(", "t", "*", "TicketTxnIDGetter", ")", "TxnDbID", "(", "txid", "string", ",", "expire", "bool", ")", "(", "uint64", ",", "error", ")", "{", "if", "t", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "t", ".", "mtx", ".", "RLock", "(", ")", "\n", "dbID", ",", "ok", ":=", "t", ".", "idCache", "[", "txid", "]", "\n", "t", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "if", "ok", "{", "if", "expire", "{", "t", ".", "mtx", ".", "Lock", "(", ")", "\n", "delete", "(", "t", ".", "idCache", ",", "txid", ")", "\n", "t", ".", "mtx", ".", "Unlock", "(", ")", "\n", "}", "\n", "return", "dbID", ",", "nil", "\n", "}", "\n", "// Cache miss. Get the row id by hash from the tickets table.", "log", ".", "Tracef", "(", "\"", "\"", ",", "txid", ")", "\n", "return", "RetrieveTicketIDByHashNoCancel", "(", "t", ".", "db", ",", "txid", ")", "\n", "}" ]
// TxnDbID fetches DB row ID for the ticket specified by the input transaction // hash. A cache is checked first. In the event of a cache hit, the DB ID is // returned and deleted from the internal cache. In the event of a cache miss, // the database is queried. If the database query fails, the error is non-nil.
[ "TxnDbID", "fetches", "DB", "row", "ID", "for", "the", "ticket", "specified", "by", "the", "input", "transaction", "hash", ".", "A", "cache", "is", "checked", "first", ".", "In", "the", "event", "of", "a", "cache", "hit", "the", "DB", "ID", "is", "returned", "and", "deleted", "from", "the", "internal", "cache", ".", "In", "the", "event", "of", "a", "cache", "miss", "the", "database", "is", "queried", ".", "If", "the", "database", "query", "fails", "the", "error", "is", "non", "-", "nil", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L402-L420
train
decred/dcrdata
db/dcrpg/pgblockchain.go
NewTicketTxnIDGetter
func NewTicketTxnIDGetter(db *sql.DB) *TicketTxnIDGetter { return &TicketTxnIDGetter{ db: db, idCache: make(map[string]uint64), } }
go
func NewTicketTxnIDGetter(db *sql.DB) *TicketTxnIDGetter { return &TicketTxnIDGetter{ db: db, idCache: make(map[string]uint64), } }
[ "func", "NewTicketTxnIDGetter", "(", "db", "*", "sql", ".", "DB", ")", "*", "TicketTxnIDGetter", "{", "return", "&", "TicketTxnIDGetter", "{", "db", ":", "db", ",", "idCache", ":", "make", "(", "map", "[", "string", "]", "uint64", ")", ",", "}", "\n", "}" ]
// NewTicketTxnIDGetter constructs a new TicketTxnIDGetter with an empty cache.
[ "NewTicketTxnIDGetter", "constructs", "a", "new", "TicketTxnIDGetter", "with", "an", "empty", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L445-L450
train
decred/dcrdata
db/dcrpg/pgblockchain.go
NewChainDB
func NewChainDB(dbi *DBInfo, params *chaincfg.Params, stakeDB *stakedb.StakeDatabase, devPrefetch, hidePGConfig bool, addrCacheCap int, mp rpcutils.MempoolAddressChecker, parser ProposalsFetcher, bg BlockGetter) (*ChainDB, error) { ctx := context.Background() chainDB, err := NewChainDBWithCancel(ctx, dbi, params, stakeDB, devPrefetch, hidePGConfig, addrCacheCap, mp, parser, bg) if err != nil { return nil, err } return chainDB, nil }
go
func NewChainDB(dbi *DBInfo, params *chaincfg.Params, stakeDB *stakedb.StakeDatabase, devPrefetch, hidePGConfig bool, addrCacheCap int, mp rpcutils.MempoolAddressChecker, parser ProposalsFetcher, bg BlockGetter) (*ChainDB, error) { ctx := context.Background() chainDB, err := NewChainDBWithCancel(ctx, dbi, params, stakeDB, devPrefetch, hidePGConfig, addrCacheCap, mp, parser, bg) if err != nil { return nil, err } return chainDB, nil }
[ "func", "NewChainDB", "(", "dbi", "*", "DBInfo", ",", "params", "*", "chaincfg", ".", "Params", ",", "stakeDB", "*", "stakedb", ".", "StakeDatabase", ",", "devPrefetch", ",", "hidePGConfig", "bool", ",", "addrCacheCap", "int", ",", "mp", "rpcutils", ".", "MempoolAddressChecker", ",", "parser", "ProposalsFetcher", ",", "bg", "BlockGetter", ")", "(", "*", "ChainDB", ",", "error", ")", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "chainDB", ",", "err", ":=", "NewChainDBWithCancel", "(", "ctx", ",", "dbi", ",", "params", ",", "stakeDB", ",", "devPrefetch", ",", "hidePGConfig", ",", "addrCacheCap", ",", "mp", ",", "parser", ",", "bg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "chainDB", ",", "nil", "\n", "}" ]
// NewChainDB constructs a ChainDB for the given connection and Decred network // parameters. By default, duplicate row checks on insertion are enabled. See // NewChainDBWithCancel to enable context cancellation of running queries. // proposalsUpdateChan is used to manage politeia update notifications trigger // between the notifier and the handler method. A non-nil BlockGetter is only // needed if database upgrades are required.
[ "NewChainDB", "constructs", "a", "ChainDB", "for", "the", "given", "connection", "and", "Decred", "network", "parameters", ".", "By", "default", "duplicate", "row", "checks", "on", "insertion", "are", "enabled", ".", "See", "NewChainDBWithCancel", "to", "enable", "context", "cancellation", "of", "running", "queries", ".", "proposalsUpdateChan", "is", "used", "to", "manage", "politeia", "update", "notifications", "trigger", "between", "the", "notifier", "and", "the", "handler", "method", ".", "A", "non", "-", "nil", "BlockGetter", "is", "only", "needed", "if", "database", "upgrades", "are", "required", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L464-L475
train
decred/dcrdata
db/dcrpg/pgblockchain.go
InitUtxoCache
func (pgb *ChainDB) InitUtxoCache(utxos []dbtypes.UTXO) { pgb.utxoCache.Reinit(utxos) }
go
func (pgb *ChainDB) InitUtxoCache(utxos []dbtypes.UTXO) { pgb.utxoCache.Reinit(utxos) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "InitUtxoCache", "(", "utxos", "[", "]", "dbtypes", ".", "UTXO", ")", "{", "pgb", ".", "utxoCache", ".", "Reinit", "(", "utxos", ")", "\n", "}" ]
// InitUtxoCache resets the UTXO cache with the given slice of UTXO data.
[ "InitUtxoCache", "resets", "the", "UTXO", "cache", "with", "the", "given", "slice", "of", "UTXO", "data", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L790-L792
train
decred/dcrdata
db/dcrpg/pgblockchain.go
SideChainBlocks
func (pgb *ChainDB) SideChainBlocks() ([]*dbtypes.BlockStatus, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() scb, err := RetrieveSideChainBlocks(ctx, pgb.db) return scb, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) SideChainBlocks() ([]*dbtypes.BlockStatus, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() scb, err := RetrieveSideChainBlocks(ctx, pgb.db) return scb, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "SideChainBlocks", "(", ")", "(", "[", "]", "*", "dbtypes", ".", "BlockStatus", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "scb", ",", "err", ":=", "RetrieveSideChainBlocks", "(", "ctx", ",", "pgb", ".", "db", ")", "\n", "return", "scb", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// SideChainBlocks retrieves all known side chain blocks.
[ "SideChainBlocks", "retrieves", "all", "known", "side", "chain", "blocks", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L874-L879
train
decred/dcrdata
db/dcrpg/pgblockchain.go
DisapprovedBlocks
func (pgb *ChainDB) DisapprovedBlocks() ([]*dbtypes.BlockStatus, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() disb, err := RetrieveDisapprovedBlocks(ctx, pgb.db) return disb, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) DisapprovedBlocks() ([]*dbtypes.BlockStatus, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() disb, err := RetrieveDisapprovedBlocks(ctx, pgb.db) return disb, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "DisapprovedBlocks", "(", ")", "(", "[", "]", "*", "dbtypes", ".", "BlockStatus", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "disb", ",", "err", ":=", "RetrieveDisapprovedBlocks", "(", "ctx", ",", "pgb", ".", "db", ")", "\n", "return", "disb", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// DisapprovedBlocks retrieves all blocks disapproved by stakeholder votes.
[ "DisapprovedBlocks", "retrieves", "all", "blocks", "disapproved", "by", "stakeholder", "votes", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L890-L895
train
decred/dcrdata
db/dcrpg/pgblockchain.go
BlockStatus
func (pgb *ChainDB) BlockStatus(hash string) (dbtypes.BlockStatus, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() bs, err := RetrieveBlockStatus(ctx, pgb.db, hash) return bs, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) BlockStatus(hash string) (dbtypes.BlockStatus, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() bs, err := RetrieveBlockStatus(ctx, pgb.db, hash) return bs, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "BlockStatus", "(", "hash", "string", ")", "(", "dbtypes", ".", "BlockStatus", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "bs", ",", "err", ":=", "RetrieveBlockStatus", "(", "ctx", ",", "pgb", ".", "db", ",", "hash", ")", "\n", "return", "bs", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// BlockStatus retrieves the block chain status of the specified block.
[ "BlockStatus", "retrieves", "the", "block", "chain", "status", "of", "the", "specified", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L898-L903
train
decred/dcrdata
db/dcrpg/pgblockchain.go
blockFlags
func (pgb *ChainDB) blockFlags(ctx context.Context, hash string) (bool, bool, error) { iv, im, err := RetrieveBlockFlags(ctx, pgb.db, hash) return iv, im, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) blockFlags(ctx context.Context, hash string) (bool, bool, error) { iv, im, err := RetrieveBlockFlags(ctx, pgb.db, hash) return iv, im, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "blockFlags", "(", "ctx", "context", ".", "Context", ",", "hash", "string", ")", "(", "bool", ",", "bool", ",", "error", ")", "{", "iv", ",", "im", ",", "err", ":=", "RetrieveBlockFlags", "(", "ctx", ",", "pgb", ".", "db", ",", "hash", ")", "\n", "return", "iv", ",", "im", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// blockFlags retrieves the block's isValid and isMainchain flags.
[ "blockFlags", "retrieves", "the", "block", "s", "isValid", "and", "isMainchain", "flags", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L906-L909
train
decred/dcrdata
db/dcrpg/pgblockchain.go
BlockFlags
func (pgb *ChainDB) BlockFlags(hash string) (bool, bool, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() return pgb.blockFlags(ctx, hash) }
go
func (pgb *ChainDB) BlockFlags(hash string) (bool, bool, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() return pgb.blockFlags(ctx, hash) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "BlockFlags", "(", "hash", "string", ")", "(", "bool", ",", "bool", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "return", "pgb", ".", "blockFlags", "(", "ctx", ",", "hash", ")", "\n", "}" ]
// BlockFlags retrieves the block's isValid and isMainchain flags.
[ "BlockFlags", "retrieves", "the", "block", "s", "isValid", "and", "isMainchain", "flags", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L912-L916
train
decred/dcrdata
db/dcrpg/pgblockchain.go
BlockFlagsNoCancel
func (pgb *ChainDB) BlockFlagsNoCancel(hash string) (bool, bool, error) { return pgb.blockFlags(context.Background(), hash) }
go
func (pgb *ChainDB) BlockFlagsNoCancel(hash string) (bool, bool, error) { return pgb.blockFlags(context.Background(), hash) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "BlockFlagsNoCancel", "(", "hash", "string", ")", "(", "bool", ",", "bool", ",", "error", ")", "{", "return", "pgb", ".", "blockFlags", "(", "context", ".", "Background", "(", ")", ",", "hash", ")", "\n", "}" ]
// BlockFlagsNoCancel retrieves the block's isValid and isMainchain flags.
[ "BlockFlagsNoCancel", "retrieves", "the", "block", "s", "isValid", "and", "isMainchain", "flags", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L919-L921
train
decred/dcrdata
db/dcrpg/pgblockchain.go
blockChainDbID
func (pgb *ChainDB) blockChainDbID(ctx context.Context, hash string) (dbID uint64, err error) { err = pgb.db.QueryRowContext(ctx, internal.SelectBlockChainRowIDByHash, hash).Scan(&dbID) err = pgb.replaceCancelError(err) return }
go
func (pgb *ChainDB) blockChainDbID(ctx context.Context, hash string) (dbID uint64, err error) { err = pgb.db.QueryRowContext(ctx, internal.SelectBlockChainRowIDByHash, hash).Scan(&dbID) err = pgb.replaceCancelError(err) return }
[ "func", "(", "pgb", "*", "ChainDB", ")", "blockChainDbID", "(", "ctx", "context", ".", "Context", ",", "hash", "string", ")", "(", "dbID", "uint64", ",", "err", "error", ")", "{", "err", "=", "pgb", ".", "db", ".", "QueryRowContext", "(", "ctx", ",", "internal", ".", "SelectBlockChainRowIDByHash", ",", "hash", ")", ".", "Scan", "(", "&", "dbID", ")", "\n", "err", "=", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "return", "\n", "}" ]
// blockChainDbID gets the row ID of the given block hash in the block_chain // table. The cancellation context is used without timeout.
[ "blockChainDbID", "gets", "the", "row", "ID", "of", "the", "given", "block", "hash", "in", "the", "block_chain", "table", ".", "The", "cancellation", "context", "is", "used", "without", "timeout", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L925-L929
train
decred/dcrdata
db/dcrpg/pgblockchain.go
BlockChainDbID
func (pgb *ChainDB) BlockChainDbID(hash string) (dbID uint64, err error) { return pgb.blockChainDbID(pgb.ctx, hash) }
go
func (pgb *ChainDB) BlockChainDbID(hash string) (dbID uint64, err error) { return pgb.blockChainDbID(pgb.ctx, hash) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "BlockChainDbID", "(", "hash", "string", ")", "(", "dbID", "uint64", ",", "err", "error", ")", "{", "return", "pgb", ".", "blockChainDbID", "(", "pgb", ".", "ctx", ",", "hash", ")", "\n", "}" ]
// BlockChainDbID gets the row ID of the given block hash in the block_chain // table. The cancellation context is used without timeout.
[ "BlockChainDbID", "gets", "the", "row", "ID", "of", "the", "given", "block", "hash", "in", "the", "block_chain", "table", ".", "The", "cancellation", "context", "is", "used", "without", "timeout", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L933-L935
train
decred/dcrdata
db/dcrpg/pgblockchain.go
BlockChainDbIDNoCancel
func (pgb *ChainDB) BlockChainDbIDNoCancel(hash string) (dbID uint64, err error) { return pgb.blockChainDbID(context.Background(), hash) }
go
func (pgb *ChainDB) BlockChainDbIDNoCancel(hash string) (dbID uint64, err error) { return pgb.blockChainDbID(context.Background(), hash) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "BlockChainDbIDNoCancel", "(", "hash", "string", ")", "(", "dbID", "uint64", ",", "err", "error", ")", "{", "return", "pgb", ".", "blockChainDbID", "(", "context", ".", "Background", "(", ")", ",", "hash", ")", "\n", "}" ]
// BlockChainDbIDNoCancel gets the row ID of the given block hash in the // block_chain table. The cancellation context is used without timeout.
[ "BlockChainDbIDNoCancel", "gets", "the", "row", "ID", "of", "the", "given", "block", "hash", "in", "the", "block_chain", "table", ".", "The", "cancellation", "context", "is", "used", "without", "timeout", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L939-L941
train
decred/dcrdata
db/dcrpg/pgblockchain.go
TransactionBlocks
func (pgb *ChainDB) TransactionBlocks(txHash string) ([]*dbtypes.BlockStatus, []uint32, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() hashes, heights, inds, valids, mainchains, err := RetrieveTxnsBlocks(ctx, pgb.db, txHash) if err != nil { return nil, nil, pgb.replaceCancelError(err) } blocks := make([]*dbtypes.BlockStatus, len(hashes)) for i := range hashes { blocks[i] = &dbtypes.BlockStatus{ IsValid: valids[i], IsMainchain: mainchains[i], Height: heights[i], Hash: hashes[i], // Next and previous hash not set } } return blocks, inds, nil }
go
func (pgb *ChainDB) TransactionBlocks(txHash string) ([]*dbtypes.BlockStatus, []uint32, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() hashes, heights, inds, valids, mainchains, err := RetrieveTxnsBlocks(ctx, pgb.db, txHash) if err != nil { return nil, nil, pgb.replaceCancelError(err) } blocks := make([]*dbtypes.BlockStatus, len(hashes)) for i := range hashes { blocks[i] = &dbtypes.BlockStatus{ IsValid: valids[i], IsMainchain: mainchains[i], Height: heights[i], Hash: hashes[i], // Next and previous hash not set } } return blocks, inds, nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "TransactionBlocks", "(", "txHash", "string", ")", "(", "[", "]", "*", "dbtypes", ".", "BlockStatus", ",", "[", "]", "uint32", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "hashes", ",", "heights", ",", "inds", ",", "valids", ",", "mainchains", ",", "err", ":=", "RetrieveTxnsBlocks", "(", "ctx", ",", "pgb", ".", "db", ",", "txHash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}", "\n\n", "blocks", ":=", "make", "(", "[", "]", "*", "dbtypes", ".", "BlockStatus", ",", "len", "(", "hashes", ")", ")", "\n\n", "for", "i", ":=", "range", "hashes", "{", "blocks", "[", "i", "]", "=", "&", "dbtypes", ".", "BlockStatus", "{", "IsValid", ":", "valids", "[", "i", "]", ",", "IsMainchain", ":", "mainchains", "[", "i", "]", ",", "Height", ":", "heights", "[", "i", "]", ",", "Hash", ":", "hashes", "[", "i", "]", ",", "// Next and previous hash not set", "}", "\n", "}", "\n\n", "return", "blocks", ",", "inds", ",", "nil", "\n", "}" ]
// TransactionBlocks retrieves the blocks in which the specified transaction // appears, along with the index of the transaction in each of the blocks. The // next and previous block hashes are NOT SET in each BlockStatus.
[ "TransactionBlocks", "retrieves", "the", "blocks", "in", "which", "the", "specified", "transaction", "appears", "along", "with", "the", "index", "of", "the", "transaction", "in", "each", "of", "the", "blocks", ".", "The", "next", "and", "previous", "block", "hashes", "are", "NOT", "SET", "in", "each", "BlockStatus", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L968-L989
train
decred/dcrdata
db/dcrpg/pgblockchain.go
HeightDB
func (pgb *ChainDB) HeightDB() (int64, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() bestHeight, _, _, err := RetrieveBestBlockHeight(ctx, pgb.db) height := int64(bestHeight) if err == sql.ErrNoRows { height = -1 } // DO NOT change this to return -1 if err == sql.ErrNoRows. return height, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) HeightDB() (int64, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() bestHeight, _, _, err := RetrieveBestBlockHeight(ctx, pgb.db) height := int64(bestHeight) if err == sql.ErrNoRows { height = -1 } // DO NOT change this to return -1 if err == sql.ErrNoRows. return height, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "HeightDB", "(", ")", "(", "int64", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "bestHeight", ",", "_", ",", "_", ",", "err", ":=", "RetrieveBestBlockHeight", "(", "ctx", ",", "pgb", ".", "db", ")", "\n", "height", ":=", "int64", "(", "bestHeight", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "height", "=", "-", "1", "\n", "}", "\n", "// DO NOT change this to return -1 if err == sql.ErrNoRows.", "return", "height", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// HeightDB queries the DB for the best block height. When the tables are empty, // the returned height will be -1.
[ "HeightDB", "queries", "the", "DB", "for", "the", "best", "block", "height", ".", "When", "the", "tables", "are", "empty", "the", "returned", "height", "will", "be", "-", "1", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L993-L1003
train
decred/dcrdata
db/dcrpg/pgblockchain.go
HashDB
func (pgb *ChainDB) HashDB() (string, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, bestHash, _, err := RetrieveBestBlockHeight(ctx, pgb.db) return bestHash, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) HashDB() (string, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, bestHash, _, err := RetrieveBestBlockHeight(ctx, pgb.db) return bestHash, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "HashDB", "(", ")", "(", "string", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "_", ",", "bestHash", ",", "_", ",", "err", ":=", "RetrieveBestBlockHeight", "(", "ctx", ",", "pgb", ".", "db", ")", "\n", "return", "bestHash", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// HashDB queries the DB for the best block's hash.
[ "HashDB", "queries", "the", "DB", "for", "the", "best", "block", "s", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1006-L1011
train
decred/dcrdata
db/dcrpg/pgblockchain.go
HeightHashDB
func (pgb *ChainDB) HeightHashDB() (uint64, string, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() height, hash, _, err := RetrieveBestBlockHeight(ctx, pgb.db) return height, hash, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) HeightHashDB() (uint64, string, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() height, hash, _, err := RetrieveBestBlockHeight(ctx, pgb.db) return height, hash, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "HeightHashDB", "(", ")", "(", "uint64", ",", "string", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "height", ",", "hash", ",", "_", ",", "err", ":=", "RetrieveBestBlockHeight", "(", "ctx", ",", "pgb", ".", "db", ")", "\n", "return", "height", ",", "hash", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// HeightHashDB queries the DB for the best block's height and hash.
[ "HeightHashDB", "queries", "the", "DB", "for", "the", "best", "block", "s", "height", "and", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1014-L1019
train
decred/dcrdata
db/dcrpg/pgblockchain.go
Height
func (block *BestBlock) Height() int64 { block.mtx.RLock() defer block.mtx.RUnlock() return block.height }
go
func (block *BestBlock) Height() int64 { block.mtx.RLock() defer block.mtx.RUnlock() return block.height }
[ "func", "(", "block", "*", "BestBlock", ")", "Height", "(", ")", "int64", "{", "block", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "block", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "block", ".", "height", "\n", "}" ]
// Height uses the last stored height.
[ "Height", "uses", "the", "last", "stored", "height", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1027-L1031
train
decred/dcrdata
db/dcrpg/pgblockchain.go
HashStr
func (block *BestBlock) HashStr() string { block.mtx.RLock() defer block.mtx.RUnlock() return block.hash }
go
func (block *BestBlock) HashStr() string { block.mtx.RLock() defer block.mtx.RUnlock() return block.hash }
[ "func", "(", "block", "*", "BestBlock", ")", "HashStr", "(", ")", "string", "{", "block", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "block", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "block", ".", "hash", "\n", "}" ]
// HashStr uses the last stored block hash.
[ "HashStr", "uses", "the", "last", "stored", "block", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1040-L1044
train
decred/dcrdata
db/dcrpg/pgblockchain.go
Hash
func (block *BestBlock) Hash() *chainhash.Hash { // Caller should check hash instead of error hash, _ := chainhash.NewHashFromStr(block.HashStr()) return hash }
go
func (block *BestBlock) Hash() *chainhash.Hash { // Caller should check hash instead of error hash, _ := chainhash.NewHashFromStr(block.HashStr()) return hash }
[ "func", "(", "block", "*", "BestBlock", ")", "Hash", "(", ")", "*", "chainhash", ".", "Hash", "{", "// Caller should check hash instead of error", "hash", ",", "_", ":=", "chainhash", ".", "NewHashFromStr", "(", "block", ".", "HashStr", "(", ")", ")", "\n", "return", "hash", "\n", "}" ]
// Hash uses the last stored block hash.
[ "Hash", "uses", "the", "last", "stored", "block", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1047-L1051
train
decred/dcrdata
db/dcrpg/pgblockchain.go
BlockHeight
func (pgb *ChainDB) BlockHeight(hash string) (int64, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() height, err := RetrieveBlockHeight(ctx, pgb.db, hash) return height, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) BlockHeight(hash string) (int64, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() height, err := RetrieveBlockHeight(ctx, pgb.db, hash) return height, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "BlockHeight", "(", "hash", "string", ")", "(", "int64", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "height", ",", "err", ":=", "RetrieveBlockHeight", "(", "ctx", ",", "pgb", ".", "db", ",", "hash", ")", "\n", "return", "height", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// BlockHeight queries the DB for the height of the specified hash.
[ "BlockHeight", "queries", "the", "DB", "for", "the", "height", "of", "the", "specified", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1077-L1082
train
decred/dcrdata
db/dcrpg/pgblockchain.go
BlockHash
func (pgb *ChainDB) BlockHash(height int64) (string, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() hash, err := RetrieveBlockHash(ctx, pgb.db, height) return hash, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) BlockHash(height int64) (string, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() hash, err := RetrieveBlockHash(ctx, pgb.db, height) return hash, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "BlockHash", "(", "height", "int64", ")", "(", "string", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "hash", ",", "err", ":=", "RetrieveBlockHash", "(", "ctx", ",", "pgb", ".", "db", ",", "height", ")", "\n", "return", "hash", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// BlockHash queries the DB for the hash of the mainchain block at the given // height.
[ "BlockHash", "queries", "the", "DB", "for", "the", "hash", "of", "the", "mainchain", "block", "at", "the", "given", "height", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1086-L1091
train
decred/dcrdata
db/dcrpg/pgblockchain.go
BlockTimeByHeight
func (pgb *ChainDB) BlockTimeByHeight(height int64) (int64, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() time, err := RetrieveBlockTimeByHeight(ctx, pgb.db, height) return time.UNIX(), pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) BlockTimeByHeight(height int64) (int64, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() time, err := RetrieveBlockTimeByHeight(ctx, pgb.db, height) return time.UNIX(), pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "BlockTimeByHeight", "(", "height", "int64", ")", "(", "int64", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "time", ",", "err", ":=", "RetrieveBlockTimeByHeight", "(", "ctx", ",", "pgb", ".", "db", ",", "height", ")", "\n", "return", "time", ".", "UNIX", "(", ")", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// BlockTimeByHeight queries the DB for the time of the mainchain block at the // given height.
[ "BlockTimeByHeight", "queries", "the", "DB", "for", "the", "time", "of", "the", "mainchain", "block", "at", "the", "given", "height", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1095-L1100
train
decred/dcrdata
db/dcrpg/pgblockchain.go
VotesInBlock
func (pgb *ChainDB) VotesInBlock(hash string) (int16, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() voters, err := RetrieveBlockVoteCount(ctx, pgb.db, hash) if err != nil { err = pgb.replaceCancelError(err) log.Errorf("Unable to get block voter count for hash %s: %v", hash, err) return -1, err } return voters, nil }
go
func (pgb *ChainDB) VotesInBlock(hash string) (int16, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() voters, err := RetrieveBlockVoteCount(ctx, pgb.db, hash) if err != nil { err = pgb.replaceCancelError(err) log.Errorf("Unable to get block voter count for hash %s: %v", hash, err) return -1, err } return voters, nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "VotesInBlock", "(", "hash", "string", ")", "(", "int16", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "voters", ",", "err", ":=", "RetrieveBlockVoteCount", "(", "ctx", ",", "pgb", ".", "db", ",", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "log", ".", "Errorf", "(", "\"", "\"", ",", "hash", ",", "err", ")", "\n", "return", "-", "1", ",", "err", "\n", "}", "\n", "return", "voters", ",", "nil", "\n", "}" ]
// VotesInBlock returns the number of votes mined in the block with the // specified hash.
[ "VotesInBlock", "returns", "the", "number", "of", "votes", "mined", "in", "the", "block", "with", "the", "specified", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1104-L1114
train
decred/dcrdata
db/dcrpg/pgblockchain.go
proposalsUpdateHandler
func (pgb *ChainDB) proposalsUpdateHandler() { // Do not initiate the async update if invalid piparser instance was found. if pgb.piparser == nil { log.Debug("invalid piparser instance was found: async update stopped") return } go func() { for range pgb.piparser.UpdateSignal() { count, err := pgb.PiProposalsHistory() if err != nil { log.Error("pgb.PiProposalsHistory failed : %v", err) } else { log.Infof("%d politeia's proposal commits were processed", count) } } }() }
go
func (pgb *ChainDB) proposalsUpdateHandler() { // Do not initiate the async update if invalid piparser instance was found. if pgb.piparser == nil { log.Debug("invalid piparser instance was found: async update stopped") return } go func() { for range pgb.piparser.UpdateSignal() { count, err := pgb.PiProposalsHistory() if err != nil { log.Error("pgb.PiProposalsHistory failed : %v", err) } else { log.Infof("%d politeia's proposal commits were processed", count) } } }() }
[ "func", "(", "pgb", "*", "ChainDB", ")", "proposalsUpdateHandler", "(", ")", "{", "// Do not initiate the async update if invalid piparser instance was found.", "if", "pgb", ".", "piparser", "==", "nil", "{", "log", ".", "Debug", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "go", "func", "(", ")", "{", "for", "range", "pgb", ".", "piparser", ".", "UpdateSignal", "(", ")", "{", "count", ",", "err", ":=", "pgb", ".", "PiProposalsHistory", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "count", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// proposalsUpdateHandler runs in the background asynchronous to retrieve the // politeia proposal updates that the piparser tool signaled.
[ "proposalsUpdateHandler", "runs", "in", "the", "background", "asynchronous", "to", "retrieve", "the", "politeia", "proposal", "updates", "that", "the", "piparser", "tool", "signaled", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1118-L1135
train
decred/dcrdata
db/dcrpg/pgblockchain.go
LastPiParserSync
func (pgb *ChainDB) LastPiParserSync() time.Time { pgb.proposalsSync.mtx.RLock() defer pgb.proposalsSync.mtx.RUnlock() return pgb.proposalsSync.syncTime }
go
func (pgb *ChainDB) LastPiParserSync() time.Time { pgb.proposalsSync.mtx.RLock() defer pgb.proposalsSync.mtx.RUnlock() return pgb.proposalsSync.syncTime }
[ "func", "(", "pgb", "*", "ChainDB", ")", "LastPiParserSync", "(", ")", "time", ".", "Time", "{", "pgb", ".", "proposalsSync", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "pgb", ".", "proposalsSync", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "pgb", ".", "proposalsSync", ".", "syncTime", "\n", "}" ]
// LastPiParserSync returns last time value when the piparser run sync on proposals // and proposal_votes table.
[ "LastPiParserSync", "returns", "last", "time", "value", "when", "the", "piparser", "run", "sync", "on", "proposals", "and", "proposal_votes", "table", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1139-L1143
train
decred/dcrdata
db/dcrpg/pgblockchain.go
PiProposalsHistory
func (pgb *ChainDB) PiProposalsHistory() (int64, error) { if pgb.piparser == nil { return -1, fmt.Errorf("invalid piparser instance was found") } pgb.proposalsSync.mtx.Lock() // set the sync time pgb.proposalsSync.syncTime = time.Now().UTC() pgb.proposalsSync.mtx.Unlock() var isChecked bool var proposalsData []*pitypes.History lastUpdate, err := retrieveLastCommitTime(pgb.db) switch { case err == sql.ErrNoRows: // No records exists yet fetch all the history. proposalsData, err = pgb.piparser.ProposalsHistory() case err != nil: return -1, fmt.Errorf("retrieveLastCommitTime failed :%v", err) default: // Fetch the updates since the last insert only. proposalsData, err = pgb.piparser.ProposalsHistorySince(lastUpdate) isChecked = true } if err != nil { return -1, fmt.Errorf("politeia proposals fetch failed: %v", err) } var commitsCount int64 for _, entry := range proposalsData { if entry.CommitSHA == "" { // If missing commit sha ignore the entry. continue } // Multiple tokens votes data can be packed in a single Politeia's commit. for _, val := range entry.Patch { if val.Token == "" { // If missing token ignore it. continue } id, err := InsertProposal(pgb.db, val.Token, entry.Author, entry.CommitSHA, entry.Date, isChecked) if err != nil { return -1, fmt.Errorf("InsertProposal failed: %v", err) } for _, vote := range val.VotesInfo { _, err = InsertProposalVote(pgb.db, id, vote.Ticket, string(vote.VoteBit), isChecked) if err != nil { return -1, fmt.Errorf("InsertProposalVote failed: %v", err) } } } commitsCount++ } return commitsCount, err }
go
func (pgb *ChainDB) PiProposalsHistory() (int64, error) { if pgb.piparser == nil { return -1, fmt.Errorf("invalid piparser instance was found") } pgb.proposalsSync.mtx.Lock() // set the sync time pgb.proposalsSync.syncTime = time.Now().UTC() pgb.proposalsSync.mtx.Unlock() var isChecked bool var proposalsData []*pitypes.History lastUpdate, err := retrieveLastCommitTime(pgb.db) switch { case err == sql.ErrNoRows: // No records exists yet fetch all the history. proposalsData, err = pgb.piparser.ProposalsHistory() case err != nil: return -1, fmt.Errorf("retrieveLastCommitTime failed :%v", err) default: // Fetch the updates since the last insert only. proposalsData, err = pgb.piparser.ProposalsHistorySince(lastUpdate) isChecked = true } if err != nil { return -1, fmt.Errorf("politeia proposals fetch failed: %v", err) } var commitsCount int64 for _, entry := range proposalsData { if entry.CommitSHA == "" { // If missing commit sha ignore the entry. continue } // Multiple tokens votes data can be packed in a single Politeia's commit. for _, val := range entry.Patch { if val.Token == "" { // If missing token ignore it. continue } id, err := InsertProposal(pgb.db, val.Token, entry.Author, entry.CommitSHA, entry.Date, isChecked) if err != nil { return -1, fmt.Errorf("InsertProposal failed: %v", err) } for _, vote := range val.VotesInfo { _, err = InsertProposalVote(pgb.db, id, vote.Ticket, string(vote.VoteBit), isChecked) if err != nil { return -1, fmt.Errorf("InsertProposalVote failed: %v", err) } } } commitsCount++ } return commitsCount, err }
[ "func", "(", "pgb", "*", "ChainDB", ")", "PiProposalsHistory", "(", ")", "(", "int64", ",", "error", ")", "{", "if", "pgb", ".", "piparser", "==", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "pgb", ".", "proposalsSync", ".", "mtx", ".", "Lock", "(", ")", "\n\n", "// set the sync time", "pgb", ".", "proposalsSync", ".", "syncTime", "=", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", "\n\n", "pgb", ".", "proposalsSync", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "var", "isChecked", "bool", "\n", "var", "proposalsData", "[", "]", "*", "pitypes", ".", "History", "\n\n", "lastUpdate", ",", "err", ":=", "retrieveLastCommitTime", "(", "pgb", ".", "db", ")", "\n", "switch", "{", "case", "err", "==", "sql", ".", "ErrNoRows", ":", "// No records exists yet fetch all the history.", "proposalsData", ",", "err", "=", "pgb", ".", "piparser", ".", "ProposalsHistory", "(", ")", "\n\n", "case", "err", "!=", "nil", ":", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n\n", "default", ":", "// Fetch the updates since the last insert only.", "proposalsData", ",", "err", "=", "pgb", ".", "piparser", ".", "ProposalsHistorySince", "(", "lastUpdate", ")", "\n", "isChecked", "=", "true", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "var", "commitsCount", "int64", "\n\n", "for", "_", ",", "entry", ":=", "range", "proposalsData", "{", "if", "entry", ".", "CommitSHA", "==", "\"", "\"", "{", "// If missing commit sha ignore the entry.", "continue", "\n", "}", "\n\n", "// Multiple tokens votes data can be packed in a single Politeia's commit.", "for", "_", ",", "val", ":=", "range", "entry", ".", "Patch", "{", "if", "val", ".", "Token", "==", "\"", "\"", "{", "// If missing token ignore it.", "continue", "\n", "}", "\n\n", "id", ",", "err", ":=", "InsertProposal", "(", "pgb", ".", "db", ",", "val", ".", "Token", ",", "entry", ".", "Author", ",", "entry", ".", "CommitSHA", ",", "entry", ".", "Date", ",", "isChecked", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "vote", ":=", "range", "val", ".", "VotesInfo", "{", "_", ",", "err", "=", "InsertProposalVote", "(", "pgb", ".", "db", ",", "id", ",", "vote", ".", "Ticket", ",", "string", "(", "vote", ".", "VoteBit", ")", ",", "isChecked", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "commitsCount", "++", "\n", "}", "\n\n", "return", "commitsCount", ",", "err", "\n", "}" ]
// PiProposalsHistory queries the politeia's proposal updates via the parser tool // and pushes them to the proposals and proposal_votes tables.
[ "PiProposalsHistory", "queries", "the", "politeia", "s", "proposal", "updates", "via", "the", "parser", "tool", "and", "pushes", "them", "to", "the", "proposals", "and", "proposal_votes", "tables", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1147-L1214
train
decred/dcrdata
db/dcrpg/pgblockchain.go
ProposalVotes
func (pgb *ChainDB) ProposalVotes(proposalToken string) (*dbtypes.ProposalChartsData, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() chartsData, err := retrieveProposalVotesData(ctx, pgb.db, proposalToken) return chartsData, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) ProposalVotes(proposalToken string) (*dbtypes.ProposalChartsData, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() chartsData, err := retrieveProposalVotesData(ctx, pgb.db, proposalToken) return chartsData, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "ProposalVotes", "(", "proposalToken", "string", ")", "(", "*", "dbtypes", ".", "ProposalChartsData", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "chartsData", ",", "err", ":=", "retrieveProposalVotesData", "(", "ctx", ",", "pgb", ".", "db", ",", "proposalToken", ")", "\n", "return", "chartsData", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// ProposalVotes retrieves all the votes data associated with the provided token.
[ "ProposalVotes", "retrieves", "all", "the", "votes", "data", "associated", "with", "the", "provided", "token", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1217-L1222
train
decred/dcrdata
db/dcrpg/pgblockchain.go
SpendingTransactions
func (pgb *ChainDB) SpendingTransactions(fundingTxID string) ([]string, []uint32, []uint32, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, spendingTxns, vinInds, voutInds, err := RetrieveSpendingTxsByFundingTx(ctx, pgb.db, fundingTxID) return spendingTxns, vinInds, voutInds, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) SpendingTransactions(fundingTxID string) ([]string, []uint32, []uint32, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, spendingTxns, vinInds, voutInds, err := RetrieveSpendingTxsByFundingTx(ctx, pgb.db, fundingTxID) return spendingTxns, vinInds, voutInds, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "SpendingTransactions", "(", "fundingTxID", "string", ")", "(", "[", "]", "string", ",", "[", "]", "uint32", ",", "[", "]", "uint32", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "_", ",", "spendingTxns", ",", "vinInds", ",", "voutInds", ",", "err", ":=", "RetrieveSpendingTxsByFundingTx", "(", "ctx", ",", "pgb", ".", "db", ",", "fundingTxID", ")", "\n", "return", "spendingTxns", ",", "vinInds", ",", "voutInds", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// SpendingTransactions retrieves all transactions spending outpoints from the // specified funding transaction. The spending transaction hashes, the spending // tx input indexes, and the corresponding funding tx output indexes, and an // error value are returned.
[ "SpendingTransactions", "retrieves", "all", "transactions", "spending", "outpoints", "from", "the", "specified", "funding", "transaction", ".", "The", "spending", "transaction", "hashes", "the", "spending", "tx", "input", "indexes", "and", "the", "corresponding", "funding", "tx", "output", "indexes", "and", "an", "error", "value", "are", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1228-L1233
train
decred/dcrdata
db/dcrpg/pgblockchain.go
SpendingTransaction
func (pgb *ChainDB) SpendingTransaction(fundingTxID string, fundingTxVout uint32) (string, uint32, int8, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, spendingTx, vinInd, tree, err := RetrieveSpendingTxByTxOut(ctx, pgb.db, fundingTxID, fundingTxVout) return spendingTx, vinInd, tree, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) SpendingTransaction(fundingTxID string, fundingTxVout uint32) (string, uint32, int8, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, spendingTx, vinInd, tree, err := RetrieveSpendingTxByTxOut(ctx, pgb.db, fundingTxID, fundingTxVout) return spendingTx, vinInd, tree, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "SpendingTransaction", "(", "fundingTxID", "string", ",", "fundingTxVout", "uint32", ")", "(", "string", ",", "uint32", ",", "int8", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "_", ",", "spendingTx", ",", "vinInd", ",", "tree", ",", "err", ":=", "RetrieveSpendingTxByTxOut", "(", "ctx", ",", "pgb", ".", "db", ",", "fundingTxID", ",", "fundingTxVout", ")", "\n", "return", "spendingTx", ",", "vinInd", ",", "tree", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// SpendingTransaction returns the transaction that spends the specified // transaction outpoint, if it is spent. The spending transaction hash, input // index, tx tree, and an error value are returned.
[ "SpendingTransaction", "returns", "the", "transaction", "that", "spends", "the", "specified", "transaction", "outpoint", "if", "it", "is", "spent", ".", "The", "spending", "transaction", "hash", "input", "index", "tx", "tree", "and", "an", "error", "value", "are", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1238-L1244
train
decred/dcrdata
db/dcrpg/pgblockchain.go
BlockTransactions
func (pgb *ChainDB) BlockTransactions(blockHash string) ([]string, []uint32, []int8, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, blockTransactions, blockInds, trees, _, err := RetrieveTxsByBlockHash(ctx, pgb.db, blockHash) return blockTransactions, blockInds, trees, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) BlockTransactions(blockHash string) ([]string, []uint32, []int8, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, blockTransactions, blockInds, trees, _, err := RetrieveTxsByBlockHash(ctx, pgb.db, blockHash) return blockTransactions, blockInds, trees, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "BlockTransactions", "(", "blockHash", "string", ")", "(", "[", "]", "string", ",", "[", "]", "uint32", ",", "[", "]", "int8", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "_", ",", "blockTransactions", ",", "blockInds", ",", "trees", ",", "_", ",", "err", ":=", "RetrieveTxsByBlockHash", "(", "ctx", ",", "pgb", ".", "db", ",", "blockHash", ")", "\n", "return", "blockTransactions", ",", "blockInds", ",", "trees", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// BlockTransactions retrieves all transactions in the specified block, their // indexes in the block, their tree, and an error value.
[ "BlockTransactions", "retrieves", "all", "transactions", "in", "the", "specified", "block", "their", "indexes", "in", "the", "block", "their", "tree", "and", "an", "error", "value", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1248-L1253
train
decred/dcrdata
db/dcrpg/pgblockchain.go
Transaction
func (pgb *ChainDB) Transaction(txHash string) ([]*dbtypes.Tx, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, dbTxs, err := RetrieveDbTxsByHash(ctx, pgb.db, txHash) return dbTxs, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) Transaction(txHash string) ([]*dbtypes.Tx, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, dbTxs, err := RetrieveDbTxsByHash(ctx, pgb.db, txHash) return dbTxs, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "Transaction", "(", "txHash", "string", ")", "(", "[", "]", "*", "dbtypes", ".", "Tx", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "_", ",", "dbTxs", ",", "err", ":=", "RetrieveDbTxsByHash", "(", "ctx", ",", "pgb", ".", "db", ",", "txHash", ")", "\n", "return", "dbTxs", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// Transaction retrieves all rows from the transactions table for the given // transaction hash.
[ "Transaction", "retrieves", "all", "rows", "from", "the", "transactions", "table", "for", "the", "given", "transaction", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1257-L1262
train
decred/dcrdata
db/dcrpg/pgblockchain.go
BlockMissedVotes
func (pgb *ChainDB) BlockMissedVotes(blockHash string) ([]string, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() mv, err := RetrieveMissedVotesInBlock(ctx, pgb.db, blockHash) return mv, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) BlockMissedVotes(blockHash string) ([]string, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() mv, err := RetrieveMissedVotesInBlock(ctx, pgb.db, blockHash) return mv, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "BlockMissedVotes", "(", "blockHash", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "mv", ",", "err", ":=", "RetrieveMissedVotesInBlock", "(", "ctx", ",", "pgb", ".", "db", ",", "blockHash", ")", "\n", "return", "mv", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// BlockMissedVotes retrieves the ticket IDs for all missed votes in the // specified block, and an error value.
[ "BlockMissedVotes", "retrieves", "the", "ticket", "IDs", "for", "all", "missed", "votes", "in", "the", "specified", "block", "and", "an", "error", "value", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1266-L1271
train
decred/dcrdata
db/dcrpg/pgblockchain.go
PoolStatusForTicket
func (pgb *ChainDB) PoolStatusForTicket(txid string) (dbtypes.TicketSpendType, dbtypes.TicketPoolStatus, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, spendType, poolStatus, err := RetrieveTicketStatusByHash(ctx, pgb.db, txid) return spendType, poolStatus, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) PoolStatusForTicket(txid string) (dbtypes.TicketSpendType, dbtypes.TicketPoolStatus, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, spendType, poolStatus, err := RetrieveTicketStatusByHash(ctx, pgb.db, txid) return spendType, poolStatus, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "PoolStatusForTicket", "(", "txid", "string", ")", "(", "dbtypes", ".", "TicketSpendType", ",", "dbtypes", ".", "TicketPoolStatus", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "_", ",", "spendType", ",", "poolStatus", ",", "err", ":=", "RetrieveTicketStatusByHash", "(", "ctx", ",", "pgb", ".", "db", ",", "txid", ")", "\n", "return", "spendType", ",", "poolStatus", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// PoolStatusForTicket retrieves the specified ticket's spend status and ticket // pool status, and an error value.
[ "PoolStatusForTicket", "retrieves", "the", "specified", "ticket", "s", "spend", "status", "and", "ticket", "pool", "status", "and", "an", "error", "value", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1296-L1301
train
decred/dcrdata
db/dcrpg/pgblockchain.go
VoutValue
func (pgb *ChainDB) VoutValue(txID string, vout uint32) (uint64, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() voutValue, err := RetrieveVoutValue(ctx, pgb.db, txID, vout) if err != nil { return 0, pgb.replaceCancelError(err) } return voutValue, nil }
go
func (pgb *ChainDB) VoutValue(txID string, vout uint32) (uint64, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() voutValue, err := RetrieveVoutValue(ctx, pgb.db, txID, vout) if err != nil { return 0, pgb.replaceCancelError(err) } return voutValue, nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "VoutValue", "(", "txID", "string", ",", "vout", "uint32", ")", "(", "uint64", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "voutValue", ",", "err", ":=", "RetrieveVoutValue", "(", "ctx", ",", "pgb", ".", "db", ",", "txID", ",", "vout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}", "\n", "return", "voutValue", ",", "nil", "\n", "}" ]
// VoutValue retrieves the value of the specified transaction outpoint in atoms.
[ "VoutValue", "retrieves", "the", "value", "of", "the", "specified", "transaction", "outpoint", "in", "atoms", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1304-L1312
train
decred/dcrdata
db/dcrpg/pgblockchain.go
VoutValues
func (pgb *ChainDB) VoutValues(txID string) ([]uint64, []uint32, []int8, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() voutValues, txInds, txTrees, err := RetrieveVoutValues(ctx, pgb.db, txID) if err != nil { return nil, nil, nil, pgb.replaceCancelError(err) } return voutValues, txInds, txTrees, nil }
go
func (pgb *ChainDB) VoutValues(txID string) ([]uint64, []uint32, []int8, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() voutValues, txInds, txTrees, err := RetrieveVoutValues(ctx, pgb.db, txID) if err != nil { return nil, nil, nil, pgb.replaceCancelError(err) } return voutValues, txInds, txTrees, nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "VoutValues", "(", "txID", "string", ")", "(", "[", "]", "uint64", ",", "[", "]", "uint32", ",", "[", "]", "int8", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "voutValues", ",", "txInds", ",", "txTrees", ",", "err", ":=", "RetrieveVoutValues", "(", "ctx", ",", "pgb", ".", "db", ",", "txID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}", "\n", "return", "voutValues", ",", "txInds", ",", "txTrees", ",", "nil", "\n", "}" ]
// VoutValues retrieves the values of each outpoint of the specified // transaction. The corresponding indexes in the block and tx trees of the // outpoints, and an error value are also returned.
[ "VoutValues", "retrieves", "the", "values", "of", "each", "outpoint", "of", "the", "specified", "transaction", ".", "The", "corresponding", "indexes", "in", "the", "block", "and", "tx", "trees", "of", "the", "outpoints", "and", "an", "error", "value", "are", "also", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1317-L1325
train
decred/dcrdata
db/dcrpg/pgblockchain.go
TransactionBlock
func (pgb *ChainDB) TransactionBlock(txID string) (string, uint32, int8, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, blockHash, blockInd, tree, err := RetrieveTxByHash(ctx, pgb.db, txID) return blockHash, blockInd, tree, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) TransactionBlock(txID string) (string, uint32, int8, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, blockHash, blockInd, tree, err := RetrieveTxByHash(ctx, pgb.db, txID) return blockHash, blockInd, tree, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "TransactionBlock", "(", "txID", "string", ")", "(", "string", ",", "uint32", ",", "int8", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "_", ",", "blockHash", ",", "blockInd", ",", "tree", ",", "err", ":=", "RetrieveTxByHash", "(", "ctx", ",", "pgb", ".", "db", ",", "txID", ")", "\n", "return", "blockHash", ",", "blockInd", ",", "tree", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// TransactionBlock retrieves the hash of the block containing the specified // transaction. The index of the transaction within the block, the transaction // index, and an error value are also returned.
[ "TransactionBlock", "retrieves", "the", "hash", "of", "the", "block", "containing", "the", "specified", "transaction", ".", "The", "index", "of", "the", "transaction", "within", "the", "block", "the", "transaction", "index", "and", "an", "error", "value", "are", "also", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1330-L1335
train
decred/dcrdata
db/dcrpg/pgblockchain.go
AgendaVotes
func (pgb *ChainDB) AgendaVotes(agendaID string, chartType int) (*dbtypes.AgendaVoteChoices, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() chainInfo := pgb.ChainInfo() agendaInfo := chainInfo.AgendaMileStones[agendaID] // check if starttime is in the future exit. if time.Now().Before(agendaInfo.StartTime) { return nil, nil } avc, err := retrieveAgendaVoteChoices(ctx, pgb.db, agendaID, chartType, agendaInfo.VotingStarted, agendaInfo.VotingDone) return avc, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) AgendaVotes(agendaID string, chartType int) (*dbtypes.AgendaVoteChoices, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() chainInfo := pgb.ChainInfo() agendaInfo := chainInfo.AgendaMileStones[agendaID] // check if starttime is in the future exit. if time.Now().Before(agendaInfo.StartTime) { return nil, nil } avc, err := retrieveAgendaVoteChoices(ctx, pgb.db, agendaID, chartType, agendaInfo.VotingStarted, agendaInfo.VotingDone) return avc, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "AgendaVotes", "(", "agendaID", "string", ",", "chartType", "int", ")", "(", "*", "dbtypes", ".", "AgendaVoteChoices", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "chainInfo", ":=", "pgb", ".", "ChainInfo", "(", ")", "\n", "agendaInfo", ":=", "chainInfo", ".", "AgendaMileStones", "[", "agendaID", "]", "\n\n", "// check if starttime is in the future exit.", "if", "time", ".", "Now", "(", ")", ".", "Before", "(", "agendaInfo", ".", "StartTime", ")", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "avc", ",", "err", ":=", "retrieveAgendaVoteChoices", "(", "ctx", ",", "pgb", ".", "db", ",", "agendaID", ",", "chartType", ",", "agendaInfo", ".", "VotingStarted", ",", "agendaInfo", ".", "VotingDone", ")", "\n", "return", "avc", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// AgendaVotes fetches the data used to plot a graph of votes cast per day per // choice for the provided agenda.
[ "AgendaVotes", "fetches", "the", "data", "used", "to", "plot", "a", "graph", "of", "votes", "cast", "per", "day", "per", "choice", "for", "the", "provided", "agenda", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1339-L1354
train
decred/dcrdata
db/dcrpg/pgblockchain.go
AgendasVotesSummary
func (pgb *ChainDB) AgendasVotesSummary(agendaID string) (summary *dbtypes.AgendaSummary, err error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() chainInfo := pgb.ChainInfo() agendaInfo := chainInfo.AgendaMileStones[agendaID] // Check if starttime is in the future and exit if true. if time.Now().Before(agendaInfo.StartTime) { return } summary = &dbtypes.AgendaSummary{ VotingStarted: agendaInfo.VotingStarted, LockedIn: agendaInfo.VotingDone, } summary.Yes, summary.Abstain, summary.No, err = retrieveTotalAgendaVotesCount(ctx, pgb.db, agendaID, agendaInfo.VotingStarted, agendaInfo.VotingDone) return }
go
func (pgb *ChainDB) AgendasVotesSummary(agendaID string) (summary *dbtypes.AgendaSummary, err error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() chainInfo := pgb.ChainInfo() agendaInfo := chainInfo.AgendaMileStones[agendaID] // Check if starttime is in the future and exit if true. if time.Now().Before(agendaInfo.StartTime) { return } summary = &dbtypes.AgendaSummary{ VotingStarted: agendaInfo.VotingStarted, LockedIn: agendaInfo.VotingDone, } summary.Yes, summary.Abstain, summary.No, err = retrieveTotalAgendaVotesCount(ctx, pgb.db, agendaID, agendaInfo.VotingStarted, agendaInfo.VotingDone) return }
[ "func", "(", "pgb", "*", "ChainDB", ")", "AgendasVotesSummary", "(", "agendaID", "string", ")", "(", "summary", "*", "dbtypes", ".", "AgendaSummary", ",", "err", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "chainInfo", ":=", "pgb", ".", "ChainInfo", "(", ")", "\n", "agendaInfo", ":=", "chainInfo", ".", "AgendaMileStones", "[", "agendaID", "]", "\n\n", "// Check if starttime is in the future and exit if true.", "if", "time", ".", "Now", "(", ")", ".", "Before", "(", "agendaInfo", ".", "StartTime", ")", "{", "return", "\n", "}", "\n\n", "summary", "=", "&", "dbtypes", ".", "AgendaSummary", "{", "VotingStarted", ":", "agendaInfo", ".", "VotingStarted", ",", "LockedIn", ":", "agendaInfo", ".", "VotingDone", ",", "}", "\n\n", "summary", ".", "Yes", ",", "summary", ".", "Abstain", ",", "summary", ".", "No", ",", "err", "=", "retrieveTotalAgendaVotesCount", "(", "ctx", ",", "pgb", ".", "db", ",", "agendaID", ",", "agendaInfo", ".", "VotingStarted", ",", "agendaInfo", ".", "VotingDone", ")", "\n", "return", "\n", "}" ]
// AgendasVotesSummary fetches the total vote choices count for the provided agenda.
[ "AgendasVotesSummary", "fetches", "the", "total", "vote", "choices", "count", "for", "the", "provided", "agenda", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1357-L1377
train
decred/dcrdata
db/dcrpg/pgblockchain.go
AgendaVoteCounts
func (pgb *ChainDB) AgendaVoteCounts(agendaID string) (yes, abstain, no uint32, err error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() chainInfo := pgb.ChainInfo() agendaInfo := chainInfo.AgendaMileStones[agendaID] // Check if starttime is in the future and exit if true. if time.Now().Before(agendaInfo.StartTime) { return } return retrieveTotalAgendaVotesCount(ctx, pgb.db, agendaID, agendaInfo.VotingStarted, agendaInfo.VotingDone) }
go
func (pgb *ChainDB) AgendaVoteCounts(agendaID string) (yes, abstain, no uint32, err error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() chainInfo := pgb.ChainInfo() agendaInfo := chainInfo.AgendaMileStones[agendaID] // Check if starttime is in the future and exit if true. if time.Now().Before(agendaInfo.StartTime) { return } return retrieveTotalAgendaVotesCount(ctx, pgb.db, agendaID, agendaInfo.VotingStarted, agendaInfo.VotingDone) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "AgendaVoteCounts", "(", "agendaID", "string", ")", "(", "yes", ",", "abstain", ",", "no", "uint32", ",", "err", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "chainInfo", ":=", "pgb", ".", "ChainInfo", "(", ")", "\n", "agendaInfo", ":=", "chainInfo", ".", "AgendaMileStones", "[", "agendaID", "]", "\n\n", "// Check if starttime is in the future and exit if true.", "if", "time", ".", "Now", "(", ")", ".", "Before", "(", "agendaInfo", ".", "StartTime", ")", "{", "return", "\n", "}", "\n\n", "return", "retrieveTotalAgendaVotesCount", "(", "ctx", ",", "pgb", ".", "db", ",", "agendaID", ",", "agendaInfo", ".", "VotingStarted", ",", "agendaInfo", ".", "VotingDone", ")", "\n", "}" ]
// AgendaVoteCounts returns the vote counts for the agenda as builtin types.
[ "AgendaVoteCounts", "returns", "the", "vote", "counts", "for", "the", "agenda", "as", "builtin", "types", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1380-L1394
train
decred/dcrdata
db/dcrpg/pgblockchain.go
AllAgendas
func (pgb *ChainDB) AllAgendas() (map[string]dbtypes.MileStone, error) { return retrieveAllAgendas(pgb.db) }
go
func (pgb *ChainDB) AllAgendas() (map[string]dbtypes.MileStone, error) { return retrieveAllAgendas(pgb.db) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "AllAgendas", "(", ")", "(", "map", "[", "string", "]", "dbtypes", ".", "MileStone", ",", "error", ")", "{", "return", "retrieveAllAgendas", "(", "pgb", ".", "db", ")", "\n", "}" ]
// AllAgendas returns all the agendas stored currently.
[ "AllAgendas", "returns", "all", "the", "agendas", "stored", "currently", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1397-L1399
train
decred/dcrdata
db/dcrpg/pgblockchain.go
NumAddressIntervals
func (pgb *ChainDB) NumAddressIntervals(addr string, grouping dbtypes.TimeBasedGrouping) (int64, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() return retrieveAddressTxsCount(ctx, pgb.db, addr, grouping.String()) }
go
func (pgb *ChainDB) NumAddressIntervals(addr string, grouping dbtypes.TimeBasedGrouping) (int64, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() return retrieveAddressTxsCount(ctx, pgb.db, addr, grouping.String()) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "NumAddressIntervals", "(", "addr", "string", ",", "grouping", "dbtypes", ".", "TimeBasedGrouping", ")", "(", "int64", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "return", "retrieveAddressTxsCount", "(", "ctx", ",", "pgb", ".", "db", ",", "addr", ",", "grouping", ".", "String", "(", ")", ")", "\n", "}" ]
// NumAddressIntervals gets the number of unique time intervals for the // specified grouping where there are entries in the addresses table for the // given address.
[ "NumAddressIntervals", "gets", "the", "number", "of", "unique", "time", "intervals", "for", "the", "specified", "grouping", "where", "there", "are", "entries", "in", "the", "addresses", "table", "for", "the", "given", "address", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1404-L1408
train
decred/dcrdata
db/dcrpg/pgblockchain.go
AddressMetrics
func (pgb *ChainDB) AddressMetrics(addr string) (*dbtypes.AddressMetrics, error) { // For each time grouping/interval size, get the number if intervals with // data for the address. var metrics dbtypes.AddressMetrics for _, s := range dbtypes.TimeIntervals { numIntervals, err := pgb.NumAddressIntervals(addr, s) if err != nil { return nil, fmt.Errorf("retrieveAddressAllTxsCount failed: error: %v", err) } switch s { case dbtypes.YearGrouping: metrics.YearTxsCount = numIntervals case dbtypes.MonthGrouping: metrics.MonthTxsCount = numIntervals case dbtypes.WeekGrouping: metrics.WeekTxsCount = numIntervals case dbtypes.DayGrouping: metrics.DayTxsCount = numIntervals } } // Get the time of the block with the first transaction involving the // address (oldest transaction block time). ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() blockTime, err := retrieveOldestTxBlockTime(ctx, pgb.db, addr) if err != nil { return nil, fmt.Errorf("retrieveOldestTxBlockTime failed: error: %v", err) } metrics.OldestBlockTime = blockTime return &metrics, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) AddressMetrics(addr string) (*dbtypes.AddressMetrics, error) { // For each time grouping/interval size, get the number if intervals with // data for the address. var metrics dbtypes.AddressMetrics for _, s := range dbtypes.TimeIntervals { numIntervals, err := pgb.NumAddressIntervals(addr, s) if err != nil { return nil, fmt.Errorf("retrieveAddressAllTxsCount failed: error: %v", err) } switch s { case dbtypes.YearGrouping: metrics.YearTxsCount = numIntervals case dbtypes.MonthGrouping: metrics.MonthTxsCount = numIntervals case dbtypes.WeekGrouping: metrics.WeekTxsCount = numIntervals case dbtypes.DayGrouping: metrics.DayTxsCount = numIntervals } } // Get the time of the block with the first transaction involving the // address (oldest transaction block time). ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() blockTime, err := retrieveOldestTxBlockTime(ctx, pgb.db, addr) if err != nil { return nil, fmt.Errorf("retrieveOldestTxBlockTime failed: error: %v", err) } metrics.OldestBlockTime = blockTime return &metrics, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "AddressMetrics", "(", "addr", "string", ")", "(", "*", "dbtypes", ".", "AddressMetrics", ",", "error", ")", "{", "// For each time grouping/interval size, get the number if intervals with", "// data for the address.", "var", "metrics", "dbtypes", ".", "AddressMetrics", "\n", "for", "_", ",", "s", ":=", "range", "dbtypes", ".", "TimeIntervals", "{", "numIntervals", ",", "err", ":=", "pgb", ".", "NumAddressIntervals", "(", "addr", ",", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "switch", "s", "{", "case", "dbtypes", ".", "YearGrouping", ":", "metrics", ".", "YearTxsCount", "=", "numIntervals", "\n", "case", "dbtypes", ".", "MonthGrouping", ":", "metrics", ".", "MonthTxsCount", "=", "numIntervals", "\n", "case", "dbtypes", ".", "WeekGrouping", ":", "metrics", ".", "WeekTxsCount", "=", "numIntervals", "\n", "case", "dbtypes", ".", "DayGrouping", ":", "metrics", ".", "DayTxsCount", "=", "numIntervals", "\n", "}", "\n", "}", "\n\n", "// Get the time of the block with the first transaction involving the", "// address (oldest transaction block time).", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "blockTime", ",", "err", ":=", "retrieveOldestTxBlockTime", "(", "ctx", ",", "pgb", ".", "db", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "metrics", ".", "OldestBlockTime", "=", "blockTime", "\n\n", "return", "&", "metrics", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// AddressMetrics returns the block time of the oldest transaction and the // total count for all the transactions linked to the provided address grouped // by years, months, weeks and days time grouping in seconds. // This helps plot more meaningful address history graphs to the user.
[ "AddressMetrics", "returns", "the", "block", "time", "of", "the", "oldest", "transaction", "and", "the", "total", "count", "for", "all", "the", "transactions", "linked", "to", "the", "provided", "address", "grouped", "by", "years", "months", "weeks", "and", "days", "time", "grouping", "in", "seconds", ".", "This", "helps", "plot", "more", "meaningful", "address", "history", "graphs", "to", "the", "user", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1414-L1447
train
decred/dcrdata
db/dcrpg/pgblockchain.go
AddressTransactionsAll
func (pgb *ChainDB) AddressTransactionsAll(address string) (addressRows []*dbtypes.AddressRow, err error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() addressRows, err = RetrieveAllMainchainAddressTxns(ctx, pgb.db, address) err = pgb.replaceCancelError(err) return }
go
func (pgb *ChainDB) AddressTransactionsAll(address string) (addressRows []*dbtypes.AddressRow, err error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() addressRows, err = RetrieveAllMainchainAddressTxns(ctx, pgb.db, address) err = pgb.replaceCancelError(err) return }
[ "func", "(", "pgb", "*", "ChainDB", ")", "AddressTransactionsAll", "(", "address", "string", ")", "(", "addressRows", "[", "]", "*", "dbtypes", ".", "AddressRow", ",", "err", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "addressRows", ",", "err", "=", "RetrieveAllMainchainAddressTxns", "(", "ctx", ",", "pgb", ".", "db", ",", "address", ")", "\n", "err", "=", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "return", "\n", "}" ]
// AddressTransactionsAll retrieves all non-merged main chain addresses table // rows for the given address.
[ "AddressTransactionsAll", "retrieves", "all", "non", "-", "merged", "main", "chain", "addresses", "table", "rows", "for", "the", "given", "address", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1483-L1490
train
decred/dcrdata
db/dcrpg/pgblockchain.go
AddressHistoryAll
func (pgb *ChainDB) AddressHistoryAll(address string, N, offset int64) ([]*dbtypes.AddressRow, *dbtypes.AddressBalance, error) { return pgb.AddressHistory(address, N, offset, dbtypes.AddrTxnAll) }
go
func (pgb *ChainDB) AddressHistoryAll(address string, N, offset int64) ([]*dbtypes.AddressRow, *dbtypes.AddressBalance, error) { return pgb.AddressHistory(address, N, offset, dbtypes.AddrTxnAll) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "AddressHistoryAll", "(", "address", "string", ",", "N", ",", "offset", "int64", ")", "(", "[", "]", "*", "dbtypes", ".", "AddressRow", ",", "*", "dbtypes", ".", "AddressBalance", ",", "error", ")", "{", "return", "pgb", ".", "AddressHistory", "(", "address", ",", "N", ",", "offset", ",", "dbtypes", ".", "AddrTxnAll", ")", "\n", "}" ]
// AddressHistoryAll retrieves N address rows of type AddrTxnAll, skipping over // offset rows first, in order of block time.
[ "AddressHistoryAll", "retrieves", "N", "address", "rows", "of", "type", "AddrTxnAll", "skipping", "over", "offset", "rows", "first", "in", "order", "of", "block", "time", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1507-L1509
train
decred/dcrdata
db/dcrpg/pgblockchain.go
TicketPoolBlockMaturity
func (pgb *ChainDB) TicketPoolBlockMaturity() int64 { bestBlock := int64(pgb.stakeDB.Height()) return bestBlock - int64(pgb.chainParams.TicketMaturity) }
go
func (pgb *ChainDB) TicketPoolBlockMaturity() int64 { bestBlock := int64(pgb.stakeDB.Height()) return bestBlock - int64(pgb.chainParams.TicketMaturity) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "TicketPoolBlockMaturity", "(", ")", "int64", "{", "bestBlock", ":=", "int64", "(", "pgb", ".", "stakeDB", ".", "Height", "(", ")", ")", "\n", "return", "bestBlock", "-", "int64", "(", "pgb", ".", "chainParams", ".", "TicketMaturity", ")", "\n", "}" ]
// TicketPoolBlockMaturity returns the block at which all tickets with height // greater than it are immature.
[ "TicketPoolBlockMaturity", "returns", "the", "block", "at", "which", "all", "tickets", "with", "height", "greater", "than", "it", "are", "immature", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1513-L1516
train
decred/dcrdata
db/dcrpg/pgblockchain.go
TicketPoolByDateAndInterval
func (pgb *ChainDB) TicketPoolByDateAndInterval(maturityBlock int64, interval dbtypes.TimeBasedGrouping) (*dbtypes.PoolTicketsData, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() tpd, err := retrieveTicketsByDate(ctx, pgb.db, maturityBlock, interval.String()) return tpd, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) TicketPoolByDateAndInterval(maturityBlock int64, interval dbtypes.TimeBasedGrouping) (*dbtypes.PoolTicketsData, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() tpd, err := retrieveTicketsByDate(ctx, pgb.db, maturityBlock, interval.String()) return tpd, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "TicketPoolByDateAndInterval", "(", "maturityBlock", "int64", ",", "interval", "dbtypes", ".", "TimeBasedGrouping", ")", "(", "*", "dbtypes", ".", "PoolTicketsData", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "tpd", ",", "err", ":=", "retrieveTicketsByDate", "(", "ctx", ",", "pgb", ".", "db", ",", "maturityBlock", ",", "interval", ".", "String", "(", ")", ")", "\n", "return", "tpd", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// TicketPoolByDateAndInterval fetches the tickets ordered by the purchase date // interval provided and an error value.
[ "TicketPoolByDateAndInterval", "fetches", "the", "tickets", "ordered", "by", "the", "purchase", "date", "interval", "provided", "and", "an", "error", "value", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1520-L1526
train
decred/dcrdata
db/dcrpg/pgblockchain.go
PosIntervals
func (pgb *ChainDB) PosIntervals(limit, offset uint64) ([]*dbtypes.BlocksGroupedInfo, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() bgi, err := retrieveWindowBlocks(ctx, pgb.db, pgb.chainParams.StakeDiffWindowSize, limit, offset) return bgi, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) PosIntervals(limit, offset uint64) ([]*dbtypes.BlocksGroupedInfo, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() bgi, err := retrieveWindowBlocks(ctx, pgb.db, pgb.chainParams.StakeDiffWindowSize, limit, offset) return bgi, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "PosIntervals", "(", "limit", ",", "offset", "uint64", ")", "(", "[", "]", "*", "dbtypes", ".", "BlocksGroupedInfo", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "bgi", ",", "err", ":=", "retrieveWindowBlocks", "(", "ctx", ",", "pgb", ".", "db", ",", "pgb", ".", "chainParams", ".", "StakeDiffWindowSize", ",", "limit", ",", "offset", ")", "\n", "return", "bgi", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// PosIntervals retrieves the blocks at the respective stakebase windows // interval. The term "window" is used here to describe the group of blocks // whose count is defined by chainParams.StakeDiffWindowSize. During this // chainParams.StakeDiffWindowSize block interval the ticket price and the // difficulty value is constant.
[ "PosIntervals", "retrieves", "the", "blocks", "at", "the", "respective", "stakebase", "windows", "interval", ".", "The", "term", "window", "is", "used", "here", "to", "describe", "the", "group", "of", "blocks", "whose", "count", "is", "defined", "by", "chainParams", ".", "StakeDiffWindowSize", ".", "During", "this", "chainParams", ".", "StakeDiffWindowSize", "block", "interval", "the", "ticket", "price", "and", "the", "difficulty", "value", "is", "constant", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1533-L1538
train
decred/dcrdata
db/dcrpg/pgblockchain.go
TimeBasedIntervals
func (pgb *ChainDB) TimeBasedIntervals(timeGrouping dbtypes.TimeBasedGrouping, limit, offset uint64) ([]*dbtypes.BlocksGroupedInfo, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() bgi, err := retrieveTimeBasedBlockListing(ctx, pgb.db, timeGrouping.String(), limit, offset) return bgi, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) TimeBasedIntervals(timeGrouping dbtypes.TimeBasedGrouping, limit, offset uint64) ([]*dbtypes.BlocksGroupedInfo, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() bgi, err := retrieveTimeBasedBlockListing(ctx, pgb.db, timeGrouping.String(), limit, offset) return bgi, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "TimeBasedIntervals", "(", "timeGrouping", "dbtypes", ".", "TimeBasedGrouping", ",", "limit", ",", "offset", "uint64", ")", "(", "[", "]", "*", "dbtypes", ".", "BlocksGroupedInfo", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "bgi", ",", "err", ":=", "retrieveTimeBasedBlockListing", "(", "ctx", ",", "pgb", ".", "db", ",", "timeGrouping", ".", "String", "(", ")", ",", "limit", ",", "offset", ")", "\n", "return", "bgi", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// TimeBasedIntervals retrieves blocks groups by the selected time-based // interval. For the consecutive groups the number of blocks grouped together is // not uniform.
[ "TimeBasedIntervals", "retrieves", "blocks", "groups", "by", "the", "selected", "time", "-", "based", "interval", ".", "For", "the", "consecutive", "groups", "the", "number", "of", "blocks", "grouped", "together", "is", "not", "uniform", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1543-L1550
train
decred/dcrdata
db/dcrpg/pgblockchain.go
TicketPoolVisualization
func (pgb *ChainDB) TicketPoolVisualization(interval dbtypes.TimeBasedGrouping) (*dbtypes.PoolTicketsData, *dbtypes.PoolTicketsData, *dbtypes.PoolTicketsData, int64, error) { // Attempt to retrieve data for the current block from cache. heightSeen := pgb.Height() // current block seen *by the ChainDB* if heightSeen < 0 { return nil, nil, nil, -1, fmt.Errorf("no charts data available") } timeChart, priceChart, donutCharts, height, intervalFound, stale := TicketPoolData(interval, heightSeen) if intervalFound && !stale { // The cache was fresh. return timeChart, priceChart, donutCharts, height, nil } // Cache is stale or empty. Attempt to gain updater status. if !pgb.tpUpdatePermission[interval].TryLock() { // Another goroutine is running db query to get the updated data. if !intervalFound { // Do not even have stale data. Must wait for the DB update to // complete to get any data at all. Use a blocking call on the // updater lock even though we are not going to actually do an // update ourselves so we do not block the cache while waiting. pgb.tpUpdatePermission[interval].Lock() defer pgb.tpUpdatePermission[interval].Unlock() // Try again to pull it from cache now that the update is completed. heightSeen = pgb.Height() timeChart, priceChart, donutCharts, height, intervalFound, stale = TicketPoolData(interval, heightSeen) // We waited for the updater of this interval, so it should be found // at this point. If not, this is an error. if !intervalFound { log.Errorf("Charts data for interval %v failed to update.", interval) return nil, nil, nil, 0, fmt.Errorf("no charts data available") } if stale { log.Warnf("Charts data for interval %v updated, but still stale.", interval) } } // else return the stale data instead of waiting. return timeChart, priceChart, donutCharts, height, nil } // This goroutine is now the cache updater. defer pgb.tpUpdatePermission[interval].Unlock() // Retrieve chart data for best block in DB. var err error timeChart, priceChart, donutCharts, height, err = pgb.ticketPoolVisualization(interval) if err != nil { log.Errorf("Failed to fetch ticket pool data: %v", err) return nil, nil, nil, 0, err } // Update the cache with the new ticket pool data. UpdateTicketPoolData(interval, timeChart, priceChart, donutCharts, height) return timeChart, priceChart, donutCharts, height, nil }
go
func (pgb *ChainDB) TicketPoolVisualization(interval dbtypes.TimeBasedGrouping) (*dbtypes.PoolTicketsData, *dbtypes.PoolTicketsData, *dbtypes.PoolTicketsData, int64, error) { // Attempt to retrieve data for the current block from cache. heightSeen := pgb.Height() // current block seen *by the ChainDB* if heightSeen < 0 { return nil, nil, nil, -1, fmt.Errorf("no charts data available") } timeChart, priceChart, donutCharts, height, intervalFound, stale := TicketPoolData(interval, heightSeen) if intervalFound && !stale { // The cache was fresh. return timeChart, priceChart, donutCharts, height, nil } // Cache is stale or empty. Attempt to gain updater status. if !pgb.tpUpdatePermission[interval].TryLock() { // Another goroutine is running db query to get the updated data. if !intervalFound { // Do not even have stale data. Must wait for the DB update to // complete to get any data at all. Use a blocking call on the // updater lock even though we are not going to actually do an // update ourselves so we do not block the cache while waiting. pgb.tpUpdatePermission[interval].Lock() defer pgb.tpUpdatePermission[interval].Unlock() // Try again to pull it from cache now that the update is completed. heightSeen = pgb.Height() timeChart, priceChart, donutCharts, height, intervalFound, stale = TicketPoolData(interval, heightSeen) // We waited for the updater of this interval, so it should be found // at this point. If not, this is an error. if !intervalFound { log.Errorf("Charts data for interval %v failed to update.", interval) return nil, nil, nil, 0, fmt.Errorf("no charts data available") } if stale { log.Warnf("Charts data for interval %v updated, but still stale.", interval) } } // else return the stale data instead of waiting. return timeChart, priceChart, donutCharts, height, nil } // This goroutine is now the cache updater. defer pgb.tpUpdatePermission[interval].Unlock() // Retrieve chart data for best block in DB. var err error timeChart, priceChart, donutCharts, height, err = pgb.ticketPoolVisualization(interval) if err != nil { log.Errorf("Failed to fetch ticket pool data: %v", err) return nil, nil, nil, 0, err } // Update the cache with the new ticket pool data. UpdateTicketPoolData(interval, timeChart, priceChart, donutCharts, height) return timeChart, priceChart, donutCharts, height, nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "TicketPoolVisualization", "(", "interval", "dbtypes", ".", "TimeBasedGrouping", ")", "(", "*", "dbtypes", ".", "PoolTicketsData", ",", "*", "dbtypes", ".", "PoolTicketsData", ",", "*", "dbtypes", ".", "PoolTicketsData", ",", "int64", ",", "error", ")", "{", "// Attempt to retrieve data for the current block from cache.", "heightSeen", ":=", "pgb", ".", "Height", "(", ")", "// current block seen *by the ChainDB*", "\n", "if", "heightSeen", "<", "0", "{", "return", "nil", ",", "nil", ",", "nil", ",", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "timeChart", ",", "priceChart", ",", "donutCharts", ",", "height", ",", "intervalFound", ",", "stale", ":=", "TicketPoolData", "(", "interval", ",", "heightSeen", ")", "\n", "if", "intervalFound", "&&", "!", "stale", "{", "// The cache was fresh.", "return", "timeChart", ",", "priceChart", ",", "donutCharts", ",", "height", ",", "nil", "\n", "}", "\n\n", "// Cache is stale or empty. Attempt to gain updater status.", "if", "!", "pgb", ".", "tpUpdatePermission", "[", "interval", "]", ".", "TryLock", "(", ")", "{", "// Another goroutine is running db query to get the updated data.", "if", "!", "intervalFound", "{", "// Do not even have stale data. Must wait for the DB update to", "// complete to get any data at all. Use a blocking call on the", "// updater lock even though we are not going to actually do an", "// update ourselves so we do not block the cache while waiting.", "pgb", ".", "tpUpdatePermission", "[", "interval", "]", ".", "Lock", "(", ")", "\n", "defer", "pgb", ".", "tpUpdatePermission", "[", "interval", "]", ".", "Unlock", "(", ")", "\n", "// Try again to pull it from cache now that the update is completed.", "heightSeen", "=", "pgb", ".", "Height", "(", ")", "\n", "timeChart", ",", "priceChart", ",", "donutCharts", ",", "height", ",", "intervalFound", ",", "stale", "=", "TicketPoolData", "(", "interval", ",", "heightSeen", ")", "\n", "// We waited for the updater of this interval, so it should be found", "// at this point. If not, this is an error.", "if", "!", "intervalFound", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "interval", ")", "\n", "return", "nil", ",", "nil", ",", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "stale", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "interval", ")", "\n", "}", "\n", "}", "\n", "// else return the stale data instead of waiting.", "return", "timeChart", ",", "priceChart", ",", "donutCharts", ",", "height", ",", "nil", "\n", "}", "\n", "// This goroutine is now the cache updater.", "defer", "pgb", ".", "tpUpdatePermission", "[", "interval", "]", ".", "Unlock", "(", ")", "\n\n", "// Retrieve chart data for best block in DB.", "var", "err", "error", "\n", "timeChart", ",", "priceChart", ",", "donutCharts", ",", "height", ",", "err", "=", "pgb", ".", "ticketPoolVisualization", "(", "interval", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "nil", ",", "nil", ",", "0", ",", "err", "\n", "}", "\n\n", "// Update the cache with the new ticket pool data.", "UpdateTicketPoolData", "(", "interval", ",", "timeChart", ",", "priceChart", ",", "donutCharts", ",", "height", ")", "\n\n", "return", "timeChart", ",", "priceChart", ",", "donutCharts", ",", "height", ",", "nil", "\n", "}" ]
// TicketPoolVisualization helps block consecutive and duplicate DB queries for // the requested ticket pool chart data. If the data for the given interval is // cached and fresh, it is returned. If the cached data is stale and there are // no queries running to update the cache for the given interval, this launches // a query and updates the cache. If there is no cached data for the interval, // this will launch a new query for the data if one is not already running, and // if one is running, it will wait for the query to complete.
[ "TicketPoolVisualization", "helps", "block", "consecutive", "and", "duplicate", "DB", "queries", "for", "the", "requested", "ticket", "pool", "chart", "data", ".", "If", "the", "data", "for", "the", "given", "interval", "is", "cached", "and", "fresh", "it", "is", "returned", ".", "If", "the", "cached", "data", "is", "stale", "and", "there", "are", "no", "queries", "running", "to", "update", "the", "cache", "for", "the", "given", "interval", "this", "launches", "a", "query", "and", "updates", "the", "cache", ".", "If", "there", "is", "no", "cached", "data", "for", "the", "interval", "this", "will", "launch", "a", "new", "query", "for", "the", "data", "if", "one", "is", "not", "already", "running", "and", "if", "one", "is", "running", "it", "will", "wait", "for", "the", "query", "to", "complete", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1559-L1616
train
decred/dcrdata
db/dcrpg/pgblockchain.go
GetTicketInfo
func (pgb *ChainDB) GetTicketInfo(txid string) (*apitypes.TicketInfo, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() spendStatus, poolStatus, purchaseBlock, lotteryBlock, spendTxid, err := RetrieveTicketInfoByHash(ctx, pgb.db, txid) if err != nil { return nil, pgb.replaceCancelError(err) } var vote, revocation *string status := strings.ToLower(poolStatus.String()) maturity := purchaseBlock.Height + uint32(pgb.chainParams.TicketMaturity) expiration := maturity + pgb.chainParams.TicketExpiry if pgb.Height() < int64(maturity) { status = "immature" } if spendStatus == dbtypes.TicketRevoked { status = spendStatus.String() revocation = &spendTxid } else if spendStatus == dbtypes.TicketVoted { vote = &spendTxid } if poolStatus == dbtypes.PoolStatusMissed { hash, height, err := RetrieveMissForTicket(ctx, pgb.db, txid) if err != nil { return nil, pgb.replaceCancelError(err) } lotteryBlock = &apitypes.TinyBlock{ Hash: hash, Height: uint32(height), } } return &apitypes.TicketInfo{ Status: status, PurchaseBlock: purchaseBlock, MaturityHeight: maturity, ExpirationHeight: expiration, LotteryBlock: lotteryBlock, Vote: vote, Revocation: revocation, }, nil }
go
func (pgb *ChainDB) GetTicketInfo(txid string) (*apitypes.TicketInfo, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() spendStatus, poolStatus, purchaseBlock, lotteryBlock, spendTxid, err := RetrieveTicketInfoByHash(ctx, pgb.db, txid) if err != nil { return nil, pgb.replaceCancelError(err) } var vote, revocation *string status := strings.ToLower(poolStatus.String()) maturity := purchaseBlock.Height + uint32(pgb.chainParams.TicketMaturity) expiration := maturity + pgb.chainParams.TicketExpiry if pgb.Height() < int64(maturity) { status = "immature" } if spendStatus == dbtypes.TicketRevoked { status = spendStatus.String() revocation = &spendTxid } else if spendStatus == dbtypes.TicketVoted { vote = &spendTxid } if poolStatus == dbtypes.PoolStatusMissed { hash, height, err := RetrieveMissForTicket(ctx, pgb.db, txid) if err != nil { return nil, pgb.replaceCancelError(err) } lotteryBlock = &apitypes.TinyBlock{ Hash: hash, Height: uint32(height), } } return &apitypes.TicketInfo{ Status: status, PurchaseBlock: purchaseBlock, MaturityHeight: maturity, ExpirationHeight: expiration, LotteryBlock: lotteryBlock, Vote: vote, Revocation: revocation, }, nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "GetTicketInfo", "(", "txid", "string", ")", "(", "*", "apitypes", ".", "TicketInfo", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "spendStatus", ",", "poolStatus", ",", "purchaseBlock", ",", "lotteryBlock", ",", "spendTxid", ",", "err", ":=", "RetrieveTicketInfoByHash", "(", "ctx", ",", "pgb", ".", "db", ",", "txid", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}", "\n\n", "var", "vote", ",", "revocation", "*", "string", "\n", "status", ":=", "strings", ".", "ToLower", "(", "poolStatus", ".", "String", "(", ")", ")", "\n", "maturity", ":=", "purchaseBlock", ".", "Height", "+", "uint32", "(", "pgb", ".", "chainParams", ".", "TicketMaturity", ")", "\n", "expiration", ":=", "maturity", "+", "pgb", ".", "chainParams", ".", "TicketExpiry", "\n", "if", "pgb", ".", "Height", "(", ")", "<", "int64", "(", "maturity", ")", "{", "status", "=", "\"", "\"", "\n", "}", "\n", "if", "spendStatus", "==", "dbtypes", ".", "TicketRevoked", "{", "status", "=", "spendStatus", ".", "String", "(", ")", "\n", "revocation", "=", "&", "spendTxid", "\n", "}", "else", "if", "spendStatus", "==", "dbtypes", ".", "TicketVoted", "{", "vote", "=", "&", "spendTxid", "\n", "}", "\n\n", "if", "poolStatus", "==", "dbtypes", ".", "PoolStatusMissed", "{", "hash", ",", "height", ",", "err", ":=", "RetrieveMissForTicket", "(", "ctx", ",", "pgb", ".", "db", ",", "txid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}", "\n", "lotteryBlock", "=", "&", "apitypes", ".", "TinyBlock", "{", "Hash", ":", "hash", ",", "Height", ":", "uint32", "(", "height", ")", ",", "}", "\n", "}", "\n\n", "return", "&", "apitypes", ".", "TicketInfo", "{", "Status", ":", "status", ",", "PurchaseBlock", ":", "purchaseBlock", ",", "MaturityHeight", ":", "maturity", ",", "ExpirationHeight", ":", "expiration", ",", "LotteryBlock", ":", "lotteryBlock", ",", "Vote", ":", "vote", ",", "Revocation", ":", "revocation", ",", "}", ",", "nil", "\n", "}" ]
// GetTicketInfo retrieves information about the pool and spend statuses, the // purchase block, the lottery block, and the spending transaction.
[ "GetTicketInfo", "retrieves", "information", "about", "the", "pool", "and", "spend", "statuses", "the", "purchase", "block", "the", "lottery", "block", "and", "the", "spending", "transaction", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1663-L1706
train
decred/dcrdata
db/dcrpg/pgblockchain.go
FreshenAddressCaches
func (pgb *ChainDB) FreshenAddressCaches(lazyProjectFund bool, expireAddresses []string) error { // Clear existing cache entries. //numCleared := pgb.AddressCache.ClearAll() numCleared := pgb.AddressCache.Clear(expireAddresses) log.Debugf("Cleared cache for %d addresses.", numCleared) // Do not initiate project fund queries if a reorg is in progress, or // pre-fetch is disabled. if !pgb.devPrefetch || pgb.InReorg { return nil } // Update project fund data. updateFundData := func() error { log.Infof("Pre-fetching project fund data at height %d...", pgb.Height()) if err := pgb.updateProjectFundCache(); err != nil && err.Error() != "retry" { err = pgb.replaceCancelError(err) return fmt.Errorf("Failed to update project fund data: %v", err) } return nil } if lazyProjectFund { go func() { runtime.Gosched() if err := updateFundData(); err != nil { log.Error(err) } }() return nil } return updateFundData() }
go
func (pgb *ChainDB) FreshenAddressCaches(lazyProjectFund bool, expireAddresses []string) error { // Clear existing cache entries. //numCleared := pgb.AddressCache.ClearAll() numCleared := pgb.AddressCache.Clear(expireAddresses) log.Debugf("Cleared cache for %d addresses.", numCleared) // Do not initiate project fund queries if a reorg is in progress, or // pre-fetch is disabled. if !pgb.devPrefetch || pgb.InReorg { return nil } // Update project fund data. updateFundData := func() error { log.Infof("Pre-fetching project fund data at height %d...", pgb.Height()) if err := pgb.updateProjectFundCache(); err != nil && err.Error() != "retry" { err = pgb.replaceCancelError(err) return fmt.Errorf("Failed to update project fund data: %v", err) } return nil } if lazyProjectFund { go func() { runtime.Gosched() if err := updateFundData(); err != nil { log.Error(err) } }() return nil } return updateFundData() }
[ "func", "(", "pgb", "*", "ChainDB", ")", "FreshenAddressCaches", "(", "lazyProjectFund", "bool", ",", "expireAddresses", "[", "]", "string", ")", "error", "{", "// Clear existing cache entries.", "//numCleared := pgb.AddressCache.ClearAll()", "numCleared", ":=", "pgb", ".", "AddressCache", ".", "Clear", "(", "expireAddresses", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "numCleared", ")", "\n\n", "// Do not initiate project fund queries if a reorg is in progress, or", "// pre-fetch is disabled.", "if", "!", "pgb", ".", "devPrefetch", "||", "pgb", ".", "InReorg", "{", "return", "nil", "\n", "}", "\n\n", "// Update project fund data.", "updateFundData", ":=", "func", "(", ")", "error", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "pgb", ".", "Height", "(", ")", ")", "\n", "if", "err", ":=", "pgb", ".", "updateProjectFundCache", "(", ")", ";", "err", "!=", "nil", "&&", "err", ".", "Error", "(", ")", "!=", "\"", "\"", "{", "err", "=", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "if", "lazyProjectFund", "{", "go", "func", "(", ")", "{", "runtime", ".", "Gosched", "(", ")", "\n", "if", "err", ":=", "updateFundData", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Error", "(", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "updateFundData", "(", ")", "\n", "}" ]
// FreshenAddressCaches resets the address balance cache by purging data for the // addresses listed in expireAddresses, and prefetches the project fund balance // if devPrefetch is enabled and not mid-reorg. The project fund update is run // asynchronously if lazyProjectFund is true.
[ "FreshenAddressCaches", "resets", "the", "address", "balance", "cache", "by", "purging", "data", "for", "the", "addresses", "listed", "in", "expireAddresses", "and", "prefetches", "the", "project", "fund", "balance", "if", "devPrefetch", "is", "enabled", "and", "not", "mid", "-", "reorg", ".", "The", "project", "fund", "update", "is", "run", "asynchronously", "if", "lazyProjectFund", "is", "true", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1725-L1757
train
decred/dcrdata
db/dcrpg/pgblockchain.go
AddressBalance
func (pgb *ChainDB) AddressBalance(address string) (bal *dbtypes.AddressBalance, cacheUpdated bool, err error) { // Check the cache first. bestHash, height := pgb.BestBlock() var validHeight *cache.BlockID bal, validHeight = pgb.AddressCache.Balance(address) if bal != nil && *bestHash == validHeight.Hash { return } busy, wait, done := pgb.CacheLocks.bal.TryLock(address) if busy { // Let others get the wait channel while we wait. // To return stale cache data if it is available: // utxos, _ := pgb.AddressCache.UTXOs(address) // if utxos != nil { // return utxos, nil // } <-wait // Try again, starting with the cache. return pgb.AddressBalance(address) } // We will run the DB query, so block others from doing the same. When query // and/or cache update is completed, broadcast to any waiters that the coast // is clear. defer done() // Cache is empty or stale, so query the DB. ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() bal, err = RetrieveAddressBalance(ctx, pgb.db, address) if err != nil { err = pgb.replaceCancelError(err) return } // Update the address cache. cacheUpdated = pgb.AddressCache.StoreBalance(address, bal, cache.NewBlockID(bestHash, height)) return }
go
func (pgb *ChainDB) AddressBalance(address string) (bal *dbtypes.AddressBalance, cacheUpdated bool, err error) { // Check the cache first. bestHash, height := pgb.BestBlock() var validHeight *cache.BlockID bal, validHeight = pgb.AddressCache.Balance(address) if bal != nil && *bestHash == validHeight.Hash { return } busy, wait, done := pgb.CacheLocks.bal.TryLock(address) if busy { // Let others get the wait channel while we wait. // To return stale cache data if it is available: // utxos, _ := pgb.AddressCache.UTXOs(address) // if utxos != nil { // return utxos, nil // } <-wait // Try again, starting with the cache. return pgb.AddressBalance(address) } // We will run the DB query, so block others from doing the same. When query // and/or cache update is completed, broadcast to any waiters that the coast // is clear. defer done() // Cache is empty or stale, so query the DB. ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() bal, err = RetrieveAddressBalance(ctx, pgb.db, address) if err != nil { err = pgb.replaceCancelError(err) return } // Update the address cache. cacheUpdated = pgb.AddressCache.StoreBalance(address, bal, cache.NewBlockID(bestHash, height)) return }
[ "func", "(", "pgb", "*", "ChainDB", ")", "AddressBalance", "(", "address", "string", ")", "(", "bal", "*", "dbtypes", ".", "AddressBalance", ",", "cacheUpdated", "bool", ",", "err", "error", ")", "{", "// Check the cache first.", "bestHash", ",", "height", ":=", "pgb", ".", "BestBlock", "(", ")", "\n", "var", "validHeight", "*", "cache", ".", "BlockID", "\n", "bal", ",", "validHeight", "=", "pgb", ".", "AddressCache", ".", "Balance", "(", "address", ")", "\n", "if", "bal", "!=", "nil", "&&", "*", "bestHash", "==", "validHeight", ".", "Hash", "{", "return", "\n", "}", "\n\n", "busy", ",", "wait", ",", "done", ":=", "pgb", ".", "CacheLocks", ".", "bal", ".", "TryLock", "(", "address", ")", "\n", "if", "busy", "{", "// Let others get the wait channel while we wait.", "// To return stale cache data if it is available:", "// utxos, _ := pgb.AddressCache.UTXOs(address)", "// if utxos != nil {", "// \treturn utxos, nil", "// }", "<-", "wait", "\n\n", "// Try again, starting with the cache.", "return", "pgb", ".", "AddressBalance", "(", "address", ")", "\n", "}", "\n\n", "// We will run the DB query, so block others from doing the same. When query", "// and/or cache update is completed, broadcast to any waiters that the coast", "// is clear.", "defer", "done", "(", ")", "\n\n", "// Cache is empty or stale, so query the DB.", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "bal", ",", "err", "=", "RetrieveAddressBalance", "(", "ctx", ",", "pgb", ".", "db", ",", "address", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "return", "\n", "}", "\n\n", "// Update the address cache.", "cacheUpdated", "=", "pgb", ".", "AddressCache", ".", "StoreBalance", "(", "address", ",", "bal", ",", "cache", ".", "NewBlockID", "(", "bestHash", ",", "height", ")", ")", "\n", "return", "\n", "}" ]
// AddressBalance attempts to retrieve balance information for a specific // address from cache, and if cache is stale or missing data for the address, a // DB query is used. A successful DB query will freshen the cache.
[ "AddressBalance", "attempts", "to", "retrieve", "balance", "information", "for", "a", "specific", "address", "from", "cache", "and", "if", "cache", "is", "stale", "or", "missing", "data", "for", "the", "address", "a", "DB", "query", "is", "used", ".", "A", "successful", "DB", "query", "will", "freshen", "the", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1789-L1830
train
decred/dcrdata
db/dcrpg/pgblockchain.go
updateAddressRows
func (pgb *ChainDB) updateAddressRows(address string) (rows []*dbtypes.AddressRow, cacheUpdated bool, err error) { busy, wait, done := pgb.CacheLocks.rows.TryLock(address) if busy { // Just wait until the updater is finished. <-wait err = fmt.Errorf("retry") return } // We will run the DB query, so block others from doing the same. When query // and/or cache update is completed, broadcast to any waiters that the coast // is clear. defer done() hash, height := pgb.BestBlock() blockID := cache.NewBlockID(hash, height) // Retrieve all non-merged address transaction rows. rows, err = pgb.AddressTransactionsAll(address) if err != nil && err != sql.ErrNoRows { return } // Update address rows cache. cacheUpdated = pgb.AddressCache.StoreRows(address, rows, blockID) return }
go
func (pgb *ChainDB) updateAddressRows(address string) (rows []*dbtypes.AddressRow, cacheUpdated bool, err error) { busy, wait, done := pgb.CacheLocks.rows.TryLock(address) if busy { // Just wait until the updater is finished. <-wait err = fmt.Errorf("retry") return } // We will run the DB query, so block others from doing the same. When query // and/or cache update is completed, broadcast to any waiters that the coast // is clear. defer done() hash, height := pgb.BestBlock() blockID := cache.NewBlockID(hash, height) // Retrieve all non-merged address transaction rows. rows, err = pgb.AddressTransactionsAll(address) if err != nil && err != sql.ErrNoRows { return } // Update address rows cache. cacheUpdated = pgb.AddressCache.StoreRows(address, rows, blockID) return }
[ "func", "(", "pgb", "*", "ChainDB", ")", "updateAddressRows", "(", "address", "string", ")", "(", "rows", "[", "]", "*", "dbtypes", ".", "AddressRow", ",", "cacheUpdated", "bool", ",", "err", "error", ")", "{", "busy", ",", "wait", ",", "done", ":=", "pgb", ".", "CacheLocks", ".", "rows", ".", "TryLock", "(", "address", ")", "\n", "if", "busy", "{", "// Just wait until the updater is finished.", "<-", "wait", "\n", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "// We will run the DB query, so block others from doing the same. When query", "// and/or cache update is completed, broadcast to any waiters that the coast", "// is clear.", "defer", "done", "(", ")", "\n\n", "hash", ",", "height", ":=", "pgb", ".", "BestBlock", "(", ")", "\n", "blockID", ":=", "cache", ".", "NewBlockID", "(", "hash", ",", "height", ")", "\n\n", "// Retrieve all non-merged address transaction rows.", "rows", ",", "err", "=", "pgb", ".", "AddressTransactionsAll", "(", "address", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "sql", ".", "ErrNoRows", "{", "return", "\n", "}", "\n\n", "// Update address rows cache.", "cacheUpdated", "=", "pgb", ".", "AddressCache", ".", "StoreRows", "(", "address", ",", "rows", ",", "blockID", ")", "\n", "return", "\n", "}" ]
// updateAddressRows updates address rows, or waits for them to update by an // ongoing query. On completion, the cache should be ready, although it must be // checked again.
[ "updateAddressRows", "updates", "address", "rows", "or", "waits", "for", "them", "to", "update", "by", "an", "ongoing", "query", ".", "On", "completion", "the", "cache", "should", "be", "ready", "although", "it", "must", "be", "checked", "again", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1835-L1861
train
decred/dcrdata
db/dcrpg/pgblockchain.go
AddressRowsMerged
func (pgb *ChainDB) AddressRowsMerged(address string) ([]dbtypes.AddressRowMerged, error) { // Try the address cache. hash := pgb.BestBlockHash() rowsCompact, validBlock := pgb.AddressCache.Rows(address) cacheCurrent := validBlock != nil && validBlock.Hash == *hash && rowsCompact != nil if cacheCurrent { log.Tracef("AddressRows: rows cache HIT for %s.", address) return dbtypes.MergeRowsCompact(rowsCompact), nil } log.Tracef("AddressRows: rows cache MISS for %s.", address) // Update or wait for an update to the cached AddressRows. rows, _, err := pgb.updateAddressRows(address) if err != nil { if err.Error() == "retry" { // Try again, starting with cache. return pgb.AddressRowsMerged(address) } return nil, err } // We have a result. return dbtypes.MergeRows(rows) }
go
func (pgb *ChainDB) AddressRowsMerged(address string) ([]dbtypes.AddressRowMerged, error) { // Try the address cache. hash := pgb.BestBlockHash() rowsCompact, validBlock := pgb.AddressCache.Rows(address) cacheCurrent := validBlock != nil && validBlock.Hash == *hash && rowsCompact != nil if cacheCurrent { log.Tracef("AddressRows: rows cache HIT for %s.", address) return dbtypes.MergeRowsCompact(rowsCompact), nil } log.Tracef("AddressRows: rows cache MISS for %s.", address) // Update or wait for an update to the cached AddressRows. rows, _, err := pgb.updateAddressRows(address) if err != nil { if err.Error() == "retry" { // Try again, starting with cache. return pgb.AddressRowsMerged(address) } return nil, err } // We have a result. return dbtypes.MergeRows(rows) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "AddressRowsMerged", "(", "address", "string", ")", "(", "[", "]", "dbtypes", ".", "AddressRowMerged", ",", "error", ")", "{", "// Try the address cache.", "hash", ":=", "pgb", ".", "BestBlockHash", "(", ")", "\n", "rowsCompact", ",", "validBlock", ":=", "pgb", ".", "AddressCache", ".", "Rows", "(", "address", ")", "\n", "cacheCurrent", ":=", "validBlock", "!=", "nil", "&&", "validBlock", ".", "Hash", "==", "*", "hash", "&&", "rowsCompact", "!=", "nil", "\n", "if", "cacheCurrent", "{", "log", ".", "Tracef", "(", "\"", "\"", ",", "address", ")", "\n", "return", "dbtypes", ".", "MergeRowsCompact", "(", "rowsCompact", ")", ",", "nil", "\n", "}", "\n\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "address", ")", "\n\n", "// Update or wait for an update to the cached AddressRows.", "rows", ",", "_", ",", "err", ":=", "pgb", ".", "updateAddressRows", "(", "address", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", ".", "Error", "(", ")", "==", "\"", "\"", "{", "// Try again, starting with cache.", "return", "pgb", ".", "AddressRowsMerged", "(", "address", ")", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// We have a result.", "return", "dbtypes", ".", "MergeRows", "(", "rows", ")", "\n", "}" ]
// AddressRowsMerged gets the merged address rows either from cache or via DB // query.
[ "AddressRowsMerged", "gets", "the", "merged", "address", "rows", "either", "from", "cache", "or", "via", "DB", "query", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1865-L1889
train
decred/dcrdata
db/dcrpg/pgblockchain.go
AddressRowsCompact
func (pgb *ChainDB) AddressRowsCompact(address string) ([]dbtypes.AddressRowCompact, error) { // Try the address cache. hash := pgb.BestBlockHash() rowsCompact, validBlock := pgb.AddressCache.Rows(address) cacheCurrent := validBlock != nil && validBlock.Hash == *hash && rowsCompact != nil if cacheCurrent { log.Tracef("AddressRows: rows cache HIT for %s.", address) return rowsCompact, nil } log.Tracef("AddressRows: rows cache MISS for %s.", address) // Update or wait for an update to the cached AddressRows. rows, _, err := pgb.updateAddressRows(address) if err != nil { if err.Error() == "retry" { // Try again, starting with cache. return pgb.AddressRowsCompact(address) } return nil, err } // We have a result. return dbtypes.CompactRows(rows), err }
go
func (pgb *ChainDB) AddressRowsCompact(address string) ([]dbtypes.AddressRowCompact, error) { // Try the address cache. hash := pgb.BestBlockHash() rowsCompact, validBlock := pgb.AddressCache.Rows(address) cacheCurrent := validBlock != nil && validBlock.Hash == *hash && rowsCompact != nil if cacheCurrent { log.Tracef("AddressRows: rows cache HIT for %s.", address) return rowsCompact, nil } log.Tracef("AddressRows: rows cache MISS for %s.", address) // Update or wait for an update to the cached AddressRows. rows, _, err := pgb.updateAddressRows(address) if err != nil { if err.Error() == "retry" { // Try again, starting with cache. return pgb.AddressRowsCompact(address) } return nil, err } // We have a result. return dbtypes.CompactRows(rows), err }
[ "func", "(", "pgb", "*", "ChainDB", ")", "AddressRowsCompact", "(", "address", "string", ")", "(", "[", "]", "dbtypes", ".", "AddressRowCompact", ",", "error", ")", "{", "// Try the address cache.", "hash", ":=", "pgb", ".", "BestBlockHash", "(", ")", "\n", "rowsCompact", ",", "validBlock", ":=", "pgb", ".", "AddressCache", ".", "Rows", "(", "address", ")", "\n", "cacheCurrent", ":=", "validBlock", "!=", "nil", "&&", "validBlock", ".", "Hash", "==", "*", "hash", "&&", "rowsCompact", "!=", "nil", "\n", "if", "cacheCurrent", "{", "log", ".", "Tracef", "(", "\"", "\"", ",", "address", ")", "\n", "return", "rowsCompact", ",", "nil", "\n", "}", "\n\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "address", ")", "\n\n", "// Update or wait for an update to the cached AddressRows.", "rows", ",", "_", ",", "err", ":=", "pgb", ".", "updateAddressRows", "(", "address", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", ".", "Error", "(", ")", "==", "\"", "\"", "{", "// Try again, starting with cache.", "return", "pgb", ".", "AddressRowsCompact", "(", "address", ")", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// We have a result.", "return", "dbtypes", ".", "CompactRows", "(", "rows", ")", ",", "err", "\n", "}" ]
// AddressRowsCompact gets non-merged address rows either from cache or via DB // query.
[ "AddressRowsCompact", "gets", "non", "-", "merged", "address", "rows", "either", "from", "cache", "or", "via", "DB", "query", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1893-L1917
train
decred/dcrdata
db/dcrpg/pgblockchain.go
retrieveMergedTxnCount
func (pgb *ChainDB) retrieveMergedTxnCount(addr string, txnView dbtypes.AddrTxnViewType) (int, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() var count int64 var err error switch txnView { case dbtypes.AddrMergedTxnDebit: count, err = CountMergedSpendingTxns(ctx, pgb.db, addr) case dbtypes.AddrMergedTxnCredit: count, err = CountMergedFundingTxns(ctx, pgb.db, addr) case dbtypes.AddrMergedTxn: count, err = CountMergedTxns(ctx, pgb.db, addr) default: return 0, fmt.Errorf("retrieveMergedTxnCount: requested count for non-merged view") } return int(count), err }
go
func (pgb *ChainDB) retrieveMergedTxnCount(addr string, txnView dbtypes.AddrTxnViewType) (int, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() var count int64 var err error switch txnView { case dbtypes.AddrMergedTxnDebit: count, err = CountMergedSpendingTxns(ctx, pgb.db, addr) case dbtypes.AddrMergedTxnCredit: count, err = CountMergedFundingTxns(ctx, pgb.db, addr) case dbtypes.AddrMergedTxn: count, err = CountMergedTxns(ctx, pgb.db, addr) default: return 0, fmt.Errorf("retrieveMergedTxnCount: requested count for non-merged view") } return int(count), err }
[ "func", "(", "pgb", "*", "ChainDB", ")", "retrieveMergedTxnCount", "(", "addr", "string", ",", "txnView", "dbtypes", ".", "AddrTxnViewType", ")", "(", "int", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "var", "count", "int64", "\n", "var", "err", "error", "\n", "switch", "txnView", "{", "case", "dbtypes", ".", "AddrMergedTxnDebit", ":", "count", ",", "err", "=", "CountMergedSpendingTxns", "(", "ctx", ",", "pgb", ".", "db", ",", "addr", ")", "\n", "case", "dbtypes", ".", "AddrMergedTxnCredit", ":", "count", ",", "err", "=", "CountMergedFundingTxns", "(", "ctx", ",", "pgb", ".", "db", ",", "addr", ")", "\n", "case", "dbtypes", ".", "AddrMergedTxn", ":", "count", ",", "err", "=", "CountMergedTxns", "(", "ctx", ",", "pgb", ".", "db", ",", "addr", ")", "\n", "default", ":", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "int", "(", "count", ")", ",", "err", "\n", "}" ]
// retrieveMergedTxnCount queries the DB for the merged address transaction view // row count.
[ "retrieveMergedTxnCount", "queries", "the", "DB", "for", "the", "merged", "address", "transaction", "view", "row", "count", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1921-L1938
train
decred/dcrdata
db/dcrpg/pgblockchain.go
mergedTxnCount
func (pgb *ChainDB) mergedTxnCount(addr string, txnView dbtypes.AddrTxnViewType) (int, error) { // Try the cache first. rows, blockID := pgb.AddressCache.Rows(addr) if blockID == nil { // Query the DB. return pgb.retrieveMergedTxnCount(addr, txnView) } return dbtypes.CountMergedRowsCompact(rows, txnView) }
go
func (pgb *ChainDB) mergedTxnCount(addr string, txnView dbtypes.AddrTxnViewType) (int, error) { // Try the cache first. rows, blockID := pgb.AddressCache.Rows(addr) if blockID == nil { // Query the DB. return pgb.retrieveMergedTxnCount(addr, txnView) } return dbtypes.CountMergedRowsCompact(rows, txnView) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "mergedTxnCount", "(", "addr", "string", ",", "txnView", "dbtypes", ".", "AddrTxnViewType", ")", "(", "int", ",", "error", ")", "{", "// Try the cache first.", "rows", ",", "blockID", ":=", "pgb", ".", "AddressCache", ".", "Rows", "(", "addr", ")", "\n", "if", "blockID", "==", "nil", "{", "// Query the DB.", "return", "pgb", ".", "retrieveMergedTxnCount", "(", "addr", ",", "txnView", ")", "\n", "}", "\n\n", "return", "dbtypes", ".", "CountMergedRowsCompact", "(", "rows", ",", "txnView", ")", "\n", "}" ]
// mergedTxnCount checks cache and falls back to retrieveMergedTxnCount.
[ "mergedTxnCount", "checks", "cache", "and", "falls", "back", "to", "retrieveMergedTxnCount", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1941-L1950
train
decred/dcrdata
db/dcrpg/pgblockchain.go
nonMergedTxnCount
func (pgb *ChainDB) nonMergedTxnCount(addr string, txnView dbtypes.AddrTxnViewType) (int, error) { bal, _, err := pgb.AddressBalance(addr) if err != nil { return 0, err } var count int64 switch txnView { case dbtypes.AddrTxnAll: count = (bal.NumSpent * 2) + bal.NumUnspent case dbtypes.AddrTxnCredit: count = bal.NumSpent + bal.NumUnspent case dbtypes.AddrTxnDebit: count = bal.NumSpent default: return 0, fmt.Errorf("NonMergedTxnCount: requested count for merged view") } return int(count), nil }
go
func (pgb *ChainDB) nonMergedTxnCount(addr string, txnView dbtypes.AddrTxnViewType) (int, error) { bal, _, err := pgb.AddressBalance(addr) if err != nil { return 0, err } var count int64 switch txnView { case dbtypes.AddrTxnAll: count = (bal.NumSpent * 2) + bal.NumUnspent case dbtypes.AddrTxnCredit: count = bal.NumSpent + bal.NumUnspent case dbtypes.AddrTxnDebit: count = bal.NumSpent default: return 0, fmt.Errorf("NonMergedTxnCount: requested count for merged view") } return int(count), nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "nonMergedTxnCount", "(", "addr", "string", ",", "txnView", "dbtypes", ".", "AddrTxnViewType", ")", "(", "int", ",", "error", ")", "{", "bal", ",", "_", ",", "err", ":=", "pgb", ".", "AddressBalance", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "var", "count", "int64", "\n", "switch", "txnView", "{", "case", "dbtypes", ".", "AddrTxnAll", ":", "count", "=", "(", "bal", ".", "NumSpent", "*", "2", ")", "+", "bal", ".", "NumUnspent", "\n", "case", "dbtypes", ".", "AddrTxnCredit", ":", "count", "=", "bal", ".", "NumSpent", "+", "bal", ".", "NumUnspent", "\n", "case", "dbtypes", ".", "AddrTxnDebit", ":", "count", "=", "bal", ".", "NumSpent", "\n", "default", ":", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "int", "(", "count", ")", ",", "nil", "\n", "}" ]
// nonMergedTxnCount gets the non-merged address transaction view row count via // AddressBalance, which checks the cache and falls back to a DB query.
[ "nonMergedTxnCount", "gets", "the", "non", "-", "merged", "address", "transaction", "view", "row", "count", "via", "AddressBalance", "which", "checks", "the", "cache", "and", "falls", "back", "to", "a", "DB", "query", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1954-L1971
train
decred/dcrdata
db/dcrpg/pgblockchain.go
CountTransactions
func (pgb *ChainDB) CountTransactions(addr string, txnView dbtypes.AddrTxnViewType) (int, error) { merged, err := txnView.IsMerged() if err != nil { return 0, err } countFn := pgb.nonMergedTxnCount if merged { countFn = pgb.mergedTxnCount } count, err := countFn(addr, txnView) if err != nil { return 0, err } return count, nil }
go
func (pgb *ChainDB) CountTransactions(addr string, txnView dbtypes.AddrTxnViewType) (int, error) { merged, err := txnView.IsMerged() if err != nil { return 0, err } countFn := pgb.nonMergedTxnCount if merged { countFn = pgb.mergedTxnCount } count, err := countFn(addr, txnView) if err != nil { return 0, err } return count, nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "CountTransactions", "(", "addr", "string", ",", "txnView", "dbtypes", ".", "AddrTxnViewType", ")", "(", "int", ",", "error", ")", "{", "merged", ",", "err", ":=", "txnView", ".", "IsMerged", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "countFn", ":=", "pgb", ".", "nonMergedTxnCount", "\n", "if", "merged", "{", "countFn", "=", "pgb", ".", "mergedTxnCount", "\n", "}", "\n\n", "count", ",", "err", ":=", "countFn", "(", "addr", ",", "txnView", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "count", ",", "nil", "\n", "}" ]
// CountTransactions gets the total row count for the given address and address // transaction view.
[ "CountTransactions", "gets", "the", "total", "row", "count", "for", "the", "given", "address", "and", "address", "transaction", "view", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L1975-L1991
train
decred/dcrdata
db/dcrpg/pgblockchain.go
DbTxByHash
func (pgb *ChainDB) DbTxByHash(txid string) (*dbtypes.Tx, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, dbTx, err := RetrieveDbTxByHash(ctx, pgb.db, txid) return dbTx, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) DbTxByHash(txid string) (*dbtypes.Tx, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() _, dbTx, err := RetrieveDbTxByHash(ctx, pgb.db, txid) return dbTx, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "DbTxByHash", "(", "txid", "string", ")", "(", "*", "dbtypes", ".", "Tx", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "_", ",", "dbTx", ",", "err", ":=", "RetrieveDbTxByHash", "(", "ctx", ",", "pgb", ".", "db", ",", "txid", ")", "\n", "return", "dbTx", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// DbTxByHash retrieves a row of the transactions table corresponding to the // given transaction hash. Transactions in valid and mainchain blocks are chosen // first.
[ "DbTxByHash", "retrieves", "a", "row", "of", "the", "transactions", "table", "corresponding", "to", "the", "given", "transaction", "hash", ".", "Transactions", "in", "valid", "and", "mainchain", "blocks", "are", "chosen", "first", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L2314-L2319
train
decred/dcrdata
db/dcrpg/pgblockchain.go
FundingOutpointIndxByVinID
func (pgb *ChainDB) FundingOutpointIndxByVinID(id uint64) (uint32, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() ind, err := RetrieveFundingOutpointIndxByVinID(ctx, pgb.db, id) return ind, pgb.replaceCancelError(err) }
go
func (pgb *ChainDB) FundingOutpointIndxByVinID(id uint64) (uint32, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() ind, err := RetrieveFundingOutpointIndxByVinID(ctx, pgb.db, id) return ind, pgb.replaceCancelError(err) }
[ "func", "(", "pgb", "*", "ChainDB", ")", "FundingOutpointIndxByVinID", "(", "id", "uint64", ")", "(", "uint32", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "ind", ",", "err", ":=", "RetrieveFundingOutpointIndxByVinID", "(", "ctx", ",", "pgb", ".", "db", ",", "id", ")", "\n", "return", "ind", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}" ]
// FundingOutpointIndxByVinID retrieves the the transaction output index of the // previous outpoint for a transaction input specified by row ID in the vins // table, which stores previous outpoints for each vin.
[ "FundingOutpointIndxByVinID", "retrieves", "the", "the", "transaction", "output", "index", "of", "the", "previous", "outpoint", "for", "a", "transaction", "input", "specified", "by", "row", "ID", "in", "the", "vins", "table", "which", "stores", "previous", "outpoints", "for", "each", "vin", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L2324-L2329
train
decred/dcrdata
db/dcrpg/pgblockchain.go
FillAddressTransactions
func (pgb *ChainDB) FillAddressTransactions(addrInfo *dbtypes.AddressInfo) error { if addrInfo == nil { return nil } var numUnconfirmed int64 for i, txn := range addrInfo.Transactions { // Retrieve the most valid, most mainchain, and most recent tx with this // hash. This means it prefers mainchain and valid blocks first. dbTx, err := pgb.DbTxByHash(txn.TxID) if err != nil { return err } txn.Size = dbTx.Size txn.FormattedSize = humanize.Bytes(uint64(dbTx.Size)) txn.Total = dcrutil.Amount(dbTx.Sent).ToCoin() txn.Time = dbTx.BlockTime if txn.Time.UNIX() > 0 { txn.Confirmations = uint64(pgb.Height() - dbTx.BlockHeight + 1) } else { numUnconfirmed++ txn.Confirmations = 0 } // Get the funding or spending transaction matching index if there is a // matching tx hash already present. During the next database // restructuring we may want to consider including matching tx index // along with matching tx hash in the addresses table. if txn.MatchedTx != `` { if !txn.IsFunding { // Spending transaction: lookup the previous outpoint's txout // index by the vins table row ID. idx, err := pgb.FundingOutpointIndxByVinID(dbTx.VinDbIds[txn.InOutID]) if err != nil { log.Warnf("Matched Transaction Lookup failed for %s:%d: id: %d: %v", txn.TxID, txn.InOutID, txn.InOutID, err) } else { addrInfo.Transactions[i].MatchedTxIndex = idx } } else { // Funding transaction: lookup by the matching (spending) tx // hash and tx index. _, idx, _, err := pgb.SpendingTransaction(txn.TxID, txn.InOutID) if err != nil { log.Warnf("Matched Transaction Lookup failed for %s:%d: %v", txn.TxID, txn.InOutID, err) } else { addrInfo.Transactions[i].MatchedTxIndex = idx } } } } addrInfo.NumUnconfirmed = numUnconfirmed return nil }
go
func (pgb *ChainDB) FillAddressTransactions(addrInfo *dbtypes.AddressInfo) error { if addrInfo == nil { return nil } var numUnconfirmed int64 for i, txn := range addrInfo.Transactions { // Retrieve the most valid, most mainchain, and most recent tx with this // hash. This means it prefers mainchain and valid blocks first. dbTx, err := pgb.DbTxByHash(txn.TxID) if err != nil { return err } txn.Size = dbTx.Size txn.FormattedSize = humanize.Bytes(uint64(dbTx.Size)) txn.Total = dcrutil.Amount(dbTx.Sent).ToCoin() txn.Time = dbTx.BlockTime if txn.Time.UNIX() > 0 { txn.Confirmations = uint64(pgb.Height() - dbTx.BlockHeight + 1) } else { numUnconfirmed++ txn.Confirmations = 0 } // Get the funding or spending transaction matching index if there is a // matching tx hash already present. During the next database // restructuring we may want to consider including matching tx index // along with matching tx hash in the addresses table. if txn.MatchedTx != `` { if !txn.IsFunding { // Spending transaction: lookup the previous outpoint's txout // index by the vins table row ID. idx, err := pgb.FundingOutpointIndxByVinID(dbTx.VinDbIds[txn.InOutID]) if err != nil { log.Warnf("Matched Transaction Lookup failed for %s:%d: id: %d: %v", txn.TxID, txn.InOutID, txn.InOutID, err) } else { addrInfo.Transactions[i].MatchedTxIndex = idx } } else { // Funding transaction: lookup by the matching (spending) tx // hash and tx index. _, idx, _, err := pgb.SpendingTransaction(txn.TxID, txn.InOutID) if err != nil { log.Warnf("Matched Transaction Lookup failed for %s:%d: %v", txn.TxID, txn.InOutID, err) } else { addrInfo.Transactions[i].MatchedTxIndex = idx } } } } addrInfo.NumUnconfirmed = numUnconfirmed return nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "FillAddressTransactions", "(", "addrInfo", "*", "dbtypes", ".", "AddressInfo", ")", "error", "{", "if", "addrInfo", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "var", "numUnconfirmed", "int64", "\n\n", "for", "i", ",", "txn", ":=", "range", "addrInfo", ".", "Transactions", "{", "// Retrieve the most valid, most mainchain, and most recent tx with this", "// hash. This means it prefers mainchain and valid blocks first.", "dbTx", ",", "err", ":=", "pgb", ".", "DbTxByHash", "(", "txn", ".", "TxID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "txn", ".", "Size", "=", "dbTx", ".", "Size", "\n", "txn", ".", "FormattedSize", "=", "humanize", ".", "Bytes", "(", "uint64", "(", "dbTx", ".", "Size", ")", ")", "\n", "txn", ".", "Total", "=", "dcrutil", ".", "Amount", "(", "dbTx", ".", "Sent", ")", ".", "ToCoin", "(", ")", "\n", "txn", ".", "Time", "=", "dbTx", ".", "BlockTime", "\n", "if", "txn", ".", "Time", ".", "UNIX", "(", ")", ">", "0", "{", "txn", ".", "Confirmations", "=", "uint64", "(", "pgb", ".", "Height", "(", ")", "-", "dbTx", ".", "BlockHeight", "+", "1", ")", "\n", "}", "else", "{", "numUnconfirmed", "++", "\n", "txn", ".", "Confirmations", "=", "0", "\n", "}", "\n\n", "// Get the funding or spending transaction matching index if there is a", "// matching tx hash already present. During the next database", "// restructuring we may want to consider including matching tx index", "// along with matching tx hash in the addresses table.", "if", "txn", ".", "MatchedTx", "!=", "``", "{", "if", "!", "txn", ".", "IsFunding", "{", "// Spending transaction: lookup the previous outpoint's txout", "// index by the vins table row ID.", "idx", ",", "err", ":=", "pgb", ".", "FundingOutpointIndxByVinID", "(", "dbTx", ".", "VinDbIds", "[", "txn", ".", "InOutID", "]", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "txn", ".", "TxID", ",", "txn", ".", "InOutID", ",", "txn", ".", "InOutID", ",", "err", ")", "\n", "}", "else", "{", "addrInfo", ".", "Transactions", "[", "i", "]", ".", "MatchedTxIndex", "=", "idx", "\n", "}", "\n\n", "}", "else", "{", "// Funding transaction: lookup by the matching (spending) tx", "// hash and tx index.", "_", ",", "idx", ",", "_", ",", "err", ":=", "pgb", ".", "SpendingTransaction", "(", "txn", ".", "TxID", ",", "txn", ".", "InOutID", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "txn", ".", "TxID", ",", "txn", ".", "InOutID", ",", "err", ")", "\n", "}", "else", "{", "addrInfo", ".", "Transactions", "[", "i", "]", ".", "MatchedTxIndex", "=", "idx", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "addrInfo", ".", "NumUnconfirmed", "=", "numUnconfirmed", "\n\n", "return", "nil", "\n", "}" ]
// FillAddressTransactions is used to fill out the transaction details in an // explorer.AddressInfo generated by dbtypes.ReduceAddressHistory, usually from // the output of AddressHistory. This function also sets the number of // unconfirmed transactions for the current best block in the database.
[ "FillAddressTransactions", "is", "used", "to", "fill", "out", "the", "transaction", "details", "in", "an", "explorer", ".", "AddressInfo", "generated", "by", "dbtypes", ".", "ReduceAddressHistory", "usually", "from", "the", "output", "of", "AddressHistory", ".", "This", "function", "also", "sets", "the", "number", "of", "unconfirmed", "transactions", "for", "the", "current", "best", "block", "in", "the", "database", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L2335-L2393
train
decred/dcrdata
db/dcrpg/pgblockchain.go
AddressTransactionDetails
func (pgb *ChainDB) AddressTransactionDetails(addr string, count, skip int64, txnType dbtypes.AddrTxnViewType) (*apitypes.Address, error) { // Fetch address history for given transaction range and type addrData, _, err := pgb.addressInfo(addr, count, skip, txnType) if err != nil { return nil, err } // No transactions found. Not an error. if addrData == nil { return &apitypes.Address{ Address: addr, Transactions: make([]*apitypes.AddressTxShort, 0), // not nil for JSON formatting }, nil } // Convert each dbtypes.AddressTx to apitypes.AddressTxShort txs := addrData.Transactions txsShort := make([]*apitypes.AddressTxShort, 0, len(txs)) for i := range txs { txsShort = append(txsShort, &apitypes.AddressTxShort{ TxID: txs[i].TxID, Time: apitypes.TimeAPI{S: txs[i].Time}, Value: txs[i].Total, Confirmations: int64(txs[i].Confirmations), Size: int32(txs[i].Size), }) } // put a bow on it return &apitypes.Address{ Address: addr, Transactions: txsShort, }, nil }
go
func (pgb *ChainDB) AddressTransactionDetails(addr string, count, skip int64, txnType dbtypes.AddrTxnViewType) (*apitypes.Address, error) { // Fetch address history for given transaction range and type addrData, _, err := pgb.addressInfo(addr, count, skip, txnType) if err != nil { return nil, err } // No transactions found. Not an error. if addrData == nil { return &apitypes.Address{ Address: addr, Transactions: make([]*apitypes.AddressTxShort, 0), // not nil for JSON formatting }, nil } // Convert each dbtypes.AddressTx to apitypes.AddressTxShort txs := addrData.Transactions txsShort := make([]*apitypes.AddressTxShort, 0, len(txs)) for i := range txs { txsShort = append(txsShort, &apitypes.AddressTxShort{ TxID: txs[i].TxID, Time: apitypes.TimeAPI{S: txs[i].Time}, Value: txs[i].Total, Confirmations: int64(txs[i].Confirmations), Size: int32(txs[i].Size), }) } // put a bow on it return &apitypes.Address{ Address: addr, Transactions: txsShort, }, nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "AddressTransactionDetails", "(", "addr", "string", ",", "count", ",", "skip", "int64", ",", "txnType", "dbtypes", ".", "AddrTxnViewType", ")", "(", "*", "apitypes", ".", "Address", ",", "error", ")", "{", "// Fetch address history for given transaction range and type", "addrData", ",", "_", ",", "err", ":=", "pgb", ".", "addressInfo", "(", "addr", ",", "count", ",", "skip", ",", "txnType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// No transactions found. Not an error.", "if", "addrData", "==", "nil", "{", "return", "&", "apitypes", ".", "Address", "{", "Address", ":", "addr", ",", "Transactions", ":", "make", "(", "[", "]", "*", "apitypes", ".", "AddressTxShort", ",", "0", ")", ",", "// not nil for JSON formatting", "}", ",", "nil", "\n", "}", "\n\n", "// Convert each dbtypes.AddressTx to apitypes.AddressTxShort", "txs", ":=", "addrData", ".", "Transactions", "\n", "txsShort", ":=", "make", "(", "[", "]", "*", "apitypes", ".", "AddressTxShort", ",", "0", ",", "len", "(", "txs", ")", ")", "\n", "for", "i", ":=", "range", "txs", "{", "txsShort", "=", "append", "(", "txsShort", ",", "&", "apitypes", ".", "AddressTxShort", "{", "TxID", ":", "txs", "[", "i", "]", ".", "TxID", ",", "Time", ":", "apitypes", ".", "TimeAPI", "{", "S", ":", "txs", "[", "i", "]", ".", "Time", "}", ",", "Value", ":", "txs", "[", "i", "]", ".", "Total", ",", "Confirmations", ":", "int64", "(", "txs", "[", "i", "]", ".", "Confirmations", ")", ",", "Size", ":", "int32", "(", "txs", "[", "i", "]", ".", "Size", ")", ",", "}", ")", "\n", "}", "\n\n", "// put a bow on it", "return", "&", "apitypes", ".", "Address", "{", "Address", ":", "addr", ",", "Transactions", ":", "txsShort", ",", "}", ",", "nil", "\n", "}" ]
// AddressTransactionDetails returns an apitypes.Address with at most the last // count transactions of type txnType in which the address was involved, // starting after skip transactions. This does NOT include unconfirmed // transactions.
[ "AddressTransactionDetails", "returns", "an", "apitypes", ".", "Address", "with", "at", "most", "the", "last", "count", "transactions", "of", "type", "txnType", "in", "which", "the", "address", "was", "involved", "starting", "after", "skip", "transactions", ".", "This", "does", "NOT", "include", "unconfirmed", "transactions", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L2610-L2643
train
decred/dcrdata
db/dcrpg/pgblockchain.go
ChainInfo
func (pgb *ChainDB) ChainInfo() *dbtypes.BlockChainData { pgb.deployments.mtx.RLock() defer pgb.deployments.mtx.RUnlock() return pgb.deployments.chainInfo }
go
func (pgb *ChainDB) ChainInfo() *dbtypes.BlockChainData { pgb.deployments.mtx.RLock() defer pgb.deployments.mtx.RUnlock() return pgb.deployments.chainInfo }
[ "func", "(", "pgb", "*", "ChainDB", ")", "ChainInfo", "(", ")", "*", "dbtypes", ".", "BlockChainData", "{", "pgb", ".", "deployments", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "pgb", ".", "deployments", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "pgb", ".", "deployments", ".", "chainInfo", "\n", "}" ]
// ChainInfo guarantees thread-safe access of the deployment data.
[ "ChainInfo", "guarantees", "thread", "-", "safe", "access", "of", "the", "deployment", "data", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/pgblockchain.go#L2746-L2750
train