// AddressData returns comprehensive, paginated information for an address.
192128
func (pgb *ChainDBRPC) AddressData(address string, limitN, offsetAddrOuts int64,
	txnType dbtypes.AddrTxnViewType) (addrData *dbtypes.AddressInfo, err error) {
	merged, err := txnType.IsMerged()
	if err != nil {
		return nil, err
	}

	addrHist, balance, err := pgb.AddressHistory(address, limitN, offsetAddrOuts, txnType)
	if dbtypes.IsTimeoutErr(err) {
		return nil, err
	}

	populateTemplate := func() {
		addrData.Offset = offsetAddrOuts
		addrData.Limit = limitN
		addrData.TxnType = txnType.String()
		addrData.Address = address
	}

	if err == sql.ErrNoRows || (err == nil && len(addrHist) == 0) {
		// We do not have any confirmed transactions. Prep to display ONLY
		// unconfirmed transactions (or none at all).
		addrData = new(dbtypes.AddressInfo)
		populateTemplate()
		addrData.Balance = &dbtypes.AddressBalance{}
		log.Tracef("AddressHistory: No confirmed transactions for address %s.", address)
	} else if err != nil {
		// Unexpected error
		log.Errorf("AddressHistory: %v", err)
		return nil, fmt.Errorf("AddressHistory: %v", err)
	} else /*err == nil*/ {
		// Generate AddressInfo skeleton from the address table rows.
		addrData, _, _ = dbtypes.ReduceAddressHistory(addrHist)
		if addrData == nil {
			// Empty history is not expected for credit or all txnType with any
			// txns. i.e. Empty history is OK for debit views (merged or not).
			if (txnType != dbtypes.AddrTxnDebit && txnType != dbtypes.AddrMergedTxnDebit) &&
				(balance.NumSpent+balance.NumUnspent) > 0 {
				log.Debugf("empty address history (%s) for view %s: n=%d&start=%d",
					address, txnType.String(), limitN, offsetAddrOuts)
				return nil, fmt.Errorf("that address has no history")
			}
			addrData = new(dbtypes.AddressInfo)
		}

		// Balances and txn counts
		populateTemplate()
		addrData.Balance = balance
		addrData.KnownTransactions = (balance.NumSpent * 2) + balance.NumUnspent
		addrData.KnownFundingTxns = balance.NumSpent + balance.NumUnspent
		addrData.KnownSpendingTxns = balance.NumSpent

		// Obtain the TxnCount, which pertains to the number of table rows.
		addrData.IsMerged, err = txnType.IsMerged()
		if err != nil {
			return nil, err
		}
		if addrData.IsMerged {
			// For merged views, check the cache and fall back on a DB query.
			count, err := pgb.mergedTxnCount(address, txnType)
			if err != nil {
				return nil, err
			}
			addrData.TxnCount = int64(count)
		} else {
			// For non-merged views, use the balance data.
			switch txnType {
			case dbtypes.AddrTxnAll:
				addrData.TxnCount = addrData.KnownFundingTxns + addrData.KnownSpendingTxns
			case dbtypes.AddrTxnCredit:
				addrData.TxnCount = addrData.KnownFundingTxns
				addrData.Transactions = addrData.TxnsFunding
			case dbtypes.AddrTxnDebit:
				addrData.TxnCount = addrData.KnownSpendingTxns
				addrData.Transactions = addrData.TxnsSpending
			}
		}

		// Transactions on current page
		addrData.NumTransactions = int64(len(addrData.Transactions))
		if addrData.NumTransactions > limitN {
			addrData.NumTransactions = limitN
		}

		// Query database for transaction details.
		err = pgb.FillAddressTransactions(addrData)
		if dbtypes.IsTimeoutErr(err) {
			return nil, err
		}
		if err != nil {
			return nil, fmt.Errorf("Unable to fill address %s transactions: %v", address, err)
		}
	}

	// Check for unconfirmed transactions.
	addressUTXOs, numUnconfirmed, err := pgb.mp.UnconfirmedTxnsForAddress(address)
	if err != nil || addressUTXOs == nil {
		return nil, fmt.Errorf("UnconfirmedTxnsForAddress failed for address %s: %v", address, err)
	}
	addrData.NumUnconfirmed = numUnconfirmed
	addrData.NumTransactions += numUnconfirmed
	if addrData.UnconfirmedTxns == nil {
		addrData.UnconfirmedTxns = new(dbtypes.AddressTransactions)
	}

	// Funding transactions (unconfirmed)
	var received, sent, numReceived, numSent int64
FUNDING_TX_DUPLICATE_CHECK:
	for _, f := range addressUTXOs.Outpoints {
		// TODO: handle merged transactions
		if merged {
			break FUNDING_TX_DUPLICATE_CHECK
		}

		// Mempool transactions stick around for 2 blocks. The first block
		// incorporates the transaction and mines it. The second block
		// validates it by the stake. However, transactions move into our
		// database as soon as they are mined and thus we need to be careful
		// to not include those transactions in our list.
		for _, b := range addrData.Transactions {
			if f.Hash.String() == b.TxID && f.Index == b.InOutID {
				continue FUNDING_TX_DUPLICATE_CHECK
			}
		}
		fundingTx, ok := addressUTXOs.TxnsStore[f.Hash]
		if !ok {
			log.Errorf("An outpoint's transaction is not available in TxnStore.")
			continue
		}
		if fundingTx.Confirmed() {
			log.Errorf("An outpoint's transaction is unexpectedly confirmed.")
			continue
		}
		if txnType == dbtypes.AddrTxnAll || txnType == dbtypes.AddrTxnCredit {
			addrTx := &dbtypes.AddressTx{
				TxID:          fundingTx.Hash().String(),
				TxType:        txhelpers.DetermineTxTypeString(fundingTx.Tx),
				InOutID:       f.Index,
				Time:          dbtypes.NewTimeDefFromUNIX(fundingTx.MemPoolTime),
				FormattedSize: humanize.Bytes(uint64(fundingTx.Tx.SerializeSize())),
				Total:         txhelpers.TotalOutFromMsgTx(fundingTx.Tx).ToCoin(),
				ReceivedTotal: dcrutil.Amount(fundingTx.Tx.TxOut[f.Index].Value).ToCoin(),
			}
			addrData.Transactions = append(addrData.Transactions, addrTx)
		}
		received += fundingTx.Tx.TxOut[f.Index].Value
		numReceived++

	}

	// Spending transactions (unconfirmed)
SPENDING_TX_DUPLICATE_CHECK:
	for _, f := range addressUTXOs.PrevOuts {
		// TODO: handle merged transactions
		if merged {
			break SPENDING_TX_DUPLICATE_CHECK
		}

		// Mempool transactions stick around for 2 blocks. The first block
		// incorporates the transaction and mines it. The second block
		// validates it by the stake. However, transactions move into our
		// database as soon as they are mined and thus we need to be careful
		// to not include those transactions in our list.
		for _, b := range addrData.Transactions {
			if f.TxSpending.String() == b.TxID && f.InputIndex == int(b.InOutID) {
				continue SPENDING_TX_DUPLICATE_CHECK
			}
		}
		spendingTx, ok := addressUTXOs.TxnsStore[f.TxSpending]
		if !ok {
			log.Errorf("A previous outpoint's spending transaction is not available in TxnStore.")
			continue
		}
		if spendingTx.Confirmed() {
			log.Errorf("An outpoint's transaction is unexpectedly confirmed.")
			continue
		}

		// The total send amount must be looked up from the previous
		// outpoint because vin:i valuein is not reliable from dcrd.
		prevhash := spendingTx.Tx.TxIn[f.InputIndex].PreviousOutPoint.Hash
		strprevhash := prevhash.String()
		previndex := spendingTx.Tx.TxIn[f.InputIndex].PreviousOutPoint.Index
		valuein := addressUTXOs.TxnsStore[prevhash].Tx.TxOut[previndex].Value

		// Look through old transactions and set the spending transactions'
		// matching transaction fields.
		for _, dbTxn := range addrData.Transactions {
			if dbTxn.TxID == strprevhash && dbTxn.InOutID == previndex && dbTxn.IsFunding {
				dbTxn.MatchedTx = spendingTx.Hash().String()
				dbTxn.MatchedTxIndex = uint32(f.InputIndex)
			}
		}

		if txnType == dbtypes.AddrTxnAll || txnType == dbtypes.AddrTxnDebit {
			addrTx := &dbtypes.AddressTx{
				TxID:           spendingTx.Hash().String(),
				TxType:         txhelpers.DetermineTxTypeString(spendingTx.Tx),
				InOutID:        uint32(f.InputIndex),
				Time:           dbtypes.NewTimeDefFromUNIX(spendingTx.MemPoolTime),
				FormattedSize:  humanize.Bytes(uint64(spendingTx.Tx.SerializeSize())),
				Total:          txhelpers.TotalOutFromMsgTx(spendingTx.Tx).ToCoin(),
				SentTotal:      dcrutil.Amount(valuein).ToCoin(),
				MatchedTx:      strprevhash,
				MatchedTxIndex: previndex,
			}
			addrData.Transactions = append(addrData.Transactions, addrTx)
		}

		sent += valuein
		numSent++
	} // range addressUTXOs.PrevOuts

	// Totals from funding and spending transactions.
	addrData.Balance.NumSpent += numSent
	addrData.Balance.NumUnspent += (numReceived - numSent)
	addrData.Balance.TotalSpent += sent
	addrData.Balance.TotalUnspent += (received - sent)

	// Sort by date and calculate block height.
	addrData.PostProcess(uint32(pgb.Height()))

	return
}
550967
func (u *Unit) serviceAddress(scope string) (network.Address, error) {
	addresses, err := u.AllAddresses()
	if err != nil {
		return network.Address{}, errors.Trace(err)
	}
	if len(addresses) == 0 {
		return network.Address{}, network.NoAddressError(scope)
	}

	getStrictPublicAddr := func(addresses []network.Address) (network.Address, bool) {
		addr, ok := network.SelectPublicAddress(addresses)
		ok = ok && addr.Scope == network.ScopePublic
		return addr, ok
	}

	getInternalAddr := func(addresses []network.Address) (network.Address, bool) {
		return network.SelectInternalAddress(addresses, false)
	}

	var addrMatch func([]network.Address) (network.Address, bool)
	switch scope {
	case "public":
		addrMatch = getStrictPublicAddr
	case "private":
		addrMatch = getInternalAddr
	default:
		return network.Address{}, errors.NotValidf("address scope %q", scope)
	}

	addr, found := addrMatch(addresses)
	if !found {
		return network.Address{}, network.NoAddressError(scope)
	}
	return addr, nil
}
951889
func (c *Client) PrivateAddress(target string) (string, error) {
	var results params.PrivateAddressResults
	p := params.PrivateAddress{Target: target}
	err := c.facade.FacadeCall("PrivateAddress", p, &results)
	return results.PrivateAddress, err
}
739013
func (s *srv) Address() (string, error) {
	_, addrs, err := s.resolver.LookupSRV(context.Background(), "", "", s.service)
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("%s:%d", strings.TrimRight(addrs[0].Target, "."), addrs[0].Port), nil
}
455958
func (e Endpoints) PostAddress(ctx context.Context, profileID string, a Address) error {
	request := postAddressRequest{ProfileID: profileID, Address: a}
	response, err := e.PostAddressEndpoint(ctx, request)
	if err != nil {
		return err
	}
	resp := response.(postAddressResponse)
	return resp.Err
}
1043400
func (c *ServerConfig) Address() string {
	return fmt.Sprintf("%s:%d", c.Host, c.Port)
}
718698
func AllDebitAddressRows(rows []*dbtypes.AddressRow) []*dbtypes.AddressRow {
	_, numDebitRows := CountCreditDebitRows(rows)
	out := make([]*dbtypes.AddressRow, numDebitRows)
	if numDebitRows == 0 {
		return out
	}
	for _, r := range rows {
		if !r.IsFunding {
			out = append(out, r)
		}
	}
	return out
}
725461
func Address(network, host string) string {
	u := url.URL{
		Scheme: network,
		Host:   host,
	}
	return u.String()
}
242590
func (d *domainClient) RequestData(ctx context.Context, args *RequestDataArgs) (reply *RequestDataReply, err error) {
	reply = new(RequestDataReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "IndexedDB.requestData", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "IndexedDB.requestData", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "IndexedDB", Op: "RequestData", Err: err}
	}
	return
}
356177
func AllCreditAddressRows(rows []*dbtypes.AddressRow) []*dbtypes.AddressRow {
	numCreditRows, _ := CountCreditDebitRows(rows)
	out := make([]*dbtypes.AddressRow, 0, numCreditRows)
	if numCreditRows == 0 {
		return out
	}
	for _, r := range rows {
		if r.IsFunding {
			out = append(out, r)
		}
	}
	return out
}
11074
func (t *TM1638Driver) sendData(address byte, data byte) {
	t.sendCommand(TM1638DataCmd | TM1638FixedAddr)
	t.pinStrobe.Off()
	t.send(TM1638AddrCmd | address)
	t.send(data)
	t.pinStrobe.On()
}
340851
func (inst *environInstance) Addresses(ctx context.ProviderCallContext) ([]network.Address, error) {
	if inst.base.Guest == nil {
		return nil, nil
	}
	res := make([]network.Address, 0, len(inst.base.Guest.Net))
	for _, net := range inst.base.Guest.Net {
		for _, ip := range net.IpAddress {
			res = append(res, network.NewAddress(ip))
		}
	}
	return res, nil
}
1250483
func (stor *maas1Storage) addressFileObject(name string) gomaasapi.MAASObject {
	return stor.maasClient.GetSubObject(name)
}
1145468
func (facade *Facade) PublicAddress(target string) (string, error) {
	addr, err := facade.addressCall("PublicAddress", target)
	return addr, errors.Trace(err)
}
71216
func (e Endpoints) DeleteAddress(ctx context.Context, profileID string, addressID string) error {
	request := deleteAddressRequest{ProfileID: profileID, AddressID: addressID}
	response, err := e.DeleteAddressEndpoint(ctx, request)
	if err != nil {
		return err
	}
	resp := response.(deleteAddressResponse)
	return resp.Err
}
1224631
func (pubKey PubKeyEd25519) Address() crypto.Address {
	return crypto.Address(tmhash.SumTruncated(pubKey[:]))
}
500540
func (exp *explorerUI) AddressPage(w http.ResponseWriter, r *http.Request) {
	// AddressPageData is the data structure passed to the HTML template

	type AddressPageData struct {
		*CommonPageData
		Data         *dbtypes.AddressInfo
		CRLFDownload bool
		FiatBalance  *exchanges.Conversion
	}

	// Grab the URL query parameters
	address, txnType, limitN, offsetAddrOuts, err := parseAddressParams(r)
	if err != nil {
		exp.StatusPage(w, defaultErrorCode, err.Error(), address, ExpStatusError)
		return
	}

	// Validate the address.
	addr, addrType, addrErr := txhelpers.AddressValidation(address, exp.ChainParams)
	isZeroAddress := addrErr == txhelpers.AddressErrorZeroAddress
	if addrErr != nil && !isZeroAddress {
		var status expStatus
		var message string
		code := defaultErrorCode
		switch addrErr {
		case txhelpers.AddressErrorDecodeFailed, txhelpers.AddressErrorUnknown:
			status = ExpStatusError
			message = "Unexpected issue validating this address."
		case txhelpers.AddressErrorWrongNet:
			status = ExpStatusWrongNetwork
			message = fmt.Sprintf("The address %v is valid on %s, not %s.",
				addr, addr.Net().Name, exp.NetName)
			code = wrongNetwork
		default:
			status = ExpStatusError
			message = "Unknown error."
		}

		exp.StatusPage(w, code, message, address, status)
		return
	}

	// Handle valid but unsupported address types.
	switch addrType {
	case txhelpers.AddressTypeP2PKH, txhelpers.AddressTypeP2SH:
		// All good.
	case txhelpers.AddressTypeP2PK:
		message := "Looks like you are searching for an address of type P2PK."
		exp.StatusPage(w, defaultErrorCode, message, address, ExpStatusP2PKAddress)
		return
	default:
		message := "Unsupported address type."
		exp.StatusPage(w, defaultErrorCode, message, address, ExpStatusNotSupported)
		return
	}

	// Retrieve address information from the DB and/or RPC.
	var addrData *dbtypes.AddressInfo
	if isZeroAddress {
		// For the zero address (e.g. DsQxuVRvS4eaJ42dhQEsCXauMWjvopWgrVg),
		// short-circuit any queries.
		addrData = &dbtypes.AddressInfo{
			Address:         address,
			Net:             addr.Net().Name,
			IsDummyAddress:  true,
			Balance:         new(dbtypes.AddressBalance),
			UnconfirmedTxns: new(dbtypes.AddressTransactions),
		}
	} else {
		addrData, err = exp.AddressListData(address, txnType, limitN, offsetAddrOuts)
		if exp.timeoutErrorPage(w, err, "TicketsPriceByHeight") {
			return
		} else if err != nil {
			exp.StatusPage(w, defaultErrorCode, err.Error(), address, ExpStatusError)
			return
		}
	}

	// Set page parameters.
	addrData.IsDummyAddress = isZeroAddress // may be redundant
	addrData.Path = r.URL.Path

	// If exchange monitoring is active, prepare a fiat balance conversion
	conversion := exp.xcBot.Conversion(dcrutil.Amount(addrData.Balance.TotalUnspent).ToCoin())

	// For Windows clients only, link to downloads with CRLF (\r\n) line
	// endings.
	UseCRLF := strings.Contains(r.UserAgent(), "Windows")

	// Execute the HTML template.
	pageData := AddressPageData{
		CommonPageData: exp.commonData(r),
		Data:           addrData,
		CRLFDownload:   UseCRLF,
		FiatBalance:    conversion,
	}
	str, err := exp.templates.execTemplateToString("address", pageData)
	if err != nil {
		log.Errorf("Template execute failure: %v", err)
		exp.StatusPage(w, defaultErrorCode, defaultErrorMessage, "", ExpStatusError)
		return
	}

	w.Header().Set("Content-Type", "text/html")
	w.Header().Set("Turbolinks-Location", r.URL.RequestURI())
	w.WriteHeader(http.StatusOK)
	io.WriteString(w, str)
}