// AddressPostCtx returns a http.HandlerFunc that embeds the {addrs} value in
// the post request into the request context.
186191
func AddressPostCtx(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		address := r.PostFormValue("addrs")
		ctx := context.WithValue(r.Context(), CtxAddress, address)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
339396
func (a *Allocator) RequestAddress(poolID string, prefAddress net.IP, opts map[string]string) (*net.IPNet, map[string]string, error) {
	logrus.Debugf("RequestAddress(%s, %v, %v)", poolID, prefAddress, opts)
	k := SubnetKey{}
	if err := k.FromString(poolID); err != nil {
		return nil, nil, types.BadRequestErrorf("invalid pool id: %s", poolID)
	}

	if err := a.refresh(k.AddressSpace); err != nil {
		return nil, nil, err
	}

	aSpace, err := a.getAddrSpace(k.AddressSpace)
	if err != nil {
		return nil, nil, err
	}

	aSpace.Lock()
	p, ok := aSpace.subnets[k]
	if !ok {
		aSpace.Unlock()
		return nil, nil, types.NotFoundErrorf("cannot find address pool for poolID:%s", poolID)
	}

	if prefAddress != nil && !p.Pool.Contains(prefAddress) {
		aSpace.Unlock()
		return nil, nil, ipamapi.ErrIPOutOfRange
	}

	c := p
	for c.Range != nil {
		k = c.ParentKey
		c = aSpace.subnets[k]
	}
	aSpace.Unlock()

	bm, err := a.retrieveBitmask(k, c.Pool)
	if err != nil {
		return nil, nil, types.InternalErrorf("could not find bitmask in datastore for %s on address %v request from pool %s: %v",
			k.String(), prefAddress, poolID, err)
	}
	// In order to request for a serial ip address allocation, callers can pass in the option to request
	// IP allocation serially or first available IP in the subnet
	var serial bool
	if opts != nil {
		if val, ok := opts[ipamapi.AllocSerialPrefix]; ok {
			serial = (val == "true")
		}
	}
	ip, err := a.getAddress(p.Pool, bm, prefAddress, p.Range, serial)
	if err != nil {
		return nil, nil, err
	}

	return &net.IPNet{IP: ip, Mask: p.Pool.Mask}, nil, nil
}
205553
func bestAddressIndex(numAddr int, getAddrFunc addressByIndexFunc, matchFunc scopeMatchFunc) int {
	indexes := bestAddressIndexes(numAddr, getAddrFunc, matchFunc)
	if len(indexes) > 0 {
		return indexes[0]
	}
	return -1
}
1220750
func (h *Handler) handlePostField(w http.ResponseWriter, r *http.Request) {
	if !validHeaderAcceptJSON(r.Header) {
		http.Error(w, "JSON only acceptable response", http.StatusNotAcceptable)
		return
	}
	indexName := mux.Vars(r)["index"]
	fieldName := mux.Vars(r)["field"]

	resp := successResponse{h: h}

	// Decode request.
	var req postFieldRequest
	dec := json.NewDecoder(r.Body)
	dec.DisallowUnknownFields()
	err := dec.Decode(&req)
	if err != nil && err != io.EOF {
		resp.write(w, err)
		return
	}

	// Validate field options.
	if err := req.Options.validate(); err != nil {
		resp.write(w, err)
		return
	}

	// Convert json options into functional options.
	var fos []pilosa.FieldOption
	switch req.Options.Type {
	case pilosa.FieldTypeSet:
		fos = append(fos, pilosa.OptFieldTypeSet(*req.Options.CacheType, *req.Options.CacheSize))
	case pilosa.FieldTypeInt:
		fos = append(fos, pilosa.OptFieldTypeInt(*req.Options.Min, *req.Options.Max))
	case pilosa.FieldTypeTime:
		fos = append(fos, pilosa.OptFieldTypeTime(*req.Options.TimeQuantum, req.Options.NoStandardView))
	case pilosa.FieldTypeMutex:
		fos = append(fos, pilosa.OptFieldTypeMutex(*req.Options.CacheType, *req.Options.CacheSize))
	case pilosa.FieldTypeBool:
		fos = append(fos, pilosa.OptFieldTypeBool())
	}
	if req.Options.Keys != nil {
		if *req.Options.Keys {
			fos = append(fos, pilosa.OptFieldKeys())
		}
	}

	_, err = h.api.CreateField(r.Context(), indexName, fieldName, fos...)
	resp.write(w, err)
}
900457
func RetrieveAddressUTXOs(ctx context.Context, db *sql.DB, address string, currentBlockHeight int64) ([]apitypes.AddressTxnOutput, error) {
	stmt, err := db.Prepare(internal.SelectAddressUnspentWithTxn)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	rows, err := stmt.QueryContext(ctx, address)
	_ = stmt.Close()
	if err != nil {
		log.Error(err)
		return nil, err
	}
	defer closeRows(rows)

	var outputs []apitypes.AddressTxnOutput
	for rows.Next() {
		pkScript := []byte{}
		var blockHeight, atoms int64
		var blockTime dbtypes.TimeDef
		txnOutput := apitypes.AddressTxnOutput{}
		if err = rows.Scan(&txnOutput.Address, &txnOutput.TxnID,
			&atoms, &blockHeight, &blockTime, &txnOutput.Vout, &pkScript); err != nil {
			log.Error(err)
		}
		txnOutput.BlockTime = blockTime.UNIX()
		txnOutput.ScriptPubKey = hex.EncodeToString(pkScript)
		txnOutput.Amount = dcrutil.Amount(atoms).ToCoin()
		txnOutput.Satoshis = atoms
		txnOutput.Height = blockHeight
		txnOutput.Confirmations = currentBlockHeight - blockHeight + 1
		outputs = append(outputs, txnOutput)
	}

	return outputs, nil
}
1179657
func (ac *AddressCache) UTXOs(addr string) ([]apitypes.AddressTxnOutput, *BlockID) {
	aci := ac.addressCacheItem(addr)
	if aci == nil {
		ac.cacheMetrics.UtxoMiss()
		return nil, nil
	}
	ac.cacheMetrics.UtxoHit()
	return aci.UTXOs()
}
1305598
func (r *PEXReactor) RequestAddrs(p Peer) {
	r.Logger.Debug("Request addrs", "from", p)
	id := string(p.ID())
	if r.requestsSent.Has(id) {
		return
	}
	r.requestsSent.Set(id, struct{}{})
	p.Send(PexChannel, cdc.MustMarshalBinaryBare(&pexRequestMessage{}))
}
832529
func (r *Router) PostFunc(pattern string, fn http.HandlerFunc) Route {
	return r.Post(pattern, http.HandlerFunc(fn))
}
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
}
620519
func TransactionsCtx(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		address := r.FormValue("address")
		if address != "" {
			ctx := context.WithValue(r.Context(), CtxAddress, address)
			next.ServeHTTP(w, r.WithContext(ctx))
		}

		hash := r.FormValue("block")
		if hash != "" {
			ctx := context.WithValue(r.Context(), ctxBlockHash, hash)
			next.ServeHTTP(w, r.WithContext(ctx))
		}
	})
}
507067
func CtxDomain(r *http.Request) string {
	val := r.Context().Value(domainCtx)
	if val == nil {
		return ""
	}
	return val.(string)
}
211022
func parseAddressParams(r *http.Request) (address string, txnType dbtypes.AddrTxnViewType, limitN, offsetAddrOuts int64, err error) {
	// Get the address URL parameter, which should be set in the request context
	// by the addressPathCtx middleware.
	var parseErr error

	address, ok := r.Context().Value(ctxAddress).(string)
	if !ok {
		log.Trace("address not set")
		err = fmt.Errorf("there seems to not be an address in this request")
		return
	}

	// Number of outputs for the address to query the database for. The URL
	// query parameter "n" is used to specify the limit (e.g. "?n=20").
	limitN, parseErr = strconv.ParseInt(r.URL.Query().Get("n"), 10, 64)
	if parseErr != nil || limitN < 0 {
		limitN = defaultAddressRows
	} else if limitN > MaxAddressRows {
		log.Warnf("addressPage: requested up to %d address rows, "+
			"limiting to %d", limitN, MaxAddressRows)
		limitN = MaxAddressRows
	}

	// Number of outputs to skip (OFFSET in database query). For UX reasons, the
	// "start" URL query parameter is used.
	offsetAddrOuts, parseErr = strconv.ParseInt(r.URL.Query().Get("start"), 10, 64)
	if parseErr != nil || offsetAddrOuts < 0 {
		offsetAddrOuts = 0
	}

	// Transaction types to show.
	txntype := r.URL.Query().Get("txntype")
	if txntype == "" {
		txntype = "all"
	}
	txnType = dbtypes.AddrTxnViewTypeFromStr(txntype)
	if txnType == dbtypes.AddrTxnUnknown {
		err = fmt.Errorf("unknown txntype query value")
	}

	// log.Debugf("Showing transaction types: %s (%d)", txntype, txnType)

	return
}
428193
func (m *Mux) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	if m.root {
		ctx = context.WithValue(ctx, internal.Path, r.URL.EscapedPath())
	}
	ctx = m.router.route(ctx, r)
	m.handler.ServeHTTPC(ctx, w, r)
}
831306
func (v *evalVisitor) pushCtx(ctx reflect.Value) {
	v.ctx = append(v.ctx, ctx)
}
880153
func (pgb *ChainDB) AddressTxIoCsv(address string) ([][]string, error) {
	rows, err := pgb.AddressRowsCompact(address)
	if err != nil {
		return nil, err
	}

	return MakeCsvAddressRowsCompact(rows), nil

	// ALT implementation, without cache update:

	// Try the address rows cache.
	// hash := pgb.BestBlockHash()
	// rows, validBlock := pgb.AddressCache.Rows(address)
	// cacheCurrent := validBlock != nil && validBlock.Hash == *hash
	// if cacheCurrent && rows != nil {
	// 	log.Debugf("AddressTxIoCsv: Merged address rows cache HIT for %s.", address)

	// 	csvRows := make([][]string, 0, len(rows)+1)
	// 	csvRows = append(csvRows, []string{"tx_hash", "direction", "io_index",
	// 		"valid_mainchain", "value", "time_stamp", "tx_type", "matching_tx_hash"})

	// 	for _, r := range rows {
	// 		var strValidMainchain string
	// 		if r.ValidMainChain {
	// 			strValidMainchain = "1"
	// 		} else {
	// 			strValidMainchain = "0"
	// 		}

	// 		var strDirection string
	// 		if r.IsFunding {
	// 			strDirection = "1"
	// 		} else {
	// 			strDirection = "-1"
	// 		}

	// 		csvRows = append(csvRows, []string{
	// 			r.TxHash,
	// 			strDirection,
	// 			strconv.Itoa(int(r.TxVinVoutIndex)),
	// 			strValidMainchain,
	// 			strconv.FormatFloat(dcrutil.Amount(r.Value).ToCoin(), 'f', -1, 64),
	// 			strconv.FormatInt(r.TxBlockTime.UNIX(), 10),
	// 			txhelpers.TxTypeToString(int(r.TxType)),
	// 			r.MatchingTxHash,
	// 		})
	// 	}

	// 	return csvRows, nil
	// }

	// log.Debugf("AddressTxIoCsv: Merged address rows cache MISS for %s.", address)

	// ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
	// defer cancel()

	// csvRows, err := retrieveAddressIoCsv(ctx, pgb.db, address)
	// if err != nil {
	// 	return nil, fmt.Errorf("retrieveAddressIoCsv: %v", err)
	// }
	// return csvRows, nil
}
708037
func TxConsumesOutpointWithAddress(msgTx *wire.MsgTx, addr string,
	c VerboseTransactionGetter, params *chaincfg.Params) (prevOuts []PrevOut, prevTxs []*TxWithBlockData) {
	// Send all the raw transaction requests
	type promiseGetRawTransaction struct {
		result rpcclient.FutureGetRawTransactionVerboseResult
		inIdx  int
	}
	numPrevOut := len(msgTx.TxIn)
	promisesGetRawTransaction := make([]promiseGetRawTransaction, 0, numPrevOut)

	for inIdx, txIn := range msgTx.TxIn {
		hash := &txIn.PreviousOutPoint.Hash
		if zeroHash.IsEqual(hash) {
			continue // coinbase or stakebase
		}
		promisesGetRawTransaction = append(promisesGetRawTransaction, promiseGetRawTransaction{
			result: c.GetRawTransactionVerboseAsync(hash),
			inIdx:  inIdx,
		})
	}

	// For each TxIn of this transaction, inspect the previous outpoint.
	for i := range promisesGetRawTransaction {
		// Previous outpoint for this TxIn
		inIdx := promisesGetRawTransaction[i].inIdx
		prevOut := &msgTx.TxIn[inIdx].PreviousOutPoint
		hash := prevOut.Hash

		prevTxRaw, err := promisesGetRawTransaction[i].result.Receive()
		if err != nil {
			fmt.Printf("Unable to get raw transaction for %v: %v\n", hash, err)
			return nil, nil
		}

		if prevTxRaw.Txid != hash.String() {
			fmt.Printf("%v != %v", prevTxRaw.Txid, hash.String())
			return nil, nil
		}

		prevTx, err := MsgTxFromHex(prevTxRaw.Hex)
		if err != nil {
			fmt.Printf("MsgTxFromHex failed: %s\n", err)
			continue
		}

		// prevOut.Index indicates which output.
		txOut := prevTx.TxOut[prevOut.Index]
		// Extract the addresses from this output's PkScript.
		_, txAddrs, _, err := txscript.ExtractPkScriptAddrs(
			txOut.Version, txOut.PkScript, params)
		if err != nil {
			fmt.Printf("ExtractPkScriptAddrs: %v\n", err.Error())
			continue
		}

		// For each address that matches the address of interest, record this
		// previous outpoint and the containing transactions.
		for _, txAddr := range txAddrs {
			addrstr := txAddr.EncodeAddress()
			if addr == addrstr {
				outpoint := wire.NewOutPoint(&hash,
					prevOut.Index, TxTree(prevTx))
				prevOuts = append(prevOuts, PrevOut{
					TxSpending:       msgTx.TxHash(),
					InputIndex:       inIdx,
					PreviousOutpoint: outpoint,
				})
				prevTxs = append(prevTxs, &TxWithBlockData{
					Tx:          prevTx,
					BlockHeight: prevTxRaw.BlockHeight,
					BlockHash:   prevTxRaw.BlockHash,
				})
			}
		}

	}
	return
}
689647
func NewAddressOutpoints(address string) *AddressOutpoints {
	return &AddressOutpoints{
		Address:   address,
		TxnsStore: make(map[chainhash.Hash]*TxWithBlockData),
	}
}