// LastChainedAddress returns the most recently requested chained
// address from calling NextChainedAddress, or the root address if
// no chained addresses have been requested.
965446
func (s *Store) LastChainedAddress() btcutil.Address {
	s.mtx.RLock()
	defer s.mtx.RUnlock()

	return s.chainIdxMap[s.highestUsed]
}
1164298
func (pgb *ChainDB) AddressUTXO(address string) ([]apitypes.AddressTxnOutput, bool, error) {
	// Check the cache first.
	bestHash, height := pgb.BestBlock()
	utxos, validHeight := pgb.AddressCache.UTXOs(address)
	if utxos != nil && *bestHash == validHeight.Hash {
		return utxos, false, nil
	}

	busy, wait, done := pgb.CacheLocks.utxo.TryLock(address)
	if busy {
		// Let others get the wait channel while we wait.
		// To return stale cache data if it is available:
		// utxos, _ := pgb.AddressCache.UTXOs(address)
		// if utxos != nil {
		// 	return utxos, nil
		// }
		<-wait

		// Try again, starting with the cache.
		return pgb.AddressUTXO(address)
	}

	// We will run the DB query, so block others from doing the same. When query
	// and/or cache update is completed, broadcast to any waiters that the coast
	// is clear.
	defer done()

	// Cache is empty or stale, so query the DB.
	ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
	defer cancel()
	blockHeight := pgb.Height()
	txnOutput, err := RetrieveAddressUTXOs(ctx, pgb.db, address, blockHeight)
	if err != nil {
		return nil, false, pgb.replaceCancelError(err)
	}

	// Update the address cache.
	cacheUpdated := pgb.AddressCache.StoreUTXOs(address, txnOutput, cache.NewBlockID(bestHash, height))
	return txnOutput, cacheUpdated, 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
}
572648
func GetPreferredNodeAddress(node *v1.Node, preferredAddressTypes []v1.NodeAddressType) (string, error) {
	for _, addressType := range preferredAddressTypes {
		for _, address := range node.Status.Addresses {
			if address.Type == addressType {
				return address.Address, nil
			}
		}
	}
	return "", &NoMatchError{addresses: node.Status.Addresses}
}
993238
func (sc *SigChain) GetCurrentSubchain(m MetaContext, eldest keybase1.KID) (ChainLinks, error) {
	return cropToRightmostSubchain(m, sc.chainLinks, eldest, sc.uid)
}
293745
func (w *Wallet) HaveAddress(a btcutil.Address) (bool, error) {
	err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
		addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
		_, err := w.Manager.Address(addrmgrNs, a)
		return err
	})
	if err == nil {
		return true, nil
	}
	if waddrmgr.IsError(err, waddrmgr.ErrAddressNotFound) {
		return false, nil
	}
	return false, err
}
680341
func (rt *routingTable) GetNodeByAddress(address string) (no *node, ok bool) {
	rt.RLock()
	defer rt.RUnlock()

	v, ok := rt.cachedNodes.Get(address)
	if ok {
		no = v.(*node)
	}
	return
}
1222661
func putChainedAddress(ns walletdb.ReadWriteBucket, scope *KeyScope,
	addressID []byte, account uint32, status syncStatus, branch,
	index uint32, addrType addressType) error {

	scopedBucket, err := fetchWriteScopeBucket(ns, scope)
	if err != nil {
		return err
	}

	addrRow := dbAddressRow{
		addrType:   addrType,
		account:    account,
		addTime:    uint64(time.Now().Unix()),
		syncStatus: status,
		rawData:    serializeChainedAddress(branch, index),
	}
	if err := putAddress(ns, scope, addressID, &addrRow); err != nil {
		return err
	}

	// Update the next index for the appropriate internal or external
	// branch.
	accountID := uint32ToBytes(account)
	bucket := scopedBucket.NestedReadWriteBucket(acctBucketName)
	serializedAccount := bucket.Get(accountID)

	// Deserialize the account row.
	row, err := deserializeAccountRow(accountID, serializedAccount)
	if err != nil {
		return err
	}
	arow, err := deserializeDefaultAccountRow(accountID, row)
	if err != nil {
		return err
	}

	// Increment the appropriate next index depending on whether the branch
	// is internal or external.
	nextExternalIndex := arow.nextExternalIndex
	nextInternalIndex := arow.nextInternalIndex
	if branch == InternalBranch {
		nextInternalIndex = index + 1
	} else {
		nextExternalIndex = index + 1
	}

	// Reserialize the account with the updated index and store it.
	row.rawData = serializeDefaultAccountRow(
		arow.pubKeyEncrypted, arow.privKeyEncrypted, nextExternalIndex,
		nextInternalIndex, arow.name,
	)
	err = bucket.Put(accountID, serializeAccountRow(row))
	if err != nil {
		str := fmt.Sprintf("failed to update next index for "+
			"address %x, account %d", addressID, account)
		return managerError(ErrDatabase, str, err)
	}
	return nil
}
582886
func firstLastAddresses(subnet *net.IPNet) (net.IP, net.IP) {
	firstIP := subnet.IP
	lastIP := make([]byte, len(firstIP))
	copy(lastIP, firstIP)

	for i, b := range lastIP {
		lastIP[i] = b ^ (^subnet.Mask[i])
	}
	return firstIP, lastIP
}
814381
func FilterBridgeAddresses(addresses []Address) []Address {
	addressesToRemove := make(map[string][]net.Addr)
	gatherLXCAddresses(addressesToRemove)
	gatherBridgeAddresses(DefaultLXDBridge, addressesToRemove)
	gatherBridgeAddresses(DefaultKVMBridge, addressesToRemove)
	filtered := filterAddrs(addresses, addressesToRemove)
	logger.Debugf("addresses after filtering: %v", filtered)
	return filtered
}
396970
func LastAddr(n *net.IPNet) net.IP {
	return manipulateAddr(n, func(n, m byte) byte { return n | ^m })
}
122567
func (client *Client) AllocateEipAddress(args *AllocateEipAddressArgs) (EipAddress string, AllocationId string, err error) {
	if args.Bandwidth == 0 {
		args.Bandwidth = 5
	}
	response := AllocateEipAddressResponse{}
	err = client.Invoke("AllocateEipAddress", args, &response)
	if err != nil {
		return "", "", err
	}
	return response.EipAddress, response.AllocationId, nil
}
1303510
func ValidateAddresses(checkLastTrit bool, addrs ...Hash) Validatable {
	return func() error {
		for i := range addrs {
			if !IsAddressWithChecksum(addrs[i]) {
				return errors.Wrapf(ErrInvalidHash, "%s at index %d (not length of 90 trytes)", addrs[i], i)
			}
			if checkLastTrit {
				lastTrits := MustTrytesToTrits(string(addrs[i][80]))
				if lastTrits[2] != 0 {
					return errors.Wrapf(ErrInvalidHash, "%s at index %d (last trit non 0)", addrs[i], i)
				}
			}
		}
		return nil
	}
}
867561
func BlockReceivesToAddresses(block *dcrutil.Block, addrs map[string]TxAction,
	params *chaincfg.Params) map[string][]*dcrutil.Tx {
	addrMap := make(map[string][]*dcrutil.Tx)

	checkForAddrOut := func(blockTxs []*dcrutil.Tx) {
		for _, tx := range blockTxs {
			// Check the addresses associated with the PkScript of each TxOut
			for _, txOut := range tx.MsgTx().TxOut {
				_, txOutAddrs, _, err := txscript.ExtractPkScriptAddrs(txOut.Version,
					txOut.PkScript, params)
				if err != nil {
					fmt.Printf("ExtractPkScriptAddrs: %v", err.Error())
					continue
				}

				// Check if we are watching any address for this TxOut
				for _, txAddr := range txOutAddrs {
					addrstr := txAddr.EncodeAddress()
					if _, ok := addrs[addrstr]; ok {
						if _, gotSlice := addrMap[addrstr]; !gotSlice {
							addrMap[addrstr] = make([]*dcrutil.Tx, 0) // nil
						}
						addrMap[addrstr] = append(addrMap[addrstr], tx)
					}
				}
			}
		}
	}

	checkForAddrOut(block.Transactions())
	checkForAddrOut(block.STransactions())

	return addrMap
}
690820
func RetrieveAddressTxns(ctx context.Context, db *sql.DB, address string, N, offset int64) ([]*dbtypes.AddressRow, error) {
	return retrieveAddressTxns(ctx, db, address, N, offset,
		internal.SelectAddressLimitNByAddress, creditDebitQuery)
}
348530
func (s *Store) extendUnlocked(bs *BlockStamp) error {
	// Get last chained address.  New chained addresses will be
	// chained off of this address's chaincode and private key.
	a := s.chainIdxMap[s.lastChainIdx]
	waddr, ok := s.addrMap[getAddressKey(a)]
	if !ok {
		return errors.New("expected last chained address not found")
	}

	if s.isLocked() {
		return ErrLocked
	}

	lastAddr, ok := waddr.(*btcAddress)
	if !ok {
		return errors.New("found non-pubkey chained address")
	}

	privkey, err := lastAddr.unlock(s.secret)
	if err != nil {
		return err
	}
	cc := lastAddr.chaincode[:]

	privkey, err = chainedPrivKey(privkey, lastAddr.pubKeyBytes(), cc)
	if err != nil {
		return err
	}
	newAddr, err := newBtcAddress(s, privkey, nil, bs, true)
	if err != nil {
		return err
	}
	if err := newAddr.verifyKeypairs(); err != nil {
		return err
	}
	if err = newAddr.encrypt(s.secret); err != nil {
		return err
	}
	a = newAddr.Address()
	s.addrMap[getAddressKey(a)] = newAddr
	newAddr.chainIndex = lastAddr.chainIndex + 1
	s.chainIdxMap[newAddr.chainIndex] = a
	s.lastChainIdx++
	copy(newAddr.chaincode[:], cc)

	return nil
}
738553
func (pgb *ChainDB) MissingAddressIndexes() (missing []string, descs []string, err error) {
	for _, idxName := range internal.AddressesIndexNames {
		var exists bool
		exists, err = ExistsIndex(pgb.db, idxName)
		if err != nil {
			return
		}
		if !exists {
			missing = append(missing, idxName)
			descs = append(descs, pgb.indexDescription(idxName))
		}
	}
	return
}