// unspentRequests returns the set of spend requests that are still seen as
// unspent by the TxNotifier.
//
// NOTE: This method must be called with the TxNotifier's lock held.
779337
func (n *TxNotifier) unspentRequests() []SpendRequest {
	var unspent []SpendRequest
	for spendRequest, spendNtfnSet := range n.spendNotifications {
		// If the notification is already aware of its spend details, or
		// it's in the process of learning them, we'll skip it as we
		// can't yet determine if it's unspent or not.
		if spendNtfnSet.rescanStatus != rescanComplete ||
			spendNtfnSet.details != nil {
			continue
		}

		unspent = append(unspent, spendRequest)
	}

	return unspent
}
480963
func (s *Store) UnspentOutputs(ns walletdb.ReadBucket) ([]Credit, error) {
	var unspent []Credit

	var op wire.OutPoint
	var block Block
	err := ns.NestedReadBucket(bucketUnspent).ForEach(func(k, v []byte) error {
		err := readCanonicalOutPoint(k, &op)
		if err != nil {
			return err
		}
		if existsRawUnminedInput(ns, k) != nil {
			// Output is spent by an unmined transaction.
			// Skip this k/v pair.
			return nil
		}
		err = readUnspentBlock(v, &block)
		if err != nil {
			return err
		}

		blockTime, err := fetchBlockTime(ns, block.Height)
		if err != nil {
			return err
		}
		// TODO(jrick): reading the entire transaction should
		// be avoidable.  Creating the credit only requires the
		// output amount and pkScript.
		rec, err := fetchTxRecord(ns, &op.Hash, &block)
		if err != nil {
			return err
		}
		txOut := rec.MsgTx.TxOut[op.Index]
		cred := Credit{
			OutPoint: op,
			BlockMeta: BlockMeta{
				Block: block,
				Time:  blockTime,
			},
			Amount:       btcutil.Amount(txOut.Value),
			PkScript:     txOut.PkScript,
			Received:     rec.Received,
			FromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),
		}
		unspent = append(unspent, cred)
		return nil
	})
	if err != nil {
		if _, ok := err.(Error); ok {
			return nil, err
		}
		str := "failed iterating unspent bucket"
		return nil, storeError(ErrDatabase, str, err)
	}

	err = ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) error {
		if existsRawUnminedInput(ns, k) != nil {
			// Output is spent by an unmined transaction.
			// Skip to next unmined credit.
			return nil
		}

		err := readCanonicalOutPoint(k, &op)
		if err != nil {
			return err
		}

		// TODO(jrick): Reading/parsing the entire transaction record
		// just for the output amount and script can be avoided.
		recVal := existsRawUnmined(ns, op.Hash[:])
		var rec TxRecord
		err = readRawTxRecord(&op.Hash, recVal, &rec)
		if err != nil {
			return err
		}

		txOut := rec.MsgTx.TxOut[op.Index]
		cred := Credit{
			OutPoint: op,
			BlockMeta: BlockMeta{
				Block: Block{Height: -1},
			},
			Amount:       btcutil.Amount(txOut.Value),
			PkScript:     txOut.PkScript,
			Received:     rec.Received,
			FromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),
		}
		unspent = append(unspent, cred)
		return nil
	})
	if err != nil {
		if _, ok := err.(Error); ok {
			return nil, err
		}
		str := "failed iterating unmined credits bucket"
		return nil, storeError(ErrDatabase, str, err)
	}

	return unspent, nil
}
919247
func (s *walletServer) GetTransactions(ctx context.Context, req *pb.GetTransactionsRequest) (
	resp *pb.GetTransactionsResponse, err error) {

	var startBlock, endBlock *wallet.BlockIdentifier
	if req.StartingBlockHash != nil && req.StartingBlockHeight != 0 {
		return nil, errors.New(
			"starting block hash and height may not be specified simultaneously")
	} else if req.StartingBlockHash != nil {
		startBlockHash, err := chainhash.NewHash(req.StartingBlockHash)
		if err != nil {
			return nil, grpc.Errorf(codes.InvalidArgument, "%s", err.Error())
		}
		startBlock = wallet.NewBlockIdentifierFromHash(startBlockHash)
	} else if req.StartingBlockHeight != 0 {
		startBlock = wallet.NewBlockIdentifierFromHeight(req.StartingBlockHeight)
	}

	if req.EndingBlockHash != nil && req.EndingBlockHeight != 0 {
		return nil, grpc.Errorf(codes.InvalidArgument,
			"ending block hash and height may not be specified simultaneously")
	} else if req.EndingBlockHash != nil {
		endBlockHash, err := chainhash.NewHash(req.EndingBlockHash)
		if err != nil {
			return nil, grpc.Errorf(codes.InvalidArgument, "%s", err.Error())
		}
		endBlock = wallet.NewBlockIdentifierFromHash(endBlockHash)
	} else if req.EndingBlockHeight != 0 {
		endBlock = wallet.NewBlockIdentifierFromHeight(req.EndingBlockHeight)
	}

	var minRecentTxs int
	if req.MinimumRecentTransactions != 0 {
		if endBlock != nil {
			return nil, grpc.Errorf(codes.InvalidArgument,
				"ending block and minimum number of recent transactions "+
					"may not be specified simultaneously")
		}
		minRecentTxs = int(req.MinimumRecentTransactions)
		if minRecentTxs < 0 {
			return nil, grpc.Errorf(codes.InvalidArgument,
				"minimum number of recent transactions may not be negative")
		}
	}

	_ = minRecentTxs

	gtr, err := s.wallet.GetTransactions(startBlock, endBlock, ctx.Done())
	if err != nil {
		return nil, translateError(err)
	}
	return marshalGetTransactionsResult(gtr)
}
129849
func (node *ClientNode) AcceptRequest(reqID, index, maxCost uint64) (accepted bool, bufShort uint64, priority int64) {
	node.lock.Lock()
	defer node.lock.Unlock()

	now := node.cm.clock.Now()
	node.update(now)
	if maxCost > node.bufValue {
		if node.log != nil {
			node.log.add(now, fmt.Sprintf("rejected  reqID=%d  bv=%d  maxCost=%d", reqID, node.bufValue, maxCost))
			node.log.dump(now)
		}
		return false, maxCost - node.bufValue, 0
	}
	node.bufValue -= maxCost
	node.sumCost += maxCost
	if node.log != nil {
		node.log.add(now, fmt.Sprintf("accepted  reqID=%d  bv=%d  maxCost=%d  sumCost=%d", reqID, node.bufValue, maxCost, node.sumCost))
	}
	node.accepted[index] = node.sumCost
	return true, 0, node.cm.accepted(node, maxCost, now)
}
804972
func UnconfirmedTxnsForAddress(client *rpcclient.Client, address string, params *chaincfg.Params) (*txhelpers.AddressOutpoints, int64, error) {
	// Mempool transactions
	var numUnconfirmed int64
	mempoolTxns, err := client.GetRawMempoolVerbose(dcrjson.GRMAll)
	if err != nil {
		log.Warnf("GetRawMempool failed for address %s: %v", address, err)
		return nil, numUnconfirmed, err
	}

	// Check each transaction for involvement with provided address.
	addressOutpoints := txhelpers.NewAddressOutpoints(address)
	for hash, tx := range mempoolTxns {
		// Transaction details from dcrd
		txhash, err1 := chainhash.NewHashFromStr(hash)
		if err1 != nil {
			log.Errorf("Invalid transaction hash %s", hash)
			return addressOutpoints, 0, err1
		}

		Tx, err1 := client.GetRawTransaction(txhash)
		if err1 != nil {
			log.Warnf("Unable to GetRawTransaction(%s): %v", hash, err1)
			err = err1
			continue
		}
		// Scan transaction for inputs/outputs involving the address of interest
		outpoints, prevouts, prevTxns := txhelpers.TxInvolvesAddress(Tx.MsgTx(),
			address, client, params)
		if len(outpoints) == 0 && len(prevouts) == 0 {
			continue
		}
		// Update previous outpoint txn slice with mempool time
		for f := range prevTxns {
			prevTxns[f].MemPoolTime = tx.Time
		}

		// Add present transaction to previous outpoint txn slice
		numUnconfirmed++
		thisTxUnconfirmed := &txhelpers.TxWithBlockData{
			Tx:          Tx.MsgTx(),
			MemPoolTime: tx.Time,
		}
		prevTxns = append(prevTxns, thisTxUnconfirmed)
		// Merge the I/Os and the transactions into results
		addressOutpoints.Update(prevTxns, outpoints, prevouts)
	}

	return addressOutpoints, numUnconfirmed, err
}
847169
func (nsPayloads_) untrackOp(payloads mongo.Collection, docID string) (txn.Op, error) {
	count, err := payloads.FindId(docID).Count()
	if err != nil {
		return txn.Op{}, errors.Trace(err)
	} else if count == 0 {
		return txn.Op{}, errAlreadyRemoved
	}
	return txn.Op{
		C:      payloads.Name(),
		Id:     docID,
		Assert: txn.DocExists,
		Remove: true,
	}, nil
}
1047467
func (d *domainClient) RequestEntries(ctx context.Context, args *RequestEntriesArgs) (reply *RequestEntriesReply, err error) {
	reply = new(RequestEntriesReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "CacheStorage.requestEntries", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "CacheStorage.requestEntries", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "CacheStorage", Op: "RequestEntries", Err: err}
	}
	return
}
719952
func (r *rpcServer) SubscribeTransactions(req *lnrpc.GetTransactionsRequest,
	updateStream lnrpc.Lightning_SubscribeTransactionsServer) error {

	txClient, err := r.server.cc.wallet.SubscribeTransactions()
	if err != nil {
		return err
	}
	defer txClient.Cancel()

	for {
		select {
		case tx := <-txClient.ConfirmedTransactions():
			detail := &lnrpc.Transaction{
				TxHash:           tx.Hash.String(),
				Amount:           int64(tx.Value),
				NumConfirmations: tx.NumConfirmations,
				BlockHash:        tx.BlockHash.String(),
				TimeStamp:        tx.Timestamp,
				TotalFees:        tx.TotalFees,
			}
			if err := updateStream.Send(detail); err != nil {
				return err
			}

		case tx := <-txClient.UnconfirmedTransactions():
			detail := &lnrpc.Transaction{
				TxHash:    tx.Hash.String(),
				Amount:    int64(tx.Value),
				TimeStamp: tx.Timestamp,
				TotalFees: tx.TotalFees,
			}
			if err := updateStream.Send(detail); err != nil {
				return err
			}

		case <-r.quit:
			return nil
		}
	}
}
487058
func (c *Client) LockUnspentAsync(unlock bool, ops []*wire.OutPoint) FutureLockUnspentResult {
	outputs := make([]btcjson.TransactionInput, len(ops))
	for i, op := range ops {
		outputs[i] = btcjson.TransactionInput{
			Txid: op.Hash.String(),
			Vout: op.Index,
		}
	}
	cmd := btcjson.NewLockUnspentCmd(unlock, outputs)
	return c.sendCmd(cmd)
}
233473
func (s *SyncStatusSubscription) Unsubscribe() {
	s.unsubOnce.Do(func() {
		req := uninstallSyncSubscriptionRequest{s.c, make(chan interface{})}
		s.api.uninstallSyncSubscription <- &req

		for {
			select {
			case <-s.c:
				// drop new status events until uninstall confirmation
				continue
			case <-req.uninstalled:
				return
			}
		}
	})
}
1081648
func (m *wsNotificationManager) UnregisterSpentRequest(wsc *wsClient, op *wire.OutPoint) {
	m.queueNotification <- &notificationUnregisterSpent{
		wsc: wsc,
		op:  op,
	}
}
208330
func (b *batchSpendReporter) notifyRequests(
	outpoint *wire.OutPoint,
	requests []*GetUtxoRequest,
	report *SpendReport,
	err error) {

	delete(b.requests, *outpoint)
	delete(b.initialTxns, *outpoint)
	delete(b.outpoints, *outpoint)

	for _, request := range requests {
		request.deliver(report, err)
	}
}
157116
func (t *transport) CancelRequest(req *http.Request) {
	type canceler interface {
		CancelRequest(*http.Request)
	}
	if cr, ok := t.base().(canceler); ok {
		t.mu.Lock()
		modReq := t.modReq[req]
		delete(t.modReq, req)
		t.mu.Unlock()
		cr.CancelRequest(modReq)
	}
}
102139
func GetNonzeroRequests(requests *v1.ResourceList) (int64, int64) {
	var outMilliCPU, outMemory int64
	// Override if un-set, but not if explicitly set to zero
	if _, found := (*requests)[v1.ResourceCPU]; !found {
		outMilliCPU = DefaultMilliCPURequest
	} else {
		outMilliCPU = requests.Cpu().MilliValue()
	}
	// Override if un-set, but not if explicitly set to zero
	if _, found := (*requests)[v1.ResourceMemory]; !found {
		outMemory = DefaultMemoryRequest
	} else {
		outMemory = requests.Memory().Value()
	}
	return outMilliCPU, outMemory
}
633976
func (a *Agent) processRequests(conn *ssh.Client) error {
	defer conn.Close()
	ticker := time.NewTicker(defaults.ReverseTunnelAgentHeartbeatPeriod)
	defer ticker.Stop()

	hb, reqC, err := conn.OpenChannel(chanHeartbeat, nil)
	if err != nil {
		return trace.Wrap(err)
	}
	newTransportC := conn.HandleChannelOpen(chanTransport)
	newDiscoveryC := conn.HandleChannelOpen(chanDiscovery)

	// send first ping right away, then start a ping timer:
	hb.SendRequest("ping", false, nil)

	for {
		select {
		// need to exit:
		case <-a.ctx.Done():
			return trace.ConnectionProblem(nil, "heartbeat: agent is stopped")
		// time to ping:
		case <-ticker.C:
			bytes, _ := a.Clock.Now().UTC().MarshalText()
			_, err := hb.SendRequest("ping", false, bytes)
			if err != nil {
				a.Error(err)
				return trace.Wrap(err)
			}
			a.Debugf("Ping -> %v.", conn.RemoteAddr())
		// ssh channel closed:
		case req := <-reqC:
			if req == nil {
				return trace.ConnectionProblem(nil, "heartbeat: connection closed")
			}
		// new transport request:
		case nch := <-newTransportC:
			if nch == nil {
				continue
			}
			a.Debugf("Transport request: %v.", nch.ChannelType())
			ch, req, err := nch.Accept()
			if err != nil {
				a.Warningf("Failed to accept request: %v.", err)
				continue
			}
			go proxyTransport(&transportParams{
				log:          a.Entry,
				closeContext: a.ctx,
				authClient:   a.Client,
				kubeDialAddr: a.KubeDialAddr,
				channel:      ch,
				requestCh:    req,
				sconn:        conn.Conn,
				server:       a.Server,
				component:    teleport.ComponentReverseTunnelAgent,
			})
		// new discovery request
		case nch := <-newDiscoveryC:
			if nch == nil {
				continue
			}
			a.Debugf("discovery request: %v", nch.ChannelType())
			ch, req, err := nch.Accept()
			if err != nil {
				a.Warningf("failed to accept request: %v", err)
				continue
			}
			go a.handleDiscovery(ch, req)
		}
	}
}
1159065
func incRequests() {
	stats.TotalRequestRate.Mark(1)
	eCtr := float64(stats.ErrorRate.Count())
	rCtr := float64(stats.TotalRequestRate.Count())
	stats.ErrorPercent.Update(eCtr / rCtr * 100)
}
793193
func (n *TxNotifier) dispatchSpendReorg(ntfn *SpendNtfn) error {
	if !ntfn.dispatched {
		return nil
	}

	// Attempt to drain the spend notification to ensure sends to the Spend
	// channel are always non-blocking.
	select {
	case <-ntfn.Event.Spend:
	default:
	}

	// Send a reorg notification to the client in order for them to
	// correctly handle reorgs.
	select {
	case ntfn.Event.Reorg <- struct{}{}:
	case <-n.quit:
		return ErrTxNotifierExiting
	}

	ntfn.dispatched = false

	return nil
}