// checkCaches copies a block into `block` if it's in one of our caches.
967517
func (brq *blockRetrievalQueue) checkCaches(ctx context.Context,
	kmd libkey.KeyMetadata, ptr data.BlockPointer, block data.Block,
	action BlockRequestAction) (PrefetchStatus, error) {
	dbc := brq.config.DiskBlockCache()
	preferredCacheType := action.CacheType()

	cachedBlock, err := brq.config.BlockCache().Get(ptr)
	if err == nil {
		if dbc == nil {
			block.Set(cachedBlock)
			return brq.getPrefetchStatus(ptr.ID)
		}

		prefetchStatus, err := dbc.GetPrefetchStatus(
			ctx, kmd.TlfID(), ptr.ID, preferredCacheType)
		if err == nil {
			block.Set(cachedBlock)
			return prefetchStatus, nil
		}
		// If the prefetch status wasn't in the preferred cache, do a
		// full `Get()` below in an attempt to move the full block
		// into the preferred cache.
	} else if dbc == nil || action.DelayCacheCheck() {
		return NoPrefetch, err
	}

	blockBuf, serverHalf, prefetchStatus, err := dbc.Get(
		ctx, kmd.TlfID(), ptr.ID, preferredCacheType)
	if err != nil {
		return NoPrefetch, err
	}
	if len(blockBuf) == 0 {
		return NoPrefetch, data.NoSuchBlockError{ID: ptr.ID}
	}

	// Assemble the block from the encrypted block buffer.
	err = brq.config.blockGetter().assembleBlock(ctx, kmd, ptr, block, blockBuf,
		serverHalf)
	if err == nil {
		// Cache the block in memory.  TODO: plumb through whether
		// journaling is enabled for this TLF, to set the right cache
		// behavior.
		brq.config.BlockCache().Put(
			ptr, kmd.TlfID(), block, data.TransientEntry, data.DoCacheHash)
	}
	return prefetchStatus, err
}
217402
func (e *edge) probeCache(d *dep, depKeys []CacheKeyWithSelector) bool {
	if len(depKeys) == 0 {
		return false
	}
	if e.op.IgnoreCache() {
		return false
	}
	keys, err := e.op.Cache().Query(depKeys, d.index, e.cacheMap.Digest, e.edge.Index)
	if err != nil {
		e.err = errors.Wrap(err, "error on cache query")
	}
	found := false
	for _, k := range keys {
		if _, ok := d.keyMap[k.ID]; !ok {
			d.keyMap[k.ID] = k
			found = true
		}
	}
	return found
}
151411
func (b *BlockChain) initThresholdCaches() error {
	// Initialize the warning and deployment caches by calculating the
	// threshold state for each of them.  This will ensure the caches are
	// populated and any states that needed to be recalculated due to
	// definition changes is done now.
	prevNode := b.bestChain.Tip().parent
	for bit := uint32(0); bit < vbNumBits; bit++ {
		checker := bitConditionChecker{bit: bit, chain: b}
		cache := &b.warningCaches[bit]
		_, err := b.thresholdState(prevNode, checker, cache)
		if err != nil {
			return err
		}
	}
	for id := 0; id < len(b.chainParams.Deployments); id++ {
		deployment := &b.chainParams.Deployments[id]
		cache := &b.deploymentCaches[id]
		checker := deploymentChecker{deployment: deployment, chain: b}
		_, err := b.thresholdState(prevNode, checker, cache)
		if err != nil {
			return err
		}
	}

	// No warnings about unknown rules or versions until the chain is
	// current.
	if b.isCurrent() {
		// Warn if a high enough percentage of the last blocks have
		// unexpected versions.
		bestNode := b.bestChain.Tip()
		if err := b.warnUnknownVersions(bestNode); err != nil {
			return err
		}

		// Warn if any unknown new rules are either about to activate or
		// have already been activated.
		if err := b.warnUnknownRuleActivations(bestNode); err != nil {
			return err
		}
	}

	return nil
}
15966
func (s *sigHead) cache() (err error) {
	if !s.clean {
		s.Protected, err = s.protected.Base64()
		if err != nil {
			return err
		}
		s.Unprotected, err = s.unprotected.Base64()
		if err != nil {
			return err
		}
	}
	s.clean = true
	return nil
}
228009
func VerifyBlockHash(indexInBuffer int, blockBuff []*common.Block) error {
	if len(blockBuff) <= indexInBuffer {
		return errors.Errorf("index %d out of bounds (total %d blocks)", indexInBuffer, len(blockBuff))
	}
	block := blockBuff[indexInBuffer]
	if block.Header == nil {
		return errors.New("missing block header")
	}
	seq := block.Header.Number
	dataHash := block.Data.Hash()
	// Verify data hash matches the hash in the header
	if !bytes.Equal(dataHash, block.Header.DataHash) {
		computedHash := hex.EncodeToString(dataHash)
		claimedHash := hex.EncodeToString(block.Header.DataHash)
		return errors.Errorf("computed hash of block (%d) (%s) doesn't match claimed hash (%s)",
			seq, computedHash, claimedHash)
	}
	// We have a previous block in the buffer, ensure current block's previous hash matches the previous one.
	if indexInBuffer > 0 {
		prevBlock := blockBuff[indexInBuffer-1]
		currSeq := block.Header.Number
		if prevBlock.Header == nil {
			return errors.New("previous block header is nil")
		}
		prevSeq := prevBlock.Header.Number
		if prevSeq+1 != currSeq {
			return errors.Errorf("sequences %d and %d were received consecutively", prevSeq, currSeq)
		}
		if !bytes.Equal(block.Header.PreviousHash, prevBlock.Header.Hash()) {
			claimedPrevHash := hex.EncodeToString(block.Header.PreviousHash)
			actualPrevHash := hex.EncodeToString(prevBlock.Header.Hash())
			return errors.Errorf("block [%d]'s hash (%s) mismatches %d's prev block hash (%s)",
				prevSeq, actualPrevHash, currSeq, claimedPrevHash)
		}
	}
	return nil
}
195532
func (c *BundlingChecker) check(items []checkerItem) {
	c.waitc <- struct{}{}
	c.wg.Add(1)
	go func() {
		c.doCheck(items)
		c.wg.Done()
		<-c.waitc
	}()

}
1181933
func (l *State) CheckStates() map[types.CheckID]*CheckState {
	l.RLock()
	defer l.RUnlock()

	m := make(map[types.CheckID]*CheckState)
	for id, c := range l.checks {
		if c.Deleted {
			continue
		}
		m[id] = c.Clone()
	}
	return m
}
1004675
func CheckPackages(c context.Context, names []string, includeHidden bool) ([]string, error) {
	if len(names) == 0 {
		return nil, nil
	}

	pkgs := make([]*Package, len(names))
	for i, n := range names {
		pkgs[i] = &Package{Name: n}
	}

	if err := datastore.Get(c, pkgs); err != nil {
		merr, ok := err.(errors.MultiError)
		if !ok {
			return nil, transient.Tag.Apply(err)
		}
		existing := pkgs[:0]
		for i, pkg := range pkgs {
			switch err := merr[i]; {
			case err == nil:
				existing = append(existing, pkg)
			case err != datastore.ErrNoSuchEntity:
				return nil, errors.Annotate(err, "failed to fetch %q", pkg.Name).Tag(transient.Tag).Err()
			}
		}
		pkgs = existing
	}

	out := make([]string, 0, len(pkgs))
	for _, p := range pkgs {
		if !p.Hidden || includeHidden {
			out = append(out, p.Name)
		}
	}
	return out, nil
}
295020
func checkCost(hash []byte) error {
	actual, err := bcrypt.Cost(hash)
	if err != nil {
		return fmt.Errorf("parsing bcrypt hash: %v", err)
	}
	if actual < bcrypt.DefaultCost {
		return fmt.Errorf("given hash cost = %d does not meet minimum cost requirement = %d", actual, bcrypt.DefaultCost)
	}
	if actual > upBoundCost {
		return fmt.Errorf("given hash cost = %d is above upper bound cost = %d, recommended cost = %d", actual, upBoundCost, recCost)
	}
	return nil
}
263184
func (g *BlockGate) CachedBlock(hash chainhash.Hash) (*dcrutil.Block, error) {
	g.mtx.RLock()
	defer g.mtx.RUnlock()
	block, ok := g.blockWithHash[hash]
	if !ok {
		return nil, fmt.Errorf("block %d not found", hash)
	}
	return block, nil
}
1079377
func (c *TwoQueueCache) Contains(key interface{}) bool {
	c.lock.RLock()
	defer c.lock.RUnlock()
	return c.frequent.Contains(key) || c.recent.Contains(key)
}
303577
func validateCacheFormats(ctx context.Context, formats []*formatCacheV1) error {
	count := 0
	for _, format := range formats {
		if format == nil {
			count++
		}
	}
	if count == len(formats) {
		return errors.New("Cache format files missing on all drives")
	}
	if _, err := checkFormatCacheValues(formats); err != nil {
		logger.LogIf(ctx, err)
		return err
	}
	if err := checkCacheDisksSliceConsistency(formats); err != nil {
		logger.LogIf(ctx, err)
		return err
	}
	err := checkCacheDiskConsistency(formats)
	logger.LogIf(ctx, err)
	return err
}
1309836
func (h *Holder) monitorCacheFlush() {
	ticker := time.NewTicker(h.cacheFlushInterval)
	defer ticker.Stop()

	for {
		select {
		case <-h.closing:
			return
		case <-ticker.C:
			h.flushCaches()
		}
	}
}
1111845
func NewCaches(p *helpers.PathSpec) (Caches, error) {
	dcfg, err := decodeConfig(p)
	if err != nil {
		return nil, err
	}

	fs := p.Fs.Source

	m := make(Caches)
	for k, v := range dcfg {
		var cfs afero.Fs

		if v.isResourceDir {
			cfs = p.BaseFs.Resources.Fs
		} else {
			cfs = fs
		}

		var baseDir string
		if !strings.HasPrefix(v.Dir, "_gen") {
			// We do cache eviction (file removes) and since the user can set
			// his/hers own cache directory, we really want to make sure
			// we do not delete any files that do not belong to this cache.
			// We do add the cache name as the root, but this is an extra safe
			// guard. We skip the files inside /resources/_gen/ because
			// that would be breaking.
			baseDir = filepath.Join(v.Dir, filecacheRootDirname, k)
		} else {
			baseDir = filepath.Join(v.Dir, k)
		}
		if err = cfs.MkdirAll(baseDir, 0777); err != nil && !os.IsExist(err) {
			return nil, err
		}

		bfs := afero.NewBasePathFs(cfs, baseDir)

		m[k] = NewCache(bfs, v.MaxAge)
	}

	return m, nil
}
85929
func (c *ARCCache) Contains(key interface{}) bool {
	c.lock.RLock()
	defer c.lock.RUnlock()
	return c.t1.Contains(key) || c.t2.Contains(key)
}
15836
func (c *ResourceConfig) CheckSet(keys []string) []error {
	var errs []error

	for _, k := range keys {
		if !c.IsSet(k) {
			errs = append(errs, fmt.Errorf("%s must be set", k))
		}
	}

	return errs
}
92511
func (r *Rule) CheckScopes(scopes []string) error {
	var notAllowed []string
	for _, scope := range scopes {
		if !r.AllowedScopes.Has(scope) {
			notAllowed = append(notAllowed, scope)
		}
	}
	if len(notAllowed) != 0 {
		return fmt.Errorf("following scopes are not allowed by the rule %q - %q", r.Rule.Name, notAllowed)
	}
	return nil
}