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 | db/dcrpg/queries.go | InsertBlockPrevNext | func InsertBlockPrevNext(db *sql.DB, blockDbID uint64,
hash, prev, next string) error {
rows, err := db.Query(internal.InsertBlockPrevNext, blockDbID, prev, hash, next)
if err == nil {
return rows.Close()
}
return err
} | go | func InsertBlockPrevNext(db *sql.DB, blockDbID uint64,
hash, prev, next string) error {
rows, err := db.Query(internal.InsertBlockPrevNext, blockDbID, prev, hash, next)
if err == nil {
return rows.Close()
}
return err
} | [
"func",
"InsertBlockPrevNext",
"(",
"db",
"*",
"sql",
".",
"DB",
",",
"blockDbID",
"uint64",
",",
"hash",
",",
"prev",
",",
"next",
"string",
")",
"error",
"{",
"rows",
",",
"err",
":=",
"db",
".",
"Query",
"(",
"internal",
".",
"InsertBlockPrevNext",
",",
"blockDbID",
",",
"prev",
",",
"hash",
",",
"next",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"rows",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // InsertBlockPrevNext inserts a new row of the block_chain table. | [
"InsertBlockPrevNext",
"inserts",
"a",
"new",
"row",
"of",
"the",
"block_chain",
"table",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3322-L3329 | train |
decred/dcrdata | db/dcrpg/queries.go | RetrieveBlockVoteCount | func RetrieveBlockVoteCount(ctx context.Context, db *sql.DB, hash string) (numVotes int16, err error) {
err = db.QueryRowContext(ctx, internal.SelectBlockVoteCount, hash).Scan(&numVotes)
return
} | go | func RetrieveBlockVoteCount(ctx context.Context, db *sql.DB, hash string) (numVotes int16, err error) {
err = db.QueryRowContext(ctx, internal.SelectBlockVoteCount, hash).Scan(&numVotes)
return
} | [
"func",
"RetrieveBlockVoteCount",
"(",
"ctx",
"context",
".",
"Context",
",",
"db",
"*",
"sql",
".",
"DB",
",",
"hash",
"string",
")",
"(",
"numVotes",
"int16",
",",
"err",
"error",
")",
"{",
"err",
"=",
"db",
".",
"QueryRowContext",
"(",
"ctx",
",",
"internal",
".",
"SelectBlockVoteCount",
",",
"hash",
")",
".",
"Scan",
"(",
"&",
"numVotes",
")",
"\n",
"return",
"\n",
"}"
] | // RetrieveBlockVoteCount gets the number of votes mined in a block. | [
"RetrieveBlockVoteCount",
"gets",
"the",
"number",
"of",
"votes",
"mined",
"in",
"a",
"block",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3380-L3383 | train |
decred/dcrdata | db/dcrpg/queries.go | RetrieveBlocksHashesAll | func RetrieveBlocksHashesAll(ctx context.Context, db *sql.DB) ([]string, error) {
var hashes []string
rows, err := db.QueryContext(ctx, internal.SelectBlocksHashes)
if err != nil {
return hashes, err
}
defer closeRows(rows)
for rows.Next() {
var hash string
err = rows.Scan(&hash)
if err != nil {
break
}
hashes = append(hashes, hash)
}
return hashes, err
} | go | func RetrieveBlocksHashesAll(ctx context.Context, db *sql.DB) ([]string, error) {
var hashes []string
rows, err := db.QueryContext(ctx, internal.SelectBlocksHashes)
if err != nil {
return hashes, err
}
defer closeRows(rows)
for rows.Next() {
var hash string
err = rows.Scan(&hash)
if err != nil {
break
}
hashes = append(hashes, hash)
}
return hashes, err
} | [
"func",
"RetrieveBlocksHashesAll",
"(",
"ctx",
"context",
".",
"Context",
",",
"db",
"*",
"sql",
".",
"DB",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"hashes",
"[",
"]",
"string",
"\n",
"rows",
",",
"err",
":=",
"db",
".",
"QueryContext",
"(",
"ctx",
",",
"internal",
".",
"SelectBlocksHashes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"hashes",
",",
"err",
"\n",
"}",
"\n",
"defer",
"closeRows",
"(",
"rows",
")",
"\n\n",
"for",
"rows",
".",
"Next",
"(",
")",
"{",
"var",
"hash",
"string",
"\n",
"err",
"=",
"rows",
".",
"Scan",
"(",
"&",
"hash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n\n",
"hashes",
"=",
"append",
"(",
"hashes",
",",
"hash",
")",
"\n",
"}",
"\n",
"return",
"hashes",
",",
"err",
"\n",
"}"
] | // RetrieveBlocksHashesAll retrieve the hash of every block in the blocks table,
// ordered by their row ID. | [
"RetrieveBlocksHashesAll",
"retrieve",
"the",
"hash",
"of",
"every",
"block",
"in",
"the",
"blocks",
"table",
"ordered",
"by",
"their",
"row",
"ID",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3387-L3405 | train |
decred/dcrdata | db/dcrpg/queries.go | RetrieveSideChainBlocks | func RetrieveSideChainBlocks(ctx context.Context, db *sql.DB) (blocks []*dbtypes.BlockStatus, err error) {
var rows *sql.Rows
rows, err = db.QueryContext(ctx, internal.SelectSideChainBlocks)
if err != nil {
return
}
defer closeRows(rows)
for rows.Next() {
var bs dbtypes.BlockStatus
err = rows.Scan(&bs.IsValid, &bs.Height, &bs.PrevHash, &bs.Hash, &bs.NextHash)
if err != nil {
return
}
blocks = append(blocks, &bs)
}
return
} | go | func RetrieveSideChainBlocks(ctx context.Context, db *sql.DB) (blocks []*dbtypes.BlockStatus, err error) {
var rows *sql.Rows
rows, err = db.QueryContext(ctx, internal.SelectSideChainBlocks)
if err != nil {
return
}
defer closeRows(rows)
for rows.Next() {
var bs dbtypes.BlockStatus
err = rows.Scan(&bs.IsValid, &bs.Height, &bs.PrevHash, &bs.Hash, &bs.NextHash)
if err != nil {
return
}
blocks = append(blocks, &bs)
}
return
} | [
"func",
"RetrieveSideChainBlocks",
"(",
"ctx",
"context",
".",
"Context",
",",
"db",
"*",
"sql",
".",
"DB",
")",
"(",
"blocks",
"[",
"]",
"*",
"dbtypes",
".",
"BlockStatus",
",",
"err",
"error",
")",
"{",
"var",
"rows",
"*",
"sql",
".",
"Rows",
"\n",
"rows",
",",
"err",
"=",
"db",
".",
"QueryContext",
"(",
"ctx",
",",
"internal",
".",
"SelectSideChainBlocks",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"closeRows",
"(",
"rows",
")",
"\n\n",
"for",
"rows",
".",
"Next",
"(",
")",
"{",
"var",
"bs",
"dbtypes",
".",
"BlockStatus",
"\n",
"err",
"=",
"rows",
".",
"Scan",
"(",
"&",
"bs",
".",
"IsValid",
",",
"&",
"bs",
".",
"Height",
",",
"&",
"bs",
".",
"PrevHash",
",",
"&",
"bs",
".",
"Hash",
",",
"&",
"bs",
".",
"NextHash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"blocks",
"=",
"append",
"(",
"blocks",
",",
"&",
"bs",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // RetrieveSideChainBlocks retrieves the block chain status for all known side
// chain blocks. | [
"RetrieveSideChainBlocks",
"retrieves",
"the",
"block",
"chain",
"status",
"for",
"all",
"known",
"side",
"chain",
"blocks",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3417-L3435 | train |
decred/dcrdata | db/dcrpg/queries.go | RetrieveBlockStatus | func RetrieveBlockStatus(ctx context.Context, db *sql.DB, hash string) (bs dbtypes.BlockStatus, err error) {
err = db.QueryRowContext(ctx, internal.SelectBlockStatus, hash).Scan(&bs.IsValid,
&bs.IsMainchain, &bs.Height, &bs.PrevHash, &bs.Hash, &bs.NextHash)
return
} | go | func RetrieveBlockStatus(ctx context.Context, db *sql.DB, hash string) (bs dbtypes.BlockStatus, err error) {
err = db.QueryRowContext(ctx, internal.SelectBlockStatus, hash).Scan(&bs.IsValid,
&bs.IsMainchain, &bs.Height, &bs.PrevHash, &bs.Hash, &bs.NextHash)
return
} | [
"func",
"RetrieveBlockStatus",
"(",
"ctx",
"context",
".",
"Context",
",",
"db",
"*",
"sql",
".",
"DB",
",",
"hash",
"string",
")",
"(",
"bs",
"dbtypes",
".",
"BlockStatus",
",",
"err",
"error",
")",
"{",
"err",
"=",
"db",
".",
"QueryRowContext",
"(",
"ctx",
",",
"internal",
".",
"SelectBlockStatus",
",",
"hash",
")",
".",
"Scan",
"(",
"&",
"bs",
".",
"IsValid",
",",
"&",
"bs",
".",
"IsMainchain",
",",
"&",
"bs",
".",
"Height",
",",
"&",
"bs",
".",
"PrevHash",
",",
"&",
"bs",
".",
"Hash",
",",
"&",
"bs",
".",
"NextHash",
")",
"\n",
"return",
"\n",
"}"
] | // RetrieveBlockStatus retrieves the block chain status for the block with the
// specified hash. | [
"RetrieveBlockStatus",
"retrieves",
"the",
"block",
"chain",
"status",
"for",
"the",
"block",
"with",
"the",
"specified",
"hash",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3484-L3488 | train |
decred/dcrdata | db/dcrpg/queries.go | RetrieveBlockFlags | func RetrieveBlockFlags(ctx context.Context, db *sql.DB, hash string) (isValid bool, isMainchain bool, err error) {
err = db.QueryRowContext(ctx, internal.SelectBlockFlags, hash).Scan(&isValid, &isMainchain)
return
} | go | func RetrieveBlockFlags(ctx context.Context, db *sql.DB, hash string) (isValid bool, isMainchain bool, err error) {
err = db.QueryRowContext(ctx, internal.SelectBlockFlags, hash).Scan(&isValid, &isMainchain)
return
} | [
"func",
"RetrieveBlockFlags",
"(",
"ctx",
"context",
".",
"Context",
",",
"db",
"*",
"sql",
".",
"DB",
",",
"hash",
"string",
")",
"(",
"isValid",
"bool",
",",
"isMainchain",
"bool",
",",
"err",
"error",
")",
"{",
"err",
"=",
"db",
".",
"QueryRowContext",
"(",
"ctx",
",",
"internal",
".",
"SelectBlockFlags",
",",
"hash",
")",
".",
"Scan",
"(",
"&",
"isValid",
",",
"&",
"isMainchain",
")",
"\n",
"return",
"\n",
"}"
] | // RetrieveBlockFlags retrieves the block's is_valid and is_mainchain flags. | [
"RetrieveBlockFlags",
"retrieves",
"the",
"block",
"s",
"is_valid",
"and",
"is_mainchain",
"flags",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3491-L3494 | train |
decred/dcrdata | db/dcrpg/queries.go | RetrieveBlockSummaryByTimeRange | func RetrieveBlockSummaryByTimeRange(ctx context.Context, db *sql.DB, minTime, maxTime int64, limit int) ([]dbtypes.BlockDataBasic, error) {
var blocks []dbtypes.BlockDataBasic
var stmt *sql.Stmt
var rows *sql.Rows
var err error
// int64 -> time.Time is required to query TIMESTAMPTZ columns.
minT := time.Unix(minTime, 0)
maxT := time.Unix(maxTime, 0)
if limit == 0 {
stmt, err = db.Prepare(internal.SelectBlockByTimeRangeSQLNoLimit)
if err != nil {
return nil, err
}
rows, err = stmt.QueryContext(ctx, minT, maxT)
} else {
stmt, err = db.Prepare(internal.SelectBlockByTimeRangeSQL)
if err != nil {
return nil, err
}
rows, err = stmt.QueryContext(ctx, minT, maxT, limit)
}
_ = stmt.Close()
if err != nil {
log.Error(err)
return nil, err
}
defer closeRows(rows)
for rows.Next() {
var dbBlock dbtypes.BlockDataBasic
var blockTime dbtypes.TimeDef
err = rows.Scan(&dbBlock.Hash, &dbBlock.Height, &dbBlock.Size,
&blockTime, &dbBlock.NumTx)
if err != nil {
log.Errorf("Unable to scan for block fields: %v", err)
}
dbBlock.Time = blockTime
blocks = append(blocks, dbBlock)
}
if err = rows.Err(); err != nil {
log.Error(err)
}
return blocks, nil
} | go | func RetrieveBlockSummaryByTimeRange(ctx context.Context, db *sql.DB, minTime, maxTime int64, limit int) ([]dbtypes.BlockDataBasic, error) {
var blocks []dbtypes.BlockDataBasic
var stmt *sql.Stmt
var rows *sql.Rows
var err error
// int64 -> time.Time is required to query TIMESTAMPTZ columns.
minT := time.Unix(minTime, 0)
maxT := time.Unix(maxTime, 0)
if limit == 0 {
stmt, err = db.Prepare(internal.SelectBlockByTimeRangeSQLNoLimit)
if err != nil {
return nil, err
}
rows, err = stmt.QueryContext(ctx, minT, maxT)
} else {
stmt, err = db.Prepare(internal.SelectBlockByTimeRangeSQL)
if err != nil {
return nil, err
}
rows, err = stmt.QueryContext(ctx, minT, maxT, limit)
}
_ = stmt.Close()
if err != nil {
log.Error(err)
return nil, err
}
defer closeRows(rows)
for rows.Next() {
var dbBlock dbtypes.BlockDataBasic
var blockTime dbtypes.TimeDef
err = rows.Scan(&dbBlock.Hash, &dbBlock.Height, &dbBlock.Size,
&blockTime, &dbBlock.NumTx)
if err != nil {
log.Errorf("Unable to scan for block fields: %v", err)
}
dbBlock.Time = blockTime
blocks = append(blocks, dbBlock)
}
if err = rows.Err(); err != nil {
log.Error(err)
}
return blocks, nil
} | [
"func",
"RetrieveBlockSummaryByTimeRange",
"(",
"ctx",
"context",
".",
"Context",
",",
"db",
"*",
"sql",
".",
"DB",
",",
"minTime",
",",
"maxTime",
"int64",
",",
"limit",
"int",
")",
"(",
"[",
"]",
"dbtypes",
".",
"BlockDataBasic",
",",
"error",
")",
"{",
"var",
"blocks",
"[",
"]",
"dbtypes",
".",
"BlockDataBasic",
"\n",
"var",
"stmt",
"*",
"sql",
".",
"Stmt",
"\n",
"var",
"rows",
"*",
"sql",
".",
"Rows",
"\n",
"var",
"err",
"error",
"\n\n",
"// int64 -> time.Time is required to query TIMESTAMPTZ columns.",
"minT",
":=",
"time",
".",
"Unix",
"(",
"minTime",
",",
"0",
")",
"\n",
"maxT",
":=",
"time",
".",
"Unix",
"(",
"maxTime",
",",
"0",
")",
"\n\n",
"if",
"limit",
"==",
"0",
"{",
"stmt",
",",
"err",
"=",
"db",
".",
"Prepare",
"(",
"internal",
".",
"SelectBlockByTimeRangeSQLNoLimit",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"rows",
",",
"err",
"=",
"stmt",
".",
"QueryContext",
"(",
"ctx",
",",
"minT",
",",
"maxT",
")",
"\n",
"}",
"else",
"{",
"stmt",
",",
"err",
"=",
"db",
".",
"Prepare",
"(",
"internal",
".",
"SelectBlockByTimeRangeSQL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"rows",
",",
"err",
"=",
"stmt",
".",
"QueryContext",
"(",
"ctx",
",",
"minT",
",",
"maxT",
",",
"limit",
")",
"\n",
"}",
"\n",
"_",
"=",
"stmt",
".",
"Close",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Error",
"(",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"closeRows",
"(",
"rows",
")",
"\n\n",
"for",
"rows",
".",
"Next",
"(",
")",
"{",
"var",
"dbBlock",
"dbtypes",
".",
"BlockDataBasic",
"\n",
"var",
"blockTime",
"dbtypes",
".",
"TimeDef",
"\n",
"err",
"=",
"rows",
".",
"Scan",
"(",
"&",
"dbBlock",
".",
"Hash",
",",
"&",
"dbBlock",
".",
"Height",
",",
"&",
"dbBlock",
".",
"Size",
",",
"&",
"blockTime",
",",
"&",
"dbBlock",
".",
"NumTx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"dbBlock",
".",
"Time",
"=",
"blockTime",
"\n",
"blocks",
"=",
"append",
"(",
"blocks",
",",
"dbBlock",
")",
"\n",
"}",
"\n",
"if",
"err",
"=",
"rows",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Error",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"blocks",
",",
"nil",
"\n",
"}"
] | // RetrieveBlockSummaryByTimeRange retrieves the slice of block summaries for
// the given time range. The limit specifies the number of most recent block
// summaries to return. A limit of 0 indicates all blocks in the time range
// should be included. | [
"RetrieveBlockSummaryByTimeRange",
"retrieves",
"the",
"slice",
"of",
"block",
"summaries",
"for",
"the",
"given",
"time",
"range",
".",
"The",
"limit",
"specifies",
"the",
"number",
"of",
"most",
"recent",
"block",
"summaries",
"to",
"return",
".",
"A",
"limit",
"of",
"0",
"indicates",
"all",
"blocks",
"in",
"the",
"time",
"range",
"should",
"be",
"included",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3500-L3546 | train |
decred/dcrdata | db/dcrpg/queries.go | RetrievePreviousHashByBlockHash | func RetrievePreviousHashByBlockHash(ctx context.Context, db *sql.DB, hash string) (previousHash string, err error) {
err = db.QueryRowContext(ctx, internal.SelectBlocksPreviousHash, hash).Scan(&previousHash)
return
} | go | func RetrievePreviousHashByBlockHash(ctx context.Context, db *sql.DB, hash string) (previousHash string, err error) {
err = db.QueryRowContext(ctx, internal.SelectBlocksPreviousHash, hash).Scan(&previousHash)
return
} | [
"func",
"RetrievePreviousHashByBlockHash",
"(",
"ctx",
"context",
".",
"Context",
",",
"db",
"*",
"sql",
".",
"DB",
",",
"hash",
"string",
")",
"(",
"previousHash",
"string",
",",
"err",
"error",
")",
"{",
"err",
"=",
"db",
".",
"QueryRowContext",
"(",
"ctx",
",",
"internal",
".",
"SelectBlocksPreviousHash",
",",
"hash",
")",
".",
"Scan",
"(",
"&",
"previousHash",
")",
"\n",
"return",
"\n",
"}"
] | // RetrievePreviousHashByBlockHash retrieves the previous block hash for the
// given block from the blocks table. | [
"RetrievePreviousHashByBlockHash",
"retrieves",
"the",
"previous",
"block",
"hash",
"for",
"the",
"given",
"block",
"from",
"the",
"blocks",
"table",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3550-L3553 | train |
decred/dcrdata | db/dcrpg/queries.go | SetMainchainByBlockHash | func SetMainchainByBlockHash(db *sql.DB, hash string, isMainchain bool) (previousHash string, err error) {
err = db.QueryRow(internal.UpdateBlockMainchain, hash, isMainchain).Scan(&previousHash)
return
} | go | func SetMainchainByBlockHash(db *sql.DB, hash string, isMainchain bool) (previousHash string, err error) {
err = db.QueryRow(internal.UpdateBlockMainchain, hash, isMainchain).Scan(&previousHash)
return
} | [
"func",
"SetMainchainByBlockHash",
"(",
"db",
"*",
"sql",
".",
"DB",
",",
"hash",
"string",
",",
"isMainchain",
"bool",
")",
"(",
"previousHash",
"string",
",",
"err",
"error",
")",
"{",
"err",
"=",
"db",
".",
"QueryRow",
"(",
"internal",
".",
"UpdateBlockMainchain",
",",
"hash",
",",
"isMainchain",
")",
".",
"Scan",
"(",
"&",
"previousHash",
")",
"\n",
"return",
"\n",
"}"
] | // SetMainchainByBlockHash is used to set the is_mainchain flag for the given
// block. This is required to handle a reoganization. | [
"SetMainchainByBlockHash",
"is",
"used",
"to",
"set",
"the",
"is_mainchain",
"flag",
"for",
"the",
"given",
"block",
".",
"This",
"is",
"required",
"to",
"handle",
"a",
"reoganization",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3557-L3560 | train |
decred/dcrdata | db/dcrpg/queries.go | UpdateVotesMainchain | func UpdateVotesMainchain(db *sql.DB, blockHash string, isMainchain bool) (int64, error) {
numRows, err := sqlExec(db, internal.UpdateVotesMainchainByBlock,
"failed to update votes is_mainchain: ", isMainchain, blockHash)
if err != nil {
return 0, err
}
return numRows, nil
} | go | func UpdateVotesMainchain(db *sql.DB, blockHash string, isMainchain bool) (int64, error) {
numRows, err := sqlExec(db, internal.UpdateVotesMainchainByBlock,
"failed to update votes is_mainchain: ", isMainchain, blockHash)
if err != nil {
return 0, err
}
return numRows, nil
} | [
"func",
"UpdateVotesMainchain",
"(",
"db",
"*",
"sql",
".",
"DB",
",",
"blockHash",
"string",
",",
"isMainchain",
"bool",
")",
"(",
"int64",
",",
"error",
")",
"{",
"numRows",
",",
"err",
":=",
"sqlExec",
"(",
"db",
",",
"internal",
".",
"UpdateVotesMainchainByBlock",
",",
"\"",
"\"",
",",
"isMainchain",
",",
"blockHash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"numRows",
",",
"nil",
"\n",
"}"
] | // UpdateVotesMainchain sets the is_mainchain column for the votes in the
// specified block. | [
"UpdateVotesMainchain",
"sets",
"the",
"is_mainchain",
"column",
"for",
"the",
"votes",
"in",
"the",
"specified",
"block",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3616-L3623 | train |
decred/dcrdata | db/dcrpg/queries.go | UpdateTicketsMainchain | func UpdateTicketsMainchain(db *sql.DB, blockHash string, isMainchain bool) (int64, error) {
numRows, err := sqlExec(db, internal.UpdateTicketsMainchainByBlock,
"failed to update tickets is_mainchain: ", isMainchain, blockHash)
if err != nil {
return 0, err
}
return numRows, nil
} | go | func UpdateTicketsMainchain(db *sql.DB, blockHash string, isMainchain bool) (int64, error) {
numRows, err := sqlExec(db, internal.UpdateTicketsMainchainByBlock,
"failed to update tickets is_mainchain: ", isMainchain, blockHash)
if err != nil {
return 0, err
}
return numRows, nil
} | [
"func",
"UpdateTicketsMainchain",
"(",
"db",
"*",
"sql",
".",
"DB",
",",
"blockHash",
"string",
",",
"isMainchain",
"bool",
")",
"(",
"int64",
",",
"error",
")",
"{",
"numRows",
",",
"err",
":=",
"sqlExec",
"(",
"db",
",",
"internal",
".",
"UpdateTicketsMainchainByBlock",
",",
"\"",
"\"",
",",
"isMainchain",
",",
"blockHash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"numRows",
",",
"nil",
"\n",
"}"
] | // UpdateTicketsMainchain sets the is_mainchain column for the tickets in the
// specified block. | [
"UpdateTicketsMainchain",
"sets",
"the",
"is_mainchain",
"column",
"for",
"the",
"tickets",
"in",
"the",
"specified",
"block",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3627-L3634 | train |
decred/dcrdata | db/dcrpg/queries.go | UpdateLastBlockValid | func UpdateLastBlockValid(db *sql.DB, blockDbID uint64, isValid bool) error {
numRows, err := sqlExec(db, internal.UpdateLastBlockValid,
"failed to update last block validity: ", blockDbID, isValid)
if err != nil {
return err
}
if numRows != 1 {
return fmt.Errorf("UpdateLastBlockValid failed to update exactly 1 row"+
"(%d)", numRows)
}
return nil
} | go | func UpdateLastBlockValid(db *sql.DB, blockDbID uint64, isValid bool) error {
numRows, err := sqlExec(db, internal.UpdateLastBlockValid,
"failed to update last block validity: ", blockDbID, isValid)
if err != nil {
return err
}
if numRows != 1 {
return fmt.Errorf("UpdateLastBlockValid failed to update exactly 1 row"+
"(%d)", numRows)
}
return nil
} | [
"func",
"UpdateLastBlockValid",
"(",
"db",
"*",
"sql",
".",
"DB",
",",
"blockDbID",
"uint64",
",",
"isValid",
"bool",
")",
"error",
"{",
"numRows",
",",
"err",
":=",
"sqlExec",
"(",
"db",
",",
"internal",
".",
"UpdateLastBlockValid",
",",
"\"",
"\"",
",",
"blockDbID",
",",
"isValid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"numRows",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"numRows",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // UpdateLastBlockValid updates the is_valid column of the block specified by
// the row id for the blocks table. | [
"UpdateLastBlockValid",
"updates",
"the",
"is_valid",
"column",
"of",
"the",
"block",
"specified",
"by",
"the",
"row",
"id",
"for",
"the",
"blocks",
"table",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3670-L3681 | train |
decred/dcrdata | db/dcrpg/queries.go | UpdateLastVins | func UpdateLastVins(db *sql.DB, blockHash string, isValid, isMainchain bool) error {
// Retrieve the hash for every transaction in this block. A context with no
// deadline or cancellation function is used since this UpdateLastVins needs
// to complete to ensure DB integrity.
_, txs, _, trees, timestamps, err := RetrieveTxsByBlockHash(context.Background(), db, blockHash)
if err != nil {
return err
}
for i, txHash := range txs {
n, err := sqlExec(db, internal.SetIsValidIsMainchainByTxHash,
"failed to update last vins tx validity: ", isValid, isMainchain,
txHash, timestamps[i], trees[i])
if err != nil {
return err
}
if n < 1 {
return fmt.Errorf(" failed to update at least 1 row")
}
}
return nil
} | go | func UpdateLastVins(db *sql.DB, blockHash string, isValid, isMainchain bool) error {
// Retrieve the hash for every transaction in this block. A context with no
// deadline or cancellation function is used since this UpdateLastVins needs
// to complete to ensure DB integrity.
_, txs, _, trees, timestamps, err := RetrieveTxsByBlockHash(context.Background(), db, blockHash)
if err != nil {
return err
}
for i, txHash := range txs {
n, err := sqlExec(db, internal.SetIsValidIsMainchainByTxHash,
"failed to update last vins tx validity: ", isValid, isMainchain,
txHash, timestamps[i], trees[i])
if err != nil {
return err
}
if n < 1 {
return fmt.Errorf(" failed to update at least 1 row")
}
}
return nil
} | [
"func",
"UpdateLastVins",
"(",
"db",
"*",
"sql",
".",
"DB",
",",
"blockHash",
"string",
",",
"isValid",
",",
"isMainchain",
"bool",
")",
"error",
"{",
"// Retrieve the hash for every transaction in this block. A context with no",
"// deadline or cancellation function is used since this UpdateLastVins needs",
"// to complete to ensure DB integrity.",
"_",
",",
"txs",
",",
"_",
",",
"trees",
",",
"timestamps",
",",
"err",
":=",
"RetrieveTxsByBlockHash",
"(",
"context",
".",
"Background",
"(",
")",
",",
"db",
",",
"blockHash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"txHash",
":=",
"range",
"txs",
"{",
"n",
",",
"err",
":=",
"sqlExec",
"(",
"db",
",",
"internal",
".",
"SetIsValidIsMainchainByTxHash",
",",
"\"",
"\"",
",",
"isValid",
",",
"isMainchain",
",",
"txHash",
",",
"timestamps",
"[",
"i",
"]",
",",
"trees",
"[",
"i",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"n",
"<",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // UpdateLastVins updates the is_valid and is_mainchain columns in the vins
// table for all of the transactions in the block specified by the given block
// hash. | [
"UpdateLastVins",
"updates",
"the",
"is_valid",
"and",
"is_mainchain",
"columns",
"in",
"the",
"vins",
"table",
"for",
"all",
"of",
"the",
"transactions",
"in",
"the",
"block",
"specified",
"by",
"the",
"given",
"block",
"hash",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3686-L3709 | train |
decred/dcrdata | db/dcrpg/queries.go | UpdateBlockNext | func UpdateBlockNext(db SqlExecutor, blockDbID uint64, next string) error {
res, err := db.Exec(internal.UpdateBlockNext, blockDbID, next)
if err != nil {
return err
}
numRows, err := res.RowsAffected()
if err != nil {
return err
}
if numRows != 1 {
return fmt.Errorf("%s (%d)", notOneRowErrMsg, numRows)
}
return nil
} | go | func UpdateBlockNext(db SqlExecutor, blockDbID uint64, next string) error {
res, err := db.Exec(internal.UpdateBlockNext, blockDbID, next)
if err != nil {
return err
}
numRows, err := res.RowsAffected()
if err != nil {
return err
}
if numRows != 1 {
return fmt.Errorf("%s (%d)", notOneRowErrMsg, numRows)
}
return nil
} | [
"func",
"UpdateBlockNext",
"(",
"db",
"SqlExecutor",
",",
"blockDbID",
"uint64",
",",
"next",
"string",
")",
"error",
"{",
"res",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"internal",
".",
"UpdateBlockNext",
",",
"blockDbID",
",",
"next",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"numRows",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"numRows",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"notOneRowErrMsg",
",",
"numRows",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // UpdateBlockNext sets the next block's hash for the specified row of the
// block_chain table specified by DB row ID. | [
"UpdateBlockNext",
"sets",
"the",
"next",
"block",
"s",
"hash",
"for",
"the",
"specified",
"row",
"of",
"the",
"block_chain",
"table",
"specified",
"by",
"DB",
"row",
"ID",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3739-L3752 | train |
decred/dcrdata | db/dcrpg/queries.go | UpdateBlockNextByHash | func UpdateBlockNextByHash(db SqlExecutor, this, next string) error {
res, err := db.Exec(internal.UpdateBlockNextByHash, this, next)
if err != nil {
return err
}
numRows, err := res.RowsAffected()
if err != nil {
return err
}
if numRows != 1 {
return fmt.Errorf("%s (%d)", notOneRowErrMsg, numRows)
}
return nil
} | go | func UpdateBlockNextByHash(db SqlExecutor, this, next string) error {
res, err := db.Exec(internal.UpdateBlockNextByHash, this, next)
if err != nil {
return err
}
numRows, err := res.RowsAffected()
if err != nil {
return err
}
if numRows != 1 {
return fmt.Errorf("%s (%d)", notOneRowErrMsg, numRows)
}
return nil
} | [
"func",
"UpdateBlockNextByHash",
"(",
"db",
"SqlExecutor",
",",
"this",
",",
"next",
"string",
")",
"error",
"{",
"res",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"internal",
".",
"UpdateBlockNextByHash",
",",
"this",
",",
"next",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"numRows",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"numRows",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"notOneRowErrMsg",
",",
"numRows",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // UpdateBlockNextByHash sets the next block's hash for the block in the
// block_chain table specified by hash. | [
"UpdateBlockNextByHash",
"sets",
"the",
"next",
"block",
"s",
"hash",
"for",
"the",
"block",
"in",
"the",
"block_chain",
"table",
"specified",
"by",
"hash",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3756-L3769 | train |
decred/dcrdata | db/dcrpg/queries.go | UpdateBlockNextByNextHash | func UpdateBlockNextByNextHash(db SqlExecutor, currentNext, newNext string) error {
res, err := db.Exec(internal.UpdateBlockNextByNextHash, currentNext, newNext)
if err != nil {
return err
}
numRows, err := res.RowsAffected()
if err != nil {
return err
}
if numRows != 1 {
return fmt.Errorf("%s (%d)", notOneRowErrMsg, numRows)
}
return nil
} | go | func UpdateBlockNextByNextHash(db SqlExecutor, currentNext, newNext string) error {
res, err := db.Exec(internal.UpdateBlockNextByNextHash, currentNext, newNext)
if err != nil {
return err
}
numRows, err := res.RowsAffected()
if err != nil {
return err
}
if numRows != 1 {
return fmt.Errorf("%s (%d)", notOneRowErrMsg, numRows)
}
return nil
} | [
"func",
"UpdateBlockNextByNextHash",
"(",
"db",
"SqlExecutor",
",",
"currentNext",
",",
"newNext",
"string",
")",
"error",
"{",
"res",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"internal",
".",
"UpdateBlockNextByNextHash",
",",
"currentNext",
",",
"newNext",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"numRows",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"numRows",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"notOneRowErrMsg",
",",
"numRows",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // UpdateBlockNextByNextHash sets the next block's hash for the block in the
// block_chain table with a current next_hash specified by hash. | [
"UpdateBlockNextByNextHash",
"sets",
"the",
"next",
"block",
"s",
"hash",
"for",
"the",
"block",
"in",
"the",
"block_chain",
"table",
"with",
"a",
"current",
"next_hash",
"specified",
"by",
"hash",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/queries.go#L3773-L3786 | train |
decred/dcrdata | exchanges/bot.go | copyStates | func copyStates(m map[string]*ExchangeState) map[string]*ExchangeState {
c := make(map[string]*ExchangeState)
for k, v := range m {
c[k] = v
}
return c
} | go | func copyStates(m map[string]*ExchangeState) map[string]*ExchangeState {
c := make(map[string]*ExchangeState)
for k, v := range m {
c[k] = v
}
return c
} | [
"func",
"copyStates",
"(",
"m",
"map",
"[",
"string",
"]",
"*",
"ExchangeState",
")",
"map",
"[",
"string",
"]",
"*",
"ExchangeState",
"{",
"c",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"ExchangeState",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"m",
"{",
"c",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"return",
"c",
"\n",
"}"
] | // Copy an ExchangeState map. | [
"Copy",
"an",
"ExchangeState",
"map",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L107-L113 | train |
decred/dcrdata | exchanges/bot.go | copy | func (state ExchangeBotState) copy() *ExchangeBotState {
state.DcrBtc = copyStates(state.DcrBtc)
state.FiatIndices = copyStates(state.FiatIndices)
return &state
} | go | func (state ExchangeBotState) copy() *ExchangeBotState {
state.DcrBtc = copyStates(state.DcrBtc)
state.FiatIndices = copyStates(state.FiatIndices)
return &state
} | [
"func",
"(",
"state",
"ExchangeBotState",
")",
"copy",
"(",
")",
"*",
"ExchangeBotState",
"{",
"state",
".",
"DcrBtc",
"=",
"copyStates",
"(",
"state",
".",
"DcrBtc",
")",
"\n",
"state",
".",
"FiatIndices",
"=",
"copyStates",
"(",
"state",
".",
"FiatIndices",
")",
"\n",
"return",
"&",
"state",
"\n",
"}"
] | // Creates a pointer to a copy of the ExchangeBotState. | [
"Creates",
"a",
"pointer",
"to",
"a",
"copy",
"of",
"the",
"ExchangeBotState",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L116-L120 | train |
decred/dcrdata | exchanges/bot.go | VolumeOrderedExchanges | func (state *ExchangeBotState) VolumeOrderedExchanges() []*tokenedExchange {
xcList := make([]*tokenedExchange, 0, len(state.DcrBtc))
for token, state := range state.DcrBtc {
xcList = append(xcList, &tokenedExchange{
Token: token,
State: state,
})
}
sort.Slice(xcList, func(i, j int) bool {
return xcList[i].State.Volume > xcList[j].State.Volume
})
return xcList
} | go | func (state *ExchangeBotState) VolumeOrderedExchanges() []*tokenedExchange {
xcList := make([]*tokenedExchange, 0, len(state.DcrBtc))
for token, state := range state.DcrBtc {
xcList = append(xcList, &tokenedExchange{
Token: token,
State: state,
})
}
sort.Slice(xcList, func(i, j int) bool {
return xcList[i].State.Volume > xcList[j].State.Volume
})
return xcList
} | [
"func",
"(",
"state",
"*",
"ExchangeBotState",
")",
"VolumeOrderedExchanges",
"(",
")",
"[",
"]",
"*",
"tokenedExchange",
"{",
"xcList",
":=",
"make",
"(",
"[",
"]",
"*",
"tokenedExchange",
",",
"0",
",",
"len",
"(",
"state",
".",
"DcrBtc",
")",
")",
"\n",
"for",
"token",
",",
"state",
":=",
"range",
"state",
".",
"DcrBtc",
"{",
"xcList",
"=",
"append",
"(",
"xcList",
",",
"&",
"tokenedExchange",
"{",
"Token",
":",
"token",
",",
"State",
":",
"state",
",",
"}",
")",
"\n",
"}",
"\n",
"sort",
".",
"Slice",
"(",
"xcList",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"xcList",
"[",
"i",
"]",
".",
"State",
".",
"Volume",
">",
"xcList",
"[",
"j",
"]",
".",
"State",
".",
"Volume",
"\n",
"}",
")",
"\n",
"return",
"xcList",
"\n",
"}"
] | // VolumeOrderedExchanges returns a list of tokenedExchange sorted by volume,
// highest volume first. | [
"VolumeOrderedExchanges",
"returns",
"a",
"list",
"of",
"tokenedExchange",
"sorted",
"by",
"volume",
"highest",
"volume",
"first",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L137-L149 | train |
decred/dcrdata | exchanges/bot.go | NewUpdateChannels | func NewUpdateChannels() *UpdateChannels {
return &UpdateChannels{
Exchange: make(chan *ExchangeUpdate, 16),
Index: make(chan *IndexUpdate, 16),
Quit: make(chan struct{}),
}
} | go | func NewUpdateChannels() *UpdateChannels {
return &UpdateChannels{
Exchange: make(chan *ExchangeUpdate, 16),
Index: make(chan *IndexUpdate, 16),
Quit: make(chan struct{}),
}
} | [
"func",
"NewUpdateChannels",
"(",
")",
"*",
"UpdateChannels",
"{",
"return",
"&",
"UpdateChannels",
"{",
"Exchange",
":",
"make",
"(",
"chan",
"*",
"ExchangeUpdate",
",",
"16",
")",
",",
"Index",
":",
"make",
"(",
"chan",
"*",
"IndexUpdate",
",",
"16",
")",
",",
"Quit",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"}"
] | // NewUpdateChannels creates a new initialized set of UpdateChannels. | [
"NewUpdateChannels",
"creates",
"a",
"new",
"initialized",
"set",
"of",
"UpdateChannels",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L176-L182 | train |
decred/dcrdata | exchanges/bot.go | connectMasterBot | func (bot *ExchangeBot) connectMasterBot(ctx context.Context, delay time.Duration) (dcrrates.DCRRates_SubscribeExchangesClient, error) {
if bot.masterConnection != nil {
bot.masterConnection.Close()
}
if delay > 0 {
expiration := time.NewTimer(delay)
select {
case <-expiration.C:
case <-ctx.Done():
return nil, fmt.Errorf("Context cancelled before reconnection")
}
}
conn, err := grpc.Dial(bot.config.MasterBot, grpc.WithTransportCredentials(bot.TLSCredentials))
if err != nil {
log.Warnf("gRPC connection error when trying to connect to %s. Falling back to direct connection: %v", bot.config.MasterBot, err)
return nil, err
}
bot.masterConnection = conn
grpcClient := dcrrates.NewDCRRatesClient(conn)
stream, err := grpcClient.SubscribeExchanges(ctx, &dcrrates.ExchangeSubscription{
BtcIndex: bot.BtcIndex,
Exchanges: bot.subscribedExchanges(),
})
if err != nil {
return nil, err
}
return stream, nil
} | go | func (bot *ExchangeBot) connectMasterBot(ctx context.Context, delay time.Duration) (dcrrates.DCRRates_SubscribeExchangesClient, error) {
if bot.masterConnection != nil {
bot.masterConnection.Close()
}
if delay > 0 {
expiration := time.NewTimer(delay)
select {
case <-expiration.C:
case <-ctx.Done():
return nil, fmt.Errorf("Context cancelled before reconnection")
}
}
conn, err := grpc.Dial(bot.config.MasterBot, grpc.WithTransportCredentials(bot.TLSCredentials))
if err != nil {
log.Warnf("gRPC connection error when trying to connect to %s. Falling back to direct connection: %v", bot.config.MasterBot, err)
return nil, err
}
bot.masterConnection = conn
grpcClient := dcrrates.NewDCRRatesClient(conn)
stream, err := grpcClient.SubscribeExchanges(ctx, &dcrrates.ExchangeSubscription{
BtcIndex: bot.BtcIndex,
Exchanges: bot.subscribedExchanges(),
})
if err != nil {
return nil, err
}
return stream, nil
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"connectMasterBot",
"(",
"ctx",
"context",
".",
"Context",
",",
"delay",
"time",
".",
"Duration",
")",
"(",
"dcrrates",
".",
"DCRRates_SubscribeExchangesClient",
",",
"error",
")",
"{",
"if",
"bot",
".",
"masterConnection",
"!=",
"nil",
"{",
"bot",
".",
"masterConnection",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"if",
"delay",
">",
"0",
"{",
"expiration",
":=",
"time",
".",
"NewTimer",
"(",
"delay",
")",
"\n",
"select",
"{",
"case",
"<-",
"expiration",
".",
"C",
":",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"conn",
",",
"err",
":=",
"grpc",
".",
"Dial",
"(",
"bot",
".",
"config",
".",
"MasterBot",
",",
"grpc",
".",
"WithTransportCredentials",
"(",
"bot",
".",
"TLSCredentials",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"bot",
".",
"config",
".",
"MasterBot",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"bot",
".",
"masterConnection",
"=",
"conn",
"\n",
"grpcClient",
":=",
"dcrrates",
".",
"NewDCRRatesClient",
"(",
"conn",
")",
"\n",
"stream",
",",
"err",
":=",
"grpcClient",
".",
"SubscribeExchanges",
"(",
"ctx",
",",
"&",
"dcrrates",
".",
"ExchangeSubscription",
"{",
"BtcIndex",
":",
"bot",
".",
"BtcIndex",
",",
"Exchanges",
":",
"bot",
".",
"subscribedExchanges",
"(",
")",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"stream",
",",
"nil",
"\n",
"}"
] | // Attempt DCRRates connection after delay. | [
"Attempt",
"DCRRates",
"connection",
"after",
"delay",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L462-L489 | train |
decred/dcrdata | exchanges/bot.go | subscribedExchanges | func (bot *ExchangeBot) subscribedExchanges() []string {
xcList := make([]string, len(bot.Exchanges))
for token := range bot.Exchanges {
xcList = append(xcList, token)
}
return xcList
} | go | func (bot *ExchangeBot) subscribedExchanges() []string {
xcList := make([]string, len(bot.Exchanges))
for token := range bot.Exchanges {
xcList = append(xcList, token)
}
return xcList
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"subscribedExchanges",
"(",
")",
"[",
"]",
"string",
"{",
"xcList",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"bot",
".",
"Exchanges",
")",
")",
"\n",
"for",
"token",
":=",
"range",
"bot",
".",
"Exchanges",
"{",
"xcList",
"=",
"append",
"(",
"xcList",
",",
"token",
")",
"\n",
"}",
"\n",
"return",
"xcList",
"\n",
"}"
] | // A list of exchanges which the ExchangeBot is monitoring. | [
"A",
"list",
"of",
"exchanges",
"which",
"the",
"ExchangeBot",
"is",
"monitoring",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L492-L498 | train |
decred/dcrdata | exchanges/bot.go | UpdateChannels | func (bot *ExchangeBot) UpdateChannels() *UpdateChannels {
update := make(chan *ExchangeUpdate, 16)
index := make(chan *IndexUpdate, 16)
quit := make(chan struct{})
bot.mtx.Lock()
defer bot.mtx.Unlock()
bot.updateChans = append(bot.updateChans, update)
bot.indexChans = append(bot.indexChans, index)
bot.quitChans = append(bot.quitChans, quit)
return &UpdateChannels{
Exchange: update,
Index: index,
Quit: quit,
}
} | go | func (bot *ExchangeBot) UpdateChannels() *UpdateChannels {
update := make(chan *ExchangeUpdate, 16)
index := make(chan *IndexUpdate, 16)
quit := make(chan struct{})
bot.mtx.Lock()
defer bot.mtx.Unlock()
bot.updateChans = append(bot.updateChans, update)
bot.indexChans = append(bot.indexChans, index)
bot.quitChans = append(bot.quitChans, quit)
return &UpdateChannels{
Exchange: update,
Index: index,
Quit: quit,
}
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"UpdateChannels",
"(",
")",
"*",
"UpdateChannels",
"{",
"update",
":=",
"make",
"(",
"chan",
"*",
"ExchangeUpdate",
",",
"16",
")",
"\n",
"index",
":=",
"make",
"(",
"chan",
"*",
"IndexUpdate",
",",
"16",
")",
"\n",
"quit",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"bot",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"bot",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"bot",
".",
"updateChans",
"=",
"append",
"(",
"bot",
".",
"updateChans",
",",
"update",
")",
"\n",
"bot",
".",
"indexChans",
"=",
"append",
"(",
"bot",
".",
"indexChans",
",",
"index",
")",
"\n",
"bot",
".",
"quitChans",
"=",
"append",
"(",
"bot",
".",
"quitChans",
",",
"quit",
")",
"\n",
"return",
"&",
"UpdateChannels",
"{",
"Exchange",
":",
"update",
",",
"Index",
":",
"index",
",",
"Quit",
":",
"quit",
",",
"}",
"\n",
"}"
] | // UpdateChannels creates an UpdateChannels, which holds a channel to receive
// exchange updates and a channel which is closed when the start loop exits. | [
"UpdateChannels",
"creates",
"an",
"UpdateChannels",
"which",
"holds",
"a",
"channel",
"to",
"receive",
"exchange",
"updates",
"and",
"a",
"channel",
"which",
"is",
"closed",
"when",
"the",
"start",
"loop",
"exits",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L502-L516 | train |
decred/dcrdata | exchanges/bot.go | ConvertedState | func (bot *ExchangeBot) ConvertedState(code string) (*ExchangeBotState, error) {
bot.mtx.RLock()
defer bot.mtx.RUnlock()
fiatIndices := make(map[string]*ExchangeState)
for token, indices := range bot.indexMap {
for symbol, price := range indices {
if symbol == code {
fiatIndices[token] = &ExchangeState{Price: price}
}
}
}
dcrPrice, volume := bot.processState(bot.currentState.DcrBtc, true)
btcPrice, _ := bot.processState(fiatIndices, false)
if dcrPrice == 0 || btcPrice == 0 {
bot.failed = true
return nil, fmt.Errorf("Unable to process price for currency %s", code)
}
state := ExchangeBotState{
BtcIndex: code,
Volume: volume * btcPrice,
Price: dcrPrice * btcPrice,
DcrBtc: bot.currentState.DcrBtc,
FiatIndices: fiatIndices,
}
return state.copy(), nil
} | go | func (bot *ExchangeBot) ConvertedState(code string) (*ExchangeBotState, error) {
bot.mtx.RLock()
defer bot.mtx.RUnlock()
fiatIndices := make(map[string]*ExchangeState)
for token, indices := range bot.indexMap {
for symbol, price := range indices {
if symbol == code {
fiatIndices[token] = &ExchangeState{Price: price}
}
}
}
dcrPrice, volume := bot.processState(bot.currentState.DcrBtc, true)
btcPrice, _ := bot.processState(fiatIndices, false)
if dcrPrice == 0 || btcPrice == 0 {
bot.failed = true
return nil, fmt.Errorf("Unable to process price for currency %s", code)
}
state := ExchangeBotState{
BtcIndex: code,
Volume: volume * btcPrice,
Price: dcrPrice * btcPrice,
DcrBtc: bot.currentState.DcrBtc,
FiatIndices: fiatIndices,
}
return state.copy(), nil
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"ConvertedState",
"(",
"code",
"string",
")",
"(",
"*",
"ExchangeBotState",
",",
"error",
")",
"{",
"bot",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"bot",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"fiatIndices",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"ExchangeState",
")",
"\n",
"for",
"token",
",",
"indices",
":=",
"range",
"bot",
".",
"indexMap",
"{",
"for",
"symbol",
",",
"price",
":=",
"range",
"indices",
"{",
"if",
"symbol",
"==",
"code",
"{",
"fiatIndices",
"[",
"token",
"]",
"=",
"&",
"ExchangeState",
"{",
"Price",
":",
"price",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"dcrPrice",
",",
"volume",
":=",
"bot",
".",
"processState",
"(",
"bot",
".",
"currentState",
".",
"DcrBtc",
",",
"true",
")",
"\n",
"btcPrice",
",",
"_",
":=",
"bot",
".",
"processState",
"(",
"fiatIndices",
",",
"false",
")",
"\n",
"if",
"dcrPrice",
"==",
"0",
"||",
"btcPrice",
"==",
"0",
"{",
"bot",
".",
"failed",
"=",
"true",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"code",
")",
"\n",
"}",
"\n\n",
"state",
":=",
"ExchangeBotState",
"{",
"BtcIndex",
":",
"code",
",",
"Volume",
":",
"volume",
"*",
"btcPrice",
",",
"Price",
":",
"dcrPrice",
"*",
"btcPrice",
",",
"DcrBtc",
":",
"bot",
".",
"currentState",
".",
"DcrBtc",
",",
"FiatIndices",
":",
"fiatIndices",
",",
"}",
"\n\n",
"return",
"state",
".",
"copy",
"(",
")",
",",
"nil",
"\n",
"}"
] | // ConvertedState returns an ExchangeBotState with a base of the provided
// currency code, if available. | [
"ConvertedState",
"returns",
"an",
"ExchangeBotState",
"with",
"a",
"base",
"of",
"the",
"provided",
"currency",
"code",
"if",
"available",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L548-L576 | train |
decred/dcrdata | exchanges/bot.go | StateBytes | func (bot *ExchangeBot) StateBytes() []byte {
bot.mtx.RLock()
defer bot.mtx.RUnlock()
return bot.currentStateBytes
} | go | func (bot *ExchangeBot) StateBytes() []byte {
bot.mtx.RLock()
defer bot.mtx.RUnlock()
return bot.currentStateBytes
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"StateBytes",
"(",
")",
"[",
"]",
"byte",
"{",
"bot",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"bot",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"bot",
".",
"currentStateBytes",
"\n",
"}"
] | // StateBytes is a JSON-encoded byte array of the currentState. | [
"StateBytes",
"is",
"a",
"JSON",
"-",
"encoded",
"byte",
"array",
"of",
"the",
"currentState",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L579-L583 | train |
decred/dcrdata | exchanges/bot.go | ConvertedStateBytes | func (bot *ExchangeBot) ConvertedStateBytes(symbol string) ([]byte, error) {
state, err := bot.ConvertedState(symbol)
if err != nil {
return nil, err
}
return bot.jsonify(state)
} | go | func (bot *ExchangeBot) ConvertedStateBytes(symbol string) ([]byte, error) {
state, err := bot.ConvertedState(symbol)
if err != nil {
return nil, err
}
return bot.jsonify(state)
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"ConvertedStateBytes",
"(",
"symbol",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"state",
",",
"err",
":=",
"bot",
".",
"ConvertedState",
"(",
"symbol",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"bot",
".",
"jsonify",
"(",
"state",
")",
"\n",
"}"
] | // ConvertedStateBytes gives a JSON-encoded byte array of the currentState
// with a base of the provided currency code, if available. | [
"ConvertedStateBytes",
"gives",
"a",
"JSON",
"-",
"encoded",
"byte",
"array",
"of",
"the",
"currentState",
"with",
"a",
"base",
"of",
"the",
"provided",
"currency",
"code",
"if",
"available",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L594-L600 | train |
decred/dcrdata | exchanges/bot.go | AvailableIndices | func (bot *ExchangeBot) AvailableIndices() []string {
bot.mtx.RLock()
defer bot.mtx.RUnlock()
var indices sort.StringSlice
add := func(index string) {
for _, symbol := range indices {
if symbol == index {
return
}
}
indices = append(indices, index)
}
for _, fiatIndices := range bot.indexMap {
for symbol := range fiatIndices {
add(symbol)
}
}
sort.Sort(indices)
return indices
} | go | func (bot *ExchangeBot) AvailableIndices() []string {
bot.mtx.RLock()
defer bot.mtx.RUnlock()
var indices sort.StringSlice
add := func(index string) {
for _, symbol := range indices {
if symbol == index {
return
}
}
indices = append(indices, index)
}
for _, fiatIndices := range bot.indexMap {
for symbol := range fiatIndices {
add(symbol)
}
}
sort.Sort(indices)
return indices
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"AvailableIndices",
"(",
")",
"[",
"]",
"string",
"{",
"bot",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"bot",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"var",
"indices",
"sort",
".",
"StringSlice",
"\n",
"add",
":=",
"func",
"(",
"index",
"string",
")",
"{",
"for",
"_",
",",
"symbol",
":=",
"range",
"indices",
"{",
"if",
"symbol",
"==",
"index",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"indices",
"=",
"append",
"(",
"indices",
",",
"index",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"fiatIndices",
":=",
"range",
"bot",
".",
"indexMap",
"{",
"for",
"symbol",
":=",
"range",
"fiatIndices",
"{",
"add",
"(",
"symbol",
")",
"\n",
"}",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"indices",
")",
"\n",
"return",
"indices",
"\n",
"}"
] | // AvailableIndices creates a fresh slice of all available index currency codes. | [
"AvailableIndices",
"creates",
"a",
"fresh",
"slice",
"of",
"all",
"available",
"index",
"currency",
"codes",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L603-L622 | train |
decred/dcrdata | exchanges/bot.go | Indices | func (bot *ExchangeBot) Indices(token string) FiatIndices {
bot.mtx.RLock()
defer bot.mtx.RUnlock()
indices := make(FiatIndices)
for code, price := range bot.indexMap[token] {
indices[code] = price
}
return indices
} | go | func (bot *ExchangeBot) Indices(token string) FiatIndices {
bot.mtx.RLock()
defer bot.mtx.RUnlock()
indices := make(FiatIndices)
for code, price := range bot.indexMap[token] {
indices[code] = price
}
return indices
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"Indices",
"(",
"token",
"string",
")",
"FiatIndices",
"{",
"bot",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"bot",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"indices",
":=",
"make",
"(",
"FiatIndices",
")",
"\n",
"for",
"code",
",",
"price",
":=",
"range",
"bot",
".",
"indexMap",
"[",
"token",
"]",
"{",
"indices",
"[",
"code",
"]",
"=",
"price",
"\n",
"}",
"\n",
"return",
"indices",
"\n",
"}"
] | // Indices is the fiat indices for a given BTC index exchange. | [
"Indices",
"is",
"the",
"fiat",
"indices",
"for",
"a",
"given",
"BTC",
"index",
"exchange",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L625-L633 | train |
decred/dcrdata | exchanges/bot.go | processState | func (bot *ExchangeBot) processState(states map[string]*ExchangeState, volumeAveraged bool) (float64, float64) {
var priceAccumulator, volSum float64
var deletions []string
oldestValid := time.Now().Add(-bot.RequestExpiry)
for token, state := range states {
if bot.Exchanges[token].LastUpdate().Before(oldestValid) {
deletions = append(deletions, token)
continue
}
volume := 1.0
if volumeAveraged {
volume = state.Volume
}
volSum += volume
priceAccumulator += volume * state.Price
}
for _, token := range deletions {
delete(states, token)
}
if volSum == 0 {
return 0, 0
}
return priceAccumulator / volSum, volSum
} | go | func (bot *ExchangeBot) processState(states map[string]*ExchangeState, volumeAveraged bool) (float64, float64) {
var priceAccumulator, volSum float64
var deletions []string
oldestValid := time.Now().Add(-bot.RequestExpiry)
for token, state := range states {
if bot.Exchanges[token].LastUpdate().Before(oldestValid) {
deletions = append(deletions, token)
continue
}
volume := 1.0
if volumeAveraged {
volume = state.Volume
}
volSum += volume
priceAccumulator += volume * state.Price
}
for _, token := range deletions {
delete(states, token)
}
if volSum == 0 {
return 0, 0
}
return priceAccumulator / volSum, volSum
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"processState",
"(",
"states",
"map",
"[",
"string",
"]",
"*",
"ExchangeState",
",",
"volumeAveraged",
"bool",
")",
"(",
"float64",
",",
"float64",
")",
"{",
"var",
"priceAccumulator",
",",
"volSum",
"float64",
"\n",
"var",
"deletions",
"[",
"]",
"string",
"\n",
"oldestValid",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"-",
"bot",
".",
"RequestExpiry",
")",
"\n",
"for",
"token",
",",
"state",
":=",
"range",
"states",
"{",
"if",
"bot",
".",
"Exchanges",
"[",
"token",
"]",
".",
"LastUpdate",
"(",
")",
".",
"Before",
"(",
"oldestValid",
")",
"{",
"deletions",
"=",
"append",
"(",
"deletions",
",",
"token",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"volume",
":=",
"1.0",
"\n",
"if",
"volumeAveraged",
"{",
"volume",
"=",
"state",
".",
"Volume",
"\n",
"}",
"\n",
"volSum",
"+=",
"volume",
"\n",
"priceAccumulator",
"+=",
"volume",
"*",
"state",
".",
"Price",
"\n",
"}",
"\n",
"for",
"_",
",",
"token",
":=",
"range",
"deletions",
"{",
"delete",
"(",
"states",
",",
"token",
")",
"\n",
"}",
"\n",
"if",
"volSum",
"==",
"0",
"{",
"return",
"0",
",",
"0",
"\n",
"}",
"\n",
"return",
"priceAccumulator",
"/",
"volSum",
",",
"volSum",
"\n",
"}"
] | // processState is a helper function to process a slice of ExchangeState into
// a price, and optionally a volume sum, and perform some cleanup along the way.
// If volumeAveraged is false, all exchanges are given equal weight in the avg. | [
"processState",
"is",
"a",
"helper",
"function",
"to",
"process",
"a",
"slice",
"of",
"ExchangeState",
"into",
"a",
"price",
"and",
"optionally",
"a",
"volume",
"sum",
"and",
"perform",
"some",
"cleanup",
"along",
"the",
"way",
".",
"If",
"volumeAveraged",
"is",
"false",
"all",
"exchanges",
"are",
"given",
"equal",
"weight",
"in",
"the",
"avg",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L655-L678 | train |
decred/dcrdata | exchanges/bot.go | updateExchange | func (bot *ExchangeBot) updateExchange(update *ExchangeUpdate) error {
bot.mtx.Lock()
defer bot.mtx.Unlock()
if update.State.Candlesticks != nil {
for bin := range update.State.Candlesticks {
bot.incrementChart(genCacheID(update.Token, string(bin)))
}
}
if update.State.Depth != nil {
bot.incrementChart(genCacheID(update.Token, "depth"))
}
bot.currentState.DcrBtc[update.Token] = update.State
return bot.updateState()
} | go | func (bot *ExchangeBot) updateExchange(update *ExchangeUpdate) error {
bot.mtx.Lock()
defer bot.mtx.Unlock()
if update.State.Candlesticks != nil {
for bin := range update.State.Candlesticks {
bot.incrementChart(genCacheID(update.Token, string(bin)))
}
}
if update.State.Depth != nil {
bot.incrementChart(genCacheID(update.Token, "depth"))
}
bot.currentState.DcrBtc[update.Token] = update.State
return bot.updateState()
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"updateExchange",
"(",
"update",
"*",
"ExchangeUpdate",
")",
"error",
"{",
"bot",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"bot",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"if",
"update",
".",
"State",
".",
"Candlesticks",
"!=",
"nil",
"{",
"for",
"bin",
":=",
"range",
"update",
".",
"State",
".",
"Candlesticks",
"{",
"bot",
".",
"incrementChart",
"(",
"genCacheID",
"(",
"update",
".",
"Token",
",",
"string",
"(",
"bin",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"update",
".",
"State",
".",
"Depth",
"!=",
"nil",
"{",
"bot",
".",
"incrementChart",
"(",
"genCacheID",
"(",
"update",
".",
"Token",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"bot",
".",
"currentState",
".",
"DcrBtc",
"[",
"update",
".",
"Token",
"]",
"=",
"update",
".",
"State",
"\n",
"return",
"bot",
".",
"updateState",
"(",
")",
"\n",
"}"
] | // updateExchange processes an update from a Decred-BTC Exchange. | [
"updateExchange",
"processes",
"an",
"update",
"from",
"a",
"Decred",
"-",
"BTC",
"Exchange",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L681-L694 | train |
decred/dcrdata | exchanges/bot.go | updateIndices | func (bot *ExchangeBot) updateIndices(update *IndexUpdate) error {
bot.mtx.Lock()
defer bot.mtx.Unlock()
bot.indexMap[update.Token] = update.Indices
price, hasCode := update.Indices[bot.config.BtcIndex]
if hasCode {
bot.currentState.FiatIndices[update.Token] = &ExchangeState{
Price: price,
Stamp: time.Now().Unix(),
}
return bot.updateState()
}
log.Warnf("Default currency code, %s, not contained in update from %s", bot.BtcIndex, update.Token)
return nil
} | go | func (bot *ExchangeBot) updateIndices(update *IndexUpdate) error {
bot.mtx.Lock()
defer bot.mtx.Unlock()
bot.indexMap[update.Token] = update.Indices
price, hasCode := update.Indices[bot.config.BtcIndex]
if hasCode {
bot.currentState.FiatIndices[update.Token] = &ExchangeState{
Price: price,
Stamp: time.Now().Unix(),
}
return bot.updateState()
}
log.Warnf("Default currency code, %s, not contained in update from %s", bot.BtcIndex, update.Token)
return nil
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"updateIndices",
"(",
"update",
"*",
"IndexUpdate",
")",
"error",
"{",
"bot",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"bot",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"bot",
".",
"indexMap",
"[",
"update",
".",
"Token",
"]",
"=",
"update",
".",
"Indices",
"\n",
"price",
",",
"hasCode",
":=",
"update",
".",
"Indices",
"[",
"bot",
".",
"config",
".",
"BtcIndex",
"]",
"\n",
"if",
"hasCode",
"{",
"bot",
".",
"currentState",
".",
"FiatIndices",
"[",
"update",
".",
"Token",
"]",
"=",
"&",
"ExchangeState",
"{",
"Price",
":",
"price",
",",
"Stamp",
":",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
",",
"}",
"\n",
"return",
"bot",
".",
"updateState",
"(",
")",
"\n",
"}",
"\n",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"bot",
".",
"BtcIndex",
",",
"update",
".",
"Token",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // updateIndices processes an update from an Bitcoin index source, essentially
// a map pairing currency codes to bitcoin prices. | [
"updateIndices",
"processes",
"an",
"update",
"from",
"an",
"Bitcoin",
"index",
"source",
"essentially",
"a",
"map",
"pairing",
"currency",
"codes",
"to",
"bitcoin",
"prices",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L698-L712 | train |
decred/dcrdata | exchanges/bot.go | nextTick | func (bot *ExchangeBot) nextTick() *time.Timer {
tNow := time.Now()
tOldest := tNow
for _, xc := range bot.Exchanges {
t := xc.LastTry()
if t.Before(tOldest) {
tOldest = t
}
}
tSince := tNow.Sub(tOldest)
tilNext := bot.DataExpiry - tSince
if tilNext < bot.minTick {
tilNext = bot.minTick
}
return time.NewTimer(tilNext)
} | go | func (bot *ExchangeBot) nextTick() *time.Timer {
tNow := time.Now()
tOldest := tNow
for _, xc := range bot.Exchanges {
t := xc.LastTry()
if t.Before(tOldest) {
tOldest = t
}
}
tSince := tNow.Sub(tOldest)
tilNext := bot.DataExpiry - tSince
if tilNext < bot.minTick {
tilNext = bot.minTick
}
return time.NewTimer(tilNext)
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"nextTick",
"(",
")",
"*",
"time",
".",
"Timer",
"{",
"tNow",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"tOldest",
":=",
"tNow",
"\n",
"for",
"_",
",",
"xc",
":=",
"range",
"bot",
".",
"Exchanges",
"{",
"t",
":=",
"xc",
".",
"LastTry",
"(",
")",
"\n",
"if",
"t",
".",
"Before",
"(",
"tOldest",
")",
"{",
"tOldest",
"=",
"t",
"\n",
"}",
"\n",
"}",
"\n",
"tSince",
":=",
"tNow",
".",
"Sub",
"(",
"tOldest",
")",
"\n",
"tilNext",
":=",
"bot",
".",
"DataExpiry",
"-",
"tSince",
"\n",
"if",
"tilNext",
"<",
"bot",
".",
"minTick",
"{",
"tilNext",
"=",
"bot",
".",
"minTick",
"\n",
"}",
"\n",
"return",
"time",
".",
"NewTimer",
"(",
"tilNext",
")",
"\n",
"}"
] | // nextTick checks the exchanges' last update and fail times, and calculates
// when the next Cycle should run. | [
"nextTick",
"checks",
"the",
"exchanges",
"last",
"update",
"and",
"fail",
"times",
"and",
"calculates",
"when",
"the",
"next",
"Cycle",
"should",
"run",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L756-L771 | train |
decred/dcrdata | exchanges/bot.go | Cycle | func (bot *ExchangeBot) Cycle() {
tNow := time.Now()
for _, xc := range bot.Exchanges {
if tNow.Sub(xc.LastTry()) > bot.DataExpiry {
go xc.Refresh()
}
}
} | go | func (bot *ExchangeBot) Cycle() {
tNow := time.Now()
for _, xc := range bot.Exchanges {
if tNow.Sub(xc.LastTry()) > bot.DataExpiry {
go xc.Refresh()
}
}
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"Cycle",
"(",
")",
"{",
"tNow",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"for",
"_",
",",
"xc",
":=",
"range",
"bot",
".",
"Exchanges",
"{",
"if",
"tNow",
".",
"Sub",
"(",
"xc",
".",
"LastTry",
"(",
")",
")",
">",
"bot",
".",
"DataExpiry",
"{",
"go",
"xc",
".",
"Refresh",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Cycle refreshes all expired exchanges. | [
"Cycle",
"refreshes",
"all",
"expired",
"exchanges",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L774-L781 | train |
decred/dcrdata | exchanges/bot.go | TwoDecimals | func (c *Conversion) TwoDecimals() string {
if c.Value == 0.0 {
return "0.00"
} else if c.Value < 1.0 && c.Value > -1.0 {
return fmt.Sprintf("%3g", c.Value)
}
return fmt.Sprintf("%.2f", c.Value)
} | go | func (c *Conversion) TwoDecimals() string {
if c.Value == 0.0 {
return "0.00"
} else if c.Value < 1.0 && c.Value > -1.0 {
return fmt.Sprintf("%3g", c.Value)
}
return fmt.Sprintf("%.2f", c.Value)
} | [
"func",
"(",
"c",
"*",
"Conversion",
")",
"TwoDecimals",
"(",
")",
"string",
"{",
"if",
"c",
".",
"Value",
"==",
"0.0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"else",
"if",
"c",
".",
"Value",
"<",
"1.0",
"&&",
"c",
".",
"Value",
">",
"-",
"1.0",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"Value",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"Value",
")",
"\n",
"}"
] | // TwoDecimals is a string representation of the value with two digits after
// the decimal point, but will show more to achieve at least three significant
// digits. | [
"TwoDecimals",
"is",
"a",
"string",
"representation",
"of",
"the",
"value",
"with",
"two",
"digits",
"after",
"the",
"decimal",
"point",
"but",
"will",
"show",
"more",
"to",
"achieve",
"at",
"least",
"three",
"significant",
"digits",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L799-L806 | train |
decred/dcrdata | exchanges/bot.go | Conversion | func (bot *ExchangeBot) Conversion(dcrVal float64) *Conversion {
if bot == nil {
return nil
}
xcState := bot.State()
if xcState != nil {
return &Conversion{
Value: xcState.Price * dcrVal,
Index: xcState.BtcIndex,
}
}
return nil
} | go | func (bot *ExchangeBot) Conversion(dcrVal float64) *Conversion {
if bot == nil {
return nil
}
xcState := bot.State()
if xcState != nil {
return &Conversion{
Value: xcState.Price * dcrVal,
Index: xcState.BtcIndex,
}
}
return nil
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"Conversion",
"(",
"dcrVal",
"float64",
")",
"*",
"Conversion",
"{",
"if",
"bot",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"xcState",
":=",
"bot",
".",
"State",
"(",
")",
"\n",
"if",
"xcState",
"!=",
"nil",
"{",
"return",
"&",
"Conversion",
"{",
"Value",
":",
"xcState",
".",
"Price",
"*",
"dcrVal",
",",
"Index",
":",
"xcState",
".",
"BtcIndex",
",",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Conversion attempts to multiply the supplied float with the default index.
// Nil pointer will be returned if there is no valid exchangeState. | [
"Conversion",
"attempts",
"to",
"multiply",
"the",
"supplied",
"float",
"with",
"the",
"default",
"index",
".",
"Nil",
"pointer",
"will",
"be",
"returned",
"if",
"there",
"is",
"no",
"valid",
"exchangeState",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L810-L822 | train |
decred/dcrdata | exchanges/bot.go | QuickSticks | func (bot *ExchangeBot) QuickSticks(token string, rawBin string) ([]byte, error) {
chartID := genCacheID(token, rawBin)
bin := candlestickKey(rawBin)
data, bestVersion, isGood := bot.fetchFromCache(chartID)
if isGood {
return data, nil
}
// No hit on cache. Re-encode.
bot.mtx.Lock()
defer bot.mtx.Unlock()
state, found := bot.currentState.DcrBtc[token]
if !found {
return nil, fmt.Errorf("Failed to find DCR exchange state for %s", token)
}
if state.Candlesticks == nil {
return nil, fmt.Errorf("Failed to find candlesticks for %s", token)
}
sticks, found := state.Candlesticks[bin]
if !found {
return nil, fmt.Errorf("Failed to find candlesticks for %s and bin %s", token, rawBin)
}
if len(sticks) == 0 {
return nil, fmt.Errorf("Empty candlesticks for %s and bin %s", token, rawBin)
}
expiration := sticks[len(sticks)-1].Start.Add(2 * bin.duration())
chart, err := bot.jsonify(&candlestickResponse{
BtcIndex: bot.BtcIndex,
Price: bot.currentState.Price,
Sticks: sticks,
Expiration: expiration.Unix(),
})
if err != nil {
return nil, fmt.Errorf("JSON encode error for %s and bin %s", token, rawBin)
}
vChart := &versionedChart{
chartID: chartID,
dataID: bestVersion,
time: expiration,
chart: chart,
}
bot.versionedCharts[chartID] = vChart
return vChart.chart, nil
} | go | func (bot *ExchangeBot) QuickSticks(token string, rawBin string) ([]byte, error) {
chartID := genCacheID(token, rawBin)
bin := candlestickKey(rawBin)
data, bestVersion, isGood := bot.fetchFromCache(chartID)
if isGood {
return data, nil
}
// No hit on cache. Re-encode.
bot.mtx.Lock()
defer bot.mtx.Unlock()
state, found := bot.currentState.DcrBtc[token]
if !found {
return nil, fmt.Errorf("Failed to find DCR exchange state for %s", token)
}
if state.Candlesticks == nil {
return nil, fmt.Errorf("Failed to find candlesticks for %s", token)
}
sticks, found := state.Candlesticks[bin]
if !found {
return nil, fmt.Errorf("Failed to find candlesticks for %s and bin %s", token, rawBin)
}
if len(sticks) == 0 {
return nil, fmt.Errorf("Empty candlesticks for %s and bin %s", token, rawBin)
}
expiration := sticks[len(sticks)-1].Start.Add(2 * bin.duration())
chart, err := bot.jsonify(&candlestickResponse{
BtcIndex: bot.BtcIndex,
Price: bot.currentState.Price,
Sticks: sticks,
Expiration: expiration.Unix(),
})
if err != nil {
return nil, fmt.Errorf("JSON encode error for %s and bin %s", token, rawBin)
}
vChart := &versionedChart{
chartID: chartID,
dataID: bestVersion,
time: expiration,
chart: chart,
}
bot.versionedCharts[chartID] = vChart
return vChart.chart, nil
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"QuickSticks",
"(",
"token",
"string",
",",
"rawBin",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"chartID",
":=",
"genCacheID",
"(",
"token",
",",
"rawBin",
")",
"\n",
"bin",
":=",
"candlestickKey",
"(",
"rawBin",
")",
"\n",
"data",
",",
"bestVersion",
",",
"isGood",
":=",
"bot",
".",
"fetchFromCache",
"(",
"chartID",
")",
"\n",
"if",
"isGood",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n\n",
"// No hit on cache. Re-encode.",
"bot",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"bot",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"state",
",",
"found",
":=",
"bot",
".",
"currentState",
".",
"DcrBtc",
"[",
"token",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"token",
")",
"\n",
"}",
"\n",
"if",
"state",
".",
"Candlesticks",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"token",
")",
"\n",
"}",
"\n\n",
"sticks",
",",
"found",
":=",
"state",
".",
"Candlesticks",
"[",
"bin",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"token",
",",
"rawBin",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"sticks",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"token",
",",
"rawBin",
")",
"\n",
"}",
"\n\n",
"expiration",
":=",
"sticks",
"[",
"len",
"(",
"sticks",
")",
"-",
"1",
"]",
".",
"Start",
".",
"Add",
"(",
"2",
"*",
"bin",
".",
"duration",
"(",
")",
")",
"\n\n",
"chart",
",",
"err",
":=",
"bot",
".",
"jsonify",
"(",
"&",
"candlestickResponse",
"{",
"BtcIndex",
":",
"bot",
".",
"BtcIndex",
",",
"Price",
":",
"bot",
".",
"currentState",
".",
"Price",
",",
"Sticks",
":",
"sticks",
",",
"Expiration",
":",
"expiration",
".",
"Unix",
"(",
")",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"token",
",",
"rawBin",
")",
"\n",
"}",
"\n\n",
"vChart",
":=",
"&",
"versionedChart",
"{",
"chartID",
":",
"chartID",
",",
"dataID",
":",
"bestVersion",
",",
"time",
":",
"expiration",
",",
"chart",
":",
"chart",
",",
"}",
"\n\n",
"bot",
".",
"versionedCharts",
"[",
"chartID",
"]",
"=",
"vChart",
"\n",
"return",
"vChart",
".",
"chart",
",",
"nil",
"\n",
"}"
] | // QuickSticks returns the up-to-date candlestick data for the specified
// exchange and bin width, pulling from the cache if appropriate. | [
"QuickSticks",
"returns",
"the",
"up",
"-",
"to",
"-",
"date",
"candlestick",
"data",
"for",
"the",
"specified",
"exchange",
"and",
"bin",
"width",
"pulling",
"from",
"the",
"cache",
"if",
"appropriate",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L841-L890 | train |
decred/dcrdata | exchanges/bot.go | QuickDepth | func (bot *ExchangeBot) QuickDepth(token string) ([]byte, error) {
chartID := genCacheID(token, "depth")
data, bestVersion, isGood := bot.fetchFromCache(chartID)
if isGood {
return data, nil
}
// No hit on cache. Re-encode.
bot.mtx.Lock()
defer bot.mtx.Unlock()
state, found := bot.currentState.DcrBtc[token]
if !found {
return []byte{}, fmt.Errorf("Failed to find DCR exchange state for %s", token)
}
if state.Depth == nil {
return []byte{}, fmt.Errorf("Failed to find depth for %s", token)
}
chart, err := bot.jsonify(&depthResponse{
BtcIndex: bot.BtcIndex,
Price: bot.currentState.Price,
Data: state.Depth,
Expiration: state.Depth.Time + int64(bot.RequestExpiry.Seconds()),
})
if err != nil {
return []byte{}, fmt.Errorf("JSON encode error for %s depth chart", token)
}
vChart := &versionedChart{
chartID: chartID,
dataID: bestVersion,
time: time.Unix(state.Depth.Time, 0),
chart: chart,
}
bot.versionedCharts[chartID] = vChart
return vChart.chart, nil
} | go | func (bot *ExchangeBot) QuickDepth(token string) ([]byte, error) {
chartID := genCacheID(token, "depth")
data, bestVersion, isGood := bot.fetchFromCache(chartID)
if isGood {
return data, nil
}
// No hit on cache. Re-encode.
bot.mtx.Lock()
defer bot.mtx.Unlock()
state, found := bot.currentState.DcrBtc[token]
if !found {
return []byte{}, fmt.Errorf("Failed to find DCR exchange state for %s", token)
}
if state.Depth == nil {
return []byte{}, fmt.Errorf("Failed to find depth for %s", token)
}
chart, err := bot.jsonify(&depthResponse{
BtcIndex: bot.BtcIndex,
Price: bot.currentState.Price,
Data: state.Depth,
Expiration: state.Depth.Time + int64(bot.RequestExpiry.Seconds()),
})
if err != nil {
return []byte{}, fmt.Errorf("JSON encode error for %s depth chart", token)
}
vChart := &versionedChart{
chartID: chartID,
dataID: bestVersion,
time: time.Unix(state.Depth.Time, 0),
chart: chart,
}
bot.versionedCharts[chartID] = vChart
return vChart.chart, nil
} | [
"func",
"(",
"bot",
"*",
"ExchangeBot",
")",
"QuickDepth",
"(",
"token",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"chartID",
":=",
"genCacheID",
"(",
"token",
",",
"\"",
"\"",
")",
"\n",
"data",
",",
"bestVersion",
",",
"isGood",
":=",
"bot",
".",
"fetchFromCache",
"(",
"chartID",
")",
"\n",
"if",
"isGood",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n\n",
"// No hit on cache. Re-encode.",
"bot",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"bot",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"state",
",",
"found",
":=",
"bot",
".",
"currentState",
".",
"DcrBtc",
"[",
"token",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"[",
"]",
"byte",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"token",
")",
"\n",
"}",
"\n",
"if",
"state",
".",
"Depth",
"==",
"nil",
"{",
"return",
"[",
"]",
"byte",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"token",
")",
"\n",
"}",
"\n",
"chart",
",",
"err",
":=",
"bot",
".",
"jsonify",
"(",
"&",
"depthResponse",
"{",
"BtcIndex",
":",
"bot",
".",
"BtcIndex",
",",
"Price",
":",
"bot",
".",
"currentState",
".",
"Price",
",",
"Data",
":",
"state",
".",
"Depth",
",",
"Expiration",
":",
"state",
".",
"Depth",
".",
"Time",
"+",
"int64",
"(",
"bot",
".",
"RequestExpiry",
".",
"Seconds",
"(",
")",
")",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"[",
"]",
"byte",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"token",
")",
"\n",
"}",
"\n\n",
"vChart",
":=",
"&",
"versionedChart",
"{",
"chartID",
":",
"chartID",
",",
"dataID",
":",
"bestVersion",
",",
"time",
":",
"time",
".",
"Unix",
"(",
"state",
".",
"Depth",
".",
"Time",
",",
"0",
")",
",",
"chart",
":",
"chart",
",",
"}",
"\n\n",
"bot",
".",
"versionedCharts",
"[",
"chartID",
"]",
"=",
"vChart",
"\n",
"return",
"vChart",
".",
"chart",
",",
"nil",
"\n",
"}"
] | // QuickDepth returns the up-to-date depth chart data for the specified
// exchange, pulling from the cache if appropriate. | [
"QuickDepth",
"returns",
"the",
"up",
"-",
"to",
"-",
"date",
"depth",
"chart",
"data",
"for",
"the",
"specified",
"exchange",
"pulling",
"from",
"the",
"cache",
"if",
"appropriate",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/bot.go#L894-L931 | train |
decred/dcrdata | middleware/apimiddleware.go | writeHTMLBadRequest | func writeHTMLBadRequest(w http.ResponseWriter, str string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, str)
} | go | func writeHTMLBadRequest(w http.ResponseWriter, str string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, str)
} | [
"func",
"writeHTMLBadRequest",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"str",
"string",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"io",
".",
"WriteString",
"(",
"w",
",",
"str",
")",
"\n",
"}"
] | // writeHTMLBadRequest is used for the Insight API error response for a BAD REQUEST.
// This means the request was malformed in some way or the request HASH,
// ADDRESS, BLOCK was not valid. | [
"writeHTMLBadRequest",
"is",
"used",
"for",
"the",
"Insight",
"API",
"error",
"response",
"for",
"a",
"BAD",
"REQUEST",
".",
"This",
"means",
"the",
"request",
"was",
"malformed",
"in",
"some",
"way",
"or",
"the",
"request",
"HASH",
"ADDRESS",
"BLOCK",
"was",
"not",
"valid",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L70-L74 | train |
decred/dcrdata | middleware/apimiddleware.go | GetBlockStepCtx | func GetBlockStepCtx(r *http.Request) int {
step, ok := r.Context().Value(ctxBlockStep).(int)
if !ok {
apiLog.Error("block step is not set or is not an int")
return -1
}
return step
} | go | func GetBlockStepCtx(r *http.Request) int {
step, ok := r.Context().Value(ctxBlockStep).(int)
if !ok {
apiLog.Error("block step is not set or is not an int")
return -1
}
return step
} | [
"func",
"GetBlockStepCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"int",
"{",
"step",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxBlockStep",
")",
".",
"(",
"int",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"-",
"1",
"\n",
"}",
"\n",
"return",
"step",
"\n",
"}"
] | // GetBlockStepCtx retrieves the ctxBlockStep data from the request context. If
// not set, the return value is -1. | [
"GetBlockStepCtx",
"retrieves",
"the",
"ctxBlockStep",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"value",
"is",
"-",
"1",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L88-L95 | train |
decred/dcrdata | middleware/apimiddleware.go | GetBlockIndex0Ctx | func GetBlockIndex0Ctx(r *http.Request) int {
idx, ok := r.Context().Value(ctxBlockIndex0).(int)
if !ok {
apiLog.Error("block index0 is not set or is not an int")
return -1
}
return idx
} | go | func GetBlockIndex0Ctx(r *http.Request) int {
idx, ok := r.Context().Value(ctxBlockIndex0).(int)
if !ok {
apiLog.Error("block index0 is not set or is not an int")
return -1
}
return idx
} | [
"func",
"GetBlockIndex0Ctx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"int",
"{",
"idx",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxBlockIndex0",
")",
".",
"(",
"int",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"-",
"1",
"\n",
"}",
"\n",
"return",
"idx",
"\n",
"}"
] | // GetBlockIndex0Ctx retrieves the ctxBlockIndex0 data from the request context.
// If not set, the return value is -1. | [
"GetBlockIndex0Ctx",
"retrieves",
"the",
"ctxBlockIndex0",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"value",
"is",
"-",
"1",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L99-L106 | train |
decred/dcrdata | middleware/apimiddleware.go | GetTxIOIndexCtx | func GetTxIOIndexCtx(r *http.Request) int {
index, ok := r.Context().Value(ctxTxInOutIndex).(int)
if !ok {
apiLog.Warn("txinoutindex is not set or is not an int")
return -1
}
return index
} | go | func GetTxIOIndexCtx(r *http.Request) int {
index, ok := r.Context().Value(ctxTxInOutIndex).(int)
if !ok {
apiLog.Warn("txinoutindex is not set or is not an int")
return -1
}
return index
} | [
"func",
"GetTxIOIndexCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"int",
"{",
"index",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxTxInOutIndex",
")",
".",
"(",
"int",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"return",
"-",
"1",
"\n",
"}",
"\n",
"return",
"index",
"\n",
"}"
] | // GetTxIOIndexCtx retrieves the ctxTxInOutIndex data from the request context.
// If not set, the return value is -1. | [
"GetTxIOIndexCtx",
"retrieves",
"the",
"ctxTxInOutIndex",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"value",
"is",
"-",
"1",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L110-L117 | train |
decred/dcrdata | middleware/apimiddleware.go | GetNCtx | func GetNCtx(r *http.Request) int {
N, ok := r.Context().Value(ctxN).(int)
if !ok {
apiLog.Trace("N is not set or is not an int")
return -1
}
return N
} | go | func GetNCtx(r *http.Request) int {
N, ok := r.Context().Value(ctxN).(int)
if !ok {
apiLog.Trace("N is not set or is not an int")
return -1
}
return N
} | [
"func",
"GetNCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"int",
"{",
"N",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxN",
")",
".",
"(",
"int",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Trace",
"(",
"\"",
"\"",
")",
"\n",
"return",
"-",
"1",
"\n",
"}",
"\n",
"return",
"N",
"\n",
"}"
] | // GetNCtx retrieves the ctxN data from the request context. If not set, the
// return value is -1. | [
"GetNCtx",
"retrieves",
"the",
"ctxN",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"value",
"is",
"-",
"1",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L121-L128 | train |
decred/dcrdata | middleware/apimiddleware.go | GetMCtx | func GetMCtx(r *http.Request) int {
M, ok := r.Context().Value(ctxM).(int)
if !ok {
apiLog.Trace("M is not set or is not an int")
return -1
}
return M
} | go | func GetMCtx(r *http.Request) int {
M, ok := r.Context().Value(ctxM).(int)
if !ok {
apiLog.Trace("M is not set or is not an int")
return -1
}
return M
} | [
"func",
"GetMCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"int",
"{",
"M",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxM",
")",
".",
"(",
"int",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Trace",
"(",
"\"",
"\"",
")",
"\n",
"return",
"-",
"1",
"\n",
"}",
"\n",
"return",
"M",
"\n",
"}"
] | // GetMCtx retrieves the ctxM data from the request context. If not set, the
// return value is -1. | [
"GetMCtx",
"retrieves",
"the",
"ctxM",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"value",
"is",
"-",
"1",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L132-L139 | train |
decred/dcrdata | middleware/apimiddleware.go | GetTpCtx | func GetTpCtx(r *http.Request) string {
tp, ok := r.Context().Value(ctxTp).(string)
if !ok {
apiLog.Trace("ticket pool interval not set")
return ""
}
return tp
} | go | func GetTpCtx(r *http.Request) string {
tp, ok := r.Context().Value(ctxTp).(string)
if !ok {
apiLog.Trace("ticket pool interval not set")
return ""
}
return tp
} | [
"func",
"GetTpCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"tp",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxTp",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Trace",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"tp",
"\n",
"}"
] | // GetTpCtx retrieves the ctxTp data from the request context.
// If the value is not set, an empty string is returned. | [
"GetTpCtx",
"retrieves",
"the",
"ctxTp",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"the",
"value",
"is",
"not",
"set",
"an",
"empty",
"string",
"is",
"returned",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L143-L150 | train |
decred/dcrdata | middleware/apimiddleware.go | GetProposalTokenCtx | func GetProposalTokenCtx(r *http.Request) string {
tp, ok := r.Context().Value(ctxProposalToken).(string)
if !ok {
apiLog.Trace("proposal token hash not set")
return ""
}
return tp
} | go | func GetProposalTokenCtx(r *http.Request) string {
tp, ok := r.Context().Value(ctxProposalToken).(string)
if !ok {
apiLog.Trace("proposal token hash not set")
return ""
}
return tp
} | [
"func",
"GetProposalTokenCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"tp",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxProposalToken",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Trace",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"tp",
"\n",
"}"
] | // GetProposalTokenCtx retrieves the ctxProposalToken data from the request context.
// If the value is not set, an empty string is returned. | [
"GetProposalTokenCtx",
"retrieves",
"the",
"ctxProposalToken",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"the",
"value",
"is",
"not",
"set",
"an",
"empty",
"string",
"is",
"returned",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L154-L161 | train |
decred/dcrdata | middleware/apimiddleware.go | GetRawHexTx | func GetRawHexTx(r *http.Request) (string, error) {
rawHexTx, ok := r.Context().Value(ctxRawHexTx).(string)
if !ok {
apiLog.Trace("hex transaction id not set")
return "", fmt.Errorf("hex transaction id not set")
}
msgtx := wire.NewMsgTx()
err := msgtx.Deserialize(hex.NewDecoder(strings.NewReader(rawHexTx)))
if err != nil {
return "", fmt.Errorf("failed to deserialize tx: %v", err)
}
return rawHexTx, nil
} | go | func GetRawHexTx(r *http.Request) (string, error) {
rawHexTx, ok := r.Context().Value(ctxRawHexTx).(string)
if !ok {
apiLog.Trace("hex transaction id not set")
return "", fmt.Errorf("hex transaction id not set")
}
msgtx := wire.NewMsgTx()
err := msgtx.Deserialize(hex.NewDecoder(strings.NewReader(rawHexTx)))
if err != nil {
return "", fmt.Errorf("failed to deserialize tx: %v", err)
}
return rawHexTx, nil
} | [
"func",
"GetRawHexTx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"string",
",",
"error",
")",
"{",
"rawHexTx",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxRawHexTx",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Trace",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"msgtx",
":=",
"wire",
".",
"NewMsgTx",
"(",
")",
"\n",
"err",
":=",
"msgtx",
".",
"Deserialize",
"(",
"hex",
".",
"NewDecoder",
"(",
"strings",
".",
"NewReader",
"(",
"rawHexTx",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"rawHexTx",
",",
"nil",
"\n",
"}"
] | // GetRawHexTx retrieves the ctxRawHexTx data from the request context. If not
// set, the return value is an empty string. | [
"GetRawHexTx",
"retrieves",
"the",
"ctxRawHexTx",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"value",
"is",
"an",
"empty",
"string",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L165-L178 | train |
decred/dcrdata | middleware/apimiddleware.go | PostBroadcastTxCtx | func PostBroadcastTxCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req apitypes.InsightRawTx
body, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
writeHTMLBadRequest(w, fmt.Sprintf("Error reading JSON message: %v", err))
return
}
err = json.Unmarshal(body, &req)
if err != nil {
writeHTMLBadRequest(w, fmt.Sprintf("Failed to parse request: %v", err))
return
}
// Successful extraction of Body JSON as long as the rawtx is not empty
// string we should return it.
if req.Rawtx == "" {
writeHTMLBadRequest(w, fmt.Sprintf("rawtx cannot be an empty string."))
return
}
ctx := context.WithValue(r.Context(), ctxRawHexTx, req.Rawtx)
next.ServeHTTP(w, r.WithContext(ctx))
})
} | go | func PostBroadcastTxCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req apitypes.InsightRawTx
body, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
writeHTMLBadRequest(w, fmt.Sprintf("Error reading JSON message: %v", err))
return
}
err = json.Unmarshal(body, &req)
if err != nil {
writeHTMLBadRequest(w, fmt.Sprintf("Failed to parse request: %v", err))
return
}
// Successful extraction of Body JSON as long as the rawtx is not empty
// string we should return it.
if req.Rawtx == "" {
writeHTMLBadRequest(w, fmt.Sprintf("rawtx cannot be an empty string."))
return
}
ctx := context.WithValue(r.Context(), ctxRawHexTx, req.Rawtx)
next.ServeHTTP(w, r.WithContext(ctx))
})
} | [
"func",
"PostBroadcastTxCtx",
"(",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"var",
"req",
"apitypes",
".",
"InsightRawTx",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeHTMLBadRequest",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"body",
",",
"&",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeHTMLBadRequest",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Successful extraction of Body JSON as long as the rawtx is not empty",
"// string we should return it.",
"if",
"req",
".",
"Rawtx",
"==",
"\"",
"\"",
"{",
"writeHTMLBadRequest",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"ctx",
":=",
"context",
".",
"WithValue",
"(",
"r",
".",
"Context",
"(",
")",
",",
"ctxRawHexTx",
",",
"req",
".",
"Rawtx",
")",
"\n",
"next",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
".",
"WithContext",
"(",
"ctx",
")",
")",
"\n",
"}",
")",
"\n",
"}"
] | // PostBroadcastTxCtx is middleware that checks for parameters given in POST
// request body of the broadcast transaction endpoint. | [
"PostBroadcastTxCtx",
"is",
"middleware",
"that",
"checks",
"for",
"parameters",
"given",
"in",
"POST",
"request",
"body",
"of",
"the",
"broadcast",
"transaction",
"endpoint",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L182-L208 | train |
decred/dcrdata | middleware/apimiddleware.go | GetTxIDCtx | func GetTxIDCtx(r *http.Request) (*chainhash.Hash, error) {
hashStr, ok := r.Context().Value(ctxTxHash).(string)
if !ok {
apiLog.Trace("txid not set")
return nil, fmt.Errorf("txid not set")
}
hash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
apiLog.Trace("invalid hash '%s': %v", hashStr, err)
return nil, fmt.Errorf("invalid hash '%s': %v",
hashStr, err)
}
return hash, nil
} | go | func GetTxIDCtx(r *http.Request) (*chainhash.Hash, error) {
hashStr, ok := r.Context().Value(ctxTxHash).(string)
if !ok {
apiLog.Trace("txid not set")
return nil, fmt.Errorf("txid not set")
}
hash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
apiLog.Trace("invalid hash '%s': %v", hashStr, err)
return nil, fmt.Errorf("invalid hash '%s': %v",
hashStr, err)
}
return hash, nil
} | [
"func",
"GetTxIDCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"hashStr",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxTxHash",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Trace",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"hash",
",",
"err",
":=",
"chainhash",
".",
"NewHashFromStr",
"(",
"hashStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"apiLog",
".",
"Trace",
"(",
"\"",
"\"",
",",
"hashStr",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hashStr",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"hash",
",",
"nil",
"\n",
"}"
] | // GetTxIDCtx retrieves the ctxTxHash data from the request context. If not set,
// the return value is an empty string. | [
"GetTxIDCtx",
"retrieves",
"the",
"ctxTxHash",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"value",
"is",
"an",
"empty",
"string",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L212-L225 | train |
decred/dcrdata | middleware/apimiddleware.go | GetTxnsCtx | func GetTxnsCtx(r *http.Request) ([]*chainhash.Hash, error) {
hashStrs, ok := r.Context().Value(ctxTxns).([]string)
if !ok || len(hashStrs) == 0 {
apiLog.Trace("ctxTxns not set")
return nil, fmt.Errorf("ctxTxns not set")
}
var hashes []*chainhash.Hash
for _, hashStr := range hashStrs {
hash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
apiLog.Trace("invalid hash '%s': %v", hashStr, err)
return nil, fmt.Errorf("invalid hash '%s': %v", hashStr, err)
}
hashes = append(hashes, hash)
}
return hashes, nil
} | go | func GetTxnsCtx(r *http.Request) ([]*chainhash.Hash, error) {
hashStrs, ok := r.Context().Value(ctxTxns).([]string)
if !ok || len(hashStrs) == 0 {
apiLog.Trace("ctxTxns not set")
return nil, fmt.Errorf("ctxTxns not set")
}
var hashes []*chainhash.Hash
for _, hashStr := range hashStrs {
hash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
apiLog.Trace("invalid hash '%s': %v", hashStr, err)
return nil, fmt.Errorf("invalid hash '%s': %v", hashStr, err)
}
hashes = append(hashes, hash)
}
return hashes, nil
} | [
"func",
"GetTxnsCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"[",
"]",
"*",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"hashStrs",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxTxns",
")",
".",
"(",
"[",
"]",
"string",
")",
"\n",
"if",
"!",
"ok",
"||",
"len",
"(",
"hashStrs",
")",
"==",
"0",
"{",
"apiLog",
".",
"Trace",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"hashes",
"[",
"]",
"*",
"chainhash",
".",
"Hash",
"\n",
"for",
"_",
",",
"hashStr",
":=",
"range",
"hashStrs",
"{",
"hash",
",",
"err",
":=",
"chainhash",
".",
"NewHashFromStr",
"(",
"hashStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"apiLog",
".",
"Trace",
"(",
"\"",
"\"",
",",
"hashStr",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hashStr",
",",
"err",
")",
"\n",
"}",
"\n",
"hashes",
"=",
"append",
"(",
"hashes",
",",
"hash",
")",
"\n",
"}",
"\n\n",
"return",
"hashes",
",",
"nil",
"\n",
"}"
] | // GetTxnsCtx retrieves the ctxTxns data from the request context. If not set,
// the return value is an empty string slice. | [
"GetTxnsCtx",
"retrieves",
"the",
"ctxTxns",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"value",
"is",
"an",
"empty",
"string",
"slice",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L229-L247 | train |
decred/dcrdata | middleware/apimiddleware.go | PostTxnsCtx | func PostTxnsCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
req := apitypes.Txns{}
body, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
apiLog.Debugf("No/invalid txns: %v", err)
http.Error(w, "error reading JSON message", http.StatusBadRequest)
return
}
err = json.Unmarshal(body, &req)
if err != nil {
apiLog.Debugf("failed to unmarshal JSON request to apitypes.Txns: %v", err)
http.Error(w, "failed to unmarshal JSON request", http.StatusBadRequest)
return
}
// Successful extraction of body JSON
ctx := context.WithValue(r.Context(), ctxTxns, req.Transactions)
next.ServeHTTP(w, r.WithContext(ctx))
})
} | go | func PostTxnsCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
req := apitypes.Txns{}
body, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
apiLog.Debugf("No/invalid txns: %v", err)
http.Error(w, "error reading JSON message", http.StatusBadRequest)
return
}
err = json.Unmarshal(body, &req)
if err != nil {
apiLog.Debugf("failed to unmarshal JSON request to apitypes.Txns: %v", err)
http.Error(w, "failed to unmarshal JSON request", http.StatusBadRequest)
return
}
// Successful extraction of body JSON
ctx := context.WithValue(r.Context(), ctxTxns, req.Transactions)
next.ServeHTTP(w, r.WithContext(ctx))
})
} | [
"func",
"PostTxnsCtx",
"(",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"req",
":=",
"apitypes",
".",
"Txns",
"{",
"}",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"apiLog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"body",
",",
"&",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"apiLog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// Successful extraction of body JSON",
"ctx",
":=",
"context",
".",
"WithValue",
"(",
"r",
".",
"Context",
"(",
")",
",",
"ctxTxns",
",",
"req",
".",
"Transactions",
")",
"\n\n",
"next",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
".",
"WithContext",
"(",
"ctx",
")",
")",
"\n",
"}",
")",
"\n",
"}"
] | // PostTxnsCtx extract transaction IDs from the POST body | [
"PostTxnsCtx",
"extract",
"transaction",
"IDs",
"from",
"the",
"POST",
"body"
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L257-L278 | train |
decred/dcrdata | middleware/apimiddleware.go | ValidateTxnsPostCtx | func ValidateTxnsPostCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
contentLengthString := r.Header.Get("Content-Length")
contentLength, err := strconv.Atoi(contentLengthString)
if err != nil {
http.Error(w, "Unable to parse Content-Length", http.StatusBadRequest)
return
}
// Broadcast Tx has the largest possible body.
maxPayload := 1 << 22
if contentLength > maxPayload {
http.Error(w, fmt.Sprintf("Maximum Content-Length is %d", maxPayload), http.StatusBadRequest)
return
}
next.ServeHTTP(w, r)
})
} | go | func ValidateTxnsPostCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
contentLengthString := r.Header.Get("Content-Length")
contentLength, err := strconv.Atoi(contentLengthString)
if err != nil {
http.Error(w, "Unable to parse Content-Length", http.StatusBadRequest)
return
}
// Broadcast Tx has the largest possible body.
maxPayload := 1 << 22
if contentLength > maxPayload {
http.Error(w, fmt.Sprintf("Maximum Content-Length is %d", maxPayload), http.StatusBadRequest)
return
}
next.ServeHTTP(w, r)
})
} | [
"func",
"ValidateTxnsPostCtx",
"(",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"contentLengthString",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"contentLength",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"contentLengthString",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// Broadcast Tx has the largest possible body.",
"maxPayload",
":=",
"1",
"<<",
"22",
"\n",
"if",
"contentLength",
">",
"maxPayload",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"maxPayload",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"next",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
] | // ValidateTxnsPostCtx will confirm Post content length is valid. | [
"ValidateTxnsPostCtx",
"will",
"confirm",
"Post",
"content",
"length",
"is",
"valid",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L281-L297 | train |
decred/dcrdata | middleware/apimiddleware.go | GetBlockHashCtx | func GetBlockHashCtx(r *http.Request) (string, error) {
hash, ok := r.Context().Value(ctxBlockHash).(string)
if !ok {
apiLog.Trace("block hash not set")
return "", fmt.Errorf("block hash not set")
}
if _, err := chainhash.NewHashFromStr(hash); err != nil {
apiLog.Trace("invalid hash '%s': %v", hash, err)
return "", fmt.Errorf("invalid hash '%s': %v", hash, err)
}
return hash, nil
} | go | func GetBlockHashCtx(r *http.Request) (string, error) {
hash, ok := r.Context().Value(ctxBlockHash).(string)
if !ok {
apiLog.Trace("block hash not set")
return "", fmt.Errorf("block hash not set")
}
if _, err := chainhash.NewHashFromStr(hash); err != nil {
apiLog.Trace("invalid hash '%s': %v", hash, err)
return "", fmt.Errorf("invalid hash '%s': %v", hash, err)
}
return hash, nil
} | [
"func",
"GetBlockHashCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"string",
",",
"error",
")",
"{",
"hash",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxBlockHash",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Trace",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"chainhash",
".",
"NewHashFromStr",
"(",
"hash",
")",
";",
"err",
"!=",
"nil",
"{",
"apiLog",
".",
"Trace",
"(",
"\"",
"\"",
",",
"hash",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hash",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"hash",
",",
"nil",
"\n",
"}"
] | // GetBlockHashCtx retrieves the ctxBlockHash data from the request context. If
// not set, the return value is an empty string. | [
"GetBlockHashCtx",
"retrieves",
"the",
"ctxBlockHash",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"value",
"is",
"an",
"empty",
"string",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L301-L313 | train |
decred/dcrdata | middleware/apimiddleware.go | GetAddressCtx | func GetAddressCtx(r *http.Request, activeNetParams *chaincfg.Params, maxAddrs int) ([]string, error) {
addressStr, ok := r.Context().Value(CtxAddress).(string)
if !ok || len(addressStr) == 0 {
apiLog.Trace("address not set")
return nil, fmt.Errorf("address not set")
}
addressStrs := strings.Split(addressStr, ",")
if len(addressStrs) > maxAddrs {
return nil, fmt.Errorf("maximum of %d addresses allowed", maxAddrs)
}
strInSlice := func(sl []string, s string) bool {
for i := range sl {
if sl[i] == s {
return true
}
}
return false
}
var addrStrs []string
for _, addrStr := range addressStrs {
address, err := dcrutil.DecodeAddress(addrStr)
if err != nil {
return nil, fmt.Errorf("invalid address '%v': %v",
addrStr, err)
}
if !address.IsForNet(activeNetParams) {
return nil, fmt.Errorf("%v is invalid for this network",
addrStr)
}
if strInSlice(addrStrs, addrStr) {
continue
}
addrStrs = append(addrStrs, addrStr)
}
return addrStrs, nil
} | go | func GetAddressCtx(r *http.Request, activeNetParams *chaincfg.Params, maxAddrs int) ([]string, error) {
addressStr, ok := r.Context().Value(CtxAddress).(string)
if !ok || len(addressStr) == 0 {
apiLog.Trace("address not set")
return nil, fmt.Errorf("address not set")
}
addressStrs := strings.Split(addressStr, ",")
if len(addressStrs) > maxAddrs {
return nil, fmt.Errorf("maximum of %d addresses allowed", maxAddrs)
}
strInSlice := func(sl []string, s string) bool {
for i := range sl {
if sl[i] == s {
return true
}
}
return false
}
var addrStrs []string
for _, addrStr := range addressStrs {
address, err := dcrutil.DecodeAddress(addrStr)
if err != nil {
return nil, fmt.Errorf("invalid address '%v': %v",
addrStr, err)
}
if !address.IsForNet(activeNetParams) {
return nil, fmt.Errorf("%v is invalid for this network",
addrStr)
}
if strInSlice(addrStrs, addrStr) {
continue
}
addrStrs = append(addrStrs, addrStr)
}
return addrStrs, nil
} | [
"func",
"GetAddressCtx",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"activeNetParams",
"*",
"chaincfg",
".",
"Params",
",",
"maxAddrs",
"int",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"addressStr",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"CtxAddress",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"||",
"len",
"(",
"addressStr",
")",
"==",
"0",
"{",
"apiLog",
".",
"Trace",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"addressStrs",
":=",
"strings",
".",
"Split",
"(",
"addressStr",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"addressStrs",
")",
">",
"maxAddrs",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"maxAddrs",
")",
"\n",
"}",
"\n\n",
"strInSlice",
":=",
"func",
"(",
"sl",
"[",
"]",
"string",
",",
"s",
"string",
")",
"bool",
"{",
"for",
"i",
":=",
"range",
"sl",
"{",
"if",
"sl",
"[",
"i",
"]",
"==",
"s",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"var",
"addrStrs",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"addrStr",
":=",
"range",
"addressStrs",
"{",
"address",
",",
"err",
":=",
"dcrutil",
".",
"DecodeAddress",
"(",
"addrStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"addrStr",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"!",
"address",
".",
"IsForNet",
"(",
"activeNetParams",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"addrStr",
")",
"\n",
"}",
"\n",
"if",
"strInSlice",
"(",
"addrStrs",
",",
"addrStr",
")",
"{",
"continue",
"\n",
"}",
"\n",
"addrStrs",
"=",
"append",
"(",
"addrStrs",
",",
"addrStr",
")",
"\n",
"}",
"\n",
"return",
"addrStrs",
",",
"nil",
"\n",
"}"
] | // GetAddressCtx retrieves the CtxAddress data from the request context. If not
// set, the return value is an empty string. The CtxAddress string data may be a
// comma-separated list of addresses, subject to the provided maximum number of
// addresses allowed. Duplicate addresses are removed, but the limit is enforced
// prior to removal of duplicates. | [
"GetAddressCtx",
"retrieves",
"the",
"CtxAddress",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"value",
"is",
"an",
"empty",
"string",
".",
"The",
"CtxAddress",
"string",
"data",
"may",
"be",
"a",
"comma",
"-",
"separated",
"list",
"of",
"addresses",
"subject",
"to",
"the",
"provided",
"maximum",
"number",
"of",
"addresses",
"allowed",
".",
"Duplicate",
"addresses",
"are",
"removed",
"but",
"the",
"limit",
"is",
"enforced",
"prior",
"to",
"removal",
"of",
"duplicates",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L320-L357 | train |
decred/dcrdata | middleware/apimiddleware.go | GetChartTypeCtx | func GetChartTypeCtx(r *http.Request) string {
chartType, ok := r.Context().Value(ctxChartType).(string)
if !ok {
apiLog.Trace("chart type not set")
return ""
}
return chartType
} | go | func GetChartTypeCtx(r *http.Request) string {
chartType, ok := r.Context().Value(ctxChartType).(string)
if !ok {
apiLog.Trace("chart type not set")
return ""
}
return chartType
} | [
"func",
"GetChartTypeCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"chartType",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxChartType",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Trace",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"chartType",
"\n",
"}"
] | // GetChartTypeCtx retrieves the ctxChart data from the request context.
// If not set, the return value is an empty string. | [
"GetChartTypeCtx",
"retrieves",
"the",
"ctxChart",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"value",
"is",
"an",
"empty",
"string",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L361-L368 | train |
decred/dcrdata | middleware/apimiddleware.go | GetChartGroupingCtx | func GetChartGroupingCtx(r *http.Request) string {
chartType, ok := r.Context().Value(ctxChartGrouping).(string)
if !ok {
apiLog.Trace("chart grouping not set")
return ""
}
return chartType
} | go | func GetChartGroupingCtx(r *http.Request) string {
chartType, ok := r.Context().Value(ctxChartGrouping).(string)
if !ok {
apiLog.Trace("chart grouping not set")
return ""
}
return chartType
} | [
"func",
"GetChartGroupingCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"chartType",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxChartGrouping",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Trace",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"chartType",
"\n",
"}"
] | // GetChartGroupingCtx retrieves the ctxChart data from the request context.
// If not set, the return value is an empty string. | [
"GetChartGroupingCtx",
"retrieves",
"the",
"ctxChart",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"value",
"is",
"an",
"empty",
"string",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L372-L379 | train |
decred/dcrdata | middleware/apimiddleware.go | GetBlockDateCtx | func GetBlockDateCtx(r *http.Request) string {
blockDate, _ := r.Context().Value(CtxBlockDate).(string)
return blockDate
} | go | func GetBlockDateCtx(r *http.Request) string {
blockDate, _ := r.Context().Value(CtxBlockDate).(string)
return blockDate
} | [
"func",
"GetBlockDateCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"blockDate",
",",
"_",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"CtxBlockDate",
")",
".",
"(",
"string",
")",
"\n",
"return",
"blockDate",
"\n",
"}"
] | // GetBlockDateCtx retrieves the ctxBlockDate data from the request context. If
// not set, the return value is an empty string. | [
"GetBlockDateCtx",
"retrieves",
"the",
"ctxBlockDate",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"value",
"is",
"an",
"empty",
"string",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L416-L419 | train |
decred/dcrdata | middleware/apimiddleware.go | GetBlockIndexCtx | func GetBlockIndexCtx(r *http.Request) int {
idx, ok := r.Context().Value(ctxBlockIndex).(int)
if !ok {
apiLog.Warn("block index not set or is not an int")
return -1
}
return idx
} | go | func GetBlockIndexCtx(r *http.Request) int {
idx, ok := r.Context().Value(ctxBlockIndex).(int)
if !ok {
apiLog.Warn("block index not set or is not an int")
return -1
}
return idx
} | [
"func",
"GetBlockIndexCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"int",
"{",
"idx",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxBlockIndex",
")",
".",
"(",
"int",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"return",
"-",
"1",
"\n",
"}",
"\n",
"return",
"idx",
"\n",
"}"
] | // GetBlockIndexCtx retrieves the ctxBlockIndex data from the request context.
// If not set, the return -1. | [
"GetBlockIndexCtx",
"retrieves",
"the",
"ctxBlockIndex",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"-",
"1",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L423-L430 | train |
decred/dcrdata | middleware/apimiddleware.go | apiDocs | func apiDocs(mux *chi.Mux) func(next http.Handler) http.Handler {
var buf bytes.Buffer
json.Indent(&buf, []byte(docgen.JSONRoutesDoc(mux)), "", "\t")
docs := buf.String()
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), ctxAPIDocs, docs)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
} | go | func apiDocs(mux *chi.Mux) func(next http.Handler) http.Handler {
var buf bytes.Buffer
json.Indent(&buf, []byte(docgen.JSONRoutesDoc(mux)), "", "\t")
docs := buf.String()
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), ctxAPIDocs, docs)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
} | [
"func",
"apiDocs",
"(",
"mux",
"*",
"chi",
".",
"Mux",
")",
"func",
"(",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"json",
".",
"Indent",
"(",
"&",
"buf",
",",
"[",
"]",
"byte",
"(",
"docgen",
".",
"JSONRoutesDoc",
"(",
"mux",
")",
")",
",",
"\"",
"\"",
",",
"\"",
"\\t",
"\"",
")",
"\n",
"docs",
":=",
"buf",
".",
"String",
"(",
")",
"\n",
"return",
"func",
"(",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"ctx",
":=",
"context",
".",
"WithValue",
"(",
"r",
".",
"Context",
"(",
")",
",",
"ctxAPIDocs",
",",
"docs",
")",
"\n",
"next",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
".",
"WithContext",
"(",
"ctx",
")",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}"
] | // apiDocs generates a middleware with a "docs" in the context containing a map
// of the routers handlers, etc. | [
"apiDocs",
"generates",
"a",
"middleware",
"with",
"a",
"docs",
"in",
"the",
"context",
"containing",
"a",
"map",
"of",
"the",
"routers",
"handlers",
"etc",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L632-L642 | train |
decred/dcrdata | middleware/apimiddleware.go | GetAgendaIdCtx | func GetAgendaIdCtx(r *http.Request) string {
agendaId, ok := r.Context().Value(ctxAgendaId).(string)
if !ok {
apiLog.Error("agendaId not parsed")
return ""
}
return agendaId
} | go | func GetAgendaIdCtx(r *http.Request) string {
agendaId, ok := r.Context().Value(ctxAgendaId).(string)
if !ok {
apiLog.Error("agendaId not parsed")
return ""
}
return agendaId
} | [
"func",
"GetAgendaIdCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"agendaId",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxAgendaId",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"agendaId",
"\n",
"}"
] | // GetAgendaIdCtx retrieves the ctxAgendaId data from the request context.
// If not set, the return value is an empty string. | [
"GetAgendaIdCtx",
"retrieves",
"the",
"ctxAgendaId",
"data",
"from",
"the",
"request",
"context",
".",
"If",
"not",
"set",
"the",
"return",
"value",
"is",
"an",
"empty",
"string",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L739-L746 | train |
decred/dcrdata | middleware/apimiddleware.go | StatusInfoCtx | func StatusInfoCtx(r *http.Request, source DataSource) context.Context {
idx := int64(-1)
h, err := source.GetHeight()
if h >= 0 && err == nil {
idx = h
}
ctx := context.WithValue(r.Context(), ctxBlockIndex, int(idx)) // Must be int!
q := r.FormValue("q")
return context.WithValue(ctx, ctxGetStatus, q)
} | go | func StatusInfoCtx(r *http.Request, source DataSource) context.Context {
idx := int64(-1)
h, err := source.GetHeight()
if h >= 0 && err == nil {
idx = h
}
ctx := context.WithValue(r.Context(), ctxBlockIndex, int(idx)) // Must be int!
q := r.FormValue("q")
return context.WithValue(ctx, ctxGetStatus, q)
} | [
"func",
"StatusInfoCtx",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"source",
"DataSource",
")",
"context",
".",
"Context",
"{",
"idx",
":=",
"int64",
"(",
"-",
"1",
")",
"\n",
"h",
",",
"err",
":=",
"source",
".",
"GetHeight",
"(",
")",
"\n",
"if",
"h",
">=",
"0",
"&&",
"err",
"==",
"nil",
"{",
"idx",
"=",
"h",
"\n",
"}",
"\n",
"ctx",
":=",
"context",
".",
"WithValue",
"(",
"r",
".",
"Context",
"(",
")",
",",
"ctxBlockIndex",
",",
"int",
"(",
"idx",
")",
")",
"// Must be int!",
"\n\n",
"q",
":=",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"\n",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"ctxGetStatus",
",",
"q",
")",
"\n",
"}"
] | // StatusInfoCtx embeds the best block index and the POST form data for
// parameter "q" into a request context. | [
"StatusInfoCtx",
"embeds",
"the",
"best",
"block",
"index",
"and",
"the",
"POST",
"form",
"data",
"for",
"parameter",
"q",
"into",
"a",
"request",
"context",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L762-L772 | train |
decred/dcrdata | middleware/apimiddleware.go | GetBlockHeightCtx | func GetBlockHeightCtx(r *http.Request, source DataSource) (int64, error) {
idxI, ok := r.Context().Value(ctxBlockIndex).(int)
idx := int64(idxI)
if !ok || idx < 0 {
hash, err := GetBlockHashCtx(r)
if err != nil {
return 0, err
}
idx, err = source.GetBlockHeight(hash)
if err != nil {
return 0, err
}
}
return idx, nil
} | go | func GetBlockHeightCtx(r *http.Request, source DataSource) (int64, error) {
idxI, ok := r.Context().Value(ctxBlockIndex).(int)
idx := int64(idxI)
if !ok || idx < 0 {
hash, err := GetBlockHashCtx(r)
if err != nil {
return 0, err
}
idx, err = source.GetBlockHeight(hash)
if err != nil {
return 0, err
}
}
return idx, nil
} | [
"func",
"GetBlockHeightCtx",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"source",
"DataSource",
")",
"(",
"int64",
",",
"error",
")",
"{",
"idxI",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxBlockIndex",
")",
".",
"(",
"int",
")",
"\n",
"idx",
":=",
"int64",
"(",
"idxI",
")",
"\n",
"if",
"!",
"ok",
"||",
"idx",
"<",
"0",
"{",
"hash",
",",
"err",
":=",
"GetBlockHashCtx",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"idx",
",",
"err",
"=",
"source",
".",
"GetBlockHeight",
"(",
"hash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"idx",
",",
"nil",
"\n",
"}"
] | // GetBlockHeightCtx returns the block height for the block index or hash
// specified on the URL path. | [
"GetBlockHeightCtx",
"returns",
"the",
"block",
"height",
"for",
"the",
"block",
"index",
"or",
"hash",
"specified",
"on",
"the",
"URL",
"path",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L818-L832 | train |
decred/dcrdata | middleware/apimiddleware.go | RetrieveExchangeTokenCtx | func RetrieveExchangeTokenCtx(r *http.Request) string {
token, ok := r.Context().Value(ctxXcToken).(string)
if !ok {
apiLog.Error("non-string encountered in exchange token context")
return ""
}
return token
} | go | func RetrieveExchangeTokenCtx(r *http.Request) string {
token, ok := r.Context().Value(ctxXcToken).(string)
if !ok {
apiLog.Error("non-string encountered in exchange token context")
return ""
}
return token
} | [
"func",
"RetrieveExchangeTokenCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"token",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxXcToken",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"token",
"\n",
"}"
] | // RetrieveExchangeTokenCtx tries to fetch the exchange token from the request
// context. | [
"RetrieveExchangeTokenCtx",
"tries",
"to",
"fetch",
"the",
"exchange",
"token",
"from",
"the",
"request",
"context",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L856-L863 | train |
decred/dcrdata | middleware/apimiddleware.go | StickWidthContext | func StickWidthContext(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
bin := chi.URLParam(r, "bin")
ctx := context.WithValue(r.Context(), ctxStickWidth, bin)
next.ServeHTTP(w, r.WithContext(ctx))
})
} | go | func StickWidthContext(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
bin := chi.URLParam(r, "bin")
ctx := context.WithValue(r.Context(), ctxStickWidth, bin)
next.ServeHTTP(w, r.WithContext(ctx))
})
} | [
"func",
"StickWidthContext",
"(",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"bin",
":=",
"chi",
".",
"URLParam",
"(",
"r",
",",
"\"",
"\"",
")",
"\n",
"ctx",
":=",
"context",
".",
"WithValue",
"(",
"r",
".",
"Context",
"(",
")",
",",
"ctxStickWidth",
",",
"bin",
")",
"\n",
"next",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
".",
"WithContext",
"(",
"ctx",
")",
")",
"\n",
"}",
")",
"\n",
"}"
] | // ExchangeTokenContext pulls the bin width from the URL. | [
"ExchangeTokenContext",
"pulls",
"the",
"bin",
"width",
"from",
"the",
"URL",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L866-L872 | train |
decred/dcrdata | middleware/apimiddleware.go | RetrieveStickWidthCtx | func RetrieveStickWidthCtx(r *http.Request) string {
bin, ok := r.Context().Value(ctxStickWidth).(string)
if !ok {
apiLog.Error("non-string encountered in candlestick width context")
return ""
}
return bin
} | go | func RetrieveStickWidthCtx(r *http.Request) string {
bin, ok := r.Context().Value(ctxStickWidth).(string)
if !ok {
apiLog.Error("non-string encountered in candlestick width context")
return ""
}
return bin
} | [
"func",
"RetrieveStickWidthCtx",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"bin",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ctxStickWidth",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"apiLog",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"bin",
"\n",
"}"
] | // RetrieveStickWidthCtx tries to fetch the candlestick width from the request
// context. | [
"RetrieveStickWidthCtx",
"tries",
"to",
"fetch",
"the",
"candlestick",
"width",
"from",
"the",
"request",
"context",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/middleware/apimiddleware.go#L876-L883 | train |
decred/dcrdata | dcrrates/rateserver/tls.go | openRPCKeyPair | func openRPCKeyPair(cfg *config) (credentials.TransportCredentials, error) {
// Generate a new keypair when the key is missing.
_, e := os.Stat(cfg.KeyPath)
keyExists := !os.IsNotExist(e)
if !keyExists {
cert, err := generateRPCKeyPair(cfg.CertificatePath, cfg.KeyPath, cfg.AltDNSNames, certWriter{})
if err != nil {
return nil, fmt.Errorf("Unable to generate TLS Certificate: %v", err)
}
// The certificate generated by generateRPCKeyPair has a nil Leaf. The x509
// certificate must be parsed from the raw bytes to access DNSNames and
// IPAddresses.
if len(cert.Certificate) == 0 {
return nil, fmt.Errorf("No raw certificate data found")
}
x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return nil, fmt.Errorf("Could not parse x509 certificate: %v", err)
}
hosts := x509Cert.DNSNames
for _, ip := range x509Cert.IPAddresses {
hosts = append(hosts, ip.String())
}
if len(hosts) > 0 {
log.Infof("TLS certificate created for hosts %s", strings.Join(hosts, ", "))
}
return credentials.NewServerTLSFromCert(&cert), nil
}
cert, err := tls.LoadX509KeyPair(cfg.CertificatePath, cfg.KeyPath)
if err != nil {
return nil, err
}
return credentials.NewServerTLSFromCert(&cert), nil
} | go | func openRPCKeyPair(cfg *config) (credentials.TransportCredentials, error) {
// Generate a new keypair when the key is missing.
_, e := os.Stat(cfg.KeyPath)
keyExists := !os.IsNotExist(e)
if !keyExists {
cert, err := generateRPCKeyPair(cfg.CertificatePath, cfg.KeyPath, cfg.AltDNSNames, certWriter{})
if err != nil {
return nil, fmt.Errorf("Unable to generate TLS Certificate: %v", err)
}
// The certificate generated by generateRPCKeyPair has a nil Leaf. The x509
// certificate must be parsed from the raw bytes to access DNSNames and
// IPAddresses.
if len(cert.Certificate) == 0 {
return nil, fmt.Errorf("No raw certificate data found")
}
x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return nil, fmt.Errorf("Could not parse x509 certificate: %v", err)
}
hosts := x509Cert.DNSNames
for _, ip := range x509Cert.IPAddresses {
hosts = append(hosts, ip.String())
}
if len(hosts) > 0 {
log.Infof("TLS certificate created for hosts %s", strings.Join(hosts, ", "))
}
return credentials.NewServerTLSFromCert(&cert), nil
}
cert, err := tls.LoadX509KeyPair(cfg.CertificatePath, cfg.KeyPath)
if err != nil {
return nil, err
}
return credentials.NewServerTLSFromCert(&cert), nil
} | [
"func",
"openRPCKeyPair",
"(",
"cfg",
"*",
"config",
")",
"(",
"credentials",
".",
"TransportCredentials",
",",
"error",
")",
"{",
"// Generate a new keypair when the key is missing.",
"_",
",",
"e",
":=",
"os",
".",
"Stat",
"(",
"cfg",
".",
"KeyPath",
")",
"\n",
"keyExists",
":=",
"!",
"os",
".",
"IsNotExist",
"(",
"e",
")",
"\n",
"if",
"!",
"keyExists",
"{",
"cert",
",",
"err",
":=",
"generateRPCKeyPair",
"(",
"cfg",
".",
"CertificatePath",
",",
"cfg",
".",
"KeyPath",
",",
"cfg",
".",
"AltDNSNames",
",",
"certWriter",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// The certificate generated by generateRPCKeyPair has a nil Leaf. The x509",
"// certificate must be parsed from the raw bytes to access DNSNames and",
"// IPAddresses.",
"if",
"len",
"(",
"cert",
".",
"Certificate",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"x509Cert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"cert",
".",
"Certificate",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"hosts",
":=",
"x509Cert",
".",
"DNSNames",
"\n",
"for",
"_",
",",
"ip",
":=",
"range",
"x509Cert",
".",
"IPAddresses",
"{",
"hosts",
"=",
"append",
"(",
"hosts",
",",
"ip",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"hosts",
")",
">",
"0",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"hosts",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"return",
"credentials",
".",
"NewServerTLSFromCert",
"(",
"&",
"cert",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"cert",
",",
"err",
":=",
"tls",
".",
"LoadX509KeyPair",
"(",
"cfg",
".",
"CertificatePath",
",",
"cfg",
".",
"KeyPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"credentials",
".",
"NewServerTLSFromCert",
"(",
"&",
"cert",
")",
",",
"nil",
"\n",
"}"
] | // openRPCKeyPair creates or loads the RPC TLS keypair specified by the
// application config. | [
"openRPCKeyPair",
"creates",
"or",
"loads",
"the",
"RPC",
"TLS",
"keypair",
"specified",
"by",
"the",
"application",
"config",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/dcrrates/rateserver/tls.go#L23-L58 | train |
decred/dcrdata | pubsub/psclient/client.go | Subscribe | func (c *Client) Subscribe(event string) (*pstypes.WebSocketMessage, error) {
// Validate the event type.
_, _, ok := pstypes.ValidateSubscription(event)
if !ok {
return nil, fmt.Errorf("invalid subscription %s", event)
}
// Send the subscribe message.
msg := newSubscribeMsg(event)
_ = c.SetWriteDeadline(time.Now().Add(c.WriteTimeout))
_, err := c.Write([]byte(msg))
if err != nil {
return nil, fmt.Errorf("failed to send subscribe message: %v", err)
}
// Read the response.
return c.ReceiveMsg()
} | go | func (c *Client) Subscribe(event string) (*pstypes.WebSocketMessage, error) {
// Validate the event type.
_, _, ok := pstypes.ValidateSubscription(event)
if !ok {
return nil, fmt.Errorf("invalid subscription %s", event)
}
// Send the subscribe message.
msg := newSubscribeMsg(event)
_ = c.SetWriteDeadline(time.Now().Add(c.WriteTimeout))
_, err := c.Write([]byte(msg))
if err != nil {
return nil, fmt.Errorf("failed to send subscribe message: %v", err)
}
// Read the response.
return c.ReceiveMsg()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Subscribe",
"(",
"event",
"string",
")",
"(",
"*",
"pstypes",
".",
"WebSocketMessage",
",",
"error",
")",
"{",
"// Validate the event type.",
"_",
",",
"_",
",",
"ok",
":=",
"pstypes",
".",
"ValidateSubscription",
"(",
"event",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"event",
")",
"\n",
"}",
"\n\n",
"// Send the subscribe message.",
"msg",
":=",
"newSubscribeMsg",
"(",
"event",
")",
"\n",
"_",
"=",
"c",
".",
"SetWriteDeadline",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"c",
".",
"WriteTimeout",
")",
")",
"\n",
"_",
",",
"err",
":=",
"c",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"msg",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Read the response.",
"return",
"c",
".",
"ReceiveMsg",
"(",
")",
"\n",
"}"
] | // Subscribe sends a subscribe type WebSocketMessage for the given event name
// after validating it. The response is returned. | [
"Subscribe",
"sends",
"a",
"subscribe",
"type",
"WebSocketMessage",
"for",
"the",
"given",
"event",
"name",
"after",
"validating",
"it",
".",
"The",
"response",
"is",
"returned",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/psclient/client.go#L52-L69 | train |
decred/dcrdata | pubsub/psclient/client.go | ReceiveMsgTimeout | func (c *Client) ReceiveMsgTimeout(timeout time.Duration) (*pstypes.WebSocketMessage, error) {
_ = c.SetReadDeadline(time.Now().Add(timeout))
msg := new(pstypes.WebSocketMessage)
if err := websocket.JSON.Receive(c.Conn, &msg); err != nil {
return nil, err
}
return msg, nil
} | go | func (c *Client) ReceiveMsgTimeout(timeout time.Duration) (*pstypes.WebSocketMessage, error) {
_ = c.SetReadDeadline(time.Now().Add(timeout))
msg := new(pstypes.WebSocketMessage)
if err := websocket.JSON.Receive(c.Conn, &msg); err != nil {
return nil, err
}
return msg, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"ReceiveMsgTimeout",
"(",
"timeout",
"time",
".",
"Duration",
")",
"(",
"*",
"pstypes",
".",
"WebSocketMessage",
",",
"error",
")",
"{",
"_",
"=",
"c",
".",
"SetReadDeadline",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"timeout",
")",
")",
"\n",
"msg",
":=",
"new",
"(",
"pstypes",
".",
"WebSocketMessage",
")",
"\n",
"if",
"err",
":=",
"websocket",
".",
"JSON",
".",
"Receive",
"(",
"c",
".",
"Conn",
",",
"&",
"msg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"msg",
",",
"nil",
"\n",
"}"
] | // ReceiveMsgTimeout waits for the specified time Duration for a message,
// returned decoded into a WebSocketMessage. | [
"ReceiveMsgTimeout",
"waits",
"for",
"the",
"specified",
"time",
"Duration",
"for",
"a",
"message",
"returned",
"decoded",
"into",
"a",
"WebSocketMessage",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/psclient/client.go#L94-L101 | train |
decred/dcrdata | pubsub/psclient/client.go | ReceiveMsg | func (c *Client) ReceiveMsg() (*pstypes.WebSocketMessage, error) {
return c.ReceiveMsgTimeout(c.ReadTimeout)
} | go | func (c *Client) ReceiveMsg() (*pstypes.WebSocketMessage, error) {
return c.ReceiveMsgTimeout(c.ReadTimeout)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"ReceiveMsg",
"(",
")",
"(",
"*",
"pstypes",
".",
"WebSocketMessage",
",",
"error",
")",
"{",
"return",
"c",
".",
"ReceiveMsgTimeout",
"(",
"c",
".",
"ReadTimeout",
")",
"\n",
"}"
] | // ReceiveMsg waits for a message, returned decoded into a WebSocketMessage. The
// Client's configured ReadTimeout is used. | [
"ReceiveMsg",
"waits",
"for",
"a",
"message",
"returned",
"decoded",
"into",
"a",
"WebSocketMessage",
".",
"The",
"Client",
"s",
"configured",
"ReadTimeout",
"is",
"used",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/psclient/client.go#L105-L107 | train |
decred/dcrdata | pubsub/psclient/client.go | ReceiveRaw | func (c *Client) ReceiveRaw() (message string, err error) {
_ = c.SetReadDeadline(time.Now().Add(c.ReadTimeout))
err = websocket.Message.Receive(c.Conn, &message)
return
} | go | func (c *Client) ReceiveRaw() (message string, err error) {
_ = c.SetReadDeadline(time.Now().Add(c.ReadTimeout))
err = websocket.Message.Receive(c.Conn, &message)
return
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"ReceiveRaw",
"(",
")",
"(",
"message",
"string",
",",
"err",
"error",
")",
"{",
"_",
"=",
"c",
".",
"SetReadDeadline",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"c",
".",
"ReadTimeout",
")",
")",
"\n",
"err",
"=",
"websocket",
".",
"Message",
".",
"Receive",
"(",
"c",
".",
"Conn",
",",
"&",
"message",
")",
"\n",
"return",
"\n",
"}"
] | // ReceiveRaw for a message, returned undecoded as a string. | [
"ReceiveRaw",
"for",
"a",
"message",
"returned",
"undecoded",
"as",
"a",
"string",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/psclient/client.go#L110-L114 | train |
decred/dcrdata | pubsub/psclient/client.go | DecodeMsgString | func DecodeMsgString(msg *pstypes.WebSocketMessage) (string, error) {
s, err := DecodeMsg(msg)
if err != nil {
return "", err
}
str, ok := s.(string)
if !ok {
return "", fmt.Errorf("content of Message was not of type string")
}
return str, nil
} | go | func DecodeMsgString(msg *pstypes.WebSocketMessage) (string, error) {
s, err := DecodeMsg(msg)
if err != nil {
return "", err
}
str, ok := s.(string)
if !ok {
return "", fmt.Errorf("content of Message was not of type string")
}
return str, nil
} | [
"func",
"DecodeMsgString",
"(",
"msg",
"*",
"pstypes",
".",
"WebSocketMessage",
")",
"(",
"string",
",",
"error",
")",
"{",
"s",
",",
"err",
":=",
"DecodeMsg",
"(",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"str",
",",
"ok",
":=",
"s",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"str",
",",
"nil",
"\n",
"}"
] | // DecodeMsgString attempts to decode the Message content of the given
// WebSocketMessage as a string. | [
"DecodeMsgString",
"attempts",
"to",
"decode",
"the",
"Message",
"content",
"of",
"the",
"given",
"WebSocketMessage",
"as",
"a",
"string",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/pubsub/psclient/client.go#L151-L161 | train |
decred/dcrdata | rpcutils/prefetcher.go | Stop | func (p *BlockPrefetchClient) Stop() {
p.Lock()
close(p.retargetChan)
p.Unlock()
} | go | func (p *BlockPrefetchClient) Stop() {
p.Lock()
close(p.retargetChan)
p.Unlock()
} | [
"func",
"(",
"p",
"*",
"BlockPrefetchClient",
")",
"Stop",
"(",
")",
"{",
"p",
".",
"Lock",
"(",
")",
"\n",
"close",
"(",
"p",
".",
"retargetChan",
")",
"\n",
"p",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Stop shuts down the fetcher goroutine. The BlockPrefetchClient may not be
// used after this. | [
"Stop",
"shuts",
"down",
"the",
"fetcher",
"goroutine",
".",
"The",
"BlockPrefetchClient",
"may",
"not",
"be",
"used",
"after",
"this",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L77-L81 | train |
decred/dcrdata | rpcutils/prefetcher.go | Hits | func (p *BlockPrefetchClient) Hits() uint64 {
p.Lock()
defer p.Unlock()
return p.hits
} | go | func (p *BlockPrefetchClient) Hits() uint64 {
p.Lock()
defer p.Unlock()
return p.hits
} | [
"func",
"(",
"p",
"*",
"BlockPrefetchClient",
")",
"Hits",
"(",
")",
"uint64",
"{",
"p",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"Unlock",
"(",
")",
"\n",
"return",
"p",
".",
"hits",
"\n",
"}"
] | // Hits safely returns the number of prefetch hits. | [
"Hits",
"safely",
"returns",
"the",
"number",
"of",
"prefetch",
"hits",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L84-L88 | train |
decred/dcrdata | rpcutils/prefetcher.go | Misses | func (p *BlockPrefetchClient) Misses() uint64 {
p.Lock()
defer p.Unlock()
return p.misses
} | go | func (p *BlockPrefetchClient) Misses() uint64 {
p.Lock()
defer p.Unlock()
return p.misses
} | [
"func",
"(",
"p",
"*",
"BlockPrefetchClient",
")",
"Misses",
"(",
")",
"uint64",
"{",
"p",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"Unlock",
"(",
")",
"\n",
"return",
"p",
".",
"misses",
"\n",
"}"
] | // Misses safely returns the number of prefetch misses. | [
"Misses",
"safely",
"returns",
"the",
"number",
"of",
"prefetch",
"misses",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L91-L95 | train |
decred/dcrdata | rpcutils/prefetcher.go | GetBestBlock | func (p *BlockPrefetchClient) GetBestBlock() (*chainhash.Hash, int64, error) {
return p.f.GetBestBlock()
} | go | func (p *BlockPrefetchClient) GetBestBlock() (*chainhash.Hash, int64, error) {
return p.f.GetBestBlock()
} | [
"func",
"(",
"p",
"*",
"BlockPrefetchClient",
")",
"GetBestBlock",
"(",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"int64",
",",
"error",
")",
"{",
"return",
"p",
".",
"f",
".",
"GetBestBlock",
"(",
")",
"\n",
"}"
] | // GetBestBlock is a passthrough to the client. It does not retarget the
// prefetch range since it does not request the actual block, just the hash and
// height of the best block. | [
"GetBestBlock",
"is",
"a",
"passthrough",
"to",
"the",
"client",
".",
"It",
"does",
"not",
"retarget",
"the",
"prefetch",
"range",
"since",
"it",
"does",
"not",
"request",
"the",
"actual",
"block",
"just",
"the",
"hash",
"and",
"height",
"of",
"the",
"best",
"block",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L100-L102 | train |
decred/dcrdata | rpcutils/prefetcher.go | GetBlockData | func (p *BlockPrefetchClient) GetBlockData(hash *chainhash.Hash) (*wire.MsgBlock, *dcrjson.GetBlockHeaderVerboseResult, error) {
p.Lock()
retargetAndUnlock := func(nextHash string) {
p.retarget(nextHash)
p.Unlock()
}
// If the block is already fetched, and the current block, return it. Do not
// retarget.
if p.current.hash == *hash /*p.haveBlockHash(*hash)*/ {
p.hits++
// Return the requested block.
defer p.Unlock()
return p.current.msgBlock, p.current.headerResult, nil
}
// If the block is already fetched, and next, return it and retarget with a
// new range starting at this block's height.
if p.next.hash == *hash /*p.haveBlockHash(*hash)*/ {
// Grab the result before retarget() changes p.next (via fetcher ->
// RetrieveAndStoreNext -> storeNext).
msgBlock, headerResult := p.next.msgBlock, p.next.headerResult
go retargetAndUnlock(p.next.headerResult.NextHash)
p.hits++
// Return the requested block.
return msgBlock, headerResult, nil
}
p.misses++
// Immediately retrieve msgBlock and header verbose result while fetcher is
// blocked by the Mutex.
msgBlock, headerResult, _, err := p.retrieveBlockAndHeaderResult(hash)
if err != nil {
p.Unlock()
return nil, nil, err
}
// Leaving the mutex locked, fire off a goroutine to retarget to the next
// block. The fetcher goroutine and other locking methods will stay blocked
// until the mutex unlocks, but the msgBlock can be returned right away.
go retargetAndUnlock(headerResult.NextHash)
return msgBlock, headerResult, err
} | go | func (p *BlockPrefetchClient) GetBlockData(hash *chainhash.Hash) (*wire.MsgBlock, *dcrjson.GetBlockHeaderVerboseResult, error) {
p.Lock()
retargetAndUnlock := func(nextHash string) {
p.retarget(nextHash)
p.Unlock()
}
// If the block is already fetched, and the current block, return it. Do not
// retarget.
if p.current.hash == *hash /*p.haveBlockHash(*hash)*/ {
p.hits++
// Return the requested block.
defer p.Unlock()
return p.current.msgBlock, p.current.headerResult, nil
}
// If the block is already fetched, and next, return it and retarget with a
// new range starting at this block's height.
if p.next.hash == *hash /*p.haveBlockHash(*hash)*/ {
// Grab the result before retarget() changes p.next (via fetcher ->
// RetrieveAndStoreNext -> storeNext).
msgBlock, headerResult := p.next.msgBlock, p.next.headerResult
go retargetAndUnlock(p.next.headerResult.NextHash)
p.hits++
// Return the requested block.
return msgBlock, headerResult, nil
}
p.misses++
// Immediately retrieve msgBlock and header verbose result while fetcher is
// blocked by the Mutex.
msgBlock, headerResult, _, err := p.retrieveBlockAndHeaderResult(hash)
if err != nil {
p.Unlock()
return nil, nil, err
}
// Leaving the mutex locked, fire off a goroutine to retarget to the next
// block. The fetcher goroutine and other locking methods will stay blocked
// until the mutex unlocks, but the msgBlock can be returned right away.
go retargetAndUnlock(headerResult.NextHash)
return msgBlock, headerResult, err
} | [
"func",
"(",
"p",
"*",
"BlockPrefetchClient",
")",
"GetBlockData",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"wire",
".",
"MsgBlock",
",",
"*",
"dcrjson",
".",
"GetBlockHeaderVerboseResult",
",",
"error",
")",
"{",
"p",
".",
"Lock",
"(",
")",
"\n\n",
"retargetAndUnlock",
":=",
"func",
"(",
"nextHash",
"string",
")",
"{",
"p",
".",
"retarget",
"(",
"nextHash",
")",
"\n",
"p",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n\n",
"// If the block is already fetched, and the current block, return it. Do not",
"// retarget.",
"if",
"p",
".",
"current",
".",
"hash",
"==",
"*",
"hash",
"/*p.haveBlockHash(*hash)*/",
"{",
"p",
".",
"hits",
"++",
"\n",
"// Return the requested block.",
"defer",
"p",
".",
"Unlock",
"(",
")",
"\n",
"return",
"p",
".",
"current",
".",
"msgBlock",
",",
"p",
".",
"current",
".",
"headerResult",
",",
"nil",
"\n",
"}",
"\n\n",
"// If the block is already fetched, and next, return it and retarget with a",
"// new range starting at this block's height.",
"if",
"p",
".",
"next",
".",
"hash",
"==",
"*",
"hash",
"/*p.haveBlockHash(*hash)*/",
"{",
"// Grab the result before retarget() changes p.next (via fetcher ->",
"// RetrieveAndStoreNext -> storeNext).",
"msgBlock",
",",
"headerResult",
":=",
"p",
".",
"next",
".",
"msgBlock",
",",
"p",
".",
"next",
".",
"headerResult",
"\n",
"go",
"retargetAndUnlock",
"(",
"p",
".",
"next",
".",
"headerResult",
".",
"NextHash",
")",
"\n",
"p",
".",
"hits",
"++",
"\n",
"// Return the requested block.",
"return",
"msgBlock",
",",
"headerResult",
",",
"nil",
"\n",
"}",
"\n\n",
"p",
".",
"misses",
"++",
"\n\n",
"// Immediately retrieve msgBlock and header verbose result while fetcher is",
"// blocked by the Mutex.",
"msgBlock",
",",
"headerResult",
",",
"_",
",",
"err",
":=",
"p",
".",
"retrieveBlockAndHeaderResult",
"(",
"hash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"p",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Leaving the mutex locked, fire off a goroutine to retarget to the next",
"// block. The fetcher goroutine and other locking methods will stay blocked",
"// until the mutex unlocks, but the msgBlock can be returned right away.",
"go",
"retargetAndUnlock",
"(",
"headerResult",
".",
"NextHash",
")",
"\n\n",
"return",
"msgBlock",
",",
"headerResult",
",",
"err",
"\n",
"}"
] | // GetBlockData attempts to get the specified block and retargets the prefetcher
// with the next block's hash. If the block was not already fetched, it is
// retrieved immediately and stored following retargeting. | [
"GetBlockData",
"attempts",
"to",
"get",
"the",
"specified",
"block",
"and",
"retargets",
"the",
"prefetcher",
"with",
"the",
"next",
"block",
"s",
"hash",
".",
"If",
"the",
"block",
"was",
"not",
"already",
"fetched",
"it",
"is",
"retrieved",
"immediately",
"and",
"stored",
"following",
"retargeting",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L107-L152 | train |
decred/dcrdata | rpcutils/prefetcher.go | GetBlock | func (p *BlockPrefetchClient) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error) {
msgBlock, _, err := p.GetBlockData(hash)
return msgBlock, err
} | go | func (p *BlockPrefetchClient) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error) {
msgBlock, _, err := p.GetBlockData(hash)
return msgBlock, err
} | [
"func",
"(",
"p",
"*",
"BlockPrefetchClient",
")",
"GetBlock",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"wire",
".",
"MsgBlock",
",",
"error",
")",
"{",
"msgBlock",
",",
"_",
",",
"err",
":=",
"p",
".",
"GetBlockData",
"(",
"hash",
")",
"\n",
"return",
"msgBlock",
",",
"err",
"\n",
"}"
] | // GetBlock retrieves the wire.MsgBlock for the block with the specified hash.
// See GetBlockData for details on how this interacts with the prefetcher. | [
"GetBlock",
"retrieves",
"the",
"wire",
".",
"MsgBlock",
"for",
"the",
"block",
"with",
"the",
"specified",
"hash",
".",
"See",
"GetBlockData",
"for",
"details",
"on",
"how",
"this",
"interacts",
"with",
"the",
"prefetcher",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L156-L159 | train |
decred/dcrdata | rpcutils/prefetcher.go | GetBlockHeaderVerbose | func (p *BlockPrefetchClient) GetBlockHeaderVerbose(hash *chainhash.Hash) (*dcrjson.GetBlockHeaderVerboseResult, error) {
_, headerResult, err := p.GetBlockData(hash)
return headerResult, err
} | go | func (p *BlockPrefetchClient) GetBlockHeaderVerbose(hash *chainhash.Hash) (*dcrjson.GetBlockHeaderVerboseResult, error) {
_, headerResult, err := p.GetBlockData(hash)
return headerResult, err
} | [
"func",
"(",
"p",
"*",
"BlockPrefetchClient",
")",
"GetBlockHeaderVerbose",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"dcrjson",
".",
"GetBlockHeaderVerboseResult",
",",
"error",
")",
"{",
"_",
",",
"headerResult",
",",
"err",
":=",
"p",
".",
"GetBlockData",
"(",
"hash",
")",
"\n",
"return",
"headerResult",
",",
"err",
"\n",
"}"
] | // GetBlockHeaderVerbose retrieves the dcrjson.GetBlockHeaderVerboseResult for
// the block with the specified hash. See GetBlockData for details on how this
// interacts with the prefetcher | [
"GetBlockHeaderVerbose",
"retrieves",
"the",
"dcrjson",
".",
"GetBlockHeaderVerboseResult",
"for",
"the",
"block",
"with",
"the",
"specified",
"hash",
".",
"See",
"GetBlockData",
"for",
"details",
"on",
"how",
"this",
"interacts",
"with",
"the",
"prefetcher"
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L164-L167 | train |
decred/dcrdata | rpcutils/prefetcher.go | storeNext | func (p *BlockPrefetchClient) storeNext(msgBlock *wire.MsgBlock, headerResult *dcrjson.GetBlockHeaderVerboseResult) {
p.current = p.next
p.next = &blockData{
height: msgBlock.Header.Height,
hash: msgBlock.BlockHash(),
msgBlock: msgBlock,
headerResult: headerResult,
}
} | go | func (p *BlockPrefetchClient) storeNext(msgBlock *wire.MsgBlock, headerResult *dcrjson.GetBlockHeaderVerboseResult) {
p.current = p.next
p.next = &blockData{
height: msgBlock.Header.Height,
hash: msgBlock.BlockHash(),
msgBlock: msgBlock,
headerResult: headerResult,
}
} | [
"func",
"(",
"p",
"*",
"BlockPrefetchClient",
")",
"storeNext",
"(",
"msgBlock",
"*",
"wire",
".",
"MsgBlock",
",",
"headerResult",
"*",
"dcrjson",
".",
"GetBlockHeaderVerboseResult",
")",
"{",
"p",
".",
"current",
"=",
"p",
".",
"next",
"\n",
"p",
".",
"next",
"=",
"&",
"blockData",
"{",
"height",
":",
"msgBlock",
".",
"Header",
".",
"Height",
",",
"hash",
":",
"msgBlock",
".",
"BlockHash",
"(",
")",
",",
"msgBlock",
":",
"msgBlock",
",",
"headerResult",
":",
"headerResult",
",",
"}",
"\n",
"}"
] | // storeNext stores the input data as the new "next" block. The existing "next"
// becomes "current". | [
"storeNext",
"stores",
"the",
"input",
"data",
"as",
"the",
"new",
"next",
"block",
".",
"The",
"existing",
"next",
"becomes",
"current",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L192-L200 | train |
decred/dcrdata | rpcutils/prefetcher.go | RetrieveAndStoreNext | func (p *BlockPrefetchClient) RetrieveAndStoreNext(nextHash *chainhash.Hash) {
p.Lock()
defer p.Unlock()
// Fetch the next block, if needed.
if p.haveBlockHash(*nextHash) {
return
}
msgBlock, headerResult, _, err := p.retrieveBlockAndHeaderResult(nextHash)
if err != nil {
if strings.HasPrefix(err.Error(), outOfRangeErr) {
log.Errorf("retrieveBlockAndHeaderResult(%v): %v",
nextHash, err)
}
return
}
// Store this block's data.
p.storeNext(msgBlock, headerResult)
} | go | func (p *BlockPrefetchClient) RetrieveAndStoreNext(nextHash *chainhash.Hash) {
p.Lock()
defer p.Unlock()
// Fetch the next block, if needed.
if p.haveBlockHash(*nextHash) {
return
}
msgBlock, headerResult, _, err := p.retrieveBlockAndHeaderResult(nextHash)
if err != nil {
if strings.HasPrefix(err.Error(), outOfRangeErr) {
log.Errorf("retrieveBlockAndHeaderResult(%v): %v",
nextHash, err)
}
return
}
// Store this block's data.
p.storeNext(msgBlock, headerResult)
} | [
"func",
"(",
"p",
"*",
"BlockPrefetchClient",
")",
"RetrieveAndStoreNext",
"(",
"nextHash",
"*",
"chainhash",
".",
"Hash",
")",
"{",
"p",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"Unlock",
"(",
")",
"\n\n",
"// Fetch the next block, if needed.",
"if",
"p",
".",
"haveBlockHash",
"(",
"*",
"nextHash",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"msgBlock",
",",
"headerResult",
",",
"_",
",",
"err",
":=",
"p",
".",
"retrieveBlockAndHeaderResult",
"(",
"nextHash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"err",
".",
"Error",
"(",
")",
",",
"outOfRangeErr",
")",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"nextHash",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Store this block's data.",
"p",
".",
"storeNext",
"(",
"msgBlock",
",",
"headerResult",
")",
"\n",
"}"
] | // RetrieveAndStoreNext retrieves the next block specified by the Hash, if it is
// not already the stored next block, and stores the block data. The existing
// "next" becomes "current". | [
"RetrieveAndStoreNext",
"retrieves",
"the",
"next",
"block",
"specified",
"by",
"the",
"Hash",
"if",
"it",
"is",
"not",
"already",
"the",
"stored",
"next",
"block",
"and",
"stores",
"the",
"block",
"data",
".",
"The",
"existing",
"next",
"becomes",
"current",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L220-L240 | train |
decred/dcrdata | rpcutils/prefetcher.go | HaveBlockHeight | func (p *BlockPrefetchClient) HaveBlockHeight(height uint32) bool {
p.Lock()
defer p.Unlock()
return p.haveBlockHeight(height)
} | go | func (p *BlockPrefetchClient) HaveBlockHeight(height uint32) bool {
p.Lock()
defer p.Unlock()
return p.haveBlockHeight(height)
} | [
"func",
"(",
"p",
"*",
"BlockPrefetchClient",
")",
"HaveBlockHeight",
"(",
"height",
"uint32",
")",
"bool",
"{",
"p",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"Unlock",
"(",
")",
"\n",
"return",
"p",
".",
"haveBlockHeight",
"(",
"height",
")",
"\n",
"}"
] | // HaveBlockHeight checks if the current or prefetched next block is for a block
// with the specified height. Use HaveBlockHash to be sure it is the desired
// block. | [
"HaveBlockHeight",
"checks",
"if",
"the",
"current",
"or",
"prefetched",
"next",
"block",
"is",
"for",
"a",
"block",
"with",
"the",
"specified",
"height",
".",
"Use",
"HaveBlockHash",
"to",
"be",
"sure",
"it",
"is",
"the",
"desired",
"block",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L257-L261 | train |
decred/dcrdata | rpcutils/prefetcher.go | HaveBlockHash | func (p *BlockPrefetchClient) HaveBlockHash(hash chainhash.Hash) bool {
p.Lock()
defer p.Unlock()
return p.haveBlockHash(hash)
} | go | func (p *BlockPrefetchClient) HaveBlockHash(hash chainhash.Hash) bool {
p.Lock()
defer p.Unlock()
return p.haveBlockHash(hash)
} | [
"func",
"(",
"p",
"*",
"BlockPrefetchClient",
")",
"HaveBlockHash",
"(",
"hash",
"chainhash",
".",
"Hash",
")",
"bool",
"{",
"p",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"Unlock",
"(",
")",
"\n",
"return",
"p",
".",
"haveBlockHash",
"(",
"hash",
")",
"\n",
"}"
] | // HaveBlockHash checks if the current or prefetched next block is for a block
// with the specified hash. | [
"HaveBlockHash",
"checks",
"if",
"the",
"current",
"or",
"prefetched",
"next",
"block",
"is",
"for",
"a",
"block",
"with",
"the",
"specified",
"hash",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/prefetcher.go#L269-L273 | train |
decred/dcrdata | gov/agendas/tracker.go | NewVoteTracker | func NewVoteTracker(params *chaincfg.Params, node VoteDataSource, counter voteCounter,
activeVersions map[uint32][]chaincfg.ConsensusDeployment) (*VoteTracker, error) {
var latestStakeVersion uint32
var starttime uint64
// Consensus deployments that share a stake version as the key should also
// have matching starttime.
for stakeVersion, val := range activeVersions {
if latestStakeVersion == 0 {
latestStakeVersion = stakeVersion
starttime = val[0].StartTime
} else if val[0].StartTime >= starttime {
latestStakeVersion = stakeVersion
starttime = val[0].StartTime
}
}
tracker := &VoteTracker{
mtx: sync.RWMutex{},
node: node,
voteCounter: counter,
countCache: make(map[string]*voteCount),
params: params,
version: latestStakeVersion,
ringIndex: -1,
blockRing: make([]int32, params.BlockUpgradeNumToCheck),
minerThreshold: float32(params.BlockRejectNumRequired) / float32(params.BlockUpgradeNumToCheck),
voterThreshold: float32(params.RuleChangeActivationMultiplier) / float32(params.RuleChangeActivationDivisor),
sviBlocks: uint32(params.StakeVersionInterval),
rciBlocks: params.RuleChangeActivationInterval,
blockTime: int64(params.TargetTimePerBlock.Seconds()),
passThreshold: float32(params.RuleChangeActivationMultiplier) / float32(params.RuleChangeActivationDivisor),
rciVotes: uint32(params.TicketsPerBlock) * params.RuleChangeActivationInterval,
}
// first sync has different error handling than Refresh.
voteInfo, err := tracker.refreshRCI()
if err != nil {
return nil, err
}
blocksToAdd, stakeVersion, err := tracker.fetchBlocks(voteInfo)
if err != nil {
return nil, err
}
stakeInfo, err := tracker.refreshSVIs(voteInfo)
if err != nil {
return nil, err
}
tracker.update(voteInfo, blocksToAdd, stakeInfo, stakeVersion)
return tracker, nil
} | go | func NewVoteTracker(params *chaincfg.Params, node VoteDataSource, counter voteCounter,
activeVersions map[uint32][]chaincfg.ConsensusDeployment) (*VoteTracker, error) {
var latestStakeVersion uint32
var starttime uint64
// Consensus deployments that share a stake version as the key should also
// have matching starttime.
for stakeVersion, val := range activeVersions {
if latestStakeVersion == 0 {
latestStakeVersion = stakeVersion
starttime = val[0].StartTime
} else if val[0].StartTime >= starttime {
latestStakeVersion = stakeVersion
starttime = val[0].StartTime
}
}
tracker := &VoteTracker{
mtx: sync.RWMutex{},
node: node,
voteCounter: counter,
countCache: make(map[string]*voteCount),
params: params,
version: latestStakeVersion,
ringIndex: -1,
blockRing: make([]int32, params.BlockUpgradeNumToCheck),
minerThreshold: float32(params.BlockRejectNumRequired) / float32(params.BlockUpgradeNumToCheck),
voterThreshold: float32(params.RuleChangeActivationMultiplier) / float32(params.RuleChangeActivationDivisor),
sviBlocks: uint32(params.StakeVersionInterval),
rciBlocks: params.RuleChangeActivationInterval,
blockTime: int64(params.TargetTimePerBlock.Seconds()),
passThreshold: float32(params.RuleChangeActivationMultiplier) / float32(params.RuleChangeActivationDivisor),
rciVotes: uint32(params.TicketsPerBlock) * params.RuleChangeActivationInterval,
}
// first sync has different error handling than Refresh.
voteInfo, err := tracker.refreshRCI()
if err != nil {
return nil, err
}
blocksToAdd, stakeVersion, err := tracker.fetchBlocks(voteInfo)
if err != nil {
return nil, err
}
stakeInfo, err := tracker.refreshSVIs(voteInfo)
if err != nil {
return nil, err
}
tracker.update(voteInfo, blocksToAdd, stakeInfo, stakeVersion)
return tracker, nil
} | [
"func",
"NewVoteTracker",
"(",
"params",
"*",
"chaincfg",
".",
"Params",
",",
"node",
"VoteDataSource",
",",
"counter",
"voteCounter",
",",
"activeVersions",
"map",
"[",
"uint32",
"]",
"[",
"]",
"chaincfg",
".",
"ConsensusDeployment",
")",
"(",
"*",
"VoteTracker",
",",
"error",
")",
"{",
"var",
"latestStakeVersion",
"uint32",
"\n",
"var",
"starttime",
"uint64",
"\n\n",
"// Consensus deployments that share a stake version as the key should also",
"// have matching starttime.",
"for",
"stakeVersion",
",",
"val",
":=",
"range",
"activeVersions",
"{",
"if",
"latestStakeVersion",
"==",
"0",
"{",
"latestStakeVersion",
"=",
"stakeVersion",
"\n",
"starttime",
"=",
"val",
"[",
"0",
"]",
".",
"StartTime",
"\n",
"}",
"else",
"if",
"val",
"[",
"0",
"]",
".",
"StartTime",
">=",
"starttime",
"{",
"latestStakeVersion",
"=",
"stakeVersion",
"\n",
"starttime",
"=",
"val",
"[",
"0",
"]",
".",
"StartTime",
"\n",
"}",
"\n",
"}",
"\n\n",
"tracker",
":=",
"&",
"VoteTracker",
"{",
"mtx",
":",
"sync",
".",
"RWMutex",
"{",
"}",
",",
"node",
":",
"node",
",",
"voteCounter",
":",
"counter",
",",
"countCache",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"voteCount",
")",
",",
"params",
":",
"params",
",",
"version",
":",
"latestStakeVersion",
",",
"ringIndex",
":",
"-",
"1",
",",
"blockRing",
":",
"make",
"(",
"[",
"]",
"int32",
",",
"params",
".",
"BlockUpgradeNumToCheck",
")",
",",
"minerThreshold",
":",
"float32",
"(",
"params",
".",
"BlockRejectNumRequired",
")",
"/",
"float32",
"(",
"params",
".",
"BlockUpgradeNumToCheck",
")",
",",
"voterThreshold",
":",
"float32",
"(",
"params",
".",
"RuleChangeActivationMultiplier",
")",
"/",
"float32",
"(",
"params",
".",
"RuleChangeActivationDivisor",
")",
",",
"sviBlocks",
":",
"uint32",
"(",
"params",
".",
"StakeVersionInterval",
")",
",",
"rciBlocks",
":",
"params",
".",
"RuleChangeActivationInterval",
",",
"blockTime",
":",
"int64",
"(",
"params",
".",
"TargetTimePerBlock",
".",
"Seconds",
"(",
")",
")",
",",
"passThreshold",
":",
"float32",
"(",
"params",
".",
"RuleChangeActivationMultiplier",
")",
"/",
"float32",
"(",
"params",
".",
"RuleChangeActivationDivisor",
")",
",",
"rciVotes",
":",
"uint32",
"(",
"params",
".",
"TicketsPerBlock",
")",
"*",
"params",
".",
"RuleChangeActivationInterval",
",",
"}",
"\n\n",
"// first sync has different error handling than Refresh.",
"voteInfo",
",",
"err",
":=",
"tracker",
".",
"refreshRCI",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"blocksToAdd",
",",
"stakeVersion",
",",
"err",
":=",
"tracker",
".",
"fetchBlocks",
"(",
"voteInfo",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"stakeInfo",
",",
"err",
":=",
"tracker",
".",
"refreshSVIs",
"(",
"voteInfo",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"tracker",
".",
"update",
"(",
"voteInfo",
",",
"blocksToAdd",
",",
"stakeInfo",
",",
"stakeVersion",
")",
"\n\n",
"return",
"tracker",
",",
"nil",
"\n",
"}"
] | // NewVoteTracker is a constructor for a VoteTracker. | [
"NewVoteTracker",
"is",
"a",
"constructor",
"for",
"a",
"VoteTracker",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L130-L181 | train |
decred/dcrdata | gov/agendas/tracker.go | Refresh | func (tracker *VoteTracker) Refresh() {
voteInfo, err := tracker.refreshRCI()
if err != nil {
log.Errorf("VoteTracker.Refresh -> refreshRCI: %v")
return
}
blocksToAdd, stakeVersion, err := tracker.fetchBlocks(voteInfo)
if err != nil {
log.Errorf("VoteTracker.Refresh -> fetchBlocks: %v")
return
}
stakeInfo, err := tracker.refreshSVIs(voteInfo)
if err != nil {
log.Errorf("VoteTracker.Refresh -> refreshSVIs: %v")
return
}
tracker.update(voteInfo, blocksToAdd, stakeInfo, stakeVersion)
} | go | func (tracker *VoteTracker) Refresh() {
voteInfo, err := tracker.refreshRCI()
if err != nil {
log.Errorf("VoteTracker.Refresh -> refreshRCI: %v")
return
}
blocksToAdd, stakeVersion, err := tracker.fetchBlocks(voteInfo)
if err != nil {
log.Errorf("VoteTracker.Refresh -> fetchBlocks: %v")
return
}
stakeInfo, err := tracker.refreshSVIs(voteInfo)
if err != nil {
log.Errorf("VoteTracker.Refresh -> refreshSVIs: %v")
return
}
tracker.update(voteInfo, blocksToAdd, stakeInfo, stakeVersion)
} | [
"func",
"(",
"tracker",
"*",
"VoteTracker",
")",
"Refresh",
"(",
")",
"{",
"voteInfo",
",",
"err",
":=",
"tracker",
".",
"refreshRCI",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"blocksToAdd",
",",
"stakeVersion",
",",
"err",
":=",
"tracker",
".",
"fetchBlocks",
"(",
"voteInfo",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"stakeInfo",
",",
"err",
":=",
"tracker",
".",
"refreshSVIs",
"(",
"voteInfo",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"tracker",
".",
"update",
"(",
"voteInfo",
",",
"blocksToAdd",
",",
"stakeInfo",
",",
"stakeVersion",
")",
"\n",
"}"
] | // Refresh refreshes node version and vote data. It can be called as a
// goroutine. All VoteTracker updating and mutex locking is handled within
// VoteTracker.update. | [
"Refresh",
"refreshes",
"node",
"version",
"and",
"vote",
"data",
".",
"It",
"can",
"be",
"called",
"as",
"a",
"goroutine",
".",
"All",
"VoteTracker",
"updating",
"and",
"mutex",
"locking",
"is",
"handled",
"within",
"VoteTracker",
".",
"update",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L186-L203 | train |
decred/dcrdata | gov/agendas/tracker.go | Version | func (tracker *VoteTracker) Version() uint32 {
tracker.mtx.RLock()
defer tracker.mtx.RUnlock()
return tracker.version
} | go | func (tracker *VoteTracker) Version() uint32 {
tracker.mtx.RLock()
defer tracker.mtx.RUnlock()
return tracker.version
} | [
"func",
"(",
"tracker",
"*",
"VoteTracker",
")",
"Version",
"(",
")",
"uint32",
"{",
"tracker",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"tracker",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"tracker",
".",
"version",
"\n",
"}"
] | // Version returns the current best known vote version.
// Since version could technically be updated without turning off dcrdata,
// the field must be protected. | [
"Version",
"returns",
"the",
"current",
"best",
"known",
"vote",
"version",
".",
"Since",
"version",
"could",
"technically",
"be",
"updated",
"without",
"turning",
"off",
"dcrdata",
"the",
"field",
"must",
"be",
"protected",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L208-L212 | train |
decred/dcrdata | gov/agendas/tracker.go | refreshRCI | func (tracker *VoteTracker) refreshRCI() (*dcrjson.GetVoteInfoResult, error) {
oldVersion := tracker.Version()
v := oldVersion
var err error
var voteInfo, vinfo *dcrjson.GetVoteInfoResult
// Retrieves the voteinfo for the last stake version supported.
for {
vinfo, err = tracker.node.GetVoteInfo(v)
if err != nil {
break
}
voteInfo = vinfo
v++
}
if voteInfo == nil {
return nil, fmt.Errorf("Vote information not found: %v", err)
}
if v > oldVersion+1 {
tracker.mtx.Lock()
tracker.version = v
tracker.mtx.Unlock()
}
return voteInfo, nil
} | go | func (tracker *VoteTracker) refreshRCI() (*dcrjson.GetVoteInfoResult, error) {
oldVersion := tracker.Version()
v := oldVersion
var err error
var voteInfo, vinfo *dcrjson.GetVoteInfoResult
// Retrieves the voteinfo for the last stake version supported.
for {
vinfo, err = tracker.node.GetVoteInfo(v)
if err != nil {
break
}
voteInfo = vinfo
v++
}
if voteInfo == nil {
return nil, fmt.Errorf("Vote information not found: %v", err)
}
if v > oldVersion+1 {
tracker.mtx.Lock()
tracker.version = v
tracker.mtx.Unlock()
}
return voteInfo, nil
} | [
"func",
"(",
"tracker",
"*",
"VoteTracker",
")",
"refreshRCI",
"(",
")",
"(",
"*",
"dcrjson",
".",
"GetVoteInfoResult",
",",
"error",
")",
"{",
"oldVersion",
":=",
"tracker",
".",
"Version",
"(",
")",
"\n",
"v",
":=",
"oldVersion",
"\n",
"var",
"err",
"error",
"\n",
"var",
"voteInfo",
",",
"vinfo",
"*",
"dcrjson",
".",
"GetVoteInfoResult",
"\n\n",
"// Retrieves the voteinfo for the last stake version supported.",
"for",
"{",
"vinfo",
",",
"err",
"=",
"tracker",
".",
"node",
".",
"GetVoteInfo",
"(",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"voteInfo",
"=",
"vinfo",
"\n",
"v",
"++",
"\n",
"}",
"\n\n",
"if",
"voteInfo",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"v",
">",
"oldVersion",
"+",
"1",
"{",
"tracker",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"tracker",
".",
"version",
"=",
"v",
"\n",
"tracker",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"return",
"voteInfo",
",",
"nil",
"\n",
"}"
] | // Grab the getvoteinfo data. Do not update VoteTracker.voteInfo here, as it
// will be updated with other fields under mutex lock in VoteTracker.update. | [
"Grab",
"the",
"getvoteinfo",
"data",
".",
"Do",
"not",
"update",
"VoteTracker",
".",
"voteInfo",
"here",
"as",
"it",
"will",
"be",
"updated",
"with",
"other",
"fields",
"under",
"mutex",
"lock",
"in",
"VoteTracker",
".",
"update",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L216-L241 | train |
decred/dcrdata | gov/agendas/tracker.go | fetchBlocks | func (tracker *VoteTracker) fetchBlocks(voteInfo *dcrjson.GetVoteInfoResult) ([]int32, uint32, error) {
blocksToRequest := 1
// If this isn't the next block, request them all again
if voteInfo.CurrentHeight < 0 || voteInfo.CurrentHeight != tracker.ringHeight+1 {
blocksToRequest = int(tracker.params.BlockUpgradeNumToCheck)
}
r, err := tracker.node.GetStakeVersions(voteInfo.Hash, int32(blocksToRequest))
if err != nil {
return nil, 0, err
}
blockCount := len(r.StakeVersions)
if blockCount != blocksToRequest {
return nil, 0, fmt.Errorf("Unexpected number of blocks returns from GetStakeVersions. Asked for %d, received %d", blocksToRequest, blockCount)
}
blocks := make([]int32, blockCount)
var block dcrjson.StakeVersions
for i := 0; i < blockCount; i++ {
block = r.StakeVersions[blockCount-i-1] // iterate backwards
tracker.ringIndex = (tracker.ringIndex + 1) % blockCount
blocks[i] = block.BlockVersion
}
return blocks, block.StakeVersion, nil
} | go | func (tracker *VoteTracker) fetchBlocks(voteInfo *dcrjson.GetVoteInfoResult) ([]int32, uint32, error) {
blocksToRequest := 1
// If this isn't the next block, request them all again
if voteInfo.CurrentHeight < 0 || voteInfo.CurrentHeight != tracker.ringHeight+1 {
blocksToRequest = int(tracker.params.BlockUpgradeNumToCheck)
}
r, err := tracker.node.GetStakeVersions(voteInfo.Hash, int32(blocksToRequest))
if err != nil {
return nil, 0, err
}
blockCount := len(r.StakeVersions)
if blockCount != blocksToRequest {
return nil, 0, fmt.Errorf("Unexpected number of blocks returns from GetStakeVersions. Asked for %d, received %d", blocksToRequest, blockCount)
}
blocks := make([]int32, blockCount)
var block dcrjson.StakeVersions
for i := 0; i < blockCount; i++ {
block = r.StakeVersions[blockCount-i-1] // iterate backwards
tracker.ringIndex = (tracker.ringIndex + 1) % blockCount
blocks[i] = block.BlockVersion
}
return blocks, block.StakeVersion, nil
} | [
"func",
"(",
"tracker",
"*",
"VoteTracker",
")",
"fetchBlocks",
"(",
"voteInfo",
"*",
"dcrjson",
".",
"GetVoteInfoResult",
")",
"(",
"[",
"]",
"int32",
",",
"uint32",
",",
"error",
")",
"{",
"blocksToRequest",
":=",
"1",
"\n",
"// If this isn't the next block, request them all again",
"if",
"voteInfo",
".",
"CurrentHeight",
"<",
"0",
"||",
"voteInfo",
".",
"CurrentHeight",
"!=",
"tracker",
".",
"ringHeight",
"+",
"1",
"{",
"blocksToRequest",
"=",
"int",
"(",
"tracker",
".",
"params",
".",
"BlockUpgradeNumToCheck",
")",
"\n",
"}",
"\n",
"r",
",",
"err",
":=",
"tracker",
".",
"node",
".",
"GetStakeVersions",
"(",
"voteInfo",
".",
"Hash",
",",
"int32",
"(",
"blocksToRequest",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"err",
"\n",
"}",
"\n",
"blockCount",
":=",
"len",
"(",
"r",
".",
"StakeVersions",
")",
"\n",
"if",
"blockCount",
"!=",
"blocksToRequest",
"{",
"return",
"nil",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"blocksToRequest",
",",
"blockCount",
")",
"\n",
"}",
"\n",
"blocks",
":=",
"make",
"(",
"[",
"]",
"int32",
",",
"blockCount",
")",
"\n",
"var",
"block",
"dcrjson",
".",
"StakeVersions",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"blockCount",
";",
"i",
"++",
"{",
"block",
"=",
"r",
".",
"StakeVersions",
"[",
"blockCount",
"-",
"i",
"-",
"1",
"]",
"// iterate backwards",
"\n",
"tracker",
".",
"ringIndex",
"=",
"(",
"tracker",
".",
"ringIndex",
"+",
"1",
")",
"%",
"blockCount",
"\n",
"blocks",
"[",
"i",
"]",
"=",
"block",
".",
"BlockVersion",
"\n",
"}",
"\n",
"return",
"blocks",
",",
"block",
".",
"StakeVersion",
",",
"nil",
"\n",
"}"
] | // Grab the block versions for up to the last BlockUpgradeNumToCheck blocks.
// If the current block builds upon the last block, only request a single
// block's data. Otherwise, request all BlockUpgradeNumToCheck. | [
"Grab",
"the",
"block",
"versions",
"for",
"up",
"to",
"the",
"last",
"BlockUpgradeNumToCheck",
"blocks",
".",
"If",
"the",
"current",
"block",
"builds",
"upon",
"the",
"last",
"block",
"only",
"request",
"a",
"single",
"block",
"s",
"data",
".",
"Otherwise",
"request",
"all",
"BlockUpgradeNumToCheck",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L251-L273 | train |
decred/dcrdata | gov/agendas/tracker.go | refreshSVIs | func (tracker *VoteTracker) refreshSVIs(voteInfo *dcrjson.GetVoteInfoResult) (*dcrjson.GetStakeVersionInfoResult, error) {
blocksInCurrentRCI := rciBlocks(voteInfo)
svis := int32(blocksInCurrentRCI / tracker.params.StakeVersionInterval)
// blocksInCurrentSVI := int32(blocksInCurrentRCI % params.StakeVersionInterval)
if blocksInCurrentRCI%tracker.params.StakeVersionInterval > 0 {
svis++
}
si, err := tracker.node.GetStakeVersionInfo(svis)
if err != nil {
return nil, fmt.Errorf("Error retrieving stake version info: %v", err)
}
return si, nil
} | go | func (tracker *VoteTracker) refreshSVIs(voteInfo *dcrjson.GetVoteInfoResult) (*dcrjson.GetStakeVersionInfoResult, error) {
blocksInCurrentRCI := rciBlocks(voteInfo)
svis := int32(blocksInCurrentRCI / tracker.params.StakeVersionInterval)
// blocksInCurrentSVI := int32(blocksInCurrentRCI % params.StakeVersionInterval)
if blocksInCurrentRCI%tracker.params.StakeVersionInterval > 0 {
svis++
}
si, err := tracker.node.GetStakeVersionInfo(svis)
if err != nil {
return nil, fmt.Errorf("Error retrieving stake version info: %v", err)
}
return si, nil
} | [
"func",
"(",
"tracker",
"*",
"VoteTracker",
")",
"refreshSVIs",
"(",
"voteInfo",
"*",
"dcrjson",
".",
"GetVoteInfoResult",
")",
"(",
"*",
"dcrjson",
".",
"GetStakeVersionInfoResult",
",",
"error",
")",
"{",
"blocksInCurrentRCI",
":=",
"rciBlocks",
"(",
"voteInfo",
")",
"\n",
"svis",
":=",
"int32",
"(",
"blocksInCurrentRCI",
"/",
"tracker",
".",
"params",
".",
"StakeVersionInterval",
")",
"\n",
"// blocksInCurrentSVI := int32(blocksInCurrentRCI % params.StakeVersionInterval)",
"if",
"blocksInCurrentRCI",
"%",
"tracker",
".",
"params",
".",
"StakeVersionInterval",
">",
"0",
"{",
"svis",
"++",
"\n",
"}",
"\n",
"si",
",",
"err",
":=",
"tracker",
".",
"node",
".",
"GetStakeVersionInfo",
"(",
"svis",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"si",
",",
"nil",
"\n",
"}"
] | // Get the info for the stake versions in the current rule change interval. | [
"Get",
"the",
"info",
"for",
"the",
"stake",
"versions",
"in",
"the",
"current",
"rule",
"change",
"interval",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L276-L288 | train |
decred/dcrdata | gov/agendas/tracker.go | cachedCounts | func (tracker *VoteTracker) cachedCounts(agendaID string) *voteCount {
tracker.mtx.RLock()
defer tracker.mtx.RUnlock()
return tracker.countCache[agendaID]
} | go | func (tracker *VoteTracker) cachedCounts(agendaID string) *voteCount {
tracker.mtx.RLock()
defer tracker.mtx.RUnlock()
return tracker.countCache[agendaID]
} | [
"func",
"(",
"tracker",
"*",
"VoteTracker",
")",
"cachedCounts",
"(",
"agendaID",
"string",
")",
"*",
"voteCount",
"{",
"tracker",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"tracker",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"tracker",
".",
"countCache",
"[",
"agendaID",
"]",
"\n",
"}"
] | // The cached voteCount for the given agenda, or nil if not found. | [
"The",
"cached",
"voteCount",
"for",
"the",
"given",
"agenda",
"or",
"nil",
"if",
"not",
"found",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L291-L295 | train |
decred/dcrdata | gov/agendas/tracker.go | cacheVoteCounts | func (tracker *VoteTracker) cacheVoteCounts(agendaID string, counts *voteCount) {
tracker.mtx.Lock()
defer tracker.mtx.Unlock()
tracker.countCache[agendaID] = counts
} | go | func (tracker *VoteTracker) cacheVoteCounts(agendaID string, counts *voteCount) {
tracker.mtx.Lock()
defer tracker.mtx.Unlock()
tracker.countCache[agendaID] = counts
} | [
"func",
"(",
"tracker",
"*",
"VoteTracker",
")",
"cacheVoteCounts",
"(",
"agendaID",
"string",
",",
"counts",
"*",
"voteCount",
")",
"{",
"tracker",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"tracker",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"tracker",
".",
"countCache",
"[",
"agendaID",
"]",
"=",
"counts",
"\n",
"}"
] | // Cache the voteCount for the given agenda. | [
"Cache",
"the",
"voteCount",
"for",
"the",
"given",
"agenda",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L298-L302 | train |
decred/dcrdata | gov/agendas/tracker.go | update | func (tracker *VoteTracker) update(voteInfo *dcrjson.GetVoteInfoResult, blocks []int32,
stakeInfo *dcrjson.GetStakeVersionInfoResult, stakeVersion uint32) {
// Check if voteCounts are needed
for idx := range voteInfo.Agendas {
agenda := &voteInfo.Agendas[idx]
if agenda.Status != statusDefined && agenda.Status != statusStarted {
// check the cache
counts := tracker.cachedCounts(agenda.ID)
if counts == nil {
counts = new(voteCount)
var err error
counts.yes, counts.abstain, counts.no, err = tracker.voteCounter(agenda.ID)
if err != nil {
log.Errorf("Error counting votes for %s: %v", agenda.ID, err)
continue
}
tracker.cacheVoteCounts(agenda.ID, counts)
}
for idx := range agenda.Choices {
choice := &agenda.Choices[idx]
if choice.ID == choiceYes {
choice.Count = counts.yes
} else if choice.ID == choiceNo {
choice.Count = counts.no
} else {
choice.Count = counts.abstain
}
}
}
}
tracker.mtx.Lock()
defer tracker.mtx.Unlock()
tracker.voteInfo = voteInfo
tracker.stakeInfo = stakeInfo
ringLen := int(tracker.params.BlockUpgradeNumToCheck)
for idx := range blocks {
tracker.ringIndex = (tracker.ringIndex + 1) % ringLen
tracker.blockRing[tracker.ringIndex] = blocks[idx]
}
tracker.blockVersion = tracker.blockRing[tracker.ringIndex]
tracker.stakeVersion = stakeVersion
tracker.ringHeight = voteInfo.CurrentHeight
tracker.summary = tracker.newVoteSummary()
} | go | func (tracker *VoteTracker) update(voteInfo *dcrjson.GetVoteInfoResult, blocks []int32,
stakeInfo *dcrjson.GetStakeVersionInfoResult, stakeVersion uint32) {
// Check if voteCounts are needed
for idx := range voteInfo.Agendas {
agenda := &voteInfo.Agendas[idx]
if agenda.Status != statusDefined && agenda.Status != statusStarted {
// check the cache
counts := tracker.cachedCounts(agenda.ID)
if counts == nil {
counts = new(voteCount)
var err error
counts.yes, counts.abstain, counts.no, err = tracker.voteCounter(agenda.ID)
if err != nil {
log.Errorf("Error counting votes for %s: %v", agenda.ID, err)
continue
}
tracker.cacheVoteCounts(agenda.ID, counts)
}
for idx := range agenda.Choices {
choice := &agenda.Choices[idx]
if choice.ID == choiceYes {
choice.Count = counts.yes
} else if choice.ID == choiceNo {
choice.Count = counts.no
} else {
choice.Count = counts.abstain
}
}
}
}
tracker.mtx.Lock()
defer tracker.mtx.Unlock()
tracker.voteInfo = voteInfo
tracker.stakeInfo = stakeInfo
ringLen := int(tracker.params.BlockUpgradeNumToCheck)
for idx := range blocks {
tracker.ringIndex = (tracker.ringIndex + 1) % ringLen
tracker.blockRing[tracker.ringIndex] = blocks[idx]
}
tracker.blockVersion = tracker.blockRing[tracker.ringIndex]
tracker.stakeVersion = stakeVersion
tracker.ringHeight = voteInfo.CurrentHeight
tracker.summary = tracker.newVoteSummary()
} | [
"func",
"(",
"tracker",
"*",
"VoteTracker",
")",
"update",
"(",
"voteInfo",
"*",
"dcrjson",
".",
"GetVoteInfoResult",
",",
"blocks",
"[",
"]",
"int32",
",",
"stakeInfo",
"*",
"dcrjson",
".",
"GetStakeVersionInfoResult",
",",
"stakeVersion",
"uint32",
")",
"{",
"// Check if voteCounts are needed",
"for",
"idx",
":=",
"range",
"voteInfo",
".",
"Agendas",
"{",
"agenda",
":=",
"&",
"voteInfo",
".",
"Agendas",
"[",
"idx",
"]",
"\n",
"if",
"agenda",
".",
"Status",
"!=",
"statusDefined",
"&&",
"agenda",
".",
"Status",
"!=",
"statusStarted",
"{",
"// check the cache",
"counts",
":=",
"tracker",
".",
"cachedCounts",
"(",
"agenda",
".",
"ID",
")",
"\n",
"if",
"counts",
"==",
"nil",
"{",
"counts",
"=",
"new",
"(",
"voteCount",
")",
"\n",
"var",
"err",
"error",
"\n",
"counts",
".",
"yes",
",",
"counts",
".",
"abstain",
",",
"counts",
".",
"no",
",",
"err",
"=",
"tracker",
".",
"voteCounter",
"(",
"agenda",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"agenda",
".",
"ID",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"tracker",
".",
"cacheVoteCounts",
"(",
"agenda",
".",
"ID",
",",
"counts",
")",
"\n",
"}",
"\n",
"for",
"idx",
":=",
"range",
"agenda",
".",
"Choices",
"{",
"choice",
":=",
"&",
"agenda",
".",
"Choices",
"[",
"idx",
"]",
"\n",
"if",
"choice",
".",
"ID",
"==",
"choiceYes",
"{",
"choice",
".",
"Count",
"=",
"counts",
".",
"yes",
"\n",
"}",
"else",
"if",
"choice",
".",
"ID",
"==",
"choiceNo",
"{",
"choice",
".",
"Count",
"=",
"counts",
".",
"no",
"\n",
"}",
"else",
"{",
"choice",
".",
"Count",
"=",
"counts",
".",
"abstain",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"tracker",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"tracker",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"tracker",
".",
"voteInfo",
"=",
"voteInfo",
"\n",
"tracker",
".",
"stakeInfo",
"=",
"stakeInfo",
"\n",
"ringLen",
":=",
"int",
"(",
"tracker",
".",
"params",
".",
"BlockUpgradeNumToCheck",
")",
"\n",
"for",
"idx",
":=",
"range",
"blocks",
"{",
"tracker",
".",
"ringIndex",
"=",
"(",
"tracker",
".",
"ringIndex",
"+",
"1",
")",
"%",
"ringLen",
"\n",
"tracker",
".",
"blockRing",
"[",
"tracker",
".",
"ringIndex",
"]",
"=",
"blocks",
"[",
"idx",
"]",
"\n",
"}",
"\n",
"tracker",
".",
"blockVersion",
"=",
"tracker",
".",
"blockRing",
"[",
"tracker",
".",
"ringIndex",
"]",
"\n",
"tracker",
".",
"stakeVersion",
"=",
"stakeVersion",
"\n",
"tracker",
".",
"ringHeight",
"=",
"voteInfo",
".",
"CurrentHeight",
"\n",
"tracker",
".",
"summary",
"=",
"tracker",
".",
"newVoteSummary",
"(",
")",
"\n",
"}"
] | // Once all resources have been retrieved from dcrd, update VoteTracker fields. | [
"Once",
"all",
"resources",
"have",
"been",
"retrieved",
"from",
"dcrd",
"update",
"VoteTracker",
"fields",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L305-L348 | train |
decred/dcrdata | gov/agendas/tracker.go | Summary | func (tracker *VoteTracker) Summary() *VoteSummary {
tracker.mtx.RLock()
defer tracker.mtx.RUnlock()
return tracker.summary
} | go | func (tracker *VoteTracker) Summary() *VoteSummary {
tracker.mtx.RLock()
defer tracker.mtx.RUnlock()
return tracker.summary
} | [
"func",
"(",
"tracker",
"*",
"VoteTracker",
")",
"Summary",
"(",
")",
"*",
"VoteSummary",
"{",
"tracker",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"tracker",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"tracker",
".",
"summary",
"\n",
"}"
] | // Summary is a getter for the cached VoteSummary. The summary returned will
// never be modified by VoteTracker, so can be used read-only by any number
// of threads. | [
"Summary",
"is",
"a",
"getter",
"for",
"the",
"cached",
"VoteSummary",
".",
"The",
"summary",
"returned",
"will",
"never",
"be",
"modified",
"by",
"VoteTracker",
"so",
"can",
"be",
"used",
"read",
"-",
"only",
"by",
"any",
"number",
"of",
"threads",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/gov/agendas/tracker.go#L469-L473 | train |
decred/dcrdata | dcrrates/rateserver/log.go | initializeLogging | func initializeLogging(logFile, logLevel string) {
log = backendLog.Logger("SRVR")
exchanges.UseLogger(xcLogger)
logDir, _ := filepath.Split(logFile)
err := os.MkdirAll(logDir, 0700)
if err != nil {
log.Errorf("failed to create log directory: %v", err)
os.Exit(1)
}
r, err := rotator.New(logFile, 10*1024, false, 3)
if err != nil {
log.Errorf("failed to create file rotator: %v\n", err)
os.Exit(1)
}
logRotator = r
if logLevel != "" {
level, ok := slog.LevelFromString(logLevel)
if ok {
log.SetLevel(level)
xcLogger.SetLevel(level)
} else {
log.Infof("Unable to assign logging level=%s. Falling back to level=info", logLevel)
}
}
} | go | func initializeLogging(logFile, logLevel string) {
log = backendLog.Logger("SRVR")
exchanges.UseLogger(xcLogger)
logDir, _ := filepath.Split(logFile)
err := os.MkdirAll(logDir, 0700)
if err != nil {
log.Errorf("failed to create log directory: %v", err)
os.Exit(1)
}
r, err := rotator.New(logFile, 10*1024, false, 3)
if err != nil {
log.Errorf("failed to create file rotator: %v\n", err)
os.Exit(1)
}
logRotator = r
if logLevel != "" {
level, ok := slog.LevelFromString(logLevel)
if ok {
log.SetLevel(level)
xcLogger.SetLevel(level)
} else {
log.Infof("Unable to assign logging level=%s. Falling back to level=info", logLevel)
}
}
} | [
"func",
"initializeLogging",
"(",
"logFile",
",",
"logLevel",
"string",
")",
"{",
"log",
"=",
"backendLog",
".",
"Logger",
"(",
"\"",
"\"",
")",
"\n",
"exchanges",
".",
"UseLogger",
"(",
"xcLogger",
")",
"\n",
"logDir",
",",
"_",
":=",
"filepath",
".",
"Split",
"(",
"logFile",
")",
"\n",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"logDir",
",",
"0700",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}",
"\n",
"r",
",",
"err",
":=",
"rotator",
".",
"New",
"(",
"logFile",
",",
"10",
"*",
"1024",
",",
"false",
",",
"3",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}",
"\n",
"logRotator",
"=",
"r",
"\n",
"if",
"logLevel",
"!=",
"\"",
"\"",
"{",
"level",
",",
"ok",
":=",
"slog",
".",
"LevelFromString",
"(",
"logLevel",
")",
"\n",
"if",
"ok",
"{",
"log",
".",
"SetLevel",
"(",
"level",
")",
"\n",
"xcLogger",
".",
"SetLevel",
"(",
"level",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"logLevel",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // initializeLogging initializes the logging rotater to write logs to logFile
// and create roll files in the same directory. It must be called before the
// package-global log rotater variables are used. | [
"initializeLogging",
"initializes",
"the",
"logging",
"rotater",
"to",
"write",
"logs",
"to",
"logFile",
"and",
"create",
"roll",
"files",
"in",
"the",
"same",
"directory",
".",
"It",
"must",
"be",
"called",
"before",
"the",
"package",
"-",
"global",
"log",
"rotater",
"variables",
"are",
"used",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/dcrrates/rateserver/log.go#L36-L60 | train |
decred/dcrdata | db/dcrpg/chainmonitor.go | NewChainMonitor | func (pgb *ChainDBRPC) NewChainMonitor(ctx context.Context, wg *sync.WaitGroup,
blockChan chan *chainhash.Hash, reorgChan chan *txhelpers.ReorgData) *ChainMonitor {
if pgb == nil {
return nil
}
return &ChainMonitor{
ctx: ctx,
db: pgb,
wg: wg,
blockChan: blockChan,
reorgChan: reorgChan,
ConnectingLock: make(chan struct{}, 1),
DoneConnecting: make(chan struct{}),
}
} | go | func (pgb *ChainDBRPC) NewChainMonitor(ctx context.Context, wg *sync.WaitGroup,
blockChan chan *chainhash.Hash, reorgChan chan *txhelpers.ReorgData) *ChainMonitor {
if pgb == nil {
return nil
}
return &ChainMonitor{
ctx: ctx,
db: pgb,
wg: wg,
blockChan: blockChan,
reorgChan: reorgChan,
ConnectingLock: make(chan struct{}, 1),
DoneConnecting: make(chan struct{}),
}
} | [
"func",
"(",
"pgb",
"*",
"ChainDBRPC",
")",
"NewChainMonitor",
"(",
"ctx",
"context",
".",
"Context",
",",
"wg",
"*",
"sync",
".",
"WaitGroup",
",",
"blockChan",
"chan",
"*",
"chainhash",
".",
"Hash",
",",
"reorgChan",
"chan",
"*",
"txhelpers",
".",
"ReorgData",
")",
"*",
"ChainMonitor",
"{",
"if",
"pgb",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"ChainMonitor",
"{",
"ctx",
":",
"ctx",
",",
"db",
":",
"pgb",
",",
"wg",
":",
"wg",
",",
"blockChan",
":",
"blockChan",
",",
"reorgChan",
":",
"reorgChan",
",",
"ConnectingLock",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
",",
"DoneConnecting",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"}"
] | // NewChainMonitor creates a new ChainMonitor. | [
"NewChainMonitor",
"creates",
"a",
"new",
"ChainMonitor",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/chainmonitor.go#L30-L44 | train |
decred/dcrdata | rpcutils/rpcclient.go | ConnectNodeRPC | func ConnectNodeRPC(host, user, pass, cert string, disableTLS, disableReconnect bool,
ntfnHandlers ...*rpcclient.NotificationHandlers) (*rpcclient.Client, semver.Semver, error) {
var dcrdCerts []byte
var err error
var nodeVer semver.Semver
if !disableTLS {
dcrdCerts, err = ioutil.ReadFile(cert)
if err != nil {
log.Errorf("Failed to read dcrd cert file at %s: %s\n",
cert, err.Error())
return nil, nodeVer, err
}
log.Debugf("Attempting to connect to dcrd RPC %s as user %s "+
"using certificate located in %s",
host, user, cert)
} else {
log.Debugf("Attempting to connect to dcrd RPC %s as user %s (no TLS)",
host, user)
}
connCfgDaemon := &rpcclient.ConnConfig{
Host: host,
Endpoint: "ws", // websocket
User: user,
Pass: pass,
Certificates: dcrdCerts,
DisableTLS: disableTLS,
DisableAutoReconnect: disableReconnect,
}
var ntfnHdlrs *rpcclient.NotificationHandlers
if len(ntfnHandlers) > 0 {
if len(ntfnHandlers) > 1 {
return nil, nodeVer, fmt.Errorf("invalid notification handler argument")
}
ntfnHdlrs = ntfnHandlers[0]
}
dcrdClient, err := rpcclient.New(connCfgDaemon, ntfnHdlrs)
if err != nil {
return nil, nodeVer, fmt.Errorf("Failed to start dcrd RPC client: %s", err.Error())
}
// Ensure the RPC server has a compatible API version.
ver, err := dcrdClient.Version()
if err != nil {
log.Error("Unable to get RPC version: ", err)
return nil, nodeVer, fmt.Errorf("unable to get node RPC version")
}
dcrdVer := ver["dcrdjsonrpcapi"]
nodeVer = semver.NewSemver(dcrdVer.Major, dcrdVer.Minor, dcrdVer.Patch)
// Check if the dcrd RPC API version is compatible with dcrdata.
isApiCompat := semver.AnyCompatible(compatibleChainServerAPIs, nodeVer)
if !isApiCompat {
return nil, nodeVer, fmt.Errorf("Node JSON-RPC server does not have "+
"a compatible API version. Advertises %v but requires one of: %v",
nodeVer, compatibleChainServerAPIs)
}
return dcrdClient, nodeVer, nil
} | go | func ConnectNodeRPC(host, user, pass, cert string, disableTLS, disableReconnect bool,
ntfnHandlers ...*rpcclient.NotificationHandlers) (*rpcclient.Client, semver.Semver, error) {
var dcrdCerts []byte
var err error
var nodeVer semver.Semver
if !disableTLS {
dcrdCerts, err = ioutil.ReadFile(cert)
if err != nil {
log.Errorf("Failed to read dcrd cert file at %s: %s\n",
cert, err.Error())
return nil, nodeVer, err
}
log.Debugf("Attempting to connect to dcrd RPC %s as user %s "+
"using certificate located in %s",
host, user, cert)
} else {
log.Debugf("Attempting to connect to dcrd RPC %s as user %s (no TLS)",
host, user)
}
connCfgDaemon := &rpcclient.ConnConfig{
Host: host,
Endpoint: "ws", // websocket
User: user,
Pass: pass,
Certificates: dcrdCerts,
DisableTLS: disableTLS,
DisableAutoReconnect: disableReconnect,
}
var ntfnHdlrs *rpcclient.NotificationHandlers
if len(ntfnHandlers) > 0 {
if len(ntfnHandlers) > 1 {
return nil, nodeVer, fmt.Errorf("invalid notification handler argument")
}
ntfnHdlrs = ntfnHandlers[0]
}
dcrdClient, err := rpcclient.New(connCfgDaemon, ntfnHdlrs)
if err != nil {
return nil, nodeVer, fmt.Errorf("Failed to start dcrd RPC client: %s", err.Error())
}
// Ensure the RPC server has a compatible API version.
ver, err := dcrdClient.Version()
if err != nil {
log.Error("Unable to get RPC version: ", err)
return nil, nodeVer, fmt.Errorf("unable to get node RPC version")
}
dcrdVer := ver["dcrdjsonrpcapi"]
nodeVer = semver.NewSemver(dcrdVer.Major, dcrdVer.Minor, dcrdVer.Patch)
// Check if the dcrd RPC API version is compatible with dcrdata.
isApiCompat := semver.AnyCompatible(compatibleChainServerAPIs, nodeVer)
if !isApiCompat {
return nil, nodeVer, fmt.Errorf("Node JSON-RPC server does not have "+
"a compatible API version. Advertises %v but requires one of: %v",
nodeVer, compatibleChainServerAPIs)
}
return dcrdClient, nodeVer, nil
} | [
"func",
"ConnectNodeRPC",
"(",
"host",
",",
"user",
",",
"pass",
",",
"cert",
"string",
",",
"disableTLS",
",",
"disableReconnect",
"bool",
",",
"ntfnHandlers",
"...",
"*",
"rpcclient",
".",
"NotificationHandlers",
")",
"(",
"*",
"rpcclient",
".",
"Client",
",",
"semver",
".",
"Semver",
",",
"error",
")",
"{",
"var",
"dcrdCerts",
"[",
"]",
"byte",
"\n",
"var",
"err",
"error",
"\n",
"var",
"nodeVer",
"semver",
".",
"Semver",
"\n",
"if",
"!",
"disableTLS",
"{",
"dcrdCerts",
",",
"err",
"=",
"ioutil",
".",
"ReadFile",
"(",
"cert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"cert",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"nodeVer",
",",
"err",
"\n",
"}",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"host",
",",
"user",
",",
"cert",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"host",
",",
"user",
")",
"\n",
"}",
"\n\n",
"connCfgDaemon",
":=",
"&",
"rpcclient",
".",
"ConnConfig",
"{",
"Host",
":",
"host",
",",
"Endpoint",
":",
"\"",
"\"",
",",
"// websocket",
"User",
":",
"user",
",",
"Pass",
":",
"pass",
",",
"Certificates",
":",
"dcrdCerts",
",",
"DisableTLS",
":",
"disableTLS",
",",
"DisableAutoReconnect",
":",
"disableReconnect",
",",
"}",
"\n\n",
"var",
"ntfnHdlrs",
"*",
"rpcclient",
".",
"NotificationHandlers",
"\n",
"if",
"len",
"(",
"ntfnHandlers",
")",
">",
"0",
"{",
"if",
"len",
"(",
"ntfnHandlers",
")",
">",
"1",
"{",
"return",
"nil",
",",
"nodeVer",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ntfnHdlrs",
"=",
"ntfnHandlers",
"[",
"0",
"]",
"\n",
"}",
"\n",
"dcrdClient",
",",
"err",
":=",
"rpcclient",
".",
"New",
"(",
"connCfgDaemon",
",",
"ntfnHdlrs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nodeVer",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"// Ensure the RPC server has a compatible API version.",
"ver",
",",
"err",
":=",
"dcrdClient",
".",
"Version",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Error",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"nodeVer",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"dcrdVer",
":=",
"ver",
"[",
"\"",
"\"",
"]",
"\n",
"nodeVer",
"=",
"semver",
".",
"NewSemver",
"(",
"dcrdVer",
".",
"Major",
",",
"dcrdVer",
".",
"Minor",
",",
"dcrdVer",
".",
"Patch",
")",
"\n\n",
"// Check if the dcrd RPC API version is compatible with dcrdata.",
"isApiCompat",
":=",
"semver",
".",
"AnyCompatible",
"(",
"compatibleChainServerAPIs",
",",
"nodeVer",
")",
"\n",
"if",
"!",
"isApiCompat",
"{",
"return",
"nil",
",",
"nodeVer",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"nodeVer",
",",
"compatibleChainServerAPIs",
")",
"\n",
"}",
"\n\n",
"return",
"dcrdClient",
",",
"nodeVer",
",",
"nil",
"\n",
"}"
] | // ConnectNodeRPC attempts to create a new websocket connection to a dcrd node,
// with the given credentials and optional notification handlers. | [
"ConnectNodeRPC",
"attempts",
"to",
"create",
"a",
"new",
"websocket",
"connection",
"to",
"a",
"dcrd",
"node",
"with",
"the",
"given",
"credentials",
"and",
"optional",
"notification",
"handlers",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L44-L105 | train |
decred/dcrdata | rpcutils/rpcclient.go | GetBlockByHash | func GetBlockByHash(blockhash *chainhash.Hash, client BlockFetcher) (*dcrutil.Block, error) {
msgBlock, err := client.GetBlock(blockhash)
if err != nil {
return nil, fmt.Errorf("GetBlock failed (%s): %v", blockhash, err)
}
block := dcrutil.NewBlock(msgBlock)
return block, nil
} | go | func GetBlockByHash(blockhash *chainhash.Hash, client BlockFetcher) (*dcrutil.Block, error) {
msgBlock, err := client.GetBlock(blockhash)
if err != nil {
return nil, fmt.Errorf("GetBlock failed (%s): %v", blockhash, err)
}
block := dcrutil.NewBlock(msgBlock)
return block, nil
} | [
"func",
"GetBlockByHash",
"(",
"blockhash",
"*",
"chainhash",
".",
"Hash",
",",
"client",
"BlockFetcher",
")",
"(",
"*",
"dcrutil",
".",
"Block",
",",
"error",
")",
"{",
"msgBlock",
",",
"err",
":=",
"client",
".",
"GetBlock",
"(",
"blockhash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"blockhash",
",",
"err",
")",
"\n",
"}",
"\n",
"block",
":=",
"dcrutil",
".",
"NewBlock",
"(",
"msgBlock",
")",
"\n\n",
"return",
"block",
",",
"nil",
"\n",
"}"
] | // GetBlockByHash gets the block with the given hash from a chain server. | [
"GetBlockByHash",
"gets",
"the",
"block",
"with",
"the",
"given",
"hash",
"from",
"a",
"chain",
"server",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L261-L269 | train |
decred/dcrdata | rpcutils/rpcclient.go | SideChains | func SideChains(client *rpcclient.Client) ([]dcrjson.GetChainTipsResult, error) {
tips, err := client.GetChainTips()
if err != nil {
return nil, err
}
return sideChainTips(tips), nil
} | go | func SideChains(client *rpcclient.Client) ([]dcrjson.GetChainTipsResult, error) {
tips, err := client.GetChainTips()
if err != nil {
return nil, err
}
return sideChainTips(tips), nil
} | [
"func",
"SideChains",
"(",
"client",
"*",
"rpcclient",
".",
"Client",
")",
"(",
"[",
"]",
"dcrjson",
".",
"GetChainTipsResult",
",",
"error",
")",
"{",
"tips",
",",
"err",
":=",
"client",
".",
"GetChainTips",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"sideChainTips",
"(",
"tips",
")",
",",
"nil",
"\n",
"}"
] | // SideChains gets a slice of known side chain tips. This corresponds to the
// results of the getchaintips node RPC where the block tip "status" is either
// "valid-headers" or "valid-fork". | [
"SideChains",
"gets",
"a",
"slice",
"of",
"known",
"side",
"chain",
"tips",
".",
"This",
"corresponds",
"to",
"the",
"results",
"of",
"the",
"getchaintips",
"node",
"RPC",
"where",
"the",
"block",
"tip",
"status",
"is",
"either",
"valid",
"-",
"headers",
"or",
"valid",
"-",
"fork",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L274-L281 | train |
decred/dcrdata | rpcutils/rpcclient.go | GetTransactionVerboseByID | func GetTransactionVerboseByID(client *rpcclient.Client, txhash *chainhash.Hash) (*dcrjson.TxRawResult, error) {
txraw, err := client.GetRawTransactionVerbose(txhash)
if err != nil {
log.Errorf("GetRawTransactionVerbose failed for: %v", txhash)
return nil, err
}
return txraw, nil
} | go | func GetTransactionVerboseByID(client *rpcclient.Client, txhash *chainhash.Hash) (*dcrjson.TxRawResult, error) {
txraw, err := client.GetRawTransactionVerbose(txhash)
if err != nil {
log.Errorf("GetRawTransactionVerbose failed for: %v", txhash)
return nil, err
}
return txraw, nil
} | [
"func",
"GetTransactionVerboseByID",
"(",
"client",
"*",
"rpcclient",
".",
"Client",
",",
"txhash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"dcrjson",
".",
"TxRawResult",
",",
"error",
")",
"{",
"txraw",
",",
"err",
":=",
"client",
".",
"GetRawTransactionVerbose",
"(",
"txhash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"txhash",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"txraw",
",",
"nil",
"\n",
"}"
] | // GetTransactionVerboseByID get a transaction by transaction id | [
"GetTransactionVerboseByID",
"get",
"a",
"transaction",
"by",
"transaction",
"id"
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L341-L348 | train |
decred/dcrdata | rpcutils/rpcclient.go | SearchRawTransaction | func SearchRawTransaction(client *rpcclient.Client, count int, address string) ([]*dcrjson.SearchRawTransactionsResult, error) {
addr, err := dcrutil.DecodeAddress(address)
if err != nil {
log.Infof("Invalid address %s: %v", address, err)
return nil, err
}
//change the 1000 000 number demo for now
txs, err := client.SearchRawTransactionsVerbose(addr, 0, count,
true, true, nil)
if err != nil {
log.Warnf("SearchRawTransaction failed for address %s: %v", addr, err)
}
return txs, nil
} | go | func SearchRawTransaction(client *rpcclient.Client, count int, address string) ([]*dcrjson.SearchRawTransactionsResult, error) {
addr, err := dcrutil.DecodeAddress(address)
if err != nil {
log.Infof("Invalid address %s: %v", address, err)
return nil, err
}
//change the 1000 000 number demo for now
txs, err := client.SearchRawTransactionsVerbose(addr, 0, count,
true, true, nil)
if err != nil {
log.Warnf("SearchRawTransaction failed for address %s: %v", addr, err)
}
return txs, nil
} | [
"func",
"SearchRawTransaction",
"(",
"client",
"*",
"rpcclient",
".",
"Client",
",",
"count",
"int",
",",
"address",
"string",
")",
"(",
"[",
"]",
"*",
"dcrjson",
".",
"SearchRawTransactionsResult",
",",
"error",
")",
"{",
"addr",
",",
"err",
":=",
"dcrutil",
".",
"DecodeAddress",
"(",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"address",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"//change the 1000 000 number demo for now",
"txs",
",",
"err",
":=",
"client",
".",
"SearchRawTransactionsVerbose",
"(",
"addr",
",",
"0",
",",
"count",
",",
"true",
",",
"true",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"addr",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"txs",
",",
"nil",
"\n",
"}"
] | // SearchRawTransaction fetch transactions the belong to an
// address | [
"SearchRawTransaction",
"fetch",
"transactions",
"the",
"belong",
"to",
"an",
"address"
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L352-L365 | train |
decred/dcrdata | rpcutils/rpcclient.go | CommonAncestor | func CommonAncestor(client BlockFetcher, hashA, hashB chainhash.Hash) (*chainhash.Hash, []chainhash.Hash, []chainhash.Hash, error) {
if client == nil {
return nil, nil, nil, errors.New("nil RPC client")
}
var length int
var chainA, chainB []chainhash.Hash
for {
if length >= maxAncestorChainLength {
return nil, nil, nil, ErrAncestorMaxChainLength
}
// Chain A
blockA, err := client.GetBlock(&hashA)
if err != nil {
return nil, nil, nil, fmt.Errorf("Failed to get block %v: %v", hashA, err)
}
heightA := blockA.Header.Height
// Chain B
blockB, err := client.GetBlock(&hashB)
if err != nil {
return nil, nil, nil, fmt.Errorf("Failed to get block %v: %v", hashB, err)
}
heightB := blockB.Header.Height
// Reach the same height on both chains before checking the loop
// termination condition. At least one previous block for each chain
// must be used, so that a chain tip block will not be considered a
// common ancestor and it will instead be added to a chain slice.
if heightA > heightB {
chainA = append([]chainhash.Hash{hashA}, chainA...)
length++
hashA = blockA.Header.PrevBlock
continue
}
if heightB > heightA {
chainB = append([]chainhash.Hash{hashB}, chainB...)
length++
hashB = blockB.Header.PrevBlock
continue
}
// Assert heightB == heightA
if heightB != heightA {
panic("you broke the code")
}
chainA = append([]chainhash.Hash{hashA}, chainA...)
chainB = append([]chainhash.Hash{hashB}, chainB...)
length++
// We are at genesis if the previous block is the zero hash.
if blockA.Header.PrevBlock == zeroHash {
return nil, chainA, chainB, ErrAncestorAtGenesis // no common ancestor, but the same block
}
hashA = blockA.Header.PrevBlock
hashB = blockB.Header.PrevBlock
// break here rather than for condition so inputs with equal hashes get
// handled properly (with ancestor as previous block and chains
// including the input blocks.)
if hashA == hashB {
break // hashA(==hashB) is the common ancestor.
}
}
// hashA == hashB
return &hashA, chainA, chainB, nil
} | go | func CommonAncestor(client BlockFetcher, hashA, hashB chainhash.Hash) (*chainhash.Hash, []chainhash.Hash, []chainhash.Hash, error) {
if client == nil {
return nil, nil, nil, errors.New("nil RPC client")
}
var length int
var chainA, chainB []chainhash.Hash
for {
if length >= maxAncestorChainLength {
return nil, nil, nil, ErrAncestorMaxChainLength
}
// Chain A
blockA, err := client.GetBlock(&hashA)
if err != nil {
return nil, nil, nil, fmt.Errorf("Failed to get block %v: %v", hashA, err)
}
heightA := blockA.Header.Height
// Chain B
blockB, err := client.GetBlock(&hashB)
if err != nil {
return nil, nil, nil, fmt.Errorf("Failed to get block %v: %v", hashB, err)
}
heightB := blockB.Header.Height
// Reach the same height on both chains before checking the loop
// termination condition. At least one previous block for each chain
// must be used, so that a chain tip block will not be considered a
// common ancestor and it will instead be added to a chain slice.
if heightA > heightB {
chainA = append([]chainhash.Hash{hashA}, chainA...)
length++
hashA = blockA.Header.PrevBlock
continue
}
if heightB > heightA {
chainB = append([]chainhash.Hash{hashB}, chainB...)
length++
hashB = blockB.Header.PrevBlock
continue
}
// Assert heightB == heightA
if heightB != heightA {
panic("you broke the code")
}
chainA = append([]chainhash.Hash{hashA}, chainA...)
chainB = append([]chainhash.Hash{hashB}, chainB...)
length++
// We are at genesis if the previous block is the zero hash.
if blockA.Header.PrevBlock == zeroHash {
return nil, chainA, chainB, ErrAncestorAtGenesis // no common ancestor, but the same block
}
hashA = blockA.Header.PrevBlock
hashB = blockB.Header.PrevBlock
// break here rather than for condition so inputs with equal hashes get
// handled properly (with ancestor as previous block and chains
// including the input blocks.)
if hashA == hashB {
break // hashA(==hashB) is the common ancestor.
}
}
// hashA == hashB
return &hashA, chainA, chainB, nil
} | [
"func",
"CommonAncestor",
"(",
"client",
"BlockFetcher",
",",
"hashA",
",",
"hashB",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"[",
"]",
"chainhash",
".",
"Hash",
",",
"[",
"]",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"if",
"client",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"length",
"int",
"\n",
"var",
"chainA",
",",
"chainB",
"[",
"]",
"chainhash",
".",
"Hash",
"\n",
"for",
"{",
"if",
"length",
">=",
"maxAncestorChainLength",
"{",
"return",
"nil",
",",
"nil",
",",
"nil",
",",
"ErrAncestorMaxChainLength",
"\n",
"}",
"\n\n",
"// Chain A",
"blockA",
",",
"err",
":=",
"client",
".",
"GetBlock",
"(",
"&",
"hashA",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hashA",
",",
"err",
")",
"\n",
"}",
"\n",
"heightA",
":=",
"blockA",
".",
"Header",
".",
"Height",
"\n\n",
"// Chain B",
"blockB",
",",
"err",
":=",
"client",
".",
"GetBlock",
"(",
"&",
"hashB",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hashB",
",",
"err",
")",
"\n",
"}",
"\n",
"heightB",
":=",
"blockB",
".",
"Header",
".",
"Height",
"\n\n",
"// Reach the same height on both chains before checking the loop",
"// termination condition. At least one previous block for each chain",
"// must be used, so that a chain tip block will not be considered a",
"// common ancestor and it will instead be added to a chain slice.",
"if",
"heightA",
">",
"heightB",
"{",
"chainA",
"=",
"append",
"(",
"[",
"]",
"chainhash",
".",
"Hash",
"{",
"hashA",
"}",
",",
"chainA",
"...",
")",
"\n",
"length",
"++",
"\n",
"hashA",
"=",
"blockA",
".",
"Header",
".",
"PrevBlock",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"heightB",
">",
"heightA",
"{",
"chainB",
"=",
"append",
"(",
"[",
"]",
"chainhash",
".",
"Hash",
"{",
"hashB",
"}",
",",
"chainB",
"...",
")",
"\n",
"length",
"++",
"\n",
"hashB",
"=",
"blockB",
".",
"Header",
".",
"PrevBlock",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// Assert heightB == heightA",
"if",
"heightB",
"!=",
"heightA",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"chainA",
"=",
"append",
"(",
"[",
"]",
"chainhash",
".",
"Hash",
"{",
"hashA",
"}",
",",
"chainA",
"...",
")",
"\n",
"chainB",
"=",
"append",
"(",
"[",
"]",
"chainhash",
".",
"Hash",
"{",
"hashB",
"}",
",",
"chainB",
"...",
")",
"\n",
"length",
"++",
"\n\n",
"// We are at genesis if the previous block is the zero hash.",
"if",
"blockA",
".",
"Header",
".",
"PrevBlock",
"==",
"zeroHash",
"{",
"return",
"nil",
",",
"chainA",
",",
"chainB",
",",
"ErrAncestorAtGenesis",
"// no common ancestor, but the same block",
"\n",
"}",
"\n\n",
"hashA",
"=",
"blockA",
".",
"Header",
".",
"PrevBlock",
"\n",
"hashB",
"=",
"blockB",
".",
"Header",
".",
"PrevBlock",
"\n\n",
"// break here rather than for condition so inputs with equal hashes get",
"// handled properly (with ancestor as previous block and chains",
"// including the input blocks.)",
"if",
"hashA",
"==",
"hashB",
"{",
"break",
"// hashA(==hashB) is the common ancestor.",
"\n",
"}",
"\n",
"}",
"\n\n",
"// hashA == hashB",
"return",
"&",
"hashA",
",",
"chainA",
",",
"chainB",
",",
"nil",
"\n",
"}"
] | // CommonAncestor attempts to determine the common ancestor block for two chains
// specified by the hash of the chain tip block. The full chains from the tips
// back to but not including the common ancestor are also returned. The first
// element in the chain slices is the lowest block following the common
// ancestor, while the last element is the chain tip. The common ancestor will
// never by one of the chain tips. Thus, if one of the chain tips is on the
// other chain, that block will be shared between the two chains, and the common
// ancestor will be the previous block. However, the intended use of this
// function is to find a common ancestor for two chains with no common blocks. | [
"CommonAncestor",
"attempts",
"to",
"determine",
"the",
"common",
"ancestor",
"block",
"for",
"two",
"chains",
"specified",
"by",
"the",
"hash",
"of",
"the",
"chain",
"tip",
"block",
".",
"The",
"full",
"chains",
"from",
"the",
"tips",
"back",
"to",
"but",
"not",
"including",
"the",
"common",
"ancestor",
"are",
"also",
"returned",
".",
"The",
"first",
"element",
"in",
"the",
"chain",
"slices",
"is",
"the",
"lowest",
"block",
"following",
"the",
"common",
"ancestor",
"while",
"the",
"last",
"element",
"is",
"the",
"chain",
"tip",
".",
"The",
"common",
"ancestor",
"will",
"never",
"by",
"one",
"of",
"the",
"chain",
"tips",
".",
"Thus",
"if",
"one",
"of",
"the",
"chain",
"tips",
"is",
"on",
"the",
"other",
"chain",
"that",
"block",
"will",
"be",
"shared",
"between",
"the",
"two",
"chains",
"and",
"the",
"common",
"ancestor",
"will",
"be",
"the",
"previous",
"block",
".",
"However",
"the",
"intended",
"use",
"of",
"this",
"function",
"is",
"to",
"find",
"a",
"common",
"ancestor",
"for",
"two",
"chains",
"with",
"no",
"common",
"blocks",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L376-L446 | train |
decred/dcrdata | rpcutils/rpcclient.go | OrphanedTipLength | func OrphanedTipLength(ctx context.Context, client BlockHashGetter,
tipHeight int64, hashFunc func(int64) (string, error)) (int64, error) {
commonHeight := tipHeight
var dbHash string
var err error
var dcrdHash *chainhash.Hash
for {
// Since there are no limits on the number of blocks scanned, allow
// cancellation for a clean exit.
select {
case <-ctx.Done():
return 0, nil
default:
}
dbHash, err = hashFunc(commonHeight)
if err != nil {
return -1, fmt.Errorf("Unable to retrieve block at height %d: %v", commonHeight, err)
}
dcrdHash, err = client.GetBlockHash(commonHeight)
if err != nil {
return -1, fmt.Errorf("Unable to retrive dcrd block at height %d: %v", commonHeight, err)
}
if dcrdHash.String() == dbHash {
break
}
commonHeight--
if commonHeight < 0 {
return -1, fmt.Errorf("Unable to find a common ancestor")
}
// Reorgs are soft-limited to depth 6 by dcrd. More than six blocks without
// a match probably indicates an issue.
if commonHeight-tipHeight == 7 {
log.Warnf("No common ancestor within 6 blocks. This is abnormal")
}
}
return tipHeight - commonHeight, nil
} | go | func OrphanedTipLength(ctx context.Context, client BlockHashGetter,
tipHeight int64, hashFunc func(int64) (string, error)) (int64, error) {
commonHeight := tipHeight
var dbHash string
var err error
var dcrdHash *chainhash.Hash
for {
// Since there are no limits on the number of blocks scanned, allow
// cancellation for a clean exit.
select {
case <-ctx.Done():
return 0, nil
default:
}
dbHash, err = hashFunc(commonHeight)
if err != nil {
return -1, fmt.Errorf("Unable to retrieve block at height %d: %v", commonHeight, err)
}
dcrdHash, err = client.GetBlockHash(commonHeight)
if err != nil {
return -1, fmt.Errorf("Unable to retrive dcrd block at height %d: %v", commonHeight, err)
}
if dcrdHash.String() == dbHash {
break
}
commonHeight--
if commonHeight < 0 {
return -1, fmt.Errorf("Unable to find a common ancestor")
}
// Reorgs are soft-limited to depth 6 by dcrd. More than six blocks without
// a match probably indicates an issue.
if commonHeight-tipHeight == 7 {
log.Warnf("No common ancestor within 6 blocks. This is abnormal")
}
}
return tipHeight - commonHeight, nil
} | [
"func",
"OrphanedTipLength",
"(",
"ctx",
"context",
".",
"Context",
",",
"client",
"BlockHashGetter",
",",
"tipHeight",
"int64",
",",
"hashFunc",
"func",
"(",
"int64",
")",
"(",
"string",
",",
"error",
")",
")",
"(",
"int64",
",",
"error",
")",
"{",
"commonHeight",
":=",
"tipHeight",
"\n",
"var",
"dbHash",
"string",
"\n",
"var",
"err",
"error",
"\n",
"var",
"dcrdHash",
"*",
"chainhash",
".",
"Hash",
"\n",
"for",
"{",
"// Since there are no limits on the number of blocks scanned, allow",
"// cancellation for a clean exit.",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"0",
",",
"nil",
"\n",
"default",
":",
"}",
"\n\n",
"dbHash",
",",
"err",
"=",
"hashFunc",
"(",
"commonHeight",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"commonHeight",
",",
"err",
")",
"\n",
"}",
"\n",
"dcrdHash",
",",
"err",
"=",
"client",
".",
"GetBlockHash",
"(",
"commonHeight",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"commonHeight",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"dcrdHash",
".",
"String",
"(",
")",
"==",
"dbHash",
"{",
"break",
"\n",
"}",
"\n\n",
"commonHeight",
"--",
"\n",
"if",
"commonHeight",
"<",
"0",
"{",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Reorgs are soft-limited to depth 6 by dcrd. More than six blocks without",
"// a match probably indicates an issue.",
"if",
"commonHeight",
"-",
"tipHeight",
"==",
"7",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"}",
"\n",
"return",
"tipHeight",
"-",
"commonHeight",
",",
"nil",
"\n",
"}"
] | // OrphanedTipLength finds a common ancestor by iterating block heights
// backwards until a common block hash is found. Unlike CommonAncestor, an
// orphaned DB tip whose corresponding block is not known to dcrd will not cause
// an error. The number of blocks that have been orphaned is returned.
// Realistically, this should rarely be anything but 0 or 1, but no limits are
// placed here on the number of blocks checked. | [
"OrphanedTipLength",
"finds",
"a",
"common",
"ancestor",
"by",
"iterating",
"block",
"heights",
"backwards",
"until",
"a",
"common",
"block",
"hash",
"is",
"found",
".",
"Unlike",
"CommonAncestor",
"an",
"orphaned",
"DB",
"tip",
"whose",
"corresponding",
"block",
"is",
"not",
"known",
"to",
"dcrd",
"will",
"not",
"cause",
"an",
"error",
".",
"The",
"number",
"of",
"blocks",
"that",
"have",
"been",
"orphaned",
"is",
"returned",
".",
"Realistically",
"this",
"should",
"rarely",
"be",
"anything",
"but",
"0",
"or",
"1",
"but",
"no",
"limits",
"are",
"placed",
"here",
"on",
"the",
"number",
"of",
"blocks",
"checked",
"."
] | 02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6 | https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/rpcutils/rpcclient.go#L458-L497 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.