// blockTemplateResult returns the current block template associated with the
// state as a btcjson.GetBlockTemplateResult that is ready to be encoded to JSON
// and returned to the caller.
//
// This function MUST be called with the state locked.
495599
func (state *gbtWorkState) blockTemplateResult(useCoinbaseValue bool, submitOld *bool) (*btcjson.GetBlockTemplateResult, error) {
	// Ensure the timestamps are still in valid range for the template.
	// This should really only ever happen if the local clock is changed
	// after the template is generated, but it's important to avoid serving
	// invalid block templates.
	template := state.template
	msgBlock := template.Block
	header := &msgBlock.Header
	adjustedTime := state.timeSource.AdjustedTime()
	maxTime := adjustedTime.Add(time.Second * blockchain.MaxTimeOffsetSeconds)
	if header.Timestamp.After(maxTime) {
		return nil, &btcjson.RPCError{
			Code: btcjson.ErrRPCOutOfRange,
			Message: fmt.Sprintf("The template time is after the "+
				"maximum allowed time for a block - template "+
				"time %v, maximum time %v", adjustedTime,
				maxTime),
		}
	}

	// Convert each transaction in the block template to a template result
	// transaction.  The result does not include the coinbase, so notice
	// the adjustments to the various lengths and indices.
	numTx := len(msgBlock.Transactions)
	transactions := make([]btcjson.GetBlockTemplateResultTx, 0, numTx-1)
	txIndex := make(map[chainhash.Hash]int64, numTx)
	for i, tx := range msgBlock.Transactions {
		txHash := tx.TxHash()
		txIndex[txHash] = int64(i)

		// Skip the coinbase transaction.
		if i == 0 {
			continue
		}

		// Create an array of 1-based indices to transactions that come
		// before this one in the transactions list which this one
		// depends on.  This is necessary since the created block must
		// ensure proper ordering of the dependencies.  A map is used
		// before creating the final array to prevent duplicate entries
		// when multiple inputs reference the same transaction.
		dependsMap := make(map[int64]struct{})
		for _, txIn := range tx.TxIn {
			if idx, ok := txIndex[txIn.PreviousOutPoint.Hash]; ok {
				dependsMap[idx] = struct{}{}
			}
		}
		depends := make([]int64, 0, len(dependsMap))
		for idx := range dependsMap {
			depends = append(depends, idx)
		}

		// Serialize the transaction for later conversion to hex.
		txBuf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize()))
		if err := tx.Serialize(txBuf); err != nil {
			context := "Failed to serialize transaction"
			return nil, internalRPCError(err.Error(), context)
		}

		bTx := btcutil.NewTx(tx)
		resultTx := btcjson.GetBlockTemplateResultTx{
			Data:    hex.EncodeToString(txBuf.Bytes()),
			Hash:    txHash.String(),
			Depends: depends,
			Fee:     template.Fees[i],
			SigOps:  template.SigOpCosts[i],
			Weight:  blockchain.GetTransactionWeight(bTx),
		}
		transactions = append(transactions, resultTx)
	}

	// Generate the block template reply.  Note that following mutations are
	// implied by the included or omission of fields:
	//  Including MinTime -> time/decrement
	//  Omitting CoinbaseTxn -> coinbase, generation
	targetDifficulty := fmt.Sprintf("%064x", blockchain.CompactToBig(header.Bits))
	templateID := encodeTemplateID(state.prevHash, state.lastGenerated)
	reply := btcjson.GetBlockTemplateResult{
		Bits:         strconv.FormatInt(int64(header.Bits), 16),
		CurTime:      header.Timestamp.Unix(),
		Height:       int64(template.Height),
		PreviousHash: header.PrevBlock.String(),
		WeightLimit:  blockchain.MaxBlockWeight,
		SigOpLimit:   blockchain.MaxBlockSigOpsCost,
		SizeLimit:    wire.MaxBlockPayload,
		Transactions: transactions,
		Version:      header.Version,
		LongPollID:   templateID,
		SubmitOld:    submitOld,
		Target:       targetDifficulty,
		MinTime:      state.minTimestamp.Unix(),
		MaxTime:      maxTime.Unix(),
		Mutable:      gbtMutableFields,
		NonceRange:   gbtNonceRange,
		Capabilities: gbtCapabilities,
	}
	// If the generated block template includes transactions with witness
	// data, then include the witness commitment in the GBT result.
	if template.WitnessCommitment != nil {
		reply.DefaultWitnessCommitment = hex.EncodeToString(template.WitnessCommitment)
	}

	if useCoinbaseValue {
		reply.CoinbaseAux = gbtCoinbaseAux
		reply.CoinbaseValue = &msgBlock.Transactions[0].TxOut[0].Value
	} else {
		// Ensure the template has a valid payment address associated
		// with it when a full coinbase is requested.
		if !template.ValidPayAddress {
			return nil, &btcjson.RPCError{
				Code: btcjson.ErrRPCInternal.Code,
				Message: "A coinbase transaction has been " +
					"requested, but the server has not " +
					"been configured with any payment " +
					"addresses via --miningaddr",
			}
		}

		// Serialize the transaction for conversion to hex.
		tx := msgBlock.Transactions[0]
		txBuf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize()))
		if err := tx.Serialize(txBuf); err != nil {
			context := "Failed to serialize transaction"
			return nil, internalRPCError(err.Error(), context)
		}

		resultTx := btcjson.GetBlockTemplateResultTx{
			Data:    hex.EncodeToString(txBuf.Bytes()),
			Hash:    tx.TxHash().String(),
			Depends: []int64{},
			Fee:     template.Fees[0],
			SigOps:  template.SigOpCosts[0],
		}

		reply.CoinbaseTxn = &resultTx
	}

	return &reply, nil
}
1203545
func NewAddTemplateResult(TemplateId string) *AddTemplateResult {
	s := new(AddTemplateResult)
	s.TemplateId = TemplateId
	return s
}
713674
func GetBlockFromBlockBytes(blockBytes []byte) (*cb.Block, error) {
	block := &cb.Block{}
	err := proto.Unmarshal(blockBytes, block)
	if err != nil {
		return block, errors.Wrap(err, "error unmarshaling block")
	}
	return block, nil
}
105149
func (loader *MapLoader) LoadTemplate(name string) (string, error) {
	if src, ok := (*loader)[name]; ok {
		return src, nil
	}
	return "", Errorf("Could not find template " + name)
}
942162
func (client *Client) GetTemplate(ctx context.Context, templateID string) (template Template, err error) {
	err = client.request(ctx, "GET", "templates/"+templateID, nil, &template)
	return template, err
}
12200
func RetrieveBlockFlags(ctx context.Context, db *sql.DB, hash string) (isValid bool, isMainchain bool, err error) {
	err = db.QueryRowContext(ctx, internal.SelectBlockFlags, hash).Scan(&isValid, &isMainchain)
	return
}
306554
func (r Virtual_Disk_Image) GetTemplateBlockDevice() (resp datatypes.Virtual_Guest_Block_Device_Template, err error) {
	err = r.Session.DoRequest("SoftLayer_Virtual_Disk_Image", "getTemplateBlockDevice", nil, &r.Options, &resp)
	return
}
837172
func (c *Client) GetBlockAsync(blockHash *chainhash.Hash) FutureGetBlockResult {
	hash := ""
	if blockHash != nil {
		hash = blockHash.String()
	}

	cmd := btcjson.NewGetBlockCmd(hash, btcjson.Bool(false), nil)
	return c.sendCmd(cmd)
}
327246
func (r FutureGetBlockHeaderVerboseResult) Receive() (*btcjson.GetBlockHeaderVerboseResult, error) {
	res, err := receiveFuture(r)
	if err != nil {
		return nil, err
	}

	// Unmarshal result as a string.
	var bh btcjson.GetBlockHeaderVerboseResult
	err = json.Unmarshal(res, &bh)
	if err != nil {
		return nil, err
	}

	return &bh, nil
}
846753
func (bt *blockTree) processGetBlocksTask(ctx context.Context,
	wg *sync.WaitGroup, wp *workerpool.WorkerPool,
	job getBlocksForOffsetRangeTask,
	results chan<- getBlocksForOffsetRangeResult) {
	defer wg.Done()

	select {
	case <-ctx.Done():
		results <- getBlocksForOffsetRangeResult{err: ctx.Err()}
		return
	default:
	}

	// We may have been passed just a pointer and need to fetch the block here.
	var pblock BlockWithPtrs
	if job.pblock == nil {
		var err error
		pblock, _, err = bt.getter(ctx, bt.kmd, job.ptr, bt.file, BlockReadParallel)
		if err != nil {
			results <- getBlocksForOffsetRangeResult{
				firstBlock: job.firstBlock,
				err:        err,
			}
			return
		}
	} else {
		pblock = job.pblock
	}

	if !pblock.IsIndirect() {
		// Return this block, under the assumption that the
		// caller already checked the range for this block.
		if job.getDirect {
			results <- getBlocksForOffsetRangeResult{
				pathFromRoot:    job.pathPrefix,
				ptr:             job.ptr,
				block:           pblock,
				nextBlockOffset: nil,
				firstBlock:      job.firstBlock,
				err:             nil,
			}
		}
		return
	}

	// Search all of the in-range child blocks, and their child
	// blocks, etc, in parallel.
	childIsFirstBlock := job.firstBlock
	for i := 0; i < pblock.NumIndirectPtrs(); i++ {
		info, iptrOff := pblock.IndirectPtr(i)
		// Some byte of this block is included in the left side of the
		// range if `job.startOff` is less than the largest byte offset in
		// the block.
		inRangeLeft := true
		if i < pblock.NumIndirectPtrs()-1 {
			_, off := pblock.IndirectPtr(i + 1)
			inRangeLeft = job.startOff.Less(off)
		}
		if !inRangeLeft {
			continue
		}
		// Some byte of this block is included in the right side of
		// the range if `job.endOff` is bigger than the smallest byte
		// offset in the block (or if we're explicitly reading all the
		// data to the end).
		inRangeRight := job.endOff == nil || iptrOff.Less(job.endOff)
		if !inRangeRight {
			// This block is the first one past the offset range
			// amount the children.
			results <- getBlocksForOffsetRangeResult{nextBlockOffset: iptrOff}
			return
		}

		childPtr := info.BlockPointer
		childIndex := i

		childPath := make([]ParentBlockAndChildIndex, len(job.pathPrefix)+1)
		copy(childPath, job.pathPrefix)
		childPath[len(childPath)-1] = ParentBlockAndChildIndex{
			pblock:     pblock,
			childIndex: childIndex,
		}

		// We only need to fetch direct blocks if we've been asked
		// to do so.  If the direct type of the pointer is
		// unknown, we can assume all the children are direct
		// blocks, since there weren't multiple levels of
		// indirection before the introduction of the flag.
		if job.getDirect || childPtr.DirectType == IndirectBlock {
			subTask := job.subTask(childPtr, childPath, childIsFirstBlock)

			// Enqueue the subTask with the WorkerPool.
			wg.Add(1)
			wp.Submit(func() {
				bt.processGetBlocksTask(ctx, wg, wp, subTask, results)
			})
		} else {
			results <- getBlocksForOffsetRangeResult{
				pathFromRoot: childPath,
				firstBlock:   childIsFirstBlock,
			}
		}
		childIsFirstBlock = false
	}
}
324676
func (p *BlockPrefetchClient) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error) {
	msgBlock, _, err := p.GetBlockData(hash)
	return msgBlock, err
}
423992
func (c *Client) GetBlockVerbose(blockHash *chainhash.Hash) (*btcjson.GetBlockVerboseResult, error) {
	return c.GetBlockVerboseAsync(blockHash).Receive()
}
4637
func (vi *VoteInfo) VotesOnBlock(blockHash string) bool {
	return vi.Validation.ForBlock(blockHash)
}
351205
func (c *BitcoindClient) GetBlockHeaderVerbose(
	hash *chainhash.Hash) (*btcjson.GetBlockHeaderVerboseResult, error) {

	return c.chainConn.client.GetBlockHeaderVerbose(hash)
}
303919
func (bra BlockRequestAction) Prefetch(block data.Block) bool {
	// When syncing, always prefetch child blocks of an indirect
	// block, since it makes no sense to sync just part of a
	// multi-block object.
	if block.IsIndirect() && bra.Sync() {
		return true
	}
	return bra.prefetch()
}
378808
func (c *Controller) RenderTemplate(templatePath string) Result {
	c.setStatusIfNil(http.StatusOK)

	// Get the Template.
	lang, _ := c.ViewArgs[CurrentLocaleViewArg].(string)
	template, err := MainTemplateLoader.TemplateLang(templatePath, lang)
	if err != nil {
		return c.RenderError(err)
	}

	return &RenderTemplateResult{
		Template: template,
		ViewArgs: c.ViewArgs,
	}
}
1361703
func (r Resource_Group) GetTemplate() (resp datatypes.Resource_Group_Template, err error) {
	err = r.Session.DoRequest("SoftLayer_Resource_Group", "getTemplate", nil, &r.Options, &resp)
	return
}