// retChan should be a buffered channel
190479
func (m *Market) AddDemand(r Requirement, bid float64, retChan chan Supply) {
	m.Lock.Lock()
	defer m.Lock.Unlock()

	if len(m.Supplies) > 0 {
		supply, matched := m.pickBestSupplyFor(r)
		if matched {
			retChan <- supply
			close(retChan)
			return
		}
	}
	m.Demands = append(m.Demands, Demand{
		Requirement: r,
		Bid:         bid,
		ReturnChan:  retChan,
	})
	m.hasDemands.Signal()
}
960893
func (o *httpOps) AscRemoteFetcher() *remoteAscFetcher {
	ensureLogger(o.Debug)
	f := func(u *url.URL, file *os.File) error {
		switch u.Scheme {
		case "http", "https":
		default:
			return fmt.Errorf("invalid signature location: expected %q scheme, got %q", "http(s)", u.Scheme)
		}
		session := o.getSession(u, file, "signature", "")
		dl := o.getDownloader(session)
		err := dl.Download(u, file)
		if err != nil {
			return err
		}
		if session.Cd.UseCached {
			return fmt.Errorf("unexpected cache reuse request for signature %q", u.String())
		}
		return nil
	}
	return &remoteAscFetcher{
		F: f,
		S: o.S,
	}
}
508265
func (p *siprng) rekey() {
	var k [16]byte
	if _, err := io.ReadFull(rand.Reader, k[:]); err != nil {
		panic(err.Error())
	}
	p.k0 = binary.LittleEndian.Uint64(k[0:8])
	p.k1 = binary.LittleEndian.Uint64(k[8:16])
	p.ctr = 1
}
844206
func (api *API) Reap() error {
	migration, err := api.backend.LatestMigration()
	if err != nil {
		return errors.Trace(err)
	}
	err = api.backend.RemoveExportingModelDocs()
	if err != nil {
		return errors.Trace(err)
	}
	// We need to mark the migration as complete here, since removing
	// the model might kill the worker before it has a chance to set
	// the phase itself.
	return errors.Trace(migration.SetPhase(coremigration.DONE))
}
447479
func (r *Reflector) resyncChan() (<-chan time.Time, func() bool) {
	if r.resyncPeriod == 0 {
		return neverExitWatch, func() bool { return false }
	}
	// The cleanup function is required: imagine the scenario where watches
	// always fail so we end up listing frequently. Then, if we don't
	// manually stop the timer, we could end up with many timers active
	// concurrently.
	t := r.clock.NewTimer(r.resyncPeriod)
	return t.C(), t.Stop
}
573724
func (us *HtdigestUserStore) ReloadOn(when os.Signal, onbad BadLineHandler) {
	// this is rather common with code in htpasswd, but I don't have a common area...
	c := make(chan os.Signal, 1)
	signal.Notify(c, when)

	go func() {
		for {
			_ = <-c
			log.Printf("Reloading!")
			us.Reload(onbad)
		}
	}()
}
444561
func (c *channelPool) wrapConn(conn net.Conn) net.Conn {
	p := &PoolConn{c: c}
	p.Conn = conn
	return p
}
575300
func (c *Chan) SendChan() chan<- interface{} {

	c.mutx.Lock()
	defer c.mutx.Unlock()

	if c.sendch == nil {
		c.sendch = make(chan interface{})
		go c.sendLoop()
	}
	return c.sendch
}
293699
func (p *BlockPrefetchClient) retarget(hash string) {
	if hash == "" {
		return
	}

	if p.next.headerResult != nil && hash == p.next.headerResult.Hash {
		return
	}
	// Do not go backwards
	if p.current.headerResult != nil && hash == p.current.headerResult.Hash {
		return
	}

	h, err := chainhash.NewHashFromStr(hash)
	if err != nil {
		log.Errorf("Invalid hash %s: %v", hash, err)
		return
	}

	p.retargetChan <- h
}
1254327
func (z *StreamLexer) ShiftLen() int {
	n := z.start - z.prevStart
	z.prevStart = z.start
	return n
}
572035
func (m *JobExecutor) DrainChan() MessageChan {
	tasks := m.RootTask.Children()
	return tasks[len(tasks)-1].(TaskRunner).MessageOut()
}
906989
func (brq *blockRetrievalQueue) TogglePrefetcher(enable bool,
	testSyncCh <-chan struct{}, testDoneCh chan<- struct{}) <-chan struct{} {
	// We must hold this lock for the whole function so that multiple calls to
	// this function doesn't leak prefetchers.
	brq.prefetchMtx.Lock()
	defer brq.prefetchMtx.Unlock()
	// Allow the caller to block on the current shutdown.
	ch := brq.prefetcher.Shutdown()
	if enable {
		brq.prefetcher = newBlockPrefetcher(
			brq, brq.config, testSyncCh, testDoneCh)
	}
	return ch
}
411434
func (d *AuthenticatedGossiper) retransmitStaleChannels() error {
	// Iterate over all of our channels and check if any of them fall
	// within the prune interval or re-broadcast interval.
	type updateTuple struct {
		info *channeldb.ChannelEdgeInfo
		edge *channeldb.ChannelEdgePolicy
	}
	var edgesToUpdate []updateTuple
	err := d.cfg.Router.ForAllOutgoingChannels(func(
		info *channeldb.ChannelEdgeInfo,
		edge *channeldb.ChannelEdgePolicy) error {

		// If there's no auth proof attached to this edge, it means
		// that it is a private channel not meant to be announced to
		// the greater network, so avoid sending channel updates for
		// this channel to not leak its
		// existence.
		if info.AuthProof == nil {
			log.Debugf("Skipping retransmission of channel "+
				"without AuthProof: %v", info.ChannelID)
			return nil
		}

		// If this edge has a ChannelUpdate that was created before the
		// introduction of the MaxHTLC field, then we'll update this
		// edge to propagate this information in the network.
		if !edge.MessageFlags.HasMaxHtlc() {
			edgesToUpdate = append(edgesToUpdate, updateTuple{
				info: info,
				edge: edge,
			})
			return nil
		}

		const broadcastInterval = time.Hour * 24

		timeElapsed := time.Since(edge.LastUpdate)

		// If it's been a full day since we've re-broadcasted the
		// channel, add the channel to the set of edges we need to
		// update.
		if timeElapsed >= broadcastInterval {
			edgesToUpdate = append(edgesToUpdate, updateTuple{
				info: info,
				edge: edge,
			})
		}

		return nil
	})
	if err != nil && err != channeldb.ErrGraphNoEdgesFound {
		return fmt.Errorf("unable to retrieve outgoing channels: %v",
			err)
	}

	var signedUpdates []lnwire.Message
	for _, chanToUpdate := range edgesToUpdate {
		// Re-sign and update the channel on disk and retrieve our
		// ChannelUpdate to broadcast.
		chanAnn, chanUpdate, err := d.updateChannel(
			chanToUpdate.info, chanToUpdate.edge,
		)
		if err != nil {
			return fmt.Errorf("unable to update channel: %v", err)
		}

		// If we have a valid announcement to transmit, then we'll send
		// that along with the update.
		if chanAnn != nil {
			signedUpdates = append(signedUpdates, chanAnn)
		}

		signedUpdates = append(signedUpdates, chanUpdate)
	}

	// If we don't have any channels to re-broadcast, then we'll exit
	// early.
	if len(signedUpdates) == 0 {
		return nil
	}

	log.Infof("Retransmitting %v outgoing channels", len(edgesToUpdate))

	// With all the wire announcements properly crafted, we'll broadcast
	// our known outgoing channels to all our immediate peers.
	if err := d.cfg.Broadcast(nil, signedUpdates...); err != nil {
		return fmt.Errorf("unable to re-broadcast channels: %v", err)
	}

	return nil
}
351027
func (l *channelLink) handleBatchFwdErrs(errChan chan error) {
	for {
		err, ok := <-errChan
		if !ok {
			// Err chan has been drained or switch is shutting
			// down.  Either way, return.
			return
		}

		if err == nil {
			continue
		}

		l.errorf("unhandled error while forwarding htlc packet over "+
			"htlcswitch: %v", err)
	}
}
394282
func (b *BlockServerRemote) RefreshAuthToken(ctx context.Context) {
	b.putConn.RefreshAuthToken(ctx)
	b.getConn.RefreshAuthToken(ctx)
}
1298582
func (p *Phosphor) reloadConfig() error {
	c := p.configProvider.Config()

	// Skip reloading if the config is the same
	h := fmt.Sprintf("%x", deephash.Hash(c))
	if p.compareConfigHash(h) {
		return nil
	}

	// keep reference to the old channel so we can drain this in parallel with
	// new traces the transport receives
	oldChan := p.traceChan

	// init new channel for traces, ensure this *isn't* zero
	bufLen := c.BufferSize
	if bufLen == 0 {
		bufLen = defaultTraceBufferSize
	}
	newChan := make(chan []byte, bufLen)

	// Get a new transport and keep a reference to the old one
	p.trMtx.Lock()
	defer p.trMtx.Unlock()
	oldTr := p.tr
	endpoint := fmt.Sprintf("%s:%v", c.Host, c.Port)
	newTr := newUDPTransport(endpoint)

	// start new transport by passing both channels to this
	// therefore it starts consuming from the new one (with nothing)
	// and also the old one (still current) in parallel to the previous transport
	// If this somehow fails, abort until next attempt
	if err := newTr.Consume(oldChan, newChan); err != nil {
		newTr.Stop()
		return err
	}

	// swap the client reference of the trace channel from old to new, so
	// new clients start using the new resized channel
	// TODO atomically swap this
	p.traceChan = newChan

	// gracefully shut down old transport, so just the new one is running
	if oldTr != nil {
		if err := oldTr.Stop(); err != nil {
			return err
		}
	}

	// set the config hash & swap the transport as we're finished
	p.updateConfigHash(h)
	p.tr = newTr

	return nil
}
817506
func (s *server) rebroadcastHandler() {
	// Wait 5 min before first tx rebroadcast.
	timer := time.NewTimer(5 * time.Minute)
	pendingInvs := make(map[wire.InvVect]interface{})

out:
	for {
		select {
		case riv := <-s.modifyRebroadcastInv:
			switch msg := riv.(type) {
			// Incoming InvVects are added to our map of RPC txs.
			case broadcastInventoryAdd:
				pendingInvs[*msg.invVect] = msg.data

			// When an InvVect has been added to a block, we can
			// now remove it, if it was present.
			case broadcastInventoryDel:
				if _, ok := pendingInvs[*msg]; ok {
					delete(pendingInvs, *msg)
				}
			}

		case <-timer.C:
			// Any inventory we have has not made it into a block
			// yet. We periodically resubmit them until they have.
			for iv, data := range pendingInvs {
				ivCopy := iv
				s.RelayInventory(&ivCopy, data)
			}

			// Process at a random time up to 30mins (in seconds)
			// in the future.
			timer.Reset(time.Second *
				time.Duration(randomUint16Number(1800)))

		case <-s.quit:
			break out
		}
	}

	timer.Stop()

	// Drain channels before exiting so nothing is left waiting around
	// to send.
cleanup:
	for {
		select {
		case <-s.modifyRebroadcastInv:
		default:
			break cleanup
		}
	}
	s.wg.Done()
}