// spendsWatchedInput returns whether the transaction matches the filter by
// spending a watched input.
776432
func (ro *rescanOptions) spendsWatchedInput(tx *btcutil.Tx) bool {
	for _, in := range tx.MsgTx().TxIn {
		for _, input := range ro.watchInputs {
			switch {
			// If we're watching for a zero outpoint, then we should
			// match on the output script being spent instead.
			case input.OutPoint == zeroOutPoint:
				pkScript, err := txscript.ComputePkScript(
					in.SignatureScript, in.Witness,
				)
				if err != nil {
					continue
				}

				if bytes.Equal(pkScript.Script(), input.PkScript) {
					return true
				}

			// Otherwise, we'll match on the outpoint being spent.
			case in.PreviousOutPoint == input.OutPoint:
				return true
			}
		}
	}
	return false
}
1003748
func (t *transfer) Watch(progressOutput progress.Output) *Watcher {
	t.mu.Lock()
	defer t.mu.Unlock()

	w := &Watcher{
		releaseChan: make(chan struct{}),
		signalChan:  make(chan struct{}),
		running:     make(chan struct{}),
	}

	t.watchers[w.releaseChan] = w

	if t.broadcastDone {
		close(w.running)
		return w
	}

	go func() {
		defer func() {
			close(w.running)
		}()
		var (
			done           bool
			lastWritten    progress.Progress
			hasLastWritten bool
		)
		for {
			t.mu.Lock()
			hasLastProgress := t.hasLastProgress
			lastProgress := t.lastProgress
			t.mu.Unlock()

			// Make sure we don't write the last progress item
			// twice.
			if hasLastProgress && (!done || !hasLastWritten || lastProgress != lastWritten) {
				progressOutput.WriteProgress(lastProgress)
				lastWritten = lastProgress
				hasLastWritten = true
			}

			if done {
				return
			}

			select {
			case <-w.signalChan:
			case <-w.releaseChan:
				done = true
				// Since the watcher is going to detach, make
				// sure the broadcaster is caught up so we
				// don't miss anything.
				select {
				case t.broadcastSyncChan <- struct{}{}:
				case <-t.running:
				}
			case <-t.running:
				done = true
			}
		}
	}()

	return w
}
1093432
func deleteRawUnminedInput(ns walletdb.ReadWriteBucket, outPointKey []byte,
	targetSpendHash chainhash.Hash) error {

	// We'll start by fetching all of the possible spending transactions.
	unminedInputs := ns.NestedReadWriteBucket(bucketUnminedInputs)
	spendHashes := unminedInputs.Get(outPointKey)
	if len(spendHashes) == 0 {
		return nil
	}

	// We'll iterate through them and pick all the ones that don't match the
	// specified spending transaction.
	var newSpendHashes []byte
	numHashes := len(spendHashes) / 32
	for i, idx := 0, 0; i < numHashes; i, idx = i+1, idx+32 {
		spendHash := spendHashes[idx : idx+32]
		if !bytes.Equal(targetSpendHash[:], spendHash) {
			newSpendHashes = append(newSpendHashes, spendHash...)
		}
	}

	// If there aren't any entries left after filtering them, then we can
	// remove the record completely. Otherwise, we'll store the filtered
	// records.
	var err error
	if len(newSpendHashes) == 0 {
		err = unminedInputs.Delete(outPointKey)
	} else {
		err = unminedInputs.Put(outPointKey, newSpendHashes)
	}
	if err != nil {
		str := "failed to delete unmined input spend"
		return storeError(ErrDatabase, str, err)
	}

	return nil
}
870343
func (rpc *EthRPC) EthNewPendingTransactionFilter() (string, error) {
	var filterID string
	err := rpc.call("eth_newPendingTransactionFilter", &filterID)
	return filterID, err
}
1146056
func (v *Verifier) isSpent(spentKey string, simulator ledger.LedgerReader) (bool, error) {
	verifierLogger.Debugf("checking if input with ID '%s' has been spent", spentKey)
	result, err := simulator.GetState(tokenNameSpace, spentKey)
	return result != nil, err
}
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
		}
	}
}
1146783
func (mem *memNamedMapping) Watch(subscriber string, callback func(idxmap.NamedMappingGenericEvent)) error {
	mem.Debug("Watch ", subscriber)

	_, found := mem.subscribers.LoadOrStore(subscriber, callback)
	if found {
		return fmt.Errorf("Already registered channel per subscriber ")
	}
	return nil
}
95017
func (e *Store) WatchPredicate(ctx context.Context, p storage.SelectionPredicate, resourceVersion string) (watch.Interface, error) {
	if name, ok := p.MatchesSingle(); ok {
		if key, err := e.KeyFunc(ctx, name); err == nil {
			w, err := e.Storage.Watch(ctx, key, resourceVersion, p)
			if err != nil {
				return nil, err
			}
			if e.Decorator != nil {
				return newDecoratedWatcher(w, e.Decorator), nil
			}
			return w, nil
		}
		// if we cannot extract a key based on the current context, the
		// optimization is skipped
	}

	w, err := e.Storage.WatchList(ctx, e.KeyRootFunc(ctx), resourceVersion, p)
	if err != nil {
		return nil, err
	}
	if e.Decorator != nil {
		return newDecoratedWatcher(w, e.Decorator), nil
	}
	return w, nil
}
1275909
func (a *Application) WatchUnits() StringsWatcher {
	members := bson.D{{"application", a.doc.Name}}
	prefix := a.doc.Name + "/"
	filter := func(unitDocID interface{}) bool {
		unitName, err := a.st.strictLocalID(unitDocID.(string))
		if err != nil {
			return false
		}
		return strings.HasPrefix(unitName, prefix)
	}
	return newLifecycleWatcher(a.st, unitsC, members, filter, nil)
}
91887
func keyWatch(params map[string]interface{}) (WatcherFunc, error) {
	stale := false
	if err := assignValueBool(params, "stale", &stale); err != nil {
		return nil, err
	}

	var key string
	if err := assignValue(params, "key", &key); err != nil {
		return nil, err
	}
	if key == "" {
		return nil, fmt.Errorf("Must specify a single key to watch")
	}
	fn := func(p *Plan) (BlockingParamVal, interface{}, error) {
		kv := p.client.KV()
		opts := makeQueryOptionsWithContext(p, stale)
		defer p.cancelFunc()
		pair, meta, err := kv.Get(key, &opts)
		if err != nil {
			return nil, nil, err
		}
		if pair == nil {
			return WaitIndexVal(meta.LastIndex), nil, err
		}
		return WaitIndexVal(meta.LastIndex), pair, err
	}
	return fn, nil
}
121962
func fetchWatchingOnly(ns walletdb.ReadBucket) (bool, error) {
	bucket := ns.NestedReadBucket(mainBucketName)

	buf := bucket.Get(watchingOnlyName)
	if len(buf) != 1 {
		str := "malformed watching-only flag stored in database"
		return false, managerError(ErrDatabase, str, nil)
	}

	return buf[0] != 0, nil
}
1246956
func (c *Client) WatchTask(id string) *WatchTasksResult {
	// during watch we don't want to have a timeout
	// Store the old timeout so we can restore when we are through
	oldTimeout := c.http.Timeout
	c.http.Timeout = time.Duration(0)

	r := &WatchTasksResult{
		EventChan: make(chan *rbody.StreamedTaskEvent),
		DoneChan:  make(chan struct{}),
	}

	url := fmt.Sprintf("%s/tasks/%v/watch", c.prefix, id)
	req, err := http.NewRequest("GET", url, nil)
	addAuth(req, c.Username, c.Password)
	if err != nil {
		r.Err = err
		r.Close()
		return r
	}
	resp, err := c.http.Do(req)
	if err != nil {
		if strings.Contains(err.Error(), "tls: oversized record") || strings.Contains(err.Error(), "malformed HTTP response") {
			r.Err = fmt.Errorf("error connecting to API URI: %s. Do you have an http/https mismatch?", c.URL)
		} else {
			r.Err = err
		}
		r.Close()
		return r
	}

	if resp.StatusCode != 200 {
		ar, err := httpRespToAPIResp(resp)
		if err != nil {
			r.Err = err
		} else {
			r.Err = errors.New(ar.Meta.Message)
		}
		r.Close()
		return r
	}

	// Start watching
	go func() {
		reader := bufio.NewReader(resp.Body)
		defer func() { c.http.Timeout = oldTimeout }()
		for {
			select {
			case <-r.DoneChan:
				resp.Body.Close()
				return
			default:
				line, _ := reader.ReadBytes('\n')
				sline := string(line)
				if sline == "" || sline == "\n" {
					continue
				}
				if strings.HasPrefix(sline, "data:") {
					sline = strings.TrimPrefix(sline, "data:")
					line = []byte(sline)
				}
				ste := &rbody.StreamedTaskEvent{}
				err := json.Unmarshal(line, ste)
				if err != nil {
					r.Err = err
					r.Close()
					return
				}
				switch ste.EventType {
				case rbody.TaskWatchTaskDisabled:
					r.EventChan <- ste
					r.Close()
				case rbody.TaskWatchTaskStopped, rbody.TaskWatchTaskEnded, rbody.TaskWatchTaskStarted, rbody.TaskWatchMetricEvent:
					r.EventChan <- ste
				}
			}
		}
	}()
	return r
}
933345
func (stack *TxStack) Consume(ev *StreamEvent) *TxExecution {
	switch {
	case ev.BeginTx != nil:
		stack.Push(initTx(ev.BeginTx))
	case ev.Envelope != nil:
		txe := stack.Peek()
		txe.Envelope = ev.Envelope
		txe.Receipt = txe.Envelope.Tx.GenerateReceipt()
	case ev.Event != nil:
		txe := stack.Peek()
		txe.Events = append(txe.Events, ev.Event)
	case ev.EndTx != nil:
		txe := stack.Pop()
		if len(*stack) == 0 {
			// This terminates the outermost transaction
			return txe
		}
		// If there is a parent tx on the stack add this tx as child
		parent := stack.Peek()
		parent.TxExecutions = append(parent.TxExecutions, txe)
	}
	return nil
}
626789
func (api *PublicFilterAPI) NewPendingTransactions(ctx context.Context) (*rpc.Subscription, error) {
	notifier, supported := rpc.NotifierFromContext(ctx)
	if !supported {
		return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported
	}

	rpcSub := notifier.CreateSubscription()

	go func() {
		txHashes := make(chan []common.Hash, 128)
		pendingTxSub := api.events.SubscribePendingTxs(txHashes)

		for {
			select {
			case hashes := <-txHashes:
				// To keep the original behaviour, send a single tx hash in one notification.
				// TODO(rjl493456442) Send a batch of tx hashes in one notification
				for _, h := range hashes {
					notifier.Notify(rpcSub.ID, h)
				}
			case <-rpcSub.Err():
				pendingTxSub.Unsubscribe()
				return
			case <-notifier.Closed():
				pendingTxSub.Unsubscribe()
				return
			}
		}
	}()

	return rpcSub, nil
}
380640
func (*kq) NewWatched(p string, fi os.FileInfo) (*watched, error) {
	fd, err := syscall.Open(p, syscall.O_NONBLOCK|syscall.O_RDONLY, 0)
	if err != nil {
		return nil, err
	}
	return &watched{
		trgWatched: trgWatched{p: p, fi: fi},
		fd:         fd,
	}, nil
}
66639
func (r *Request) Watch() (watch.Interface, error) {
	return r.WatchWithSpecificDecoders(
		func(body io.ReadCloser) streaming.Decoder {
			framer := r.serializers.Framer.NewFrameReader(body)
			return streaming.NewDecoder(framer, r.serializers.StreamingSerializer)
		},
		r.serializers.Decoder,
	)
}
1340911
func isSuccessSpend(spend *chainntnfs.SpendDetail, localCommit bool) bool {
	// Based on the spending input index and transaction, obtain the
	// witness that tells us what type of spend this is.
	spenderIndex := spend.SpenderInputIndex
	spendingInput := spend.SpendingTx.TxIn[spenderIndex]
	spendingWitness := spendingInput.Witness

	// If this is the remote commitment then the only possible spends for
	// outgoing HTLCs are:
	//
	//  RECVR: <0> <sender sig> <recvr sig> <preimage> (2nd level success spend)
	//  REVOK: <sig> <key>
	//  SENDR: <sig> 0
	//
	// In this case, if 5 witness elements are present (factoring the
	// witness script), and the 3rd element is the size of the pre-image,
	// then this is a remote spend. If not, then we swept it ourselves, or
	// revoked their output.
	if !localCommit {
		return len(spendingWitness) == expectedRemoteWitnessSuccessSize &&
			len(spendingWitness[remotePreimageIndex]) == lntypes.HashSize
	}

	// Otherwise, for our commitment, the only possible spends for an
	// outgoing HTLC are:
	//
	//  SENDR: <0> <sendr sig>  <recvr sig> <0> (2nd level timeout)
	//  RECVR: <recvr sig>  <preimage>
	//  REVOK: <revoke sig> <revoke key>
	//
	// So the only success case has the pre-image as the 2nd (index 1)
	// element in the witness.
	return len(spendingWitness[localPreimageIndex]) == lntypes.HashSize
}