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
api/insight/converter.go
DcrToInsightBlock
func (iapi *InsightApi) DcrToInsightBlock(inBlocks []*dcrjson.GetBlockVerboseResult) ([]*apitypes.InsightBlockResult, error) { RewardAtBlock := func(blocknum int64, voters uint16) float64 { subsidyCache := blockchain.NewSubsidyCache(0, iapi.params) work := blockchain.CalcBlockWorkSubsidy(subsidyCache, blocknum, voters, iapi.params) stake := blockchain.CalcStakeVoteSubsidy(subsidyCache, blocknum, iapi.params) * int64(voters) tax := blockchain.CalcBlockTaxSubsidy(subsidyCache, blocknum, voters, iapi.params) return dcrutil.Amount(work + stake + tax).ToCoin() } outBlocks := make([]*apitypes.InsightBlockResult, 0, len(inBlocks)) for _, inBlock := range inBlocks { outBlock := apitypes.InsightBlockResult{ Hash: inBlock.Hash, Confirmations: inBlock.Confirmations, Size: inBlock.Size, Height: inBlock.Height, Version: inBlock.Version, MerkleRoot: inBlock.MerkleRoot, Tx: append(inBlock.Tx, inBlock.STx...), Time: inBlock.Time, Nonce: inBlock.Nonce, Bits: inBlock.Bits, Difficulty: inBlock.Difficulty, PreviousHash: inBlock.PreviousHash, NextHash: inBlock.NextHash, Reward: RewardAtBlock(inBlock.Height, inBlock.Voters), IsMainChain: inBlock.Height > 0, } outBlocks = append(outBlocks, &outBlock) } return outBlocks, nil }
go
func (iapi *InsightApi) DcrToInsightBlock(inBlocks []*dcrjson.GetBlockVerboseResult) ([]*apitypes.InsightBlockResult, error) { RewardAtBlock := func(blocknum int64, voters uint16) float64 { subsidyCache := blockchain.NewSubsidyCache(0, iapi.params) work := blockchain.CalcBlockWorkSubsidy(subsidyCache, blocknum, voters, iapi.params) stake := blockchain.CalcStakeVoteSubsidy(subsidyCache, blocknum, iapi.params) * int64(voters) tax := blockchain.CalcBlockTaxSubsidy(subsidyCache, blocknum, voters, iapi.params) return dcrutil.Amount(work + stake + tax).ToCoin() } outBlocks := make([]*apitypes.InsightBlockResult, 0, len(inBlocks)) for _, inBlock := range inBlocks { outBlock := apitypes.InsightBlockResult{ Hash: inBlock.Hash, Confirmations: inBlock.Confirmations, Size: inBlock.Size, Height: inBlock.Height, Version: inBlock.Version, MerkleRoot: inBlock.MerkleRoot, Tx: append(inBlock.Tx, inBlock.STx...), Time: inBlock.Time, Nonce: inBlock.Nonce, Bits: inBlock.Bits, Difficulty: inBlock.Difficulty, PreviousHash: inBlock.PreviousHash, NextHash: inBlock.NextHash, Reward: RewardAtBlock(inBlock.Height, inBlock.Voters), IsMainChain: inBlock.Height > 0, } outBlocks = append(outBlocks, &outBlock) } return outBlocks, nil }
[ "func", "(", "iapi", "*", "InsightApi", ")", "DcrToInsightBlock", "(", "inBlocks", "[", "]", "*", "dcrjson", ".", "GetBlockVerboseResult", ")", "(", "[", "]", "*", "apitypes", ".", "InsightBlockResult", ",", "error", ")", "{", "RewardAtBlock", ":=", "func", "(", "blocknum", "int64", ",", "voters", "uint16", ")", "float64", "{", "subsidyCache", ":=", "blockchain", ".", "NewSubsidyCache", "(", "0", ",", "iapi", ".", "params", ")", "\n", "work", ":=", "blockchain", ".", "CalcBlockWorkSubsidy", "(", "subsidyCache", ",", "blocknum", ",", "voters", ",", "iapi", ".", "params", ")", "\n", "stake", ":=", "blockchain", ".", "CalcStakeVoteSubsidy", "(", "subsidyCache", ",", "blocknum", ",", "iapi", ".", "params", ")", "*", "int64", "(", "voters", ")", "\n", "tax", ":=", "blockchain", ".", "CalcBlockTaxSubsidy", "(", "subsidyCache", ",", "blocknum", ",", "voters", ",", "iapi", ".", "params", ")", "\n", "return", "dcrutil", ".", "Amount", "(", "work", "+", "stake", "+", "tax", ")", ".", "ToCoin", "(", ")", "\n", "}", "\n\n", "outBlocks", ":=", "make", "(", "[", "]", "*", "apitypes", ".", "InsightBlockResult", ",", "0", ",", "len", "(", "inBlocks", ")", ")", "\n", "for", "_", ",", "inBlock", ":=", "range", "inBlocks", "{", "outBlock", ":=", "apitypes", ".", "InsightBlockResult", "{", "Hash", ":", "inBlock", ".", "Hash", ",", "Confirmations", ":", "inBlock", ".", "Confirmations", ",", "Size", ":", "inBlock", ".", "Size", ",", "Height", ":", "inBlock", ".", "Height", ",", "Version", ":", "inBlock", ".", "Version", ",", "MerkleRoot", ":", "inBlock", ".", "MerkleRoot", ",", "Tx", ":", "append", "(", "inBlock", ".", "Tx", ",", "inBlock", ".", "STx", "...", ")", ",", "Time", ":", "inBlock", ".", "Time", ",", "Nonce", ":", "inBlock", ".", "Nonce", ",", "Bits", ":", "inBlock", ".", "Bits", ",", "Difficulty", ":", "inBlock", ".", "Difficulty", ",", "PreviousHash", ":", "inBlock", ".", "PreviousHash", ",", "NextHash", ":", "inBlock", ".", "NextHash", ",", "Reward", ":", "RewardAtBlock", "(", "inBlock", ".", "Height", ",", "inBlock", ".", "Voters", ")", ",", "IsMainChain", ":", "inBlock", ".", "Height", ">", "0", ",", "}", "\n", "outBlocks", "=", "append", "(", "outBlocks", ",", "&", "outBlock", ")", "\n", "}", "\n", "return", "outBlocks", ",", "nil", "\n", "}" ]
// DcrToInsightBlock converts a dcrjson.GetBlockVerboseResult to Insight block.
[ "DcrToInsightBlock", "converts", "a", "dcrjson", ".", "GetBlockVerboseResult", "to", "Insight", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/insight/converter.go#L143-L174
train
decred/dcrdata
notification/ntfnchans.go
MakeNtfnChans
func MakeNtfnChans() { // If we're monitoring for blocks OR collecting block data, these channels // are necessary to handle new block notifications. Otherwise, leave them // as nil so that both a send (below) blocks and a receive (in // blockConnectedHandler) block. default case makes non-blocking below. // quit channel case manages blockConnectedHandlers. //NtfnChans.ConnectChan = make(chan *chainhash.Hash, blockConnChanBuffer) // WiredDB channel for connecting new blocks NtfnChans.ConnectChanWiredDB = make(chan *chainhash.Hash, blockConnChanBuffer) // Stake DB channel for connecting new blocks - BLOCKING! //NtfnChans.ConnectChanStakeDB = make(chan *chainhash.Hash) NtfnChans.ConnectChanDcrpgDB = make(chan *chainhash.Hash, blockConnChanBuffer) // Reorg data channels NtfnChans.ReorgChanBlockData = make(chan *txhelpers.ReorgData) NtfnChans.ReorgChanWiredDB = make(chan *txhelpers.ReorgData) NtfnChans.ReorgChanStakeDB = make(chan *txhelpers.ReorgData) NtfnChans.ReorgChanDcrpgDB = make(chan *txhelpers.ReorgData) // To update app status NtfnChans.UpdateStatusNodeHeight = make(chan uint32, blockConnChanBuffer) NtfnChans.UpdateStatusDBHeight = make(chan uint32, blockConnChanBuffer) // watchaddress // if len(cfg.WatchAddresses) > 0 { // // recv/SpendTxBlockChan come with connected blocks // NtfnChans.RecvTxBlockChan = make(chan *txhelpers.BlockWatchedTx, blockConnChanBuffer) // NtfnChans.SpendTxBlockChan = make(chan *txhelpers.BlockWatchedTx, blockConnChanBuffer) // NtfnChans.RelevantTxMempoolChan = make(chan *dcrutil.Tx, relevantMempoolTxChanBuffer) // } // New mempool tx chan for general purpose mempool monitor/collector/saver. NtfnChans.NewTxChan = make(chan *dcrjson.TxRawResult, newTxChanBuffer) NtfnChans.InsightNewTxChan = make(chan *insight.NewTx, expNewTxChanBuffer) NtfnChans.ReorgChartsCache = make(chan *txhelpers.ReorgData) }
go
func MakeNtfnChans() { // If we're monitoring for blocks OR collecting block data, these channels // are necessary to handle new block notifications. Otherwise, leave them // as nil so that both a send (below) blocks and a receive (in // blockConnectedHandler) block. default case makes non-blocking below. // quit channel case manages blockConnectedHandlers. //NtfnChans.ConnectChan = make(chan *chainhash.Hash, blockConnChanBuffer) // WiredDB channel for connecting new blocks NtfnChans.ConnectChanWiredDB = make(chan *chainhash.Hash, blockConnChanBuffer) // Stake DB channel for connecting new blocks - BLOCKING! //NtfnChans.ConnectChanStakeDB = make(chan *chainhash.Hash) NtfnChans.ConnectChanDcrpgDB = make(chan *chainhash.Hash, blockConnChanBuffer) // Reorg data channels NtfnChans.ReorgChanBlockData = make(chan *txhelpers.ReorgData) NtfnChans.ReorgChanWiredDB = make(chan *txhelpers.ReorgData) NtfnChans.ReorgChanStakeDB = make(chan *txhelpers.ReorgData) NtfnChans.ReorgChanDcrpgDB = make(chan *txhelpers.ReorgData) // To update app status NtfnChans.UpdateStatusNodeHeight = make(chan uint32, blockConnChanBuffer) NtfnChans.UpdateStatusDBHeight = make(chan uint32, blockConnChanBuffer) // watchaddress // if len(cfg.WatchAddresses) > 0 { // // recv/SpendTxBlockChan come with connected blocks // NtfnChans.RecvTxBlockChan = make(chan *txhelpers.BlockWatchedTx, blockConnChanBuffer) // NtfnChans.SpendTxBlockChan = make(chan *txhelpers.BlockWatchedTx, blockConnChanBuffer) // NtfnChans.RelevantTxMempoolChan = make(chan *dcrutil.Tx, relevantMempoolTxChanBuffer) // } // New mempool tx chan for general purpose mempool monitor/collector/saver. NtfnChans.NewTxChan = make(chan *dcrjson.TxRawResult, newTxChanBuffer) NtfnChans.InsightNewTxChan = make(chan *insight.NewTx, expNewTxChanBuffer) NtfnChans.ReorgChartsCache = make(chan *txhelpers.ReorgData) }
[ "func", "MakeNtfnChans", "(", ")", "{", "// If we're monitoring for blocks OR collecting block data, these channels", "// are necessary to handle new block notifications. Otherwise, leave them", "// as nil so that both a send (below) blocks and a receive (in", "// blockConnectedHandler) block. default case makes non-blocking below.", "// quit channel case manages blockConnectedHandlers.", "//NtfnChans.ConnectChan = make(chan *chainhash.Hash, blockConnChanBuffer)", "// WiredDB channel for connecting new blocks", "NtfnChans", ".", "ConnectChanWiredDB", "=", "make", "(", "chan", "*", "chainhash", ".", "Hash", ",", "blockConnChanBuffer", ")", "\n\n", "// Stake DB channel for connecting new blocks - BLOCKING!", "//NtfnChans.ConnectChanStakeDB = make(chan *chainhash.Hash)", "NtfnChans", ".", "ConnectChanDcrpgDB", "=", "make", "(", "chan", "*", "chainhash", ".", "Hash", ",", "blockConnChanBuffer", ")", "\n\n", "// Reorg data channels", "NtfnChans", ".", "ReorgChanBlockData", "=", "make", "(", "chan", "*", "txhelpers", ".", "ReorgData", ")", "\n", "NtfnChans", ".", "ReorgChanWiredDB", "=", "make", "(", "chan", "*", "txhelpers", ".", "ReorgData", ")", "\n", "NtfnChans", ".", "ReorgChanStakeDB", "=", "make", "(", "chan", "*", "txhelpers", ".", "ReorgData", ")", "\n", "NtfnChans", ".", "ReorgChanDcrpgDB", "=", "make", "(", "chan", "*", "txhelpers", ".", "ReorgData", ")", "\n\n", "// To update app status", "NtfnChans", ".", "UpdateStatusNodeHeight", "=", "make", "(", "chan", "uint32", ",", "blockConnChanBuffer", ")", "\n", "NtfnChans", ".", "UpdateStatusDBHeight", "=", "make", "(", "chan", "uint32", ",", "blockConnChanBuffer", ")", "\n\n", "// watchaddress", "// if len(cfg.WatchAddresses) > 0 {", "// // recv/SpendTxBlockChan come with connected blocks", "// \tNtfnChans.RecvTxBlockChan = make(chan *txhelpers.BlockWatchedTx, blockConnChanBuffer)", "// \tNtfnChans.SpendTxBlockChan = make(chan *txhelpers.BlockWatchedTx, blockConnChanBuffer)", "// \tNtfnChans.RelevantTxMempoolChan = make(chan *dcrutil.Tx, relevantMempoolTxChanBuffer)", "// }", "// New mempool tx chan for general purpose mempool monitor/collector/saver.", "NtfnChans", ".", "NewTxChan", "=", "make", "(", "chan", "*", "dcrjson", ".", "TxRawResult", ",", "newTxChanBuffer", ")", "\n\n", "NtfnChans", ".", "InsightNewTxChan", "=", "make", "(", "chan", "*", "insight", ".", "NewTx", ",", "expNewTxChanBuffer", ")", "\n", "NtfnChans", ".", "ReorgChartsCache", "=", "make", "(", "chan", "*", "txhelpers", ".", "ReorgData", ")", "\n", "}" ]
// MakeNtfnChans create notification channels based on config
[ "MakeNtfnChans", "create", "notification", "channels", "based", "on", "config" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/notification/ntfnchans.go#L52-L91
train
decred/dcrdata
notification/ntfnchans.go
CloseNtfnChans
func CloseNtfnChans() { if NtfnChans.ConnectChan != nil { close(NtfnChans.ConnectChan) } if NtfnChans.ConnectChanWiredDB != nil { close(NtfnChans.ConnectChanWiredDB) } if NtfnChans.ConnectChanStakeDB != nil { close(NtfnChans.ConnectChanStakeDB) } if NtfnChans.ConnectChanDcrpgDB != nil { close(NtfnChans.ConnectChanDcrpgDB) } if NtfnChans.ReorgChanBlockData != nil { close(NtfnChans.ReorgChanBlockData) } if NtfnChans.ReorgChanWiredDB != nil { close(NtfnChans.ReorgChanWiredDB) } if NtfnChans.ReorgChanStakeDB != nil { close(NtfnChans.ReorgChanStakeDB) } if NtfnChans.ReorgChanDcrpgDB != nil { close(NtfnChans.ReorgChanDcrpgDB) } if NtfnChans.UpdateStatusNodeHeight != nil { close(NtfnChans.UpdateStatusNodeHeight) } if NtfnChans.UpdateStatusDBHeight != nil { close(NtfnChans.UpdateStatusDBHeight) } if NtfnChans.NewTxChan != nil { close(NtfnChans.NewTxChan) } if NtfnChans.RelevantTxMempoolChan != nil { close(NtfnChans.RelevantTxMempoolChan) } if NtfnChans.SpendTxBlockChan != nil { close(NtfnChans.SpendTxBlockChan) } if NtfnChans.RecvTxBlockChan != nil { close(NtfnChans.RecvTxBlockChan) } if NtfnChans.InsightNewTxChan != nil { close(NtfnChans.InsightNewTxChan) } if NtfnChans.ReorgChartsCache != nil { close(NtfnChans.ReorgChartsCache) } }
go
func CloseNtfnChans() { if NtfnChans.ConnectChan != nil { close(NtfnChans.ConnectChan) } if NtfnChans.ConnectChanWiredDB != nil { close(NtfnChans.ConnectChanWiredDB) } if NtfnChans.ConnectChanStakeDB != nil { close(NtfnChans.ConnectChanStakeDB) } if NtfnChans.ConnectChanDcrpgDB != nil { close(NtfnChans.ConnectChanDcrpgDB) } if NtfnChans.ReorgChanBlockData != nil { close(NtfnChans.ReorgChanBlockData) } if NtfnChans.ReorgChanWiredDB != nil { close(NtfnChans.ReorgChanWiredDB) } if NtfnChans.ReorgChanStakeDB != nil { close(NtfnChans.ReorgChanStakeDB) } if NtfnChans.ReorgChanDcrpgDB != nil { close(NtfnChans.ReorgChanDcrpgDB) } if NtfnChans.UpdateStatusNodeHeight != nil { close(NtfnChans.UpdateStatusNodeHeight) } if NtfnChans.UpdateStatusDBHeight != nil { close(NtfnChans.UpdateStatusDBHeight) } if NtfnChans.NewTxChan != nil { close(NtfnChans.NewTxChan) } if NtfnChans.RelevantTxMempoolChan != nil { close(NtfnChans.RelevantTxMempoolChan) } if NtfnChans.SpendTxBlockChan != nil { close(NtfnChans.SpendTxBlockChan) } if NtfnChans.RecvTxBlockChan != nil { close(NtfnChans.RecvTxBlockChan) } if NtfnChans.InsightNewTxChan != nil { close(NtfnChans.InsightNewTxChan) } if NtfnChans.ReorgChartsCache != nil { close(NtfnChans.ReorgChartsCache) } }
[ "func", "CloseNtfnChans", "(", ")", "{", "if", "NtfnChans", ".", "ConnectChan", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "ConnectChan", ")", "\n", "}", "\n", "if", "NtfnChans", ".", "ConnectChanWiredDB", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "ConnectChanWiredDB", ")", "\n", "}", "\n", "if", "NtfnChans", ".", "ConnectChanStakeDB", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "ConnectChanStakeDB", ")", "\n", "}", "\n", "if", "NtfnChans", ".", "ConnectChanDcrpgDB", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "ConnectChanDcrpgDB", ")", "\n", "}", "\n\n", "if", "NtfnChans", ".", "ReorgChanBlockData", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "ReorgChanBlockData", ")", "\n", "}", "\n", "if", "NtfnChans", ".", "ReorgChanWiredDB", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "ReorgChanWiredDB", ")", "\n", "}", "\n", "if", "NtfnChans", ".", "ReorgChanStakeDB", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "ReorgChanStakeDB", ")", "\n", "}", "\n", "if", "NtfnChans", ".", "ReorgChanDcrpgDB", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "ReorgChanDcrpgDB", ")", "\n", "}", "\n\n", "if", "NtfnChans", ".", "UpdateStatusNodeHeight", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "UpdateStatusNodeHeight", ")", "\n", "}", "\n", "if", "NtfnChans", ".", "UpdateStatusDBHeight", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "UpdateStatusDBHeight", ")", "\n", "}", "\n\n", "if", "NtfnChans", ".", "NewTxChan", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "NewTxChan", ")", "\n", "}", "\n", "if", "NtfnChans", ".", "RelevantTxMempoolChan", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "RelevantTxMempoolChan", ")", "\n", "}", "\n\n", "if", "NtfnChans", ".", "SpendTxBlockChan", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "SpendTxBlockChan", ")", "\n", "}", "\n", "if", "NtfnChans", ".", "RecvTxBlockChan", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "RecvTxBlockChan", ")", "\n", "}", "\n\n", "if", "NtfnChans", ".", "InsightNewTxChan", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "InsightNewTxChan", ")", "\n", "}", "\n\n", "if", "NtfnChans", ".", "ReorgChartsCache", "!=", "nil", "{", "close", "(", "NtfnChans", ".", "ReorgChartsCache", ")", "\n", "}", "\n", "}" ]
// CloseNtfnChans close all notification channels
[ "CloseNtfnChans", "close", "all", "notification", "channels" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/notification/ntfnchans.go#L94-L149
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
String
func (v CompatibilityAction) String() string { actions := map[CompatibilityAction]string{ compatRebuild: "rebuild", compatUpgrade: "upgrade", compatReindex: "reindex", compatOK: "ok", } if actionStr, ok := actions[v]; ok { return actionStr } return "unknown" }
go
func (v CompatibilityAction) String() string { actions := map[CompatibilityAction]string{ compatRebuild: "rebuild", compatUpgrade: "upgrade", compatReindex: "reindex", compatOK: "ok", } if actionStr, ok := actions[v]; ok { return actionStr } return "unknown" }
[ "func", "(", "v", "CompatibilityAction", ")", "String", "(", ")", "string", "{", "actions", ":=", "map", "[", "CompatibilityAction", "]", "string", "{", "compatRebuild", ":", "\"", "\"", ",", "compatUpgrade", ":", "\"", "\"", ",", "compatReindex", ":", "\"", "\"", ",", "compatOK", ":", "\"", "\"", ",", "}", "\n", "if", "actionStr", ",", "ok", ":=", "actions", "[", "v", "]", ";", "ok", "{", "return", "actionStr", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// String implements Stringer for CompatibilityAction.
[ "String", "implements", "Stringer", "for", "CompatibilityAction", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L93-L104
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
NewTableVersion
func NewTableVersion(major, minor, patch uint32) TableVersion { return TableVersion{major, minor, patch} }
go
func NewTableVersion(major, minor, patch uint32) TableVersion { return TableVersion{major, minor, patch} }
[ "func", "NewTableVersion", "(", "major", ",", "minor", ",", "patch", "uint32", ")", "TableVersion", "{", "return", "TableVersion", "{", "major", ",", "minor", ",", "patch", "}", "\n", "}" ]
// NewTableVersion returns a new TableVersion with the version major.minor.patch
[ "NewTableVersion", "returns", "a", "new", "TableVersion", "with", "the", "version", "major", ".", "minor", ".", "patch" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L107-L109
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
CreateTablesLegacy
func CreateTablesLegacy(db *sql.DB) error { var err error for tableName, createCommand := range createLegacyTableStatements { var exists bool exists, err = TableExists(db, tableName) if err != nil { return err } tableVersion, ok := requiredVersions[tableName] if !ok { return fmt.Errorf("no version assigned to table %s", tableName) } if !exists { log.Infof("Creating the \"%s\" table.", tableName) _, err = db.Exec(createCommand) if err != nil { return err } _, err = db.Exec(fmt.Sprintf(`COMMENT ON TABLE %s IS 'v%s';`, tableName, tableVersion)) if err != nil { return err } } else { log.Tracef("Table \"%s\" exist.", tableName) } } return ClearTestingTable(db) }
go
func CreateTablesLegacy(db *sql.DB) error { var err error for tableName, createCommand := range createLegacyTableStatements { var exists bool exists, err = TableExists(db, tableName) if err != nil { return err } tableVersion, ok := requiredVersions[tableName] if !ok { return fmt.Errorf("no version assigned to table %s", tableName) } if !exists { log.Infof("Creating the \"%s\" table.", tableName) _, err = db.Exec(createCommand) if err != nil { return err } _, err = db.Exec(fmt.Sprintf(`COMMENT ON TABLE %s IS 'v%s';`, tableName, tableVersion)) if err != nil { return err } } else { log.Tracef("Table \"%s\" exist.", tableName) } } return ClearTestingTable(db) }
[ "func", "CreateTablesLegacy", "(", "db", "*", "sql", ".", "DB", ")", "error", "{", "var", "err", "error", "\n", "for", "tableName", ",", "createCommand", ":=", "range", "createLegacyTableStatements", "{", "var", "exists", "bool", "\n", "exists", ",", "err", "=", "TableExists", "(", "db", ",", "tableName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "tableVersion", ",", "ok", ":=", "requiredVersions", "[", "tableName", "]", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tableName", ")", "\n", "}", "\n\n", "if", "!", "exists", "{", "log", ".", "Infof", "(", "\"", "\\\"", "\\\"", "\"", ",", "tableName", ")", "\n", "_", ",", "err", "=", "db", ".", "Exec", "(", "createCommand", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "db", ".", "Exec", "(", "fmt", ".", "Sprintf", "(", "`COMMENT ON TABLE %s IS 'v%s';`", ",", "tableName", ",", "tableVersion", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "log", ".", "Tracef", "(", "\"", "\\\"", "\\\"", "\"", ",", "tableName", ")", "\n", "}", "\n", "}", "\n\n", "return", "ClearTestingTable", "(", "db", ")", "\n", "}" ]
// CreateTablesLegacy creates all tables required by dcrdata if they do not // already exist.
[ "CreateTablesLegacy", "creates", "all", "tables", "required", "by", "dcrdata", "if", "they", "do", "not", "already", "exist", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L142-L173
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
TableUpgradesRequired
func TableUpgradesRequired(versions map[string]TableVersion) []TableUpgrade { var tableUpgrades []TableUpgrade for t := range createLegacyTableStatements { var ok bool var req, act TableVersion if req, ok = requiredVersions[t]; !ok { log.Errorf("required version unknown for table %s", t) tableUpgrades = append(tableUpgrades, TableUpgrade{ TableName: t, UpgradeType: compatUnknown, }) continue } if act, ok = versions[t]; !ok { log.Errorf("current version unknown for table %s", t) tableUpgrades = append(tableUpgrades, TableUpgrade{ TableName: t, UpgradeType: compatRebuild, RequiredVer: req, }) continue } versionCompatibility := TableVersionCompatible(req, act) tableUpgrades = append(tableUpgrades, TableUpgrade{ TableName: t, UpgradeType: versionCompatibility, CurrentVer: act, RequiredVer: req, }) } return tableUpgrades }
go
func TableUpgradesRequired(versions map[string]TableVersion) []TableUpgrade { var tableUpgrades []TableUpgrade for t := range createLegacyTableStatements { var ok bool var req, act TableVersion if req, ok = requiredVersions[t]; !ok { log.Errorf("required version unknown for table %s", t) tableUpgrades = append(tableUpgrades, TableUpgrade{ TableName: t, UpgradeType: compatUnknown, }) continue } if act, ok = versions[t]; !ok { log.Errorf("current version unknown for table %s", t) tableUpgrades = append(tableUpgrades, TableUpgrade{ TableName: t, UpgradeType: compatRebuild, RequiredVer: req, }) continue } versionCompatibility := TableVersionCompatible(req, act) tableUpgrades = append(tableUpgrades, TableUpgrade{ TableName: t, UpgradeType: versionCompatibility, CurrentVer: act, RequiredVer: req, }) } return tableUpgrades }
[ "func", "TableUpgradesRequired", "(", "versions", "map", "[", "string", "]", "TableVersion", ")", "[", "]", "TableUpgrade", "{", "var", "tableUpgrades", "[", "]", "TableUpgrade", "\n", "for", "t", ":=", "range", "createLegacyTableStatements", "{", "var", "ok", "bool", "\n", "var", "req", ",", "act", "TableVersion", "\n", "if", "req", ",", "ok", "=", "requiredVersions", "[", "t", "]", ";", "!", "ok", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "t", ")", "\n", "tableUpgrades", "=", "append", "(", "tableUpgrades", ",", "TableUpgrade", "{", "TableName", ":", "t", ",", "UpgradeType", ":", "compatUnknown", ",", "}", ")", "\n", "continue", "\n", "}", "\n", "if", "act", ",", "ok", "=", "versions", "[", "t", "]", ";", "!", "ok", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "t", ")", "\n", "tableUpgrades", "=", "append", "(", "tableUpgrades", ",", "TableUpgrade", "{", "TableName", ":", "t", ",", "UpgradeType", ":", "compatRebuild", ",", "RequiredVer", ":", "req", ",", "}", ")", "\n", "continue", "\n", "}", "\n", "versionCompatibility", ":=", "TableVersionCompatible", "(", "req", ",", "act", ")", "\n", "tableUpgrades", "=", "append", "(", "tableUpgrades", ",", "TableUpgrade", "{", "TableName", ":", "t", ",", "UpgradeType", ":", "versionCompatibility", ",", "CurrentVer", ":", "act", ",", "RequiredVer", ":", "req", ",", "}", ")", "\n", "}", "\n", "return", "tableUpgrades", "\n", "}" ]
// TableUpgradesRequired builds a list of table upgrade information for each // of the supported auxiliary db tables. The upgrade information includes the // table name, its current & required table versions and the action to be taken // after comparing the current & required versions.
[ "TableUpgradesRequired", "builds", "a", "list", "of", "table", "upgrade", "information", "for", "each", "of", "the", "supported", "auxiliary", "db", "tables", ".", "The", "upgrade", "information", "includes", "the", "table", "name", "its", "current", "&", "required", "table", "versions", "and", "the", "action", "to", "be", "taken", "after", "comparing", "the", "current", "&", "required", "versions", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L215-L246
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
TableVersions
func TableVersions(db *sql.DB) map[string]TableVersion { versions := map[string]TableVersion{} for tableName := range createLegacyTableStatements { // Retrieve the table description. var desc string err := db.QueryRow(`select obj_description($1::regclass);`, tableName).Scan(&desc) if err != nil { log.Errorf("Query of table %s description failed: %v", tableName, err) continue } // Attempt to parse a version out of the table description. sv, err := semver.ParseVersionStr(desc) if err != nil { log.Errorf("Failed to parse version from table description %s: %v", desc, err) continue } versions[tableName] = NewTableVersion(sv.Split()) } return versions }
go
func TableVersions(db *sql.DB) map[string]TableVersion { versions := map[string]TableVersion{} for tableName := range createLegacyTableStatements { // Retrieve the table description. var desc string err := db.QueryRow(`select obj_description($1::regclass);`, tableName).Scan(&desc) if err != nil { log.Errorf("Query of table %s description failed: %v", tableName, err) continue } // Attempt to parse a version out of the table description. sv, err := semver.ParseVersionStr(desc) if err != nil { log.Errorf("Failed to parse version from table description %s: %v", desc, err) continue } versions[tableName] = NewTableVersion(sv.Split()) } return versions }
[ "func", "TableVersions", "(", "db", "*", "sql", ".", "DB", ")", "map", "[", "string", "]", "TableVersion", "{", "versions", ":=", "map", "[", "string", "]", "TableVersion", "{", "}", "\n", "for", "tableName", ":=", "range", "createLegacyTableStatements", "{", "// Retrieve the table description.", "var", "desc", "string", "\n", "err", ":=", "db", ".", "QueryRow", "(", "`select obj_description($1::regclass);`", ",", "tableName", ")", ".", "Scan", "(", "&", "desc", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "tableName", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "// Attempt to parse a version out of the table description.", "sv", ",", "err", ":=", "semver", ".", "ParseVersionStr", "(", "desc", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "desc", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "versions", "[", "tableName", "]", "=", "NewTableVersion", "(", "sv", ".", "Split", "(", ")", ")", "\n", "}", "\n", "return", "versions", "\n", "}" ]
// TableVersions retrieve and maps the tables names in the auxiliary db to their // current table versions.
[ "TableVersions", "retrieve", "and", "maps", "the", "tables", "names", "in", "the", "auxiliary", "db", "to", "their", "current", "table", "versions", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L250-L272
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
VersionCheck
func (pgb *ChainDB) VersionCheck(client BlockGetter) error { vers := TableVersions(pgb.db) for tab, ver := range vers { log.Debugf("Table %s: v%s", tab, ver) } var needsUpgrade []TableUpgrade tableUpgrades := TableUpgradesRequired(vers) for _, val := range tableUpgrades { switch val.UpgradeType { case compatUpgrade, compatReindex: // Select the all tables that need an upgrade or reindex. needsUpgrade = append(needsUpgrade, val) case compatUnknown, compatRebuild: // All the tables require rebuilding. return fmt.Errorf("rebuild of PostgreSQL tables required (drop with rebuilddb2 -D)") } } if len(needsUpgrade) == 0 { // All tables have the correct version. log.Debugf("All tables at correct version (%v)", tableUpgrades[0].RequiredVer) return nil } // UpgradeTables adds the pending db upgrades and reindexes. _, err := pgb.UpgradeTables(client, needsUpgrade[0].CurrentVer, needsUpgrade[0].RequiredVer) if err != nil { return err } // Upgrade was successful. return nil }
go
func (pgb *ChainDB) VersionCheck(client BlockGetter) error { vers := TableVersions(pgb.db) for tab, ver := range vers { log.Debugf("Table %s: v%s", tab, ver) } var needsUpgrade []TableUpgrade tableUpgrades := TableUpgradesRequired(vers) for _, val := range tableUpgrades { switch val.UpgradeType { case compatUpgrade, compatReindex: // Select the all tables that need an upgrade or reindex. needsUpgrade = append(needsUpgrade, val) case compatUnknown, compatRebuild: // All the tables require rebuilding. return fmt.Errorf("rebuild of PostgreSQL tables required (drop with rebuilddb2 -D)") } } if len(needsUpgrade) == 0 { // All tables have the correct version. log.Debugf("All tables at correct version (%v)", tableUpgrades[0].RequiredVer) return nil } // UpgradeTables adds the pending db upgrades and reindexes. _, err := pgb.UpgradeTables(client, needsUpgrade[0].CurrentVer, needsUpgrade[0].RequiredVer) if err != nil { return err } // Upgrade was successful. return nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "VersionCheck", "(", "client", "BlockGetter", ")", "error", "{", "vers", ":=", "TableVersions", "(", "pgb", ".", "db", ")", "\n", "for", "tab", ",", "ver", ":=", "range", "vers", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "tab", ",", "ver", ")", "\n", "}", "\n\n", "var", "needsUpgrade", "[", "]", "TableUpgrade", "\n", "tableUpgrades", ":=", "TableUpgradesRequired", "(", "vers", ")", "\n\n", "for", "_", ",", "val", ":=", "range", "tableUpgrades", "{", "switch", "val", ".", "UpgradeType", "{", "case", "compatUpgrade", ",", "compatReindex", ":", "// Select the all tables that need an upgrade or reindex.", "needsUpgrade", "=", "append", "(", "needsUpgrade", ",", "val", ")", "\n\n", "case", "compatUnknown", ",", "compatRebuild", ":", "// All the tables require rebuilding.", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "needsUpgrade", ")", "==", "0", "{", "// All tables have the correct version.", "log", ".", "Debugf", "(", "\"", "\"", ",", "tableUpgrades", "[", "0", "]", ".", "RequiredVer", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// UpgradeTables adds the pending db upgrades and reindexes.", "_", ",", "err", ":=", "pgb", ".", "UpgradeTables", "(", "client", ",", "needsUpgrade", "[", "0", "]", ".", "CurrentVer", ",", "needsUpgrade", "[", "0", "]", ".", "RequiredVer", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Upgrade was successful.", "return", "nil", "\n", "}" ]
// VersionCheck checks the current version of all known tables and notifies when // an upgrade is required. If there is no automatic upgrade supported, an error // is returned when any table is not of the correct version. An RPC client is // passed to implement the supported upgrades if need be.
[ "VersionCheck", "checks", "the", "current", "version", "of", "all", "known", "tables", "and", "notifies", "when", "an", "upgrade", "is", "required", ".", "If", "there", "is", "no", "automatic", "upgrade", "supported", "an", "error", "is", "returned", "when", "any", "table", "is", "not", "of", "the", "correct", "version", ".", "An", "RPC", "client", "is", "passed", "to", "implement", "the", "supported", "upgrades", "if", "need", "be", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L328-L364
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
initiatePgUpgrade
func (pgb *ChainDB) initiatePgUpgrade(client BlockGetter, theseUpgrades []TableUpgradeType) (bool, error) { for it := range theseUpgrades { upgradeSuccess, err := pgb.handleUpgrades(client, theseUpgrades[it].upgradeType) if err != nil || !upgradeSuccess { return false, fmt.Errorf("failed to upgrade %s table to version %v. Error: %v", theseUpgrades[it].TableName, toVersion, err) } } // A Table upgrade must have happened therefore Bump version if err := versionAllTables(pgb.db, toVersion); err != nil { return false, fmt.Errorf("failed to bump version to %v: %v", toVersion, err) } return true, nil }
go
func (pgb *ChainDB) initiatePgUpgrade(client BlockGetter, theseUpgrades []TableUpgradeType) (bool, error) { for it := range theseUpgrades { upgradeSuccess, err := pgb.handleUpgrades(client, theseUpgrades[it].upgradeType) if err != nil || !upgradeSuccess { return false, fmt.Errorf("failed to upgrade %s table to version %v. Error: %v", theseUpgrades[it].TableName, toVersion, err) } } // A Table upgrade must have happened therefore Bump version if err := versionAllTables(pgb.db, toVersion); err != nil { return false, fmt.Errorf("failed to bump version to %v: %v", toVersion, err) } return true, nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "initiatePgUpgrade", "(", "client", "BlockGetter", ",", "theseUpgrades", "[", "]", "TableUpgradeType", ")", "(", "bool", ",", "error", ")", "{", "for", "it", ":=", "range", "theseUpgrades", "{", "upgradeSuccess", ",", "err", ":=", "pgb", ".", "handleUpgrades", "(", "client", ",", "theseUpgrades", "[", "it", "]", ".", "upgradeType", ")", "\n", "if", "err", "!=", "nil", "||", "!", "upgradeSuccess", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "theseUpgrades", "[", "it", "]", ".", "TableName", ",", "toVersion", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// A Table upgrade must have happened therefore Bump version", "if", "err", ":=", "versionAllTables", "(", "pgb", ".", "db", ",", "toVersion", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "toVersion", ",", "err", ")", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// initiatePgUpgrade starts the specific auxiliary database.
[ "initiatePgUpgrade", "starts", "the", "specific", "auxiliary", "database", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L724-L738
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
dropBlockTimeIndexes
func (pgb *ChainDB) dropBlockTimeIndexes() { log.Info("Dropping block time indexes") err := DeindexBlockTimeOnTableAddress(pgb.db) if err != nil { log.Warnf("DeindexBlockTimeOnTableAddress failed: error: %v", err) } }
go
func (pgb *ChainDB) dropBlockTimeIndexes() { log.Info("Dropping block time indexes") err := DeindexBlockTimeOnTableAddress(pgb.db) if err != nil { log.Warnf("DeindexBlockTimeOnTableAddress failed: error: %v", err) } }
[ "func", "(", "pgb", "*", "ChainDB", ")", "dropBlockTimeIndexes", "(", ")", "{", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "err", ":=", "DeindexBlockTimeOnTableAddress", "(", "pgb", ".", "db", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// dropBlockTimeIndexes drops all indexes that are likely to slow down the db // upgrade.
[ "dropBlockTimeIndexes", "drops", "all", "indexes", "that", "are", "likely", "to", "slow", "down", "the", "db", "upgrade", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1097-L1103
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
createBlockTimeIndexes
func (pgb *ChainDB) createBlockTimeIndexes() { log.Info("Creating the dropped block time indexes") err := IndexBlockTimeOnTableAddress(pgb.db) if err != nil { log.Warnf("IndexBlockTimeOnTableAddress failed: error: %v", err) } }
go
func (pgb *ChainDB) createBlockTimeIndexes() { log.Info("Creating the dropped block time indexes") err := IndexBlockTimeOnTableAddress(pgb.db) if err != nil { log.Warnf("IndexBlockTimeOnTableAddress failed: error: %v", err) } }
[ "func", "(", "pgb", "*", "ChainDB", ")", "createBlockTimeIndexes", "(", ")", "{", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "err", ":=", "IndexBlockTimeOnTableAddress", "(", "pgb", ".", "db", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// CreateBlockTimeIndexes creates back all the dropped indexes.
[ "CreateBlockTimeIndexes", "creates", "back", "all", "the", "dropped", "indexes", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1106-L1112
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
updateAllVotesMainchain
func updateAllVotesMainchain(db *sql.DB) (rowsUpdated int64, err error) { return sqlExec(db, internal.UpdateVotesMainchainAll, "failed to update votes and mainchain status") }
go
func updateAllVotesMainchain(db *sql.DB) (rowsUpdated int64, err error) { return sqlExec(db, internal.UpdateVotesMainchainAll, "failed to update votes and mainchain status") }
[ "func", "updateAllVotesMainchain", "(", "db", "*", "sql", ".", "DB", ")", "(", "rowsUpdated", "int64", ",", "err", "error", ")", "{", "return", "sqlExec", "(", "db", ",", "internal", ".", "UpdateVotesMainchainAll", ",", "\"", "\"", ")", "\n", "}" ]
// updateAllVotesMainchain sets is_mainchain for all votes according to their // containing block.
[ "updateAllVotesMainchain", "sets", "is_mainchain", "for", "all", "votes", "according", "to", "their", "containing", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1360-L1363
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
updateAllTicketsMainchain
func updateAllTicketsMainchain(db *sql.DB) (rowsUpdated int64, err error) { return sqlExec(db, internal.UpdateTicketsMainchainAll, "failed to update tickets and mainchain status") }
go
func updateAllTicketsMainchain(db *sql.DB) (rowsUpdated int64, err error) { return sqlExec(db, internal.UpdateTicketsMainchainAll, "failed to update tickets and mainchain status") }
[ "func", "updateAllTicketsMainchain", "(", "db", "*", "sql", ".", "DB", ")", "(", "rowsUpdated", "int64", ",", "err", "error", ")", "{", "return", "sqlExec", "(", "db", ",", "internal", ".", "UpdateTicketsMainchainAll", ",", "\"", "\"", ")", "\n", "}" ]
// updateAllTicketsMainchain sets is_mainchain for all tickets according to // their containing block.
[ "updateAllTicketsMainchain", "sets", "is_mainchain", "for", "all", "tickets", "according", "to", "their", "containing", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1367-L1370
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
updateAllTxnsValidMainchain
func updateAllTxnsValidMainchain(db *sql.DB) (rowsUpdated int64, err error) { rowsUpdated, err = sqlExec(db, internal.UpdateRegularTxnsValidAll, "failed to update regular transactions' validity status") if err != nil { return } return sqlExec(db, internal.UpdateTxnsMainchainAll, "failed to update all transactions' mainchain status") }
go
func updateAllTxnsValidMainchain(db *sql.DB) (rowsUpdated int64, err error) { rowsUpdated, err = sqlExec(db, internal.UpdateRegularTxnsValidAll, "failed to update regular transactions' validity status") if err != nil { return } return sqlExec(db, internal.UpdateTxnsMainchainAll, "failed to update all transactions' mainchain status") }
[ "func", "updateAllTxnsValidMainchain", "(", "db", "*", "sql", ".", "DB", ")", "(", "rowsUpdated", "int64", ",", "err", "error", ")", "{", "rowsUpdated", ",", "err", "=", "sqlExec", "(", "db", ",", "internal", ".", "UpdateRegularTxnsValidAll", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "sqlExec", "(", "db", ",", "internal", ".", "UpdateTxnsMainchainAll", ",", "\"", "\"", ")", "\n", "}" ]
// updateAllTxnsValidMainchain sets is_mainchain and is_valid for all // transactions according to their containing block.
[ "updateAllTxnsValidMainchain", "sets", "is_mainchain", "and", "is_valid", "for", "all", "transactions", "according", "to", "their", "containing", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1374-L1382
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
updateAllAddressesValidMainchain
func updateAllAddressesValidMainchain(db *sql.DB) (rowsUpdated int64, err error) { return sqlExec(db, internal.UpdateValidMainchainFromTransactions, "failed to update addresses rows valid_mainchain status") }
go
func updateAllAddressesValidMainchain(db *sql.DB) (rowsUpdated int64, err error) { return sqlExec(db, internal.UpdateValidMainchainFromTransactions, "failed to update addresses rows valid_mainchain status") }
[ "func", "updateAllAddressesValidMainchain", "(", "db", "*", "sql", ".", "DB", ")", "(", "rowsUpdated", "int64", ",", "err", "error", ")", "{", "return", "sqlExec", "(", "db", ",", "internal", ".", "UpdateValidMainchainFromTransactions", ",", "\"", "\"", ")", "\n", "}" ]
// updateAllAddressesValidMainchain sets valid_mainchain for all addresses table // rows according to their corresponding transaction.
[ "updateAllAddressesValidMainchain", "sets", "valid_mainchain", "for", "all", "addresses", "table", "rows", "according", "to", "their", "corresponding", "transaction", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1386-L1389
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
updateAddressesValidMainchainPatch
func updateAddressesValidMainchainPatch(db *sql.DB) (rowsUpdated int64, err error) { return sqlExec(db, internal.UpdateAddressesGloballyInvalid, "failed to update addresses rows valid_mainchain status") }
go
func updateAddressesValidMainchainPatch(db *sql.DB) (rowsUpdated int64, err error) { return sqlExec(db, internal.UpdateAddressesGloballyInvalid, "failed to update addresses rows valid_mainchain status") }
[ "func", "updateAddressesValidMainchainPatch", "(", "db", "*", "sql", ".", "DB", ")", "(", "rowsUpdated", "int64", ",", "err", "error", ")", "{", "return", "sqlExec", "(", "db", ",", "internal", ".", "UpdateAddressesGloballyInvalid", ",", "\"", "\"", ")", "\n", "}" ]
// updateAddressesValidMainchainPatch selectively sets valid_mainchain for // addresses table rows that are set incorrectly according to their // corresponding transaction.
[ "updateAddressesValidMainchainPatch", "selectively", "sets", "valid_mainchain", "for", "addresses", "table", "rows", "that", "are", "set", "incorrectly", "according", "to", "their", "corresponding", "transaction", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1394-L1397
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
updateAddressesMatchingTxHashPatch
func updateAddressesMatchingTxHashPatch(db *sql.DB) (rowsUpdated int64, err error) { return sqlExec(db, internal.UpdateAddressesFundingMatchingHash, "failed to update addresses rows matching_tx_hash") }
go
func updateAddressesMatchingTxHashPatch(db *sql.DB) (rowsUpdated int64, err error) { return sqlExec(db, internal.UpdateAddressesFundingMatchingHash, "failed to update addresses rows matching_tx_hash") }
[ "func", "updateAddressesMatchingTxHashPatch", "(", "db", "*", "sql", ".", "DB", ")", "(", "rowsUpdated", "int64", ",", "err", "error", ")", "{", "return", "sqlExec", "(", "db", ",", "internal", ".", "UpdateAddressesFundingMatchingHash", ",", "\"", "\"", ")", "\n", "}" ]
// updateAddressesMatchingTxHashPatch selectively sets matching_tx_hash for // addresses table rows that are set incorrectly according to their // corresponding transaction.
[ "updateAddressesMatchingTxHashPatch", "selectively", "sets", "matching_tx_hash", "for", "addresses", "table", "rows", "that", "are", "set", "incorrectly", "according", "to", "their", "corresponding", "transaction", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1402-L1405
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
handleBlocksTableMainchainUpgrade
func (pgb *ChainDB) handleBlocksTableMainchainUpgrade(bestBlock string) (int64, error) { // Start at best block, upgrade, and move to previous block. Stop after // genesis, which previous block hash is the zero hash. var blocksUpdated int64 previousHash, thisBlockHash := bestBlock, bestBlock for !bytes.Equal(zeroHashStringBytes, []byte(previousHash)) { // set is_mainchain=1 and get previous_hash var err error previousHash, err = SetMainchainByBlockHash(pgb.db, thisBlockHash, true) if err != nil { return blocksUpdated, fmt.Errorf("SetMainchainByBlockHash for block %s failed: %v", thisBlockHash, err) } blocksUpdated++ // genesis is not in the block_chain table. All done! if bytes.Equal(zeroHashStringBytes, []byte(previousHash)) { break } // patch block_chain table err = UpdateBlockNextByHash(pgb.db, previousHash, thisBlockHash) if err != nil { log.Errorf("Failed to update next_hash in block_chain for block %s", previousHash) } thisBlockHash = previousHash } return blocksUpdated, nil }
go
func (pgb *ChainDB) handleBlocksTableMainchainUpgrade(bestBlock string) (int64, error) { // Start at best block, upgrade, and move to previous block. Stop after // genesis, which previous block hash is the zero hash. var blocksUpdated int64 previousHash, thisBlockHash := bestBlock, bestBlock for !bytes.Equal(zeroHashStringBytes, []byte(previousHash)) { // set is_mainchain=1 and get previous_hash var err error previousHash, err = SetMainchainByBlockHash(pgb.db, thisBlockHash, true) if err != nil { return blocksUpdated, fmt.Errorf("SetMainchainByBlockHash for block %s failed: %v", thisBlockHash, err) } blocksUpdated++ // genesis is not in the block_chain table. All done! if bytes.Equal(zeroHashStringBytes, []byte(previousHash)) { break } // patch block_chain table err = UpdateBlockNextByHash(pgb.db, previousHash, thisBlockHash) if err != nil { log.Errorf("Failed to update next_hash in block_chain for block %s", previousHash) } thisBlockHash = previousHash } return blocksUpdated, nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "handleBlocksTableMainchainUpgrade", "(", "bestBlock", "string", ")", "(", "int64", ",", "error", ")", "{", "// Start at best block, upgrade, and move to previous block. Stop after", "// genesis, which previous block hash is the zero hash.", "var", "blocksUpdated", "int64", "\n", "previousHash", ",", "thisBlockHash", ":=", "bestBlock", ",", "bestBlock", "\n", "for", "!", "bytes", ".", "Equal", "(", "zeroHashStringBytes", ",", "[", "]", "byte", "(", "previousHash", ")", ")", "{", "// set is_mainchain=1 and get previous_hash", "var", "err", "error", "\n", "previousHash", ",", "err", "=", "SetMainchainByBlockHash", "(", "pgb", ".", "db", ",", "thisBlockHash", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "blocksUpdated", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "thisBlockHash", ",", "err", ")", "\n", "}", "\n", "blocksUpdated", "++", "\n\n", "// genesis is not in the block_chain table. All done!", "if", "bytes", ".", "Equal", "(", "zeroHashStringBytes", ",", "[", "]", "byte", "(", "previousHash", ")", ")", "{", "break", "\n", "}", "\n\n", "// patch block_chain table", "err", "=", "UpdateBlockNextByHash", "(", "pgb", ".", "db", ",", "previousHash", ",", "thisBlockHash", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "previousHash", ")", "\n", "}", "\n\n", "thisBlockHash", "=", "previousHash", "\n", "}", "\n", "return", "blocksUpdated", ",", "nil", "\n", "}" ]
// handleBlocksTableMainchainUpgrade sets is_mainchain=true for all blocks in // the main chain, starting with the best block and working back to genesis.
[ "handleBlocksTableMainchainUpgrade", "sets", "is_mainchain", "=", "true", "for", "all", "blocks", "in", "the", "main", "chain", "starting", "with", "the", "best", "block", "and", "working", "back", "to", "genesis", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1409-L1438
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
handlevinsTableCoinSupplyUpgrade
func (pgb *ChainDB) handlevinsTableCoinSupplyUpgrade(msgBlock *wire.MsgBlock) (int64, error) { var isValid bool var rowsUpdated int64 var err = pgb.db.QueryRow(`SELECT is_valid, is_mainchain FROM blocks WHERE hash = $1 ;`, msgBlock.BlockHash().String()).Scan(&isValid) if err != nil { return 0, err } // isMainchain does not mater since it is not used in this upgrade. _, _, stakedDbTxVins := dbtypes.ExtractBlockTransactions( msgBlock, wire.TxTreeStake, pgb.chainParams, isValid, false) _, _, regularDbTxVins := dbtypes.ExtractBlockTransactions( msgBlock, wire.TxTreeRegular, pgb.chainParams, isValid, false) dbTxVins := append(stakedDbTxVins, regularDbTxVins...) for _, v := range dbTxVins { for _, s := range v { // does not set is_mainchain result, err := pgb.db.Exec(internal.SetVinsTableCoinSupplyUpgrade, s.IsValid, s.Time, s.ValueIn, s.TxID, s.TxIndex, s.TxTree) if err != nil { return 0, err } c, err := result.RowsAffected() if err != nil { return 0, err } rowsUpdated += c } } return rowsUpdated, nil }
go
func (pgb *ChainDB) handlevinsTableCoinSupplyUpgrade(msgBlock *wire.MsgBlock) (int64, error) { var isValid bool var rowsUpdated int64 var err = pgb.db.QueryRow(`SELECT is_valid, is_mainchain FROM blocks WHERE hash = $1 ;`, msgBlock.BlockHash().String()).Scan(&isValid) if err != nil { return 0, err } // isMainchain does not mater since it is not used in this upgrade. _, _, stakedDbTxVins := dbtypes.ExtractBlockTransactions( msgBlock, wire.TxTreeStake, pgb.chainParams, isValid, false) _, _, regularDbTxVins := dbtypes.ExtractBlockTransactions( msgBlock, wire.TxTreeRegular, pgb.chainParams, isValid, false) dbTxVins := append(stakedDbTxVins, regularDbTxVins...) for _, v := range dbTxVins { for _, s := range v { // does not set is_mainchain result, err := pgb.db.Exec(internal.SetVinsTableCoinSupplyUpgrade, s.IsValid, s.Time, s.ValueIn, s.TxID, s.TxIndex, s.TxTree) if err != nil { return 0, err } c, err := result.RowsAffected() if err != nil { return 0, err } rowsUpdated += c } } return rowsUpdated, nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "handlevinsTableCoinSupplyUpgrade", "(", "msgBlock", "*", "wire", ".", "MsgBlock", ")", "(", "int64", ",", "error", ")", "{", "var", "isValid", "bool", "\n", "var", "rowsUpdated", "int64", "\n\n", "var", "err", "=", "pgb", ".", "db", ".", "QueryRow", "(", "`SELECT is_valid, is_mainchain FROM blocks WHERE hash = $1 ;`", ",", "msgBlock", ".", "BlockHash", "(", ")", ".", "String", "(", ")", ")", ".", "Scan", "(", "&", "isValid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "// isMainchain does not mater since it is not used in this upgrade.", "_", ",", "_", ",", "stakedDbTxVins", ":=", "dbtypes", ".", "ExtractBlockTransactions", "(", "msgBlock", ",", "wire", ".", "TxTreeStake", ",", "pgb", ".", "chainParams", ",", "isValid", ",", "false", ")", "\n", "_", ",", "_", ",", "regularDbTxVins", ":=", "dbtypes", ".", "ExtractBlockTransactions", "(", "msgBlock", ",", "wire", ".", "TxTreeRegular", ",", "pgb", ".", "chainParams", ",", "isValid", ",", "false", ")", "\n", "dbTxVins", ":=", "append", "(", "stakedDbTxVins", ",", "regularDbTxVins", "...", ")", "\n\n", "for", "_", ",", "v", ":=", "range", "dbTxVins", "{", "for", "_", ",", "s", ":=", "range", "v", "{", "// does not set is_mainchain", "result", ",", "err", ":=", "pgb", ".", "db", ".", "Exec", "(", "internal", ".", "SetVinsTableCoinSupplyUpgrade", ",", "s", ".", "IsValid", ",", "s", ".", "Time", ",", "s", ".", "ValueIn", ",", "s", ".", "TxID", ",", "s", ".", "TxIndex", ",", "s", ".", "TxTree", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "c", ",", "err", ":=", "result", ".", "RowsAffected", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "rowsUpdated", "+=", "c", "\n", "}", "\n", "}", "\n", "return", "rowsUpdated", ",", "nil", "\n", "}" ]
// handlevinsTableCoinSupplyUpgrade implements the upgrade to the new newly added columns // in the vins table. The new columns are mainly used for the coin supply chart. // If all the new columns are not added, quit the db upgrade.
[ "handlevinsTableCoinSupplyUpgrade", "implements", "the", "upgrade", "to", "the", "new", "newly", "added", "columns", "in", "the", "vins", "table", ".", "The", "new", "columns", "are", "mainly", "used", "for", "the", "coin", "supply", "chart", ".", "If", "all", "the", "new", "columns", "are", "not", "added", "quit", "the", "db", "upgrade", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1450-L1485
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
handleAgendasTableUpgrade
func (pgb *ChainDB) handleAgendasTableUpgrade(msgBlock *wire.MsgBlock) (int64, error) { // neither isValid or isMainchain are important dbTxns, _, _ := dbtypes.ExtractBlockTransactions(msgBlock, wire.TxTreeStake, pgb.chainParams, true, false) var rowsUpdated int64 for i, tx := range dbTxns { if tx.TxType != int16(stake.TxTypeSSGen) { continue } _, _, _, choices, err := txhelpers.SSGenVoteChoices(msgBlock.STransactions[i], pgb.chainParams) if err != nil { return 0, err } var rowID uint64 for _, val := range choices { // check if agenda id exists, if not it skips to the next agenda id var progress, ok = votingMilestones[val.ID] if !ok { log.Debugf("The Agenda ID: '%s' is unknown", val.ID) continue } var index, err = dbtypes.ChoiceIndexFromStr(val.Choice.Id) if err != nil { return 0, err } err = pgb.db.QueryRow(internal.MakeAgendaInsertStatement(false), val.ID, index, tx.TxID, tx.BlockHeight, tx.BlockTime, progress.VotingDone == tx.BlockHeight, progress.Activated == tx.BlockHeight, progress.HardForked == tx.BlockHeight).Scan(&rowID) if err != nil { return 0, err } rowsUpdated++ } } return rowsUpdated, nil }
go
func (pgb *ChainDB) handleAgendasTableUpgrade(msgBlock *wire.MsgBlock) (int64, error) { // neither isValid or isMainchain are important dbTxns, _, _ := dbtypes.ExtractBlockTransactions(msgBlock, wire.TxTreeStake, pgb.chainParams, true, false) var rowsUpdated int64 for i, tx := range dbTxns { if tx.TxType != int16(stake.TxTypeSSGen) { continue } _, _, _, choices, err := txhelpers.SSGenVoteChoices(msgBlock.STransactions[i], pgb.chainParams) if err != nil { return 0, err } var rowID uint64 for _, val := range choices { // check if agenda id exists, if not it skips to the next agenda id var progress, ok = votingMilestones[val.ID] if !ok { log.Debugf("The Agenda ID: '%s' is unknown", val.ID) continue } var index, err = dbtypes.ChoiceIndexFromStr(val.Choice.Id) if err != nil { return 0, err } err = pgb.db.QueryRow(internal.MakeAgendaInsertStatement(false), val.ID, index, tx.TxID, tx.BlockHeight, tx.BlockTime, progress.VotingDone == tx.BlockHeight, progress.Activated == tx.BlockHeight, progress.HardForked == tx.BlockHeight).Scan(&rowID) if err != nil { return 0, err } rowsUpdated++ } } return rowsUpdated, nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "handleAgendasTableUpgrade", "(", "msgBlock", "*", "wire", ".", "MsgBlock", ")", "(", "int64", ",", "error", ")", "{", "// neither isValid or isMainchain are important", "dbTxns", ",", "_", ",", "_", ":=", "dbtypes", ".", "ExtractBlockTransactions", "(", "msgBlock", ",", "wire", ".", "TxTreeStake", ",", "pgb", ".", "chainParams", ",", "true", ",", "false", ")", "\n\n", "var", "rowsUpdated", "int64", "\n", "for", "i", ",", "tx", ":=", "range", "dbTxns", "{", "if", "tx", ".", "TxType", "!=", "int16", "(", "stake", ".", "TxTypeSSGen", ")", "{", "continue", "\n", "}", "\n", "_", ",", "_", ",", "_", ",", "choices", ",", "err", ":=", "txhelpers", ".", "SSGenVoteChoices", "(", "msgBlock", ".", "STransactions", "[", "i", "]", ",", "pgb", ".", "chainParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "var", "rowID", "uint64", "\n", "for", "_", ",", "val", ":=", "range", "choices", "{", "// check if agenda id exists, if not it skips to the next agenda id", "var", "progress", ",", "ok", "=", "votingMilestones", "[", "val", ".", "ID", "]", "\n", "if", "!", "ok", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "val", ".", "ID", ")", "\n", "continue", "\n", "}", "\n\n", "var", "index", ",", "err", "=", "dbtypes", ".", "ChoiceIndexFromStr", "(", "val", ".", "Choice", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "err", "=", "pgb", ".", "db", ".", "QueryRow", "(", "internal", ".", "MakeAgendaInsertStatement", "(", "false", ")", ",", "val", ".", "ID", ",", "index", ",", "tx", ".", "TxID", ",", "tx", ".", "BlockHeight", ",", "tx", ".", "BlockTime", ",", "progress", ".", "VotingDone", "==", "tx", ".", "BlockHeight", ",", "progress", ".", "Activated", "==", "tx", ".", "BlockHeight", ",", "progress", ".", "HardForked", "==", "tx", ".", "BlockHeight", ")", ".", "Scan", "(", "&", "rowID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "rowsUpdated", "++", "\n", "}", "\n", "}", "\n", "return", "rowsUpdated", ",", "nil", "\n", "}" ]
// handleAgendasTableUpgrade implements the upgrade to the newly added agenda table.
[ "handleAgendasTableUpgrade", "implements", "the", "upgrade", "to", "the", "newly", "added", "agenda", "table", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1488-L1531
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
handleAgendaAndAgendaVotesTablesUpgrade
func (pgb *ChainDB) handleAgendaAndAgendaVotesTablesUpgrade(msgBlock *wire.MsgBlock) (int64, error) { // neither isValid or isMainchain are important dbTxns, _, _ := dbtypes.ExtractBlockTransactions(msgBlock, wire.TxTreeStake, pgb.chainParams, true, false) var rowsUpdated int64 query := `UPDATE votes SET block_time = $3 WHERE tx_hash =$1` + ` AND block_hash = $2 RETURNING id;` for i, tx := range dbTxns { if tx.TxType != int16(stake.TxTypeSSGen) { continue } var voteRowID int64 err := pgb.db.QueryRow(query, tx.TxID, tx.BlockHash, tx.BlockTime).Scan(&voteRowID) if err != nil || voteRowID == 0 { return -1, err } _, _, _, choices, err := txhelpers.SSGenVoteChoices(msgBlock.STransactions[i], pgb.chainParams) if err != nil { return -1, err } var rowID uint64 chainInfo := pgb.ChainInfo() for _, val := range choices { // check if agendas row id is not set then save the agenda details. progress := chainInfo.AgendaMileStones[val.ID] if progress.ID == 0 { err = pgb.db.QueryRow(internal.MakeAgendaInsertStatement(false), val.ID, progress.Status, progress.VotingDone, progress.Activated, progress.HardForked).Scan(&progress.ID) if err != nil { return -1, err } chainInfo.AgendaMileStones[val.ID] = progress } var index, err = dbtypes.ChoiceIndexFromStr(val.Choice.Id) if err != nil { return -1, err } err = pgb.db.QueryRow(internal.MakeAgendaVotesInsertStatement(false), voteRowID, progress.ID, index).Scan(&rowID) if err != nil { return -1, err } rowsUpdated++ } } return rowsUpdated, nil }
go
func (pgb *ChainDB) handleAgendaAndAgendaVotesTablesUpgrade(msgBlock *wire.MsgBlock) (int64, error) { // neither isValid or isMainchain are important dbTxns, _, _ := dbtypes.ExtractBlockTransactions(msgBlock, wire.TxTreeStake, pgb.chainParams, true, false) var rowsUpdated int64 query := `UPDATE votes SET block_time = $3 WHERE tx_hash =$1` + ` AND block_hash = $2 RETURNING id;` for i, tx := range dbTxns { if tx.TxType != int16(stake.TxTypeSSGen) { continue } var voteRowID int64 err := pgb.db.QueryRow(query, tx.TxID, tx.BlockHash, tx.BlockTime).Scan(&voteRowID) if err != nil || voteRowID == 0 { return -1, err } _, _, _, choices, err := txhelpers.SSGenVoteChoices(msgBlock.STransactions[i], pgb.chainParams) if err != nil { return -1, err } var rowID uint64 chainInfo := pgb.ChainInfo() for _, val := range choices { // check if agendas row id is not set then save the agenda details. progress := chainInfo.AgendaMileStones[val.ID] if progress.ID == 0 { err = pgb.db.QueryRow(internal.MakeAgendaInsertStatement(false), val.ID, progress.Status, progress.VotingDone, progress.Activated, progress.HardForked).Scan(&progress.ID) if err != nil { return -1, err } chainInfo.AgendaMileStones[val.ID] = progress } var index, err = dbtypes.ChoiceIndexFromStr(val.Choice.Id) if err != nil { return -1, err } err = pgb.db.QueryRow(internal.MakeAgendaVotesInsertStatement(false), voteRowID, progress.ID, index).Scan(&rowID) if err != nil { return -1, err } rowsUpdated++ } } return rowsUpdated, nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "handleAgendaAndAgendaVotesTablesUpgrade", "(", "msgBlock", "*", "wire", ".", "MsgBlock", ")", "(", "int64", ",", "error", ")", "{", "// neither isValid or isMainchain are important", "dbTxns", ",", "_", ",", "_", ":=", "dbtypes", ".", "ExtractBlockTransactions", "(", "msgBlock", ",", "wire", ".", "TxTreeStake", ",", "pgb", ".", "chainParams", ",", "true", ",", "false", ")", "\n\n", "var", "rowsUpdated", "int64", "\n", "query", ":=", "`UPDATE votes SET block_time = $3 WHERE tx_hash =$1`", "+", "` AND block_hash = $2 RETURNING id;`", "\n\n", "for", "i", ",", "tx", ":=", "range", "dbTxns", "{", "if", "tx", ".", "TxType", "!=", "int16", "(", "stake", ".", "TxTypeSSGen", ")", "{", "continue", "\n", "}", "\n\n", "var", "voteRowID", "int64", "\n", "err", ":=", "pgb", ".", "db", ".", "QueryRow", "(", "query", ",", "tx", ".", "TxID", ",", "tx", ".", "BlockHash", ",", "tx", ".", "BlockTime", ")", ".", "Scan", "(", "&", "voteRowID", ")", "\n", "if", "err", "!=", "nil", "||", "voteRowID", "==", "0", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "_", ",", "_", ",", "_", ",", "choices", ",", "err", ":=", "txhelpers", ".", "SSGenVoteChoices", "(", "msgBlock", ".", "STransactions", "[", "i", "]", ",", "pgb", ".", "chainParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n\n", "var", "rowID", "uint64", "\n", "chainInfo", ":=", "pgb", ".", "ChainInfo", "(", ")", "\n", "for", "_", ",", "val", ":=", "range", "choices", "{", "// check if agendas row id is not set then save the agenda details.", "progress", ":=", "chainInfo", ".", "AgendaMileStones", "[", "val", ".", "ID", "]", "\n", "if", "progress", ".", "ID", "==", "0", "{", "err", "=", "pgb", ".", "db", ".", "QueryRow", "(", "internal", ".", "MakeAgendaInsertStatement", "(", "false", ")", ",", "val", ".", "ID", ",", "progress", ".", "Status", ",", "progress", ".", "VotingDone", ",", "progress", ".", "Activated", ",", "progress", ".", "HardForked", ")", ".", "Scan", "(", "&", "progress", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "chainInfo", ".", "AgendaMileStones", "[", "val", ".", "ID", "]", "=", "progress", "\n", "}", "\n\n", "var", "index", ",", "err", "=", "dbtypes", ".", "ChoiceIndexFromStr", "(", "val", ".", "Choice", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n\n", "err", "=", "pgb", ".", "db", ".", "QueryRow", "(", "internal", ".", "MakeAgendaVotesInsertStatement", "(", "false", ")", ",", "voteRowID", ",", "progress", ".", "ID", ",", "index", ")", ".", "Scan", "(", "&", "rowID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n\n", "rowsUpdated", "++", "\n", "}", "\n", "}", "\n", "return", "rowsUpdated", ",", "nil", "\n", "}" ]
// handleAgendaAndAgendaVotesTableUpgrade restructures the agendas table, creates // a new agenda_votes table and adds a new block time column to votes table.
[ "handleAgendaAndAgendaVotesTableUpgrade", "restructures", "the", "agendas", "table", "creates", "a", "new", "agenda_votes", "table", "and", "adds", "a", "new", "block", "time", "column", "to", "votes", "table", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1535-L1590
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
haveEmptyAgendasTable
func haveEmptyAgendasTable(db *sql.DB) (bool, error) { var isExists int var err = db.QueryRow(`SELECT COUNT(*) FROM agendas;`).Scan(&isExists) if err != nil { return false, err } if isExists != 0 { return false, nil } return true, nil }
go
func haveEmptyAgendasTable(db *sql.DB) (bool, error) { var isExists int var err = db.QueryRow(`SELECT COUNT(*) FROM agendas;`).Scan(&isExists) if err != nil { return false, err } if isExists != 0 { return false, nil } return true, nil }
[ "func", "haveEmptyAgendasTable", "(", "db", "*", "sql", ".", "DB", ")", "(", "bool", ",", "error", ")", "{", "var", "isExists", "int", "\n", "var", "err", "=", "db", ".", "QueryRow", "(", "`SELECT COUNT(*) FROM agendas;`", ")", ".", "Scan", "(", "&", "isExists", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "if", "isExists", "!=", "0", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "return", "true", ",", "nil", "\n", "}" ]
// haveEmptyAgendasTable checks if the agendas table is empty. If the agenda // table exists bool false is returned otherwise bool true is returned. // If the table is not empty then this upgrade doesn't proceed.
[ "haveEmptyAgendasTable", "checks", "if", "the", "agendas", "table", "is", "empty", ".", "If", "the", "agenda", "table", "exists", "bool", "false", "is", "returned", "otherwise", "bool", "true", "is", "returned", ".", "If", "the", "table", "is", "not", "empty", "then", "this", "upgrade", "doesn", "t", "proceed", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1595-L1607
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
versionAllTables
func versionAllTables(db *sql.DB, version TableVersion) error { for tableName := range createLegacyTableStatements { _, err := db.Exec(fmt.Sprintf(`COMMENT ON TABLE %s IS 'v%s';`, tableName, version)) if err != nil { return err } log.Infof("Modified the %v table version to %v", tableName, version) } return nil }
go
func versionAllTables(db *sql.DB, version TableVersion) error { for tableName := range createLegacyTableStatements { _, err := db.Exec(fmt.Sprintf(`COMMENT ON TABLE %s IS 'v%s';`, tableName, version)) if err != nil { return err } log.Infof("Modified the %v table version to %v", tableName, version) } return nil }
[ "func", "versionAllTables", "(", "db", "*", "sql", ".", "DB", ",", "version", "TableVersion", ")", "error", "{", "for", "tableName", ":=", "range", "createLegacyTableStatements", "{", "_", ",", "err", ":=", "db", ".", "Exec", "(", "fmt", ".", "Sprintf", "(", "`COMMENT ON TABLE %s IS 'v%s';`", ",", "tableName", ",", "version", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "tableName", ",", "version", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// versionAllTables comments the tables with the upgraded table version.
[ "versionAllTables", "comments", "the", "tables", "with", "the", "upgraded", "table", "version", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1865-L1876
train
decred/dcrdata
db/dcrpg/upgrades_legacy.go
verifyChainWork
func verifyChainWork(client BlockGetter, db *sql.DB) (int64, error) { // Count rows with missing chainWork. var count int64 countRow := db.QueryRow(`SELECT COUNT(hash) FROM blocks WHERE chainwork = '0';`) err := countRow.Scan(&count) if err != nil { log.Error("Failed to count null chainwork columns: %v", err) return 0, err } if count == 0 { return 0, nil } // Prepare the insertion statement. Parameters: 1. chainwork; 2. blockhash. stmt, err := db.Prepare(`UPDATE blocks SET chainwork=$1 WHERE hash=$2;`) if err != nil { log.Error("Failed to prepare chainwork insertion statement: %v", err) return 0, err } defer stmt.Close() // Grab the blockhashes from rows that don't have chainwork. rows, err := db.Query(`SELECT hash, is_mainchain FROM blocks WHERE chainwork = '0';`) if err != nil { log.Error("Failed to query database for missing chainwork: %v", err) return 0, err } defer rows.Close() var updated int64 tReport := time.Now() for rows.Next() { var hashStr string var isMainchain bool err = rows.Scan(&hashStr, &isMainchain) if err != nil { log.Error("Failed to Scan null chainwork results. Aborting chainwork sync: %v", err) return updated, err } blockHash, err := chainhash.NewHashFromStr(hashStr) if err != nil { log.Errorf("Failed to parse hash from string %s. Aborting chainwork sync.: %v", hashStr, err) return updated, err } chainWork, err := rpcutils.GetChainWork(client, blockHash) if err != nil { // If it's an orphaned block, it may not be in dcrd database. OK to skip. if strings.HasPrefix(err.Error(), "-5: Block not found") { if isMainchain { // Although every mainchain block should have a corresponding // blockNode and chainwork value in drcd, this upgrade is run before // the chain is synced, so it's possible an orphaned block is still // marked mainchain. log.Warnf("No chainwork found for mainchain block %s. Skipping.", hashStr) } updated++ continue } log.Errorf("GetChainWork failed (%s). Aborting chainwork sync.: %v", hashStr, err) return updated, err } _, err = stmt.Exec(chainWork, hashStr) if err != nil { log.Errorf("Failed to insert chainwork (%s) for block %s. Aborting chainwork sync: %v", chainWork, hashStr, err) return updated, err } updated++ // Every two minutes, report the sync status. if updated%100 == 0 && time.Since(tReport) > 2*time.Minute { tReport = time.Now() log.Infof("Chainwork sync is %.1f%% complete.", float64(updated)/float64(count)*100) } } log.Info("Chainwork sync complete.") return updated, nil }
go
func verifyChainWork(client BlockGetter, db *sql.DB) (int64, error) { // Count rows with missing chainWork. var count int64 countRow := db.QueryRow(`SELECT COUNT(hash) FROM blocks WHERE chainwork = '0';`) err := countRow.Scan(&count) if err != nil { log.Error("Failed to count null chainwork columns: %v", err) return 0, err } if count == 0 { return 0, nil } // Prepare the insertion statement. Parameters: 1. chainwork; 2. blockhash. stmt, err := db.Prepare(`UPDATE blocks SET chainwork=$1 WHERE hash=$2;`) if err != nil { log.Error("Failed to prepare chainwork insertion statement: %v", err) return 0, err } defer stmt.Close() // Grab the blockhashes from rows that don't have chainwork. rows, err := db.Query(`SELECT hash, is_mainchain FROM blocks WHERE chainwork = '0';`) if err != nil { log.Error("Failed to query database for missing chainwork: %v", err) return 0, err } defer rows.Close() var updated int64 tReport := time.Now() for rows.Next() { var hashStr string var isMainchain bool err = rows.Scan(&hashStr, &isMainchain) if err != nil { log.Error("Failed to Scan null chainwork results. Aborting chainwork sync: %v", err) return updated, err } blockHash, err := chainhash.NewHashFromStr(hashStr) if err != nil { log.Errorf("Failed to parse hash from string %s. Aborting chainwork sync.: %v", hashStr, err) return updated, err } chainWork, err := rpcutils.GetChainWork(client, blockHash) if err != nil { // If it's an orphaned block, it may not be in dcrd database. OK to skip. if strings.HasPrefix(err.Error(), "-5: Block not found") { if isMainchain { // Although every mainchain block should have a corresponding // blockNode and chainwork value in drcd, this upgrade is run before // the chain is synced, so it's possible an orphaned block is still // marked mainchain. log.Warnf("No chainwork found for mainchain block %s. Skipping.", hashStr) } updated++ continue } log.Errorf("GetChainWork failed (%s). Aborting chainwork sync.: %v", hashStr, err) return updated, err } _, err = stmt.Exec(chainWork, hashStr) if err != nil { log.Errorf("Failed to insert chainwork (%s) for block %s. Aborting chainwork sync: %v", chainWork, hashStr, err) return updated, err } updated++ // Every two minutes, report the sync status. if updated%100 == 0 && time.Since(tReport) > 2*time.Minute { tReport = time.Now() log.Infof("Chainwork sync is %.1f%% complete.", float64(updated)/float64(count)*100) } } log.Info("Chainwork sync complete.") return updated, nil }
[ "func", "verifyChainWork", "(", "client", "BlockGetter", ",", "db", "*", "sql", ".", "DB", ")", "(", "int64", ",", "error", ")", "{", "// Count rows with missing chainWork.", "var", "count", "int64", "\n", "countRow", ":=", "db", ".", "QueryRow", "(", "`SELECT COUNT(hash) FROM blocks WHERE chainwork = '0';`", ")", "\n", "err", ":=", "countRow", ".", "Scan", "(", "&", "count", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "return", "0", ",", "err", "\n", "}", "\n", "if", "count", "==", "0", "{", "return", "0", ",", "nil", "\n", "}", "\n\n", "// Prepare the insertion statement. Parameters: 1. chainwork; 2. blockhash.", "stmt", ",", "err", ":=", "db", ".", "Prepare", "(", "`UPDATE blocks SET chainwork=$1 WHERE hash=$2;`", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "return", "0", ",", "err", "\n", "}", "\n", "defer", "stmt", ".", "Close", "(", ")", "\n\n", "// Grab the blockhashes from rows that don't have chainwork.", "rows", ",", "err", ":=", "db", ".", "Query", "(", "`SELECT hash, is_mainchain FROM blocks WHERE chainwork = '0';`", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "return", "0", ",", "err", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n\n", "var", "updated", "int64", "\n", "tReport", ":=", "time", ".", "Now", "(", ")", "\n", "for", "rows", ".", "Next", "(", ")", "{", "var", "hashStr", "string", "\n", "var", "isMainchain", "bool", "\n", "err", "=", "rows", ".", "Scan", "(", "&", "hashStr", ",", "&", "isMainchain", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "return", "updated", ",", "err", "\n", "}", "\n\n", "blockHash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "hashStr", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "hashStr", ",", "err", ")", "\n", "return", "updated", ",", "err", "\n", "}", "\n\n", "chainWork", ",", "err", ":=", "rpcutils", ".", "GetChainWork", "(", "client", ",", "blockHash", ")", "\n", "if", "err", "!=", "nil", "{", "// If it's an orphaned block, it may not be in dcrd database. OK to skip.", "if", "strings", ".", "HasPrefix", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "if", "isMainchain", "{", "// Although every mainchain block should have a corresponding", "// blockNode and chainwork value in drcd, this upgrade is run before", "// the chain is synced, so it's possible an orphaned block is still", "// marked mainchain.", "log", ".", "Warnf", "(", "\"", "\"", ",", "hashStr", ")", "\n", "}", "\n", "updated", "++", "\n", "continue", "\n", "}", "\n", "log", ".", "Errorf", "(", "\"", "\"", ",", "hashStr", ",", "err", ")", "\n", "return", "updated", ",", "err", "\n", "}", "\n\n", "_", ",", "err", "=", "stmt", ".", "Exec", "(", "chainWork", ",", "hashStr", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "chainWork", ",", "hashStr", ",", "err", ")", "\n", "return", "updated", ",", "err", "\n", "}", "\n", "updated", "++", "\n", "// Every two minutes, report the sync status.", "if", "updated", "%", "100", "==", "0", "&&", "time", ".", "Since", "(", "tReport", ")", ">", "2", "*", "time", ".", "Minute", "{", "tReport", "=", "time", ".", "Now", "(", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "float64", "(", "updated", ")", "/", "float64", "(", "count", ")", "*", "100", ")", "\n", "}", "\n", "}", "\n\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "updated", ",", "nil", "\n", "}" ]
// verifyChainWork fetches and inserts missing chainwork values. // This addresses a table update done at DB version 3.7.0.
[ "verifyChainWork", "fetches", "and", "inserts", "missing", "chainwork", "values", ".", "This", "addresses", "a", "table", "update", "done", "at", "DB", "version", "3", ".", "7", ".", "0", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades_legacy.go#L1880-L1959
train
decred/dcrdata
gov/politeia/types/types.go
VotesStatuses
func VotesStatuses() map[VoteStatusType]string { m := make(map[VoteStatusType]string) for k, val := range ShorterDesc { if k == piapi.PropVoteStatusInvalid || k == piapi.PropVoteStatusDoesntExist { continue } m[VoteStatusType(k)] = val } return m }
go
func VotesStatuses() map[VoteStatusType]string { m := make(map[VoteStatusType]string) for k, val := range ShorterDesc { if k == piapi.PropVoteStatusInvalid || k == piapi.PropVoteStatusDoesntExist { continue } m[VoteStatusType(k)] = val } return m }
[ "func", "VotesStatuses", "(", ")", "map", "[", "VoteStatusType", "]", "string", "{", "m", ":=", "make", "(", "map", "[", "VoteStatusType", "]", "string", ")", "\n", "for", "k", ",", "val", ":=", "range", "ShorterDesc", "{", "if", "k", "==", "piapi", ".", "PropVoteStatusInvalid", "||", "k", "==", "piapi", ".", "PropVoteStatusDoesntExist", "{", "continue", "\n", "}", "\n", "m", "[", "VoteStatusType", "(", "k", ")", "]", "=", "val", "\n", "}", "\n", "return", "m", "\n", "}" ]
// VotesStatuses returns the ShorterDesc map contents exclusive of Invalid and // Doesn't exist statuses.
[ "VotesStatuses", "returns", "the", "ShorterDesc", "map", "contents", "exclusive", "of", "Invalid", "and", "Doesn", "t", "exist", "statuses", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/types/types.go#L181-L191
train
decred/dcrdata
gov/politeia/types/types.go
IsEqual
func (a *ProposalInfo) IsEqual(b *ProposalInfo) bool { if a.CensorshipRecord != b.CensorshipRecord || a.Name != b.Name || a.State != b.State || a.NumComments != b.NumComments || a.StatusChangeMsg != b.StatusChangeMsg || a.Status != b.Status || a.Timestamp != b.Timestamp || a.Token != b.Token || a.CensoredDate != b.CensoredDate || a.AbandonedDate != b.AbandonedDate || a.VoteStatus != b.VoteStatus || a.TotalVotes != b.TotalVotes || a.PublishedDate != b.PublishedDate || len(a.VoteResults) != len(b.VoteResults) { return false } return true }
go
func (a *ProposalInfo) IsEqual(b *ProposalInfo) bool { if a.CensorshipRecord != b.CensorshipRecord || a.Name != b.Name || a.State != b.State || a.NumComments != b.NumComments || a.StatusChangeMsg != b.StatusChangeMsg || a.Status != b.Status || a.Timestamp != b.Timestamp || a.Token != b.Token || a.CensoredDate != b.CensoredDate || a.AbandonedDate != b.AbandonedDate || a.VoteStatus != b.VoteStatus || a.TotalVotes != b.TotalVotes || a.PublishedDate != b.PublishedDate || len(a.VoteResults) != len(b.VoteResults) { return false } return true }
[ "func", "(", "a", "*", "ProposalInfo", ")", "IsEqual", "(", "b", "*", "ProposalInfo", ")", "bool", "{", "if", "a", ".", "CensorshipRecord", "!=", "b", ".", "CensorshipRecord", "||", "a", ".", "Name", "!=", "b", ".", "Name", "||", "a", ".", "State", "!=", "b", ".", "State", "||", "a", ".", "NumComments", "!=", "b", ".", "NumComments", "||", "a", ".", "StatusChangeMsg", "!=", "b", ".", "StatusChangeMsg", "||", "a", ".", "Status", "!=", "b", ".", "Status", "||", "a", ".", "Timestamp", "!=", "b", ".", "Timestamp", "||", "a", ".", "Token", "!=", "b", ".", "Token", "||", "a", ".", "CensoredDate", "!=", "b", ".", "CensoredDate", "||", "a", ".", "AbandonedDate", "!=", "b", ".", "AbandonedDate", "||", "a", ".", "VoteStatus", "!=", "b", ".", "VoteStatus", "||", "a", ".", "TotalVotes", "!=", "b", ".", "TotalVotes", "||", "a", ".", "PublishedDate", "!=", "b", ".", "PublishedDate", "||", "len", "(", "a", ".", "VoteResults", ")", "!=", "len", "(", "b", ".", "VoteResults", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsEqual compares CensorshipRecord, Name, State, NumComments, StatusChangeMsg, // Timestamp, CensoredDate, AbandonedDate, PublishedDate, Token, VoteStatus, // TotalVotes and count of VoteResults between the two ProposalsInfo structs passed.
[ "IsEqual", "compares", "CensorshipRecord", "Name", "State", "NumComments", "StatusChangeMsg", "Timestamp", "CensoredDate", "AbandonedDate", "PublishedDate", "Token", "VoteStatus", "TotalVotes", "and", "count", "of", "VoteResults", "between", "the", "two", "ProposalsInfo", "structs", "passed", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/types/types.go#L196-L206
train
decred/dcrdata
main.go
FileServer
func FileServer(r chi.Router, pathRoot, fsRoot string, cacheControlMaxAge int64) { if strings.ContainsAny(pathRoot, "{}*") { panic("FileServer does not permit URL parameters.") } // Define a http.HandlerFunc to serve files but not directory indexes. hf := func(w http.ResponseWriter, r *http.Request) { // Ensure the path begins with "/". upath := r.URL.Path if strings.Contains(upath, "..") { http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } if !strings.HasPrefix(upath, "/") { upath = "/" + upath r.URL.Path = upath } // Strip the path prefix and clean the path. upath = path.Clean(strings.TrimPrefix(upath, pathRoot)) // Deny directory listings (http.ServeFile recognizes index.html and // attempts to serve the directory contents instead). if strings.HasSuffix(upath, "/index.html") { http.NotFound(w, r) return } // Generate the full file system path and test for existence. fullFilePath := filepath.Join(fsRoot, upath) fi, err := os.Stat(fullFilePath) if err != nil { http.NotFound(w, r) return } // Deny directory listings if fi.IsDir() { http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } http.ServeFile(w, r, fullFilePath) } // For the chi.Mux, make sure a path that ends in "/" and append a "*". muxRoot := pathRoot if pathRoot != "/" && pathRoot[len(pathRoot)-1] != '/' { r.Get(pathRoot, http.RedirectHandler(pathRoot+"/", 301).ServeHTTP) muxRoot += "/" } muxRoot += "*" // Mount the http.HandlerFunc on the pathRoot. r.With(m.CacheControl(cacheControlMaxAge)).Get(muxRoot, hf) }
go
func FileServer(r chi.Router, pathRoot, fsRoot string, cacheControlMaxAge int64) { if strings.ContainsAny(pathRoot, "{}*") { panic("FileServer does not permit URL parameters.") } // Define a http.HandlerFunc to serve files but not directory indexes. hf := func(w http.ResponseWriter, r *http.Request) { // Ensure the path begins with "/". upath := r.URL.Path if strings.Contains(upath, "..") { http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } if !strings.HasPrefix(upath, "/") { upath = "/" + upath r.URL.Path = upath } // Strip the path prefix and clean the path. upath = path.Clean(strings.TrimPrefix(upath, pathRoot)) // Deny directory listings (http.ServeFile recognizes index.html and // attempts to serve the directory contents instead). if strings.HasSuffix(upath, "/index.html") { http.NotFound(w, r) return } // Generate the full file system path and test for existence. fullFilePath := filepath.Join(fsRoot, upath) fi, err := os.Stat(fullFilePath) if err != nil { http.NotFound(w, r) return } // Deny directory listings if fi.IsDir() { http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } http.ServeFile(w, r, fullFilePath) } // For the chi.Mux, make sure a path that ends in "/" and append a "*". muxRoot := pathRoot if pathRoot != "/" && pathRoot[len(pathRoot)-1] != '/' { r.Get(pathRoot, http.RedirectHandler(pathRoot+"/", 301).ServeHTTP) muxRoot += "/" } muxRoot += "*" // Mount the http.HandlerFunc on the pathRoot. r.With(m.CacheControl(cacheControlMaxAge)).Get(muxRoot, hf) }
[ "func", "FileServer", "(", "r", "chi", ".", "Router", ",", "pathRoot", ",", "fsRoot", "string", ",", "cacheControlMaxAge", "int64", ")", "{", "if", "strings", ".", "ContainsAny", "(", "pathRoot", ",", "\"", "\"", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Define a http.HandlerFunc to serve files but not directory indexes.", "hf", ":=", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "// Ensure the path begins with \"/\".", "upath", ":=", "r", ".", "URL", ".", "Path", "\n", "if", "strings", ".", "Contains", "(", "upath", ",", "\"", "\"", ")", "{", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "http", ".", "StatusForbidden", ")", ",", "http", ".", "StatusForbidden", ")", "\n", "return", "\n", "}", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "upath", ",", "\"", "\"", ")", "{", "upath", "=", "\"", "\"", "+", "upath", "\n", "r", ".", "URL", ".", "Path", "=", "upath", "\n", "}", "\n", "// Strip the path prefix and clean the path.", "upath", "=", "path", ".", "Clean", "(", "strings", ".", "TrimPrefix", "(", "upath", ",", "pathRoot", ")", ")", "\n\n", "// Deny directory listings (http.ServeFile recognizes index.html and", "// attempts to serve the directory contents instead).", "if", "strings", ".", "HasSuffix", "(", "upath", ",", "\"", "\"", ")", "{", "http", ".", "NotFound", "(", "w", ",", "r", ")", "\n", "return", "\n", "}", "\n\n", "// Generate the full file system path and test for existence.", "fullFilePath", ":=", "filepath", ".", "Join", "(", "fsRoot", ",", "upath", ")", "\n", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "fullFilePath", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "NotFound", "(", "w", ",", "r", ")", "\n", "return", "\n", "}", "\n\n", "// Deny directory listings", "if", "fi", ".", "IsDir", "(", ")", "{", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "http", ".", "StatusForbidden", ")", ",", "http", ".", "StatusForbidden", ")", "\n", "return", "\n", "}", "\n\n", "http", ".", "ServeFile", "(", "w", ",", "r", ",", "fullFilePath", ")", "\n", "}", "\n\n", "// For the chi.Mux, make sure a path that ends in \"/\" and append a \"*\".", "muxRoot", ":=", "pathRoot", "\n", "if", "pathRoot", "!=", "\"", "\"", "&&", "pathRoot", "[", "len", "(", "pathRoot", ")", "-", "1", "]", "!=", "'/'", "{", "r", ".", "Get", "(", "pathRoot", ",", "http", ".", "RedirectHandler", "(", "pathRoot", "+", "\"", "\"", ",", "301", ")", ".", "ServeHTTP", ")", "\n", "muxRoot", "+=", "\"", "\"", "\n", "}", "\n", "muxRoot", "+=", "\"", "\"", "\n\n", "// Mount the http.HandlerFunc on the pathRoot.", "r", ".", "With", "(", "m", ".", "CacheControl", "(", "cacheControlMaxAge", ")", ")", ".", "Get", "(", "muxRoot", ",", "hf", ")", "\n", "}" ]
// FileServer conveniently sets up a http.FileServer handler to serve static // files from path on the file system. Directory listings are denied, as are URL // paths containing "..".
[ "FileServer", "conveniently", "sets", "up", "a", "http", ".", "FileServer", "handler", "to", "serve", "static", "files", "from", "path", "on", "the", "file", "system", ".", "Directory", "listings", "are", "denied", "as", "are", "URL", "paths", "containing", "..", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/main.go#L1350-L1404
train
decred/dcrdata
api/insight/apimiddleware.go
StatusInfoCtx
func (iapi *InsightApi) StatusInfoCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := m.StatusInfoCtx(r, iapi.BlockData.ChainDB) next.ServeHTTP(w, r.WithContext(ctx)) }) }
go
func (iapi *InsightApi) StatusInfoCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := m.StatusInfoCtx(r, iapi.BlockData.ChainDB) next.ServeHTTP(w, r.WithContext(ctx)) }) }
[ "func", "(", "iapi", "*", "InsightApi", ")", "StatusInfoCtx", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "ctx", ":=", "m", ".", "StatusInfoCtx", "(", "r", ",", "iapi", ".", "BlockData", ".", "ChainDB", ")", "\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ".", "WithContext", "(", "ctx", ")", ")", "\n", "}", ")", "\n\n", "}" ]
// StatusInfoCtx is a middleware that embeds into the request context the data // for the "?q=x" URL query, where x is "getInfo" or "getDifficulty" or // "getBestBlockHash" or "getLastBlockHash".
[ "StatusInfoCtx", "is", "a", "middleware", "that", "embeds", "into", "the", "request", "context", "the", "data", "for", "the", "?q", "=", "x", "URL", "query", "where", "x", "is", "getInfo", "or", "getDifficulty", "or", "getBestBlockHash", "or", "getLastBlockHash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/insight/apimiddleware.go#L46-L52
train
decred/dcrdata
api/insight/apimiddleware.go
ValidatePostCtx
func (iapi *InsightApi) ValidatePostCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { contentLengthString := r.Header.Get("Content-Length") contentLength, err := strconv.Atoi(contentLengthString) if err != nil { writeInsightError(w, "Content-Length Header must be set") return } // Broadcast Tx has the largest possible body. Cap max content length // to iapi.params.MaxTxSize * 2 plus some arbitrary extra for JSON // encapsulation. maxPayload := (iapi.params.MaxTxSize * 2) + 50 if contentLength > maxPayload { writeInsightError(w, fmt.Sprintf("Maximum Content-Length is %d", maxPayload)) return } next.ServeHTTP(w, r) }) }
go
func (iapi *InsightApi) ValidatePostCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { contentLengthString := r.Header.Get("Content-Length") contentLength, err := strconv.Atoi(contentLengthString) if err != nil { writeInsightError(w, "Content-Length Header must be set") return } // Broadcast Tx has the largest possible body. Cap max content length // to iapi.params.MaxTxSize * 2 plus some arbitrary extra for JSON // encapsulation. maxPayload := (iapi.params.MaxTxSize * 2) + 50 if contentLength > maxPayload { writeInsightError(w, fmt.Sprintf("Maximum Content-Length is %d", maxPayload)) return } next.ServeHTTP(w, r) }) }
[ "func", "(", "iapi", "*", "InsightApi", ")", "ValidatePostCtx", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "contentLengthString", ":=", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "contentLength", ",", "err", ":=", "strconv", ".", "Atoi", "(", "contentLengthString", ")", "\n", "if", "err", "!=", "nil", "{", "writeInsightError", "(", "w", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "// Broadcast Tx has the largest possible body. Cap max content length", "// to iapi.params.MaxTxSize * 2 plus some arbitrary extra for JSON", "// encapsulation.", "maxPayload", ":=", "(", "iapi", ".", "params", ".", "MaxTxSize", "*", "2", ")", "+", "50", "\n", "if", "contentLength", ">", "maxPayload", "{", "writeInsightError", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "maxPayload", ")", ")", "\n", "return", "\n", "}", "\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", ")", "\n", "}" ]
// ValidatePostCtx will confirm Post content length is valid.
[ "ValidatePostCtx", "will", "confirm", "Post", "content", "length", "is", "valid", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/insight/apimiddleware.go#L148-L166
train
decred/dcrdata
api/insight/apimiddleware.go
PostAddrsTxsCtx
func PostAddrsTxsCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req apitypes.InsightMultiAddrsTx var from, to, noAsm, noScriptSig, noSpent int64 body, err := ioutil.ReadAll(r.Body) r.Body.Close() if err != nil { writeInsightError(w, fmt.Sprintf("error reading JSON message: %v", err)) return } err = json.Unmarshal(body, &req) if err != nil { writeInsightError(w, fmt.Sprintf("Failed to parse request: %v", err)) return } // Successful extraction of body JSON. ctx := context.WithValue(r.Context(), m.CtxAddress, req.Addresses) if req.From != "" { from, err = req.From.Int64() if err == nil { ctx = context.WithValue(ctx, ctxFrom, int(from)) } } if req.To != "" { to, err = req.To.Int64() if err == nil { ctx = context.WithValue(ctx, ctxTo, int(to)) } } if req.NoAsm != "" { noAsm, err = req.NoAsm.Int64() if err == nil && noAsm != 0 { ctx = context.WithValue(ctx, ctxNoAsm, true) } } if req.NoScriptSig != "" { noScriptSig, err = req.NoScriptSig.Int64() if err == nil && noScriptSig != 0 { ctx = context.WithValue(ctx, ctxNoScriptSig, true) } } if req.NoSpent != "" { noSpent, err = req.NoSpent.Int64() if err == nil && noSpent != 0 { ctx = context.WithValue(ctx, ctxNoSpent, true) } } next.ServeHTTP(w, r.WithContext(ctx)) }) }
go
func PostAddrsTxsCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req apitypes.InsightMultiAddrsTx var from, to, noAsm, noScriptSig, noSpent int64 body, err := ioutil.ReadAll(r.Body) r.Body.Close() if err != nil { writeInsightError(w, fmt.Sprintf("error reading JSON message: %v", err)) return } err = json.Unmarshal(body, &req) if err != nil { writeInsightError(w, fmt.Sprintf("Failed to parse request: %v", err)) return } // Successful extraction of body JSON. ctx := context.WithValue(r.Context(), m.CtxAddress, req.Addresses) if req.From != "" { from, err = req.From.Int64() if err == nil { ctx = context.WithValue(ctx, ctxFrom, int(from)) } } if req.To != "" { to, err = req.To.Int64() if err == nil { ctx = context.WithValue(ctx, ctxTo, int(to)) } } if req.NoAsm != "" { noAsm, err = req.NoAsm.Int64() if err == nil && noAsm != 0 { ctx = context.WithValue(ctx, ctxNoAsm, true) } } if req.NoScriptSig != "" { noScriptSig, err = req.NoScriptSig.Int64() if err == nil && noScriptSig != 0 { ctx = context.WithValue(ctx, ctxNoScriptSig, true) } } if req.NoSpent != "" { noSpent, err = req.NoSpent.Int64() if err == nil && noSpent != 0 { ctx = context.WithValue(ctx, ctxNoSpent, true) } } next.ServeHTTP(w, r.WithContext(ctx)) }) }
[ "func", "PostAddrsTxsCtx", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "var", "req", "apitypes", ".", "InsightMultiAddrsTx", "\n", "var", "from", ",", "to", ",", "noAsm", ",", "noScriptSig", ",", "noSpent", "int64", "\n\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ".", "Body", ")", "\n", "r", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "writeInsightError", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "writeInsightError", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n", "// Successful extraction of body JSON.", "ctx", ":=", "context", ".", "WithValue", "(", "r", ".", "Context", "(", ")", ",", "m", ".", "CtxAddress", ",", "req", ".", "Addresses", ")", "\n\n", "if", "req", ".", "From", "!=", "\"", "\"", "{", "from", ",", "err", "=", "req", ".", "From", ".", "Int64", "(", ")", "\n", "if", "err", "==", "nil", "{", "ctx", "=", "context", ".", "WithValue", "(", "ctx", ",", "ctxFrom", ",", "int", "(", "from", ")", ")", "\n", "}", "\n", "}", "\n", "if", "req", ".", "To", "!=", "\"", "\"", "{", "to", ",", "err", "=", "req", ".", "To", ".", "Int64", "(", ")", "\n", "if", "err", "==", "nil", "{", "ctx", "=", "context", ".", "WithValue", "(", "ctx", ",", "ctxTo", ",", "int", "(", "to", ")", ")", "\n", "}", "\n", "}", "\n", "if", "req", ".", "NoAsm", "!=", "\"", "\"", "{", "noAsm", ",", "err", "=", "req", ".", "NoAsm", ".", "Int64", "(", ")", "\n", "if", "err", "==", "nil", "&&", "noAsm", "!=", "0", "{", "ctx", "=", "context", ".", "WithValue", "(", "ctx", ",", "ctxNoAsm", ",", "true", ")", "\n", "}", "\n", "}", "\n", "if", "req", ".", "NoScriptSig", "!=", "\"", "\"", "{", "noScriptSig", ",", "err", "=", "req", ".", "NoScriptSig", ".", "Int64", "(", ")", "\n", "if", "err", "==", "nil", "&&", "noScriptSig", "!=", "0", "{", "ctx", "=", "context", ".", "WithValue", "(", "ctx", ",", "ctxNoScriptSig", ",", "true", ")", "\n", "}", "\n", "}", "\n\n", "if", "req", ".", "NoSpent", "!=", "\"", "\"", "{", "noSpent", ",", "err", "=", "req", ".", "NoSpent", ".", "Int64", "(", ")", "\n", "if", "err", "==", "nil", "&&", "noSpent", "!=", "0", "{", "ctx", "=", "context", ".", "WithValue", "(", "ctx", ",", "ctxNoSpent", ",", "true", ")", "\n", "}", "\n", "}", "\n\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ".", "WithContext", "(", "ctx", ")", ")", "\n", "}", ")", "\n", "}" ]
// PostAddrsTxsCtx middleware processes parameters given in the POST request // body for an addrs endpoint.
[ "PostAddrsTxsCtx", "middleware", "processes", "parameters", "given", "in", "the", "POST", "request", "body", "for", "an", "addrs", "endpoint", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/insight/apimiddleware.go#L170-L223
train
decred/dcrdata
api/insight/apimiddleware.go
PostAddrsUtxoCtx
func PostAddrsUtxoCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { req := apitypes.InsightAddr{} body, err := ioutil.ReadAll(r.Body) r.Body.Close() if err != nil { writeInsightError(w, fmt.Sprintf("error reading JSON message: %v", err)) return } err = json.Unmarshal(body, &req) if err != nil { writeInsightError(w, fmt.Sprintf("Failed to parse request: %v", err)) return } // Successful extraction of Body JSON ctx := context.WithValue(r.Context(), m.CtxAddress, req.Addrs) next.ServeHTTP(w, r.WithContext(ctx)) }) }
go
func PostAddrsUtxoCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { req := apitypes.InsightAddr{} body, err := ioutil.ReadAll(r.Body) r.Body.Close() if err != nil { writeInsightError(w, fmt.Sprintf("error reading JSON message: %v", err)) return } err = json.Unmarshal(body, &req) if err != nil { writeInsightError(w, fmt.Sprintf("Failed to parse request: %v", err)) return } // Successful extraction of Body JSON ctx := context.WithValue(r.Context(), m.CtxAddress, req.Addrs) next.ServeHTTP(w, r.WithContext(ctx)) }) }
[ "func", "PostAddrsUtxoCtx", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "req", ":=", "apitypes", ".", "InsightAddr", "{", "}", "\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ".", "Body", ")", "\n", "r", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "writeInsightError", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "writeInsightError", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n\n", "// Successful extraction of Body JSON", "ctx", ":=", "context", ".", "WithValue", "(", "r", ".", "Context", "(", ")", ",", "m", ".", "CtxAddress", ",", "req", ".", "Addrs", ")", "\n\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ".", "WithContext", "(", "ctx", ")", ")", "\n", "}", ")", "\n", "}" ]
// PostAddrsUtxoCtx middleware processes parameters given in the POST request // body for an addrs utxo endpoint.
[ "PostAddrsUtxoCtx", "middleware", "processes", "parameters", "given", "in", "the", "POST", "request", "body", "for", "an", "addrs", "utxo", "endpoint", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/insight/apimiddleware.go#L227-L248
train
decred/dcrdata
api/insight/apimiddleware.go
GetAddressCommandCtx
func GetAddressCommandCtx(r *http.Request) (string, bool) { command, ok := r.Context().Value(ctxAddrCmd).(string) if !ok { return "", false } return command, true }
go
func GetAddressCommandCtx(r *http.Request) (string, bool) { command, ok := r.Context().Value(ctxAddrCmd).(string) if !ok { return "", false } return command, true }
[ "func", "GetAddressCommandCtx", "(", "r", "*", "http", ".", "Request", ")", "(", "string", ",", "bool", ")", "{", "command", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxAddrCmd", ")", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "false", "\n", "}", "\n", "return", "command", ",", "true", "\n", "}" ]
// GetAddressCommandCtx retrieves the ctxAddrCmd data from the request context. // If not set the return value is "" and false.
[ "GetAddressCommandCtx", "retrieves", "the", "ctxAddrCmd", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "and", "false", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/insight/apimiddleware.go#L262-L268
train
decred/dcrdata
api/insight/apimiddleware.go
GetLimitCtx
func GetLimitCtx(r *http.Request) int { limit, ok := r.Context().Value(m.CtxLimit).(string) if !ok { return 0 } intValue, err := strconv.Atoi(limit) if err != nil { return 0 } return intValue }
go
func GetLimitCtx(r *http.Request) int { limit, ok := r.Context().Value(m.CtxLimit).(string) if !ok { return 0 } intValue, err := strconv.Atoi(limit) if err != nil { return 0 } return intValue }
[ "func", "GetLimitCtx", "(", "r", "*", "http", ".", "Request", ")", "int", "{", "limit", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "m", ".", "CtxLimit", ")", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "0", "\n", "}", "\n", "intValue", ",", "err", ":=", "strconv", ".", "Atoi", "(", "limit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", "\n", "}", "\n", "return", "intValue", "\n", "}" ]
// GetLimitCtx retrieves the ctxLimit data from the request context. If not set, // the return value is 0 which is interpreted as no limit.
[ "GetLimitCtx", "retrieves", "the", "ctxLimit", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "0", "which", "is", "interpreted", "as", "no", "limit", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/insight/apimiddleware.go#L286-L296
train
decred/dcrdata
api/insight/apimiddleware.go
GetNbBlocksCtx
func GetNbBlocksCtx(r *http.Request) int { nbBlocks, ok := r.Context().Value(ctxNbBlocks).(int) if !ok { return 0 } return nbBlocks }
go
func GetNbBlocksCtx(r *http.Request) int { nbBlocks, ok := r.Context().Value(ctxNbBlocks).(int) if !ok { return 0 } return nbBlocks }
[ "func", "GetNbBlocksCtx", "(", "r", "*", "http", ".", "Request", ")", "int", "{", "nbBlocks", ",", "ok", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "ctxNbBlocks", ")", ".", "(", "int", ")", "\n", "if", "!", "ok", "{", "return", "0", "\n", "}", "\n", "return", "nbBlocks", "\n", "}" ]
// GetNbBlocksCtx retrieves the ctxNbBlocks data from the request context. If not // set, the return value is 0.
[ "GetNbBlocksCtx", "retrieves", "the", "ctxNbBlocks", "data", "from", "the", "request", "context", ".", "If", "not", "set", "the", "return", "value", "is", "0", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/insight/apimiddleware.go#L322-L328
train
decred/dcrdata
api/insight/apimiddleware.go
NbBlocksCtx
func NbBlocksCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() nbBlocks := r.FormValue("nbBlocks") nbBlocksint, err := strconv.Atoi(nbBlocks) if err == nil { ctx = context.WithValue(r.Context(), ctxNbBlocks, nbBlocksint) } next.ServeHTTP(w, r.WithContext(ctx)) }) }
go
func NbBlocksCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() nbBlocks := r.FormValue("nbBlocks") nbBlocksint, err := strconv.Atoi(nbBlocks) if err == nil { ctx = context.WithValue(r.Context(), ctxNbBlocks, nbBlocksint) } next.ServeHTTP(w, r.WithContext(ctx)) }) }
[ "func", "NbBlocksCtx", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "ctx", ":=", "r", ".", "Context", "(", ")", "\n", "nbBlocks", ":=", "r", ".", "FormValue", "(", "\"", "\"", ")", "\n", "nbBlocksint", ",", "err", ":=", "strconv", ".", "Atoi", "(", "nbBlocks", ")", "\n", "if", "err", "==", "nil", "{", "ctx", "=", "context", ".", "WithValue", "(", "r", ".", "Context", "(", ")", ",", "ctxNbBlocks", ",", "nbBlocksint", ")", "\n", "}", "\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ".", "WithContext", "(", "ctx", ")", ")", "\n", "}", ")", "\n", "}" ]
// NbBlocksCtx will parse the query parameters for nbBlocks.
[ "NbBlocksCtx", "will", "parse", "the", "query", "parameters", "for", "nbBlocks", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/insight/apimiddleware.go#L331-L341
train
decred/dcrdata
mempool/monitor.go
NewMempoolMonitor
func NewMempoolMonitor(ctx context.Context, collector *MempoolDataCollector, savers []MempoolDataSaver, params *chaincfg.Params, wg *sync.WaitGroup, newTxInChan <-chan *dcrjson.TxRawResult, signalOuts []chan<- pstypes.HubMessage, initialStore bool) (*MempoolMonitor, error) { // Make the skeleton MempoolMonitor. p := &MempoolMonitor{ ctx: ctx, params: params, collector: collector, dataSavers: savers, newTxIn: newTxInChan, signalOuts: signalOuts, wg: wg, } if initialStore { return p, p.CollectAndStore() } _, _, _, err := p.Refresh() return p, err }
go
func NewMempoolMonitor(ctx context.Context, collector *MempoolDataCollector, savers []MempoolDataSaver, params *chaincfg.Params, wg *sync.WaitGroup, newTxInChan <-chan *dcrjson.TxRawResult, signalOuts []chan<- pstypes.HubMessage, initialStore bool) (*MempoolMonitor, error) { // Make the skeleton MempoolMonitor. p := &MempoolMonitor{ ctx: ctx, params: params, collector: collector, dataSavers: savers, newTxIn: newTxInChan, signalOuts: signalOuts, wg: wg, } if initialStore { return p, p.CollectAndStore() } _, _, _, err := p.Refresh() return p, err }
[ "func", "NewMempoolMonitor", "(", "ctx", "context", ".", "Context", ",", "collector", "*", "MempoolDataCollector", ",", "savers", "[", "]", "MempoolDataSaver", ",", "params", "*", "chaincfg", ".", "Params", ",", "wg", "*", "sync", ".", "WaitGroup", ",", "newTxInChan", "<-", "chan", "*", "dcrjson", ".", "TxRawResult", ",", "signalOuts", "[", "]", "chan", "<-", "pstypes", ".", "HubMessage", ",", "initialStore", "bool", ")", "(", "*", "MempoolMonitor", ",", "error", ")", "{", "// Make the skeleton MempoolMonitor.", "p", ":=", "&", "MempoolMonitor", "{", "ctx", ":", "ctx", ",", "params", ":", "params", ",", "collector", ":", "collector", ",", "dataSavers", ":", "savers", ",", "newTxIn", ":", "newTxInChan", ",", "signalOuts", ":", "signalOuts", ",", "wg", ":", "wg", ",", "}", "\n\n", "if", "initialStore", "{", "return", "p", ",", "p", ".", "CollectAndStore", "(", ")", "\n", "}", "\n", "_", ",", "_", ",", "_", ",", "err", ":=", "p", ".", "Refresh", "(", ")", "\n", "return", "p", ",", "err", "\n", "}" ]
// NewMempoolMonitor creates a new MempoolMonitor. The MempoolMonitor receives // notifications of new transactions on newTxInChan, and of new blocks on the // same channel using a nil transaction message. Once TxHandler is started, the // MempoolMonitor will process incoming transactions, and forward new ones on // via the newTxOutChan following an appropriate signal on hubRelay.
[ "NewMempoolMonitor", "creates", "a", "new", "MempoolMonitor", ".", "The", "MempoolMonitor", "receives", "notifications", "of", "new", "transactions", "on", "newTxInChan", "and", "of", "new", "blocks", "on", "the", "same", "channel", "using", "a", "nil", "transaction", "message", ".", "Once", "TxHandler", "is", "started", "the", "MempoolMonitor", "will", "process", "incoming", "transactions", "and", "forward", "new", "ones", "on", "via", "the", "newTxOutChan", "following", "an", "appropriate", "signal", "on", "hubRelay", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/monitor.go#L72-L93
train
decred/dcrdata
mempool/monitor.go
LastBlockHash
func (p *MempoolMonitor) LastBlockHash() chainhash.Hash { p.mtx.RLock() defer p.mtx.RUnlock() return p.lastBlock.Hash }
go
func (p *MempoolMonitor) LastBlockHash() chainhash.Hash { p.mtx.RLock() defer p.mtx.RUnlock() return p.lastBlock.Hash }
[ "func", "(", "p", "*", "MempoolMonitor", ")", "LastBlockHash", "(", ")", "chainhash", ".", "Hash", "{", "p", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "p", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "p", ".", "lastBlock", ".", "Hash", "\n", "}" ]
// LastBlockHash returns the hash of the most recently stored block.
[ "LastBlockHash", "returns", "the", "hash", "of", "the", "most", "recently", "stored", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/monitor.go#L96-L100
train
decred/dcrdata
mempool/monitor.go
LastBlockHeight
func (p *MempoolMonitor) LastBlockHeight() int64 { p.mtx.RLock() defer p.mtx.RUnlock() return p.lastBlock.Height }
go
func (p *MempoolMonitor) LastBlockHeight() int64 { p.mtx.RLock() defer p.mtx.RUnlock() return p.lastBlock.Height }
[ "func", "(", "p", "*", "MempoolMonitor", ")", "LastBlockHeight", "(", ")", "int64", "{", "p", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "p", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "p", ".", "lastBlock", ".", "Height", "\n", "}" ]
// LastBlockHeight returns the height of the most recently stored block.
[ "LastBlockHeight", "returns", "the", "height", "of", "the", "most", "recently", "stored", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/monitor.go#L103-L107
train
decred/dcrdata
mempool/monitor.go
LastBlockTime
func (p *MempoolMonitor) LastBlockTime() int64 { p.mtx.RLock() defer p.mtx.RUnlock() return p.lastBlock.Time }
go
func (p *MempoolMonitor) LastBlockTime() int64 { p.mtx.RLock() defer p.mtx.RUnlock() return p.lastBlock.Time }
[ "func", "(", "p", "*", "MempoolMonitor", ")", "LastBlockTime", "(", ")", "int64", "{", "p", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "p", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "p", ".", "lastBlock", ".", "Time", "\n", "}" ]
// LastBlockTime returns the time of the most recently stored block.
[ "LastBlockTime", "returns", "the", "time", "of", "the", "most", "recently", "stored", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/monitor.go#L110-L114
train
decred/dcrdata
mempool/monitor.go
Refresh
func (p *MempoolMonitor) Refresh() (*StakeData, []exptypes.MempoolTx, *exptypes.MempoolInfo, error) { // Collect mempool data (currently ticket fees) log.Trace("Gathering new mempool data.") stakeData, txs, addrOuts, txnsStore, err := p.collector.Collect() if err != nil { log.Errorf("mempool data collection failed: %v", err.Error()) // stakeData is nil when err != nil return nil, nil, nil, err } log.Debugf("%d addresses in mempool pertaining to %d transactions", len(addrOuts), len(txnsStore)) // Pre-sort the txs so other consumers will not have to do it. sort.Sort(exptypes.MPTxsByTime(txs)) inventory := ParseTxns(txs, p.params, &stakeData.LatestBlock) // Reset the counter for tickets since last report. p.mtx.Lock() newTickets := p.mpoolInfo.NumTicketsSinceStatsReport p.mpoolInfo.NumTicketsSinceStatsReport = 0 // Reset the timer and ticket counter. p.mpoolInfo.CurrentHeight = uint32(stakeData.LatestBlock.Height) p.mpoolInfo.LastCollectTime = stakeData.Time p.mpoolInfo.NumTicketPurchasesInMempool = stakeData.Ticketfees.FeeInfoMempool.Number // Store the current best block info. p.lastBlock = stakeData.LatestBlock if p.inventory != nil { inventory.Ident = p.inventory.ID() + 1 } p.inventory = inventory p.txnsStore = txnsStore p.mtx.Unlock() p.addrMap.mtx.Lock() p.addrMap.store = addrOuts p.addrMap.mtx.Unlock() // Insert new ticket counter into stakeData structure. stakeData.NewTickets = uint32(newTickets) return stakeData, txs, inventory, err }
go
func (p *MempoolMonitor) Refresh() (*StakeData, []exptypes.MempoolTx, *exptypes.MempoolInfo, error) { // Collect mempool data (currently ticket fees) log.Trace("Gathering new mempool data.") stakeData, txs, addrOuts, txnsStore, err := p.collector.Collect() if err != nil { log.Errorf("mempool data collection failed: %v", err.Error()) // stakeData is nil when err != nil return nil, nil, nil, err } log.Debugf("%d addresses in mempool pertaining to %d transactions", len(addrOuts), len(txnsStore)) // Pre-sort the txs so other consumers will not have to do it. sort.Sort(exptypes.MPTxsByTime(txs)) inventory := ParseTxns(txs, p.params, &stakeData.LatestBlock) // Reset the counter for tickets since last report. p.mtx.Lock() newTickets := p.mpoolInfo.NumTicketsSinceStatsReport p.mpoolInfo.NumTicketsSinceStatsReport = 0 // Reset the timer and ticket counter. p.mpoolInfo.CurrentHeight = uint32(stakeData.LatestBlock.Height) p.mpoolInfo.LastCollectTime = stakeData.Time p.mpoolInfo.NumTicketPurchasesInMempool = stakeData.Ticketfees.FeeInfoMempool.Number // Store the current best block info. p.lastBlock = stakeData.LatestBlock if p.inventory != nil { inventory.Ident = p.inventory.ID() + 1 } p.inventory = inventory p.txnsStore = txnsStore p.mtx.Unlock() p.addrMap.mtx.Lock() p.addrMap.store = addrOuts p.addrMap.mtx.Unlock() // Insert new ticket counter into stakeData structure. stakeData.NewTickets = uint32(newTickets) return stakeData, txs, inventory, err }
[ "func", "(", "p", "*", "MempoolMonitor", ")", "Refresh", "(", ")", "(", "*", "StakeData", ",", "[", "]", "exptypes", ".", "MempoolTx", ",", "*", "exptypes", ".", "MempoolInfo", ",", "error", ")", "{", "// Collect mempool data (currently ticket fees)", "log", ".", "Trace", "(", "\"", "\"", ")", "\n", "stakeData", ",", "txs", ",", "addrOuts", ",", "txnsStore", ",", "err", ":=", "p", ".", "collector", ".", "Collect", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "// stakeData is nil when err != nil", "return", "nil", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "len", "(", "addrOuts", ")", ",", "len", "(", "txnsStore", ")", ")", "\n\n", "// Pre-sort the txs so other consumers will not have to do it.", "sort", ".", "Sort", "(", "exptypes", ".", "MPTxsByTime", "(", "txs", ")", ")", "\n", "inventory", ":=", "ParseTxns", "(", "txs", ",", "p", ".", "params", ",", "&", "stakeData", ".", "LatestBlock", ")", "\n\n", "// Reset the counter for tickets since last report.", "p", ".", "mtx", ".", "Lock", "(", ")", "\n", "newTickets", ":=", "p", ".", "mpoolInfo", ".", "NumTicketsSinceStatsReport", "\n", "p", ".", "mpoolInfo", ".", "NumTicketsSinceStatsReport", "=", "0", "\n\n", "// Reset the timer and ticket counter.", "p", ".", "mpoolInfo", ".", "CurrentHeight", "=", "uint32", "(", "stakeData", ".", "LatestBlock", ".", "Height", ")", "\n", "p", ".", "mpoolInfo", ".", "LastCollectTime", "=", "stakeData", ".", "Time", "\n", "p", ".", "mpoolInfo", ".", "NumTicketPurchasesInMempool", "=", "stakeData", ".", "Ticketfees", ".", "FeeInfoMempool", ".", "Number", "\n\n", "// Store the current best block info.", "p", ".", "lastBlock", "=", "stakeData", ".", "LatestBlock", "\n", "if", "p", ".", "inventory", "!=", "nil", "{", "inventory", ".", "Ident", "=", "p", ".", "inventory", ".", "ID", "(", ")", "+", "1", "\n", "}", "\n", "p", ".", "inventory", "=", "inventory", "\n", "p", ".", "txnsStore", "=", "txnsStore", "\n", "p", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "p", ".", "addrMap", ".", "mtx", ".", "Lock", "(", ")", "\n", "p", ".", "addrMap", ".", "store", "=", "addrOuts", "\n", "p", ".", "addrMap", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// Insert new ticket counter into stakeData structure.", "stakeData", ".", "NewTickets", "=", "uint32", "(", "newTickets", ")", "\n\n", "return", "stakeData", ",", "txs", ",", "inventory", ",", "err", "\n", "}" ]
// Refresh collects mempool data, resets counters ticket counters and the timer, // but does not dispatch the MempoolDataSavers.
[ "Refresh", "collects", "mempool", "data", "resets", "counters", "ticket", "counters", "and", "the", "timer", "but", "does", "not", "dispatch", "the", "MempoolDataSavers", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/monitor.go#L368-L412
train
decred/dcrdata
mempool/monitor.go
CollectAndStore
func (p *MempoolMonitor) CollectAndStore() error { log.Trace("Gathering new mempool data.") stakeData, txs, inv, err := p.Refresh() if err != nil { log.Errorf("mempool data collection failed: %v", err.Error()) // stakeData is nil when err != nil return err } // Store mempool stakeData with each registered saver. for _, s := range p.dataSavers { if s != nil { log.Trace("Saving MP data.") // Save data to wherever the saver wants to put it. // Deep copy the txs slice so each saver can modify it. txsCopy := exptypes.CopyMempoolTxSlice(txs) go s.StoreMPData(stakeData, txsCopy, inv) } } return nil }
go
func (p *MempoolMonitor) CollectAndStore() error { log.Trace("Gathering new mempool data.") stakeData, txs, inv, err := p.Refresh() if err != nil { log.Errorf("mempool data collection failed: %v", err.Error()) // stakeData is nil when err != nil return err } // Store mempool stakeData with each registered saver. for _, s := range p.dataSavers { if s != nil { log.Trace("Saving MP data.") // Save data to wherever the saver wants to put it. // Deep copy the txs slice so each saver can modify it. txsCopy := exptypes.CopyMempoolTxSlice(txs) go s.StoreMPData(stakeData, txsCopy, inv) } } return nil }
[ "func", "(", "p", "*", "MempoolMonitor", ")", "CollectAndStore", "(", ")", "error", "{", "log", ".", "Trace", "(", "\"", "\"", ")", "\n", "stakeData", ",", "txs", ",", "inv", ",", "err", ":=", "p", ".", "Refresh", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "// stakeData is nil when err != nil", "return", "err", "\n", "}", "\n\n", "// Store mempool stakeData with each registered saver.", "for", "_", ",", "s", ":=", "range", "p", ".", "dataSavers", "{", "if", "s", "!=", "nil", "{", "log", ".", "Trace", "(", "\"", "\"", ")", "\n", "// Save data to wherever the saver wants to put it.", "// Deep copy the txs slice so each saver can modify it.", "txsCopy", ":=", "exptypes", ".", "CopyMempoolTxSlice", "(", "txs", ")", "\n", "go", "s", ".", "StoreMPData", "(", "stakeData", ",", "txsCopy", ",", "inv", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CollectAndStore collects mempool data, resets counters ticket counters and // the timer, and dispatches the storers.
[ "CollectAndStore", "collects", "mempool", "data", "resets", "counters", "ticket", "counters", "and", "the", "timer", "and", "dispatches", "the", "storers", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/monitor.go#L416-L437
train
decred/dcrdata
explorer/types/explorertypes.go
BlocksToTicketMaturity
func (t *TxInfo) BlocksToTicketMaturity() (blocks int64) { if t.Type != "Ticket" { return } if t.Mature == "True" { return } return t.TicketInfo.TicketMaturity + 1 - t.Confirmations }
go
func (t *TxInfo) BlocksToTicketMaturity() (blocks int64) { if t.Type != "Ticket" { return } if t.Mature == "True" { return } return t.TicketInfo.TicketMaturity + 1 - t.Confirmations }
[ "func", "(", "t", "*", "TxInfo", ")", "BlocksToTicketMaturity", "(", ")", "(", "blocks", "int64", ")", "{", "if", "t", ".", "Type", "!=", "\"", "\"", "{", "return", "\n", "}", "\n", "if", "t", ".", "Mature", "==", "\"", "\"", "{", "return", "\n", "}", "\n", "return", "t", ".", "TicketInfo", ".", "TicketMaturity", "+", "1", "-", "t", ".", "Confirmations", "\n", "}" ]
// BlocksToTicketMaturity will return 0 if this isn't an immature ticket.
[ "BlocksToTicketMaturity", "will", "return", "0", "if", "this", "isn", "t", "an", "immature", "ticket", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L227-L235
train
decred/dcrdata
explorer/types/explorertypes.go
VotesOnBlock
func (vi *VoteInfo) VotesOnBlock(blockHash string) bool { return vi.Validation.ForBlock(blockHash) }
go
func (vi *VoteInfo) VotesOnBlock(blockHash string) bool { return vi.Validation.ForBlock(blockHash) }
[ "func", "(", "vi", "*", "VoteInfo", ")", "VotesOnBlock", "(", "blockHash", "string", ")", "bool", "{", "return", "vi", ".", "Validation", ".", "ForBlock", "(", "blockHash", ")", "\n", "}" ]
// VotesOnBlock indicates if the vote is voting on the validity of block // specified by the given hash.
[ "VotesOnBlock", "indicates", "if", "the", "vote", "is", "voting", "on", "the", "validity", "of", "block", "specified", "by", "the", "given", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L318-L320
train
decred/dcrdata
explorer/types/explorertypes.go
ForBlock
func (v *BlockValidation) ForBlock(blockHash string) bool { return blockHash != "" && blockHash == v.Hash }
go
func (v *BlockValidation) ForBlock(blockHash string) bool { return blockHash != "" && blockHash == v.Hash }
[ "func", "(", "v", "*", "BlockValidation", ")", "ForBlock", "(", "blockHash", "string", ")", "bool", "{", "return", "blockHash", "!=", "\"", "\"", "&&", "blockHash", "==", "v", ".", "Hash", "\n", "}" ]
// ForBlock indicates if the validation choice is for the specified block.
[ "ForBlock", "indicates", "if", "the", "validation", "choice", "is", "for", "the", "specified", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L323-L325
train
decred/dcrdata
explorer/types/explorertypes.go
DeepCopy
func (mpi *MempoolInfo) DeepCopy() *MempoolInfo { if mpi == nil { return nil } mpi.RLock() defer mpi.RUnlock() out := new(MempoolInfo) out.Transactions = CopyMempoolTxSlice(mpi.Transactions) out.Tickets = CopyMempoolTxSlice(mpi.Tickets) out.Votes = CopyMempoolTxSlice(mpi.Votes) out.Revocations = CopyMempoolTxSlice(mpi.Revocations) mps := mpi.MempoolShort.DeepCopy() out.MempoolShort = *mps return out }
go
func (mpi *MempoolInfo) DeepCopy() *MempoolInfo { if mpi == nil { return nil } mpi.RLock() defer mpi.RUnlock() out := new(MempoolInfo) out.Transactions = CopyMempoolTxSlice(mpi.Transactions) out.Tickets = CopyMempoolTxSlice(mpi.Tickets) out.Votes = CopyMempoolTxSlice(mpi.Votes) out.Revocations = CopyMempoolTxSlice(mpi.Revocations) mps := mpi.MempoolShort.DeepCopy() out.MempoolShort = *mps return out }
[ "func", "(", "mpi", "*", "MempoolInfo", ")", "DeepCopy", "(", ")", "*", "MempoolInfo", "{", "if", "mpi", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "mpi", ".", "RLock", "(", ")", "\n", "defer", "mpi", ".", "RUnlock", "(", ")", "\n\n", "out", ":=", "new", "(", "MempoolInfo", ")", "\n", "out", ".", "Transactions", "=", "CopyMempoolTxSlice", "(", "mpi", ".", "Transactions", ")", "\n", "out", ".", "Tickets", "=", "CopyMempoolTxSlice", "(", "mpi", ".", "Tickets", ")", "\n", "out", ".", "Votes", "=", "CopyMempoolTxSlice", "(", "mpi", ".", "Votes", ")", "\n", "out", ".", "Revocations", "=", "CopyMempoolTxSlice", "(", "mpi", ".", "Revocations", ")", "\n\n", "mps", ":=", "mpi", ".", "MempoolShort", ".", "DeepCopy", "(", ")", "\n", "out", ".", "MempoolShort", "=", "*", "mps", "\n\n", "return", "out", "\n", "}" ]
// DeepCopy makes a deep copy of MempoolInfo, where all the slice and map data // are copied over.
[ "DeepCopy", "makes", "a", "deep", "copy", "of", "MempoolInfo", "where", "all", "the", "slice", "and", "map", "data", "are", "copied", "over", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L449-L467
train
decred/dcrdata
explorer/types/explorertypes.go
Trim
func (mpi *MempoolInfo) Trim() *TrimmedMempoolInfo { mpi.RLock() mempoolRegularTxs := TrimMempoolTx(mpi.Transactions) mempoolVotes := TrimMempoolTx(mpi.Votes) data := &TrimmedMempoolInfo{ Transactions: FilterRegularTx(mempoolRegularTxs), Tickets: TrimMempoolTx(mpi.Tickets), Votes: FilterUniqueLastBlockVotes(mempoolVotes), Revocations: TrimMempoolTx(mpi.Revocations), Total: mpi.TotalOut, Time: mpi.LastBlockTime, } mpi.RUnlock() // Calculate total fees for all mempool transactions. getTotalFee := func(txs []*TrimmedTxInfo) dcrutil.Amount { var sum dcrutil.Amount for _, tx := range txs { sum += tx.TxBasic.Fee } return sum } allFees := getTotalFee(data.Transactions) + getTotalFee(data.Revocations) + getTotalFee(data.Tickets) + getTotalFee(data.Votes) data.Fees = allFees.ToCoin() return data }
go
func (mpi *MempoolInfo) Trim() *TrimmedMempoolInfo { mpi.RLock() mempoolRegularTxs := TrimMempoolTx(mpi.Transactions) mempoolVotes := TrimMempoolTx(mpi.Votes) data := &TrimmedMempoolInfo{ Transactions: FilterRegularTx(mempoolRegularTxs), Tickets: TrimMempoolTx(mpi.Tickets), Votes: FilterUniqueLastBlockVotes(mempoolVotes), Revocations: TrimMempoolTx(mpi.Revocations), Total: mpi.TotalOut, Time: mpi.LastBlockTime, } mpi.RUnlock() // Calculate total fees for all mempool transactions. getTotalFee := func(txs []*TrimmedTxInfo) dcrutil.Amount { var sum dcrutil.Amount for _, tx := range txs { sum += tx.TxBasic.Fee } return sum } allFees := getTotalFee(data.Transactions) + getTotalFee(data.Revocations) + getTotalFee(data.Tickets) + getTotalFee(data.Votes) data.Fees = allFees.ToCoin() return data }
[ "func", "(", "mpi", "*", "MempoolInfo", ")", "Trim", "(", ")", "*", "TrimmedMempoolInfo", "{", "mpi", ".", "RLock", "(", ")", "\n\n", "mempoolRegularTxs", ":=", "TrimMempoolTx", "(", "mpi", ".", "Transactions", ")", "\n", "mempoolVotes", ":=", "TrimMempoolTx", "(", "mpi", ".", "Votes", ")", "\n\n", "data", ":=", "&", "TrimmedMempoolInfo", "{", "Transactions", ":", "FilterRegularTx", "(", "mempoolRegularTxs", ")", ",", "Tickets", ":", "TrimMempoolTx", "(", "mpi", ".", "Tickets", ")", ",", "Votes", ":", "FilterUniqueLastBlockVotes", "(", "mempoolVotes", ")", ",", "Revocations", ":", "TrimMempoolTx", "(", "mpi", ".", "Revocations", ")", ",", "Total", ":", "mpi", ".", "TotalOut", ",", "Time", ":", "mpi", ".", "LastBlockTime", ",", "}", "\n\n", "mpi", ".", "RUnlock", "(", ")", "\n\n", "// Calculate total fees for all mempool transactions.", "getTotalFee", ":=", "func", "(", "txs", "[", "]", "*", "TrimmedTxInfo", ")", "dcrutil", ".", "Amount", "{", "var", "sum", "dcrutil", ".", "Amount", "\n", "for", "_", ",", "tx", ":=", "range", "txs", "{", "sum", "+=", "tx", ".", "TxBasic", ".", "Fee", "\n", "}", "\n", "return", "sum", "\n", "}", "\n\n", "allFees", ":=", "getTotalFee", "(", "data", ".", "Transactions", ")", "+", "getTotalFee", "(", "data", ".", "Revocations", ")", "+", "getTotalFee", "(", "data", ".", "Tickets", ")", "+", "getTotalFee", "(", "data", ".", "Votes", ")", "\n", "data", ".", "Fees", "=", "allFees", ".", "ToCoin", "(", ")", "\n\n", "return", "data", "\n", "}" ]
// Trim converts the MempoolInfo to TrimmedMempoolInfo.
[ "Trim", "converts", "the", "MempoolInfo", "to", "TrimmedMempoolInfo", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L470-L501
train
decred/dcrdata
explorer/types/explorertypes.go
getTxFromList
func getTxFromList(txid string, txns []MempoolTx) (MempoolTx, bool) { for idx := range txns { if txns[idx].TxID == txid { return txns[idx], true } } return MempoolTx{}, false }
go
func getTxFromList(txid string, txns []MempoolTx) (MempoolTx, bool) { for idx := range txns { if txns[idx].TxID == txid { return txns[idx], true } } return MempoolTx{}, false }
[ "func", "getTxFromList", "(", "txid", "string", ",", "txns", "[", "]", "MempoolTx", ")", "(", "MempoolTx", ",", "bool", ")", "{", "for", "idx", ":=", "range", "txns", "{", "if", "txns", "[", "idx", "]", ".", "TxID", "==", "txid", "{", "return", "txns", "[", "idx", "]", ",", "true", "\n", "}", "\n", "}", "\n", "return", "MempoolTx", "{", "}", ",", "false", "\n", "}" ]
// getTxFromList is a helper function for searching the MempoolInfo tx lists.
[ "getTxFromList", "is", "a", "helper", "function", "for", "searching", "the", "MempoolInfo", "tx", "lists", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L504-L511
train
decred/dcrdata
explorer/types/explorertypes.go
Tx
func (mpi *MempoolInfo) Tx(txid string) (MempoolTx, bool) { mpi.RLock() defer mpi.RUnlock() _, found := mpi.InvRegular[txid] if found { return getTxFromList(txid, mpi.Transactions) } _, found = mpi.InvStake[txid] if found { tx, found := getTxFromList(txid, mpi.Tickets) if found { return tx, true } tx, found = getTxFromList(txid, mpi.Votes) if found { return tx, true } return getTxFromList(txid, mpi.Revocations) } return MempoolTx{}, false }
go
func (mpi *MempoolInfo) Tx(txid string) (MempoolTx, bool) { mpi.RLock() defer mpi.RUnlock() _, found := mpi.InvRegular[txid] if found { return getTxFromList(txid, mpi.Transactions) } _, found = mpi.InvStake[txid] if found { tx, found := getTxFromList(txid, mpi.Tickets) if found { return tx, true } tx, found = getTxFromList(txid, mpi.Votes) if found { return tx, true } return getTxFromList(txid, mpi.Revocations) } return MempoolTx{}, false }
[ "func", "(", "mpi", "*", "MempoolInfo", ")", "Tx", "(", "txid", "string", ")", "(", "MempoolTx", ",", "bool", ")", "{", "mpi", ".", "RLock", "(", ")", "\n", "defer", "mpi", ".", "RUnlock", "(", ")", "\n", "_", ",", "found", ":=", "mpi", ".", "InvRegular", "[", "txid", "]", "\n", "if", "found", "{", "return", "getTxFromList", "(", "txid", ",", "mpi", ".", "Transactions", ")", "\n", "}", "\n", "_", ",", "found", "=", "mpi", ".", "InvStake", "[", "txid", "]", "\n", "if", "found", "{", "tx", ",", "found", ":=", "getTxFromList", "(", "txid", ",", "mpi", ".", "Tickets", ")", "\n", "if", "found", "{", "return", "tx", ",", "true", "\n", "}", "\n", "tx", ",", "found", "=", "getTxFromList", "(", "txid", ",", "mpi", ".", "Votes", ")", "\n", "if", "found", "{", "return", "tx", ",", "true", "\n", "}", "\n", "return", "getTxFromList", "(", "txid", ",", "mpi", ".", "Revocations", ")", "\n", "}", "\n", "return", "MempoolTx", "{", "}", ",", "false", "\n", "}" ]
// Tx checks the inventory and searches the appropriate lists for a // transaction matching the provided transaction ID.
[ "Tx", "checks", "the", "inventory", "and", "searches", "the", "appropriate", "lists", "for", "a", "transaction", "matching", "the", "provided", "transaction", "ID", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L515-L535
train
decred/dcrdata
explorer/types/explorertypes.go
ID
func (mpi *MempoolInfo) ID() uint64 { mpi.RLock() defer mpi.RUnlock() return mpi.Ident }
go
func (mpi *MempoolInfo) ID() uint64 { mpi.RLock() defer mpi.RUnlock() return mpi.Ident }
[ "func", "(", "mpi", "*", "MempoolInfo", ")", "ID", "(", ")", "uint64", "{", "mpi", ".", "RLock", "(", ")", "\n", "defer", "mpi", ".", "RUnlock", "(", ")", "\n", "return", "mpi", ".", "Ident", "\n", "}" ]
// ID can be used to track state changes.
[ "ID", "can", "be", "used", "to", "track", "state", "changes", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L538-L542
train
decred/dcrdata
explorer/types/explorertypes.go
FilterUniqueLastBlockVotes
func FilterUniqueLastBlockVotes(txs []*TrimmedTxInfo) (votes []*TrimmedTxInfo) { seenVotes := make(map[string]struct{}) for _, tx := range txs { if tx.VoteInfo != nil && tx.VoteInfo.ForLastBlock { // Do not append duplicates. if _, seen := seenVotes[tx.TxID]; seen { continue } votes = append(votes, tx) seenVotes[tx.TxID] = struct{}{} } } return votes }
go
func FilterUniqueLastBlockVotes(txs []*TrimmedTxInfo) (votes []*TrimmedTxInfo) { seenVotes := make(map[string]struct{}) for _, tx := range txs { if tx.VoteInfo != nil && tx.VoteInfo.ForLastBlock { // Do not append duplicates. if _, seen := seenVotes[tx.TxID]; seen { continue } votes = append(votes, tx) seenVotes[tx.TxID] = struct{}{} } } return votes }
[ "func", "FilterUniqueLastBlockVotes", "(", "txs", "[", "]", "*", "TrimmedTxInfo", ")", "(", "votes", "[", "]", "*", "TrimmedTxInfo", ")", "{", "seenVotes", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "tx", ":=", "range", "txs", "{", "if", "tx", ".", "VoteInfo", "!=", "nil", "&&", "tx", ".", "VoteInfo", ".", "ForLastBlock", "{", "// Do not append duplicates.", "if", "_", ",", "seen", ":=", "seenVotes", "[", "tx", ".", "TxID", "]", ";", "seen", "{", "continue", "\n", "}", "\n", "votes", "=", "append", "(", "votes", ",", "tx", ")", "\n", "seenVotes", "[", "tx", ".", "TxID", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n", "return", "votes", "\n", "}" ]
// FilterUniqueLastBlockVotes returns a slice of all the vote transactions from // the input slice that are flagged as voting on the previous block.
[ "FilterUniqueLastBlockVotes", "returns", "a", "slice", "of", "all", "the", "vote", "transactions", "from", "the", "input", "slice", "that", "are", "flagged", "as", "voting", "on", "the", "previous", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L594-L607
train
decred/dcrdata
explorer/types/explorertypes.go
NewVotingInfo
func NewVotingInfo(votesPerBlock uint16) VotingInfo { return VotingInfo{ MaxVotesPerBlock: votesPerBlock, VotedTickets: make(map[string]bool), VoteTallys: make(map[string]*VoteTally), } }
go
func NewVotingInfo(votesPerBlock uint16) VotingInfo { return VotingInfo{ MaxVotesPerBlock: votesPerBlock, VotedTickets: make(map[string]bool), VoteTallys: make(map[string]*VoteTally), } }
[ "func", "NewVotingInfo", "(", "votesPerBlock", "uint16", ")", "VotingInfo", "{", "return", "VotingInfo", "{", "MaxVotesPerBlock", ":", "votesPerBlock", ",", "VotedTickets", ":", "make", "(", "map", "[", "string", "]", "bool", ")", ",", "VoteTallys", ":", "make", "(", "map", "[", "string", "]", "*", "VoteTally", ")", ",", "}", "\n", "}" ]
// NewVotingInfo initializes a VotingInfo.
[ "NewVotingInfo", "initializes", "a", "VotingInfo", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L726-L732
train
decred/dcrdata
explorer/types/explorertypes.go
Tally
func (vi *VotingInfo) Tally(vinfo *VoteInfo) { _, ok := vi.VoteTallys[vinfo.Validation.Hash] if ok { vi.VoteTallys[vinfo.Validation.Hash].Mark(vinfo.Validation.Validity) return } marks := make([]bool, 1, vi.MaxVotesPerBlock) marks[0] = vinfo.Validation.Validity vi.VoteTallys[vinfo.Validation.Hash] = &VoteTally{ TicketsPerBlock: int(vi.MaxVotesPerBlock), Marks: marks, } }
go
func (vi *VotingInfo) Tally(vinfo *VoteInfo) { _, ok := vi.VoteTallys[vinfo.Validation.Hash] if ok { vi.VoteTallys[vinfo.Validation.Hash].Mark(vinfo.Validation.Validity) return } marks := make([]bool, 1, vi.MaxVotesPerBlock) marks[0] = vinfo.Validation.Validity vi.VoteTallys[vinfo.Validation.Hash] = &VoteTally{ TicketsPerBlock: int(vi.MaxVotesPerBlock), Marks: marks, } }
[ "func", "(", "vi", "*", "VotingInfo", ")", "Tally", "(", "vinfo", "*", "VoteInfo", ")", "{", "_", ",", "ok", ":=", "vi", ".", "VoteTallys", "[", "vinfo", ".", "Validation", ".", "Hash", "]", "\n", "if", "ok", "{", "vi", ".", "VoteTallys", "[", "vinfo", ".", "Validation", ".", "Hash", "]", ".", "Mark", "(", "vinfo", ".", "Validation", ".", "Validity", ")", "\n", "return", "\n", "}", "\n", "marks", ":=", "make", "(", "[", "]", "bool", ",", "1", ",", "vi", ".", "MaxVotesPerBlock", ")", "\n", "marks", "[", "0", "]", "=", "vinfo", ".", "Validation", ".", "Validity", "\n", "vi", ".", "VoteTallys", "[", "vinfo", ".", "Validation", ".", "Hash", "]", "=", "&", "VoteTally", "{", "TicketsPerBlock", ":", "int", "(", "vi", ".", "MaxVotesPerBlock", ")", ",", "Marks", ":", "marks", ",", "}", "\n", "}" ]
// Tally adds the VoteInfo to the VotingInfo.VoteTally
[ "Tally", "adds", "the", "VoteInfo", "to", "the", "VotingInfo", ".", "VoteTally" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L735-L747
train
decred/dcrdata
explorer/types/explorertypes.go
BlockStatus
func (vi *VotingInfo) BlockStatus(hash string) ([]int, int) { tally, ok := vi.VoteTallys[hash] if ok { return tally.Status() } marks := make([]int, int(vi.MaxVotesPerBlock)) for i := range marks { marks[i] = VoteMissing } return marks, VoteMissing }
go
func (vi *VotingInfo) BlockStatus(hash string) ([]int, int) { tally, ok := vi.VoteTallys[hash] if ok { return tally.Status() } marks := make([]int, int(vi.MaxVotesPerBlock)) for i := range marks { marks[i] = VoteMissing } return marks, VoteMissing }
[ "func", "(", "vi", "*", "VotingInfo", ")", "BlockStatus", "(", "hash", "string", ")", "(", "[", "]", "int", ",", "int", ")", "{", "tally", ",", "ok", ":=", "vi", ".", "VoteTallys", "[", "hash", "]", "\n", "if", "ok", "{", "return", "tally", ".", "Status", "(", ")", "\n", "}", "\n", "marks", ":=", "make", "(", "[", "]", "int", ",", "int", "(", "vi", ".", "MaxVotesPerBlock", ")", ")", "\n", "for", "i", ":=", "range", "marks", "{", "marks", "[", "i", "]", "=", "VoteMissing", "\n", "}", "\n", "return", "marks", ",", "VoteMissing", "\n", "}" ]
// BlockStatus fetches a list of votes in mempool, for the provided block hash. // If not found, a list of VoteMissing is returned.
[ "BlockStatus", "fetches", "a", "list", "of", "votes", "in", "mempool", "for", "the", "provided", "block", "hash", ".", "If", "not", "found", "a", "list", "of", "VoteMissing", "is", "returned", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L751-L761
train
decred/dcrdata
explorer/types/explorertypes.go
Mark
func (tally *VoteTally) Mark(vote bool) { tally.Marks = append(tally.Marks, vote) }
go
func (tally *VoteTally) Mark(vote bool) { tally.Marks = append(tally.Marks, vote) }
[ "func", "(", "tally", "*", "VoteTally", ")", "Mark", "(", "vote", "bool", ")", "{", "tally", ".", "Marks", "=", "append", "(", "tally", ".", "Marks", ",", "vote", ")", "\n", "}" ]
// Mark adds the vote to the VoteTally.
[ "Mark", "adds", "the", "vote", "to", "the", "VoteTally", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L770-L772
train
decred/dcrdata
explorer/types/explorertypes.go
Affirmations
func (tally *VoteTally) Affirmations() (c int) { for _, affirmed := range tally.Marks { if affirmed { c++ } } return c }
go
func (tally *VoteTally) Affirmations() (c int) { for _, affirmed := range tally.Marks { if affirmed { c++ } } return c }
[ "func", "(", "tally", "*", "VoteTally", ")", "Affirmations", "(", ")", "(", "c", "int", ")", "{", "for", "_", ",", "affirmed", ":=", "range", "tally", ".", "Marks", "{", "if", "affirmed", "{", "c", "++", "\n", "}", "\n", "}", "\n", "return", "c", "\n", "}" ]
// Affirmations counts the number of selected ticket holders who have voted // in favor of the block for the given hash.
[ "Affirmations", "counts", "the", "number", "of", "selected", "ticket", "holders", "who", "have", "voted", "in", "favor", "of", "the", "block", "for", "the", "given", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L803-L810
train
decred/dcrdata
explorer/types/explorertypes.go
AddressPrefixes
func AddressPrefixes(params *chaincfg.Params) []AddrPrefix { Descriptions := []string{"P2PK address", "P2PKH address prefix. Standard wallet address. 1 public key -> 1 private key", "Ed25519 P2PKH address prefix", "secp256k1 Schnorr P2PKH address prefix", "P2SH address prefix", "WIF private key prefix", "HD extended private key prefix", "HD extended public key prefix", } Name := []string{"PubKeyAddrID", "PubKeyHashAddrID", "PKHEdwardsAddrID", "PKHSchnorrAddrID", "ScriptHashAddrID", "PrivateKeyID", "HDPrivateKeyID", "HDPublicKeyID", } MainnetPrefixes := []string{"Dk", "Ds", "De", "DS", "Dc", "Pm", "dprv", "dpub"} TestnetPrefixes := []string{"Tk", "Ts", "Te", "TS", "Tc", "Pt", "tprv", "tpub"} SimnetPrefixes := []string{"Sk", "Ss", "Se", "SS", "Sc", "Ps", "sprv", "spub"} name := params.Name var netPrefixes []string if name == "mainnet" { netPrefixes = MainnetPrefixes } else if strings.HasPrefix(name, "testnet") { netPrefixes = TestnetPrefixes } else if name == "simnet" { netPrefixes = SimnetPrefixes } else { return nil } addrPrefix := make([]AddrPrefix, 0, len(Descriptions)) for i, desc := range Descriptions { addrPrefix = append(addrPrefix, AddrPrefix{ Name: Name[i], Description: desc, Prefix: netPrefixes[i], }) } return addrPrefix }
go
func AddressPrefixes(params *chaincfg.Params) []AddrPrefix { Descriptions := []string{"P2PK address", "P2PKH address prefix. Standard wallet address. 1 public key -> 1 private key", "Ed25519 P2PKH address prefix", "secp256k1 Schnorr P2PKH address prefix", "P2SH address prefix", "WIF private key prefix", "HD extended private key prefix", "HD extended public key prefix", } Name := []string{"PubKeyAddrID", "PubKeyHashAddrID", "PKHEdwardsAddrID", "PKHSchnorrAddrID", "ScriptHashAddrID", "PrivateKeyID", "HDPrivateKeyID", "HDPublicKeyID", } MainnetPrefixes := []string{"Dk", "Ds", "De", "DS", "Dc", "Pm", "dprv", "dpub"} TestnetPrefixes := []string{"Tk", "Ts", "Te", "TS", "Tc", "Pt", "tprv", "tpub"} SimnetPrefixes := []string{"Sk", "Ss", "Se", "SS", "Sc", "Ps", "sprv", "spub"} name := params.Name var netPrefixes []string if name == "mainnet" { netPrefixes = MainnetPrefixes } else if strings.HasPrefix(name, "testnet") { netPrefixes = TestnetPrefixes } else if name == "simnet" { netPrefixes = SimnetPrefixes } else { return nil } addrPrefix := make([]AddrPrefix, 0, len(Descriptions)) for i, desc := range Descriptions { addrPrefix = append(addrPrefix, AddrPrefix{ Name: Name[i], Description: desc, Prefix: netPrefixes[i], }) } return addrPrefix }
[ "func", "AddressPrefixes", "(", "params", "*", "chaincfg", ".", "Params", ")", "[", "]", "AddrPrefix", "{", "Descriptions", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "}", "\n", "Name", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "}", "\n\n", "MainnetPrefixes", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "\n", "TestnetPrefixes", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "\n", "SimnetPrefixes", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "\n\n", "name", ":=", "params", ".", "Name", "\n", "var", "netPrefixes", "[", "]", "string", "\n", "if", "name", "==", "\"", "\"", "{", "netPrefixes", "=", "MainnetPrefixes", "\n", "}", "else", "if", "strings", ".", "HasPrefix", "(", "name", ",", "\"", "\"", ")", "{", "netPrefixes", "=", "TestnetPrefixes", "\n", "}", "else", "if", "name", "==", "\"", "\"", "{", "netPrefixes", "=", "SimnetPrefixes", "\n", "}", "else", "{", "return", "nil", "\n", "}", "\n\n", "addrPrefix", ":=", "make", "(", "[", "]", "AddrPrefix", ",", "0", ",", "len", "(", "Descriptions", ")", ")", "\n", "for", "i", ",", "desc", ":=", "range", "Descriptions", "{", "addrPrefix", "=", "append", "(", "addrPrefix", ",", "AddrPrefix", "{", "Name", ":", "Name", "[", "i", "]", ",", "Description", ":", "desc", ",", "Prefix", ":", "netPrefixes", "[", "i", "]", ",", "}", ")", "\n", "}", "\n", "return", "addrPrefix", "\n", "}" ]
// AddressPrefixes generates an array AddrPrefix by using chaincfg.Params
[ "AddressPrefixes", "generates", "an", "array", "AddrPrefix", "by", "using", "chaincfg", ".", "Params" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L952-L997
train
decred/dcrdata
explorer/types/explorertypes.go
UnspentOutputIndices
func UnspentOutputIndices(vouts []Vout) (unspents []int) { for idx := range vouts { vout := vouts[idx] if vout.Amount == 0.0 || vout.Spent { continue } unspents = append(unspents, idx) } return }
go
func UnspentOutputIndices(vouts []Vout) (unspents []int) { for idx := range vouts { vout := vouts[idx] if vout.Amount == 0.0 || vout.Spent { continue } unspents = append(unspents, idx) } return }
[ "func", "UnspentOutputIndices", "(", "vouts", "[", "]", "Vout", ")", "(", "unspents", "[", "]", "int", ")", "{", "for", "idx", ":=", "range", "vouts", "{", "vout", ":=", "vouts", "[", "idx", "]", "\n", "if", "vout", ".", "Amount", "==", "0.0", "||", "vout", ".", "Spent", "{", "continue", "\n", "}", "\n", "unspents", "=", "append", "(", "unspents", ",", "idx", ")", "\n", "}", "\n", "return", "\n", "}" ]
// UnspentOutputIndices finds the indices of the transaction outputs that appear // unspent. The indices returned are the index within the passed slice, not // within the transaction.
[ "UnspentOutputIndices", "finds", "the", "indices", "of", "the", "transaction", "outputs", "that", "appear", "unspent", ".", "The", "indices", "returned", "are", "the", "index", "within", "the", "passed", "slice", "not", "within", "the", "transaction", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L1035-L1044
train
decred/dcrdata
explorer/types/explorertypes.go
MsgTxMempoolInputs
func MsgTxMempoolInputs(msgTx *wire.MsgTx) (inputs []MempoolInput) { for vindex := range msgTx.TxIn { outpoint := msgTx.TxIn[vindex].PreviousOutPoint outId := outpoint.Hash.String() inputs = append(inputs, MempoolInput{ TxId: outId, Index: uint32(vindex), Outdex: outpoint.Index, }) } return }
go
func MsgTxMempoolInputs(msgTx *wire.MsgTx) (inputs []MempoolInput) { for vindex := range msgTx.TxIn { outpoint := msgTx.TxIn[vindex].PreviousOutPoint outId := outpoint.Hash.String() inputs = append(inputs, MempoolInput{ TxId: outId, Index: uint32(vindex), Outdex: outpoint.Index, }) } return }
[ "func", "MsgTxMempoolInputs", "(", "msgTx", "*", "wire", ".", "MsgTx", ")", "(", "inputs", "[", "]", "MempoolInput", ")", "{", "for", "vindex", ":=", "range", "msgTx", ".", "TxIn", "{", "outpoint", ":=", "msgTx", ".", "TxIn", "[", "vindex", "]", ".", "PreviousOutPoint", "\n", "outId", ":=", "outpoint", ".", "Hash", ".", "String", "(", ")", "\n", "inputs", "=", "append", "(", "inputs", ",", "MempoolInput", "{", "TxId", ":", "outId", ",", "Index", ":", "uint32", "(", "vindex", ")", ",", "Outdex", ":", "outpoint", ".", "Index", ",", "}", ")", "\n", "}", "\n", "return", "\n", "}" ]
// MsgTxMempoolInputs parses a MsgTx and creates a list of MempoolInput.
[ "MsgTxMempoolInputs", "parses", "a", "MsgTx", "and", "creates", "a", "list", "of", "MempoolInput", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/types/explorertypes.go#L1047-L1058
train
decred/dcrdata
explorer/templates.go
execTemplateToString
func (t *templates) execTemplateToString(name string, data interface{}) (string, error) { temp, ok := t.templates[name] if !ok { return "", fmt.Errorf("Template %s not known", name) } var page bytes.Buffer err := temp.template.ExecuteTemplate(&page, name, data) return page.String(), err }
go
func (t *templates) execTemplateToString(name string, data interface{}) (string, error) { temp, ok := t.templates[name] if !ok { return "", fmt.Errorf("Template %s not known", name) } var page bytes.Buffer err := temp.template.ExecuteTemplate(&page, name, data) return page.String(), err }
[ "func", "(", "t", "*", "templates", ")", "execTemplateToString", "(", "name", "string", ",", "data", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "temp", ",", "ok", ":=", "t", ".", "templates", "[", "name", "]", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "var", "page", "bytes", ".", "Buffer", "\n", "err", ":=", "temp", ".", "template", ".", "ExecuteTemplate", "(", "&", "page", ",", "name", ",", "data", ")", "\n", "return", "page", ".", "String", "(", ")", ",", "err", "\n", "}" ]
// execTemplateToString executes the associated input template using the // supplied data, and writes the result into a string. If the template fails to // execute or isn't found, a non-nil error will be returned. Check it before // writing to theclient, otherwise you might as well execute directly into // your response writer instead of the internal buffer of this function.
[ "execTemplateToString", "executes", "the", "associated", "input", "template", "using", "the", "supplied", "data", "and", "writes", "the", "result", "into", "a", "string", ".", "If", "the", "template", "fails", "to", "execute", "or", "isn", "t", "found", "a", "non", "-", "nil", "error", "will", "be", "returned", ".", "Check", "it", "before", "writing", "to", "theclient", "otherwise", "you", "might", "as", "well", "execute", "directly", "into", "your", "response", "writer", "instead", "of", "the", "internal", "buffer", "of", "this", "function", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/templates.go#L83-L92
train
decred/dcrdata
txhelpers/subsidy.go
UltimateSubsidy
func UltimateSubsidy(params *chaincfg.Params) int64 { // Check previously computed ultimate subsidies. totalSubsidy, ok := ultimateSubsidies[params] if ok { return totalSubsidy } subsidyCache := blockchain.NewSubsidyCache(0, params) totalSubsidy = params.BlockOneSubsidy() for i := int64(0); ; i++ { // Genesis block or first block. if i <= 1 { continue } if i%params.SubsidyReductionInterval == 0 { numBlocks := params.SubsidyReductionInterval // First reduction internal, which is reduction interval - 2 to skip // the genesis block and block one. if i == params.SubsidyReductionInterval { numBlocks -= 2 } height := i - numBlocks work := blockchain.CalcBlockWorkSubsidy(subsidyCache, height, params.TicketsPerBlock, params) stake := blockchain.CalcStakeVoteSubsidy(subsidyCache, height, params) * int64(params.TicketsPerBlock) tax := blockchain.CalcBlockTaxSubsidy(subsidyCache, height, params.TicketsPerBlock, params) if (work + stake + tax) == 0 { break // all done } totalSubsidy += ((work + stake + tax) * numBlocks) // First reduction internal -- subtract the stake subsidy for blocks // before the staking system is enabled. if i == params.SubsidyReductionInterval { totalSubsidy -= stake * (params.StakeValidationHeight - 2) } } } // Update the ultimate subsidy store. ultimateSubsidies[params] = totalSubsidy return totalSubsidy }
go
func UltimateSubsidy(params *chaincfg.Params) int64 { // Check previously computed ultimate subsidies. totalSubsidy, ok := ultimateSubsidies[params] if ok { return totalSubsidy } subsidyCache := blockchain.NewSubsidyCache(0, params) totalSubsidy = params.BlockOneSubsidy() for i := int64(0); ; i++ { // Genesis block or first block. if i <= 1 { continue } if i%params.SubsidyReductionInterval == 0 { numBlocks := params.SubsidyReductionInterval // First reduction internal, which is reduction interval - 2 to skip // the genesis block and block one. if i == params.SubsidyReductionInterval { numBlocks -= 2 } height := i - numBlocks work := blockchain.CalcBlockWorkSubsidy(subsidyCache, height, params.TicketsPerBlock, params) stake := blockchain.CalcStakeVoteSubsidy(subsidyCache, height, params) * int64(params.TicketsPerBlock) tax := blockchain.CalcBlockTaxSubsidy(subsidyCache, height, params.TicketsPerBlock, params) if (work + stake + tax) == 0 { break // all done } totalSubsidy += ((work + stake + tax) * numBlocks) // First reduction internal -- subtract the stake subsidy for blocks // before the staking system is enabled. if i == params.SubsidyReductionInterval { totalSubsidy -= stake * (params.StakeValidationHeight - 2) } } } // Update the ultimate subsidy store. ultimateSubsidies[params] = totalSubsidy return totalSubsidy }
[ "func", "UltimateSubsidy", "(", "params", "*", "chaincfg", ".", "Params", ")", "int64", "{", "// Check previously computed ultimate subsidies.", "totalSubsidy", ",", "ok", ":=", "ultimateSubsidies", "[", "params", "]", "\n", "if", "ok", "{", "return", "totalSubsidy", "\n", "}", "\n\n", "subsidyCache", ":=", "blockchain", ".", "NewSubsidyCache", "(", "0", ",", "params", ")", "\n\n", "totalSubsidy", "=", "params", ".", "BlockOneSubsidy", "(", ")", "\n", "for", "i", ":=", "int64", "(", "0", ")", ";", ";", "i", "++", "{", "// Genesis block or first block.", "if", "i", "<=", "1", "{", "continue", "\n", "}", "\n\n", "if", "i", "%", "params", ".", "SubsidyReductionInterval", "==", "0", "{", "numBlocks", ":=", "params", ".", "SubsidyReductionInterval", "\n", "// First reduction internal, which is reduction interval - 2 to skip", "// the genesis block and block one.", "if", "i", "==", "params", ".", "SubsidyReductionInterval", "{", "numBlocks", "-=", "2", "\n", "}", "\n", "height", ":=", "i", "-", "numBlocks", "\n\n", "work", ":=", "blockchain", ".", "CalcBlockWorkSubsidy", "(", "subsidyCache", ",", "height", ",", "params", ".", "TicketsPerBlock", ",", "params", ")", "\n", "stake", ":=", "blockchain", ".", "CalcStakeVoteSubsidy", "(", "subsidyCache", ",", "height", ",", "params", ")", "*", "int64", "(", "params", ".", "TicketsPerBlock", ")", "\n", "tax", ":=", "blockchain", ".", "CalcBlockTaxSubsidy", "(", "subsidyCache", ",", "height", ",", "params", ".", "TicketsPerBlock", ",", "params", ")", "\n", "if", "(", "work", "+", "stake", "+", "tax", ")", "==", "0", "{", "break", "// all done", "\n", "}", "\n", "totalSubsidy", "+=", "(", "(", "work", "+", "stake", "+", "tax", ")", "*", "numBlocks", ")", "\n\n", "// First reduction internal -- subtract the stake subsidy for blocks", "// before the staking system is enabled.", "if", "i", "==", "params", ".", "SubsidyReductionInterval", "{", "totalSubsidy", "-=", "stake", "*", "(", "params", ".", "StakeValidationHeight", "-", "2", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Update the ultimate subsidy store.", "ultimateSubsidies", "[", "params", "]", "=", "totalSubsidy", "\n\n", "return", "totalSubsidy", "\n", "}" ]
// UltimateSubsidy computes the total subsidy over the entire subsidy // distribution period of the network.
[ "UltimateSubsidy", "computes", "the", "total", "subsidy", "over", "the", "entire", "subsidy", "distribution", "period", "of", "the", "network", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/subsidy.go#L18-L66
train
decred/dcrdata
db/dcrsqlite/apisource.go
InitWiredDB
func InitWiredDB(dbInfo *DBInfo, stakeDB *stakedb.StakeDatabase, statusC chan uint32, cl *rpcclient.Client, p *chaincfg.Params, shutdown func()) (*WiredDB, error) { db, err := InitDB(dbInfo, shutdown) if err != nil { return nil, err } return newWiredDB(db, stakeDB, statusC, cl, p), nil }
go
func InitWiredDB(dbInfo *DBInfo, stakeDB *stakedb.StakeDatabase, statusC chan uint32, cl *rpcclient.Client, p *chaincfg.Params, shutdown func()) (*WiredDB, error) { db, err := InitDB(dbInfo, shutdown) if err != nil { return nil, err } return newWiredDB(db, stakeDB, statusC, cl, p), nil }
[ "func", "InitWiredDB", "(", "dbInfo", "*", "DBInfo", ",", "stakeDB", "*", "stakedb", ".", "StakeDatabase", ",", "statusC", "chan", "uint32", ",", "cl", "*", "rpcclient", ".", "Client", ",", "p", "*", "chaincfg", ".", "Params", ",", "shutdown", "func", "(", ")", ")", "(", "*", "WiredDB", ",", "error", ")", "{", "db", ",", "err", ":=", "InitDB", "(", "dbInfo", ",", "shutdown", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "newWiredDB", "(", "db", ",", "stakeDB", ",", "statusC", ",", "cl", ",", "p", ")", ",", "nil", "\n", "}" ]
// InitWiredDB creates a new WiredDB from a file containing the data for a // sql.DB. The other parameters are same as those for NewWiredDB.
[ "InitWiredDB", "creates", "a", "new", "WiredDB", "from", "a", "file", "containing", "the", "data", "for", "a", "sql", ".", "DB", ".", "The", "other", "parameters", "are", "same", "as", "those", "for", "NewWiredDB", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L78-L86
train
decred/dcrdata
db/dcrsqlite/apisource.go
ReportHeights
func (db *WiredDB) ReportHeights() error { // Check and report heights of the DBs. dbHeight is the lowest of the // heights, and may be -1 with an empty SQLite DB. dbHeight, summaryHeight, stakeInfoHeight, stakeDBHeight, err := db.DBHeights() if err != nil { return fmt.Errorf("DBHeights failed: %v", err) } if dbHeight < -1 { panic("invalid starting height") } log.Info("SQLite block summary table height: ", summaryHeight) log.Info("SQLite stake info table height: ", stakeInfoHeight) if stakeInfoHeight != summaryHeight { err = fmt.Errorf("SQLite database (dcrdata.sqlt.db) is corrupted") } log.Info("StakeDatabase height: ", stakeDBHeight) return err }
go
func (db *WiredDB) ReportHeights() error { // Check and report heights of the DBs. dbHeight is the lowest of the // heights, and may be -1 with an empty SQLite DB. dbHeight, summaryHeight, stakeInfoHeight, stakeDBHeight, err := db.DBHeights() if err != nil { return fmt.Errorf("DBHeights failed: %v", err) } if dbHeight < -1 { panic("invalid starting height") } log.Info("SQLite block summary table height: ", summaryHeight) log.Info("SQLite stake info table height: ", stakeInfoHeight) if stakeInfoHeight != summaryHeight { err = fmt.Errorf("SQLite database (dcrdata.sqlt.db) is corrupted") } log.Info("StakeDatabase height: ", stakeDBHeight) return err }
[ "func", "(", "db", "*", "WiredDB", ")", "ReportHeights", "(", ")", "error", "{", "// Check and report heights of the DBs. dbHeight is the lowest of the", "// heights, and may be -1 with an empty SQLite DB.", "dbHeight", ",", "summaryHeight", ",", "stakeInfoHeight", ",", "stakeDBHeight", ",", "err", ":=", "db", ".", "DBHeights", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "dbHeight", "<", "-", "1", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "log", ".", "Info", "(", "\"", "\"", ",", "summaryHeight", ")", "\n", "log", ".", "Info", "(", "\"", "\"", ",", "stakeInfoHeight", ")", "\n", "if", "stakeInfoHeight", "!=", "summaryHeight", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "log", ".", "Info", "(", "\"", "\"", ",", "stakeDBHeight", ")", "\n\n", "return", "err", "\n", "}" ]
// ReportHeights logs the SQLite table heights, and the stake database height, // returning a non-nil error only when the SQLite tables are not at the same // height.
[ "ReportHeights", "logs", "the", "SQLite", "table", "heights", "and", "the", "stake", "database", "height", "returning", "a", "non", "-", "nil", "error", "only", "when", "the", "SQLite", "tables", "are", "not", "at", "the", "same", "height", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L149-L168
train
decred/dcrdata
db/dcrsqlite/apisource.go
CheckConnectivity
func (db *WiredDB) CheckConnectivity() error { var err error if err = db.Ping(); err != nil { return err } if err = db.client.Ping(); err != nil { return err } return err }
go
func (db *WiredDB) CheckConnectivity() error { var err error if err = db.Ping(); err != nil { return err } if err = db.client.Ping(); err != nil { return err } return err }
[ "func", "(", "db", "*", "WiredDB", ")", "CheckConnectivity", "(", ")", "error", "{", "var", "err", "error", "\n", "if", "err", "=", "db", ".", "Ping", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "db", ".", "client", ".", "Ping", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "err", "\n", "}" ]
// CheckConnectivity ensures the db and RPC client are working.
[ "CheckConnectivity", "ensures", "the", "db", "and", "RPC", "client", "are", "working", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L171-L180
train
decred/dcrdata
db/dcrsqlite/apisource.go
PurgeBlocksAboveHeight
func (db *WiredDB) PurgeBlocksAboveHeight(height int64) (NSummaryRows, NStakeInfoRows int64, err error) { var summaryHeight, stakeInfoHeight int64 _, summaryHeight, stakeInfoHeight, _, err = db.DBHeights() if err != nil { return } if summaryHeight != stakeInfoHeight { log.Warnf("Tables are at different heights. "+ "Block summary height = %d. Stake info height = %d. Purging anyway!", summaryHeight, stakeInfoHeight) } NSummaryRows, NStakeInfoRows, err = db.DeleteBlocksAboveHeight(height) // DeleteBlock should not return sql.ErrNoRows, but check anyway. if err == sql.ErrNoRows { err = nil } if err != nil { return } _, summaryHeight, stakeInfoHeight, _, err = db.DBHeights() if err != nil { return } if summaryHeight != stakeInfoHeight { err = fmt.Errorf("tables are at different heights after the purge! "+ "Block summary height = %d. Stake info height = %d.", summaryHeight, stakeInfoHeight) return } // Rewind stake database to this height. var stakeDBHeight int64 stakeDBHeight, err = db.RewindStakeDB(context.Background(), height, true) if err != nil { return } if stakeDBHeight != height { err = fmt.Errorf("rewind of StakeDatabase to height %d failed, "+ "reaching height %d instead", height, stakeDBHeight) return } if height != summaryHeight { err = fmt.Errorf("failed to purge to %d, got to %d", height, summaryHeight) } return }
go
func (db *WiredDB) PurgeBlocksAboveHeight(height int64) (NSummaryRows, NStakeInfoRows int64, err error) { var summaryHeight, stakeInfoHeight int64 _, summaryHeight, stakeInfoHeight, _, err = db.DBHeights() if err != nil { return } if summaryHeight != stakeInfoHeight { log.Warnf("Tables are at different heights. "+ "Block summary height = %d. Stake info height = %d. Purging anyway!", summaryHeight, stakeInfoHeight) } NSummaryRows, NStakeInfoRows, err = db.DeleteBlocksAboveHeight(height) // DeleteBlock should not return sql.ErrNoRows, but check anyway. if err == sql.ErrNoRows { err = nil } if err != nil { return } _, summaryHeight, stakeInfoHeight, _, err = db.DBHeights() if err != nil { return } if summaryHeight != stakeInfoHeight { err = fmt.Errorf("tables are at different heights after the purge! "+ "Block summary height = %d. Stake info height = %d.", summaryHeight, stakeInfoHeight) return } // Rewind stake database to this height. var stakeDBHeight int64 stakeDBHeight, err = db.RewindStakeDB(context.Background(), height, true) if err != nil { return } if stakeDBHeight != height { err = fmt.Errorf("rewind of StakeDatabase to height %d failed, "+ "reaching height %d instead", height, stakeDBHeight) return } if height != summaryHeight { err = fmt.Errorf("failed to purge to %d, got to %d", height, summaryHeight) } return }
[ "func", "(", "db", "*", "WiredDB", ")", "PurgeBlocksAboveHeight", "(", "height", "int64", ")", "(", "NSummaryRows", ",", "NStakeInfoRows", "int64", ",", "err", "error", ")", "{", "var", "summaryHeight", ",", "stakeInfoHeight", "int64", "\n", "_", ",", "summaryHeight", ",", "stakeInfoHeight", ",", "_", ",", "err", "=", "db", ".", "DBHeights", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "summaryHeight", "!=", "stakeInfoHeight", "{", "log", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", ",", "summaryHeight", ",", "stakeInfoHeight", ")", "\n", "}", "\n\n", "NSummaryRows", ",", "NStakeInfoRows", ",", "err", "=", "db", ".", "DeleteBlocksAboveHeight", "(", "height", ")", "\n", "// DeleteBlock should not return sql.ErrNoRows, but check anyway.", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "err", "=", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "_", ",", "summaryHeight", ",", "stakeInfoHeight", ",", "_", ",", "err", "=", "db", ".", "DBHeights", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "summaryHeight", "!=", "stakeInfoHeight", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "summaryHeight", ",", "stakeInfoHeight", ")", "\n", "return", "\n", "}", "\n\n", "// Rewind stake database to this height.", "var", "stakeDBHeight", "int64", "\n", "stakeDBHeight", ",", "err", "=", "db", ".", "RewindStakeDB", "(", "context", ".", "Background", "(", ")", ",", "height", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "stakeDBHeight", "!=", "height", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "height", ",", "stakeDBHeight", ")", "\n", "return", "\n", "}", "\n\n", "if", "height", "!=", "summaryHeight", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "height", ",", "summaryHeight", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// PurgeBlocksAboveHeight deletes all data across all tables for the blocks // above the given height, including side chain blocks. The numbers of blocks // removed from the block summary table and stake info table are returned. // PurgeBlocksAboveHeight will not return sql.ErrNoRows, but it will return // without removing a block if the tables are empty.
[ "PurgeBlocksAboveHeight", "deletes", "all", "data", "across", "all", "tables", "for", "the", "blocks", "above", "the", "given", "height", "including", "side", "chain", "blocks", ".", "The", "numbers", "of", "blocks", "removed", "from", "the", "block", "summary", "table", "and", "stake", "info", "table", "are", "returned", ".", "PurgeBlocksAboveHeight", "will", "not", "return", "sql", ".", "ErrNoRows", "but", "it", "will", "return", "without", "removing", "a", "block", "if", "the", "tables", "are", "empty", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L257-L306
train
decred/dcrdata
db/dcrsqlite/apisource.go
PurgeBlock
func (db *WiredDB) PurgeBlock(hash string) (NSummaryRows, NStakeInfoRows int64, err error) { NSummaryRows, NStakeInfoRows, err = db.DeleteBlock(hash) // DeleteBlock should not return sql.ErrNoRows, but check anyway. if err == sql.ErrNoRows { err = nil } return }
go
func (db *WiredDB) PurgeBlock(hash string) (NSummaryRows, NStakeInfoRows int64, err error) { NSummaryRows, NStakeInfoRows, err = db.DeleteBlock(hash) // DeleteBlock should not return sql.ErrNoRows, but check anyway. if err == sql.ErrNoRows { err = nil } return }
[ "func", "(", "db", "*", "WiredDB", ")", "PurgeBlock", "(", "hash", "string", ")", "(", "NSummaryRows", ",", "NStakeInfoRows", "int64", ",", "err", "error", ")", "{", "NSummaryRows", ",", "NStakeInfoRows", ",", "err", "=", "db", ".", "DeleteBlock", "(", "hash", ")", "\n", "// DeleteBlock should not return sql.ErrNoRows, but check anyway.", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "err", "=", "nil", "\n", "}", "\n", "return", "\n", "}" ]
// PurgeBlock deletes all data across all tables for the block with the // specified hash. The numbers of blocks removed from the block summary table // and stake info table are returned. PurgeBlock will not return sql.ErrNoRows, // but it may return without removing a block.
[ "PurgeBlock", "deletes", "all", "data", "across", "all", "tables", "for", "the", "block", "with", "the", "specified", "hash", ".", "The", "numbers", "of", "blocks", "removed", "from", "the", "block", "summary", "table", "and", "stake", "info", "table", "are", "returned", ".", "PurgeBlock", "will", "not", "return", "sql", ".", "ErrNoRows", "but", "it", "may", "return", "without", "removing", "a", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L312-L319
train
decred/dcrdata
db/dcrsqlite/apisource.go
PurgeBestBlock
func (db *WiredDB) PurgeBestBlock() (NSummaryRows, NStakeInfoRows, height int64, hash string, err error) { var summaryHeight, stakeInfoHeight int64 _, summaryHeight, stakeInfoHeight, _, err = db.DBHeights() if err != nil { return } if summaryHeight != stakeInfoHeight { err = fmt.Errorf("tables are at different heights. "+ "Block summary height = %d. Stake info height = %d.", summaryHeight, stakeInfoHeight) return } var h chainhash.Hash h, height, err = db.GetBestBlockHeightHash() if err != nil { if err == sql.ErrNoRows { log.Warnf("No blocks to remove from SQLite summary table.") err = nil } return } hash = h.String() NSummaryRows, NStakeInfoRows, err = db.PurgeBlock(hash) if err != nil { return } h, height, err = db.GetBestBlockHeightHash() if err != nil { if err == sql.ErrNoRows { // Last block removed. err = nil } hash = "" return } hash = h.String() return }
go
func (db *WiredDB) PurgeBestBlock() (NSummaryRows, NStakeInfoRows, height int64, hash string, err error) { var summaryHeight, stakeInfoHeight int64 _, summaryHeight, stakeInfoHeight, _, err = db.DBHeights() if err != nil { return } if summaryHeight != stakeInfoHeight { err = fmt.Errorf("tables are at different heights. "+ "Block summary height = %d. Stake info height = %d.", summaryHeight, stakeInfoHeight) return } var h chainhash.Hash h, height, err = db.GetBestBlockHeightHash() if err != nil { if err == sql.ErrNoRows { log.Warnf("No blocks to remove from SQLite summary table.") err = nil } return } hash = h.String() NSummaryRows, NStakeInfoRows, err = db.PurgeBlock(hash) if err != nil { return } h, height, err = db.GetBestBlockHeightHash() if err != nil { if err == sql.ErrNoRows { // Last block removed. err = nil } hash = "" return } hash = h.String() return }
[ "func", "(", "db", "*", "WiredDB", ")", "PurgeBestBlock", "(", ")", "(", "NSummaryRows", ",", "NStakeInfoRows", ",", "height", "int64", ",", "hash", "string", ",", "err", "error", ")", "{", "var", "summaryHeight", ",", "stakeInfoHeight", "int64", "\n", "_", ",", "summaryHeight", ",", "stakeInfoHeight", ",", "_", ",", "err", "=", "db", ".", "DBHeights", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "summaryHeight", "!=", "stakeInfoHeight", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "summaryHeight", ",", "stakeInfoHeight", ")", "\n", "return", "\n", "}", "\n\n", "var", "h", "chainhash", ".", "Hash", "\n", "h", ",", "height", ",", "err", "=", "db", ".", "GetBestBlockHeightHash", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "log", ".", "Warnf", "(", "\"", "\"", ")", "\n", "err", "=", "nil", "\n", "}", "\n", "return", "\n", "}", "\n", "hash", "=", "h", ".", "String", "(", ")", "\n\n", "NSummaryRows", ",", "NStakeInfoRows", ",", "err", "=", "db", ".", "PurgeBlock", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "h", ",", "height", ",", "err", "=", "db", ".", "GetBestBlockHeightHash", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "// Last block removed.", "err", "=", "nil", "\n", "}", "\n", "hash", "=", "\"", "\"", "\n", "return", "\n", "}", "\n", "hash", "=", "h", ".", "String", "(", ")", "\n\n", "return", "\n", "}" ]
// PurgeBestBlock deletes all data across all tables for the best block in the // block summary table. The numbers of blocks removed from the block summary // table and stake info table are returned. PurgeBestBlock will not return // sql.ErrNoRows, but it will return without removing a block if the tables are // empty. The returned height and hash values represent the best block after // successful data removal, or before a failed removal attempt.
[ "PurgeBestBlock", "deletes", "all", "data", "across", "all", "tables", "for", "the", "best", "block", "in", "the", "block", "summary", "table", ".", "The", "numbers", "of", "blocks", "removed", "from", "the", "block", "summary", "table", "and", "stake", "info", "table", "are", "returned", ".", "PurgeBestBlock", "will", "not", "return", "sql", ".", "ErrNoRows", "but", "it", "will", "return", "without", "removing", "a", "block", "if", "the", "tables", "are", "empty", ".", "The", "returned", "height", "and", "hash", "values", "represent", "the", "best", "block", "after", "successful", "data", "removal", "or", "before", "a", "failed", "removal", "attempt", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L327-L368
train
decred/dcrdata
db/dcrsqlite/apisource.go
PurgeBestBlocks
func (db *WiredDB) PurgeBestBlocks(N int64) (NSummaryRows, NStakeInfoRows, height int64, hash string, err error) { // If N is less than 1, get the current best block height and hash, then // return. if N < 1 { var h chainhash.Hash h, height, err = db.GetBestBlockHeightHash() if err == sql.ErrNoRows { err = nil } hash = h.String() return } for i := int64(0); i < N; i++ { // Attempt removal of the best block. var NSumi, Nstakei, heighti int64 var hashi string NSumi, Nstakei, heighti, hashi, err = db.PurgeBestBlock() if err != nil { // Return with previous (or initial) best block info and block // removal count. return } if (i%100 == 0 && i > 0) || i == N-1 { log.Debugf("Removed data for %d blocks.", i+1) } // Removal succeeded. Returned best block values are valid. NSummaryRows += NSumi NStakeInfoRows += Nstakei height = heighti hash = hashi // Rewind stake database to this height. var stakeDBHeight int64 stakeDBHeight, err = db.RewindStakeDB(context.Background(), height, true) if err != nil { return } if stakeDBHeight != height { err = fmt.Errorf("rewind of StakeDatabase to height %d failed, "+ "reaching height %d instead", height, stakeDBHeight) return } } return }
go
func (db *WiredDB) PurgeBestBlocks(N int64) (NSummaryRows, NStakeInfoRows, height int64, hash string, err error) { // If N is less than 1, get the current best block height and hash, then // return. if N < 1 { var h chainhash.Hash h, height, err = db.GetBestBlockHeightHash() if err == sql.ErrNoRows { err = nil } hash = h.String() return } for i := int64(0); i < N; i++ { // Attempt removal of the best block. var NSumi, Nstakei, heighti int64 var hashi string NSumi, Nstakei, heighti, hashi, err = db.PurgeBestBlock() if err != nil { // Return with previous (or initial) best block info and block // removal count. return } if (i%100 == 0 && i > 0) || i == N-1 { log.Debugf("Removed data for %d blocks.", i+1) } // Removal succeeded. Returned best block values are valid. NSummaryRows += NSumi NStakeInfoRows += Nstakei height = heighti hash = hashi // Rewind stake database to this height. var stakeDBHeight int64 stakeDBHeight, err = db.RewindStakeDB(context.Background(), height, true) if err != nil { return } if stakeDBHeight != height { err = fmt.Errorf("rewind of StakeDatabase to height %d failed, "+ "reaching height %d instead", height, stakeDBHeight) return } } return }
[ "func", "(", "db", "*", "WiredDB", ")", "PurgeBestBlocks", "(", "N", "int64", ")", "(", "NSummaryRows", ",", "NStakeInfoRows", ",", "height", "int64", ",", "hash", "string", ",", "err", "error", ")", "{", "// If N is less than 1, get the current best block height and hash, then", "// return.", "if", "N", "<", "1", "{", "var", "h", "chainhash", ".", "Hash", "\n", "h", ",", "height", ",", "err", "=", "db", ".", "GetBestBlockHeightHash", "(", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "err", "=", "nil", "\n", "}", "\n", "hash", "=", "h", ".", "String", "(", ")", "\n", "return", "\n", "}", "\n\n", "for", "i", ":=", "int64", "(", "0", ")", ";", "i", "<", "N", ";", "i", "++", "{", "// Attempt removal of the best block.", "var", "NSumi", ",", "Nstakei", ",", "heighti", "int64", "\n", "var", "hashi", "string", "\n", "NSumi", ",", "Nstakei", ",", "heighti", ",", "hashi", ",", "err", "=", "db", ".", "PurgeBestBlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// Return with previous (or initial) best block info and block", "// removal count.", "return", "\n", "}", "\n\n", "if", "(", "i", "%", "100", "==", "0", "&&", "i", ">", "0", ")", "||", "i", "==", "N", "-", "1", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "i", "+", "1", ")", "\n", "}", "\n\n", "// Removal succeeded. Returned best block values are valid.", "NSummaryRows", "+=", "NSumi", "\n", "NStakeInfoRows", "+=", "Nstakei", "\n", "height", "=", "heighti", "\n", "hash", "=", "hashi", "\n\n", "// Rewind stake database to this height.", "var", "stakeDBHeight", "int64", "\n", "stakeDBHeight", ",", "err", "=", "db", ".", "RewindStakeDB", "(", "context", ".", "Background", "(", ")", ",", "height", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "stakeDBHeight", "!=", "height", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "height", ",", "stakeDBHeight", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// PurgeBestBlocks deletes all data across all tables for the N best blocks in // the block summary table. The number of blocks removed is returned. // PurgeBestBlocks will not return sql.ErrNoRows, but it will return without // removing the requested number of blocks if the tables are empty or become // empty. The returned height and hash values represent the best block after // successful data removal, or before a failed removal attempt.
[ "PurgeBestBlocks", "deletes", "all", "data", "across", "all", "tables", "for", "the", "N", "best", "blocks", "in", "the", "block", "summary", "table", ".", "The", "number", "of", "blocks", "removed", "is", "returned", ".", "PurgeBestBlocks", "will", "not", "return", "sql", ".", "ErrNoRows", "but", "it", "will", "return", "without", "removing", "the", "requested", "number", "of", "blocks", "if", "the", "tables", "are", "empty", "or", "become", "empty", ".", "The", "returned", "height", "and", "hash", "values", "represent", "the", "best", "block", "after", "successful", "data", "removal", "or", "before", "a", "failed", "removal", "attempt", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L376-L424
train
decred/dcrdata
db/dcrsqlite/apisource.go
GetBestBlockHeightHash
func (db *WiredDB) GetBestBlockHeightHash() (chainhash.Hash, int64, error) { bestBlockSummary := db.GetBestBlockSummary() if bestBlockSummary == nil { return chainhash.Hash{}, -1, fmt.Errorf("unable to retrieve best block summary") } height := int64(bestBlockSummary.Height) hash, err := chainhash.NewHashFromStr(bestBlockSummary.Hash) return *hash, height, err }
go
func (db *WiredDB) GetBestBlockHeightHash() (chainhash.Hash, int64, error) { bestBlockSummary := db.GetBestBlockSummary() if bestBlockSummary == nil { return chainhash.Hash{}, -1, fmt.Errorf("unable to retrieve best block summary") } height := int64(bestBlockSummary.Height) hash, err := chainhash.NewHashFromStr(bestBlockSummary.Hash) return *hash, height, err }
[ "func", "(", "db", "*", "WiredDB", ")", "GetBestBlockHeightHash", "(", ")", "(", "chainhash", ".", "Hash", ",", "int64", ",", "error", ")", "{", "bestBlockSummary", ":=", "db", ".", "GetBestBlockSummary", "(", ")", "\n", "if", "bestBlockSummary", "==", "nil", "{", "return", "chainhash", ".", "Hash", "{", "}", ",", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "height", ":=", "int64", "(", "bestBlockSummary", ".", "Height", ")", "\n", "hash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "bestBlockSummary", ".", "Hash", ")", "\n", "return", "*", "hash", ",", "height", ",", "err", "\n", "}" ]
// GetBestBlockHeightHash retrieves the DB's best block hash and height.
[ "GetBestBlockHeightHash", "retrieves", "the", "DB", "s", "best", "block", "hash", "and", "height", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L427-L435
train
decred/dcrdata
db/dcrsqlite/apisource.go
GetRawTransactionWithPrevOutAddresses
func (db *WiredDB) GetRawTransactionWithPrevOutAddresses(txid *chainhash.Hash) (*apitypes.Tx, [][]string) { tx, _ := db.getRawTransaction(txid) if tx == nil { return nil, nil } prevOutAddresses := make([][]string, len(tx.Vin)) for i := range tx.Vin { vin := &tx.Vin[i] // Skip inspecting previous outpoint for coinbase transaction, and // vin[0] of stakebase transcation. if vin.IsCoinBase() || (vin.IsStakeBase() && i == 0) { continue } var err error prevOutAddresses[i], err = txhelpers.OutPointAddressesFromString( vin.Txid, vin.Vout, vin.Tree, db.client, db.params) if err != nil { log.Warnf("failed to get outpoint address from txid: %v", err) } } return tx, prevOutAddresses }
go
func (db *WiredDB) GetRawTransactionWithPrevOutAddresses(txid *chainhash.Hash) (*apitypes.Tx, [][]string) { tx, _ := db.getRawTransaction(txid) if tx == nil { return nil, nil } prevOutAddresses := make([][]string, len(tx.Vin)) for i := range tx.Vin { vin := &tx.Vin[i] // Skip inspecting previous outpoint for coinbase transaction, and // vin[0] of stakebase transcation. if vin.IsCoinBase() || (vin.IsStakeBase() && i == 0) { continue } var err error prevOutAddresses[i], err = txhelpers.OutPointAddressesFromString( vin.Txid, vin.Vout, vin.Tree, db.client, db.params) if err != nil { log.Warnf("failed to get outpoint address from txid: %v", err) } } return tx, prevOutAddresses }
[ "func", "(", "db", "*", "WiredDB", ")", "GetRawTransactionWithPrevOutAddresses", "(", "txid", "*", "chainhash", ".", "Hash", ")", "(", "*", "apitypes", ".", "Tx", ",", "[", "]", "[", "]", "string", ")", "{", "tx", ",", "_", ":=", "db", ".", "getRawTransaction", "(", "txid", ")", "\n", "if", "tx", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "prevOutAddresses", ":=", "make", "(", "[", "]", "[", "]", "string", ",", "len", "(", "tx", ".", "Vin", ")", ")", "\n\n", "for", "i", ":=", "range", "tx", ".", "Vin", "{", "vin", ":=", "&", "tx", ".", "Vin", "[", "i", "]", "\n", "// Skip inspecting previous outpoint for coinbase transaction, and", "// vin[0] of stakebase transcation.", "if", "vin", ".", "IsCoinBase", "(", ")", "||", "(", "vin", ".", "IsStakeBase", "(", ")", "&&", "i", "==", "0", ")", "{", "continue", "\n", "}", "\n", "var", "err", "error", "\n", "prevOutAddresses", "[", "i", "]", ",", "err", "=", "txhelpers", ".", "OutPointAddressesFromString", "(", "vin", ".", "Txid", ",", "vin", ".", "Vout", ",", "vin", ".", "Tree", ",", "db", ".", "client", ",", "db", ".", "params", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "tx", ",", "prevOutAddresses", "\n", "}" ]
// GetRawTransactionWithPrevOutAddresses looks up the previous outpoints for a // transaction and extracts a slice of addresses encoded by the pkScript for // each previous outpoint consumed by the transaction.
[ "GetRawTransactionWithPrevOutAddresses", "looks", "up", "the", "previous", "outpoints", "for", "a", "transaction", "and", "extracts", "a", "slice", "of", "addresses", "encoded", "by", "the", "pkScript", "for", "each", "previous", "outpoint", "consumed", "by", "the", "transaction", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L611-L635
train
decred/dcrdata
db/dcrsqlite/apisource.go
GetVoteVersionInfo
func (db *WiredDB) GetVoteVersionInfo(ver uint32) (*dcrjson.GetVoteInfoResult, error) { return db.client.GetVoteInfo(ver) }
go
func (db *WiredDB) GetVoteVersionInfo(ver uint32) (*dcrjson.GetVoteInfoResult, error) { return db.client.GetVoteInfo(ver) }
[ "func", "(", "db", "*", "WiredDB", ")", "GetVoteVersionInfo", "(", "ver", "uint32", ")", "(", "*", "dcrjson", ".", "GetVoteInfoResult", ",", "error", ")", "{", "return", "db", ".", "client", ".", "GetVoteInfo", "(", "ver", ")", "\n", "}" ]
// GetVoteVersionInfo requests stake version info from the dcrd RPC server
[ "GetVoteVersionInfo", "requests", "stake", "version", "info", "from", "the", "dcrd", "RPC", "server" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L700-L702
train
decred/dcrdata
db/dcrsqlite/apisource.go
GetStakeVersions
func (db *WiredDB) GetStakeVersions(blockHash string, count int32) (*dcrjson.GetStakeVersionsResult, error) { return db.client.GetStakeVersions(blockHash, count) }
go
func (db *WiredDB) GetStakeVersions(blockHash string, count int32) (*dcrjson.GetStakeVersionsResult, error) { return db.client.GetStakeVersions(blockHash, count) }
[ "func", "(", "db", "*", "WiredDB", ")", "GetStakeVersions", "(", "blockHash", "string", ",", "count", "int32", ")", "(", "*", "dcrjson", ".", "GetStakeVersionsResult", ",", "error", ")", "{", "return", "db", ".", "client", ".", "GetStakeVersions", "(", "blockHash", ",", "count", ")", "\n", "}" ]
// GetStakeVersions requests the output of the getstakeversions RPC, which gets // stake version information and individual vote version information starting at the // given block and for count-1 blocks prior.
[ "GetStakeVersions", "requests", "the", "output", "of", "the", "getstakeversions", "RPC", "which", "gets", "stake", "version", "information", "and", "individual", "vote", "version", "information", "starting", "at", "the", "given", "block", "and", "for", "count", "-", "1", "blocks", "prior", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L707-L709
train
decred/dcrdata
db/dcrsqlite/apisource.go
GetBlockSummaryTimeRange
func (db *WiredDB) GetBlockSummaryTimeRange(min, max int64, limit int) []apitypes.BlockDataBasic { blockSummary, err := db.RetrieveBlockSummaryByTimeRange(min, max, limit) if err != nil { log.Errorf("Unable to retrieve block summary using time %d: %v", min, err) } return blockSummary }
go
func (db *WiredDB) GetBlockSummaryTimeRange(min, max int64, limit int) []apitypes.BlockDataBasic { blockSummary, err := db.RetrieveBlockSummaryByTimeRange(min, max, limit) if err != nil { log.Errorf("Unable to retrieve block summary using time %d: %v", min, err) } return blockSummary }
[ "func", "(", "db", "*", "WiredDB", ")", "GetBlockSummaryTimeRange", "(", "min", ",", "max", "int64", ",", "limit", "int", ")", "[", "]", "apitypes", ".", "BlockDataBasic", "{", "blockSummary", ",", "err", ":=", "db", ".", "RetrieveBlockSummaryByTimeRange", "(", "min", ",", "max", ",", "limit", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "min", ",", "err", ")", "\n", "}", "\n", "return", "blockSummary", "\n", "}" ]
// GetBlockSummaryTimeRange returns the blocks created within a specified time // range min, max time
[ "GetBlockSummaryTimeRange", "returns", "the", "blocks", "created", "within", "a", "specified", "time", "range", "min", "max", "time" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L930-L936
train
decred/dcrdata
db/dcrsqlite/apisource.go
RetreiveDifficulty
func (db *WiredDB) RetreiveDifficulty(timestamp int64) float64 { sdiff, err := db.RetrieveDiff(timestamp) if err != nil { log.Errorf("Unable to retrieve difficulty: %v", err) return -1 } return sdiff }
go
func (db *WiredDB) RetreiveDifficulty(timestamp int64) float64 { sdiff, err := db.RetrieveDiff(timestamp) if err != nil { log.Errorf("Unable to retrieve difficulty: %v", err) return -1 } return sdiff }
[ "func", "(", "db", "*", "WiredDB", ")", "RetreiveDifficulty", "(", "timestamp", "int64", ")", "float64", "{", "sdiff", ",", "err", ":=", "db", ".", "RetrieveDiff", "(", "timestamp", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "-", "1", "\n", "}", "\n", "return", "sdiff", "\n", "}" ]
// RetreiveDifficulty fetches the difficulty value in the last 24hrs or // immediately after 24hrs.
[ "RetreiveDifficulty", "fetches", "the", "difficulty", "value", "in", "the", "last", "24hrs", "or", "immediately", "after", "24hrs", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L985-L992
train
decred/dcrdata
db/dcrsqlite/apisource.go
GetAddressTransactionsWithSkip
func (db *WiredDB) GetAddressTransactionsWithSkip(addr string, count, skip int) *apitypes.Address { address, err := dcrutil.DecodeAddress(addr) if err != nil { log.Infof("Invalid address %s: %v", addr, err) return nil } txs, err := db.client.SearchRawTransactionsVerbose(address, skip, count, false, true, nil) if err != nil && err.Error() == "-32603: No Txns available" { log.Debugf("GetAddressTransactionsWithSkip: No transactions found for address %s: %v", addr, err) return &apitypes.Address{ Address: addr, Transactions: make([]*apitypes.AddressTxShort, 0), // not nil for JSON formatting } } if err != nil { log.Errorf("GetAddressTransactionsWithSkip failed for address %s: %v", addr, err) return nil } tx := make([]*apitypes.AddressTxShort, 0, len(txs)) for i := range txs { tx = append(tx, &apitypes.AddressTxShort{ TxID: txs[i].Txid, Time: apitypes.TimeAPI{S: dbtypes.NewTimeDefFromUNIX(txs[i].Time)}, Value: txhelpers.TotalVout(txs[i].Vout).ToCoin(), Confirmations: int64(txs[i].Confirmations), Size: int32(len(txs[i].Hex) / 2), }) } return &apitypes.Address{ Address: addr, Transactions: tx, } }
go
func (db *WiredDB) GetAddressTransactionsWithSkip(addr string, count, skip int) *apitypes.Address { address, err := dcrutil.DecodeAddress(addr) if err != nil { log.Infof("Invalid address %s: %v", addr, err) return nil } txs, err := db.client.SearchRawTransactionsVerbose(address, skip, count, false, true, nil) if err != nil && err.Error() == "-32603: No Txns available" { log.Debugf("GetAddressTransactionsWithSkip: No transactions found for address %s: %v", addr, err) return &apitypes.Address{ Address: addr, Transactions: make([]*apitypes.AddressTxShort, 0), // not nil for JSON formatting } } if err != nil { log.Errorf("GetAddressTransactionsWithSkip failed for address %s: %v", addr, err) return nil } tx := make([]*apitypes.AddressTxShort, 0, len(txs)) for i := range txs { tx = append(tx, &apitypes.AddressTxShort{ TxID: txs[i].Txid, Time: apitypes.TimeAPI{S: dbtypes.NewTimeDefFromUNIX(txs[i].Time)}, Value: txhelpers.TotalVout(txs[i].Vout).ToCoin(), Confirmations: int64(txs[i].Confirmations), Size: int32(len(txs[i].Hex) / 2), }) } return &apitypes.Address{ Address: addr, Transactions: tx, } }
[ "func", "(", "db", "*", "WiredDB", ")", "GetAddressTransactionsWithSkip", "(", "addr", "string", ",", "count", ",", "skip", "int", ")", "*", "apitypes", ".", "Address", "{", "address", ",", "err", ":=", "dcrutil", ".", "DecodeAddress", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "addr", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "txs", ",", "err", ":=", "db", ".", "client", ".", "SearchRawTransactionsVerbose", "(", "address", ",", "skip", ",", "count", ",", "false", ",", "true", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "&&", "err", ".", "Error", "(", ")", "==", "\"", "\"", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "addr", ",", "err", ")", "\n", "return", "&", "apitypes", ".", "Address", "{", "Address", ":", "addr", ",", "Transactions", ":", "make", "(", "[", "]", "*", "apitypes", ".", "AddressTxShort", ",", "0", ")", ",", "// not nil for JSON formatting", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "addr", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "tx", ":=", "make", "(", "[", "]", "*", "apitypes", ".", "AddressTxShort", ",", "0", ",", "len", "(", "txs", ")", ")", "\n", "for", "i", ":=", "range", "txs", "{", "tx", "=", "append", "(", "tx", ",", "&", "apitypes", ".", "AddressTxShort", "{", "TxID", ":", "txs", "[", "i", "]", ".", "Txid", ",", "Time", ":", "apitypes", ".", "TimeAPI", "{", "S", ":", "dbtypes", ".", "NewTimeDefFromUNIX", "(", "txs", "[", "i", "]", ".", "Time", ")", "}", ",", "Value", ":", "txhelpers", ".", "TotalVout", "(", "txs", "[", "i", "]", ".", "Vout", ")", ".", "ToCoin", "(", ")", ",", "Confirmations", ":", "int64", "(", "txs", "[", "i", "]", ".", "Confirmations", ")", ",", "Size", ":", "int32", "(", "len", "(", "txs", "[", "i", "]", ".", "Hex", ")", "/", "2", ")", ",", "}", ")", "\n", "}", "\n", "return", "&", "apitypes", ".", "Address", "{", "Address", ":", "addr", ",", "Transactions", ":", "tx", ",", "}", "\n\n", "}" ]
// GetAddressTransactionsWithSkip returns an apitypes.Address Object with at most the // last count transactions the address was in
[ "GetAddressTransactionsWithSkip", "returns", "an", "apitypes", ".", "Address", "Object", "with", "at", "most", "the", "last", "count", "transactions", "the", "address", "was", "in" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L1040-L1073
train
decred/dcrdata
db/dcrsqlite/apisource.go
GetAddressTransactions
func (db *WiredDB) GetAddressTransactions(addr string, count int) *apitypes.Address { return db.GetAddressTransactionsWithSkip(addr, count, 0) }
go
func (db *WiredDB) GetAddressTransactions(addr string, count int) *apitypes.Address { return db.GetAddressTransactionsWithSkip(addr, count, 0) }
[ "func", "(", "db", "*", "WiredDB", ")", "GetAddressTransactions", "(", "addr", "string", ",", "count", "int", ")", "*", "apitypes", ".", "Address", "{", "return", "db", ".", "GetAddressTransactionsWithSkip", "(", "addr", ",", "count", ",", "0", ")", "\n", "}" ]
// GetAddressTransactions returns an apitypes.Address Object with at most the // last count transactions the address was in
[ "GetAddressTransactions", "returns", "an", "apitypes", ".", "Address", "Object", "with", "at", "most", "the", "last", "count", "transactions", "the", "address", "was", "in" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L1077-L1079
train
decred/dcrdata
db/dcrsqlite/apisource.go
GetAddressTransactionsRaw
func (db *WiredDB) GetAddressTransactionsRaw(addr string, count int) []*apitypes.AddressTxRaw { return db.GetAddressTransactionsRawWithSkip(addr, count, 0) }
go
func (db *WiredDB) GetAddressTransactionsRaw(addr string, count int) []*apitypes.AddressTxRaw { return db.GetAddressTransactionsRawWithSkip(addr, count, 0) }
[ "func", "(", "db", "*", "WiredDB", ")", "GetAddressTransactionsRaw", "(", "addr", "string", ",", "count", "int", ")", "[", "]", "*", "apitypes", ".", "AddressTxRaw", "{", "return", "db", ".", "GetAddressTransactionsRawWithSkip", "(", "addr", ",", "count", ",", "0", ")", "\n", "}" ]
// GetAddressTransactionsRaw returns an array of apitypes.AddressTxRaw objects // representing the raw result of SearchRawTransactionsverbose
[ "GetAddressTransactionsRaw", "returns", "an", "array", "of", "apitypes", ".", "AddressTxRaw", "objects", "representing", "the", "raw", "result", "of", "SearchRawTransactionsverbose" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L1083-L1085
train
decred/dcrdata
db/dcrsqlite/apisource.go
GetExplorerBlocks
func (db *WiredDB) GetExplorerBlocks(start int, end int) []*exptypes.BlockBasic { if start < end { return nil } summaries := make([]*exptypes.BlockBasic, 0, start-end) for i := start; i > end; i-- { data := db.GetBlockVerbose(i, true) block := new(exptypes.BlockBasic) if data != nil { block = makeExplorerBlockBasic(data, db.params) } summaries = append(summaries, block) } return summaries }
go
func (db *WiredDB) GetExplorerBlocks(start int, end int) []*exptypes.BlockBasic { if start < end { return nil } summaries := make([]*exptypes.BlockBasic, 0, start-end) for i := start; i > end; i-- { data := db.GetBlockVerbose(i, true) block := new(exptypes.BlockBasic) if data != nil { block = makeExplorerBlockBasic(data, db.params) } summaries = append(summaries, block) } return summaries }
[ "func", "(", "db", "*", "WiredDB", ")", "GetExplorerBlocks", "(", "start", "int", ",", "end", "int", ")", "[", "]", "*", "exptypes", ".", "BlockBasic", "{", "if", "start", "<", "end", "{", "return", "nil", "\n", "}", "\n", "summaries", ":=", "make", "(", "[", "]", "*", "exptypes", ".", "BlockBasic", ",", "0", ",", "start", "-", "end", ")", "\n", "for", "i", ":=", "start", ";", "i", ">", "end", ";", "i", "--", "{", "data", ":=", "db", ".", "GetBlockVerbose", "(", "i", ",", "true", ")", "\n", "block", ":=", "new", "(", "exptypes", ".", "BlockBasic", ")", "\n", "if", "data", "!=", "nil", "{", "block", "=", "makeExplorerBlockBasic", "(", "data", ",", "db", ".", "params", ")", "\n", "}", "\n", "summaries", "=", "append", "(", "summaries", ",", "block", ")", "\n", "}", "\n", "return", "summaries", "\n", "}" ]
// GetExplorerBlocks creates an slice of exptypes.BlockBasic beginning at start // and decreasing in block height to end, not including end.
[ "GetExplorerBlocks", "creates", "an", "slice", "of", "exptypes", ".", "BlockBasic", "beginning", "at", "start", "and", "decreasing", "in", "block", "height", "to", "end", "not", "including", "end", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L1245-L1259
train
decred/dcrdata
db/dcrsqlite/apisource.go
GetMempool
func (db *WiredDB) GetMempool() []exptypes.MempoolTx { mempooltxs, err := db.client.GetRawMempoolVerbose(dcrjson.GRMAll) if err != nil { log.Errorf("GetRawMempoolVerbose failed: %v", err) return nil } txs := make([]exptypes.MempoolTx, 0, len(mempooltxs)) for hashStr, tx := range mempooltxs { hash, err := chainhash.NewHashFromStr(hashStr) if err != nil { continue } rawtx, hex := db.getRawTransaction(hash) total := 0.0 if rawtx == nil { continue } for _, v := range rawtx.Vout { total += v.Value } msgTx, err := txhelpers.MsgTxFromHex(hex) if err != nil { continue } var voteInfo *exptypes.VoteInfo if ok := stake.IsSSGen(msgTx); ok { validation, version, bits, choices, err := txhelpers.SSGenVoteChoices(msgTx, db.params) if err != nil { log.Debugf("Cannot get vote choices for %s", hash) } else { voteInfo = &exptypes.VoteInfo{ Validation: exptypes.BlockValidation{ Hash: validation.Hash.String(), Height: validation.Height, Validity: validation.Validity, }, Version: version, Bits: bits, Choices: choices, TicketSpent: msgTx.TxIn[1].PreviousOutPoint.Hash.String(), } } } txs = append(txs, exptypes.MempoolTx{ TxID: msgTx.TxHash().String(), Hash: hashStr, Time: tx.Time, Size: tx.Size, TotalOut: total, Type: txhelpers.DetermineTxTypeString(msgTx), VoteInfo: voteInfo, Vin: exptypes.MsgTxMempoolInputs(msgTx), }) } return txs }
go
func (db *WiredDB) GetMempool() []exptypes.MempoolTx { mempooltxs, err := db.client.GetRawMempoolVerbose(dcrjson.GRMAll) if err != nil { log.Errorf("GetRawMempoolVerbose failed: %v", err) return nil } txs := make([]exptypes.MempoolTx, 0, len(mempooltxs)) for hashStr, tx := range mempooltxs { hash, err := chainhash.NewHashFromStr(hashStr) if err != nil { continue } rawtx, hex := db.getRawTransaction(hash) total := 0.0 if rawtx == nil { continue } for _, v := range rawtx.Vout { total += v.Value } msgTx, err := txhelpers.MsgTxFromHex(hex) if err != nil { continue } var voteInfo *exptypes.VoteInfo if ok := stake.IsSSGen(msgTx); ok { validation, version, bits, choices, err := txhelpers.SSGenVoteChoices(msgTx, db.params) if err != nil { log.Debugf("Cannot get vote choices for %s", hash) } else { voteInfo = &exptypes.VoteInfo{ Validation: exptypes.BlockValidation{ Hash: validation.Hash.String(), Height: validation.Height, Validity: validation.Validity, }, Version: version, Bits: bits, Choices: choices, TicketSpent: msgTx.TxIn[1].PreviousOutPoint.Hash.String(), } } } txs = append(txs, exptypes.MempoolTx{ TxID: msgTx.TxHash().String(), Hash: hashStr, Time: tx.Time, Size: tx.Size, TotalOut: total, Type: txhelpers.DetermineTxTypeString(msgTx), VoteInfo: voteInfo, Vin: exptypes.MsgTxMempoolInputs(msgTx), }) } return txs }
[ "func", "(", "db", "*", "WiredDB", ")", "GetMempool", "(", ")", "[", "]", "exptypes", ".", "MempoolTx", "{", "mempooltxs", ",", "err", ":=", "db", ".", "client", ".", "GetRawMempoolVerbose", "(", "dcrjson", ".", "GRMAll", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n\n", "txs", ":=", "make", "(", "[", "]", "exptypes", ".", "MempoolTx", ",", "0", ",", "len", "(", "mempooltxs", ")", ")", "\n\n", "for", "hashStr", ",", "tx", ":=", "range", "mempooltxs", "{", "hash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "hashStr", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "rawtx", ",", "hex", ":=", "db", ".", "getRawTransaction", "(", "hash", ")", "\n", "total", ":=", "0.0", "\n", "if", "rawtx", "==", "nil", "{", "continue", "\n", "}", "\n", "for", "_", ",", "v", ":=", "range", "rawtx", ".", "Vout", "{", "total", "+=", "v", ".", "Value", "\n", "}", "\n", "msgTx", ",", "err", ":=", "txhelpers", ".", "MsgTxFromHex", "(", "hex", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "var", "voteInfo", "*", "exptypes", ".", "VoteInfo", "\n\n", "if", "ok", ":=", "stake", ".", "IsSSGen", "(", "msgTx", ")", ";", "ok", "{", "validation", ",", "version", ",", "bits", ",", "choices", ",", "err", ":=", "txhelpers", ".", "SSGenVoteChoices", "(", "msgTx", ",", "db", ".", "params", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "hash", ")", "\n\n", "}", "else", "{", "voteInfo", "=", "&", "exptypes", ".", "VoteInfo", "{", "Validation", ":", "exptypes", ".", "BlockValidation", "{", "Hash", ":", "validation", ".", "Hash", ".", "String", "(", ")", ",", "Height", ":", "validation", ".", "Height", ",", "Validity", ":", "validation", ".", "Validity", ",", "}", ",", "Version", ":", "version", ",", "Bits", ":", "bits", ",", "Choices", ":", "choices", ",", "TicketSpent", ":", "msgTx", ".", "TxIn", "[", "1", "]", ".", "PreviousOutPoint", ".", "Hash", ".", "String", "(", ")", ",", "}", "\n", "}", "\n", "}", "\n", "txs", "=", "append", "(", "txs", ",", "exptypes", ".", "MempoolTx", "{", "TxID", ":", "msgTx", ".", "TxHash", "(", ")", ".", "String", "(", ")", ",", "Hash", ":", "hashStr", ",", "Time", ":", "tx", ".", "Time", ",", "Size", ":", "tx", ".", "Size", ",", "TotalOut", ":", "total", ",", "Type", ":", "txhelpers", ".", "DetermineTxTypeString", "(", "msgTx", ")", ",", "VoteInfo", ":", "voteInfo", ",", "Vin", ":", "exptypes", ".", "MsgTxMempoolInputs", "(", "msgTx", ")", ",", "}", ")", "\n", "}", "\n\n", "return", "txs", "\n", "}" ]
// GetMempool gets all transactions from the mempool for explorer and adds the // total out for all the txs and vote info for the votes. The returned slice // will be nil if the GetRawMempoolVerbose RPC fails. A zero-length non-nil // slice is returned if there are no transactions in mempool.
[ "GetMempool", "gets", "all", "transactions", "from", "the", "mempool", "for", "explorer", "and", "adds", "the", "total", "out", "for", "all", "the", "txs", "and", "vote", "info", "for", "the", "votes", ".", "The", "returned", "slice", "will", "be", "nil", "if", "the", "GetRawMempoolVerbose", "RPC", "fails", ".", "A", "zero", "-", "length", "non", "-", "nil", "slice", "is", "returned", "if", "there", "are", "no", "transactions", "in", "mempool", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L1706-L1766
train
decred/dcrdata
db/dcrsqlite/apisource.go
TxHeight
func (db *WiredDB) TxHeight(txid *chainhash.Hash) (height int64) { txraw, err := db.client.GetRawTransactionVerbose(txid) if err != nil { log.Errorf("GetRawTransactionVerbose failed for: %v", txid) return 0 } height = txraw.BlockHeight return }
go
func (db *WiredDB) TxHeight(txid *chainhash.Hash) (height int64) { txraw, err := db.client.GetRawTransactionVerbose(txid) if err != nil { log.Errorf("GetRawTransactionVerbose failed for: %v", txid) return 0 } height = txraw.BlockHeight return }
[ "func", "(", "db", "*", "WiredDB", ")", "TxHeight", "(", "txid", "*", "chainhash", ".", "Hash", ")", "(", "height", "int64", ")", "{", "txraw", ",", "err", ":=", "db", ".", "client", ".", "GetRawTransactionVerbose", "(", "txid", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "txid", ")", "\n", "return", "0", "\n", "}", "\n", "height", "=", "txraw", ".", "BlockHeight", "\n", "return", "\n", "}" ]
// TxHeight gives the block height of the transaction id specified
[ "TxHeight", "gives", "the", "block", "height", "of", "the", "transaction", "id", "specified" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L1769-L1777
train
decred/dcrdata
db/dcrsqlite/apisource.go
Difficulty
func (db *WiredDB) Difficulty() (float64, error) { diff, err := db.client.GetDifficulty() if err != nil { log.Error("GetDifficulty failed") return diff, err } return diff, nil }
go
func (db *WiredDB) Difficulty() (float64, error) { diff, err := db.client.GetDifficulty() if err != nil { log.Error("GetDifficulty failed") return diff, err } return diff, nil }
[ "func", "(", "db", "*", "WiredDB", ")", "Difficulty", "(", ")", "(", "float64", ",", "error", ")", "{", "diff", ",", "err", ":=", "db", ".", "client", ".", "GetDifficulty", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "diff", ",", "err", "\n", "}", "\n", "return", "diff", ",", "nil", "\n", "}" ]
// Difficulty returns the difficulty.
[ "Difficulty", "returns", "the", "difficulty", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L1780-L1787
train
decred/dcrdata
db/dcrsqlite/apisource.go
GetTip
func (db *WiredDB) GetTip() (*exptypes.WebBasicBlock, error) { tip, err := db.DB.getTip() if err != nil { return nil, err } blockdata := exptypes.WebBasicBlock{ Height: tip.Height, Size: tip.Size, Hash: tip.Hash, Difficulty: tip.Difficulty, StakeDiff: tip.StakeDiff, Time: tip.Time.S.UNIX(), NumTx: tip.NumTx, PoolSize: tip.PoolInfo.Size, PoolValue: tip.PoolInfo.Value, PoolValAvg: tip.PoolInfo.ValAvg, PoolWinners: tip.PoolInfo.Winners, } return &blockdata, nil }
go
func (db *WiredDB) GetTip() (*exptypes.WebBasicBlock, error) { tip, err := db.DB.getTip() if err != nil { return nil, err } blockdata := exptypes.WebBasicBlock{ Height: tip.Height, Size: tip.Size, Hash: tip.Hash, Difficulty: tip.Difficulty, StakeDiff: tip.StakeDiff, Time: tip.Time.S.UNIX(), NumTx: tip.NumTx, PoolSize: tip.PoolInfo.Size, PoolValue: tip.PoolInfo.Value, PoolValAvg: tip.PoolInfo.ValAvg, PoolWinners: tip.PoolInfo.Winners, } return &blockdata, nil }
[ "func", "(", "db", "*", "WiredDB", ")", "GetTip", "(", ")", "(", "*", "exptypes", ".", "WebBasicBlock", ",", "error", ")", "{", "tip", ",", "err", ":=", "db", ".", "DB", ".", "getTip", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "blockdata", ":=", "exptypes", ".", "WebBasicBlock", "{", "Height", ":", "tip", ".", "Height", ",", "Size", ":", "tip", ".", "Size", ",", "Hash", ":", "tip", ".", "Hash", ",", "Difficulty", ":", "tip", ".", "Difficulty", ",", "StakeDiff", ":", "tip", ".", "StakeDiff", ",", "Time", ":", "tip", ".", "Time", ".", "S", ".", "UNIX", "(", ")", ",", "NumTx", ":", "tip", ".", "NumTx", ",", "PoolSize", ":", "tip", ".", "PoolInfo", ".", "Size", ",", "PoolValue", ":", "tip", ".", "PoolInfo", ".", "Value", ",", "PoolValAvg", ":", "tip", ".", "PoolInfo", ".", "ValAvg", ",", "PoolWinners", ":", "tip", ".", "PoolInfo", ".", "Winners", ",", "}", "\n", "return", "&", "blockdata", ",", "nil", "\n", "}" ]
// GetTip grabs the highest block stored in the database.
[ "GetTip", "grabs", "the", "highest", "block", "stored", "in", "the", "database", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/apisource.go#L1790-L1809
train
decred/dcrdata
api/types/apitypes.go
MarshalJSON
func (t *TimeAPI) MarshalJSON() ([]byte, error) { return json.Marshal(t.S.UNIX()) }
go
func (t *TimeAPI) MarshalJSON() ([]byte, error) { return json.Marshal(t.S.UNIX()) }
[ "func", "(", "t", "*", "TimeAPI", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "t", ".", "S", ".", "UNIX", "(", ")", ")", "\n", "}" ]
// MarshalJSON is set as the default marshalling function for TimeAPI struct.
[ "MarshalJSON", "is", "set", "as", "the", "default", "marshalling", "function", "for", "TimeAPI", "struct", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apitypes.go#L37-L39
train
decred/dcrdata
api/types/apitypes.go
NewTimeAPI
func NewTimeAPI(t time.Time) TimeAPI { return TimeAPI{ S: dbtypes.NewTimeDef(t), } }
go
func NewTimeAPI(t time.Time) TimeAPI { return TimeAPI{ S: dbtypes.NewTimeDef(t), } }
[ "func", "NewTimeAPI", "(", "t", "time", ".", "Time", ")", "TimeAPI", "{", "return", "TimeAPI", "{", "S", ":", "dbtypes", ".", "NewTimeDef", "(", "t", ")", ",", "}", "\n", "}" ]
// NewTimeAPI constructs a TimeAPI from the given time.Time. It presets the // timezone for formatting to UTC.
[ "NewTimeAPI", "constructs", "a", "TimeAPI", "from", "the", "given", "time", ".", "Time", ".", "It", "presets", "the", "timezone", "for", "formatting", "to", "UTC", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apitypes.go#L56-L60
train
decred/dcrdata
api/types/apitypes.go
String
func (sc ScriptClass) String() string { name, found := scriptClassToName[sc] if !found { return ScriptClassInvalid.String() // better be in scriptClassToName! } return name }
go
func (sc ScriptClass) String() string { name, found := scriptClassToName[sc] if !found { return ScriptClassInvalid.String() // better be in scriptClassToName! } return name }
[ "func", "(", "sc", "ScriptClass", ")", "String", "(", ")", "string", "{", "name", ",", "found", ":=", "scriptClassToName", "[", "sc", "]", "\n", "if", "!", "found", "{", "return", "ScriptClassInvalid", ".", "String", "(", ")", "// better be in scriptClassToName!", "\n", "}", "\n", "return", "name", "\n", "}" ]
// String returns the name of the ScriptClass. If the ScriptClass is // unrecognized it is treated as ScriptClassInvalid.
[ "String", "returns", "the", "name", "of", "the", "ScriptClass", ".", "If", "the", "ScriptClass", "is", "unrecognized", "it", "is", "treated", "as", "ScriptClassInvalid", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apitypes.go#L265-L271
train
decred/dcrdata
api/types/apitypes.go
NewStatus
func NewStatus(nodeHeight uint32, conns int64, apiVersion int, dcrdataVersion, netName string) *Status { return &Status{ height: nodeHeight, nodeConnections: conns, api: APIStatus{ APIVersion: apiVersion, DcrdataVersion: dcrdataVersion, NetworkName: netName, }, } }
go
func NewStatus(nodeHeight uint32, conns int64, apiVersion int, dcrdataVersion, netName string) *Status { return &Status{ height: nodeHeight, nodeConnections: conns, api: APIStatus{ APIVersion: apiVersion, DcrdataVersion: dcrdataVersion, NetworkName: netName, }, } }
[ "func", "NewStatus", "(", "nodeHeight", "uint32", ",", "conns", "int64", ",", "apiVersion", "int", ",", "dcrdataVersion", ",", "netName", "string", ")", "*", "Status", "{", "return", "&", "Status", "{", "height", ":", "nodeHeight", ",", "nodeConnections", ":", "conns", ",", "api", ":", "APIStatus", "{", "APIVersion", ":", "apiVersion", ",", "DcrdataVersion", ":", "dcrdataVersion", ",", "NetworkName", ":", "netName", ",", "}", ",", "}", "\n", "}" ]
// NewStatus is the constructor for a new Status.
[ "NewStatus", "is", "the", "constructor", "for", "a", "new", "Status", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apitypes.go#L435-L445
train
decred/dcrdata
api/types/apitypes.go
API
func (s *Status) API() APIStatus { s.RLock() defer s.RUnlock() return APIStatus{ Ready: s.ready, DBHeight: s.dbHeight, DBLastBlockTime: s.dbLastBlockTime, Height: s.height, NodeConnections: s.nodeConnections, APIVersion: s.api.APIVersion, DcrdataVersion: s.api.DcrdataVersion, NetworkName: s.api.NetworkName, } }
go
func (s *Status) API() APIStatus { s.RLock() defer s.RUnlock() return APIStatus{ Ready: s.ready, DBHeight: s.dbHeight, DBLastBlockTime: s.dbLastBlockTime, Height: s.height, NodeConnections: s.nodeConnections, APIVersion: s.api.APIVersion, DcrdataVersion: s.api.DcrdataVersion, NetworkName: s.api.NetworkName, } }
[ "func", "(", "s", "*", "Status", ")", "API", "(", ")", "APIStatus", "{", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n", "return", "APIStatus", "{", "Ready", ":", "s", ".", "ready", ",", "DBHeight", ":", "s", ".", "dbHeight", ",", "DBLastBlockTime", ":", "s", ".", "dbLastBlockTime", ",", "Height", ":", "s", ".", "height", ",", "NodeConnections", ":", "s", ".", "nodeConnections", ",", "APIVersion", ":", "s", ".", "api", ".", "APIVersion", ",", "DcrdataVersion", ":", "s", ".", "api", ".", "DcrdataVersion", ",", "NetworkName", ":", "s", ".", "api", ".", "NetworkName", ",", "}", "\n", "}" ]
// API is a method for creating an APIStatus from Status.
[ "API", "is", "a", "method", "for", "creating", "an", "APIStatus", "from", "Status", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apitypes.go#L448-L461
train
decred/dcrdata
api/types/apitypes.go
Height
func (s *Status) Height() uint32 { s.RLock() defer s.RUnlock() return s.height }
go
func (s *Status) Height() uint32 { s.RLock() defer s.RUnlock() return s.height }
[ "func", "(", "s", "*", "Status", ")", "Height", "(", ")", "uint32", "{", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n", "return", "s", ".", "height", "\n", "}" ]
// Height is the last known node height.
[ "Height", "is", "the", "last", "known", "node", "height", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apitypes.go#L464-L468
train
decred/dcrdata
api/types/apitypes.go
SetHeight
func (s *Status) SetHeight(height uint32) { s.Lock() defer s.Unlock() s.ready = height == s.dbHeight s.height = height }
go
func (s *Status) SetHeight(height uint32) { s.Lock() defer s.Unlock() s.ready = height == s.dbHeight s.height = height }
[ "func", "(", "s", "*", "Status", ")", "SetHeight", "(", "height", "uint32", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n", "s", ".", "ready", "=", "height", "==", "s", ".", "dbHeight", "\n", "s", ".", "height", "=", "height", "\n", "}" ]
// SetHeight stores the node height. Additionally, Status.ready is set to true // if Status.height is the same as Status.dbHeight.
[ "SetHeight", "stores", "the", "node", "height", ".", "Additionally", "Status", ".", "ready", "is", "set", "to", "true", "if", "Status", ".", "height", "is", "the", "same", "as", "Status", ".", "dbHeight", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apitypes.go#L472-L477
train
decred/dcrdata
api/types/apitypes.go
SetHeightAndConnections
func (s *Status) SetHeightAndConnections(height uint32, conns int64) { s.Lock() defer s.Unlock() s.nodeConnections = conns s.ready = height == s.dbHeight s.height = height }
go
func (s *Status) SetHeightAndConnections(height uint32, conns int64) { s.Lock() defer s.Unlock() s.nodeConnections = conns s.ready = height == s.dbHeight s.height = height }
[ "func", "(", "s", "*", "Status", ")", "SetHeightAndConnections", "(", "height", "uint32", ",", "conns", "int64", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n", "s", ".", "nodeConnections", "=", "conns", "\n", "s", ".", "ready", "=", "height", "==", "s", ".", "dbHeight", "\n", "s", ".", "height", "=", "height", "\n", "}" ]
// SetHeightAndConnections simultaneously sets the node height and node // connection count. Status.ready is set to true if the height and dbHeight are // the same.
[ "SetHeightAndConnections", "simultaneously", "sets", "the", "node", "height", "and", "node", "connection", "count", ".", "Status", ".", "ready", "is", "set", "to", "true", "if", "the", "height", "and", "dbHeight", "are", "the", "same", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apitypes.go#L482-L488
train
decred/dcrdata
api/types/apitypes.go
SetReady
func (s *Status) SetReady(ready bool) { s.Lock() defer s.Unlock() s.ready = ready }
go
func (s *Status) SetReady(ready bool) { s.Lock() defer s.Unlock() s.ready = ready }
[ "func", "(", "s", "*", "Status", ")", "SetReady", "(", "ready", "bool", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n", "s", ".", "ready", "=", "ready", "\n", "}" ]
// SetReady sets the ready state.
[ "SetReady", "sets", "the", "ready", "state", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apitypes.go#L491-L495
train
decred/dcrdata
api/types/apitypes.go
DBUpdate
func (s *Status) DBUpdate(height uint32, blockTime int64) { s.Lock() defer s.Unlock() s.dbHeight = height s.dbLastBlockTime = blockTime s.ready = s.dbHeight == height }
go
func (s *Status) DBUpdate(height uint32, blockTime int64) { s.Lock() defer s.Unlock() s.dbHeight = height s.dbLastBlockTime = blockTime s.ready = s.dbHeight == height }
[ "func", "(", "s", "*", "Status", ")", "DBUpdate", "(", "height", "uint32", ",", "blockTime", "int64", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n", "s", ".", "dbHeight", "=", "height", "\n", "s", ".", "dbLastBlockTime", "=", "blockTime", "\n", "s", ".", "ready", "=", "s", ".", "dbHeight", "==", "height", "\n", "}" ]
// DBUpdate updates both the height and time of the best DB block. Status.ready // is set to true if Status.height is the same as Status.dbHeight.
[ "DBUpdate", "updates", "both", "the", "height", "and", "time", "of", "the", "best", "DB", "block", ".", "Status", ".", "ready", "is", "set", "to", "true", "if", "Status", ".", "height", "is", "the", "same", "as", "Status", ".", "dbHeight", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/types/apitypes.go#L499-L505
train
decred/dcrdata
db/dcrpg/upgrades.go
String
func (v DatabaseVersion) String() string { return fmt.Sprintf("%d.%d.%d", v.compat, v.schema, v.maint) }
go
func (v DatabaseVersion) String() string { return fmt.Sprintf("%d.%d.%d", v.compat, v.schema, v.maint) }
[ "func", "(", "v", "DatabaseVersion", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "v", ".", "compat", ",", "v", ".", "schema", ",", "v", ".", "maint", ")", "\n", "}" ]
// String implements Stringer for DatabaseVersion.
[ "String", "implements", "Stringer", "for", "DatabaseVersion", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades.go#L52-L54
train
decred/dcrdata
db/dcrpg/upgrades.go
NewDatabaseVersion
func NewDatabaseVersion(major, minor, patch uint32) DatabaseVersion { return DatabaseVersion{major, minor, patch} }
go
func NewDatabaseVersion(major, minor, patch uint32) DatabaseVersion { return DatabaseVersion{major, minor, patch} }
[ "func", "NewDatabaseVersion", "(", "major", ",", "minor", ",", "patch", "uint32", ")", "DatabaseVersion", "{", "return", "DatabaseVersion", "{", "major", ",", "minor", ",", "patch", "}", "\n", "}" ]
// NewDatabaseVersion returns a new DatabaseVersion with the version major.minor.patch
[ "NewDatabaseVersion", "returns", "a", "new", "DatabaseVersion", "with", "the", "version", "major", ".", "minor", ".", "patch" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades.go#L57-L59
train
decred/dcrdata
db/dcrpg/upgrades.go
NeededToReach
func (v *DatabaseVersion) NeededToReach(other *DatabaseVersion) CompatAction { switch { case v.compat < other.compat: return Rebuild case v.compat < other.compat: return TimeTravel case v.schema < other.schema: return Upgrade case v.schema > other.schema: return TimeTravel case v.maint < other.maint: return Maintenance case v.maint > other.maint: return TimeTravel default: return OK } }
go
func (v *DatabaseVersion) NeededToReach(other *DatabaseVersion) CompatAction { switch { case v.compat < other.compat: return Rebuild case v.compat < other.compat: return TimeTravel case v.schema < other.schema: return Upgrade case v.schema > other.schema: return TimeTravel case v.maint < other.maint: return Maintenance case v.maint > other.maint: return TimeTravel default: return OK } }
[ "func", "(", "v", "*", "DatabaseVersion", ")", "NeededToReach", "(", "other", "*", "DatabaseVersion", ")", "CompatAction", "{", "switch", "{", "case", "v", ".", "compat", "<", "other", ".", "compat", ":", "return", "Rebuild", "\n", "case", "v", ".", "compat", "<", "other", ".", "compat", ":", "return", "TimeTravel", "\n", "case", "v", ".", "schema", "<", "other", ".", "schema", ":", "return", "Upgrade", "\n", "case", "v", ".", "schema", ">", "other", ".", "schema", ":", "return", "TimeTravel", "\n", "case", "v", ".", "maint", "<", "other", ".", "maint", ":", "return", "Maintenance", "\n", "case", "v", ".", "maint", ">", "other", ".", "maint", ":", "return", "TimeTravel", "\n", "default", ":", "return", "OK", "\n", "}", "\n", "}" ]
// NeededToReach describes what action is required for the DatabaseVersion to // reach another version provided in the input argument.
[ "NeededToReach", "describes", "what", "action", "is", "required", "for", "the", "DatabaseVersion", "to", "reach", "another", "version", "provided", "in", "the", "input", "argument", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades.go#L83-L100
train
decred/dcrdata
db/dcrpg/upgrades.go
String
func (v CompatAction) String() string { actions := map[CompatAction]string{ Rebuild: "rebuild", Upgrade: "upgrade", Maintenance: "maintenance", TimeTravel: "time travel", OK: "ok", } if actionStr, ok := actions[v]; ok { return actionStr } return "unknown" }
go
func (v CompatAction) String() string { actions := map[CompatAction]string{ Rebuild: "rebuild", Upgrade: "upgrade", Maintenance: "maintenance", TimeTravel: "time travel", OK: "ok", } if actionStr, ok := actions[v]; ok { return actionStr } return "unknown" }
[ "func", "(", "v", "CompatAction", ")", "String", "(", ")", "string", "{", "actions", ":=", "map", "[", "CompatAction", "]", "string", "{", "Rebuild", ":", "\"", "\"", ",", "Upgrade", ":", "\"", "\"", ",", "Maintenance", ":", "\"", "\"", ",", "TimeTravel", ":", "\"", "\"", ",", "OK", ":", "\"", "\"", ",", "}", "\n", "if", "actionStr", ",", "ok", ":=", "actions", "[", "v", "]", ";", "ok", "{", "return", "actionStr", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// String implements Stringer for CompatAction.
[ "String", "implements", "Stringer", "for", "CompatAction", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/upgrades.go#L103-L115
train
decred/dcrdata
dcrrates/rateserver/types.go
NewRateServer
func NewRateServer(index string, xcBot *exchanges.ExchangeBot) *RateServer { return &RateServer{ btcIndex: index, clientLock: new(sync.RWMutex), clients: make(map[StreamID]RateClient), xcBot: xcBot, } }
go
func NewRateServer(index string, xcBot *exchanges.ExchangeBot) *RateServer { return &RateServer{ btcIndex: index, clientLock: new(sync.RWMutex), clients: make(map[StreamID]RateClient), xcBot: xcBot, } }
[ "func", "NewRateServer", "(", "index", "string", ",", "xcBot", "*", "exchanges", ".", "ExchangeBot", ")", "*", "RateServer", "{", "return", "&", "RateServer", "{", "btcIndex", ":", "index", ",", "clientLock", ":", "new", "(", "sync", ".", "RWMutex", ")", ",", "clients", ":", "make", "(", "map", "[", "StreamID", "]", "RateClient", ")", ",", "xcBot", ":", "xcBot", ",", "}", "\n", "}" ]
// NewRateServer is a constructor for a RateServer.
[ "NewRateServer", "is", "a", "constructor", "for", "a", "RateServer", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/dcrrates/rateserver/types.go#L37-L44
train
decred/dcrdata
dcrrates/rateserver/types.go
sendStateList
func sendStateList(client RateClient, states map[string]*exchanges.ExchangeState) (err error) { for token, state := range states { err = client.SendExchangeUpdate(makeExchangeRateUpdate(&exchanges.ExchangeUpdate{ Token: token, State: state, })) if err != nil { log.Errorf("SendExchangeUpdate error for %s: %v", token, err) return } } return }
go
func sendStateList(client RateClient, states map[string]*exchanges.ExchangeState) (err error) { for token, state := range states { err = client.SendExchangeUpdate(makeExchangeRateUpdate(&exchanges.ExchangeUpdate{ Token: token, State: state, })) if err != nil { log.Errorf("SendExchangeUpdate error for %s: %v", token, err) return } } return }
[ "func", "sendStateList", "(", "client", "RateClient", ",", "states", "map", "[", "string", "]", "*", "exchanges", ".", "ExchangeState", ")", "(", "err", "error", ")", "{", "for", "token", ",", "state", ":=", "range", "states", "{", "err", "=", "client", ".", "SendExchangeUpdate", "(", "makeExchangeRateUpdate", "(", "&", "exchanges", ".", "ExchangeUpdate", "{", "Token", ":", "token", ",", "State", ":", "state", ",", "}", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "token", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// sendStateList is a helper for parsing the ExchangeBotState when a new client // subscription is received.
[ "sendStateList", "is", "a", "helper", "for", "parsing", "the", "ExchangeBotState", "when", "a", "new", "client", "subscription", "is", "received", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/dcrrates/rateserver/types.go#L54-L66
train
decred/dcrdata
dcrrates/rateserver/types.go
ReallySubscribeExchanges
func (server *RateServer) ReallySubscribeExchanges(hello *dcrrates.ExchangeSubscription, stream GRPCStream) (err error) { // For now, require the ExchangeBot clients to have the same base currency. // ToDo: Allow any index. if hello.BtcIndex != server.btcIndex { return fmt.Errorf("Exchange subscription has wrong BTC index. Given: %s, Required: %s", hello.BtcIndex, server.btcIndex) } // Save the client for use in the main loop. client, sid := server.addClient(stream, hello) // Get the address for an Infof. Seems like peerInfo is always found, but // am checking anyway. peerInfo, peerFound := grpcPeer.FromContext(client.Stream().Context()) var clientAddr string if peerFound { clientAddr = peerInfo.Addr.String() log.Infof("Client has connected from %s", clientAddr) } state := server.xcBot.State() // Send Decred exchanges. err = sendStateList(client, state.DcrBtc) if err != nil { return err } // Send Bitcoin-fiat indices. for token := range state.FiatIndices { err = client.SendExchangeUpdate(&dcrrates.ExchangeRateUpdate{ Token: token, Indices: server.xcBot.Indices(token), }) if err != nil { log.Errorf("Error encountered while sending fiat indices to client at %s: %v", clientAddr, err) // Assuming the Done channel will be closed on error, no further iteration // is necessary. break } } // Keep stream alive. <-client.Stream().Context().Done() server.deleteClient(sid) log.Infof("Client at %s has disconnected", clientAddr) return }
go
func (server *RateServer) ReallySubscribeExchanges(hello *dcrrates.ExchangeSubscription, stream GRPCStream) (err error) { // For now, require the ExchangeBot clients to have the same base currency. // ToDo: Allow any index. if hello.BtcIndex != server.btcIndex { return fmt.Errorf("Exchange subscription has wrong BTC index. Given: %s, Required: %s", hello.BtcIndex, server.btcIndex) } // Save the client for use in the main loop. client, sid := server.addClient(stream, hello) // Get the address for an Infof. Seems like peerInfo is always found, but // am checking anyway. peerInfo, peerFound := grpcPeer.FromContext(client.Stream().Context()) var clientAddr string if peerFound { clientAddr = peerInfo.Addr.String() log.Infof("Client has connected from %s", clientAddr) } state := server.xcBot.State() // Send Decred exchanges. err = sendStateList(client, state.DcrBtc) if err != nil { return err } // Send Bitcoin-fiat indices. for token := range state.FiatIndices { err = client.SendExchangeUpdate(&dcrrates.ExchangeRateUpdate{ Token: token, Indices: server.xcBot.Indices(token), }) if err != nil { log.Errorf("Error encountered while sending fiat indices to client at %s: %v", clientAddr, err) // Assuming the Done channel will be closed on error, no further iteration // is necessary. break } } // Keep stream alive. <-client.Stream().Context().Done() server.deleteClient(sid) log.Infof("Client at %s has disconnected", clientAddr) return }
[ "func", "(", "server", "*", "RateServer", ")", "ReallySubscribeExchanges", "(", "hello", "*", "dcrrates", ".", "ExchangeSubscription", ",", "stream", "GRPCStream", ")", "(", "err", "error", ")", "{", "// For now, require the ExchangeBot clients to have the same base currency.", "// ToDo: Allow any index.", "if", "hello", ".", "BtcIndex", "!=", "server", ".", "btcIndex", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hello", ".", "BtcIndex", ",", "server", ".", "btcIndex", ")", "\n", "}", "\n", "// Save the client for use in the main loop.", "client", ",", "sid", ":=", "server", ".", "addClient", "(", "stream", ",", "hello", ")", "\n\n", "// Get the address for an Infof. Seems like peerInfo is always found, but", "// am checking anyway.", "peerInfo", ",", "peerFound", ":=", "grpcPeer", ".", "FromContext", "(", "client", ".", "Stream", "(", ")", ".", "Context", "(", ")", ")", "\n", "var", "clientAddr", "string", "\n", "if", "peerFound", "{", "clientAddr", "=", "peerInfo", ".", "Addr", ".", "String", "(", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "clientAddr", ")", "\n", "}", "\n\n", "state", ":=", "server", ".", "xcBot", ".", "State", "(", ")", "\n", "// Send Decred exchanges.", "err", "=", "sendStateList", "(", "client", ",", "state", ".", "DcrBtc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Send Bitcoin-fiat indices.", "for", "token", ":=", "range", "state", ".", "FiatIndices", "{", "err", "=", "client", ".", "SendExchangeUpdate", "(", "&", "dcrrates", ".", "ExchangeRateUpdate", "{", "Token", ":", "token", ",", "Indices", ":", "server", ".", "xcBot", ".", "Indices", "(", "token", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "clientAddr", ",", "err", ")", "\n", "// Assuming the Done channel will be closed on error, no further iteration", "// is necessary.", "break", "\n", "}", "\n", "}", "\n\n", "// Keep stream alive.", "<-", "client", ".", "Stream", "(", ")", ".", "Context", "(", ")", ".", "Done", "(", ")", "\n\n", "server", ".", "deleteClient", "(", "sid", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "clientAddr", ")", "\n", "return", "\n", "}" ]
// ReallySubscribeExchanges stores the client and their exchange subscriptions. // It waits for the client contexts Done channel to close and deletes the client // from the RateServer.clients map.
[ "ReallySubscribeExchanges", "stores", "the", "client", "and", "their", "exchange", "subscriptions", ".", "It", "waits", "for", "the", "client", "contexts", "Done", "channel", "to", "close", "and", "deletes", "the", "client", "from", "the", "RateServer", ".", "clients", "map", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/dcrrates/rateserver/types.go#L78-L122
train
decred/dcrdata
dcrrates/rateserver/types.go
addClient
func (server *RateServer) addClient(stream GRPCStream, hello *dcrrates.ExchangeSubscription) (RateClient, StreamID) { server.clientLock.Lock() defer server.clientLock.Unlock() client := NewRateClient(stream, hello.GetExchanges()) streamCounter++ server.clients[streamCounter] = client return client, streamCounter }
go
func (server *RateServer) addClient(stream GRPCStream, hello *dcrrates.ExchangeSubscription) (RateClient, StreamID) { server.clientLock.Lock() defer server.clientLock.Unlock() client := NewRateClient(stream, hello.GetExchanges()) streamCounter++ server.clients[streamCounter] = client return client, streamCounter }
[ "func", "(", "server", "*", "RateServer", ")", "addClient", "(", "stream", "GRPCStream", ",", "hello", "*", "dcrrates", ".", "ExchangeSubscription", ")", "(", "RateClient", ",", "StreamID", ")", "{", "server", ".", "clientLock", ".", "Lock", "(", ")", "\n", "defer", "server", ".", "clientLock", ".", "Unlock", "(", ")", "\n", "client", ":=", "NewRateClient", "(", "stream", ",", "hello", ".", "GetExchanges", "(", ")", ")", "\n", "streamCounter", "++", "\n", "server", ".", "clients", "[", "streamCounter", "]", "=", "client", "\n", "return", "client", ",", "streamCounter", "\n", "}" ]
// addClient adds a client to the map and advance the streamCounter.
[ "addClient", "adds", "a", "client", "to", "the", "map", "and", "advance", "the", "streamCounter", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/dcrrates/rateserver/types.go#L125-L132
train