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
stakedb/stakedb.go
DBTipBlockHeader
func (db *StakeDatabase) DBTipBlockHeader() (*wire.BlockHeader, error) { _, hash, err := db.DBState() if err != nil { return nil, err } return db.NodeClient.GetBlockHeader(hash) }
go
func (db *StakeDatabase) DBTipBlockHeader() (*wire.BlockHeader, error) { _, hash, err := db.DBState() if err != nil { return nil, err } return db.NodeClient.GetBlockHeader(hash) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "DBTipBlockHeader", "(", ")", "(", "*", "wire", ".", "BlockHeader", ",", "error", ")", "{", "_", ",", "hash", ",", "err", ":=", "db", ".", "DBState", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "db", ".", "NodeClient", ".", "GetBlockHeader", "(", "hash", ")", "\n", "}" ]
// DBTipBlockHeader gets the block header for the current best block in the // stake database. It used DBState to get the best block hash, and the node RPC // client to get the header.
[ "DBTipBlockHeader", "gets", "the", "block", "header", "for", "the", "current", "best", "block", "in", "the", "stake", "database", ".", "It", "used", "DBState", "to", "get", "the", "best", "block", "hash", "and", "the", "node", "RPC", "client", "to", "get", "the", "header", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L989-L996
train
decred/dcrdata
stakedb/stakedb.go
DBPrevBlockHeader
func (db *StakeDatabase) DBPrevBlockHeader() (*wire.BlockHeader, error) { _, hash, err := db.DBState() if err != nil { return nil, err } parentHeader, err := db.NodeClient.GetBlockHeader(hash) if err != nil { return nil, err } return db.NodeClient.GetBlockHeader(&parentHeader.PrevBlock) }
go
func (db *StakeDatabase) DBPrevBlockHeader() (*wire.BlockHeader, error) { _, hash, err := db.DBState() if err != nil { return nil, err } parentHeader, err := db.NodeClient.GetBlockHeader(hash) if err != nil { return nil, err } return db.NodeClient.GetBlockHeader(&parentHeader.PrevBlock) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "DBPrevBlockHeader", "(", ")", "(", "*", "wire", ".", "BlockHeader", ",", "error", ")", "{", "_", ",", "hash", ",", "err", ":=", "db", ".", "DBState", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "parentHeader", ",", "err", ":=", "db", ".", "NodeClient", ".", "GetBlockHeader", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "db", ".", "NodeClient", ".", "GetBlockHeader", "(", "&", "parentHeader", ".", "PrevBlock", ")", "\n", "}" ]
// DBPrevBlockHeader gets the block header for the previous best block in the // stake database. It used DBState to get the best block hash, and the node RPC // client to get the header.
[ "DBPrevBlockHeader", "gets", "the", "block", "header", "for", "the", "previous", "best", "block", "in", "the", "stake", "database", ".", "It", "used", "DBState", "to", "get", "the", "best", "block", "hash", "and", "the", "node", "RPC", "client", "to", "get", "the", "header", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L1001-L1013
train
decred/dcrdata
stakedb/stakedb.go
DBTipBlock
func (db *StakeDatabase) DBTipBlock() (*dcrutil.Block, error) { _, hash, err := db.DBState() if err != nil { return nil, err } return db.getBlock(hash) }
go
func (db *StakeDatabase) DBTipBlock() (*dcrutil.Block, error) { _, hash, err := db.DBState() if err != nil { return nil, err } return db.getBlock(hash) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "DBTipBlock", "(", ")", "(", "*", "dcrutil", ".", "Block", ",", "error", ")", "{", "_", ",", "hash", ",", "err", ":=", "db", ".", "DBState", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "db", ".", "getBlock", "(", "hash", ")", "\n", "}" ]
// DBTipBlock gets the dcrutil.Block for the current best block in the stake // database. It used DBState to get the best block hash, and the node RPC client // to get the block itself.
[ "DBTipBlock", "gets", "the", "dcrutil", ".", "Block", "for", "the", "current", "best", "block", "in", "the", "stake", "database", ".", "It", "used", "DBState", "to", "get", "the", "best", "block", "hash", "and", "the", "node", "RPC", "client", "to", "get", "the", "block", "itself", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L1018-L1025
train
decred/dcrdata
stakedb/stakedb.go
DBPrevBlock
func (db *StakeDatabase) DBPrevBlock() (*dcrutil.Block, error) { _, hash, err := db.DBState() if err != nil { return nil, err } parentHeader, err := db.NodeClient.GetBlockHeader(hash) if err != nil { return nil, err } return db.getBlock(&parentHeader.PrevBlock) }
go
func (db *StakeDatabase) DBPrevBlock() (*dcrutil.Block, error) { _, hash, err := db.DBState() if err != nil { return nil, err } parentHeader, err := db.NodeClient.GetBlockHeader(hash) if err != nil { return nil, err } return db.getBlock(&parentHeader.PrevBlock) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "DBPrevBlock", "(", ")", "(", "*", "dcrutil", ".", "Block", ",", "error", ")", "{", "_", ",", "hash", ",", "err", ":=", "db", ".", "DBState", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "parentHeader", ",", "err", ":=", "db", ".", "NodeClient", ".", "GetBlockHeader", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "db", ".", "getBlock", "(", "&", "parentHeader", ".", "PrevBlock", ")", "\n", "}" ]
// DBPrevBlock gets the dcrutil.Block for the previous best block in the stake // database. It used DBState to get the best block hash, and the node RPC client // to get the block itself.
[ "DBPrevBlock", "gets", "the", "dcrutil", ".", "Block", "for", "the", "previous", "best", "block", "in", "the", "stake", "database", ".", "It", "used", "DBState", "to", "get", "the", "best", "block", "hash", "and", "the", "node", "RPC", "client", "to", "get", "the", "block", "itself", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L1030-L1042
train
decred/dcrdata
stakedb/stakedb.go
dbPrevBlock
func (db *StakeDatabase) dbPrevBlock() (*dcrutil.Block, error) { _, hash, err := db.dbState() if err != nil { return nil, err } parentHeader, err := db.NodeClient.GetBlockHeader(hash) if err != nil { return nil, err } return db.getBlock(&parentHeader.PrevBlock) }
go
func (db *StakeDatabase) dbPrevBlock() (*dcrutil.Block, error) { _, hash, err := db.dbState() if err != nil { return nil, err } parentHeader, err := db.NodeClient.GetBlockHeader(hash) if err != nil { return nil, err } return db.getBlock(&parentHeader.PrevBlock) }
[ "func", "(", "db", "*", "StakeDatabase", ")", "dbPrevBlock", "(", ")", "(", "*", "dcrutil", ".", "Block", ",", "error", ")", "{", "_", ",", "hash", ",", "err", ":=", "db", ".", "dbState", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "parentHeader", ",", "err", ":=", "db", ".", "NodeClient", ".", "GetBlockHeader", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "db", ".", "getBlock", "(", "&", "parentHeader", ".", "PrevBlock", ")", "\n", "}" ]
// dbPrevBlock is the non-thread-safe version of DBPrevBlock.
[ "dbPrevBlock", "is", "the", "non", "-", "thread", "-", "safe", "version", "of", "DBPrevBlock", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/stakedb.go#L1045-L1057
train
decred/dcrdata
rpcutils/blockgate.go
NewBlockGate
func NewBlockGate(client BlockFetcher, capacity int) *BlockGate { return &BlockGate{ client: client, height: -1, fetchToHeight: -1, hashAtHeight: make(map[int64]chainhash.Hash), blockWithHash: make(map[chainhash.Hash]*dcrutil.Block), heightWaiters: make(map[int64][]chan chainhash.Hash), hashWaiters: make(map[chainhash.Hash][]chan int64), expireQueue: heightHashQueue{ cap: capacity, }, } }
go
func NewBlockGate(client BlockFetcher, capacity int) *BlockGate { return &BlockGate{ client: client, height: -1, fetchToHeight: -1, hashAtHeight: make(map[int64]chainhash.Hash), blockWithHash: make(map[chainhash.Hash]*dcrutil.Block), heightWaiters: make(map[int64][]chan chainhash.Hash), hashWaiters: make(map[chainhash.Hash][]chan int64), expireQueue: heightHashQueue{ cap: capacity, }, } }
[ "func", "NewBlockGate", "(", "client", "BlockFetcher", ",", "capacity", "int", ")", "*", "BlockGate", "{", "return", "&", "BlockGate", "{", "client", ":", "client", ",", "height", ":", "-", "1", ",", "fetchToHeight", ":", "-", "1", ",", "hashAtHeight", ":", "make", "(", "map", "[", "int64", "]", "chainhash", ".", "Hash", ")", ",", "blockWithHash", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "*", "dcrutil", ".", "Block", ")", ",", "heightWaiters", ":", "make", "(", "map", "[", "int64", "]", "[", "]", "chan", "chainhash", ".", "Hash", ")", ",", "hashWaiters", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "[", "]", "chan", "int64", ")", ",", "expireQueue", ":", "heightHashQueue", "{", "cap", ":", "capacity", ",", "}", ",", "}", "\n", "}" ]
// NewBlockGate constructs a new BlockGate, wrapping an RPC client, with a // specified block cache capacity.
[ "NewBlockGate", "constructs", "a", "new", "BlockGate", "wrapping", "an", "RPC", "client", "with", "a", "specified", "block", "cache", "capacity", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L83-L96
train
decred/dcrdata
rpcutils/blockgate.go
SetFetchToHeight
func (g *BlockGate) SetFetchToHeight(height int64) { g.mtx.RLock() defer g.mtx.RUnlock() g.fetchToHeight = height }
go
func (g *BlockGate) SetFetchToHeight(height int64) { g.mtx.RLock() defer g.mtx.RUnlock() g.fetchToHeight = height }
[ "func", "(", "g", "*", "BlockGate", ")", "SetFetchToHeight", "(", "height", "int64", ")", "{", "g", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "g", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "g", ".", "fetchToHeight", "=", "height", "\n", "}" ]
// SetFetchToHeight sets the height up to which WaitForHeight will trigger an // RPC to retrieve the block immediately. For the given height and up, // WaitForHeight will only return a notification channel.
[ "SetFetchToHeight", "sets", "the", "height", "up", "to", "which", "WaitForHeight", "will", "trigger", "an", "RPC", "to", "retrieve", "the", "block", "immediately", ".", "For", "the", "given", "height", "and", "up", "WaitForHeight", "will", "only", "return", "a", "notification", "channel", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L101-L105
train
decred/dcrdata
rpcutils/blockgate.go
NodeHeight
func (g *BlockGate) NodeHeight() (int64, error) { _, height, err := g.client.GetBestBlock() return height, err }
go
func (g *BlockGate) NodeHeight() (int64, error) { _, height, err := g.client.GetBestBlock() return height, err }
[ "func", "(", "g", "*", "BlockGate", ")", "NodeHeight", "(", ")", "(", "int64", ",", "error", ")", "{", "_", ",", "height", ",", "err", ":=", "g", ".", "client", ".", "GetBestBlock", "(", ")", "\n", "return", "height", ",", "err", "\n", "}" ]
// NodeHeight gets the chain height from dcrd.
[ "NodeHeight", "gets", "the", "chain", "height", "from", "dcrd", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L108-L111
train
decred/dcrdata
rpcutils/blockgate.go
BestBlockHeight
func (g *BlockGate) BestBlockHeight() int64 { g.mtx.RLock() defer g.mtx.RUnlock() return g.height }
go
func (g *BlockGate) BestBlockHeight() int64 { g.mtx.RLock() defer g.mtx.RUnlock() return g.height }
[ "func", "(", "g", "*", "BlockGate", ")", "BestBlockHeight", "(", ")", "int64", "{", "g", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "g", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "g", ".", "height", "\n", "}" ]
// BestBlockHeight gets the best block height in the block cache.
[ "BestBlockHeight", "gets", "the", "best", "block", "height", "in", "the", "block", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L114-L118
train
decred/dcrdata
rpcutils/blockgate.go
BestBlockHash
func (g *BlockGate) BestBlockHash() (chainhash.Hash, int64, error) { g.mtx.RLock() defer g.mtx.RUnlock() var err error hash, ok := g.hashAtHeight[g.height] if !ok { err = fmt.Errorf("hash of best block %d not found", g.height) } return hash, g.height, err }
go
func (g *BlockGate) BestBlockHash() (chainhash.Hash, int64, error) { g.mtx.RLock() defer g.mtx.RUnlock() var err error hash, ok := g.hashAtHeight[g.height] if !ok { err = fmt.Errorf("hash of best block %d not found", g.height) } return hash, g.height, err }
[ "func", "(", "g", "*", "BlockGate", ")", "BestBlockHash", "(", ")", "(", "chainhash", ".", "Hash", ",", "int64", ",", "error", ")", "{", "g", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "g", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "var", "err", "error", "\n", "hash", ",", "ok", ":=", "g", ".", "hashAtHeight", "[", "g", ".", "height", "]", "\n", "if", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "g", ".", "height", ")", "\n", "}", "\n", "return", "hash", ",", "g", ".", "height", ",", "err", "\n", "}" ]
// BestBlockHash gets the hash and height of the best block in cache.
[ "BestBlockHash", "gets", "the", "hash", "and", "height", "of", "the", "best", "block", "in", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L121-L130
train
decred/dcrdata
rpcutils/blockgate.go
BestBlock
func (g *BlockGate) BestBlock() (*dcrutil.Block, error) { g.mtx.RLock() defer g.mtx.RUnlock() var err error hash, ok := g.hashAtHeight[g.height] if !ok { err = fmt.Errorf("hash of best block %d not found", g.height) } block, ok := g.blockWithHash[hash] if !ok { err = fmt.Errorf("block %d at height %d not found", hash, g.height) } return block, err }
go
func (g *BlockGate) BestBlock() (*dcrutil.Block, error) { g.mtx.RLock() defer g.mtx.RUnlock() var err error hash, ok := g.hashAtHeight[g.height] if !ok { err = fmt.Errorf("hash of best block %d not found", g.height) } block, ok := g.blockWithHash[hash] if !ok { err = fmt.Errorf("block %d at height %d not found", hash, g.height) } return block, err }
[ "func", "(", "g", "*", "BlockGate", ")", "BestBlock", "(", ")", "(", "*", "dcrutil", ".", "Block", ",", "error", ")", "{", "g", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "g", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "var", "err", "error", "\n", "hash", ",", "ok", ":=", "g", ".", "hashAtHeight", "[", "g", ".", "height", "]", "\n", "if", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "g", ".", "height", ")", "\n", "}", "\n", "block", ",", "ok", ":=", "g", ".", "blockWithHash", "[", "hash", "]", "\n", "if", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hash", ",", "g", ".", "height", ")", "\n", "}", "\n", "return", "block", ",", "err", "\n", "}" ]
// BestBlock gets the best block in cache.
[ "BestBlock", "gets", "the", "best", "block", "in", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L133-L146
train
decred/dcrdata
rpcutils/blockgate.go
CachedBlock
func (g *BlockGate) CachedBlock(hash chainhash.Hash) (*dcrutil.Block, error) { g.mtx.RLock() defer g.mtx.RUnlock() block, ok := g.blockWithHash[hash] if !ok { return nil, fmt.Errorf("block %d not found", hash) } return block, nil }
go
func (g *BlockGate) CachedBlock(hash chainhash.Hash) (*dcrutil.Block, error) { g.mtx.RLock() defer g.mtx.RUnlock() block, ok := g.blockWithHash[hash] if !ok { return nil, fmt.Errorf("block %d not found", hash) } return block, nil }
[ "func", "(", "g", "*", "BlockGate", ")", "CachedBlock", "(", "hash", "chainhash", ".", "Hash", ")", "(", "*", "dcrutil", ".", "Block", ",", "error", ")", "{", "g", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "g", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "block", ",", "ok", ":=", "g", ".", "blockWithHash", "[", "hash", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hash", ")", "\n", "}", "\n", "return", "block", ",", "nil", "\n", "}" ]
// CachedBlock attempts to get the block with the specified hash from cache.
[ "CachedBlock", "attempts", "to", "get", "the", "block", "with", "the", "specified", "hash", "from", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L149-L157
train
decred/dcrdata
rpcutils/blockgate.go
Block
func (g *BlockGate) Block(hash chainhash.Hash) (*dcrutil.Block, error) { // Try block cache first. block, err := g.CachedBlock(hash) if err == nil { return block, nil } // Cache miss. Retrieve from dcrd RPC. block, err = GetBlockByHash(&hash, g.client) if err != nil { return nil, fmt.Errorf("GetBlock (%v) failed: %v", hash, err) } g.mtx.RLock() fmt.Printf("Block cache miss: requested %d, cache capacity %d, tip %d.", block.Height(), g.expireQueue.cap, g.height) g.mtx.RUnlock() return block, nil }
go
func (g *BlockGate) Block(hash chainhash.Hash) (*dcrutil.Block, error) { // Try block cache first. block, err := g.CachedBlock(hash) if err == nil { return block, nil } // Cache miss. Retrieve from dcrd RPC. block, err = GetBlockByHash(&hash, g.client) if err != nil { return nil, fmt.Errorf("GetBlock (%v) failed: %v", hash, err) } g.mtx.RLock() fmt.Printf("Block cache miss: requested %d, cache capacity %d, tip %d.", block.Height(), g.expireQueue.cap, g.height) g.mtx.RUnlock() return block, nil }
[ "func", "(", "g", "*", "BlockGate", ")", "Block", "(", "hash", "chainhash", ".", "Hash", ")", "(", "*", "dcrutil", ".", "Block", ",", "error", ")", "{", "// Try block cache first.", "block", ",", "err", ":=", "g", ".", "CachedBlock", "(", "hash", ")", "\n", "if", "err", "==", "nil", "{", "return", "block", ",", "nil", "\n", "}", "\n\n", "// Cache miss. Retrieve from dcrd RPC.", "block", ",", "err", "=", "GetBlockByHash", "(", "&", "hash", ",", "g", ".", "client", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hash", ",", "err", ")", "\n", "}", "\n\n", "g", ".", "mtx", ".", "RLock", "(", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\"", ",", "block", ".", "Height", "(", ")", ",", "g", ".", "expireQueue", ".", "cap", ",", "g", ".", "height", ")", "\n", "g", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "block", ",", "nil", "\n", "}" ]
// Block first attempts to get the block with the specified hash from cache. In // the event of a cache miss, the block is retrieved from dcrd via RPC.
[ "Block", "first", "attempts", "to", "get", "the", "block", "with", "the", "specified", "hash", "from", "cache", ".", "In", "the", "event", "of", "a", "cache", "miss", "the", "block", "is", "retrieved", "from", "dcrd", "via", "RPC", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L161-L179
train
decred/dcrdata
rpcutils/blockgate.go
UpdateToBestBlock
func (g *BlockGate) UpdateToBestBlock() (*dcrutil.Block, error) { _, height, err := g.client.GetBestBlock() if err != nil { return nil, fmt.Errorf("GetBestBlockHash failed: %v", err) } return g.UpdateToBlock(height) }
go
func (g *BlockGate) UpdateToBestBlock() (*dcrutil.Block, error) { _, height, err := g.client.GetBestBlock() if err != nil { return nil, fmt.Errorf("GetBestBlockHash failed: %v", err) } return g.UpdateToBlock(height) }
[ "func", "(", "g", "*", "BlockGate", ")", "UpdateToBestBlock", "(", ")", "(", "*", "dcrutil", ".", "Block", ",", "error", ")", "{", "_", ",", "height", ",", "err", ":=", "g", ".", "client", ".", "GetBestBlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "g", ".", "UpdateToBlock", "(", "height", ")", "\n", "}" ]
// UpdateToBestBlock gets the best block via RPC and updates the cache.
[ "UpdateToBestBlock", "gets", "the", "best", "block", "via", "RPC", "and", "updates", "the", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L182-L189
train
decred/dcrdata
rpcutils/blockgate.go
UpdateToNextBlock
func (g *BlockGate) UpdateToNextBlock() (*dcrutil.Block, error) { g.mtx.Lock() height := g.height + 1 g.mtx.Unlock() return g.UpdateToBlock(height) }
go
func (g *BlockGate) UpdateToNextBlock() (*dcrutil.Block, error) { g.mtx.Lock() height := g.height + 1 g.mtx.Unlock() return g.UpdateToBlock(height) }
[ "func", "(", "g", "*", "BlockGate", ")", "UpdateToNextBlock", "(", ")", "(", "*", "dcrutil", ".", "Block", ",", "error", ")", "{", "g", ".", "mtx", ".", "Lock", "(", ")", "\n", "height", ":=", "g", ".", "height", "+", "1", "\n", "g", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "g", ".", "UpdateToBlock", "(", "height", ")", "\n", "}" ]
// UpdateToNextBlock gets the next block following the best in cache via RPC and // updates the cache.
[ "UpdateToNextBlock", "gets", "the", "next", "block", "following", "the", "best", "in", "cache", "via", "RPC", "and", "updates", "the", "cache", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L193-L198
train
decred/dcrdata
rpcutils/blockgate.go
UpdateToBlock
func (g *BlockGate) UpdateToBlock(height int64) (*dcrutil.Block, error) { g.mtx.Lock() defer g.mtx.Unlock() return g.updateToBlock(height) }
go
func (g *BlockGate) UpdateToBlock(height int64) (*dcrutil.Block, error) { g.mtx.Lock() defer g.mtx.Unlock() return g.updateToBlock(height) }
[ "func", "(", "g", "*", "BlockGate", ")", "UpdateToBlock", "(", "height", "int64", ")", "(", "*", "dcrutil", ".", "Block", ",", "error", ")", "{", "g", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "g", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "g", ".", "updateToBlock", "(", "height", ")", "\n", "}" ]
// UpdateToBlock gets the block at the specified height on the main chain from // dcrd, stores it in cache, and signals any waiters. This is the thread-safe // version of updateToBlock.
[ "UpdateToBlock", "gets", "the", "block", "at", "the", "specified", "height", "on", "the", "main", "chain", "from", "dcrd", "stores", "it", "in", "cache", "and", "signals", "any", "waiters", ".", "This", "is", "the", "thread", "-", "safe", "version", "of", "updateToBlock", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L203-L207
train
decred/dcrdata
rpcutils/blockgate.go
updateToBlock
func (g *BlockGate) updateToBlock(height int64) (*dcrutil.Block, error) { block, hash, err := GetBlock(height, g.client) if err != nil { return nil, fmt.Errorf("GetBlock (%d) failed: %v", height, err) } if block.Height() != height { return nil, fmt.Errorf("GetBlock (%d) returned block at height %d", height, block.Height()) } if !hash.IsEqual(block.Hash()) { return nil, fmt.Errorf("GetBlock (%s) returned block with hash %s", hash.String(), block.Hash().String()) } g.height = height g.hashAtHeight[height] = *hash g.blockWithHash[*hash] = block // Push the new block onto the expiration queue, and remove any old ones if // above capacity. g.rotateIn(height, *hash) // Launch goroutines to signal to height and hash waiters. g.signalHeight(height, *hash) g.signalHash(*hash, height) return block, nil }
go
func (g *BlockGate) updateToBlock(height int64) (*dcrutil.Block, error) { block, hash, err := GetBlock(height, g.client) if err != nil { return nil, fmt.Errorf("GetBlock (%d) failed: %v", height, err) } if block.Height() != height { return nil, fmt.Errorf("GetBlock (%d) returned block at height %d", height, block.Height()) } if !hash.IsEqual(block.Hash()) { return nil, fmt.Errorf("GetBlock (%s) returned block with hash %s", hash.String(), block.Hash().String()) } g.height = height g.hashAtHeight[height] = *hash g.blockWithHash[*hash] = block // Push the new block onto the expiration queue, and remove any old ones if // above capacity. g.rotateIn(height, *hash) // Launch goroutines to signal to height and hash waiters. g.signalHeight(height, *hash) g.signalHash(*hash, height) return block, nil }
[ "func", "(", "g", "*", "BlockGate", ")", "updateToBlock", "(", "height", "int64", ")", "(", "*", "dcrutil", ".", "Block", ",", "error", ")", "{", "block", ",", "hash", ",", "err", ":=", "GetBlock", "(", "height", ",", "g", ".", "client", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "height", ",", "err", ")", "\n", "}", "\n\n", "if", "block", ".", "Height", "(", ")", "!=", "height", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "height", ",", "block", ".", "Height", "(", ")", ")", "\n", "}", "\n", "if", "!", "hash", ".", "IsEqual", "(", "block", ".", "Hash", "(", ")", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hash", ".", "String", "(", ")", ",", "block", ".", "Hash", "(", ")", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "g", ".", "height", "=", "height", "\n", "g", ".", "hashAtHeight", "[", "height", "]", "=", "*", "hash", "\n", "g", ".", "blockWithHash", "[", "*", "hash", "]", "=", "block", "\n\n", "// Push the new block onto the expiration queue, and remove any old ones if", "// above capacity.", "g", ".", "rotateIn", "(", "height", ",", "*", "hash", ")", "\n\n", "// Launch goroutines to signal to height and hash waiters.", "g", ".", "signalHeight", "(", "height", ",", "*", "hash", ")", "\n", "g", ".", "signalHash", "(", "*", "hash", ",", "height", ")", "\n\n", "return", "block", ",", "nil", "\n", "}" ]
// updateToBlock gets the block at the specified height on the main chain from // dcrd. It is not thread-safe. It wrapped by UpdateToBlock for thread-safety, // and used directly by WaitForHeight which locks the BlockGate.
[ "updateToBlock", "gets", "the", "block", "at", "the", "specified", "height", "on", "the", "main", "chain", "from", "dcrd", ".", "It", "is", "not", "thread", "-", "safe", ".", "It", "wrapped", "by", "UpdateToBlock", "for", "thread", "-", "safety", "and", "used", "directly", "by", "WaitForHeight", "which", "locks", "the", "BlockGate", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L212-L240
train
decred/dcrdata
rpcutils/blockgate.go
WaitForHeight
func (g *BlockGate) WaitForHeight(height int64) chan chainhash.Hash { g.mtx.Lock() defer g.mtx.Unlock() if height < 0 { return nil } waitChan := make(chan chainhash.Hash, 1) // Queue for future send. g.heightWaiters[height] = append(g.heightWaiters[height], waitChan) // If the block is already cached, send now. if hash, ok := g.hashAtHeight[height]; ok { g.signalHeight(height, hash) } else if height <= g.fetchToHeight { if _, err := g.updateToBlock(height); err != nil { fmt.Printf("Failed to updateToBlock: %v", err) return nil } } else if height < g.height { fmt.Printf("WARNING: WaitForHeight(%d), but the best block is at %d. "+ "You may wait forever for this block.", height, g.height) } return waitChan }
go
func (g *BlockGate) WaitForHeight(height int64) chan chainhash.Hash { g.mtx.Lock() defer g.mtx.Unlock() if height < 0 { return nil } waitChan := make(chan chainhash.Hash, 1) // Queue for future send. g.heightWaiters[height] = append(g.heightWaiters[height], waitChan) // If the block is already cached, send now. if hash, ok := g.hashAtHeight[height]; ok { g.signalHeight(height, hash) } else if height <= g.fetchToHeight { if _, err := g.updateToBlock(height); err != nil { fmt.Printf("Failed to updateToBlock: %v", err) return nil } } else if height < g.height { fmt.Printf("WARNING: WaitForHeight(%d), but the best block is at %d. "+ "You may wait forever for this block.", height, g.height) } return waitChan }
[ "func", "(", "g", "*", "BlockGate", ")", "WaitForHeight", "(", "height", "int64", ")", "chan", "chainhash", ".", "Hash", "{", "g", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "g", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "if", "height", "<", "0", "{", "return", "nil", "\n", "}", "\n\n", "waitChan", ":=", "make", "(", "chan", "chainhash", ".", "Hash", ",", "1", ")", "\n", "// Queue for future send.", "g", ".", "heightWaiters", "[", "height", "]", "=", "append", "(", "g", ".", "heightWaiters", "[", "height", "]", ",", "waitChan", ")", "\n\n", "// If the block is already cached, send now.", "if", "hash", ",", "ok", ":=", "g", ".", "hashAtHeight", "[", "height", "]", ";", "ok", "{", "g", ".", "signalHeight", "(", "height", ",", "hash", ")", "\n", "}", "else", "if", "height", "<=", "g", ".", "fetchToHeight", "{", "if", "_", ",", "err", ":=", "g", ".", "updateToBlock", "(", "height", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "else", "if", "height", "<", "g", ".", "height", "{", "fmt", ".", "Printf", "(", "\"", "\"", "+", "\"", "\"", ",", "height", ",", "g", ".", "height", ")", "\n", "}", "\n\n", "return", "waitChan", "\n", "}" ]
// WaitForHeight provides a notification channel for signaling to the caller // when the block at the specified height is available.
[ "WaitForHeight", "provides", "a", "notification", "channel", "for", "signaling", "to", "the", "caller", "when", "the", "block", "at", "the", "specified", "height", "is", "available", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L324-L351
train
decred/dcrdata
rpcutils/blockgate.go
WaitForHash
func (g *BlockGate) WaitForHash(hash chainhash.Hash) chan int64 { g.mtx.Lock() defer g.mtx.Unlock() waitChan := make(chan int64, 1) // Queue for future send. g.hashWaiters[hash] = append(g.hashWaiters[hash], waitChan) // If the block is already cached, send now. if block, ok := g.blockWithHash[hash]; ok { g.signalHash(hash, block.Height()) } return waitChan }
go
func (g *BlockGate) WaitForHash(hash chainhash.Hash) chan int64 { g.mtx.Lock() defer g.mtx.Unlock() waitChan := make(chan int64, 1) // Queue for future send. g.hashWaiters[hash] = append(g.hashWaiters[hash], waitChan) // If the block is already cached, send now. if block, ok := g.blockWithHash[hash]; ok { g.signalHash(hash, block.Height()) } return waitChan }
[ "func", "(", "g", "*", "BlockGate", ")", "WaitForHash", "(", "hash", "chainhash", ".", "Hash", ")", "chan", "int64", "{", "g", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "g", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "waitChan", ":=", "make", "(", "chan", "int64", ",", "1", ")", "\n\n", "// Queue for future send.", "g", ".", "hashWaiters", "[", "hash", "]", "=", "append", "(", "g", ".", "hashWaiters", "[", "hash", "]", ",", "waitChan", ")", "\n\n", "// If the block is already cached, send now.", "if", "block", ",", "ok", ":=", "g", ".", "blockWithHash", "[", "hash", "]", ";", "ok", "{", "g", ".", "signalHash", "(", "hash", ",", "block", ".", "Height", "(", ")", ")", "\n", "}", "\n\n", "return", "waitChan", "\n", "}" ]
// WaitForHash provides a notification channel for signaling to the caller // when the block with the specified hash is available.
[ "WaitForHash", "provides", "a", "notification", "channel", "for", "signaling", "to", "the", "caller", "when", "the", "block", "with", "the", "specified", "hash", "is", "available", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L355-L370
train
decred/dcrdata
rpcutils/blockgate.go
GetChainWork
func (g *BlockGate) GetChainWork(hash *chainhash.Hash) (string, error) { return GetChainWork(g.client, hash) }
go
func (g *BlockGate) GetChainWork(hash *chainhash.Hash) (string, error) { return GetChainWork(g.client, hash) }
[ "func", "(", "g", "*", "BlockGate", ")", "GetChainWork", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "string", ",", "error", ")", "{", "return", "GetChainWork", "(", "g", ".", "client", ",", "hash", ")", "\n", "}" ]
// GetChainWork fetches the dcrjson.BlockHeaderVerbose and returns only the // ChainWork attribute as a string.
[ "GetChainWork", "fetches", "the", "dcrjson", ".", "BlockHeaderVerbose", "and", "returns", "only", "the", "ChainWork", "attribute", "as", "a", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/blockgate.go#L374-L376
train
decred/dcrdata
stakedb/ticketpool.go
Infof
func (l *badgerLogger) Infof(format string, v ...interface{}) { l.logf(logLevelInfo, format, v...) }
go
func (l *badgerLogger) Infof(format string, v ...interface{}) { l.logf(logLevelInfo, format, v...) }
[ "func", "(", "l", "*", "badgerLogger", ")", "Infof", "(", "format", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "l", ".", "logf", "(", "logLevelInfo", ",", "format", ",", "v", "...", ")", "\n", "}" ]
// Infof filters messages through logf with logLevelInfo before sending the // message to the slog.Logger.
[ "Infof", "filters", "messages", "through", "logf", "with", "logLevelInfo", "before", "sending", "the", "message", "to", "the", "slog", ".", "Logger", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L118-L120
train
decred/dcrdata
stakedb/ticketpool.go
Warningf
func (l *badgerLogger) Warningf(format string, v ...interface{}) { l.logf(logLevelWarn, format, v...) }
go
func (l *badgerLogger) Warningf(format string, v ...interface{}) { l.logf(logLevelWarn, format, v...) }
[ "func", "(", "l", "*", "badgerLogger", ")", "Warningf", "(", "format", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "l", ".", "logf", "(", "logLevelWarn", ",", "format", ",", "v", "...", ")", "\n", "}" ]
// Warningf filters messages through logf with logLevelWarn before sending the // message to the slog.Logger.
[ "Warningf", "filters", "messages", "through", "logf", "with", "logLevelWarn", "before", "sending", "the", "message", "to", "the", "slog", ".", "Logger", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L124-L126
train
decred/dcrdata
stakedb/ticketpool.go
Errorf
func (l *badgerLogger) Errorf(format string, v ...interface{}) { l.logf(logLevelError, format, v...) }
go
func (l *badgerLogger) Errorf(format string, v ...interface{}) { l.logf(logLevelError, format, v...) }
[ "func", "(", "l", "*", "badgerLogger", ")", "Errorf", "(", "format", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "l", ".", "logf", "(", "logLevelError", ",", "format", ",", "v", "...", ")", "\n", "}" ]
// Errorf filters messages through logf with logLevelError before sending the // message to the slog.Logger.
[ "Errorf", "filters", "messages", "through", "logf", "with", "logLevelError", "before", "sending", "the", "message", "to", "the", "slog", ".", "Logger", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L130-L132
train
decred/dcrdata
stakedb/ticketpool.go
NewTicketPool
func NewTicketPool(dataDir, dbSubDir string) (tp *TicketPool, err error) { // Open ticket pool diffs database badgerDbPath := filepath.Join(dataDir, dbSubDir) opts := badger.DefaultOptions opts.Dir = badgerDbPath opts.ValueDir = badgerDbPath opts.Logger = &badgerLogger{log} db, err := badger.Open(opts) if err == badger.ErrTruncateNeeded { log.Warnf("NewTicketPool badger db: %v", err) // Try again with value log truncation enabled. opts.Truncate = true log.Warnf("Attempting to reopening ticket pool db with the Truncate option set...") db, err = badger.Open(opts) } if err != nil { return nil, fmt.Errorf("failed badger.Open: %v", err) } defer func() { if r := recover(); r != nil { db.Close() panic(r) } if err != nil { db.Close() } }() // Attempt garbage collection of badger value log. If greater than // rewriteThreshold of the space was discarded, rewrite the entire value // log. However, there should be few discards as chain reorgs that cause // data to be deleted are a small percentage of the ticket pool data. rewriteThreshold := 0.5 err = db.RunValueLogGC(rewriteThreshold) if err != nil { if err != badger.ErrNoRewrite { return nil, fmt.Errorf("failed badger.RunValueLogGC: %v", err) } log.Debugf("badger value log not rewritten (OK).") } // Attempt migration from storm to badger if badger was empty TableInfo := db.Tables() oldDBPath := filepath.Join(dataDir, DefaultTicketPoolDbName) if len(TableInfo) == 0 { migrated, err := MigrateFromStorm(oldDBPath, db) if err != nil { return nil, fmt.Errorf("migration from storm failed: %v", err) } if migrated { log.Info("Successfully migrated ticket pool db from storm to badger DB.") } } if _, err = os.Stat(oldDBPath); err == nil { log.Infof("You may delete the old ticket pool DB file (%s).", oldDBPath) } // Load all diffs log.Infof("Loading all ticket pool diffs...") poolDiffs, err := LoadAllPoolDiffs(db) if err != nil { return nil, fmt.Errorf("failed LoadAllPoolDiffs: %v", err) } log.Infof("Successfully loaded %d ticket pool diffs", len(poolDiffs)) // Construct TicketPool with loaded diffs and diff DB return &TicketPool{ pool: make(map[chainhash.Hash]struct{}), diffs: poolDiffs, tip: int64(len(poolDiffs)), // number of blocks connected over genesis diffDB: db, }, nil }
go
func NewTicketPool(dataDir, dbSubDir string) (tp *TicketPool, err error) { // Open ticket pool diffs database badgerDbPath := filepath.Join(dataDir, dbSubDir) opts := badger.DefaultOptions opts.Dir = badgerDbPath opts.ValueDir = badgerDbPath opts.Logger = &badgerLogger{log} db, err := badger.Open(opts) if err == badger.ErrTruncateNeeded { log.Warnf("NewTicketPool badger db: %v", err) // Try again with value log truncation enabled. opts.Truncate = true log.Warnf("Attempting to reopening ticket pool db with the Truncate option set...") db, err = badger.Open(opts) } if err != nil { return nil, fmt.Errorf("failed badger.Open: %v", err) } defer func() { if r := recover(); r != nil { db.Close() panic(r) } if err != nil { db.Close() } }() // Attempt garbage collection of badger value log. If greater than // rewriteThreshold of the space was discarded, rewrite the entire value // log. However, there should be few discards as chain reorgs that cause // data to be deleted are a small percentage of the ticket pool data. rewriteThreshold := 0.5 err = db.RunValueLogGC(rewriteThreshold) if err != nil { if err != badger.ErrNoRewrite { return nil, fmt.Errorf("failed badger.RunValueLogGC: %v", err) } log.Debugf("badger value log not rewritten (OK).") } // Attempt migration from storm to badger if badger was empty TableInfo := db.Tables() oldDBPath := filepath.Join(dataDir, DefaultTicketPoolDbName) if len(TableInfo) == 0 { migrated, err := MigrateFromStorm(oldDBPath, db) if err != nil { return nil, fmt.Errorf("migration from storm failed: %v", err) } if migrated { log.Info("Successfully migrated ticket pool db from storm to badger DB.") } } if _, err = os.Stat(oldDBPath); err == nil { log.Infof("You may delete the old ticket pool DB file (%s).", oldDBPath) } // Load all diffs log.Infof("Loading all ticket pool diffs...") poolDiffs, err := LoadAllPoolDiffs(db) if err != nil { return nil, fmt.Errorf("failed LoadAllPoolDiffs: %v", err) } log.Infof("Successfully loaded %d ticket pool diffs", len(poolDiffs)) // Construct TicketPool with loaded diffs and diff DB return &TicketPool{ pool: make(map[chainhash.Hash]struct{}), diffs: poolDiffs, tip: int64(len(poolDiffs)), // number of blocks connected over genesis diffDB: db, }, nil }
[ "func", "NewTicketPool", "(", "dataDir", ",", "dbSubDir", "string", ")", "(", "tp", "*", "TicketPool", ",", "err", "error", ")", "{", "// Open ticket pool diffs database", "badgerDbPath", ":=", "filepath", ".", "Join", "(", "dataDir", ",", "dbSubDir", ")", "\n", "opts", ":=", "badger", ".", "DefaultOptions", "\n", "opts", ".", "Dir", "=", "badgerDbPath", "\n", "opts", ".", "ValueDir", "=", "badgerDbPath", "\n", "opts", ".", "Logger", "=", "&", "badgerLogger", "{", "log", "}", "\n", "db", ",", "err", ":=", "badger", ".", "Open", "(", "opts", ")", "\n", "if", "err", "==", "badger", ".", "ErrTruncateNeeded", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "// Try again with value log truncation enabled.", "opts", ".", "Truncate", "=", "true", "\n", "log", ".", "Warnf", "(", "\"", "\"", ")", "\n", "db", ",", "err", "=", "badger", ".", "Open", "(", "opts", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "db", ".", "Close", "(", ")", "\n", "panic", "(", "r", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "db", ".", "Close", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// Attempt garbage collection of badger value log. If greater than", "// rewriteThreshold of the space was discarded, rewrite the entire value", "// log. However, there should be few discards as chain reorgs that cause", "// data to be deleted are a small percentage of the ticket pool data.", "rewriteThreshold", ":=", "0.5", "\n", "err", "=", "db", ".", "RunValueLogGC", "(", "rewriteThreshold", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "badger", ".", "ErrNoRewrite", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Attempt migration from storm to badger if badger was empty", "TableInfo", ":=", "db", ".", "Tables", "(", ")", "\n", "oldDBPath", ":=", "filepath", ".", "Join", "(", "dataDir", ",", "DefaultTicketPoolDbName", ")", "\n", "if", "len", "(", "TableInfo", ")", "==", "0", "{", "migrated", ",", "err", ":=", "MigrateFromStorm", "(", "oldDBPath", ",", "db", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "migrated", "{", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "if", "_", ",", "err", "=", "os", ".", "Stat", "(", "oldDBPath", ")", ";", "err", "==", "nil", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "oldDBPath", ")", "\n", "}", "\n\n", "// Load all diffs", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "poolDiffs", ",", "err", ":=", "LoadAllPoolDiffs", "(", "db", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "len", "(", "poolDiffs", ")", ")", "\n\n", "// Construct TicketPool with loaded diffs and diff DB", "return", "&", "TicketPool", "{", "pool", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "struct", "{", "}", ")", ",", "diffs", ":", "poolDiffs", ",", "tip", ":", "int64", "(", "len", "(", "poolDiffs", ")", ")", ",", "// number of blocks connected over genesis", "diffDB", ":", "db", ",", "}", ",", "nil", "\n", "}" ]
// NewTicketPool constructs a TicketPool by opening the persistent diff db, // loading all known diffs, initializing the TicketPool values.
[ "NewTicketPool", "constructs", "a", "TicketPool", "by", "opening", "the", "persistent", "diff", "db", "loading", "all", "known", "diffs", "initializing", "the", "TicketPool", "values", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L136-L209
train
decred/dcrdata
stakedb/ticketpool.go
MigrateFromStorm
func MigrateFromStorm(stormDBFile string, db *badger.DB) (bool, error) { // Check for the storm DB file finfo, err := os.Stat(stormDBFile) if os.IsNotExist(err) { return false, nil } if err != nil { return false, err } if finfo.Size() == 0 { return false, nil } // Open the storm DB file dbOld, err := storm.Open(stormDBFile) if err != nil { return false, fmt.Errorf("failed storm.Open: %v", err) } defer dbOld.Close() // Attempt to load the pool diffs for block 1 var blockOneDiffs PoolDiffDBItem err = dbOld.One("Height", 1, &blockOneDiffs) // If bucket or element with id 1 does not exist, not an error if err == storm.ErrNotFound { return false, nil } if err != nil { return false, fmt.Errorf("failed to retrieve block one pool diff "+ "(delete storm db file and try again): %v", err) } log.Info("Found storm ticket pool DB. Attempting migration to badger.") // Load all diffs from storm log.Info("Loading all items from storm db...") var poolDiffsItems []PoolDiffDBItem err = dbOld.AllByIndex("Height", &poolDiffsItems) if err != nil { return false, fmt.Errorf("failed (*storm.DB).AllByIndex: %v", err) } poolDiffs := make([]*PoolDiff, 0, len(poolDiffsItems)) poolHeights := make([]int64, len(poolDiffsItems)) for i := range poolDiffsItems { poolHeights[i] = poolDiffsItems[i].Height poolDiffs = append(poolDiffs, &poolDiffsItems[i].PoolDiff) } // Store all diffs in badger log.Info("Storing all items in badger db...") err = storeDiffs(db, poolDiffs, poolHeights) if err != nil { return false, fmt.Errorf("failed to store diff in badger: %v", err) } return true, nil }
go
func MigrateFromStorm(stormDBFile string, db *badger.DB) (bool, error) { // Check for the storm DB file finfo, err := os.Stat(stormDBFile) if os.IsNotExist(err) { return false, nil } if err != nil { return false, err } if finfo.Size() == 0 { return false, nil } // Open the storm DB file dbOld, err := storm.Open(stormDBFile) if err != nil { return false, fmt.Errorf("failed storm.Open: %v", err) } defer dbOld.Close() // Attempt to load the pool diffs for block 1 var blockOneDiffs PoolDiffDBItem err = dbOld.One("Height", 1, &blockOneDiffs) // If bucket or element with id 1 does not exist, not an error if err == storm.ErrNotFound { return false, nil } if err != nil { return false, fmt.Errorf("failed to retrieve block one pool diff "+ "(delete storm db file and try again): %v", err) } log.Info("Found storm ticket pool DB. Attempting migration to badger.") // Load all diffs from storm log.Info("Loading all items from storm db...") var poolDiffsItems []PoolDiffDBItem err = dbOld.AllByIndex("Height", &poolDiffsItems) if err != nil { return false, fmt.Errorf("failed (*storm.DB).AllByIndex: %v", err) } poolDiffs := make([]*PoolDiff, 0, len(poolDiffsItems)) poolHeights := make([]int64, len(poolDiffsItems)) for i := range poolDiffsItems { poolHeights[i] = poolDiffsItems[i].Height poolDiffs = append(poolDiffs, &poolDiffsItems[i].PoolDiff) } // Store all diffs in badger log.Info("Storing all items in badger db...") err = storeDiffs(db, poolDiffs, poolHeights) if err != nil { return false, fmt.Errorf("failed to store diff in badger: %v", err) } return true, nil }
[ "func", "MigrateFromStorm", "(", "stormDBFile", "string", ",", "db", "*", "badger", ".", "DB", ")", "(", "bool", ",", "error", ")", "{", "// Check for the storm DB file", "finfo", ",", "err", ":=", "os", ".", "Stat", "(", "stormDBFile", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "false", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "finfo", ".", "Size", "(", ")", "==", "0", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "// Open the storm DB file", "dbOld", ",", "err", ":=", "storm", ".", "Open", "(", "stormDBFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "dbOld", ".", "Close", "(", ")", "\n\n", "// Attempt to load the pool diffs for block 1", "var", "blockOneDiffs", "PoolDiffDBItem", "\n", "err", "=", "dbOld", ".", "One", "(", "\"", "\"", ",", "1", ",", "&", "blockOneDiffs", ")", "\n", "// If bucket or element with id 1 does not exist, not an error", "if", "err", "==", "storm", ".", "ErrNotFound", "{", "return", "false", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n\n", "// Load all diffs from storm", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "var", "poolDiffsItems", "[", "]", "PoolDiffDBItem", "\n", "err", "=", "dbOld", ".", "AllByIndex", "(", "\"", "\"", ",", "&", "poolDiffsItems", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "poolDiffs", ":=", "make", "(", "[", "]", "*", "PoolDiff", ",", "0", ",", "len", "(", "poolDiffsItems", ")", ")", "\n", "poolHeights", ":=", "make", "(", "[", "]", "int64", ",", "len", "(", "poolDiffsItems", ")", ")", "\n", "for", "i", ":=", "range", "poolDiffsItems", "{", "poolHeights", "[", "i", "]", "=", "poolDiffsItems", "[", "i", "]", ".", "Height", "\n", "poolDiffs", "=", "append", "(", "poolDiffs", ",", "&", "poolDiffsItems", "[", "i", "]", ".", "PoolDiff", ")", "\n", "}", "\n\n", "// Store all diffs in badger", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "err", "=", "storeDiffs", "(", "db", ",", "poolDiffs", ",", "poolHeights", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "true", ",", "nil", "\n", "}" ]
// MigrateFromStorm attempts to load the storm DB specified by the given file // name, and migrate all ticket pool diffs to the badger db.
[ "MigrateFromStorm", "attempts", "to", "load", "the", "storm", "DB", "specified", "by", "the", "given", "file", "name", "and", "migrate", "all", "ticket", "pool", "diffs", "to", "the", "badger", "db", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L213-L270
train
decred/dcrdata
stakedb/ticketpool.go
LoadAllPoolDiffs
func LoadAllPoolDiffs(db *badger.DB) ([]PoolDiff, error) { var poolDiffs []PoolDiff err := db.View(func(txn *badger.Txn) error { // Create the badger iterator opts := badger.IteratorOptions{ PrefetchValues: true, PrefetchSize: 1000, Reverse: false, AllVersions: false, } it := txn.NewIterator(opts) defer it.Close() var lastheight uint64 for it.Rewind(); it.Valid(); it.Next() { item := it.Item() height := binary.BigEndian.Uint64(item.Key()) // Don't waste time with a copy since we are going to read the data in // this transaction. var hashReader bytes.Reader //nolint:unparam errTx := item.Value(func(v []byte) error { hashReader.Reset(v) return nil }) if errTx != nil { return fmt.Errorf("key [%x]. Error while fetching value [%v]", item.Key(), errTx) } var poolDiff PoolDiff if errTx = gob.NewDecoder(&hashReader).Decode(&poolDiff); errTx != nil { log.Errorf("failed to decode PoolDiff[%d]: %v", height, errTx) return errTx } poolDiffs = append(poolDiffs, poolDiff) if lastheight+1 != height { panic(fmt.Sprintf("height: %d, lastheight: %d", height, lastheight)) } lastheight = height } // extra sanity check poolDiffLen := uint64(len(poolDiffs)) if poolDiffLen > 0 { if poolDiffLen != lastheight { panic(fmt.Sprintf("last poolDiff Height (%d) != %d", lastheight, poolDiffLen)) } } return nil }) return poolDiffs, err }
go
func LoadAllPoolDiffs(db *badger.DB) ([]PoolDiff, error) { var poolDiffs []PoolDiff err := db.View(func(txn *badger.Txn) error { // Create the badger iterator opts := badger.IteratorOptions{ PrefetchValues: true, PrefetchSize: 1000, Reverse: false, AllVersions: false, } it := txn.NewIterator(opts) defer it.Close() var lastheight uint64 for it.Rewind(); it.Valid(); it.Next() { item := it.Item() height := binary.BigEndian.Uint64(item.Key()) // Don't waste time with a copy since we are going to read the data in // this transaction. var hashReader bytes.Reader //nolint:unparam errTx := item.Value(func(v []byte) error { hashReader.Reset(v) return nil }) if errTx != nil { return fmt.Errorf("key [%x]. Error while fetching value [%v]", item.Key(), errTx) } var poolDiff PoolDiff if errTx = gob.NewDecoder(&hashReader).Decode(&poolDiff); errTx != nil { log.Errorf("failed to decode PoolDiff[%d]: %v", height, errTx) return errTx } poolDiffs = append(poolDiffs, poolDiff) if lastheight+1 != height { panic(fmt.Sprintf("height: %d, lastheight: %d", height, lastheight)) } lastheight = height } // extra sanity check poolDiffLen := uint64(len(poolDiffs)) if poolDiffLen > 0 { if poolDiffLen != lastheight { panic(fmt.Sprintf("last poolDiff Height (%d) != %d", lastheight, poolDiffLen)) } } return nil }) return poolDiffs, err }
[ "func", "LoadAllPoolDiffs", "(", "db", "*", "badger", ".", "DB", ")", "(", "[", "]", "PoolDiff", ",", "error", ")", "{", "var", "poolDiffs", "[", "]", "PoolDiff", "\n", "err", ":=", "db", ".", "View", "(", "func", "(", "txn", "*", "badger", ".", "Txn", ")", "error", "{", "// Create the badger iterator", "opts", ":=", "badger", ".", "IteratorOptions", "{", "PrefetchValues", ":", "true", ",", "PrefetchSize", ":", "1000", ",", "Reverse", ":", "false", ",", "AllVersions", ":", "false", ",", "}", "\n", "it", ":=", "txn", ".", "NewIterator", "(", "opts", ")", "\n", "defer", "it", ".", "Close", "(", ")", "\n\n", "var", "lastheight", "uint64", "\n", "for", "it", ".", "Rewind", "(", ")", ";", "it", ".", "Valid", "(", ")", ";", "it", ".", "Next", "(", ")", "{", "item", ":=", "it", ".", "Item", "(", ")", "\n", "height", ":=", "binary", ".", "BigEndian", ".", "Uint64", "(", "item", ".", "Key", "(", ")", ")", "\n\n", "// Don't waste time with a copy since we are going to read the data in", "// this transaction.", "var", "hashReader", "bytes", ".", "Reader", "\n", "//nolint:unparam", "errTx", ":=", "item", ".", "Value", "(", "func", "(", "v", "[", "]", "byte", ")", "error", "{", "hashReader", ".", "Reset", "(", "v", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "errTx", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "item", ".", "Key", "(", ")", ",", "errTx", ")", "\n", "}", "\n\n", "var", "poolDiff", "PoolDiff", "\n", "if", "errTx", "=", "gob", ".", "NewDecoder", "(", "&", "hashReader", ")", ".", "Decode", "(", "&", "poolDiff", ")", ";", "errTx", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "height", ",", "errTx", ")", "\n", "return", "errTx", "\n", "}", "\n\n", "poolDiffs", "=", "append", "(", "poolDiffs", ",", "poolDiff", ")", "\n", "if", "lastheight", "+", "1", "!=", "height", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "height", ",", "lastheight", ")", ")", "\n", "}", "\n", "lastheight", "=", "height", "\n", "}", "\n", "// extra sanity check", "poolDiffLen", ":=", "uint64", "(", "len", "(", "poolDiffs", ")", ")", "\n", "if", "poolDiffLen", ">", "0", "{", "if", "poolDiffLen", "!=", "lastheight", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "lastheight", ",", "poolDiffLen", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n", "return", "poolDiffs", ",", "err", "\n", "}" ]
// LoadAllPoolDiffs loads all found ticket pool diffs from badger DB.
[ "LoadAllPoolDiffs", "loads", "all", "found", "ticket", "pool", "diffs", "from", "badger", "DB", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L273-L327
train
decred/dcrdata
stakedb/ticketpool.go
Tip
func (tp *TicketPool) Tip() int64 { tp.mtx.RLock() defer tp.mtx.RUnlock() return tp.tip }
go
func (tp *TicketPool) Tip() int64 { tp.mtx.RLock() defer tp.mtx.RUnlock() return tp.tip }
[ "func", "(", "tp", "*", "TicketPool", ")", "Tip", "(", ")", "int64", "{", "tp", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "tp", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "tp", ".", "tip", "\n", "}" ]
// Tip returns the current length of the diffs slice.
[ "Tip", "returns", "the", "current", "length", "of", "the", "diffs", "slice", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L335-L339
train
decred/dcrdata
stakedb/ticketpool.go
Cursor
func (tp *TicketPool) Cursor() int64 { tp.mtx.RLock() defer tp.mtx.RUnlock() return tp.cursor }
go
func (tp *TicketPool) Cursor() int64 { tp.mtx.RLock() defer tp.mtx.RUnlock() return tp.cursor }
[ "func", "(", "tp", "*", "TicketPool", ")", "Cursor", "(", ")", "int64", "{", "tp", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "tp", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "tp", ".", "cursor", "\n", "}" ]
// Cursor returns the current cursor, the location of the next unapplied diff.
[ "Cursor", "returns", "the", "current", "cursor", "the", "location", "of", "the", "next", "unapplied", "diff", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L342-L346
train
decred/dcrdata
stakedb/ticketpool.go
append
func (tp *TicketPool) append(diff *PoolDiff) { tp.tip++ tp.diffs = append(tp.diffs, *diff) }
go
func (tp *TicketPool) append(diff *PoolDiff) { tp.tip++ tp.diffs = append(tp.diffs, *diff) }
[ "func", "(", "tp", "*", "TicketPool", ")", "append", "(", "diff", "*", "PoolDiff", ")", "{", "tp", ".", "tip", "++", "\n", "tp", ".", "diffs", "=", "append", "(", "tp", ".", "diffs", ",", "*", "diff", ")", "\n", "}" ]
// append grows the diffs slice and advances the tip height.
[ "append", "grows", "the", "diffs", "slice", "and", "advances", "the", "tip", "height", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L349-L352
train
decred/dcrdata
stakedb/ticketpool.go
trim
func (tp *TicketPool) trim() (int64, PoolDiff) { if tp.tip == 0 || len(tp.diffs) == 0 { return tp.tip, PoolDiff{} } tp.tip-- newMaxCursor := tp.maxCursor() if tp.cursor > newMaxCursor { if err := tp.retreatTo(newMaxCursor); err != nil { log.Errorf("retreatTo failed: %v", err) } } // Trim AFTER retreating undo := tp.diffs[len(tp.diffs)-1] tp.diffs = tp.diffs[:len(tp.diffs)-1] return tp.tip, undo }
go
func (tp *TicketPool) trim() (int64, PoolDiff) { if tp.tip == 0 || len(tp.diffs) == 0 { return tp.tip, PoolDiff{} } tp.tip-- newMaxCursor := tp.maxCursor() if tp.cursor > newMaxCursor { if err := tp.retreatTo(newMaxCursor); err != nil { log.Errorf("retreatTo failed: %v", err) } } // Trim AFTER retreating undo := tp.diffs[len(tp.diffs)-1] tp.diffs = tp.diffs[:len(tp.diffs)-1] return tp.tip, undo }
[ "func", "(", "tp", "*", "TicketPool", ")", "trim", "(", ")", "(", "int64", ",", "PoolDiff", ")", "{", "if", "tp", ".", "tip", "==", "0", "||", "len", "(", "tp", ".", "diffs", ")", "==", "0", "{", "return", "tp", ".", "tip", ",", "PoolDiff", "{", "}", "\n", "}", "\n", "tp", ".", "tip", "--", "\n", "newMaxCursor", ":=", "tp", ".", "maxCursor", "(", ")", "\n", "if", "tp", ".", "cursor", ">", "newMaxCursor", "{", "if", "err", ":=", "tp", ".", "retreatTo", "(", "newMaxCursor", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "// Trim AFTER retreating", "undo", ":=", "tp", ".", "diffs", "[", "len", "(", "tp", ".", "diffs", ")", "-", "1", "]", "\n", "tp", ".", "diffs", "=", "tp", ".", "diffs", "[", ":", "len", "(", "tp", ".", "diffs", ")", "-", "1", "]", "\n", "return", "tp", ".", "tip", ",", "undo", "\n", "}" ]
// trim is the non-thread-safe version of Trim.
[ "trim", "is", "the", "non", "-", "thread", "-", "safe", "version", "of", "Trim", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L355-L370
train
decred/dcrdata
stakedb/ticketpool.go
Trim
func (tp *TicketPool) Trim() (int64, PoolDiff) { tp.mtx.Lock() defer tp.mtx.Unlock() return tp.trim() }
go
func (tp *TicketPool) Trim() (int64, PoolDiff) { tp.mtx.Lock() defer tp.mtx.Unlock() return tp.trim() }
[ "func", "(", "tp", "*", "TicketPool", ")", "Trim", "(", ")", "(", "int64", ",", "PoolDiff", ")", "{", "tp", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "tp", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "tp", ".", "trim", "(", ")", "\n", "}" ]
// Trim removes the end diff and decrements the tip height. If the cursor would // fall beyond the end of the diffs, the removed diffs are applied in reverse.
[ "Trim", "removes", "the", "end", "diff", "and", "decrements", "the", "tip", "height", ".", "If", "the", "cursor", "would", "fall", "beyond", "the", "end", "of", "the", "diffs", "the", "removed", "diffs", "are", "applied", "in", "reverse", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L374-L378
train
decred/dcrdata
stakedb/ticketpool.go
storeDiff
func storeDiff(db *badger.DB, diff *PoolDiff, height int64) error { var heightBytes [8]byte binary.BigEndian.PutUint64(heightBytes[:], uint64(height)) var poolDiffBuffer bytes.Buffer if err := gob.NewEncoder(&poolDiffBuffer).Encode(diff); err != nil { return err } return db.Update(func(txn *badger.Txn) error { return txn.Set(heightBytes[:], poolDiffBuffer.Bytes()) }) }
go
func storeDiff(db *badger.DB, diff *PoolDiff, height int64) error { var heightBytes [8]byte binary.BigEndian.PutUint64(heightBytes[:], uint64(height)) var poolDiffBuffer bytes.Buffer if err := gob.NewEncoder(&poolDiffBuffer).Encode(diff); err != nil { return err } return db.Update(func(txn *badger.Txn) error { return txn.Set(heightBytes[:], poolDiffBuffer.Bytes()) }) }
[ "func", "storeDiff", "(", "db", "*", "badger", ".", "DB", ",", "diff", "*", "PoolDiff", ",", "height", "int64", ")", "error", "{", "var", "heightBytes", "[", "8", "]", "byte", "\n", "binary", ".", "BigEndian", ".", "PutUint64", "(", "heightBytes", "[", ":", "]", ",", "uint64", "(", "height", ")", ")", "\n\n", "var", "poolDiffBuffer", "bytes", ".", "Buffer", "\n", "if", "err", ":=", "gob", ".", "NewEncoder", "(", "&", "poolDiffBuffer", ")", ".", "Encode", "(", "diff", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "db", ".", "Update", "(", "func", "(", "txn", "*", "badger", ".", "Txn", ")", "error", "{", "return", "txn", ".", "Set", "(", "heightBytes", "[", ":", "]", ",", "poolDiffBuffer", ".", "Bytes", "(", ")", ")", "\n", "}", ")", "\n", "}" ]
// storeDiff stores the input diff for the specified height in the on-disk DB.
[ "storeDiff", "stores", "the", "input", "diff", "for", "the", "specified", "height", "in", "the", "on", "-", "disk", "DB", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L381-L393
train
decred/dcrdata
stakedb/ticketpool.go
storeDiffs
func storeDiffs(db *badger.DB, diffs []*PoolDiff, heights []int64) error { heightToBytes := func(height int64) (heightBytes [8]byte) { binary.BigEndian.PutUint64(heightBytes[:], uint64(height)) return } poolDiffBuffer := new(bytes.Buffer) txn := db.NewTransaction(true) for i, h := range heights { heightBytes := heightToBytes(h) poolDiffBuffer.Reset() gobEnc := gob.NewEncoder(poolDiffBuffer) err := gobEnc.Encode(diffs[i]) if err != nil { txn.Discard() return err } err = txn.Set(heightBytes[:], poolDiffBuffer.Bytes()) // If this transaction got too big, commit and make a new one if err == badger.ErrTxnTooBig { if err = txn.Commit(); err != nil { txn.Discard() return err } txn = db.NewTransaction(true) if err = txn.Set(heightBytes[:], poolDiffBuffer.Bytes()); err != nil { txn.Discard() return err } } if err != nil { txn.Discard() return err } } return txn.Commit() }
go
func storeDiffs(db *badger.DB, diffs []*PoolDiff, heights []int64) error { heightToBytes := func(height int64) (heightBytes [8]byte) { binary.BigEndian.PutUint64(heightBytes[:], uint64(height)) return } poolDiffBuffer := new(bytes.Buffer) txn := db.NewTransaction(true) for i, h := range heights { heightBytes := heightToBytes(h) poolDiffBuffer.Reset() gobEnc := gob.NewEncoder(poolDiffBuffer) err := gobEnc.Encode(diffs[i]) if err != nil { txn.Discard() return err } err = txn.Set(heightBytes[:], poolDiffBuffer.Bytes()) // If this transaction got too big, commit and make a new one if err == badger.ErrTxnTooBig { if err = txn.Commit(); err != nil { txn.Discard() return err } txn = db.NewTransaction(true) if err = txn.Set(heightBytes[:], poolDiffBuffer.Bytes()); err != nil { txn.Discard() return err } } if err != nil { txn.Discard() return err } } return txn.Commit() }
[ "func", "storeDiffs", "(", "db", "*", "badger", ".", "DB", ",", "diffs", "[", "]", "*", "PoolDiff", ",", "heights", "[", "]", "int64", ")", "error", "{", "heightToBytes", ":=", "func", "(", "height", "int64", ")", "(", "heightBytes", "[", "8", "]", "byte", ")", "{", "binary", ".", "BigEndian", ".", "PutUint64", "(", "heightBytes", "[", ":", "]", ",", "uint64", "(", "height", ")", ")", "\n", "return", "\n", "}", "\n\n", "poolDiffBuffer", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "txn", ":=", "db", ".", "NewTransaction", "(", "true", ")", "\n", "for", "i", ",", "h", ":=", "range", "heights", "{", "heightBytes", ":=", "heightToBytes", "(", "h", ")", "\n", "poolDiffBuffer", ".", "Reset", "(", ")", "\n", "gobEnc", ":=", "gob", ".", "NewEncoder", "(", "poolDiffBuffer", ")", "\n", "err", ":=", "gobEnc", ".", "Encode", "(", "diffs", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "txn", ".", "Discard", "(", ")", "\n", "return", "err", "\n", "}", "\n", "err", "=", "txn", ".", "Set", "(", "heightBytes", "[", ":", "]", ",", "poolDiffBuffer", ".", "Bytes", "(", ")", ")", "\n", "// If this transaction got too big, commit and make a new one", "if", "err", "==", "badger", ".", "ErrTxnTooBig", "{", "if", "err", "=", "txn", ".", "Commit", "(", ")", ";", "err", "!=", "nil", "{", "txn", ".", "Discard", "(", ")", "\n", "return", "err", "\n", "}", "\n", "txn", "=", "db", ".", "NewTransaction", "(", "true", ")", "\n", "if", "err", "=", "txn", ".", "Set", "(", "heightBytes", "[", ":", "]", ",", "poolDiffBuffer", ".", "Bytes", "(", ")", ")", ";", "err", "!=", "nil", "{", "txn", ".", "Discard", "(", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "txn", ".", "Discard", "(", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "return", "txn", ".", "Commit", "(", ")", "\n", "}" ]
// storeDiffs stores the input diffs for the specified heights in the on-disk DB.
[ "storeDiffs", "stores", "the", "input", "diffs", "for", "the", "specified", "heights", "in", "the", "on", "-", "disk", "DB", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L396-L432
train
decred/dcrdata
stakedb/ticketpool.go
fetchDiff
func (tp *TicketPool) fetchDiff(height int64) (*PoolDiffDBItem, error) { var heightBytes [8]byte binary.BigEndian.PutUint64(heightBytes[:], uint64(height)) var diff *PoolDiffDBItem err := tp.diffDB.View(func(txn *badger.Txn) error { item, errTx := txn.Get(heightBytes[:]) if errTx != nil { return fmt.Errorf("failed to find height %d in TicketPool: %v", height, errTx) } // Don't waste time with a copy since we are going to read the data in // this transaction. var hashReader bytes.Reader //nolint:unparam errTx = item.Value(func(v []byte) error { hashReader.Reset(v) return nil }) if errTx != nil { return fmt.Errorf("key [%x]. Error while fetching value [%v]", item.Key(), errTx) } var poolDiff PoolDiff if errTx = gob.NewDecoder(&hashReader).Decode(&poolDiff); errTx != nil { return fmt.Errorf("failed to decode PoolDiff: %v", errTx) } diff = &PoolDiffDBItem{ Height: height, PoolDiff: poolDiff, } return nil }) return diff, err }
go
func (tp *TicketPool) fetchDiff(height int64) (*PoolDiffDBItem, error) { var heightBytes [8]byte binary.BigEndian.PutUint64(heightBytes[:], uint64(height)) var diff *PoolDiffDBItem err := tp.diffDB.View(func(txn *badger.Txn) error { item, errTx := txn.Get(heightBytes[:]) if errTx != nil { return fmt.Errorf("failed to find height %d in TicketPool: %v", height, errTx) } // Don't waste time with a copy since we are going to read the data in // this transaction. var hashReader bytes.Reader //nolint:unparam errTx = item.Value(func(v []byte) error { hashReader.Reset(v) return nil }) if errTx != nil { return fmt.Errorf("key [%x]. Error while fetching value [%v]", item.Key(), errTx) } var poolDiff PoolDiff if errTx = gob.NewDecoder(&hashReader).Decode(&poolDiff); errTx != nil { return fmt.Errorf("failed to decode PoolDiff: %v", errTx) } diff = &PoolDiffDBItem{ Height: height, PoolDiff: poolDiff, } return nil }) return diff, err }
[ "func", "(", "tp", "*", "TicketPool", ")", "fetchDiff", "(", "height", "int64", ")", "(", "*", "PoolDiffDBItem", ",", "error", ")", "{", "var", "heightBytes", "[", "8", "]", "byte", "\n", "binary", ".", "BigEndian", ".", "PutUint64", "(", "heightBytes", "[", ":", "]", ",", "uint64", "(", "height", ")", ")", "\n\n", "var", "diff", "*", "PoolDiffDBItem", "\n", "err", ":=", "tp", ".", "diffDB", ".", "View", "(", "func", "(", "txn", "*", "badger", ".", "Txn", ")", "error", "{", "item", ",", "errTx", ":=", "txn", ".", "Get", "(", "heightBytes", "[", ":", "]", ")", "\n", "if", "errTx", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "height", ",", "errTx", ")", "\n", "}", "\n\n", "// Don't waste time with a copy since we are going to read the data in", "// this transaction.", "var", "hashReader", "bytes", ".", "Reader", "\n", "//nolint:unparam", "errTx", "=", "item", ".", "Value", "(", "func", "(", "v", "[", "]", "byte", ")", "error", "{", "hashReader", ".", "Reset", "(", "v", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "errTx", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "item", ".", "Key", "(", ")", ",", "errTx", ")", "\n", "}", "\n\n", "var", "poolDiff", "PoolDiff", "\n", "if", "errTx", "=", "gob", ".", "NewDecoder", "(", "&", "hashReader", ")", ".", "Decode", "(", "&", "poolDiff", ")", ";", "errTx", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "errTx", ")", "\n", "}", "\n\n", "diff", "=", "&", "PoolDiffDBItem", "{", "Height", ":", "height", ",", "PoolDiff", ":", "poolDiff", ",", "}", "\n", "return", "nil", "\n", "}", ")", "\n\n", "return", "diff", ",", "err", "\n", "}" ]
// fetchDiff retrieves the diff at the specified height from the on-disk DB.
[ "fetchDiff", "retrieves", "the", "diff", "at", "the", "specified", "height", "from", "the", "on", "-", "disk", "DB", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L439-L477
train
decred/dcrdata
stakedb/ticketpool.go
Append
func (tp *TicketPool) Append(diff *PoolDiff, height int64) error { if height != tp.tip+1 { return fmt.Errorf("block height %d does not build on %d", height, tp.tip) } tp.mtx.Lock() defer tp.mtx.Unlock() tp.append(diff) return tp.storeDiff(diff, height) }
go
func (tp *TicketPool) Append(diff *PoolDiff, height int64) error { if height != tp.tip+1 { return fmt.Errorf("block height %d does not build on %d", height, tp.tip) } tp.mtx.Lock() defer tp.mtx.Unlock() tp.append(diff) return tp.storeDiff(diff, height) }
[ "func", "(", "tp", "*", "TicketPool", ")", "Append", "(", "diff", "*", "PoolDiff", ",", "height", "int64", ")", "error", "{", "if", "height", "!=", "tp", ".", "tip", "+", "1", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "height", ",", "tp", ".", "tip", ")", "\n", "}", "\n", "tp", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "tp", ".", "mtx", ".", "Unlock", "(", ")", "\n", "tp", ".", "append", "(", "diff", ")", "\n", "return", "tp", ".", "storeDiff", "(", "diff", ",", "height", ")", "\n", "}" ]
// Append grows the diffs slice with the specified diff, and stores it in the // on-disk DB. The height of the diff is used to check that it builds on the // chain tip, and as a primary key in the DB.
[ "Append", "grows", "the", "diffs", "slice", "with", "the", "specified", "diff", "and", "stores", "it", "in", "the", "on", "-", "disk", "DB", ".", "The", "height", "of", "the", "diff", "is", "used", "to", "check", "that", "it", "builds", "on", "the", "chain", "tip", "and", "as", "a", "primary", "key", "in", "the", "DB", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L482-L490
train
decred/dcrdata
stakedb/ticketpool.go
AppendAndAdvancePool
func (tp *TicketPool) AppendAndAdvancePool(diff *PoolDiff, height int64) error { if height != tp.tip+1 { return fmt.Errorf("block height %d does not build on %d", height, tp.tip) } tp.mtx.Lock() defer tp.mtx.Unlock() tp.append(diff) if err := tp.storeDiff(diff, height); err != nil { return err } return tp.advance() }
go
func (tp *TicketPool) AppendAndAdvancePool(diff *PoolDiff, height int64) error { if height != tp.tip+1 { return fmt.Errorf("block height %d does not build on %d", height, tp.tip) } tp.mtx.Lock() defer tp.mtx.Unlock() tp.append(diff) if err := tp.storeDiff(diff, height); err != nil { return err } return tp.advance() }
[ "func", "(", "tp", "*", "TicketPool", ")", "AppendAndAdvancePool", "(", "diff", "*", "PoolDiff", ",", "height", "int64", ")", "error", "{", "if", "height", "!=", "tp", ".", "tip", "+", "1", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "height", ",", "tp", ".", "tip", ")", "\n", "}", "\n", "tp", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "tp", ".", "mtx", ".", "Unlock", "(", ")", "\n", "tp", ".", "append", "(", "diff", ")", "\n", "if", "err", ":=", "tp", ".", "storeDiff", "(", "diff", ",", "height", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "tp", ".", "advance", "(", ")", "\n", "}" ]
// AppendAndAdvancePool functions like Append, except that after growing the // diffs slice and storing the diff in DB, the ticket pool is advanced.
[ "AppendAndAdvancePool", "functions", "like", "Append", "except", "that", "after", "growing", "the", "diffs", "slice", "and", "storing", "the", "diff", "in", "DB", "the", "ticket", "pool", "is", "advanced", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L494-L505
train
decred/dcrdata
stakedb/ticketpool.go
currentPool
func (tp *TicketPool) currentPool() ([]chainhash.Hash, int64) { poolSize := len(tp.pool) // allocate space for all the ticket hashes, but use append to avoid the // slice initialization having to zero initialize all of the arrays. pool := make([]chainhash.Hash, 0, poolSize) for h := range tp.pool { pool = append(pool, h) } return pool, tp.cursor }
go
func (tp *TicketPool) currentPool() ([]chainhash.Hash, int64) { poolSize := len(tp.pool) // allocate space for all the ticket hashes, but use append to avoid the // slice initialization having to zero initialize all of the arrays. pool := make([]chainhash.Hash, 0, poolSize) for h := range tp.pool { pool = append(pool, h) } return pool, tp.cursor }
[ "func", "(", "tp", "*", "TicketPool", ")", "currentPool", "(", ")", "(", "[", "]", "chainhash", ".", "Hash", ",", "int64", ")", "{", "poolSize", ":=", "len", "(", "tp", ".", "pool", ")", "\n", "// allocate space for all the ticket hashes, but use append to avoid the", "// slice initialization having to zero initialize all of the arrays.", "pool", ":=", "make", "(", "[", "]", "chainhash", ".", "Hash", ",", "0", ",", "poolSize", ")", "\n", "for", "h", ":=", "range", "tp", ".", "pool", "{", "pool", "=", "append", "(", "pool", ",", "h", ")", "\n", "}", "\n", "return", "pool", ",", "tp", ".", "cursor", "\n", "}" ]
// currentPool is the non-thread-safe version of CurrentPool.
[ "currentPool", "is", "the", "non", "-", "thread", "-", "safe", "version", "of", "CurrentPool", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L508-L517
train
decred/dcrdata
stakedb/ticketpool.go
CurrentPoolSize
func (tp *TicketPool) CurrentPoolSize() int { tp.mtx.RLock() defer tp.mtx.RUnlock() return len(tp.pool) }
go
func (tp *TicketPool) CurrentPoolSize() int { tp.mtx.RLock() defer tp.mtx.RUnlock() return len(tp.pool) }
[ "func", "(", "tp", "*", "TicketPool", ")", "CurrentPoolSize", "(", ")", "int", "{", "tp", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "tp", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "len", "(", "tp", ".", "pool", ")", "\n", "}" ]
// CurrentPoolSize returns the number of tickets stored in the current pool map.
[ "CurrentPoolSize", "returns", "the", "number", "of", "tickets", "stored", "in", "the", "current", "pool", "map", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L530-L534
train
decred/dcrdata
stakedb/ticketpool.go
advance
func (tp *TicketPool) advance() error { if tp.cursor > tp.maxCursor() { return fmt.Errorf("cursor at tip, unable to advance") } diffToNext := tp.diffs[tp.cursor] initPoolSize := len(tp.pool) expectedFinalSize := initPoolSize + len(diffToNext.In) - len(diffToNext.Out) tp.applyDiff(diffToNext.In, diffToNext.Out) tp.cursor++ if len(tp.pool) != expectedFinalSize { return fmt.Errorf("pool size is %d, expected %d, at height %d", len(tp.pool), expectedFinalSize, tp.cursor-1) } return nil }
go
func (tp *TicketPool) advance() error { if tp.cursor > tp.maxCursor() { return fmt.Errorf("cursor at tip, unable to advance") } diffToNext := tp.diffs[tp.cursor] initPoolSize := len(tp.pool) expectedFinalSize := initPoolSize + len(diffToNext.In) - len(diffToNext.Out) tp.applyDiff(diffToNext.In, diffToNext.Out) tp.cursor++ if len(tp.pool) != expectedFinalSize { return fmt.Errorf("pool size is %d, expected %d, at height %d", len(tp.pool), expectedFinalSize, tp.cursor-1) } return nil }
[ "func", "(", "tp", "*", "TicketPool", ")", "advance", "(", ")", "error", "{", "if", "tp", ".", "cursor", ">", "tp", ".", "maxCursor", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "diffToNext", ":=", "tp", ".", "diffs", "[", "tp", ".", "cursor", "]", "\n", "initPoolSize", ":=", "len", "(", "tp", ".", "pool", ")", "\n", "expectedFinalSize", ":=", "initPoolSize", "+", "len", "(", "diffToNext", ".", "In", ")", "-", "len", "(", "diffToNext", ".", "Out", ")", "\n\n", "tp", ".", "applyDiff", "(", "diffToNext", ".", "In", ",", "diffToNext", ".", "Out", ")", "\n", "tp", ".", "cursor", "++", "\n\n", "if", "len", "(", "tp", ".", "pool", ")", "!=", "expectedFinalSize", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "tp", ".", "pool", ")", ",", "expectedFinalSize", ",", "tp", ".", "cursor", "-", "1", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// advance applies the pool diff at the current cursor location, and advances // the cursor. Note that when advancing at the last diff, the resulting cursor // will be beyond the last element in the diffs slice.
[ "advance", "applies", "the", "pool", "diff", "at", "the", "current", "cursor", "location", "and", "advances", "the", "cursor", ".", "Note", "that", "when", "advancing", "at", "the", "last", "diff", "the", "resulting", "cursor", "will", "be", "beyond", "the", "last", "element", "in", "the", "diffs", "slice", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L564-L582
train
decred/dcrdata
stakedb/ticketpool.go
advanceTo
func (tp *TicketPool) advanceTo(height int64) error { if height > tp.tip { return fmt.Errorf("cannot advance past tip") } for height > tp.cursor { if err := tp.advance(); err != nil { return err } } return nil }
go
func (tp *TicketPool) advanceTo(height int64) error { if height > tp.tip { return fmt.Errorf("cannot advance past tip") } for height > tp.cursor { if err := tp.advance(); err != nil { return err } } return nil }
[ "func", "(", "tp", "*", "TicketPool", ")", "advanceTo", "(", "height", "int64", ")", "error", "{", "if", "height", ">", "tp", ".", "tip", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "height", ">", "tp", ".", "cursor", "{", "if", "err", ":=", "tp", ".", "advance", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// advanceTo successively applies pool diffs with advance until the cursor // reaches the desired height. Note that this function will return without error // if the initial cursor is at or beyond the specified height.
[ "advanceTo", "successively", "applies", "pool", "diffs", "with", "advance", "until", "the", "cursor", "reaches", "the", "desired", "height", ".", "Note", "that", "this", "function", "will", "return", "without", "error", "if", "the", "initial", "cursor", "is", "at", "or", "beyond", "the", "specified", "height", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L587-L597
train
decred/dcrdata
stakedb/ticketpool.go
AdvanceToTip
func (tp *TicketPool) AdvanceToTip() (int64, error) { tp.mtx.Lock() defer tp.mtx.Unlock() err := tp.advanceTo(tp.tip) return tp.cursor - 1, err }
go
func (tp *TicketPool) AdvanceToTip() (int64, error) { tp.mtx.Lock() defer tp.mtx.Unlock() err := tp.advanceTo(tp.tip) return tp.cursor - 1, err }
[ "func", "(", "tp", "*", "TicketPool", ")", "AdvanceToTip", "(", ")", "(", "int64", ",", "error", ")", "{", "tp", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "tp", ".", "mtx", ".", "Unlock", "(", ")", "\n", "err", ":=", "tp", ".", "advanceTo", "(", "tp", ".", "tip", ")", "\n", "return", "tp", ".", "cursor", "-", "1", ",", "err", "\n", "}" ]
// AdvanceToTip advances the pool map by applying all stored diffs. Note that // the cursor will stop just beyond the last element of the diffs slice. It will // not be possible to advance further, only retreat.
[ "AdvanceToTip", "advances", "the", "pool", "map", "by", "applying", "all", "stored", "diffs", ".", "Note", "that", "the", "cursor", "will", "stop", "just", "beyond", "the", "last", "element", "of", "the", "diffs", "slice", ".", "It", "will", "not", "be", "possible", "to", "advance", "further", "only", "retreat", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L602-L607
train
decred/dcrdata
stakedb/ticketpool.go
retreat
func (tp *TicketPool) retreat() error { if tp.cursor == 0 { return fmt.Errorf("cursor at genesis, unable to retreat") } diffFromPrev := tp.diffs[tp.cursor-1] initPoolSize := len(tp.pool) expectedFinalSize := initPoolSize - len(diffFromPrev.In) + len(diffFromPrev.Out) tp.applyDiff(diffFromPrev.Out, diffFromPrev.In) tp.cursor-- if len(tp.pool) != expectedFinalSize { return fmt.Errorf("pool size is %d, expected %d", len(tp.pool), expectedFinalSize) } return nil }
go
func (tp *TicketPool) retreat() error { if tp.cursor == 0 { return fmt.Errorf("cursor at genesis, unable to retreat") } diffFromPrev := tp.diffs[tp.cursor-1] initPoolSize := len(tp.pool) expectedFinalSize := initPoolSize - len(diffFromPrev.In) + len(diffFromPrev.Out) tp.applyDiff(diffFromPrev.Out, diffFromPrev.In) tp.cursor-- if len(tp.pool) != expectedFinalSize { return fmt.Errorf("pool size is %d, expected %d", len(tp.pool), expectedFinalSize) } return nil }
[ "func", "(", "tp", "*", "TicketPool", ")", "retreat", "(", ")", "error", "{", "if", "tp", ".", "cursor", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "diffFromPrev", ":=", "tp", ".", "diffs", "[", "tp", ".", "cursor", "-", "1", "]", "\n", "initPoolSize", ":=", "len", "(", "tp", ".", "pool", ")", "\n", "expectedFinalSize", ":=", "initPoolSize", "-", "len", "(", "diffFromPrev", ".", "In", ")", "+", "len", "(", "diffFromPrev", ".", "Out", ")", "\n\n", "tp", ".", "applyDiff", "(", "diffFromPrev", ".", "Out", ",", "diffFromPrev", ".", "In", ")", "\n", "tp", ".", "cursor", "--", "\n\n", "if", "len", "(", "tp", ".", "pool", ")", "!=", "expectedFinalSize", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "tp", ".", "pool", ")", ",", "expectedFinalSize", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// retreat applies the previous diff in reverse, moving the pool map to the // state before that diff was applied. The cursor is decremented, and may go to // 0 but not beyond as the cursor is the location of the next unapplied diff.
[ "retreat", "applies", "the", "previous", "diff", "in", "reverse", "moving", "the", "pool", "map", "to", "the", "state", "before", "that", "diff", "was", "applied", ".", "The", "cursor", "is", "decremented", "and", "may", "go", "to", "0", "but", "not", "beyond", "as", "the", "cursor", "is", "the", "location", "of", "the", "next", "unapplied", "diff", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L612-L628
train
decred/dcrdata
stakedb/ticketpool.go
retreatTo
func (tp *TicketPool) retreatTo(height int64) error { if height < 0 || height > tp.tip { return fmt.Errorf("Invalid destination cursor %d", height) } for tp.cursor > height { if err := tp.retreat(); err != nil { return err } } return nil }
go
func (tp *TicketPool) retreatTo(height int64) error { if height < 0 || height > tp.tip { return fmt.Errorf("Invalid destination cursor %d", height) } for tp.cursor > height { if err := tp.retreat(); err != nil { return err } } return nil }
[ "func", "(", "tp", "*", "TicketPool", ")", "retreatTo", "(", "height", "int64", ")", "error", "{", "if", "height", "<", "0", "||", "height", ">", "tp", ".", "tip", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "height", ")", "\n", "}", "\n", "for", "tp", ".", "cursor", ">", "height", "{", "if", "err", ":=", "tp", ".", "retreat", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// retreatTo successively applies pool diffs in reverse with retreate until the // cursor reaches the desired height. Note that this function will return // without error if the initial cursor is at or below the specified height.
[ "retreatTo", "successively", "applies", "pool", "diffs", "in", "reverse", "with", "retreate", "until", "the", "cursor", "reaches", "the", "desired", "height", ".", "Note", "that", "this", "function", "will", "return", "without", "error", "if", "the", "initial", "cursor", "is", "at", "or", "below", "the", "specified", "height", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L642-L652
train
decred/dcrdata
stakedb/ticketpool.go
applyDiff
func (tp *TicketPool) applyDiff(in, out []chainhash.Hash) { initsize := len(tp.pool) for i := range in { tp.pool[in[i]] = struct{}{} } endsize := len(tp.pool) if endsize != initsize+len(in) { log.Warnf("pool grew by %d instead of %d", endsize-initsize, len(in)) } initsize = endsize for i := range out { ii := len(tp.pool) delete(tp.pool, out[i]) if len(tp.pool) == ii { log.Errorf("Failed to remove ticket %v from pool.", out[i]) } } endsize = len(tp.pool) if endsize != initsize-len(out) { log.Warnf("pool shrank by %d instead of %d", initsize-endsize, len(out)) } }
go
func (tp *TicketPool) applyDiff(in, out []chainhash.Hash) { initsize := len(tp.pool) for i := range in { tp.pool[in[i]] = struct{}{} } endsize := len(tp.pool) if endsize != initsize+len(in) { log.Warnf("pool grew by %d instead of %d", endsize-initsize, len(in)) } initsize = endsize for i := range out { ii := len(tp.pool) delete(tp.pool, out[i]) if len(tp.pool) == ii { log.Errorf("Failed to remove ticket %v from pool.", out[i]) } } endsize = len(tp.pool) if endsize != initsize-len(out) { log.Warnf("pool shrank by %d instead of %d", initsize-endsize, len(out)) } }
[ "func", "(", "tp", "*", "TicketPool", ")", "applyDiff", "(", "in", ",", "out", "[", "]", "chainhash", ".", "Hash", ")", "{", "initsize", ":=", "len", "(", "tp", ".", "pool", ")", "\n", "for", "i", ":=", "range", "in", "{", "tp", ".", "pool", "[", "in", "[", "i", "]", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "endsize", ":=", "len", "(", "tp", ".", "pool", ")", "\n", "if", "endsize", "!=", "initsize", "+", "len", "(", "in", ")", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "endsize", "-", "initsize", ",", "len", "(", "in", ")", ")", "\n", "}", "\n", "initsize", "=", "endsize", "\n", "for", "i", ":=", "range", "out", "{", "ii", ":=", "len", "(", "tp", ".", "pool", ")", "\n", "delete", "(", "tp", ".", "pool", ",", "out", "[", "i", "]", ")", "\n", "if", "len", "(", "tp", ".", "pool", ")", "==", "ii", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "out", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n", "endsize", "=", "len", "(", "tp", ".", "pool", ")", "\n", "if", "endsize", "!=", "initsize", "-", "len", "(", "out", ")", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "initsize", "-", "endsize", ",", "len", "(", "out", ")", ")", "\n", "}", "\n", "}" ]
// applyDiff adds and removes tickets from the pool map.
[ "applyDiff", "adds", "and", "removes", "tickets", "from", "the", "pool", "map", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/stakedb/ticketpool.go#L655-L676
train
decred/dcrdata
mempool/mempoolcache.go
GetHeight
func (c *MempoolDataCache) GetHeight() uint32 { c.mtx.RLock() defer c.mtx.RUnlock() return c.height }
go
func (c *MempoolDataCache) GetHeight() uint32 { c.mtx.RLock() defer c.mtx.RUnlock() return c.height }
[ "func", "(", "c", "*", "MempoolDataCache", ")", "GetHeight", "(", ")", "uint32", "{", "c", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "c", ".", "height", "\n", "}" ]
// GetHeight returns the mempool height
[ "GetHeight", "returns", "the", "mempool", "height" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/mempoolcache.go#L64-L68
train
decred/dcrdata
mempool/mempoolcache.go
GetNumTickets
func (c *MempoolDataCache) GetNumTickets() (uint32, uint32) { c.mtx.RLock() defer c.mtx.RUnlock() return c.height, c.numTickets }
go
func (c *MempoolDataCache) GetNumTickets() (uint32, uint32) { c.mtx.RLock() defer c.mtx.RUnlock() return c.height, c.numTickets }
[ "func", "(", "c", "*", "MempoolDataCache", ")", "GetNumTickets", "(", ")", "(", "uint32", ",", "uint32", ")", "{", "c", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "c", ".", "height", ",", "c", ".", "numTickets", "\n", "}" ]
// GetNumTickets returns the mempool height and number of tickets
[ "GetNumTickets", "returns", "the", "mempool", "height", "and", "number", "of", "tickets" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/mempoolcache.go#L71-L75
train
decred/dcrdata
mempool/mempoolcache.go
GetFeeInfo
func (c *MempoolDataCache) GetFeeInfo() (uint32, dcrjson.FeeInfoMempool) { c.mtx.RLock() defer c.mtx.RUnlock() return c.height, c.ticketFeeInfo }
go
func (c *MempoolDataCache) GetFeeInfo() (uint32, dcrjson.FeeInfoMempool) { c.mtx.RLock() defer c.mtx.RUnlock() return c.height, c.ticketFeeInfo }
[ "func", "(", "c", "*", "MempoolDataCache", ")", "GetFeeInfo", "(", ")", "(", "uint32", ",", "dcrjson", ".", "FeeInfoMempool", ")", "{", "c", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "c", ".", "height", ",", "c", ".", "ticketFeeInfo", "\n", "}" ]
// GetFeeInfo returns the mempool height and basic fee info
[ "GetFeeInfo", "returns", "the", "mempool", "height", "and", "basic", "fee", "info" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/mempoolcache.go#L78-L82
train
decred/dcrdata
mempool/mempoolcache.go
GetFeeInfoExtra
func (c *MempoolDataCache) GetFeeInfoExtra() (uint32, *apitypes.MempoolTicketFeeInfo) { c.mtx.RLock() defer c.mtx.RUnlock() feeInfo := apitypes.MempoolTicketFeeInfo{ Height: c.height, Time: c.timestamp.Unix(), FeeInfoMempool: c.ticketFeeInfo, LowestMineable: c.lowestMineableByFeeRate, } return c.height, &feeInfo }
go
func (c *MempoolDataCache) GetFeeInfoExtra() (uint32, *apitypes.MempoolTicketFeeInfo) { c.mtx.RLock() defer c.mtx.RUnlock() feeInfo := apitypes.MempoolTicketFeeInfo{ Height: c.height, Time: c.timestamp.Unix(), FeeInfoMempool: c.ticketFeeInfo, LowestMineable: c.lowestMineableByFeeRate, } return c.height, &feeInfo }
[ "func", "(", "c", "*", "MempoolDataCache", ")", "GetFeeInfoExtra", "(", ")", "(", "uint32", ",", "*", "apitypes", ".", "MempoolTicketFeeInfo", ")", "{", "c", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "feeInfo", ":=", "apitypes", ".", "MempoolTicketFeeInfo", "{", "Height", ":", "c", ".", "height", ",", "Time", ":", "c", ".", "timestamp", ".", "Unix", "(", ")", ",", "FeeInfoMempool", ":", "c", ".", "ticketFeeInfo", ",", "LowestMineable", ":", "c", ".", "lowestMineableByFeeRate", ",", "}", "\n", "return", "c", ".", "height", ",", "&", "feeInfo", "\n", "}" ]
// GetFeeInfoExtra returns the mempool height and detailed fee info
[ "GetFeeInfoExtra", "returns", "the", "mempool", "height", "and", "detailed", "fee", "info" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/mempoolcache.go#L85-L95
train
decred/dcrdata
mempool/mempoolcache.go
GetFees
func (c *MempoolDataCache) GetFees(N int) (uint32, int, []float64) { c.mtx.RLock() defer c.mtx.RUnlock() numFees := len(c.allFees) //var fees []float64 fees := []float64{} // for consistency if N == 0 { return c.height, numFees, fees } if N < 0 || N >= numFees { fees = make([]float64, numFees) copy(fees, c.allFees) } else if N < numFees { // fees are in ascending order, take from end of slice smallestFeeInd := numFees - N fees = make([]float64, N) copy(fees, c.allFees[smallestFeeInd:]) } return c.height, numFees, fees }
go
func (c *MempoolDataCache) GetFees(N int) (uint32, int, []float64) { c.mtx.RLock() defer c.mtx.RUnlock() numFees := len(c.allFees) //var fees []float64 fees := []float64{} // for consistency if N == 0 { return c.height, numFees, fees } if N < 0 || N >= numFees { fees = make([]float64, numFees) copy(fees, c.allFees) } else if N < numFees { // fees are in ascending order, take from end of slice smallestFeeInd := numFees - N fees = make([]float64, N) copy(fees, c.allFees[smallestFeeInd:]) } return c.height, numFees, fees }
[ "func", "(", "c", "*", "MempoolDataCache", ")", "GetFees", "(", "N", "int", ")", "(", "uint32", ",", "int", ",", "[", "]", "float64", ")", "{", "c", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "numFees", ":=", "len", "(", "c", ".", "allFees", ")", "\n\n", "//var fees []float64", "fees", ":=", "[", "]", "float64", "{", "}", "// for consistency", "\n", "if", "N", "==", "0", "{", "return", "c", ".", "height", ",", "numFees", ",", "fees", "\n", "}", "\n\n", "if", "N", "<", "0", "||", "N", ">=", "numFees", "{", "fees", "=", "make", "(", "[", "]", "float64", ",", "numFees", ")", "\n", "copy", "(", "fees", ",", "c", ".", "allFees", ")", "\n", "}", "else", "if", "N", "<", "numFees", "{", "// fees are in ascending order, take from end of slice", "smallestFeeInd", ":=", "numFees", "-", "N", "\n", "fees", "=", "make", "(", "[", "]", "float64", ",", "N", ")", "\n", "copy", "(", "fees", ",", "c", ".", "allFees", "[", "smallestFeeInd", ":", "]", ")", "\n", "}", "\n\n", "return", "c", ".", "height", ",", "numFees", ",", "fees", "\n", "}" ]
// GetFees returns the mempool height number of fees and an array of the fields
[ "GetFees", "returns", "the", "mempool", "height", "number", "of", "fees", "and", "an", "array", "of", "the", "fields" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/mempoolcache.go#L98-L121
train
decred/dcrdata
mempool/mempoolcache.go
GetFeeRates
func (c *MempoolDataCache) GetFeeRates(N int) (uint32, int64, int, []float64) { c.mtx.RLock() defer c.mtx.RUnlock() numFees := len(c.allFeeRates) //var fees []float64 fees := []float64{} if N == 0 { return c.height, c.timestamp.Unix(), numFees, fees } if N < 0 || N >= numFees { fees = make([]float64, numFees) copy(fees, c.allFeeRates) } else if N < numFees { // fees are in ascending order, take from end of slice smallestFeeInd := numFees - N fees = make([]float64, N) copy(fees, c.allFeeRates[smallestFeeInd:]) } return c.height, c.timestamp.Unix(), numFees, fees }
go
func (c *MempoolDataCache) GetFeeRates(N int) (uint32, int64, int, []float64) { c.mtx.RLock() defer c.mtx.RUnlock() numFees := len(c.allFeeRates) //var fees []float64 fees := []float64{} if N == 0 { return c.height, c.timestamp.Unix(), numFees, fees } if N < 0 || N >= numFees { fees = make([]float64, numFees) copy(fees, c.allFeeRates) } else if N < numFees { // fees are in ascending order, take from end of slice smallestFeeInd := numFees - N fees = make([]float64, N) copy(fees, c.allFeeRates[smallestFeeInd:]) } return c.height, c.timestamp.Unix(), numFees, fees }
[ "func", "(", "c", "*", "MempoolDataCache", ")", "GetFeeRates", "(", "N", "int", ")", "(", "uint32", ",", "int64", ",", "int", ",", "[", "]", "float64", ")", "{", "c", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "numFees", ":=", "len", "(", "c", ".", "allFeeRates", ")", "\n\n", "//var fees []float64", "fees", ":=", "[", "]", "float64", "{", "}", "\n", "if", "N", "==", "0", "{", "return", "c", ".", "height", ",", "c", ".", "timestamp", ".", "Unix", "(", ")", ",", "numFees", ",", "fees", "\n", "}", "\n\n", "if", "N", "<", "0", "||", "N", ">=", "numFees", "{", "fees", "=", "make", "(", "[", "]", "float64", ",", "numFees", ")", "\n", "copy", "(", "fees", ",", "c", ".", "allFeeRates", ")", "\n", "}", "else", "if", "N", "<", "numFees", "{", "// fees are in ascending order, take from end of slice", "smallestFeeInd", ":=", "numFees", "-", "N", "\n", "fees", "=", "make", "(", "[", "]", "float64", ",", "N", ")", "\n", "copy", "(", "fees", ",", "c", ".", "allFeeRates", "[", "smallestFeeInd", ":", "]", ")", "\n", "}", "\n\n", "return", "c", ".", "height", ",", "c", ".", "timestamp", ".", "Unix", "(", ")", ",", "numFees", ",", "fees", "\n", "}" ]
// GetFeeRates returns the mempool height, time, number of fees and an array of // fee rates
[ "GetFeeRates", "returns", "the", "mempool", "height", "time", "number", "of", "fees", "and", "an", "array", "of", "fee", "rates" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/mempoolcache.go#L125-L148
train
decred/dcrdata
mempool/mempoolcache.go
GetTicketsDetails
func (c *MempoolDataCache) GetTicketsDetails(N int) (uint32, int64, int, TicketsDetails) { c.mtx.RLock() defer c.mtx.RUnlock() numSSTx := len(c.allTicketsDetails) //var details TicketsDetails details := TicketsDetails{} if N == 0 { return c.height, c.timestamp.Unix(), numSSTx, details } if N < 0 || N >= numSSTx { details = make(TicketsDetails, numSSTx) copy(details, c.allTicketsDetails) } else if N < numSSTx { // fees are in ascending order, take from end of slice smallestFeeInd := numSSTx - N details = make(TicketsDetails, N) copy(details, c.allTicketsDetails[smallestFeeInd:]) } return c.height, c.timestamp.Unix(), numSSTx, details }
go
func (c *MempoolDataCache) GetTicketsDetails(N int) (uint32, int64, int, TicketsDetails) { c.mtx.RLock() defer c.mtx.RUnlock() numSSTx := len(c.allTicketsDetails) //var details TicketsDetails details := TicketsDetails{} if N == 0 { return c.height, c.timestamp.Unix(), numSSTx, details } if N < 0 || N >= numSSTx { details = make(TicketsDetails, numSSTx) copy(details, c.allTicketsDetails) } else if N < numSSTx { // fees are in ascending order, take from end of slice smallestFeeInd := numSSTx - N details = make(TicketsDetails, N) copy(details, c.allTicketsDetails[smallestFeeInd:]) } return c.height, c.timestamp.Unix(), numSSTx, details }
[ "func", "(", "c", "*", "MempoolDataCache", ")", "GetTicketsDetails", "(", "N", "int", ")", "(", "uint32", ",", "int64", ",", "int", ",", "TicketsDetails", ")", "{", "c", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "numSSTx", ":=", "len", "(", "c", ".", "allTicketsDetails", ")", "\n\n", "//var details TicketsDetails", "details", ":=", "TicketsDetails", "{", "}", "\n", "if", "N", "==", "0", "{", "return", "c", ".", "height", ",", "c", ".", "timestamp", ".", "Unix", "(", ")", ",", "numSSTx", ",", "details", "\n", "}", "\n", "if", "N", "<", "0", "||", "N", ">=", "numSSTx", "{", "details", "=", "make", "(", "TicketsDetails", ",", "numSSTx", ")", "\n", "copy", "(", "details", ",", "c", ".", "allTicketsDetails", ")", "\n", "}", "else", "if", "N", "<", "numSSTx", "{", "// fees are in ascending order, take from end of slice", "smallestFeeInd", ":=", "numSSTx", "-", "N", "\n", "details", "=", "make", "(", "TicketsDetails", ",", "N", ")", "\n", "copy", "(", "details", ",", "c", ".", "allTicketsDetails", "[", "smallestFeeInd", ":", "]", ")", "\n", "}", "\n\n", "return", "c", ".", "height", ",", "c", ".", "timestamp", ".", "Unix", "(", ")", ",", "numSSTx", ",", "details", "\n", "}" ]
// GetTicketsDetails returns the mempool height, time, number of tickets and the // ticket details
[ "GetTicketsDetails", "returns", "the", "mempool", "height", "time", "number", "of", "tickets", "and", "the", "ticket", "details" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/mempoolcache.go#L152-L174
train
decred/dcrdata
mempool/mempoolcache.go
GetTicketPriceCountTime
func (c *MempoolDataCache) GetTicketPriceCountTime(feeAvgLength int) *apitypes.PriceCountTime { c.mtx.RLock() defer c.mtx.RUnlock() numFees := len(c.allFees) if numFees < feeAvgLength { feeAvgLength = numFees } var feeAvg float64 for i := 0; i < feeAvgLength; i++ { feeAvg += c.allFees[numFees-i-1] } feeAvg /= float64(feeAvgLength) return &apitypes.PriceCountTime{ Price: c.stakeDiff + feeAvg, Count: numFees, Time: dbtypes.NewTimeDef(c.timestamp), } }
go
func (c *MempoolDataCache) GetTicketPriceCountTime(feeAvgLength int) *apitypes.PriceCountTime { c.mtx.RLock() defer c.mtx.RUnlock() numFees := len(c.allFees) if numFees < feeAvgLength { feeAvgLength = numFees } var feeAvg float64 for i := 0; i < feeAvgLength; i++ { feeAvg += c.allFees[numFees-i-1] } feeAvg /= float64(feeAvgLength) return &apitypes.PriceCountTime{ Price: c.stakeDiff + feeAvg, Count: numFees, Time: dbtypes.NewTimeDef(c.timestamp), } }
[ "func", "(", "c", "*", "MempoolDataCache", ")", "GetTicketPriceCountTime", "(", "feeAvgLength", "int", ")", "*", "apitypes", ".", "PriceCountTime", "{", "c", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "numFees", ":=", "len", "(", "c", ".", "allFees", ")", "\n", "if", "numFees", "<", "feeAvgLength", "{", "feeAvgLength", "=", "numFees", "\n", "}", "\n", "var", "feeAvg", "float64", "\n", "for", "i", ":=", "0", ";", "i", "<", "feeAvgLength", ";", "i", "++", "{", "feeAvg", "+=", "c", ".", "allFees", "[", "numFees", "-", "i", "-", "1", "]", "\n", "}", "\n", "feeAvg", "/=", "float64", "(", "feeAvgLength", ")", "\n\n", "return", "&", "apitypes", ".", "PriceCountTime", "{", "Price", ":", "c", ".", "stakeDiff", "+", "feeAvg", ",", "Count", ":", "numFees", ",", "Time", ":", "dbtypes", ".", "NewTimeDef", "(", "c", ".", "timestamp", ")", ",", "}", "\n", "}" ]
// GetTicketPriceCountTime gathers the nominal info for mempool tickets.
[ "GetTicketPriceCountTime", "gathers", "the", "nominal", "info", "for", "mempool", "tickets", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/mempool/mempoolcache.go#L177-L196
train
decred/dcrdata
api/insight/apiroutes.go
NewInsightApi
func NewInsightApi(client *rpcclient.Client, blockData *dcrpg.ChainDBRPC, params *chaincfg.Params, memPoolData rpcutils.MempoolAddressChecker, JSONIndent string, maxAddrs int, status *apitypes.Status) *InsightApi { newContext := InsightApi{ nodeClient: client, BlockData: blockData, params: params, mp: memPoolData, status: status, ReqPerSecLimit: defaultReqPerSecLimit, maxCSVAddrs: maxAddrs, } return &newContext }
go
func NewInsightApi(client *rpcclient.Client, blockData *dcrpg.ChainDBRPC, params *chaincfg.Params, memPoolData rpcutils.MempoolAddressChecker, JSONIndent string, maxAddrs int, status *apitypes.Status) *InsightApi { newContext := InsightApi{ nodeClient: client, BlockData: blockData, params: params, mp: memPoolData, status: status, ReqPerSecLimit: defaultReqPerSecLimit, maxCSVAddrs: maxAddrs, } return &newContext }
[ "func", "NewInsightApi", "(", "client", "*", "rpcclient", ".", "Client", ",", "blockData", "*", "dcrpg", ".", "ChainDBRPC", ",", "params", "*", "chaincfg", ".", "Params", ",", "memPoolData", "rpcutils", ".", "MempoolAddressChecker", ",", "JSONIndent", "string", ",", "maxAddrs", "int", ",", "status", "*", "apitypes", ".", "Status", ")", "*", "InsightApi", "{", "newContext", ":=", "InsightApi", "{", "nodeClient", ":", "client", ",", "BlockData", ":", "blockData", ",", "params", ":", "params", ",", "mp", ":", "memPoolData", ",", "status", ":", "status", ",", "ReqPerSecLimit", ":", "defaultReqPerSecLimit", ",", "maxCSVAddrs", ":", "maxAddrs", ",", "}", "\n", "return", "&", "newContext", "\n", "}" ]
// NewInsightApi is the constructor for InsightApi.
[ "NewInsightApi", "is", "the", "constructor", "for", "InsightApi", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/insight/apiroutes.go#L46-L59
train
decred/dcrdata
db/dcrpg/insightapi.go
GetRawTransaction
func (pgb *ChainDBRPC) GetRawTransaction(txid *chainhash.Hash) (*dcrjson.TxRawResult, error) { txraw, err := rpcutils.GetTransactionVerboseByID(pgb.Client, txid) if err != nil { log.Errorf("GetRawTransactionVerbose failed for: %s", txid) return nil, err } return txraw, nil }
go
func (pgb *ChainDBRPC) GetRawTransaction(txid *chainhash.Hash) (*dcrjson.TxRawResult, error) { txraw, err := rpcutils.GetTransactionVerboseByID(pgb.Client, txid) if err != nil { log.Errorf("GetRawTransactionVerbose failed for: %s", txid) return nil, err } return txraw, nil }
[ "func", "(", "pgb", "*", "ChainDBRPC", ")", "GetRawTransaction", "(", "txid", "*", "chainhash", ".", "Hash", ")", "(", "*", "dcrjson", ".", "TxRawResult", ",", "error", ")", "{", "txraw", ",", "err", ":=", "rpcutils", ".", "GetTransactionVerboseByID", "(", "pgb", ".", "Client", ",", "txid", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "txid", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "txraw", ",", "nil", "\n", "}" ]
// GetRawTransaction gets a dcrjson.TxRawResult for the specified transaction // hash.
[ "GetRawTransaction", "gets", "a", "dcrjson", ".", "TxRawResult", "for", "the", "specified", "transaction", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/insightapi.go#L23-L30
train
decred/dcrdata
db/dcrpg/insightapi.go
GetBlockHeight
func (pgb *ChainDB) GetBlockHeight(hash string) (int64, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() height, err := RetrieveBlockHeight(ctx, pgb.db, hash) if err != nil { log.Errorf("Unable to get block height for hash %s: %v", hash, err) return -1, pgb.replaceCancelError(err) } return height, nil }
go
func (pgb *ChainDB) GetBlockHeight(hash string) (int64, error) { ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout) defer cancel() height, err := RetrieveBlockHeight(ctx, pgb.db, hash) if err != nil { log.Errorf("Unable to get block height for hash %s: %v", hash, err) return -1, pgb.replaceCancelError(err) } return height, nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "GetBlockHeight", "(", "hash", "string", ")", "(", "int64", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "pgb", ".", "ctx", ",", "pgb", ".", "queryTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "height", ",", "err", ":=", "RetrieveBlockHeight", "(", "ctx", ",", "pgb", ".", "db", ",", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "hash", ",", "err", ")", "\n", "return", "-", "1", ",", "pgb", ".", "replaceCancelError", "(", "err", ")", "\n", "}", "\n", "return", "height", ",", "nil", "\n", "}" ]
// GetBlockHeight returns the height of the block with the specified hash.
[ "GetBlockHeight", "returns", "the", "height", "of", "the", "block", "with", "the", "specified", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/insightapi.go#L33-L42
train
decred/dcrdata
db/dcrpg/insightapi.go
SendRawTransaction
func (pgb *ChainDBRPC) SendRawTransaction(txhex string) (string, error) { msg, err := txhelpers.MsgTxFromHex(txhex) if err != nil { log.Errorf("SendRawTransaction failed: could not decode hex") return "", err } hash, err := pgb.Client.SendRawTransaction(msg, true) if err != nil { log.Errorf("SendRawTransaction failed: %v", err) return "", err } return hash.String(), err }
go
func (pgb *ChainDBRPC) SendRawTransaction(txhex string) (string, error) { msg, err := txhelpers.MsgTxFromHex(txhex) if err != nil { log.Errorf("SendRawTransaction failed: could not decode hex") return "", err } hash, err := pgb.Client.SendRawTransaction(msg, true) if err != nil { log.Errorf("SendRawTransaction failed: %v", err) return "", err } return hash.String(), err }
[ "func", "(", "pgb", "*", "ChainDBRPC", ")", "SendRawTransaction", "(", "txhex", "string", ")", "(", "string", ",", "error", ")", "{", "msg", ",", "err", ":=", "txhelpers", ".", "MsgTxFromHex", "(", "txhex", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "hash", ",", "err", ":=", "pgb", ".", "Client", ".", "SendRawTransaction", "(", "msg", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "hash", ".", "String", "(", ")", ",", "err", "\n", "}" ]
// SendRawTransaction attempts to decode the input serialized transaction, // passed as hex encoded string, and broadcast it, returning the tx hash.
[ "SendRawTransaction", "attempts", "to", "decode", "the", "input", "serialized", "transaction", "passed", "as", "hex", "encoded", "string", "and", "broadcast", "it", "returning", "the", "tx", "hash", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/insightapi.go#L46-L58
train
decred/dcrdata
db/dcrpg/insightapi.go
GetTransactionHex
func (pgb *ChainDBRPC) GetTransactionHex(txid *chainhash.Hash) string { txraw, err := rpcutils.GetTransactionVerboseByID(pgb.Client, txid) if err != nil { log.Errorf("GetRawTransactionVerbose failed for: %v", err) return "" } return txraw.Hex }
go
func (pgb *ChainDBRPC) GetTransactionHex(txid *chainhash.Hash) string { txraw, err := rpcutils.GetTransactionVerboseByID(pgb.Client, txid) if err != nil { log.Errorf("GetRawTransactionVerbose failed for: %v", err) return "" } return txraw.Hex }
[ "func", "(", "pgb", "*", "ChainDBRPC", ")", "GetTransactionHex", "(", "txid", "*", "chainhash", ".", "Hash", ")", "string", "{", "txraw", ",", "err", ":=", "rpcutils", ".", "GetTransactionVerboseByID", "(", "pgb", ".", "Client", ",", "txid", ")", "\n\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\"", "\"", "\n", "}", "\n\n", "return", "txraw", ".", "Hex", "\n", "}" ]
// GetTransactionHex returns the full serialized transaction for the specified // transaction hash as a hex encode string.
[ "GetTransactionHex", "returns", "the", "full", "serialized", "transaction", "for", "the", "specified", "transaction", "hash", "as", "a", "hex", "encode", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/insightapi.go#L172-L181
train
decred/dcrdata
db/dcrpg/indexing.go
IndexVinTableOnVins
func IndexVinTableOnVins(db *sql.DB) (err error) { _, err = db.Exec(internal.IndexVinTableOnVins) return }
go
func IndexVinTableOnVins(db *sql.DB) (err error) { _, err = db.Exec(internal.IndexVinTableOnVins) return }
[ "func", "IndexVinTableOnVins", "(", "db", "*", "sql", ".", "DB", ")", "(", "err", "error", ")", "{", "_", ",", "err", "=", "db", ".", "Exec", "(", "internal", ".", "IndexVinTableOnVins", ")", "\n", "return", "\n", "}" ]
// Vins table indexes
[ "Vins", "table", "indexes" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/indexing.go#L29-L32
train
decred/dcrdata
db/dcrpg/indexing.go
MissingIndexes
func (pgb *ChainDB) MissingIndexes() (missing, descs []string, err error) { for idxName, desc := range internal.IndexDescriptions { var exists bool exists, err = ExistsIndex(pgb.db, idxName) if err != nil { return } if !exists { missing = append(missing, idxName) descs = append(descs, desc) } } return }
go
func (pgb *ChainDB) MissingIndexes() (missing, descs []string, err error) { for idxName, desc := range internal.IndexDescriptions { var exists bool exists, err = ExistsIndex(pgb.db, idxName) if err != nil { return } if !exists { missing = append(missing, idxName) descs = append(descs, desc) } } return }
[ "func", "(", "pgb", "*", "ChainDB", ")", "MissingIndexes", "(", ")", "(", "missing", ",", "descs", "[", "]", "string", ",", "err", "error", ")", "{", "for", "idxName", ",", "desc", ":=", "range", "internal", ".", "IndexDescriptions", "{", "var", "exists", "bool", "\n", "exists", ",", "err", "=", "ExistsIndex", "(", "pgb", ".", "db", ",", "idxName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "!", "exists", "{", "missing", "=", "append", "(", "missing", ",", "idxName", ")", "\n", "descs", "=", "append", "(", "descs", ",", "desc", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Indexes checks // MissingIndexes lists missing table indexes and their descriptions.
[ "Indexes", "checks", "MissingIndexes", "lists", "missing", "table", "indexes", "and", "their", "descriptions", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/indexing.go#L364-L377
train
decred/dcrdata
db/dcrpg/indexing.go
MissingAddressIndexes
func (pgb *ChainDB) MissingAddressIndexes() (missing []string, descs []string, err error) { for _, idxName := range internal.AddressesIndexNames { var exists bool exists, err = ExistsIndex(pgb.db, idxName) if err != nil { return } if !exists { missing = append(missing, idxName) descs = append(descs, pgb.indexDescription(idxName)) } } return }
go
func (pgb *ChainDB) MissingAddressIndexes() (missing []string, descs []string, err error) { for _, idxName := range internal.AddressesIndexNames { var exists bool exists, err = ExistsIndex(pgb.db, idxName) if err != nil { return } if !exists { missing = append(missing, idxName) descs = append(descs, pgb.indexDescription(idxName)) } } return }
[ "func", "(", "pgb", "*", "ChainDB", ")", "MissingAddressIndexes", "(", ")", "(", "missing", "[", "]", "string", ",", "descs", "[", "]", "string", ",", "err", "error", ")", "{", "for", "_", ",", "idxName", ":=", "range", "internal", ".", "AddressesIndexNames", "{", "var", "exists", "bool", "\n", "exists", ",", "err", "=", "ExistsIndex", "(", "pgb", ".", "db", ",", "idxName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "!", "exists", "{", "missing", "=", "append", "(", "missing", ",", "idxName", ")", "\n", "descs", "=", "append", "(", "descs", ",", "pgb", ".", "indexDescription", "(", "idxName", ")", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// MissingAddressIndexes list missing addresses table indexes and their // descriptions.
[ "MissingAddressIndexes", "list", "missing", "addresses", "table", "indexes", "and", "their", "descriptions", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/indexing.go#L381-L394
train
decred/dcrdata
db/dcrpg/indexing.go
indexDescription
func (pgb *ChainDB) indexDescription(indexName string) string { name, ok := internal.IndexDescriptions[indexName] if !ok { name = "unknown index" } return name }
go
func (pgb *ChainDB) indexDescription(indexName string) string { name, ok := internal.IndexDescriptions[indexName] if !ok { name = "unknown index" } return name }
[ "func", "(", "pgb", "*", "ChainDB", ")", "indexDescription", "(", "indexName", "string", ")", "string", "{", "name", ",", "ok", ":=", "internal", ".", "IndexDescriptions", "[", "indexName", "]", "\n", "if", "!", "ok", "{", "name", "=", "\"", "\"", "\n", "}", "\n", "return", "name", "\n", "}" ]
// indexDescription gives the description of the named index.
[ "indexDescription", "gives", "the", "description", "of", "the", "named", "index", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/indexing.go#L397-L403
train
decred/dcrdata
db/dcrpg/indexing.go
DeindexAll
func (pgb *ChainDB) DeindexAll() error { allDeIndexes := []deIndexingInfo{ // blocks table {DeindexBlockTableOnHash}, {DeindexBlockTableOnHeight}, // transactions table {DeindexTransactionTableOnHashes}, {DeindexTransactionTableOnBlockIn}, // vins table {DeindexVinTableOnVins}, {DeindexVinTableOnPrevOuts}, // vouts table {DeindexVoutTableOnTxHashIdx}, // addresses table {DeindexBlockTimeOnTableAddress}, {DeindexMatchingTxHashOnTableAddress}, {DeindexAddressTableOnAddress}, {DeindexAddressTableOnVoutID}, {DeindexAddressTableOnTxHash}, // votes table {DeindexVotesTableOnCandidate}, {DeindexVotesTableOnBlockHash}, {DeindexVotesTableOnHash}, {DeindexVotesTableOnVoteVersion}, {DeindexVotesTableOnHeight}, {DeindexVotesTableOnBlockTime}, // misses table {DeindexMissesTableOnHash}, // agendas table {DeindexAgendasTableOnAgendaID}, // agenda votes table {DeindexAgendaVotesTableOnAgendaID}, // proposals table {DeindexProposalsTableOnToken}, // proposal votes table {DeindexProposalVotesTableOnProposalsID}, } var err error for _, val := range allDeIndexes { if err = val.DeIndexFunc(pgb.db); err != nil { warnUnlessNotExists(err) } } if err = pgb.DeindexTicketsTable(); err != nil { warnUnlessNotExists(err) err = nil } return err }
go
func (pgb *ChainDB) DeindexAll() error { allDeIndexes := []deIndexingInfo{ // blocks table {DeindexBlockTableOnHash}, {DeindexBlockTableOnHeight}, // transactions table {DeindexTransactionTableOnHashes}, {DeindexTransactionTableOnBlockIn}, // vins table {DeindexVinTableOnVins}, {DeindexVinTableOnPrevOuts}, // vouts table {DeindexVoutTableOnTxHashIdx}, // addresses table {DeindexBlockTimeOnTableAddress}, {DeindexMatchingTxHashOnTableAddress}, {DeindexAddressTableOnAddress}, {DeindexAddressTableOnVoutID}, {DeindexAddressTableOnTxHash}, // votes table {DeindexVotesTableOnCandidate}, {DeindexVotesTableOnBlockHash}, {DeindexVotesTableOnHash}, {DeindexVotesTableOnVoteVersion}, {DeindexVotesTableOnHeight}, {DeindexVotesTableOnBlockTime}, // misses table {DeindexMissesTableOnHash}, // agendas table {DeindexAgendasTableOnAgendaID}, // agenda votes table {DeindexAgendaVotesTableOnAgendaID}, // proposals table {DeindexProposalsTableOnToken}, // proposal votes table {DeindexProposalVotesTableOnProposalsID}, } var err error for _, val := range allDeIndexes { if err = val.DeIndexFunc(pgb.db); err != nil { warnUnlessNotExists(err) } } if err = pgb.DeindexTicketsTable(); err != nil { warnUnlessNotExists(err) err = nil } return err }
[ "func", "(", "pgb", "*", "ChainDB", ")", "DeindexAll", "(", ")", "error", "{", "allDeIndexes", ":=", "[", "]", "deIndexingInfo", "{", "// blocks table", "{", "DeindexBlockTableOnHash", "}", ",", "{", "DeindexBlockTableOnHeight", "}", ",", "// transactions table", "{", "DeindexTransactionTableOnHashes", "}", ",", "{", "DeindexTransactionTableOnBlockIn", "}", ",", "// vins table", "{", "DeindexVinTableOnVins", "}", ",", "{", "DeindexVinTableOnPrevOuts", "}", ",", "// vouts table", "{", "DeindexVoutTableOnTxHashIdx", "}", ",", "// addresses table", "{", "DeindexBlockTimeOnTableAddress", "}", ",", "{", "DeindexMatchingTxHashOnTableAddress", "}", ",", "{", "DeindexAddressTableOnAddress", "}", ",", "{", "DeindexAddressTableOnVoutID", "}", ",", "{", "DeindexAddressTableOnTxHash", "}", ",", "// votes table", "{", "DeindexVotesTableOnCandidate", "}", ",", "{", "DeindexVotesTableOnBlockHash", "}", ",", "{", "DeindexVotesTableOnHash", "}", ",", "{", "DeindexVotesTableOnVoteVersion", "}", ",", "{", "DeindexVotesTableOnHeight", "}", ",", "{", "DeindexVotesTableOnBlockTime", "}", ",", "// misses table", "{", "DeindexMissesTableOnHash", "}", ",", "// agendas table", "{", "DeindexAgendasTableOnAgendaID", "}", ",", "// agenda votes table", "{", "DeindexAgendaVotesTableOnAgendaID", "}", ",", "// proposals table", "{", "DeindexProposalsTableOnToken", "}", ",", "// proposal votes table", "{", "DeindexProposalVotesTableOnProposalsID", "}", ",", "}", "\n\n", "var", "err", "error", "\n", "for", "_", ",", "val", ":=", "range", "allDeIndexes", "{", "if", "err", "=", "val", ".", "DeIndexFunc", "(", "pgb", ".", "db", ")", ";", "err", "!=", "nil", "{", "warnUnlessNotExists", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "if", "err", "=", "pgb", ".", "DeindexTicketsTable", "(", ")", ";", "err", "!=", "nil", "{", "warnUnlessNotExists", "(", "err", ")", "\n", "err", "=", "nil", "\n", "}", "\n", "return", "err", "\n", "}" ]
// DeindexAll drops indexes in most tables.
[ "DeindexAll", "drops", "indexes", "in", "most", "tables", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/indexing.go#L406-L466
train
decred/dcrdata
db/dcrpg/indexing.go
IndexTicketsTable
func (pgb *ChainDB) IndexTicketsTable(barLoad chan *dbtypes.ProgressBarLoad) error { ticketsTableIndexes := []indexingInfo{ {Msg: "ticket hash", IndexFunc: IndexTicketsTableOnHashes}, {Msg: "ticket pool status", IndexFunc: IndexTicketsTableOnPoolStatus}, {Msg: "transaction Db ID", IndexFunc: IndexTicketsTableOnTxDbID}, } for _, val := range ticketsTableIndexes { logMsg := "Indexing tickets table on " + val.Msg + "..." log.Info(logMsg) if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.AddressesTableSync, Subtitle: logMsg} } if err := val.IndexFunc(pgb.db); err != nil { return err } } // Signal task is done. if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.AddressesTableSync, Subtitle: " "} } return nil }
go
func (pgb *ChainDB) IndexTicketsTable(barLoad chan *dbtypes.ProgressBarLoad) error { ticketsTableIndexes := []indexingInfo{ {Msg: "ticket hash", IndexFunc: IndexTicketsTableOnHashes}, {Msg: "ticket pool status", IndexFunc: IndexTicketsTableOnPoolStatus}, {Msg: "transaction Db ID", IndexFunc: IndexTicketsTableOnTxDbID}, } for _, val := range ticketsTableIndexes { logMsg := "Indexing tickets table on " + val.Msg + "..." log.Info(logMsg) if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.AddressesTableSync, Subtitle: logMsg} } if err := val.IndexFunc(pgb.db); err != nil { return err } } // Signal task is done. if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.AddressesTableSync, Subtitle: " "} } return nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "IndexTicketsTable", "(", "barLoad", "chan", "*", "dbtypes", ".", "ProgressBarLoad", ")", "error", "{", "ticketsTableIndexes", ":=", "[", "]", "indexingInfo", "{", "{", "Msg", ":", "\"", "\"", ",", "IndexFunc", ":", "IndexTicketsTableOnHashes", "}", ",", "{", "Msg", ":", "\"", "\"", ",", "IndexFunc", ":", "IndexTicketsTableOnPoolStatus", "}", ",", "{", "Msg", ":", "\"", "\"", ",", "IndexFunc", ":", "IndexTicketsTableOnTxDbID", "}", ",", "}", "\n\n", "for", "_", ",", "val", ":=", "range", "ticketsTableIndexes", "{", "logMsg", ":=", "\"", "\"", "+", "val", ".", "Msg", "+", "\"", "\"", "\n", "log", ".", "Info", "(", "logMsg", ")", "\n", "if", "barLoad", "!=", "nil", "{", "barLoad", "<-", "&", "dbtypes", ".", "ProgressBarLoad", "{", "BarID", ":", "dbtypes", ".", "AddressesTableSync", ",", "Subtitle", ":", "logMsg", "}", "\n", "}", "\n\n", "if", "err", ":=", "val", ".", "IndexFunc", "(", "pgb", ".", "db", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "// Signal task is done.", "if", "barLoad", "!=", "nil", "{", "barLoad", "<-", "&", "dbtypes", ".", "ProgressBarLoad", "{", "BarID", ":", "dbtypes", ".", "AddressesTableSync", ",", "Subtitle", ":", "\"", "\"", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// IndexTicketsTable creates indexes in the tickets table on ticket hash, // ticket pool status and tx DB ID columns.
[ "IndexTicketsTable", "creates", "indexes", "in", "the", "tickets", "table", "on", "ticket", "hash", "ticket", "pool", "status", "and", "tx", "DB", "ID", "columns", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/indexing.go#L540-L563
train
decred/dcrdata
db/dcrpg/indexing.go
DeindexTicketsTable
func (pgb *ChainDB) DeindexTicketsTable() error { ticketsTablesDeIndexes := []deIndexingInfo{ {DeindexTicketsTableOnHashes}, {DeindexTicketsTableOnPoolStatus}, {DeindexTicketsTableOnTxDbID}, } var err error for _, val := range ticketsTablesDeIndexes { if err = val.DeIndexFunc(pgb.db); err != nil { warnUnlessNotExists(err) err = nil } } return err }
go
func (pgb *ChainDB) DeindexTicketsTable() error { ticketsTablesDeIndexes := []deIndexingInfo{ {DeindexTicketsTableOnHashes}, {DeindexTicketsTableOnPoolStatus}, {DeindexTicketsTableOnTxDbID}, } var err error for _, val := range ticketsTablesDeIndexes { if err = val.DeIndexFunc(pgb.db); err != nil { warnUnlessNotExists(err) err = nil } } return err }
[ "func", "(", "pgb", "*", "ChainDB", ")", "DeindexTicketsTable", "(", ")", "error", "{", "ticketsTablesDeIndexes", ":=", "[", "]", "deIndexingInfo", "{", "{", "DeindexTicketsTableOnHashes", "}", ",", "{", "DeindexTicketsTableOnPoolStatus", "}", ",", "{", "DeindexTicketsTableOnTxDbID", "}", ",", "}", "\n\n", "var", "err", "error", "\n", "for", "_", ",", "val", ":=", "range", "ticketsTablesDeIndexes", "{", "if", "err", "=", "val", ".", "DeIndexFunc", "(", "pgb", ".", "db", ")", ";", "err", "!=", "nil", "{", "warnUnlessNotExists", "(", "err", ")", "\n", "err", "=", "nil", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// DeindexTicketsTable drops indexes in the tickets table on ticket hash, // ticket pool status and tx DB ID columns.
[ "DeindexTicketsTable", "drops", "indexes", "in", "the", "tickets", "table", "on", "ticket", "hash", "ticket", "pool", "status", "and", "tx", "DB", "ID", "columns", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/indexing.go#L567-L582
train
decred/dcrdata
db/dcrpg/indexing.go
IndexAddressTable
func (pgb *ChainDB) IndexAddressTable(barLoad chan *dbtypes.ProgressBarLoad) error { addressesTableIndexes := []indexingInfo{ {Msg: "address", IndexFunc: IndexAddressTableOnAddress}, {Msg: "matching tx hash", IndexFunc: IndexMatchingTxHashOnTableAddress}, {Msg: "block time", IndexFunc: IndexBlockTimeOnTableAddress}, {Msg: "vout Db ID", IndexFunc: IndexAddressTableOnVoutID}, //{Msg: "tx hash", IndexFunc: IndexAddressTableOnTxHash}, } for _, val := range addressesTableIndexes { logMsg := "Indexing addresses table on " + val.Msg + "..." log.Info(logMsg) if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.AddressesTableSync, Subtitle: logMsg} } if err := val.IndexFunc(pgb.db); err != nil { return err } } // Signal task is done. if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.AddressesTableSync, Subtitle: " "} } return nil }
go
func (pgb *ChainDB) IndexAddressTable(barLoad chan *dbtypes.ProgressBarLoad) error { addressesTableIndexes := []indexingInfo{ {Msg: "address", IndexFunc: IndexAddressTableOnAddress}, {Msg: "matching tx hash", IndexFunc: IndexMatchingTxHashOnTableAddress}, {Msg: "block time", IndexFunc: IndexBlockTimeOnTableAddress}, {Msg: "vout Db ID", IndexFunc: IndexAddressTableOnVoutID}, //{Msg: "tx hash", IndexFunc: IndexAddressTableOnTxHash}, } for _, val := range addressesTableIndexes { logMsg := "Indexing addresses table on " + val.Msg + "..." log.Info(logMsg) if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.AddressesTableSync, Subtitle: logMsg} } if err := val.IndexFunc(pgb.db); err != nil { return err } } // Signal task is done. if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.AddressesTableSync, Subtitle: " "} } return nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "IndexAddressTable", "(", "barLoad", "chan", "*", "dbtypes", ".", "ProgressBarLoad", ")", "error", "{", "addressesTableIndexes", ":=", "[", "]", "indexingInfo", "{", "{", "Msg", ":", "\"", "\"", ",", "IndexFunc", ":", "IndexAddressTableOnAddress", "}", ",", "{", "Msg", ":", "\"", "\"", ",", "IndexFunc", ":", "IndexMatchingTxHashOnTableAddress", "}", ",", "{", "Msg", ":", "\"", "\"", ",", "IndexFunc", ":", "IndexBlockTimeOnTableAddress", "}", ",", "{", "Msg", ":", "\"", "\"", ",", "IndexFunc", ":", "IndexAddressTableOnVoutID", "}", ",", "//{Msg: \"tx hash\", IndexFunc: IndexAddressTableOnTxHash},", "}", "\n\n", "for", "_", ",", "val", ":=", "range", "addressesTableIndexes", "{", "logMsg", ":=", "\"", "\"", "+", "val", ".", "Msg", "+", "\"", "\"", "\n", "log", ".", "Info", "(", "logMsg", ")", "\n", "if", "barLoad", "!=", "nil", "{", "barLoad", "<-", "&", "dbtypes", ".", "ProgressBarLoad", "{", "BarID", ":", "dbtypes", ".", "AddressesTableSync", ",", "Subtitle", ":", "logMsg", "}", "\n", "}", "\n\n", "if", "err", ":=", "val", ".", "IndexFunc", "(", "pgb", ".", "db", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "// Signal task is done.", "if", "barLoad", "!=", "nil", "{", "barLoad", "<-", "&", "dbtypes", ".", "ProgressBarLoad", "{", "BarID", ":", "dbtypes", ".", "AddressesTableSync", ",", "Subtitle", ":", "\"", "\"", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// IndexAddressTable creates the indexes on the address table on the vout ID, // block_time, matching_tx_hash and address columns.
[ "IndexAddressTable", "creates", "the", "indexes", "on", "the", "address", "table", "on", "the", "vout", "ID", "block_time", "matching_tx_hash", "and", "address", "columns", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/indexing.go#L607-L632
train
decred/dcrdata
db/dcrpg/indexing.go
DeindexAddressTable
func (pgb *ChainDB) DeindexAddressTable() error { addressesDeindexes := []deIndexingInfo{ {DeindexAddressTableOnAddress}, {DeindexMatchingTxHashOnTableAddress}, {DeindexBlockTimeOnTableAddress}, {DeindexAddressTableOnVoutID}, //{DeindexAddressTableOnTxHash}, } var err error for _, val := range addressesDeindexes { if err = val.DeIndexFunc(pgb.db); err != nil { warnUnlessNotExists(err) err = nil } } return err }
go
func (pgb *ChainDB) DeindexAddressTable() error { addressesDeindexes := []deIndexingInfo{ {DeindexAddressTableOnAddress}, {DeindexMatchingTxHashOnTableAddress}, {DeindexBlockTimeOnTableAddress}, {DeindexAddressTableOnVoutID}, //{DeindexAddressTableOnTxHash}, } var err error for _, val := range addressesDeindexes { if err = val.DeIndexFunc(pgb.db); err != nil { warnUnlessNotExists(err) err = nil } } return err }
[ "func", "(", "pgb", "*", "ChainDB", ")", "DeindexAddressTable", "(", ")", "error", "{", "addressesDeindexes", ":=", "[", "]", "deIndexingInfo", "{", "{", "DeindexAddressTableOnAddress", "}", ",", "{", "DeindexMatchingTxHashOnTableAddress", "}", ",", "{", "DeindexBlockTimeOnTableAddress", "}", ",", "{", "DeindexAddressTableOnVoutID", "}", ",", "//{DeindexAddressTableOnTxHash},", "}", "\n\n", "var", "err", "error", "\n", "for", "_", ",", "val", ":=", "range", "addressesDeindexes", "{", "if", "err", "=", "val", ".", "DeIndexFunc", "(", "pgb", ".", "db", ")", ";", "err", "!=", "nil", "{", "warnUnlessNotExists", "(", "err", ")", "\n", "err", "=", "nil", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// DeindexAddressTable drops the vin ID, block_time, matching_tx_hash // and address column indexes for the address table.
[ "DeindexAddressTable", "drops", "the", "vin", "ID", "block_time", "matching_tx_hash", "and", "address", "column", "indexes", "for", "the", "address", "table", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/indexing.go#L636-L653
train
decred/dcrdata
txhelpers/staketree.go
TicketTxnsInBlock
func TicketTxnsInBlock(bl *dcrutil.Block) ([]chainhash.Hash, []*dcrutil.Tx) { tickets := make([]chainhash.Hash, 0) ticketTxns := make([]*dcrutil.Tx, 0) for _, stx := range bl.STransactions() { if stake.DetermineTxType(stx.MsgTx()) == stake.TxTypeSStx { h := stx.Hash() tickets = append(tickets, *h) ticketTxns = append(ticketTxns, stx) } } return tickets, ticketTxns }
go
func TicketTxnsInBlock(bl *dcrutil.Block) ([]chainhash.Hash, []*dcrutil.Tx) { tickets := make([]chainhash.Hash, 0) ticketTxns := make([]*dcrutil.Tx, 0) for _, stx := range bl.STransactions() { if stake.DetermineTxType(stx.MsgTx()) == stake.TxTypeSStx { h := stx.Hash() tickets = append(tickets, *h) ticketTxns = append(ticketTxns, stx) } } return tickets, ticketTxns }
[ "func", "TicketTxnsInBlock", "(", "bl", "*", "dcrutil", ".", "Block", ")", "(", "[", "]", "chainhash", ".", "Hash", ",", "[", "]", "*", "dcrutil", ".", "Tx", ")", "{", "tickets", ":=", "make", "(", "[", "]", "chainhash", ".", "Hash", ",", "0", ")", "\n", "ticketTxns", ":=", "make", "(", "[", "]", "*", "dcrutil", ".", "Tx", ",", "0", ")", "\n", "for", "_", ",", "stx", ":=", "range", "bl", ".", "STransactions", "(", ")", "{", "if", "stake", ".", "DetermineTxType", "(", "stx", ".", "MsgTx", "(", ")", ")", "==", "stake", ".", "TxTypeSStx", "{", "h", ":=", "stx", ".", "Hash", "(", ")", "\n", "tickets", "=", "append", "(", "tickets", ",", "*", "h", ")", "\n", "ticketTxns", "=", "append", "(", "ticketTxns", ",", "stx", ")", "\n", "}", "\n", "}", "\n\n", "return", "tickets", ",", "ticketTxns", "\n", "}" ]
// TicketTxnsInBlock finds all the new tickets in the block.
[ "TicketTxnsInBlock", "finds", "all", "the", "new", "tickets", "in", "the", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/staketree.go#L161-L173
train
decred/dcrdata
txhelpers/staketree.go
TicketsSpentInBlock
func TicketsSpentInBlock(bl *dcrutil.Block) []chainhash.Hash { tickets := make([]chainhash.Hash, 0) for _, stx := range bl.STransactions() { if stake.DetermineTxType(stx.MsgTx()) == stake.TxTypeSSGen { // Hash of the original STtx tickets = append(tickets, stx.MsgTx().TxIn[1].PreviousOutPoint.Hash) } } return tickets }
go
func TicketsSpentInBlock(bl *dcrutil.Block) []chainhash.Hash { tickets := make([]chainhash.Hash, 0) for _, stx := range bl.STransactions() { if stake.DetermineTxType(stx.MsgTx()) == stake.TxTypeSSGen { // Hash of the original STtx tickets = append(tickets, stx.MsgTx().TxIn[1].PreviousOutPoint.Hash) } } return tickets }
[ "func", "TicketsSpentInBlock", "(", "bl", "*", "dcrutil", ".", "Block", ")", "[", "]", "chainhash", ".", "Hash", "{", "tickets", ":=", "make", "(", "[", "]", "chainhash", ".", "Hash", ",", "0", ")", "\n", "for", "_", ",", "stx", ":=", "range", "bl", ".", "STransactions", "(", ")", "{", "if", "stake", ".", "DetermineTxType", "(", "stx", ".", "MsgTx", "(", ")", ")", "==", "stake", ".", "TxTypeSSGen", "{", "// Hash of the original STtx", "tickets", "=", "append", "(", "tickets", ",", "stx", ".", "MsgTx", "(", ")", ".", "TxIn", "[", "1", "]", ".", "PreviousOutPoint", ".", "Hash", ")", "\n", "}", "\n", "}", "\n\n", "return", "tickets", "\n", "}" ]
// TicketsSpentInBlock finds all the tickets spent in the block.
[ "TicketsSpentInBlock", "finds", "all", "the", "tickets", "spent", "in", "the", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/staketree.go#L176-L186
train
decred/dcrdata
txhelpers/staketree.go
VotesInBlock
func VotesInBlock(bl *dcrutil.Block) []chainhash.Hash { votes := make([]chainhash.Hash, 0) for _, stx := range bl.STransactions() { if stake.DetermineTxType(stx.MsgTx()) == stake.TxTypeSSGen { h := stx.Hash() votes = append(votes, *h) } } return votes }
go
func VotesInBlock(bl *dcrutil.Block) []chainhash.Hash { votes := make([]chainhash.Hash, 0) for _, stx := range bl.STransactions() { if stake.DetermineTxType(stx.MsgTx()) == stake.TxTypeSSGen { h := stx.Hash() votes = append(votes, *h) } } return votes }
[ "func", "VotesInBlock", "(", "bl", "*", "dcrutil", ".", "Block", ")", "[", "]", "chainhash", ".", "Hash", "{", "votes", ":=", "make", "(", "[", "]", "chainhash", ".", "Hash", ",", "0", ")", "\n", "for", "_", ",", "stx", ":=", "range", "bl", ".", "STransactions", "(", ")", "{", "if", "stake", ".", "DetermineTxType", "(", "stx", ".", "MsgTx", "(", ")", ")", "==", "stake", ".", "TxTypeSSGen", "{", "h", ":=", "stx", ".", "Hash", "(", ")", "\n", "votes", "=", "append", "(", "votes", ",", "*", "h", ")", "\n", "}", "\n", "}", "\n\n", "return", "votes", "\n", "}" ]
// VotesInBlock finds all the votes in the block.
[ "VotesInBlock", "finds", "all", "the", "votes", "in", "the", "block", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/staketree.go#L189-L199
train
decred/dcrdata
pubsub/democlient/main.go
AnotInB
func AnotInB(sA []string, sB []string) (AnotB []string) { for _, s := range sA { if found, _ := strInSlice(sB, s); found { continue } AnotB = append(AnotB, s) } return }
go
func AnotInB(sA []string, sB []string) (AnotB []string) { for _, s := range sA { if found, _ := strInSlice(sB, s); found { continue } AnotB = append(AnotB, s) } return }
[ "func", "AnotInB", "(", "sA", "[", "]", "string", ",", "sB", "[", "]", "string", ")", "(", "AnotB", "[", "]", "string", ")", "{", "for", "_", ",", "s", ":=", "range", "sA", "{", "if", "found", ",", "_", ":=", "strInSlice", "(", "sB", ",", "s", ")", ";", "found", "{", "continue", "\n", "}", "\n", "AnotB", "=", "append", "(", "AnotB", ",", "s", ")", "\n", "}", "\n", "return", "\n", "}" ]
// AnotInB returns strings in the slice sA that are not in slice sB.
[ "AnotInB", "returns", "strings", "in", "the", "slice", "sA", "that", "are", "not", "in", "slice", "sB", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/democlient/main.go#L237-L245
train
decred/dcrdata
db/dcrsqlite/sync.go
RewindStakeDB
func (db *WiredDB) RewindStakeDB(ctx context.Context, toHeight int64, quiet ...bool) (stakeDBHeight int64, err error) { // Target height must be non-negative. It is not possible to disconnect the // genesis block. if toHeight < 0 { toHeight = 0 } // Periodically log progress unless quiet[0]==true showProgress := true if len(quiet) > 0 { showProgress = !quiet[0] } // Disconnect blocks until the stake database reaches the target height. stakeDBHeight = int64(db.sDB.Height()) startHeight := stakeDBHeight pStep := int64(1000) for stakeDBHeight > toHeight { // Log rewind progress at regular intervals. if stakeDBHeight == startHeight || stakeDBHeight%pStep == 0 { endSegment := pStep * ((stakeDBHeight - 1) / pStep) if endSegment < toHeight { endSegment = toHeight } if showProgress { log.Infof("Rewinding from %d to %d", stakeDBHeight, endSegment) } } // Check for quit signal. select { case <-ctx.Done(): log.Infof("Rewind cancelled at height %d.", stakeDBHeight) return default: } // Disconect the best block. if err = db.sDB.DisconnectBlock(false); err != nil { return } stakeDBHeight = int64(db.sDB.Height()) log.Tracef("Stake db now at height %d.", stakeDBHeight) } return }
go
func (db *WiredDB) RewindStakeDB(ctx context.Context, toHeight int64, quiet ...bool) (stakeDBHeight int64, err error) { // Target height must be non-negative. It is not possible to disconnect the // genesis block. if toHeight < 0 { toHeight = 0 } // Periodically log progress unless quiet[0]==true showProgress := true if len(quiet) > 0 { showProgress = !quiet[0] } // Disconnect blocks until the stake database reaches the target height. stakeDBHeight = int64(db.sDB.Height()) startHeight := stakeDBHeight pStep := int64(1000) for stakeDBHeight > toHeight { // Log rewind progress at regular intervals. if stakeDBHeight == startHeight || stakeDBHeight%pStep == 0 { endSegment := pStep * ((stakeDBHeight - 1) / pStep) if endSegment < toHeight { endSegment = toHeight } if showProgress { log.Infof("Rewinding from %d to %d", stakeDBHeight, endSegment) } } // Check for quit signal. select { case <-ctx.Done(): log.Infof("Rewind cancelled at height %d.", stakeDBHeight) return default: } // Disconect the best block. if err = db.sDB.DisconnectBlock(false); err != nil { return } stakeDBHeight = int64(db.sDB.Height()) log.Tracef("Stake db now at height %d.", stakeDBHeight) } return }
[ "func", "(", "db", "*", "WiredDB", ")", "RewindStakeDB", "(", "ctx", "context", ".", "Context", ",", "toHeight", "int64", ",", "quiet", "...", "bool", ")", "(", "stakeDBHeight", "int64", ",", "err", "error", ")", "{", "// Target height must be non-negative. It is not possible to disconnect the", "// genesis block.", "if", "toHeight", "<", "0", "{", "toHeight", "=", "0", "\n", "}", "\n\n", "// Periodically log progress unless quiet[0]==true", "showProgress", ":=", "true", "\n", "if", "len", "(", "quiet", ")", ">", "0", "{", "showProgress", "=", "!", "quiet", "[", "0", "]", "\n", "}", "\n\n", "// Disconnect blocks until the stake database reaches the target height.", "stakeDBHeight", "=", "int64", "(", "db", ".", "sDB", ".", "Height", "(", ")", ")", "\n", "startHeight", ":=", "stakeDBHeight", "\n", "pStep", ":=", "int64", "(", "1000", ")", "\n", "for", "stakeDBHeight", ">", "toHeight", "{", "// Log rewind progress at regular intervals.", "if", "stakeDBHeight", "==", "startHeight", "||", "stakeDBHeight", "%", "pStep", "==", "0", "{", "endSegment", ":=", "pStep", "*", "(", "(", "stakeDBHeight", "-", "1", ")", "/", "pStep", ")", "\n", "if", "endSegment", "<", "toHeight", "{", "endSegment", "=", "toHeight", "\n", "}", "\n", "if", "showProgress", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "stakeDBHeight", ",", "endSegment", ")", "\n", "}", "\n", "}", "\n\n", "// Check for quit signal.", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "log", ".", "Infof", "(", "\"", "\"", ",", "stakeDBHeight", ")", "\n", "return", "\n", "default", ":", "}", "\n\n", "// Disconect the best block.", "if", "err", "=", "db", ".", "sDB", ".", "DisconnectBlock", "(", "false", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "stakeDBHeight", "=", "int64", "(", "db", ".", "sDB", ".", "Height", "(", ")", ")", "\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "stakeDBHeight", ")", "\n", "}", "\n", "return", "\n", "}" ]
// RewindStakeDB attempts to disconnect blocks from the stake database to reach // the specified height. A channel must be provided for signaling if the rewind // should abort. If the specified height is greater than the current stake DB // height, RewindStakeDB will exit without error, returning the current stake DB // height and a nil error.
[ "RewindStakeDB", "attempts", "to", "disconnect", "blocks", "from", "the", "stake", "database", "to", "reach", "the", "specified", "height", ".", "A", "channel", "must", "be", "provided", "for", "signaling", "if", "the", "rewind", "should", "abort", ".", "If", "the", "specified", "height", "is", "greater", "than", "the", "current", "stake", "DB", "height", "RewindStakeDB", "will", "exit", "without", "error", "returning", "the", "current", "stake", "DB", "height", "and", "a", "nil", "error", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sync.go#L103-L148
train
decred/dcrdata
db/dcrsqlite/sync.go
ImportSideChains
func (db *WiredDB) ImportSideChains(collector *blockdata.Collector) error { tips, err := rpcutils.SideChains(db.client) if err != nil { return err } var hashlist []*chainhash.Hash for it := range tips { log.Tracef("Primary DB -> Getting base DB side chain with tip %s at %d.", tips[it].Hash, tips[it].Height) sideChain, err := rpcutils.SideChainFull(db.client, tips[it].Hash) if err != nil { log.Errorf("Primary DB -> Unable to get side chain blocks for chain tip %s: %v", tips[it].Hash, err) return err } // For each block in the side chain, check if it already stored. for is := range sideChain { // Check for the block hash in the DB. isMainchainNow, err := db.getMainchainStatus(sideChain[is]) if isMainchainNow || err == sql.ErrNoRows { blockhash, err := chainhash.NewHashFromStr(sideChain[is]) if err != nil { log.Errorf("Primary DB -> Invalid block hash %s: %v.", blockhash, err) continue } hashlist = append(hashlist, blockhash) } } } log.Infof("Primary DB -> %d new sidechain block(s) to import", len(hashlist)) for _, blockhash := range hashlist { // Collect block data. blockDataBasic, _ := collector.CollectAPITypes(blockhash) log.Debugf("Primary DB -> Importing block %s (height %d) into primary DB.", blockhash.String(), blockDataBasic.Height) if blockDataBasic == nil { // Do not quit if unable to collect side chain block data. log.Error("Primary DB -> Unable to collect data for side chain block %s", blockhash.String()) continue } err := db.StoreSideBlockSummary(blockDataBasic) if err != nil { log.Errorf("Primary DB -> Failed to store block %s", blockhash.String()) } } return nil }
go
func (db *WiredDB) ImportSideChains(collector *blockdata.Collector) error { tips, err := rpcutils.SideChains(db.client) if err != nil { return err } var hashlist []*chainhash.Hash for it := range tips { log.Tracef("Primary DB -> Getting base DB side chain with tip %s at %d.", tips[it].Hash, tips[it].Height) sideChain, err := rpcutils.SideChainFull(db.client, tips[it].Hash) if err != nil { log.Errorf("Primary DB -> Unable to get side chain blocks for chain tip %s: %v", tips[it].Hash, err) return err } // For each block in the side chain, check if it already stored. for is := range sideChain { // Check for the block hash in the DB. isMainchainNow, err := db.getMainchainStatus(sideChain[is]) if isMainchainNow || err == sql.ErrNoRows { blockhash, err := chainhash.NewHashFromStr(sideChain[is]) if err != nil { log.Errorf("Primary DB -> Invalid block hash %s: %v.", blockhash, err) continue } hashlist = append(hashlist, blockhash) } } } log.Infof("Primary DB -> %d new sidechain block(s) to import", len(hashlist)) for _, blockhash := range hashlist { // Collect block data. blockDataBasic, _ := collector.CollectAPITypes(blockhash) log.Debugf("Primary DB -> Importing block %s (height %d) into primary DB.", blockhash.String(), blockDataBasic.Height) if blockDataBasic == nil { // Do not quit if unable to collect side chain block data. log.Error("Primary DB -> Unable to collect data for side chain block %s", blockhash.String()) continue } err := db.StoreSideBlockSummary(blockDataBasic) if err != nil { log.Errorf("Primary DB -> Failed to store block %s", blockhash.String()) } } return nil }
[ "func", "(", "db", "*", "WiredDB", ")", "ImportSideChains", "(", "collector", "*", "blockdata", ".", "Collector", ")", "error", "{", "tips", ",", "err", ":=", "rpcutils", ".", "SideChains", "(", "db", ".", "client", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "hashlist", "[", "]", "*", "chainhash", ".", "Hash", "\n", "for", "it", ":=", "range", "tips", "{", "log", ".", "Tracef", "(", "\"", "\"", ",", "tips", "[", "it", "]", ".", "Hash", ",", "tips", "[", "it", "]", ".", "Height", ")", "\n", "sideChain", ",", "err", ":=", "rpcutils", ".", "SideChainFull", "(", "db", ".", "client", ",", "tips", "[", "it", "]", ".", "Hash", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "tips", "[", "it", "]", ".", "Hash", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "// For each block in the side chain, check if it already stored.", "for", "is", ":=", "range", "sideChain", "{", "// Check for the block hash in the DB.", "isMainchainNow", ",", "err", ":=", "db", ".", "getMainchainStatus", "(", "sideChain", "[", "is", "]", ")", "\n", "if", "isMainchainNow", "||", "err", "==", "sql", ".", "ErrNoRows", "{", "blockhash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "sideChain", "[", "is", "]", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "blockhash", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "hashlist", "=", "append", "(", "hashlist", ",", "blockhash", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "len", "(", "hashlist", ")", ")", "\n", "for", "_", ",", "blockhash", ":=", "range", "hashlist", "{", "// Collect block data.", "blockDataBasic", ",", "_", ":=", "collector", ".", "CollectAPITypes", "(", "blockhash", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "blockhash", ".", "String", "(", ")", ",", "blockDataBasic", ".", "Height", ")", "\n", "if", "blockDataBasic", "==", "nil", "{", "// Do not quit if unable to collect side chain block data.", "log", ".", "Error", "(", "\"", "\"", ",", "blockhash", ".", "String", "(", ")", ")", "\n", "continue", "\n", "}", "\n", "err", ":=", "db", ".", "StoreSideBlockSummary", "(", "blockDataBasic", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "blockhash", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ImportSideChains imports all side chains. Similar to pgblockchain.MissingSideChainBlocks // plus the rest from main.go
[ "ImportSideChains", "imports", "all", "side", "chains", ".", "Similar", "to", "pgblockchain", ".", "MissingSideChainBlocks", "plus", "the", "rest", "from", "main", ".", "go" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrsqlite/sync.go#L452-L497
train
decred/dcrdata
gov/agendas/deployments.go
NewAgendasDB
func NewAgendasDB(client DeploymentSource, dbPath string) (*AgendaDB, error) { if dbPath == "" { return nil, fmt.Errorf("empty db Path found") } if client == DeploymentSource(nil) { return nil, fmt.Errorf("invalid deployment source found") } _, err := os.Stat(dbPath) if err != nil && !os.IsNotExist(err) { return nil, err } db, err := storm.Open(dbPath) if err != nil { return nil, err } // Checks if the correct db version has been set. var version string err = db.Get(dbinfo, "version", &version) if err != nil && err != storm.ErrNotFound { return nil, err } // Check if the versions match. if version != dbVersion.String() { // Attempt to delete AgendaTagged bucket. if err = db.Drop(&AgendaTagged{}); err != nil { // If error due bucket not found was returned ignore it. if !strings.Contains(err.Error(), "not found") { return nil, fmt.Errorf("delete bucket struct failed: %v", err) } } // Set the required db version. err = db.Set(dbinfo, "version", dbVersion.String()) if err != nil { return nil, err } log.Infof("agendas.db version %v was set", dbVersion) } return &AgendaDB{sdb: db, rpcClient: client}, nil }
go
func NewAgendasDB(client DeploymentSource, dbPath string) (*AgendaDB, error) { if dbPath == "" { return nil, fmt.Errorf("empty db Path found") } if client == DeploymentSource(nil) { return nil, fmt.Errorf("invalid deployment source found") } _, err := os.Stat(dbPath) if err != nil && !os.IsNotExist(err) { return nil, err } db, err := storm.Open(dbPath) if err != nil { return nil, err } // Checks if the correct db version has been set. var version string err = db.Get(dbinfo, "version", &version) if err != nil && err != storm.ErrNotFound { return nil, err } // Check if the versions match. if version != dbVersion.String() { // Attempt to delete AgendaTagged bucket. if err = db.Drop(&AgendaTagged{}); err != nil { // If error due bucket not found was returned ignore it. if !strings.Contains(err.Error(), "not found") { return nil, fmt.Errorf("delete bucket struct failed: %v", err) } } // Set the required db version. err = db.Set(dbinfo, "version", dbVersion.String()) if err != nil { return nil, err } log.Infof("agendas.db version %v was set", dbVersion) } return &AgendaDB{sdb: db, rpcClient: client}, nil }
[ "func", "NewAgendasDB", "(", "client", "DeploymentSource", ",", "dbPath", "string", ")", "(", "*", "AgendaDB", ",", "error", ")", "{", "if", "dbPath", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "client", "==", "DeploymentSource", "(", "nil", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "_", ",", "err", ":=", "os", ".", "Stat", "(", "dbPath", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "db", ",", "err", ":=", "storm", ".", "Open", "(", "dbPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Checks if the correct db version has been set.", "var", "version", "string", "\n", "err", "=", "db", ".", "Get", "(", "dbinfo", ",", "\"", "\"", ",", "&", "version", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "storm", ".", "ErrNotFound", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Check if the versions match.", "if", "version", "!=", "dbVersion", ".", "String", "(", ")", "{", "// Attempt to delete AgendaTagged bucket.", "if", "err", "=", "db", ".", "Drop", "(", "&", "AgendaTagged", "{", "}", ")", ";", "err", "!=", "nil", "{", "// If error due bucket not found was returned ignore it.", "if", "!", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Set the required db version.", "err", "=", "db", ".", "Set", "(", "dbinfo", ",", "\"", "\"", ",", "dbVersion", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "dbVersion", ")", "\n", "}", "\n\n", "return", "&", "AgendaDB", "{", "sdb", ":", "db", ",", "rpcClient", ":", "client", "}", ",", "nil", "\n", "}" ]
// NewAgendasDB opens an existing database or create a new one using with the // specified file name. An initialized agendas db connection is returned. // It also checks the db version, Reindexes the db if need be and sets the // required db version.
[ "NewAgendasDB", "opens", "an", "existing", "database", "or", "create", "a", "new", "one", "using", "with", "the", "specified", "file", "name", ".", "An", "initialized", "agendas", "db", "connection", "is", "returned", ".", "It", "also", "checks", "the", "db", "version", "Reindexes", "the", "db", "if", "need", "be", "and", "sets", "the", "required", "db", "version", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/deployments.go#L66-L111
train
decred/dcrdata
gov/agendas/deployments.go
countProperties
func (db *AgendaDB) countProperties() error { numAgendas, err := db.sdb.Count(&AgendaTagged{}) if err != nil { log.Errorf("Agendas count failed: %v\n", err) return err } db.NumAgendas = numAgendas return nil }
go
func (db *AgendaDB) countProperties() error { numAgendas, err := db.sdb.Count(&AgendaTagged{}) if err != nil { log.Errorf("Agendas count failed: %v\n", err) return err } db.NumAgendas = numAgendas return nil }
[ "func", "(", "db", "*", "AgendaDB", ")", "countProperties", "(", ")", "error", "{", "numAgendas", ",", "err", ":=", "db", ".", "sdb", ".", "Count", "(", "&", "AgendaTagged", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "db", ".", "NumAgendas", "=", "numAgendas", "\n", "return", "nil", "\n", "}" ]
// countProperties fetches the Agendas count and appends it to the AgendaDB // receiver.
[ "countProperties", "fetches", "the", "Agendas", "count", "and", "appends", "it", "to", "the", "AgendaDB", "receiver", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/deployments.go#L115-L124
train
decred/dcrdata
gov/agendas/deployments.go
Close
func (db *AgendaDB) Close() error { if db == nil || db.sdb == nil { return nil } return db.sdb.Close() }
go
func (db *AgendaDB) Close() error { if db == nil || db.sdb == nil { return nil } return db.sdb.Close() }
[ "func", "(", "db", "*", "AgendaDB", ")", "Close", "(", ")", "error", "{", "if", "db", "==", "nil", "||", "db", ".", "sdb", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "db", ".", "sdb", ".", "Close", "(", ")", "\n", "}" ]
// Close should be called when you are done with the AgendaDB to close the // underlying database.
[ "Close", "should", "be", "called", "when", "you", "are", "done", "with", "the", "AgendaDB", "to", "close", "the", "underlying", "database", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/deployments.go#L128-L133
train
decred/dcrdata
gov/agendas/deployments.go
loadAgenda
func (db *AgendaDB) loadAgenda(agendaID string) (*AgendaTagged, error) { agenda := new(AgendaTagged) if err := db.sdb.One("ID", agendaID, agenda); err != nil { return nil, err } return agenda, nil }
go
func (db *AgendaDB) loadAgenda(agendaID string) (*AgendaTagged, error) { agenda := new(AgendaTagged) if err := db.sdb.One("ID", agendaID, agenda); err != nil { return nil, err } return agenda, nil }
[ "func", "(", "db", "*", "AgendaDB", ")", "loadAgenda", "(", "agendaID", "string", ")", "(", "*", "AgendaTagged", ",", "error", ")", "{", "agenda", ":=", "new", "(", "AgendaTagged", ")", "\n", "if", "err", ":=", "db", ".", "sdb", ".", "One", "(", "\"", "\"", ",", "agendaID", ",", "agenda", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "agenda", ",", "nil", "\n", "}" ]
// loadAgenda retrieves an agenda corresponding to the specified unique agenda // ID, or returns nil if it does not exist.
[ "loadAgenda", "retrieves", "an", "agenda", "corresponding", "to", "the", "specified", "unique", "agenda", "ID", "or", "returns", "nil", "if", "it", "does", "not", "exist", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/deployments.go#L137-L144
train
decred/dcrdata
gov/agendas/deployments.go
agendasForVoteVersion
func agendasForVoteVersion(ver uint32, client DeploymentSource) ([]AgendaTagged, error) { voteInfo, err := client.GetVoteInfo(ver) if err != nil { return nil, err } // Set the agendas slice capacity. agendas := make([]AgendaTagged, 0, len(voteInfo.Agendas)) for i := range voteInfo.Agendas { v := &voteInfo.Agendas[i] agendas = append(agendas, AgendaTagged{ ID: v.ID, Description: v.Description, Mask: v.Mask, StartTime: v.StartTime, ExpireTime: v.ExpireTime, Status: dbtypes.AgendaStatusFromStr(v.Status), QuorumProgress: v.QuorumProgress, Choices: v.Choices, VoteVersion: voteInfo.VoteVersion, }) } return agendas, nil }
go
func agendasForVoteVersion(ver uint32, client DeploymentSource) ([]AgendaTagged, error) { voteInfo, err := client.GetVoteInfo(ver) if err != nil { return nil, err } // Set the agendas slice capacity. agendas := make([]AgendaTagged, 0, len(voteInfo.Agendas)) for i := range voteInfo.Agendas { v := &voteInfo.Agendas[i] agendas = append(agendas, AgendaTagged{ ID: v.ID, Description: v.Description, Mask: v.Mask, StartTime: v.StartTime, ExpireTime: v.ExpireTime, Status: dbtypes.AgendaStatusFromStr(v.Status), QuorumProgress: v.QuorumProgress, Choices: v.Choices, VoteVersion: voteInfo.VoteVersion, }) } return agendas, nil }
[ "func", "agendasForVoteVersion", "(", "ver", "uint32", ",", "client", "DeploymentSource", ")", "(", "[", "]", "AgendaTagged", ",", "error", ")", "{", "voteInfo", ",", "err", ":=", "client", ".", "GetVoteInfo", "(", "ver", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Set the agendas slice capacity.", "agendas", ":=", "make", "(", "[", "]", "AgendaTagged", ",", "0", ",", "len", "(", "voteInfo", ".", "Agendas", ")", ")", "\n", "for", "i", ":=", "range", "voteInfo", ".", "Agendas", "{", "v", ":=", "&", "voteInfo", ".", "Agendas", "[", "i", "]", "\n", "agendas", "=", "append", "(", "agendas", ",", "AgendaTagged", "{", "ID", ":", "v", ".", "ID", ",", "Description", ":", "v", ".", "Description", ",", "Mask", ":", "v", ".", "Mask", ",", "StartTime", ":", "v", ".", "StartTime", ",", "ExpireTime", ":", "v", ".", "ExpireTime", ",", "Status", ":", "dbtypes", ".", "AgendaStatusFromStr", "(", "v", ".", "Status", ")", ",", "QuorumProgress", ":", "v", ".", "QuorumProgress", ",", "Choices", ":", "v", ".", "Choices", ",", "VoteVersion", ":", "voteInfo", ".", "VoteVersion", ",", "}", ")", "\n", "}", "\n\n", "return", "agendas", ",", "nil", "\n", "}" ]
// agendasForVoteVersion fetches the agendas using the vote versions provided.
[ "agendasForVoteVersion", "fetches", "the", "agendas", "using", "the", "vote", "versions", "provided", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/deployments.go#L147-L171
train
decred/dcrdata
gov/agendas/deployments.go
updatedb
func (db *AgendaDB) updatedb(activeVersions map[uint32][]chaincfg.ConsensusDeployment) (int, error) { var agendas []AgendaTagged for voteVersion := range activeVersions { taggedAgendas, err := agendasForVoteVersion(voteVersion, db.rpcClient) if err != nil || len(taggedAgendas) == 0 { return -1, fmt.Errorf("vote version %d agendas retrieval failed: %v", voteVersion, err) } agendas = append(agendas, taggedAgendas...) } for i := range agendas { agenda := &agendas[i] err := db.storeAgenda(agenda) if err != nil { return -1, fmt.Errorf("agenda '%s' was not saved: %v", agenda.Description, err) } } return len(agendas), nil }
go
func (db *AgendaDB) updatedb(activeVersions map[uint32][]chaincfg.ConsensusDeployment) (int, error) { var agendas []AgendaTagged for voteVersion := range activeVersions { taggedAgendas, err := agendasForVoteVersion(voteVersion, db.rpcClient) if err != nil || len(taggedAgendas) == 0 { return -1, fmt.Errorf("vote version %d agendas retrieval failed: %v", voteVersion, err) } agendas = append(agendas, taggedAgendas...) } for i := range agendas { agenda := &agendas[i] err := db.storeAgenda(agenda) if err != nil { return -1, fmt.Errorf("agenda '%s' was not saved: %v", agenda.Description, err) } } return len(agendas), nil }
[ "func", "(", "db", "*", "AgendaDB", ")", "updatedb", "(", "activeVersions", "map", "[", "uint32", "]", "[", "]", "chaincfg", ".", "ConsensusDeployment", ")", "(", "int", ",", "error", ")", "{", "var", "agendas", "[", "]", "AgendaTagged", "\n", "for", "voteVersion", ":=", "range", "activeVersions", "{", "taggedAgendas", ",", "err", ":=", "agendasForVoteVersion", "(", "voteVersion", ",", "db", ".", "rpcClient", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "taggedAgendas", ")", "==", "0", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "voteVersion", ",", "err", ")", "\n", "}", "\n\n", "agendas", "=", "append", "(", "agendas", ",", "taggedAgendas", "...", ")", "\n", "}", "\n\n", "for", "i", ":=", "range", "agendas", "{", "agenda", ":=", "&", "agendas", "[", "i", "]", "\n", "err", ":=", "db", ".", "storeAgenda", "(", "agenda", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "agenda", ".", "Description", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "len", "(", "agendas", ")", ",", "nil", "\n", "}" ]
// updatedb checks if vote versions available in chaincfg.ConsensusDeployment // are already updated in the agendas db, if not yet their data is updated. // dcrjson.GetVoteInfoResult and chaincfg.ConsensusDeployment hold almost similar // data contents but chaincfg.Vote does not contain the important vote status // field that is found in dcrjson.Agenda.
[ "updatedb", "checks", "if", "vote", "versions", "available", "in", "chaincfg", ".", "ConsensusDeployment", "are", "already", "updated", "in", "the", "agendas", "db", "if", "not", "yet", "their", "data", "is", "updated", ".", "dcrjson", ".", "GetVoteInfoResult", "and", "chaincfg", ".", "ConsensusDeployment", "hold", "almost", "similar", "data", "contents", "but", "chaincfg", ".", "Vote", "does", "not", "contain", "the", "important", "vote", "status", "field", "that", "is", "found", "in", "dcrjson", ".", "Agenda", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/deployments.go#L178-L200
train
decred/dcrdata
gov/agendas/deployments.go
storeAgenda
func (db *AgendaDB) storeAgenda(agenda *AgendaTagged) error { return db.sdb.Save(agenda) }
go
func (db *AgendaDB) storeAgenda(agenda *AgendaTagged) error { return db.sdb.Save(agenda) }
[ "func", "(", "db", "*", "AgendaDB", ")", "storeAgenda", "(", "agenda", "*", "AgendaTagged", ")", "error", "{", "return", "db", ".", "sdb", ".", "Save", "(", "agenda", ")", "\n", "}" ]
// storeAgenda saves an agenda in the database.
[ "storeAgenda", "saves", "an", "agenda", "in", "the", "database", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/deployments.go#L203-L205
train
decred/dcrdata
gov/agendas/deployments.go
CheckAgendasUpdates
func (db *AgendaDB) CheckAgendasUpdates(activeVersions map[uint32][]chaincfg.ConsensusDeployment) error { if db == nil || db.sdb == nil { return errDefault } if len(activeVersions) == 0 { return nil } numRecords, err := db.updatedb(activeVersions) if err != nil { return fmt.Errorf("agendas.CheckAgendasUpdates failed: %v", err) } log.Infof("%d agenda records (agendas) were updated", numRecords) return db.countProperties() }
go
func (db *AgendaDB) CheckAgendasUpdates(activeVersions map[uint32][]chaincfg.ConsensusDeployment) error { if db == nil || db.sdb == nil { return errDefault } if len(activeVersions) == 0 { return nil } numRecords, err := db.updatedb(activeVersions) if err != nil { return fmt.Errorf("agendas.CheckAgendasUpdates failed: %v", err) } log.Infof("%d agenda records (agendas) were updated", numRecords) return db.countProperties() }
[ "func", "(", "db", "*", "AgendaDB", ")", "CheckAgendasUpdates", "(", "activeVersions", "map", "[", "uint32", "]", "[", "]", "chaincfg", ".", "ConsensusDeployment", ")", "error", "{", "if", "db", "==", "nil", "||", "db", ".", "sdb", "==", "nil", "{", "return", "errDefault", "\n", "}", "\n\n", "if", "len", "(", "activeVersions", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "numRecords", ",", "err", ":=", "db", ".", "updatedb", "(", "activeVersions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "numRecords", ")", "\n\n", "return", "db", ".", "countProperties", "(", ")", "\n", "}" ]
// CheckAgendasUpdates checks for update at the start of the process and will // proceed to update when necessary.
[ "CheckAgendasUpdates", "checks", "for", "update", "at", "the", "start", "of", "the", "process", "and", "will", "proceed", "to", "update", "when", "necessary", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/deployments.go#L209-L226
train
decred/dcrdata
gov/agendas/deployments.go
AgendaInfo
func (db *AgendaDB) AgendaInfo(agendaID string) (*AgendaTagged, error) { if db == nil || db.sdb == nil { return nil, errDefault } agenda, err := db.loadAgenda(agendaID) if err != nil { return nil, err } return agenda, nil }
go
func (db *AgendaDB) AgendaInfo(agendaID string) (*AgendaTagged, error) { if db == nil || db.sdb == nil { return nil, errDefault } agenda, err := db.loadAgenda(agendaID) if err != nil { return nil, err } return agenda, nil }
[ "func", "(", "db", "*", "AgendaDB", ")", "AgendaInfo", "(", "agendaID", "string", ")", "(", "*", "AgendaTagged", ",", "error", ")", "{", "if", "db", "==", "nil", "||", "db", ".", "sdb", "==", "nil", "{", "return", "nil", ",", "errDefault", "\n", "}", "\n\n", "agenda", ",", "err", ":=", "db", ".", "loadAgenda", "(", "agendaID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "agenda", ",", "nil", "\n", "}" ]
// AgendaInfo fetches an agenda's details given it's agendaID.
[ "AgendaInfo", "fetches", "an", "agenda", "s", "details", "given", "it", "s", "agendaID", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/deployments.go#L229-L240
train
decred/dcrdata
gov/agendas/deployments.go
AllAgendas
func (db *AgendaDB) AllAgendas() (agendas []*AgendaTagged, err error) { if db == nil || db.sdb == nil { return nil, errDefault } err = db.sdb.All(&agendas) if err != nil { log.Errorf("Failed to fetch data from Agendas DB: %v", err) } return }
go
func (db *AgendaDB) AllAgendas() (agendas []*AgendaTagged, err error) { if db == nil || db.sdb == nil { return nil, errDefault } err = db.sdb.All(&agendas) if err != nil { log.Errorf("Failed to fetch data from Agendas DB: %v", err) } return }
[ "func", "(", "db", "*", "AgendaDB", ")", "AllAgendas", "(", ")", "(", "agendas", "[", "]", "*", "AgendaTagged", ",", "err", "error", ")", "{", "if", "db", "==", "nil", "||", "db", ".", "sdb", "==", "nil", "{", "return", "nil", ",", "errDefault", "\n", "}", "\n\n", "err", "=", "db", ".", "sdb", ".", "All", "(", "&", "agendas", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}" ]
// AllAgendas returns all agendas and their info in the db.
[ "AllAgendas", "returns", "all", "agendas", "and", "their", "info", "in", "the", "db", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/deployments.go#L243-L253
train
decred/dcrdata
db/dbtypes/extraction.go
DevSubsidyAddress
func DevSubsidyAddress(params *chaincfg.Params) (string, error) { var devSubsidyAddress string var err error switch params.Name { case "testnet2": // TestNet2 uses an invalid organization PkScript devSubsidyAddress = "TccTkqj8wFqrUemmHMRSx8SYEueQYLmuuFk" err = fmt.Errorf("testnet2 has invalid project fund script") default: _, devSubsidyAddresses, _, err0 := txscript.ExtractPkScriptAddrs( params.OrganizationPkScriptVersion, params.OrganizationPkScript, params) if err0 != nil || len(devSubsidyAddresses) != 1 { err = fmt.Errorf("failed to decode dev subsidy address: %v", err0) } else { devSubsidyAddress = devSubsidyAddresses[0].String() } } return devSubsidyAddress, err }
go
func DevSubsidyAddress(params *chaincfg.Params) (string, error) { var devSubsidyAddress string var err error switch params.Name { case "testnet2": // TestNet2 uses an invalid organization PkScript devSubsidyAddress = "TccTkqj8wFqrUemmHMRSx8SYEueQYLmuuFk" err = fmt.Errorf("testnet2 has invalid project fund script") default: _, devSubsidyAddresses, _, err0 := txscript.ExtractPkScriptAddrs( params.OrganizationPkScriptVersion, params.OrganizationPkScript, params) if err0 != nil || len(devSubsidyAddresses) != 1 { err = fmt.Errorf("failed to decode dev subsidy address: %v", err0) } else { devSubsidyAddress = devSubsidyAddresses[0].String() } } return devSubsidyAddress, err }
[ "func", "DevSubsidyAddress", "(", "params", "*", "chaincfg", ".", "Params", ")", "(", "string", ",", "error", ")", "{", "var", "devSubsidyAddress", "string", "\n", "var", "err", "error", "\n", "switch", "params", ".", "Name", "{", "case", "\"", "\"", ":", "// TestNet2 uses an invalid organization PkScript", "devSubsidyAddress", "=", "\"", "\"", "\n", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "default", ":", "_", ",", "devSubsidyAddresses", ",", "_", ",", "err0", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "params", ".", "OrganizationPkScriptVersion", ",", "params", ".", "OrganizationPkScript", ",", "params", ")", "\n", "if", "err0", "!=", "nil", "||", "len", "(", "devSubsidyAddresses", ")", "!=", "1", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err0", ")", "\n", "}", "else", "{", "devSubsidyAddress", "=", "devSubsidyAddresses", "[", "0", "]", ".", "String", "(", ")", "\n", "}", "\n", "}", "\n", "return", "devSubsidyAddress", ",", "err", "\n", "}" ]
// DevSubsidyAddress returns the development subsidy address for the specified // network.
[ "DevSubsidyAddress", "returns", "the", "development", "subsidy", "address", "for", "the", "specified", "network", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/extraction.go#L17-L35
train
decred/dcrdata
db/dbtypes/extraction.go
ExtractBlockTransactions
func ExtractBlockTransactions(msgBlock *wire.MsgBlock, txTree int8, chainParams *chaincfg.Params, isValid, isMainchain bool) ([]*Tx, [][]*Vout, []VinTxPropertyARRAY) { dbTxs, dbTxVouts, dbTxVins := processTransactions(msgBlock, txTree, chainParams, isValid, isMainchain) if txTree != wire.TxTreeRegular && txTree != wire.TxTreeStake { fmt.Printf("Invalid transaction tree: %v", txTree) } return dbTxs, dbTxVouts, dbTxVins }
go
func ExtractBlockTransactions(msgBlock *wire.MsgBlock, txTree int8, chainParams *chaincfg.Params, isValid, isMainchain bool) ([]*Tx, [][]*Vout, []VinTxPropertyARRAY) { dbTxs, dbTxVouts, dbTxVins := processTransactions(msgBlock, txTree, chainParams, isValid, isMainchain) if txTree != wire.TxTreeRegular && txTree != wire.TxTreeStake { fmt.Printf("Invalid transaction tree: %v", txTree) } return dbTxs, dbTxVouts, dbTxVins }
[ "func", "ExtractBlockTransactions", "(", "msgBlock", "*", "wire", ".", "MsgBlock", ",", "txTree", "int8", ",", "chainParams", "*", "chaincfg", ".", "Params", ",", "isValid", ",", "isMainchain", "bool", ")", "(", "[", "]", "*", "Tx", ",", "[", "]", "[", "]", "*", "Vout", ",", "[", "]", "VinTxPropertyARRAY", ")", "{", "dbTxs", ",", "dbTxVouts", ",", "dbTxVins", ":=", "processTransactions", "(", "msgBlock", ",", "txTree", ",", "chainParams", ",", "isValid", ",", "isMainchain", ")", "\n", "if", "txTree", "!=", "wire", ".", "TxTreeRegular", "&&", "txTree", "!=", "wire", ".", "TxTreeStake", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "txTree", ")", "\n", "}", "\n", "return", "dbTxs", ",", "dbTxVouts", ",", "dbTxVins", "\n", "}" ]
// ExtractBlockTransactions extracts transaction information from a // wire.MsgBlock and returns the processed information in slices of the dbtypes // Tx, Vout, and VinTxPropertyARRAY.
[ "ExtractBlockTransactions", "extracts", "transaction", "information", "from", "a", "wire", ".", "MsgBlock", "and", "returns", "the", "processed", "information", "in", "slices", "of", "the", "dbtypes", "Tx", "Vout", "and", "VinTxPropertyARRAY", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/extraction.go#L40-L48
train
decred/dcrdata
gov/politeia/piclient/piclient.go
RetrieveAllProposals
func RetrieveAllProposals(client *http.Client, APIRootPath, URLParams string) ( *pitypes.Proposals, error) { // Constructs the full vetted proposals API URL URLpath := APIRootPath + piapi.RouteAllVetted + URLParams data, err := HandleGetRequests(client, URLpath) if err != nil { return nil, err } var publicProposals pitypes.Proposals err = json.Unmarshal(data, &publicProposals) if err != nil || len(publicProposals.Data) == 0 { return &publicProposals, err } // Constructs the full vote status API URL URLpath = APIRootPath + piapi.RouteAllVoteStatus + URLParams data, err = HandleGetRequests(client, URLpath) if err != nil { return nil, err } var votesInfo pitypes.Votes err = json.Unmarshal(data, &votesInfo) if err != nil { return nil, err } // Append the votes status information to the respective proposals if it exists. for _, val := range publicProposals.Data { for k := range votesInfo.Data { if val.TokenVal == votesInfo.Data[k].Token { val.ProposalVotes = votesInfo.Data[k] // exits the second loop after finding a match. break } } } return &publicProposals, nil }
go
func RetrieveAllProposals(client *http.Client, APIRootPath, URLParams string) ( *pitypes.Proposals, error) { // Constructs the full vetted proposals API URL URLpath := APIRootPath + piapi.RouteAllVetted + URLParams data, err := HandleGetRequests(client, URLpath) if err != nil { return nil, err } var publicProposals pitypes.Proposals err = json.Unmarshal(data, &publicProposals) if err != nil || len(publicProposals.Data) == 0 { return &publicProposals, err } // Constructs the full vote status API URL URLpath = APIRootPath + piapi.RouteAllVoteStatus + URLParams data, err = HandleGetRequests(client, URLpath) if err != nil { return nil, err } var votesInfo pitypes.Votes err = json.Unmarshal(data, &votesInfo) if err != nil { return nil, err } // Append the votes status information to the respective proposals if it exists. for _, val := range publicProposals.Data { for k := range votesInfo.Data { if val.TokenVal == votesInfo.Data[k].Token { val.ProposalVotes = votesInfo.Data[k] // exits the second loop after finding a match. break } } } return &publicProposals, nil }
[ "func", "RetrieveAllProposals", "(", "client", "*", "http", ".", "Client", ",", "APIRootPath", ",", "URLParams", "string", ")", "(", "*", "pitypes", ".", "Proposals", ",", "error", ")", "{", "// Constructs the full vetted proposals API URL", "URLpath", ":=", "APIRootPath", "+", "piapi", ".", "RouteAllVetted", "+", "URLParams", "\n", "data", ",", "err", ":=", "HandleGetRequests", "(", "client", ",", "URLpath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "publicProposals", "pitypes", ".", "Proposals", "\n", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "publicProposals", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "publicProposals", ".", "Data", ")", "==", "0", "{", "return", "&", "publicProposals", ",", "err", "\n", "}", "\n\n", "// Constructs the full vote status API URL", "URLpath", "=", "APIRootPath", "+", "piapi", ".", "RouteAllVoteStatus", "+", "URLParams", "\n", "data", ",", "err", "=", "HandleGetRequests", "(", "client", ",", "URLpath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "votesInfo", "pitypes", ".", "Votes", "\n", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "votesInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Append the votes status information to the respective proposals if it exists.", "for", "_", ",", "val", ":=", "range", "publicProposals", ".", "Data", "{", "for", "k", ":=", "range", "votesInfo", ".", "Data", "{", "if", "val", ".", "TokenVal", "==", "votesInfo", ".", "Data", "[", "k", "]", ".", "Token", "{", "val", ".", "ProposalVotes", "=", "votesInfo", ".", "Data", "[", "k", "]", "\n", "// exits the second loop after finding a match.", "break", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "&", "publicProposals", ",", "nil", "\n", "}" ]
// RetrieveAllProposals returns a list of Proposals whose maximum count is defined // by piapi.ProposalListPageSize. Data returned is queried from Politeia API.
[ "RetrieveAllProposals", "returns", "a", "list", "of", "Proposals", "whose", "maximum", "count", "is", "defined", "by", "piapi", ".", "ProposalListPageSize", ".", "Data", "returned", "is", "queried", "from", "Politeia", "API", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/piclient/piclient.go#L54-L94
train
decred/dcrdata
gov/politeia/piclient/piclient.go
RetrieveProposalByToken
func RetrieveProposalByToken(client *http.Client, APIRootPath, token string) (*pitypes.Proposal, error) { // Constructs the full proposal's URl and fetch is data. proposalRoute := APIRootPath + DropURLRegex(piapi.RouteProposalDetails, token) data, err := HandleGetRequests(client, proposalRoute) if err != nil { return nil, fmt.Errorf("retrieving %s proposal details failed: %v", token, err) } var proposal pitypes.Proposal err = json.Unmarshal(data, &proposal) if err != nil { return nil, err } // Check if null proposal data was returned as part of the proposal details. if proposal.Data == nil { return nil, fmt.Errorf("invalid proposal with null data found for %s", token) } // Constructs the full votes status URL and fetch its data. votesStatusRoute := APIRootPath + DropURLRegex(piapi.RouteVoteStatus, token) data, err = HandleGetRequests(client, votesStatusRoute) if err != nil { return nil, fmt.Errorf("retrieving %s proposal vote status failed: %v", token, err) } err = json.Unmarshal(data, &proposal.Data.ProposalVotes) if err != nil { return nil, err } return &proposal, nil }
go
func RetrieveProposalByToken(client *http.Client, APIRootPath, token string) (*pitypes.Proposal, error) { // Constructs the full proposal's URl and fetch is data. proposalRoute := APIRootPath + DropURLRegex(piapi.RouteProposalDetails, token) data, err := HandleGetRequests(client, proposalRoute) if err != nil { return nil, fmt.Errorf("retrieving %s proposal details failed: %v", token, err) } var proposal pitypes.Proposal err = json.Unmarshal(data, &proposal) if err != nil { return nil, err } // Check if null proposal data was returned as part of the proposal details. if proposal.Data == nil { return nil, fmt.Errorf("invalid proposal with null data found for %s", token) } // Constructs the full votes status URL and fetch its data. votesStatusRoute := APIRootPath + DropURLRegex(piapi.RouteVoteStatus, token) data, err = HandleGetRequests(client, votesStatusRoute) if err != nil { return nil, fmt.Errorf("retrieving %s proposal vote status failed: %v", token, err) } err = json.Unmarshal(data, &proposal.Data.ProposalVotes) if err != nil { return nil, err } return &proposal, nil }
[ "func", "RetrieveProposalByToken", "(", "client", "*", "http", ".", "Client", ",", "APIRootPath", ",", "token", "string", ")", "(", "*", "pitypes", ".", "Proposal", ",", "error", ")", "{", "// Constructs the full proposal's URl and fetch is data.", "proposalRoute", ":=", "APIRootPath", "+", "DropURLRegex", "(", "piapi", ".", "RouteProposalDetails", ",", "token", ")", "\n", "data", ",", "err", ":=", "HandleGetRequests", "(", "client", ",", "proposalRoute", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ",", "err", ")", "\n", "}", "\n\n", "var", "proposal", "pitypes", ".", "Proposal", "\n", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "proposal", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Check if null proposal data was returned as part of the proposal details.", "if", "proposal", ".", "Data", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ")", "\n", "}", "\n\n", "// Constructs the full votes status URL and fetch its data.", "votesStatusRoute", ":=", "APIRootPath", "+", "DropURLRegex", "(", "piapi", ".", "RouteVoteStatus", ",", "token", ")", "\n", "data", ",", "err", "=", "HandleGetRequests", "(", "client", ",", "votesStatusRoute", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ",", "err", ")", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "proposal", ".", "Data", ".", "ProposalVotes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "proposal", ",", "nil", "\n", "}" ]
// RetrieveProposalByToken returns a single proposal identified by the token // hash provided if it exists. Data returned is queried from Politeia API.
[ "RetrieveProposalByToken", "returns", "a", "single", "proposal", "identified", "by", "the", "token", "hash", "provided", "if", "it", "exists", ".", "Data", "returned", "is", "queried", "from", "Politeia", "API", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/politeia/piclient/piclient.go#L98-L130
train
decred/dcrdata
explorer/syncstatus.go
ShowingSyncStatusPage
func (exp *explorerUI) ShowingSyncStatusPage() bool { display, ok := exp.displaySyncStatusPage.Load().(bool) return ok && display }
go
func (exp *explorerUI) ShowingSyncStatusPage() bool { display, ok := exp.displaySyncStatusPage.Load().(bool) return ok && display }
[ "func", "(", "exp", "*", "explorerUI", ")", "ShowingSyncStatusPage", "(", ")", "bool", "{", "display", ",", "ok", ":=", "exp", ".", "displaySyncStatusPage", ".", "Load", "(", ")", ".", "(", "bool", ")", "\n", "return", "ok", "&&", "display", "\n", "}" ]
// ShowingSyncStatusPage is a thread-safe way to fetch the // displaySyncStatusPage.
[ "ShowingSyncStatusPage", "is", "a", "thread", "-", "safe", "way", "to", "fetch", "the", "displaySyncStatusPage", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/syncstatus.go#L50-L53
train
decred/dcrdata
explorer/syncstatus.go
BeginSyncStatusUpdates
func (exp *explorerUI) BeginSyncStatusUpdates(barLoad chan *dbtypes.ProgressBarLoad) { // Do not start listening for updates if channel is nil. if barLoad == nil { log.Warnf("Not updating sync status page.") return } // stopTimer allows safe exit of the goroutine that triggers periodic // websocket progress update. stopTimer := make(chan struct{}) exp.EnableSyncStatusPage(true) // Periodically trigger websocket hub to signal a progress update. go func() { timer := time.NewTicker(syncStatusInterval) timerLoop: for { select { case <-timer.C: log.Trace("Sending progress bar signal.") exp.wsHub.HubRelay <- pstypes.HubMessage{Signal: sigSyncStatus} case <-stopTimer: log.Debug("Stopping progress bar signals.") timer.Stop() break timerLoop } } }() // Update the progress bar data when progress updates are received from the // sync routine of a database backend. go func() { // The receive loop quits when barLoad is closed or a nil *Hash is sent. // In either case, the barLoad channel is set to nil when the goroutine // returns. As a result, the websocket trigger goroutine will return. defer func() { log.Debug("Finished with sync status updates.") barLoad = nil // Send the one last signal so that the websocket can send the final // confirmation that syncing is done and home page auto reload should // happen. exp.wsHub.HubRelay <- pstypes.HubMessage{Signal: sigSyncStatus} exp.EnableSyncStatusPage(false) }() barloop: for bar := range barLoad { if bar == nil { stopTimer <- struct{}{} return } var percentage float64 if bar.To > 0 { percentage = math.Floor(float64(bar.From)/float64(bar.To)*10000) / 100 } val := SyncStatusInfo{ PercentComplete: percentage, BarMsg: bar.Msg, Time: bar.Timestamp, ProgressBarID: bar.BarID, BarSubtitle: bar.Subtitle, } // Update existing progress bar if one is found with this ID. blockchainSyncStatus.Lock() for i, v := range blockchainSyncStatus.ProgressBars { if v.ProgressBarID == bar.BarID { // Existing progress bar data. if len(bar.Subtitle) > 0 && bar.Timestamp == 0 { // Handle case scenario when only subtitle should be updated. blockchainSyncStatus.ProgressBars[i].BarSubtitle = bar.Subtitle } else { blockchainSyncStatus.ProgressBars[i] = val } // Go back to waiting for updates. blockchainSyncStatus.Unlock() continue barloop } } // Existing bar with this ID not found, append new. blockchainSyncStatus.ProgressBars = append(blockchainSyncStatus.ProgressBars, val) blockchainSyncStatus.Unlock() } }() }
go
func (exp *explorerUI) BeginSyncStatusUpdates(barLoad chan *dbtypes.ProgressBarLoad) { // Do not start listening for updates if channel is nil. if barLoad == nil { log.Warnf("Not updating sync status page.") return } // stopTimer allows safe exit of the goroutine that triggers periodic // websocket progress update. stopTimer := make(chan struct{}) exp.EnableSyncStatusPage(true) // Periodically trigger websocket hub to signal a progress update. go func() { timer := time.NewTicker(syncStatusInterval) timerLoop: for { select { case <-timer.C: log.Trace("Sending progress bar signal.") exp.wsHub.HubRelay <- pstypes.HubMessage{Signal: sigSyncStatus} case <-stopTimer: log.Debug("Stopping progress bar signals.") timer.Stop() break timerLoop } } }() // Update the progress bar data when progress updates are received from the // sync routine of a database backend. go func() { // The receive loop quits when barLoad is closed or a nil *Hash is sent. // In either case, the barLoad channel is set to nil when the goroutine // returns. As a result, the websocket trigger goroutine will return. defer func() { log.Debug("Finished with sync status updates.") barLoad = nil // Send the one last signal so that the websocket can send the final // confirmation that syncing is done and home page auto reload should // happen. exp.wsHub.HubRelay <- pstypes.HubMessage{Signal: sigSyncStatus} exp.EnableSyncStatusPage(false) }() barloop: for bar := range barLoad { if bar == nil { stopTimer <- struct{}{} return } var percentage float64 if bar.To > 0 { percentage = math.Floor(float64(bar.From)/float64(bar.To)*10000) / 100 } val := SyncStatusInfo{ PercentComplete: percentage, BarMsg: bar.Msg, Time: bar.Timestamp, ProgressBarID: bar.BarID, BarSubtitle: bar.Subtitle, } // Update existing progress bar if one is found with this ID. blockchainSyncStatus.Lock() for i, v := range blockchainSyncStatus.ProgressBars { if v.ProgressBarID == bar.BarID { // Existing progress bar data. if len(bar.Subtitle) > 0 && bar.Timestamp == 0 { // Handle case scenario when only subtitle should be updated. blockchainSyncStatus.ProgressBars[i].BarSubtitle = bar.Subtitle } else { blockchainSyncStatus.ProgressBars[i] = val } // Go back to waiting for updates. blockchainSyncStatus.Unlock() continue barloop } } // Existing bar with this ID not found, append new. blockchainSyncStatus.ProgressBars = append(blockchainSyncStatus.ProgressBars, val) blockchainSyncStatus.Unlock() } }() }
[ "func", "(", "exp", "*", "explorerUI", ")", "BeginSyncStatusUpdates", "(", "barLoad", "chan", "*", "dbtypes", ".", "ProgressBarLoad", ")", "{", "// Do not start listening for updates if channel is nil.", "if", "barLoad", "==", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "// stopTimer allows safe exit of the goroutine that triggers periodic", "// websocket progress update.", "stopTimer", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n\n", "exp", ".", "EnableSyncStatusPage", "(", "true", ")", "\n\n", "// Periodically trigger websocket hub to signal a progress update.", "go", "func", "(", ")", "{", "timer", ":=", "time", ".", "NewTicker", "(", "syncStatusInterval", ")", "\n\n", "timerLoop", ":", "for", "{", "select", "{", "case", "<-", "timer", ".", "C", ":", "log", ".", "Trace", "(", "\"", "\"", ")", "\n", "exp", ".", "wsHub", ".", "HubRelay", "<-", "pstypes", ".", "HubMessage", "{", "Signal", ":", "sigSyncStatus", "}", "\n\n", "case", "<-", "stopTimer", ":", "log", ".", "Debug", "(", "\"", "\"", ")", "\n", "timer", ".", "Stop", "(", ")", "\n", "break", "timerLoop", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "// Update the progress bar data when progress updates are received from the", "// sync routine of a database backend.", "go", "func", "(", ")", "{", "// The receive loop quits when barLoad is closed or a nil *Hash is sent.", "// In either case, the barLoad channel is set to nil when the goroutine", "// returns. As a result, the websocket trigger goroutine will return.", "defer", "func", "(", ")", "{", "log", ".", "Debug", "(", "\"", "\"", ")", "\n", "barLoad", "=", "nil", "\n", "// Send the one last signal so that the websocket can send the final", "// confirmation that syncing is done and home page auto reload should", "// happen.", "exp", ".", "wsHub", ".", "HubRelay", "<-", "pstypes", ".", "HubMessage", "{", "Signal", ":", "sigSyncStatus", "}", "\n", "exp", ".", "EnableSyncStatusPage", "(", "false", ")", "\n", "}", "(", ")", "\n\n", "barloop", ":", "for", "bar", ":=", "range", "barLoad", "{", "if", "bar", "==", "nil", "{", "stopTimer", "<-", "struct", "{", "}", "{", "}", "\n", "return", "\n", "}", "\n\n", "var", "percentage", "float64", "\n", "if", "bar", ".", "To", ">", "0", "{", "percentage", "=", "math", ".", "Floor", "(", "float64", "(", "bar", ".", "From", ")", "/", "float64", "(", "bar", ".", "To", ")", "*", "10000", ")", "/", "100", "\n", "}", "\n\n", "val", ":=", "SyncStatusInfo", "{", "PercentComplete", ":", "percentage", ",", "BarMsg", ":", "bar", ".", "Msg", ",", "Time", ":", "bar", ".", "Timestamp", ",", "ProgressBarID", ":", "bar", ".", "BarID", ",", "BarSubtitle", ":", "bar", ".", "Subtitle", ",", "}", "\n\n", "// Update existing progress bar if one is found with this ID.", "blockchainSyncStatus", ".", "Lock", "(", ")", "\n", "for", "i", ",", "v", ":=", "range", "blockchainSyncStatus", ".", "ProgressBars", "{", "if", "v", ".", "ProgressBarID", "==", "bar", ".", "BarID", "{", "// Existing progress bar data.", "if", "len", "(", "bar", ".", "Subtitle", ")", ">", "0", "&&", "bar", ".", "Timestamp", "==", "0", "{", "// Handle case scenario when only subtitle should be updated.", "blockchainSyncStatus", ".", "ProgressBars", "[", "i", "]", ".", "BarSubtitle", "=", "bar", ".", "Subtitle", "\n", "}", "else", "{", "blockchainSyncStatus", ".", "ProgressBars", "[", "i", "]", "=", "val", "\n", "}", "\n", "// Go back to waiting for updates.", "blockchainSyncStatus", ".", "Unlock", "(", ")", "\n", "continue", "barloop", "\n", "}", "\n", "}", "\n\n", "// Existing bar with this ID not found, append new.", "blockchainSyncStatus", ".", "ProgressBars", "=", "append", "(", "blockchainSyncStatus", ".", "ProgressBars", ",", "val", ")", "\n", "blockchainSyncStatus", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// BeginSyncStatusUpdates receives the progress updates and and updates the // blockchainSyncStatus.ProgressBars.
[ "BeginSyncStatusUpdates", "receives", "the", "progress", "updates", "and", "and", "updates", "the", "blockchainSyncStatus", ".", "ProgressBars", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/explorer/syncstatus.go#L62-L152
train
decred/dcrdata
pubsub/pubsubhub.go
NewPubSubHub
func NewPubSubHub(dataSource wsDataSource) (*PubSubHub, error) { psh := new(PubSubHub) psh.sourceBase = dataSource // Allocate Mempool fields. psh.invs = new(exptypes.MempoolInfo) // Retrieve chain parameters. params := psh.sourceBase.GetChainParams() psh.params = params // Development subsidy address of the current network devSubsidyAddress, err := dbtypes.DevSubsidyAddress(params) if err != nil { return nil, fmt.Errorf("bad project fund address: %v", err) } psh.state = &State{ // Set the constant parameters of GeneralInfo. GeneralInfo: &exptypes.HomeInfo{ DevAddress: devSubsidyAddress, Params: exptypes.ChainParams{ WindowSize: params.StakeDiffWindowSize, RewardWindowSize: params.SubsidyReductionInterval, BlockTime: params.TargetTimePerBlock.Nanoseconds(), MeanVotingBlocks: txhelpers.CalcMeanVotingBlocks(params), }, PoolInfo: exptypes.TicketPoolInfo{ Target: params.TicketPoolSize * params.TicketsPerBlock, }, }, // BlockInfo and BlockchainInfo are set by Store() } psh.wsHub = NewWebsocketHub() go psh.wsHub.Run() return psh, nil }
go
func NewPubSubHub(dataSource wsDataSource) (*PubSubHub, error) { psh := new(PubSubHub) psh.sourceBase = dataSource // Allocate Mempool fields. psh.invs = new(exptypes.MempoolInfo) // Retrieve chain parameters. params := psh.sourceBase.GetChainParams() psh.params = params // Development subsidy address of the current network devSubsidyAddress, err := dbtypes.DevSubsidyAddress(params) if err != nil { return nil, fmt.Errorf("bad project fund address: %v", err) } psh.state = &State{ // Set the constant parameters of GeneralInfo. GeneralInfo: &exptypes.HomeInfo{ DevAddress: devSubsidyAddress, Params: exptypes.ChainParams{ WindowSize: params.StakeDiffWindowSize, RewardWindowSize: params.SubsidyReductionInterval, BlockTime: params.TargetTimePerBlock.Nanoseconds(), MeanVotingBlocks: txhelpers.CalcMeanVotingBlocks(params), }, PoolInfo: exptypes.TicketPoolInfo{ Target: params.TicketPoolSize * params.TicketsPerBlock, }, }, // BlockInfo and BlockchainInfo are set by Store() } psh.wsHub = NewWebsocketHub() go psh.wsHub.Run() return psh, nil }
[ "func", "NewPubSubHub", "(", "dataSource", "wsDataSource", ")", "(", "*", "PubSubHub", ",", "error", ")", "{", "psh", ":=", "new", "(", "PubSubHub", ")", "\n", "psh", ".", "sourceBase", "=", "dataSource", "\n\n", "// Allocate Mempool fields.", "psh", ".", "invs", "=", "new", "(", "exptypes", ".", "MempoolInfo", ")", "\n\n", "// Retrieve chain parameters.", "params", ":=", "psh", ".", "sourceBase", ".", "GetChainParams", "(", ")", "\n", "psh", ".", "params", "=", "params", "\n\n", "// Development subsidy address of the current network", "devSubsidyAddress", ",", "err", ":=", "dbtypes", ".", "DevSubsidyAddress", "(", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "psh", ".", "state", "=", "&", "State", "{", "// Set the constant parameters of GeneralInfo.", "GeneralInfo", ":", "&", "exptypes", ".", "HomeInfo", "{", "DevAddress", ":", "devSubsidyAddress", ",", "Params", ":", "exptypes", ".", "ChainParams", "{", "WindowSize", ":", "params", ".", "StakeDiffWindowSize", ",", "RewardWindowSize", ":", "params", ".", "SubsidyReductionInterval", ",", "BlockTime", ":", "params", ".", "TargetTimePerBlock", ".", "Nanoseconds", "(", ")", ",", "MeanVotingBlocks", ":", "txhelpers", ".", "CalcMeanVotingBlocks", "(", "params", ")", ",", "}", ",", "PoolInfo", ":", "exptypes", ".", "TicketPoolInfo", "{", "Target", ":", "params", ".", "TicketPoolSize", "*", "params", ".", "TicketsPerBlock", ",", "}", ",", "}", ",", "// BlockInfo and BlockchainInfo are set by Store()", "}", "\n\n", "psh", ".", "wsHub", "=", "NewWebsocketHub", "(", ")", "\n", "go", "psh", ".", "wsHub", ".", "Run", "(", ")", "\n\n", "return", "psh", ",", "nil", "\n", "}" ]
// NewPubSubHub constructs a PubSubHub given a primary and auxiliary data // source. The primary data source is required, while the aux. source may be // nil, which indicates a "lite" mode of operation. The WebSocketHub is // automatically started.
[ "NewPubSubHub", "constructs", "a", "PubSubHub", "given", "a", "primary", "and", "auxiliary", "data", "source", ".", "The", "primary", "data", "source", "is", "required", "while", "the", "aux", ".", "source", "may", "be", "nil", "which", "indicates", "a", "lite", "mode", "of", "operation", ".", "The", "WebSocketHub", "is", "automatically", "started", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/pubsubhub.go#L89-L127
train
decred/dcrdata
pubsub/pubsubhub.go
StopWebsocketHub
func (psh *PubSubHub) StopWebsocketHub() { if psh == nil { return } log.Info("Stopping websocket hub.") psh.wsHub.Stop() }
go
func (psh *PubSubHub) StopWebsocketHub() { if psh == nil { return } log.Info("Stopping websocket hub.") psh.wsHub.Stop() }
[ "func", "(", "psh", "*", "PubSubHub", ")", "StopWebsocketHub", "(", ")", "{", "if", "psh", "==", "nil", "{", "return", "\n", "}", "\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "psh", ".", "wsHub", ".", "Stop", "(", ")", "\n", "}" ]
// StopWebsocketHub stops the websocket hub.
[ "StopWebsocketHub", "stops", "the", "websocket", "hub", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/pubsubhub.go#L130-L136
train
decred/dcrdata
pubsub/pubsubhub.go
closeWS
func closeWS(ws *websocket.Conn) { err := ws.Close() // Do not log error if connection is just closed if err != nil && !pstypes.IsWSClosedErr(err) && !pstypes.IsIOTimeoutErr(err) { log.Errorf("Failed to close websocket: %v", err) } }
go
func closeWS(ws *websocket.Conn) { err := ws.Close() // Do not log error if connection is just closed if err != nil && !pstypes.IsWSClosedErr(err) && !pstypes.IsIOTimeoutErr(err) { log.Errorf("Failed to close websocket: %v", err) } }
[ "func", "closeWS", "(", "ws", "*", "websocket", ".", "Conn", ")", "{", "err", ":=", "ws", ".", "Close", "(", ")", "\n", "// Do not log error if connection is just closed", "if", "err", "!=", "nil", "&&", "!", "pstypes", ".", "IsWSClosedErr", "(", "err", ")", "&&", "!", "pstypes", ".", "IsIOTimeoutErr", "(", "err", ")", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// closeWS attempts to close a websocket.Conn, logging errors other than those // with messages containing ErrWsClosed.
[ "closeWS", "attempts", "to", "close", "a", "websocket", ".", "Conn", "logging", "errors", "other", "than", "those", "with", "messages", "containing", "ErrWsClosed", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/pubsubhub.go#L163-L169
train
decred/dcrdata
pubsub/websocket.go
Ready
func (wsh *WebsocketHub) Ready() bool { syncing, ok := wsh.ready.Load().(bool) return ok && syncing }
go
func (wsh *WebsocketHub) Ready() bool { syncing, ok := wsh.ready.Load().(bool) return ok && syncing }
[ "func", "(", "wsh", "*", "WebsocketHub", ")", "Ready", "(", ")", "bool", "{", "syncing", ",", "ok", ":=", "wsh", ".", "ready", ".", "Load", "(", ")", ".", "(", "bool", ")", "\n", "return", "ok", "&&", "syncing", "\n", "}" ]
// Ready is a thread-safe way to fetch the boolean in ready.
[ "Ready", "is", "a", "thread", "-", "safe", "way", "to", "fetch", "the", "boolean", "in", "ready", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/websocket.go#L92-L95
train
decred/dcrdata
pubsub/websocket.go
NewWebsocketHub
func NewWebsocketHub() *WebsocketHub { return &WebsocketHub{ clients: make(map[*hubSpoke]*client), Register: make(chan *clientHubSpoke), Unregister: make(chan *hubSpoke), HubRelay: make(chan pstypes.HubMessage), bufferTickerChan: make(chan int, clientSignalSize), quitWSHandler: make(chan struct{}), requestLimit: MaxPayloadBytes, // 1 MB } }
go
func NewWebsocketHub() *WebsocketHub { return &WebsocketHub{ clients: make(map[*hubSpoke]*client), Register: make(chan *clientHubSpoke), Unregister: make(chan *hubSpoke), HubRelay: make(chan pstypes.HubMessage), bufferTickerChan: make(chan int, clientSignalSize), quitWSHandler: make(chan struct{}), requestLimit: MaxPayloadBytes, // 1 MB } }
[ "func", "NewWebsocketHub", "(", ")", "*", "WebsocketHub", "{", "return", "&", "WebsocketHub", "{", "clients", ":", "make", "(", "map", "[", "*", "hubSpoke", "]", "*", "client", ")", ",", "Register", ":", "make", "(", "chan", "*", "clientHubSpoke", ")", ",", "Unregister", ":", "make", "(", "chan", "*", "hubSpoke", ")", ",", "HubRelay", ":", "make", "(", "chan", "pstypes", ".", "HubMessage", ")", ",", "bufferTickerChan", ":", "make", "(", "chan", "int", ",", "clientSignalSize", ")", ",", "quitWSHandler", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "requestLimit", ":", "MaxPayloadBytes", ",", "// 1 MB", "}", "\n", "}" ]
// NewWebsocketHub creates a new WebsocketHub.
[ "NewWebsocketHub", "creates", "a", "new", "WebsocketHub", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/websocket.go#L189-L199
train
decred/dcrdata
pubsub/websocket.go
NewClientHubSpoke
func (wsh *WebsocketHub) NewClientHubSpoke() *clientHubSpoke { c := make(hubSpoke, 16) ch := &clientHubSpoke{ cl: newClient(), c: &c, } wsh.Register <- ch return ch }
go
func (wsh *WebsocketHub) NewClientHubSpoke() *clientHubSpoke { c := make(hubSpoke, 16) ch := &clientHubSpoke{ cl: newClient(), c: &c, } wsh.Register <- ch return ch }
[ "func", "(", "wsh", "*", "WebsocketHub", ")", "NewClientHubSpoke", "(", ")", "*", "clientHubSpoke", "{", "c", ":=", "make", "(", "hubSpoke", ",", "16", ")", "\n", "ch", ":=", "&", "clientHubSpoke", "{", "cl", ":", "newClient", "(", ")", ",", "c", ":", "&", "c", ",", "}", "\n", "wsh", ".", "Register", "<-", "ch", "\n", "return", "ch", "\n", "}" ]
// NewClientHubSpoke registers a connection with the hub, and returns a pointer // to the new client data object. Use UnregisterClient on this object to stop // signaling messages, and close the signal channel.
[ "NewClientHubSpoke", "registers", "a", "connection", "with", "the", "hub", "and", "returns", "a", "pointer", "to", "the", "new", "client", "data", "object", ".", "Use", "UnregisterClient", "on", "this", "object", "to", "stop", "signaling", "messages", "and", "close", "the", "signal", "channel", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/websocket.go#L211-L219
train
decred/dcrdata
pubsub/websocket.go
registerClient
func (wsh *WebsocketHub) registerClient(ch *clientHubSpoke) { wsh.clients[ch.c] = ch.cl wsh.setNumClients(len(wsh.clients)) log.Debugf("Registered new websocket client (%d).", wsh.NumClients()) }
go
func (wsh *WebsocketHub) registerClient(ch *clientHubSpoke) { wsh.clients[ch.c] = ch.cl wsh.setNumClients(len(wsh.clients)) log.Debugf("Registered new websocket client (%d).", wsh.NumClients()) }
[ "func", "(", "wsh", "*", "WebsocketHub", ")", "registerClient", "(", "ch", "*", "clientHubSpoke", ")", "{", "wsh", ".", "clients", "[", "ch", ".", "c", "]", "=", "ch", ".", "cl", "\n", "wsh", ".", "setNumClients", "(", "len", "(", "wsh", ".", "clients", ")", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "wsh", ".", "NumClients", "(", ")", ")", "\n", "}" ]
// registerClient should only be called from the run loop.
[ "registerClient", "should", "only", "be", "called", "from", "the", "run", "loop", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/websocket.go#L233-L237
train
decred/dcrdata
pubsub/websocket.go
addTxToBuffer
func (wsh *WebsocketHub) addTxToBuffer(tx *exptypes.MempoolTx) (someReadyToSend bool) { for _, client := range wsh.clients { someReadyToSend = client.newTxs.addTxToBuffer(tx) } return }
go
func (wsh *WebsocketHub) addTxToBuffer(tx *exptypes.MempoolTx) (someReadyToSend bool) { for _, client := range wsh.clients { someReadyToSend = client.newTxs.addTxToBuffer(tx) } return }
[ "func", "(", "wsh", "*", "WebsocketHub", ")", "addTxToBuffer", "(", "tx", "*", "exptypes", ".", "MempoolTx", ")", "(", "someReadyToSend", "bool", ")", "{", "for", "_", ",", "client", ":=", "range", "wsh", ".", "clients", "{", "someReadyToSend", "=", "client", ".", "newTxs", ".", "addTxToBuffer", "(", "tx", ")", "\n", "}", "\n", "return", "\n", "}" ]
// addTxToBuffer adds a tx to each client's tx buffer. The return boolean value // indicates if at least one buffer is ready to be sent.
[ "addTxToBuffer", "adds", "a", "tx", "to", "each", "client", "s", "tx", "buffer", ".", "The", "return", "boolean", "value", "indicates", "if", "at", "least", "one", "buffer", "is", "ready", "to", "be", "sent", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/websocket.go#L465-L470
train
decred/dcrdata
pubsub/websocket.go
periodicTxBufferSend
func (wsh *WebsocketHub) periodicTxBufferSend() { ticker := time.NewTicker(bufferTickerInterval * time.Second) for { select { case <-ticker.C: wsh.SetTimeToSendTxBuffer(true) case sig := <-wsh.bufferTickerChan: switch sig { case tickerSigReset: ticker.Stop() ticker = time.NewTicker(bufferTickerInterval * time.Second) case tickerSigStop: close(wsh.bufferTickerChan) return } } } }
go
func (wsh *WebsocketHub) periodicTxBufferSend() { ticker := time.NewTicker(bufferTickerInterval * time.Second) for { select { case <-ticker.C: wsh.SetTimeToSendTxBuffer(true) case sig := <-wsh.bufferTickerChan: switch sig { case tickerSigReset: ticker.Stop() ticker = time.NewTicker(bufferTickerInterval * time.Second) case tickerSigStop: close(wsh.bufferTickerChan) return } } } }
[ "func", "(", "wsh", "*", "WebsocketHub", ")", "periodicTxBufferSend", "(", ")", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "bufferTickerInterval", "*", "time", ".", "Second", ")", "\n", "for", "{", "select", "{", "case", "<-", "ticker", ".", "C", ":", "wsh", ".", "SetTimeToSendTxBuffer", "(", "true", ")", "\n", "case", "sig", ":=", "<-", "wsh", ".", "bufferTickerChan", ":", "switch", "sig", "{", "case", "tickerSigReset", ":", "ticker", ".", "Stop", "(", ")", "\n", "ticker", "=", "time", ".", "NewTicker", "(", "bufferTickerInterval", "*", "time", ".", "Second", ")", "\n", "case", "tickerSigStop", ":", "close", "(", "wsh", ".", "bufferTickerChan", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// periodicTxBufferSend initiates a transaction buffer send via sendTxBufferChan // every bufferTickerInterval seconds.
[ "periodicTxBufferSend", "initiates", "a", "transaction", "buffer", "send", "via", "sendTxBufferChan", "every", "bufferTickerInterval", "seconds", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/websocket.go#L474-L491
train
decred/dcrdata
txhelpers/txhelpers.go
HashInSlice
func HashInSlice(h chainhash.Hash, list []chainhash.Hash) bool { for _, hash := range list { if h == hash { return true } } return false }
go
func HashInSlice(h chainhash.Hash, list []chainhash.Hash) bool { for _, hash := range list { if h == hash { return true } } return false }
[ "func", "HashInSlice", "(", "h", "chainhash", ".", "Hash", ",", "list", "[", "]", "chainhash", ".", "Hash", ")", "bool", "{", "for", "_", ",", "hash", ":=", "range", "list", "{", "if", "h", "==", "hash", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HashInSlice determines if a hash exists in a slice of hashes.
[ "HashInSlice", "determines", "if", "a", "hash", "exists", "in", "a", "slice", "of", "hashes", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L100-L107
train
decred/dcrdata
txhelpers/txhelpers.go
IncludesStakeTx
func IncludesStakeTx(txHash *chainhash.Hash, block *dcrutil.Block) (int, int8) { blockTxs := block.STransactions() if tx := TxhashInSlice(blockTxs, txHash); tx != nil { return tx.Index(), tx.Tree() } return -1, -1 }
go
func IncludesStakeTx(txHash *chainhash.Hash, block *dcrutil.Block) (int, int8) { blockTxs := block.STransactions() if tx := TxhashInSlice(blockTxs, txHash); tx != nil { return tx.Index(), tx.Tree() } return -1, -1 }
[ "func", "IncludesStakeTx", "(", "txHash", "*", "chainhash", ".", "Hash", ",", "block", "*", "dcrutil", ".", "Block", ")", "(", "int", ",", "int8", ")", "{", "blockTxs", ":=", "block", ".", "STransactions", "(", ")", "\n\n", "if", "tx", ":=", "TxhashInSlice", "(", "blockTxs", ",", "txHash", ")", ";", "tx", "!=", "nil", "{", "return", "tx", ".", "Index", "(", ")", ",", "tx", ".", "Tree", "(", ")", "\n", "}", "\n", "return", "-", "1", ",", "-", "1", "\n", "}" ]
// IncludesStakeTx checks if a block contains a stake transaction hash
[ "IncludesStakeTx", "checks", "if", "a", "block", "contains", "a", "stake", "transaction", "hash" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L126-L133
train
decred/dcrdata
txhelpers/txhelpers.go
IncludesTx
func IncludesTx(txHash *chainhash.Hash, block *dcrutil.Block) (int, int8) { blockTxs := block.Transactions() if tx := TxhashInSlice(blockTxs, txHash); tx != nil { return tx.Index(), tx.Tree() } return -1, -1 }
go
func IncludesTx(txHash *chainhash.Hash, block *dcrutil.Block) (int, int8) { blockTxs := block.Transactions() if tx := TxhashInSlice(blockTxs, txHash); tx != nil { return tx.Index(), tx.Tree() } return -1, -1 }
[ "func", "IncludesTx", "(", "txHash", "*", "chainhash", ".", "Hash", ",", "block", "*", "dcrutil", ".", "Block", ")", "(", "int", ",", "int8", ")", "{", "blockTxs", ":=", "block", ".", "Transactions", "(", ")", "\n\n", "if", "tx", ":=", "TxhashInSlice", "(", "blockTxs", ",", "txHash", ")", ";", "tx", "!=", "nil", "{", "return", "tx", ".", "Index", "(", ")", ",", "tx", ".", "Tree", "(", ")", "\n", "}", "\n", "return", "-", "1", ",", "-", "1", "\n", "}" ]
// IncludesTx checks if a block contains a transaction hash
[ "IncludesTx", "checks", "if", "a", "block", "contains", "a", "transaction", "hash" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L136-L143
train