// NewDirtyBlockCacheStandard constructs a new BlockCacheStandard
// instance.  The min and max buffer capacities define the possible
// range of how many bytes we'll try to sync in any one sync, and the
// start size defines the initial buffer size.
485743
func NewDirtyBlockCacheStandard(
	clock idutil.Clock, log logger.Logger, vlog *libkb.VDebugLog,
	minSyncBufCap int64, maxSyncBufCap int64,
	startSyncBufCap int64) *DirtyBlockCacheStandard {
	d := &DirtyBlockCacheStandard{
		clock:              clock,
		log:                log,
		vlog:               vlog,
		requestsChan:       make(chan dirtyReq, 1000),
		bytesDecreasedChan: make(chan struct{}, 1),
		shutdownChan:       make(chan struct{}),
		cache:              make(map[dirtyBlockID]Block),
		minSyncBufCap:      minSyncBufCap,
		maxSyncBufCap:      maxSyncBufCap,
		syncBufferCap:      startSyncBufCap,
		resetBufferCapTime: resetBufferCapTimeDefault,
	}
	d.reqWg.Add(1)
	go d.processPermission()
	return d
}
388287
func (ncs *nodeCacheStandard) UpdatePointer(
	oldRef data.BlockRef, newPtr data.BlockPointer) (updatedNode NodeID) {
	if oldRef == (data.BlockRef{}) && newPtr == (data.BlockPointer{}) {
		return nil
	}

	if !oldRef.IsValid() {
		panic(fmt.Sprintf("invalid oldRef %s with newPtr %s", oldRef, newPtr))
	}

	if !newPtr.IsValid() {
		panic(fmt.Sprintf("invalid newPtr %s with oldRef %s", newPtr, oldRef))
	}

	ncs.lock.Lock()
	defer ncs.lock.Unlock()
	entry, ok := ncs.nodes[oldRef]
	if !ok {
		return nil
	}

	// Cannot update the pointer for an unlinked node.
	if entry.core.cachedPath.IsValid() {
		return nil
	}

	entry.core.pathNode.BlockPointer = newPtr
	delete(ncs.nodes, oldRef)
	ncs.nodes[newPtr.Ref()] = entry
	return entry.core
}
904901
func (c *Client) CreateBlockStorage(name string, regionID, size int) (BlockStorage, error) {
	values := url.Values{
		"label":   {name},
		"DCID":    {fmt.Sprintf("%v", regionID)},
		"size_gb": {fmt.Sprintf("%v", size)},
	}

	var storage BlockStorage
	if err := c.post(`block/create`, values, &storage); err != nil {
		return BlockStorage{}, err
	}
	storage.RegionID = regionID
	storage.Name = name
	storage.SizeGB = size

	return storage, nil
}
1235859
func NewBlockData(height uint64) *BlockData {
	data := types.EventData{
		Tables:      make(map[string]types.EventDataTable),
		BlockHeight: height,
	}

	return &BlockData{
		Data: data,
	}
}
646039
func cacheSize(block uint64) uint64 {
	epoch := int(block / epochLength)
	if epoch < maxEpoch {
		return cacheSizes[epoch]
	}
	return calcCacheSize(epoch)
}
1123176
func (apic *APICache) GetCachedBlockByHeight(height int64) *CachedBlock {
	apic.mtx.Lock()
	defer apic.mtx.Unlock()
	hash, ok := apic.MainchainBlocks[height]
	if !ok {
		return nil
	}
	return apic.getCachedBlockByHash(hash)
}
1166277
func NewNRTCachingDirectory(delegate Directory, maxMergeSizeMB, maxCachedMB float64) (nrt *NRTCachingDirectory) {
	nrt = &NRTCachingDirectory{
		Directory:         delegate,
		Locker:            &sync.Mutex{},
		cache:             NewRAMDirectory(),
		maxMergeSizeBytes: int64(maxMergeSizeMB * 1024 * 1024),
		maxCachedBytes:    int64(maxCachedMB * 1024 * 1024),
		uncacheLock:       &sync.Mutex{},
	}
	// Subclass can override this to customize logic; return true if this
	// file should be written to the RAMDirectory.
	nrt.doCacheWrite = func(name string, context IOContext) bool {
		var bytes int64
		if context.MergeInfo != nil {
			bytes = context.MergeInfo.EstimatedMergeBytes
		} else if context.FlushInfo != nil {
			bytes = context.FlushInfo.EstimatedSegmentSize
		}
		if NRT_VERBOSE {
			log.Printf("CACHE check merge=%v flush=%v size=%v",
				context.MergeInfo, context.FlushInfo, bytes)
		}
		return name != "segments.gen" &&
			bytes <= nrt.maxMergeSizeBytes &&
			bytes+nrt.cache.RamBytesUsed() <= nrt.maxCachedBytes
	}
	return
}
886464
func (d *DirtyBlockCacheStandard) UpdateSyncingBytes(_ tlf.ID, size int64) {
	d.lock.Lock()
	defer d.lock.Unlock()
	d.syncBufBytes += size
	d.updateWaitBufLocked(-size)
	d.signalDecreasedBytes()
}
374097
func checkBlockSize(blockSize, minBlockSize, maxBlockSize int) int {
	assert2(blockSize >= minBlockSize && blockSize <= maxBlockSize,
		"blockSize must be >= %v and <= %v, got %v",
		minBlockSize, maxBlockSize, blockSize)
	assert2((blockSize&(blockSize-1)) == 0,
		"blockSIze must be a power of 2, got %v", blockSize)
	return TrailingZeros[blockSize]
}
101812
func (c *ConfigLocal) SetBlockCache(b data.BlockCache) {
	c.lock.Lock()
	defer c.lock.Unlock()
	c.bcache = b
}
74364
func (b *blockManager) BlockHeadersSynced() bool {
	b.syncPeerMutex.RLock()
	defer b.syncPeerMutex.RUnlock()

	// Figure out the latest block we know.
	header, height, err := b.server.BlockHeaders.ChainTip()
	if err != nil {
		return false
	}

	// There is no last checkpoint if checkpoints are disabled or there are
	// none for this current network.
	checkpoints := b.server.chainParams.Checkpoints
	if len(checkpoints) != 0 {
		// We aren't current if the newest block we know of isn't ahead
		// of all checkpoints.
		if checkpoints[len(checkpoints)-1].Height >= int32(height) {
			return false
		}
	}

	// If we have a syncPeer and are below the block we are syncing to, we
	// are not current.
	if b.syncPeer != nil && int32(height) < b.syncPeer.LastBlock() {
		return false
	}

	// If our time source (median times of all the connected peers) is at
	// least 24 hours ahead of our best known block, we aren't current.
	minus24Hours := b.server.timeSource.AdjustedTime().Add(-24 * time.Hour)
	if header.Timestamp.Before(minus24Hours) {
		return false
	}

	// If we have no sync peer, we can assume we're current for now.
	if b.syncPeer == nil {
		return true
	}

	// If we have a syncPeer and the peer reported a higher known block
	// height on connect than we know the peer already has, we're probably
	// not current. If the peer is lying to us, other code will disconnect
	// it and then we'll re-check and notice that we're actually current.
	return b.syncPeer.LastBlock() >= b.syncPeer.StartingHeight()
}
948236
func (d *DirtyBlockCacheStandard) IsAnyDirty(_ tlf.ID) bool {
	d.lock.RLock()
	defer d.lock.RUnlock()
	return len(d.cache) > 0 || d.syncBufBytes > 0 || d.waitBufBytes > 0
}
129246
func NewHashCache(maxSize uint) *HashCache {
	return &HashCache{
		sigHashes: make(map[chainhash.Hash]*TxSigHashes, maxSize),
	}
}
207323
func (l *MockLedger) NewBlock(channelID string, transactions ...*TxInfo) Block {
	l.Lock()
	defer l.Unlock()
	block := NewBlockWrapper(l.blockProducer.NewBlock(channelID, transactions...))
	l.Store(block)
	return block
}
137914
func (pq *BlockPriorityQueue) RescanMinMaxForUpdate(heightAdd, heightRemove uint32) {
	// If removing a block at either min or max height AND the added block does
	// not expand the range on the on relevant end, a rescan is necessary.
	if (int64(heightRemove) == pq.minHeight && heightAdd >= heightRemove) ||
		(int64(heightRemove) == pq.maxHeight && heightAdd <= heightRemove) {
		pq.RescanMinMax()
	}
	// only the added block height needs to be checked now, no rescan needed
	pq.updateMinMax(heightAdd)
}
1183711
func NewBlockConnected(header wire.BlockHeader, height uint32) *Connected {
	return &Connected{header: header, height: height}
}
922916
func NewBlockDisconnected(headerDisconnected wire.BlockHeader,
	heightDisconnected uint32, chainTip wire.BlockHeader) *Disconnected {

	return &Disconnected{
		headerDisconnected: headerDisconnected,
		heightDisconnected: heightDisconnected,
		chainTip:           chainTip,
	}
}