// MergedAddresses provides a single list of addresses without duplicates
// suitable for returning as an address list for a machine.
// TODO (cherylj) Add explicit unit tests - tracked with bug #1544158
17608
func MergedAddresses(machineAddresses, providerAddresses []Address) []Address {
	merged := make([]Address, 0, len(providerAddresses)+len(machineAddresses))
	providerValues := set.NewStrings()
	for _, address := range providerAddresses {
		// Older versions of Juju may have stored an empty address so ignore it here.
		if address.Value == "" || providerValues.Contains(address.Value) {
			continue
		}
		providerValues.Add(address.Value)
		merged = append(merged, address)
	}
	for _, address := range machineAddresses {
		if !providerValues.Contains(address.Value) {
			merged = append(merged, address)
		}
	}
	return merged
}
261524
func (p *proxy) SetNewAddresses(addresses []addressTuple) {
	// Randomize the addresses so not all instances get them in the same order
	dest := make([]addressTuple, len(addresses))
	perm := rand.Perm(len(addresses))
	for i, v := range perm {
		dest[v] = addresses[i]
	}
	p.newAddresses <- dest
}
971605
func (a *AddressOutpoints) Merge(ao *AddressOutpoints) {
	// Relevant outpoints
	a.Outpoints = append(a.Outpoints, ao.Outpoints...)

	// Previous outpoints (inputs)
	a.PrevOuts = append(a.PrevOuts, ao.PrevOuts...)

	// Referenced transactions
	for h, t := range ao.TxnsStore {
		a.TxnsStore[h] = t
	}
}
403916
func (m *Machine) ProviderAddresses() ([]network.Address, error) {
	var results params.MachineAddressesResults
	args := params.Entities{Entities: []params.Entity{
		{Tag: m.tag.String()},
	}}
	err := m.facade.FacadeCall("ProviderAddresses", args, &results)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if len(results.Results) != 1 {
		err := errors.Errorf("expected 1 result, got %d", len(results.Results))
		return nil, err
	}
	result := results.Results[0]
	if result.Error != nil {
		return nil, result.Error
	}
	return params.NetworkAddresses(result.Addresses...), nil
}
424304
func (r *remoteServer) UpdateAddresses(addresses []string) {
	r.mutex.Lock()
	defer r.mutex.Unlock()

	if r.connection == nil && r.stopConnecting != nil {
		// We are probably trying to reconnect, so interrupt that so we don't
		// get a race between setting addresses and trying to read them to
		// connect. Note that we don't call the interruptConnecting method
		// here because that method also tries to lock the mutex.
		r.logger.Debugf("interrupting connecting due to new addresses: %v", addresses)
		close(r.stopConnecting)
		r.stopConnecting = nil
	}
	r.info.Addrs = addresses
}
506716
func (m *Machine) setAddresses(machineAddresses, providerAddresses *[]network.Address) error {
	var (
		machineStateAddresses, providerStateAddresses []address
		newPrivate, newPublic                         *address
		err                                           error
	)
	machine := m
	buildTxn := func(attempt int) ([]txn.Op, error) {
		if attempt != 0 {
			if machine, err = machine.st.Machine(machine.doc.Id); err != nil {
				return nil, err
			}
		}
		var ops []txn.Op
		ops, machineStateAddresses, providerStateAddresses, newPrivate, newPublic, err = machine.setAddressesOps(
			machineAddresses, providerAddresses,
		)
		if err != nil {
			return nil, err
		}
		return ops, nil
	}
	if err := m.st.db().Run(buildTxn); err != nil {
		return errors.Trace(err)
	}

	m.doc.MachineAddresses = machineStateAddresses
	m.doc.Addresses = providerStateAddresses
	if newPrivate != nil {
		oldPrivate := m.doc.PreferredPrivateAddress.networkAddress()
		m.doc.PreferredPrivateAddress = *newPrivate
		logger.Infof(
			"machine %q preferred private address changed from %q to %q",
			m.Id(), oldPrivate, newPrivate.networkAddress(),
		)
	}
	if newPublic != nil {
		oldPublic := m.doc.PreferredPublicAddress.networkAddress()
		m.doc.PreferredPublicAddress = *newPublic
		logger.Infof(
			"machine %q preferred public address changed from %q to %q",
			m.Id(), oldPublic, newPublic.networkAddress(),
		)
	}
	return nil
}
389262
func (a *AddrManager) AddAddresses(addrs []*wire.NetAddress, srcAddr *wire.NetAddress) {
	a.mtx.Lock()
	defer a.mtx.Unlock()

	for _, na := range addrs {
		a.updateAddress(na, srcAddr)
	}
}
888565
func (dev *LinkLayerDevice) RemoveAddresses() error {
	findQuery := findAddressesQuery(dev.doc.MachineID, dev.doc.Name)
	ops, err := dev.st.removeMatchingIPAddressesDocOps(findQuery)
	if err != nil {
		return errors.Trace(err)
	}

	return dev.st.db().RunTransaction(ops)
}
787099
func (i *Instances) NodeAddresses(name types.NodeName) ([]v1.NodeAddress, error) {
	glog.V(4).Infof("NodeAddresses(%v) called", name)

	addrs, err := getAddressesByName(i.compute, name)
	if err != nil {
		return nil, err
	}

	glog.V(4).Infof("NodeAddresses(%v) => %v", name, addrs)
	return addrs, nil
}
1146293
func (mi *maas1Instance) interfaceAddresses(ctx context.ProviderCallContext) ([]network.Address, error) {
	// Fetch a fresh copy of the instance JSON first.
	obj, err := refreshMAASObject(mi.maasObject)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return nil, errors.Annotate(err, "getting instance details")
	}

	subnetsMap, err := mi.environ.subnetToSpaceIds(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}
	// Get all the interface details and extract the addresses.
	interfaces, err := maasObjectNetworkInterfaces(ctx, &obj, subnetsMap)
	if err != nil {
		return nil, errors.Trace(err)
	}

	var addresses []network.Address
	for _, iface := range interfaces {
		if iface.Address.Value != "" {
			logger.Debugf("found address %q on interface %q", iface.Address, iface.InterfaceName)
			addresses = append(addresses, iface.Address)
		} else {
			logger.Infof("no address found on interface %q", iface.InterfaceName)
		}
	}
	return addresses, nil
}
1126330
func bestAddressIndexes(numAddr int, getAddrFunc addressByIndexFunc, matchFunc scopeMatchFunc) []int {
	// Categorise addresses by scope and type matching quality.
	matches := filterAndCollateAddressIndexes(numAddr, getAddrFunc, matchFunc)

	// Retrieve the indexes of the addresses with the best scope and type match.
	allowedMatchTypes := []scopeMatch{exactScopeIPv4, exactScope, firstFallbackScopeIPv4, firstFallbackScope, secondFallbackScopeIPv4, secondFallbackScope}
	for _, matchType := range allowedMatchTypes {
		indexes, ok := matches[matchType]
		if ok && len(indexes) > 0 {
			return indexes
		}
	}
	return []int{}
}
281196
func (b *BigIP) VirtualAddresses() (*VirtualAddresses, error) {
	var va VirtualAddresses
	err, _ := b.getForEntity(&va, uriLtm, uriVirtualAddress)
	if err != nil {
		return nil, err
	}
	return &va, nil
}
585175
func (a *NetAddr) FullAddress() string {
	return fmt.Sprintf("%v://%v", a.AddrNetwork, a.Addr)
}
178687
func UncompactMergedRows(merged []AddressRowMerged) []*AddressRow {
	rows := make([]*AddressRow, 0, len(merged))
	for i := range merged {
		r := &merged[i]
		rows = append(rows, &AddressRow{
			Address:        r.Address,
			ValidMainChain: r.ValidMainChain,
			// no MatchingTxHash for merged
			IsFunding:   r.IsFunding(),
			TxBlockTime: NewTimeDefFromUNIX(r.TxBlockTime),
			TxHash:      r.TxHash.String(),
			// no TxVinVoutIndex for merged
			Value: r.Value(),
			// no VinVoutDbID for merged
			MergedCount: uint64(r.MergedCount),
			TxType:      r.TxType,
		})
	}
	return rows
}
382737
func retrieveAddressTxns(ctx context.Context, db *sql.DB, address string, N, offset int64,
	statement string, queryType int) ([]*dbtypes.AddressRow, error) {
	rows, err := db.QueryContext(ctx, statement, address, N, offset)
	if err != nil {
		return nil, err
	}
	defer closeRows(rows)

	switch queryType {
	case mergedCreditQuery, mergedDebitQuery, mergedQuery:
		onlyValidMainchain := true
		addr, err := scanAddressMergedRows(rows, address, queryType, onlyValidMainchain)
		return addr, err
	default:
		return scanAddressQueryRows(rows, queryType)
	}
}
1089182
func FormatAddressList(addrs []*Address) (fields []interface{}) {
	fields = make([]interface{}, len(addrs))

	for i, addr := range addrs {
		fields[i] = addr.Format()
	}

	return
}
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
}