// fetchUtxos loads the unspent transaction outputs for the provided set of
// outputs into the view from the database as needed unless they already exist
// in the view in which case they are ignored.
497129
func (view *UtxoViewpoint) fetchUtxos(db database.DB, outpoints map[wire.OutPoint]struct{}) error {
	// Nothing to do if there are no requested outputs.
	if len(outpoints) == 0 {
		return nil
	}

	// Filter entries that are already in the view.
	neededSet := make(map[wire.OutPoint]struct{})
	for outpoint := range outpoints {
		// Already loaded into the current view.
		if _, ok := view.entries[outpoint]; ok {
			continue
		}

		neededSet[outpoint] = struct{}{}
	}

	// Request the input utxos from the database.
	return view.fetchUtxosMain(db, neededSet)
}
64864
func fetchRawTxRecordPkScript(k, v []byte, index uint32) ([]byte, error) {
	var rec TxRecord
	copy(rec.Hash[:], k) // Silly but need an array
	err := readRawTxRecord(&rec.Hash, v, &rec)
	if err != nil {
		return nil, err
	}
	if int(index) >= len(rec.MsgTx.TxOut) {
		str := "missing transaction output for credit index"
		return nil, storeError(ErrData, str, nil)
	}
	return rec.MsgTx.TxOut[index].PkScript, nil
}
293417
func (c *connection) Fetch(req *proto.FetchReq) (*proto.FetchResp, error) {
	b, err := c.sendRequest(req)
	if err != nil {
		return nil, err
	}

	resp, err := proto.ReadVersionedFetchResp(bytes.NewReader(b), req.GetVersion())
	if err != nil {
		return nil, err
	}

	// Compressed messages are returned in full batches for efficiency
	// (the broker doesn't need to decompress).
	// This means that it's possible to get some leading messages
	// with a smaller offset than requested. Trim those.
	for ti := range resp.Topics {
		topic := &resp.Topics[ti]
		reqTopic := &req.Topics[ti]
		for pi := range topic.Partitions {
			partition := &topic.Partitions[pi]
			requestedOffset := reqTopic.Partitions[pi].FetchOffset
			i := 0
			if partition.MessageVersion < 2 {
				for _, msg := range partition.Messages {
					if msg.Offset >= requestedOffset {
						break
					}
					i++
				}
				partition.Messages = partition.Messages[i:]
			} else {
				firstOffset := partition.RecordBatch.FirstOffset
				for _, rec := range partition.RecordBatch.Records {
					if firstOffset+rec.OffsetDelta >= requestedOffset {
						break
					}
					i++
				}
				partition.RecordBatch.Records = partition.RecordBatch.Records[i:]
			}
		}
	}
	return resp, nil
}
49358
func (b *boltArbitratorLog) FetchUnresolvedContracts() ([]ContractResolver, error) {
	resKit := ResolverKit{
		ChannelArbitratorConfig: b.cfg,
		Checkpoint:              b.checkpointContract,
	}
	var contracts []ContractResolver
	err := b.db.View(func(tx *bbolt.Tx) error {
		contractBucket, err := fetchContractReadBucket(tx, b.scopeKey[:])
		if err != nil {
			return err
		}

		return contractBucket.ForEach(func(resKey, resBytes []byte) error {
			if len(resKey) != resolverIDLen {
				return nil
			}

			var res ContractResolver

			// We'll snip off the first byte of the raw resolver
			// bytes in order to extract what type of resolver
			// we're about to encode.
			resType := resBytes[0]

			// Then we'll create a reader using the remaining
			// bytes.
			resReader := bytes.NewReader(resBytes[1:])

			switch resType {
			case resolverTimeout:
				timeoutRes := &htlcTimeoutResolver{}
				if err := timeoutRes.Decode(resReader); err != nil {
					return err
				}
				timeoutRes.AttachResolverKit(resKit)

				res = timeoutRes

			case resolverSuccess:
				successRes := &htlcSuccessResolver{}
				if err := successRes.Decode(resReader); err != nil {
					return err
				}

				res = successRes

			case resolverOutgoingContest:
				outContestRes := &htlcOutgoingContestResolver{
					htlcTimeoutResolver: htlcTimeoutResolver{},
				}
				if err := outContestRes.Decode(resReader); err != nil {
					return err
				}

				res = outContestRes

			case resolverIncomingContest:
				inContestRes := &htlcIncomingContestResolver{
					htlcSuccessResolver: htlcSuccessResolver{},
				}
				if err := inContestRes.Decode(resReader); err != nil {
					return err
				}

				res = inContestRes

			case resolverUnilateralSweep:
				sweepRes := &commitSweepResolver{}
				if err := sweepRes.Decode(resReader); err != nil {
					return err
				}

				res = sweepRes

			default:
				return fmt.Errorf("unknown resolver type: %v", resType)
			}

			resKit.Quit = make(chan struct{})
			res.AttachResolverKit(resKit)
			contracts = append(contracts, res)
			return nil
		})
	})
	if err != nil && err != errScopeBucketNoExist && err != errNoContracts {
		return nil, err
	}

	return contracts, nil
}
1358018
func (c *conn) ExecTx(fn func(tx *trans) error) error {
	if c.flavor.executeTx != nil {
		return c.flavor.executeTx(c.db, func(sqlTx *sql.Tx) error {
			return fn(&trans{sqlTx, c})
		})
	}

	sqlTx, err := c.db.Begin()
	if err != nil {
		return err
	}
	if err := fn(&trans{sqlTx, c}); err != nil {
		sqlTx.Rollback()
		return err
	}
	return sqlTx.Commit()
}
207695
func fetchNStatusResults(col mongo.Collection, key string,
	filter status.StatusHistoryFilter) ([]historicalStatusDoc, error) {
	var (
		docs  []historicalStatusDoc
		query mongo.Query
	)
	baseQuery := bson.M{"globalkey": key}
	if filter.Delta != nil {
		delta := *filter.Delta
		// TODO(perrito666) 2016-10-06 lp:1558657
		updated := time.Now().Add(-delta)
		baseQuery["updated"] = bson.M{"$gt": updated.UnixNano()}
	}
	if filter.FromDate != nil {
		baseQuery["updated"] = bson.M{"$gt": filter.FromDate.UnixNano()}
	}
	excludes := []string{}
	excludes = append(excludes, filter.Exclude.Values()...)
	if len(excludes) > 0 {
		baseQuery["statusinfo"] = bson.M{"$nin": excludes}
	}

	query = col.Find(baseQuery).Sort("-updated")
	if filter.Size > 0 {
		query = query.Limit(filter.Size)
	}
	err := query.All(&docs)

	if err == mgo.ErrNotFound {
		return []historicalStatusDoc{}, errors.NotFoundf("status history")
	} else if err != nil {
		return []historicalStatusDoc{}, errors.Annotatef(err, "cannot get status history")
	}
	return docs, nil

}
390741
func (d dynamicSystemView) fetchTTLs() (def, max time.Duration) {
	def = d.core.defaultLeaseTTL
	max = d.core.maxLeaseTTL

	if d.mountEntry != nil {
		if d.mountEntry.Config.DefaultLeaseTTL != 0 {
			def = d.mountEntry.Config.DefaultLeaseTTL
		}
		if d.mountEntry.Config.MaxLeaseTTL != 0 {
			max = d.mountEntry.Config.MaxLeaseTTL
		}
	}

	return
}
396008
func (c *BitcoindClient) GetTxOut(txHash *chainhash.Hash, index uint32,
	mempool bool) (*btcjson.GetTxOutResult, error) {

	return c.chainConn.client.GetTxOut(txHash, index, mempool)
}
1243257
func (s *SearchSource) FetchSource(fetchSource bool) *SearchSource {
	if s.fetchSourceContext == nil {
		s.fetchSourceContext = NewFetchSourceContext(fetchSource)
	} else {
		s.fetchSourceContext.SetFetchSource(fetchSource)
	}
	return s
}
422787
func (f *Fetcher) FetchFromTFTP(u url.URL, dest *os.File, opts FetchOptions) error {
	if !strings.ContainsRune(u.Host, ':') {
		u.Host = u.Host + ":69"
	}
	c, err := tftp.NewClient(u.Host)
	if err != nil {
		return err
	}
	wt, err := c.Receive(u.Path, "octet")
	if err != nil {
		return err
	}
	// The TFTP library takes an io.Writer to send data in to, but to decompress
	// the stream the gzip library wraps an io.Reader, so let's create a pipe to
	// connect these two things
	pReader, pWriter := io.Pipe()
	doneChan := make(chan error, 2)

	checkForDoneChanErr := func(err error) error {
		// If an error is encountered while decompressing or copying data out of
		// the pipe, there's probably an error from writing into the pipe that
		// will better describe what went wrong. This function does a
		// non-blocking read of doneChan, overriding the returned error val if
		// there's anything in doneChan.
		select {
		case writeErr := <-doneChan:
			if writeErr != nil {
				return writeErr
			}
			return err
		default:
			return err
		}
	}

	// A goroutine is used to handle writing the fetched data into the pipe
	// while also copying it out of the pipe concurrently
	go func() {
		_, err := wt.WriteTo(pWriter)
		doneChan <- err
		err = pWriter.Close()
		doneChan <- err
	}()
	err = f.decompressCopyHashAndVerify(dest, pReader, opts)
	if err != nil {
		return checkForDoneChanErr(err)
	}
	// receive the error from wt.WriteTo()
	err = <-doneChan
	if err != nil {
		return err
	}
	// receive the error from pWriter.Close()
	err = <-doneChan
	if err != nil {
		return err
	}
	return nil
}
518511
func (c *appContext) getTransactionOutputs(w http.ResponseWriter, r *http.Request) {
	txid, err := m.GetTxIDCtx(r)
	if err != nil {
		http.Error(w, http.StatusText(422), 422)
		return
	}

	allTxOut := c.BlockData.GetAllTxOut(txid)
	// allTxOut may be empty, but not a nil slice
	if allTxOut == nil {
		apiLog.Errorf("Unable to get all TxOut for transaction %s", txid)
		http.Error(w, http.StatusText(422), 422)
		return
	}

	writeJSON(w, allTxOut, c.getIndentQuery(r))
}
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
}
412296
func (m *nativeGitClient) Fetch() error {
	log.Debugf("Fetching repo %s at %s", m.repoURL, m.root)
	// Two techniques are used for fetching the remote depending if the remote is SSH vs. HTTPS
	// If http, we fork/exec the git CLI since the go-git client does not properly support git
	// providers such as AWS CodeCommit and Azure DevOps.
	if _, ok := m.auth.(*ssh2.PublicKeys); ok {
		return m.goGitFetch()
	}
	_, err := m.runCredentialedCmd("git", "fetch", "origin", "--tags", "--force")
	return err
}
266154
func (tx *transaction) fetchKey(key []byte) []byte {
	// When the transaction is writable, check the pending transaction
	// state first.
	if tx.writable {
		if tx.pendingRemove.Has(key) {
			return nil
		}
		if value := tx.pendingKeys.Get(key); value != nil {
			return value
		}
	}

	// Consult the database cache and underlying database.
	return tx.snapshot.Get(key)
}
995367
func (t *OSesTable) fetch(c context.Context) error {
	db := database.Get(c)
	rows, err := db.QueryContext(c, `
		SELECT id, name, description
		FROM oses
	`)
	if err != nil {
		return errors.Annotate(err, "failed to select operating systems").Err()
	}
	defer rows.Close()
	for rows.Next() {
		os := &OS{}
		if err := rows.Scan(&os.Id, &os.Name, &os.Description); err != nil {
			return errors.Annotate(err, "failed to scan operating system").Err()
		}
		t.current = append(t.current, os)
	}
	return nil
}
584768
func (c *ownAccountLookupCacheImpl) fetch(mctx libkb.MetaContext) {
	go func() {
		mc := mctx.BackgroundWithLogTags()
		defer c.Unlock()
		bundle, err := remote.FetchSecretlessBundle(mc)
		c.loadErr = err
		if err != nil {
			return
		}
		for _, account := range bundle.Accounts {
			name := account.Name
			c.accounts[account.AccountID] = &name
		}
	}()
}
909543
func FetchRelease(db *sql.DB, bundle, version string) (*Release, error) {
	rel, err := NewRelease(bundle, version)
	if err != nil {
		return nil, err
	}

	tx, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer tx.Rollback() // nop if commit is called.

	err = rel.Select(tx)
	if err != nil {
		return nil, err
	}

	err = tx.Commit()
	if err != nil {
		return nil, err
	}

	return rel, nil
}