// RemarkBlock returns a remark block with the given title or an empty block if
// not found.
430986
func (p *Parsed) RemarkBlock(title string) RemarkBlock {
	for _, b := range p.Remarks {
		if b.Title == title {
			return b
		}
	}
	return RemarkBlock{}
}
654919
func WriteBlock(db ethdb.Writer, block *types.Block) {
	WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
	WriteHeader(db, block.Header())
}
923525
func (c *Client) writeBlock(data []byte) (int, error) {
	ss, err := c.streamSizes()
	if err != nil {
		return 0, err
	}
	// TODO: maybe make this buffer (and header and trailer buffers) part of Context struct
	var b [4]sspi.SecBuffer
	b[0].Set(sspi.SECBUFFER_STREAM_HEADER, make([]byte, ss.Header))
	b[1].Set(sspi.SECBUFFER_DATA, data)
	b[2].Set(sspi.SECBUFFER_STREAM_TRAILER, make([]byte, ss.Trailer))
	b[3].Set(sspi.SECBUFFER_EMPTY, nil)
	ret := sspi.EncryptMessage(c.ctx.Handle, 0, sspi.NewSecBufferDesc(b[:]), 0)
	switch ret {
	case sspi.SEC_E_OK:
	case sspi.SEC_E_CONTEXT_EXPIRED:
		// TODO: handle this
		panic("writeBlock: SEC_E_CONTEXT_EXPIRED")
	default:
		return 0, ret
	}
	n1, err := b[0].WriteAll(c.conn)
	if err != nil {
		return n1, err
	}
	n2, err := b[1].WriteAll(c.conn)
	if err != nil {
		return n1 + n2, err
	}
	n3, err := b[2].WriteAll(c.conn)
	return n1 + n2 + n3, err
}
953754
func notifyBlock(chain ChainSource, ro *rescanOptions,
	curHeader wire.BlockHeader, curStamp waddrmgr.BlockStamp,
	scanning bool) error {

	// Find relevant transactions based on watch list. If scanning is
	// false, we can safely assume this block has no relevant transactions.
	var relevantTxs []*btcutil.Tx
	if len(ro.watchList) != 0 && scanning {
		// If we have a non-empty watch list, then we need to see if it
		// matches the rescan's filters, so we get the basic filter
		// from the DB or network.
		matched, err := blockFilterMatches(chain, ro, &curStamp.Hash)
		if err != nil {
			return err
		}

		if matched {
			relevantTxs, err = extractBlockMatches(
				chain, ro, &curStamp,
			)
			if err != nil {
				return err
			}
		}
	}

	if ro.ntfn.OnFilteredBlockConnected != nil {
		ro.ntfn.OnFilteredBlockConnected(curStamp.Height, &curHeader,
			relevantTxs)
	}

	if ro.ntfn.OnBlockConnected != nil {
		ro.ntfn.OnBlockConnected(&curStamp.Hash,
			curStamp.Height, curHeader.Timestamp)
	}

	return nil
}
1221968
func (c *LeveledCompactor) populateBlock(blocks []BlockReader, meta *BlockMeta, indexw IndexWriter, chunkw ChunkWriter) (err error) {
	if len(blocks) == 0 {
		return errors.New("cannot populate block from no readers")
	}

	var (
		set         ChunkSeriesSet
		allSymbols  = make(map[string]struct{}, 1<<16)
		closers     = []io.Closer{}
		overlapping bool
	)
	defer func() {
		var merr tsdb_errors.MultiError
		merr.Add(err)
		merr.Add(closeAll(closers))
		err = merr.Err()
		c.metrics.populatingBlocks.Set(0)
	}()
	c.metrics.populatingBlocks.Set(1)

	globalMaxt := blocks[0].MaxTime()
	for i, b := range blocks {
		select {
		case <-c.ctx.Done():
			return c.ctx.Err()
		default:
		}

		if !overlapping {
			if i > 0 && b.MinTime() < globalMaxt {
				c.metrics.overlappingBlocks.Inc()
				overlapping = true
				level.Warn(c.logger).Log("msg", "found overlapping blocks during compaction", "ulid", meta.ULID)
			}
			if b.MaxTime() > globalMaxt {
				globalMaxt = b.MaxTime()
			}
		}

		indexr, err := b.Index()
		if err != nil {
			return errors.Wrapf(err, "open index reader for block %s", b)
		}
		closers = append(closers, indexr)

		chunkr, err := b.Chunks()
		if err != nil {
			return errors.Wrapf(err, "open chunk reader for block %s", b)
		}
		closers = append(closers, chunkr)

		tombsr, err := b.Tombstones()
		if err != nil {
			return errors.Wrapf(err, "open tombstone reader for block %s", b)
		}
		closers = append(closers, tombsr)

		symbols, err := indexr.Symbols()
		if err != nil {
			return errors.Wrap(err, "read symbols")
		}
		for s := range symbols {
			allSymbols[s] = struct{}{}
		}

		all, err := indexr.Postings(index.AllPostingsKey())
		if err != nil {
			return err
		}
		all = indexr.SortedPostings(all)

		s := newCompactionSeriesSet(indexr, chunkr, tombsr, all)

		if i == 0 {
			set = s
			continue
		}
		set, err = newCompactionMerger(set, s)
		if err != nil {
			return err
		}
	}

	// We fully rebuild the postings list index from merged series.
	var (
		postings = index.NewMemPostings()
		values   = map[string]stringset{}
		i        = uint64(0)
	)

	if err := indexw.AddSymbols(allSymbols); err != nil {
		return errors.Wrap(err, "add symbols")
	}

	for set.Next() {
		select {
		case <-c.ctx.Done():
			return c.ctx.Err()
		default:
		}

		lset, chks, dranges := set.At() // The chunks here are not fully deleted.
		if overlapping {
			// If blocks are overlapping, it is possible to have unsorted chunks.
			sort.Slice(chks, func(i, j int) bool {
				return chks[i].MinTime < chks[j].MinTime
			})
		}

		// Skip the series with all deleted chunks.
		if len(chks) == 0 {
			continue
		}

		for i, chk := range chks {
			if chk.MinTime < meta.MinTime || chk.MaxTime > meta.MaxTime {
				return errors.Errorf("found chunk with minTime: %d maxTime: %d outside of compacted minTime: %d maxTime: %d",
					chk.MinTime, chk.MaxTime, meta.MinTime, meta.MaxTime)
			}

			if len(dranges) > 0 {
				// Re-encode the chunk to not have deleted values.
				if !chk.OverlapsClosedInterval(dranges[0].Mint, dranges[len(dranges)-1].Maxt) {
					continue
				}
				newChunk := chunkenc.NewXORChunk()
				app, err := newChunk.Appender()
				if err != nil {
					return err
				}

				it := &deletedIterator{it: chk.Chunk.Iterator(), intervals: dranges}
				for it.Next() {
					ts, v := it.At()
					app.Append(ts, v)
				}

				chks[i].Chunk = newChunk
			}
		}

		mergedChks := chks
		if overlapping {
			mergedChks, err = chunks.MergeOverlappingChunks(chks)
			if err != nil {
				return errors.Wrap(err, "merge overlapping chunks")
			}
		}
		if err := chunkw.WriteChunks(mergedChks...); err != nil {
			return errors.Wrap(err, "write chunks")
		}

		if err := indexw.AddSeries(i, lset, mergedChks...); err != nil {
			return errors.Wrap(err, "add series")
		}

		meta.Stats.NumChunks += uint64(len(mergedChks))
		meta.Stats.NumSeries++
		for _, chk := range mergedChks {
			meta.Stats.NumSamples += uint64(chk.Chunk.NumSamples())
		}

		for _, chk := range mergedChks {
			if err := c.chunkPool.Put(chk.Chunk); err != nil {
				return errors.Wrap(err, "put chunk")
			}
		}

		for _, l := range lset {
			valset, ok := values[l.Name]
			if !ok {
				valset = stringset{}
				values[l.Name] = valset
			}
			valset.set(l.Value)
		}
		postings.Add(i, lset)

		i++
	}
	if set.Err() != nil {
		return errors.Wrap(set.Err(), "iterate compaction set")
	}

	s := make([]string, 0, 256)
	for n, v := range values {
		s = s[:0]

		for x := range v {
			s = append(s, x)
		}
		if err := indexw.WriteLabelIndex([]string{n}, s); err != nil {
			return errors.Wrap(err, "write label index")
		}
	}

	for _, l := range postings.SortedKeys() {
		if err := indexw.WritePostings(l.Name, l.Value, postings.Get(l.Name, l.Value)); err != nil {
			return errors.Wrap(err, "write postings")
		}
	}
	return nil
}
57522
func (db *DB) AppendBlockFeeRows(charts *cache.ChartData, rows *sql.Rows) error {
	defer rows.Close()
	blocks := charts.Blocks
	for rows.Next() {
		var feeMed float64
		var blockHeight uint64
		if err := rows.Scan(&blockHeight, &feeMed); err != nil {
			log.Errorf("Unable to scan for FeeInfoPerBlock fields: %v", err)
			return err
		}

		// Converting to atoms.
		blocks.Fees = append(blocks.Fees, uint64(feeMed*1e8))
	}

	return nil
}
726137
func (p *parser) parseBlock() *ast.BlockStatement {
	// openBlock
	result, blockParams := p.parseOpenBlock()

	// program
	program := p.parseProgram()
	program.BlockParams = blockParams
	result.Program = program

	// inverseChain?
	if p.isInverseChain() {
		result.Inverse = p.parseInverseChain()
	}

	// closeBlock
	p.parseCloseBlock(result)

	setBlockInverseStrip(result)

	return result
}
1259161
func (s *Statement) BlockFunc(f func(*Group)) *Statement {
	g := &Group{
		close:     "}",
		multi:     true,
		name:      "block",
		open:      "{",
		separator: "",
	}
	f(g)
	*s = append(*s, g)
	return s
}
938375
func (w *TermsWriter) writeBlocks(prefixLength, count int) (err error) {
	assert(count > 0)

	// Root block better writes all remaining pending entries:
	assert(prefixLength > 0 || count == len(w.pending))

	lastSuffixLeadLabel := -1

	// True if we saw at least one term in this block (we record if a
	// block only points to sub-blocks in the terms index so we can
	// avoid seeking to it when we are looking for a term):
	hasTerms := false
	hasSubBlocks := false

	end := len(w.pending)
	start := end - count
	nextBlockStart := start
	nextFloorLeadLabel := -1

	for i, ent := range w.pending[start:] {
		var suffixLeadLabel int
		if ent.isTerm() {
			term := ent.(*PendingTerm)
			if len(term.term) == prefixLength {
				// suffix is 0, ie prefix 'foo' and term is 'foo' so the
				// term has empty string suffix in this block
				assert(lastSuffixLeadLabel == -1)
				suffixLeadLabel = -1
			} else {
				suffixLeadLabel = int(term.term[prefixLength])
			}
		} else {
			block := ent.(*PendingBlock)
			assert(len(block.prefix) > prefixLength)
			suffixLeadLabel = int(block.prefix[prefixLength])
		}

		if suffixLeadLabel != lastSuffixLeadLabel {
			if itemsInBlock := i + count - nextBlockStart; itemsInBlock >= w.owner.minItemsInBlock &&
				end-nextBlockStart > w.owner.maxItemsInBlock {
				// The count is too large for one block, so we must break
				// it into "floor" blocks, where we record the leading
				// label of the suffix of the first term in each floor
				// block, so at search time we can jump to the right floor
				// block. We just use a naive greedy segmenter here: make a
				// new floor block as soon as we have at least
				// minItemsInBlock. This is not always best: it often
				// produces a too-small block as the final block:
				isFloor := itemsInBlock < count
				var block *PendingBlock
				if block, err = w.writeBlock(prefixLength, isFloor,
					nextFloorLeadLabel, nextBlockStart, i+count, hasTerms,
					hasSubBlocks); err != nil {
					return
				}
				w.newBlocks = append(w.newBlocks, block)

				hasTerms = false
				hasSubBlocks = false
				nextFloorLeadLabel = suffixLeadLabel
				nextBlockStart = i + count
			}

			lastSuffixLeadLabel = suffixLeadLabel
		}

		if ent.isTerm() {
			hasTerms = true
		} else {
			hasSubBlocks = true
		}
	}

	// Write last block, if any:
	if nextBlockStart < end {
		itemsInBlock := end - nextBlockStart
		isFloor := itemsInBlock < count
		var block *PendingBlock
		if block, err = w.writeBlock(prefixLength, isFloor,
			nextFloorLeadLabel, nextBlockStart, end, hasTerms,
			hasSubBlocks); err != nil {
			return
		}
		w.newBlocks = append(w.newBlocks, block)
	}

	assert(len(w.newBlocks) > 0)

	firstBlock := w.newBlocks[0]

	assert(firstBlock.isFloor || len(w.newBlocks) == 1)

	if err = firstBlock.compileIndex(w.newBlocks,
		w.owner.scratchBytes, w.owner.scratchIntsRef); err != nil {
		return
	}

	// Remove slice from the top of the pending stack, that we just wrote:
	w.pending = w.pending[:start]

	// Append new block
	w.pending = append(w.pending, firstBlock)

	w.newBlocks = nil
	return nil
}
1258597
func parseBlock(t *Tree, start Pos) (Node, error) {
	blockName, err := t.expect(tokenName)
	if err != nil {
		return nil, err
	}
	_, err = t.expect(tokenTagClose)
	if err != nil {
		return nil, err
	}
	body, err := t.parseUntilEndTag("block", start)
	if err != nil {
		return nil, err
	}
	nod := NewBlockNode(blockName.value, body, start)
	nod.Origin = t.Name
	t.setBlock(blockName.value, nod)
	return nod, nil
}
1164457
func (bc *BlockChain) CurrentBlock() *types.Block {
	return bc.currentBlock.Load().(*types.Block)
}
434435
func (list *ReviewBlockerList) AddReviewBlocker(
	fixed bool,
	commentURL string,
	commitSHA string,
	blockerSummary string,
) bool {

	for _, item := range list.items {
		if item.CommentURL == commentURL {
			return false
		}
	}

	list.items = append(list.items, &ReviewBlockerItem{
		Fixed:          fixed,
		CommentURL:     commentURL,
		CommitSHA:      commitSHA,
		BlockerNumber:  len(list.items) + 1,
		BlockerSummary: blockerSummary,
	})
	return true
}
648426
func (db *StakeDatabase) DBTipBlockHeader() (*wire.BlockHeader, error) {
	_, hash, err := db.DBState()
	if err != nil {
		return nil, err
	}

	return db.NodeClient.GetBlockHeader(hash)
}
1044315
func NewBlock(name string, required bool, nested *Spec) *Spec {
	return BlockSpec(&Block{
		Name:     name,
		Required: required,
		Nested:   nested,
	})
}
1069138
func (p BlockPointer) Ref() BlockRef {
	return BlockRef{
		ID:       p.ID,
		RefNonce: p.RefNonce,
	}
}
975046
func (iapi *InsightApi) DcrToInsightBlock(inBlocks []*dcrjson.GetBlockVerboseResult) ([]*apitypes.InsightBlockResult, error) {
	RewardAtBlock := func(blocknum int64, voters uint16) float64 {
		subsidyCache := blockchain.NewSubsidyCache(0, iapi.params)
		work := blockchain.CalcBlockWorkSubsidy(subsidyCache, blocknum, voters, iapi.params)
		stake := blockchain.CalcStakeVoteSubsidy(subsidyCache, blocknum, iapi.params) * int64(voters)
		tax := blockchain.CalcBlockTaxSubsidy(subsidyCache, blocknum, voters, iapi.params)
		return dcrutil.Amount(work + stake + tax).ToCoin()
	}

	outBlocks := make([]*apitypes.InsightBlockResult, 0, len(inBlocks))
	for _, inBlock := range inBlocks {
		outBlock := apitypes.InsightBlockResult{
			Hash:          inBlock.Hash,
			Confirmations: inBlock.Confirmations,
			Size:          inBlock.Size,
			Height:        inBlock.Height,
			Version:       inBlock.Version,
			MerkleRoot:    inBlock.MerkleRoot,
			Tx:            append(inBlock.Tx, inBlock.STx...),
			Time:          inBlock.Time,
			Nonce:         inBlock.Nonce,
			Bits:          inBlock.Bits,
			Difficulty:    inBlock.Difficulty,
			PreviousHash:  inBlock.PreviousHash,
			NextHash:      inBlock.NextHash,
			Reward:        RewardAtBlock(inBlock.Height, inBlock.Voters),
			IsMainChain:   inBlock.Height > 0,
		}
		outBlocks = append(outBlocks, &outBlock)
	}
	return outBlocks, nil
}
643855
func (db *WiredDB) GetBestBlockSummary() *apitypes.BlockDataBasic {
	// Attempt to retrieve height of best block in DB.
	dbBlkHeight, err := db.GetBlockSummaryHeight()
	if err != nil {
		log.Errorf("GetBlockSummaryHeight failed: %v", err)
		return nil
	}

	// Empty table is not an error.
	if dbBlkHeight == -1 {
		return nil
	}

	// Retrieve the block data.
	blockSummary, err := db.RetrieveBlockSummary(dbBlkHeight)
	if err != nil {
		log.Errorf("Unable to retrieve block %d summary: %v", dbBlkHeight, err)
		return nil
	}

	return blockSummary
}