// BlockIndexPathCtx returns a http.HandlerFunc that embeds the value at the url
// part {idx} into the request context.
356577
func BlockIndexPathCtx(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		pathIdxStr := chi.URLParam(r, "idx")
		idx, err := strconv.Atoi(pathIdxStr)
		if err != nil {
			apiLog.Infof("No/invalid idx value (int64): %v", err)
			http.Error(w, "Valid index not provided", http.StatusBadRequest)
			return
		}
		ctx := context.WithValue(r.Context(), ctxBlockIndex, idx)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
1330091
func (c *BitcoindClient) onRelevantTx(tx *wtxmgr.TxRecord,
	blockDetails *btcjson.BlockDetails) {

	block, err := parseBlock(blockDetails)
	if err != nil {
		log.Errorf("Unable to send onRelevantTx notification, failed "+
			"parse block: %v", err)
		return
	}

	select {
	case c.notificationQueue.ChanIn() <- RelevantTx{
		TxRecord: tx,
		Block:    block,
	}:
	case <-c.quit:
	}
}
1053872
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))
	})
}
756235
func TransactionIOIndexCtx(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		idxStr := chi.URLParam(r, "txinoutindex")
		idx, err := strconv.Atoi(idxStr)
		if err != nil {
			apiLog.Infof("No/invalid numeric value (%v): %v", idxStr, err)
			http.NotFound(w, r)
			return
		}
		ctx := context.WithValue(r.Context(), ctxTxInOutIndex, idx)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
25902
func newBlockIndex(db database.DB, chainParams *chaincfg.Params) *blockIndex {
	return &blockIndex{
		db:          db,
		chainParams: chainParams,
		index:       make(map[chainhash.Hash]*blockNode),
		dirty:       make(map[*blockNode]struct{}),
	}
}
813821
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)
}
696104
func (c handlerContext) childCtx(fi *fileInfo) *handlerContext {
	if c.currentPage == nil {
		panic("Need a Page to create a child context")
	}

	c.target = strings.TrimPrefix(fi.Path(), c.bundle.fi.Dir())
	c.source = fi

	c.doNotAddToSiteCollections = c.bundle != nil && c.bundle.tp != bundleBranch

	c.bundle = nil

	c.parentPage = c.currentPage
	c.currentPage = nil

	return &c
}
507077
func (h *guiHandler) serveIndex(w http.ResponseWriter, req *http.Request) {
	logger.Debugf("serving Juju GUI index")
	spriteFile := filepath.Join(h.rootDir, spritePath)
	spriteContent, err := ioutil.ReadFile(spriteFile)
	if err != nil {
		writeError(w, errors.Annotate(err, "cannot read sprite file"))
		return
	}
	tmpl := filepath.Join(h.rootDir, "templates", "index.html.go")
	if err := renderGUITemplate(w, tmpl, map[string]interface{}{
		// staticURL holds the root of the static hierarchy, hence why the
		// empty string is used here.
		"staticURL": h.hashedPath(""),
		"comboURL":  h.hashedPath("combo"),
		"configURL": h.hashedPath(getConfigPath(req.URL.Path, h.ctxt)),
		// TODO frankban: make it possible to enable debug.
		"debug":         false,
		"spriteContent": string(spriteContent),
	}); err != nil {
		writeError(w, err)
	}
}
770115
func (e *EvalDequeueResponse) GetWaitIndex() uint64 {
	// Prefer the wait index sent. This will be populated on all responses from
	// 0.7.0 and above
	if e.WaitIndex != 0 {
		return e.WaitIndex
	} else if e.Eval != nil {
		return e.Eval.ModifyIndex
	}

	// This should never happen
	return 1
}
733589
func (idx IndexTable) CommonPrefixSearchCallback(input string, callback func(id, l int)) {
	idx.Da.CommonPrefixSearchCallback(input, func(x, y int) {
		dup := idx.Dup[int32(x)]
		for i := x; i < x+int(dup)+1; i++ {
			callback(i, y)
		}
	})
	return
}
534190
func (f *FileStore) BlockCount(path string, idx int) int {
	f.mu.RLock()
	defer f.mu.RUnlock()

	if idx < 0 {
		return 0
	}

	for _, fd := range f.files {
		if fd.Path() == path {
			iter := fd.BlockIterator()
			for i := 0; i < idx; i++ {
				if !iter.Next() {
					return 0
				}
			}
			_, _, _, _, _, block, _ := iter.Read()
			return BlockCount(block)
		}
	}
	return 0
}
67534
func (rc *ResourceController) IndexHandler(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			switch x := r.(type) {
			case *search.Error:
				c.JSON(x.HTTPStatus, x.OperationOutcome)
				return
			default:
				outcome := models.NewOperationOutcome("fatal", "exception", "")
				c.JSON(http.StatusInternalServerError, outcome)
				return
			}
		}
	}()

	searchQuery := search.Query{Resource: rc.Name, Query: c.Request.URL.RawQuery}
	baseURL := responseURL(c.Request, rc.Name)
	bundle, err := rc.DAL.Search(*baseURL, searchQuery)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	c.Set("bundle", bundle)
	c.Set("Resource", rc.Name)
	c.Set("Action", "search")

	c.JSON(http.StatusOK, bundle)
}
718422
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))
	})
}
1125708
func TicketPoolCtx(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		tp := chi.URLParam(r, "tp")
		ctx := context.WithValue(r.Context(), ctxTp, tp)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
1099644
func (r *Router) pathAppendQueryFromCtx(path []byte, ctx *Context) []byte {
	queryBuf := ctx.URI().QueryString()
	if len(queryBuf) > zero {
		path = append(path, QuestionMark...)
		path = append(path, queryBuf...)
	}

	return path
}
772353
func GetLastConfigIndexFromBlockOrPanic(block *cb.Block) uint64 {
	index, err := GetLastConfigIndexFromBlock(block)
	if err != nil {
		panic(err)
	}
	return index
}
1365962
func (tx *Tx) Queryx(query string, args ...interface{}) (*Rows, error) {
	r, err := tx.Tx.Query(query, args...)
	if err != nil {
		return nil, err
	}
	return &Rows{Rows: r, unsafe: tx.unsafe, Mapper: tx.Mapper}, err
}