// handleGetBlockHash implements the getblockhash command.
169524
func handleGetBlockHash(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	c := cmd.(*btcjson.GetBlockHashCmd)
	hash, err := s.cfg.Chain.BlockHashByHeight(int32(c.Index))
	if err != nil {
		return nil, &btcjson.RPCError{
			Code:    btcjson.ErrRPCOutOfRange,
			Message: "Block number out of range",
		}
	}

	return hash.String(), nil
}
895175
func handleGetBlockTemplate(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	c := cmd.(*btcjson.GetBlockTemplateCmd)
	request := c.Request

	// Set the default mode and override it if supplied.
	mode := "template"
	if request != nil && request.Mode != "" {
		mode = request.Mode
	}

	switch mode {
	case "template":
		return handleGetBlockTemplateRequest(s, request, closeChan)
	case "proposal":
		return handleGetBlockTemplateProposal(s, request)
	}

	return nil, &btcjson.RPCError{
		Code:    btcjson.ErrRPCInvalidParameter,
		Message: "Invalid mode",
	}
}
304361
func (db *PublicRecord) GetBlock(hash *wire.ShaHash) (*ombjson.Block, error) {
	row := db.selectBlock.QueryRow(hash.String())
	block, err := scanBlockHead(row)
	if err != nil {
		return &ombjson.Block{}, err
	}

	bltns, err := db.getBlockBltns(block.Head.Height)
	if err != nil {
		return &ombjson.Block{}, err
	}

	endos, err := db.getBlockEndos(block.Head.Height)
	if err != nil {
		return &ombjson.Block{}, err
	}

	block.Bulletins = bltns
	block.Endorsements = endos
	return block, nil
}
919825
func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block {
	return nil
}
387009
func handleGetBlock(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	c := cmd.(*btcjson.GetBlockCmd)

	// Load the raw block bytes from the database.
	hash, err := chainhash.NewHashFromStr(c.Hash)
	if err != nil {
		return nil, rpcDecodeHexError(c.Hash)
	}
	var blkBytes []byte
	err = s.cfg.DB.View(func(dbTx database.Tx) error {
		var err error
		blkBytes, err = dbTx.FetchBlock(hash)
		return err
	})
	if err != nil {
		return nil, &btcjson.RPCError{
			Code:    btcjson.ErrRPCBlockNotFound,
			Message: "Block not found",
		}
	}

	// When the verbose flag isn't set, simply return the serialized block
	// as a hex-encoded string.
	if c.Verbose != nil && !*c.Verbose {
		return hex.EncodeToString(blkBytes), nil
	}

	// The verbose flag is set, so generate the JSON object and return it.

	// Deserialize the block.
	blk, err := btcutil.NewBlockFromBytes(blkBytes)
	if err != nil {
		context := "Failed to deserialize block"
		return nil, internalRPCError(err.Error(), context)
	}

	// Get the block height from chain.
	blockHeight, err := s.cfg.Chain.BlockHeightByHash(hash)
	if err != nil {
		context := "Failed to obtain block height"
		return nil, internalRPCError(err.Error(), context)
	}
	blk.SetHeight(blockHeight)
	best := s.cfg.Chain.BestSnapshot()

	// Get next block hash unless there are none.
	var nextHashString string
	if blockHeight < best.Height {
		nextHash, err := s.cfg.Chain.BlockHashByHeight(blockHeight + 1)
		if err != nil {
			context := "No next block"
			return nil, internalRPCError(err.Error(), context)
		}
		nextHashString = nextHash.String()
	}

	params := s.cfg.ChainParams
	blockHeader := &blk.MsgBlock().Header
	blockReply := btcjson.GetBlockVerboseResult{
		Hash:          c.Hash,
		Version:       blockHeader.Version,
		VersionHex:    fmt.Sprintf("%08x", blockHeader.Version),
		MerkleRoot:    blockHeader.MerkleRoot.String(),
		PreviousHash:  blockHeader.PrevBlock.String(),
		Nonce:         blockHeader.Nonce,
		Time:          blockHeader.Timestamp.Unix(),
		Confirmations: int64(1 + best.Height - blockHeight),
		Height:        int64(blockHeight),
		Size:          int32(len(blkBytes)),
		StrippedSize:  int32(blk.MsgBlock().SerializeSizeStripped()),
		Weight:        int32(blockchain.GetBlockWeight(blk)),
		Bits:          strconv.FormatInt(int64(blockHeader.Bits), 16),
		Difficulty:    getDifficultyRatio(blockHeader.Bits, params),
		NextHash:      nextHashString,
	}

	if c.VerboseTx == nil || !*c.VerboseTx {
		transactions := blk.Transactions()
		txNames := make([]string, len(transactions))
		for i, tx := range transactions {
			txNames[i] = tx.Hash().String()
		}

		blockReply.Tx = txNames
	} else {
		txns := blk.Transactions()
		rawTxns := make([]btcjson.TxRawResult, len(txns))
		for i, tx := range txns {
			rawTxn, err := createTxRawResult(params, tx.MsgTx(),
				tx.Hash().String(), blockHeader, hash.String(),
				blockHeight, best.Height)
			if err != nil {
				return nil, err
			}
			rawTxns[i] = *rawTxn
		}
		blockReply.RawTx = rawTxns
	}

	return blockReply, nil
}
1346920
func RetrieveBlockHash(ctx context.Context, db *sql.DB, idx int64) (hash string, err error) {
	err = db.QueryRowContext(ctx, internal.SelectBlockHashByHeight, idx).Scan(&hash)
	return
}
1093890
func (c *Client) GetBestBlock() (*chainhash.Hash, int32, error) {
	return c.GetBestBlockAsync().Receive()
}
950618
func (bg *realBlockGetter) getBlock(
	ctx context.Context, kmd libkey.KeyMetadata, blockPtr data.BlockPointer,
	block data.Block, cacheType DiskBlockCacheType) error {
	bserv := bg.config.BlockServer()
	buf, blockServerHalf, err := bserv.Get(
		ctx, kmd.TlfID(), blockPtr.ID, blockPtr.Context, cacheType)
	if err != nil {
		// Temporary code to track down bad block
		// requests. Remove when not needed anymore.
		if _, ok := err.(kbfsblock.ServerErrorBadRequest); ok {
			panic(fmt.Sprintf("Bad BServer request detected: err=%s, blockPtr=%s",
				err, blockPtr))
		}

		return err
	}

	return assembleBlock(
		ctx, bg.config.keyGetter(), bg.config.Codec(), bg.config.cryptoPure(),
		kmd, blockPtr, block, buf, blockServerHalf)
}
656601
func (m *MockCryptoSuite) GetHash(opts core.HashOpts) (hash.Hash, error) {
	return sha256.New(), nil
}
935576
func (p *BlockPrefetchClient) GetBlockData(hash *chainhash.Hash) (*wire.MsgBlock, *dcrjson.GetBlockHeaderVerboseResult, error) {
	p.Lock()

	retargetAndUnlock := func(nextHash string) {
		p.retarget(nextHash)
		p.Unlock()
	}

	// If the block is already fetched, and the current block, return it. Do not
	// retarget.
	if p.current.hash == *hash /*p.haveBlockHash(*hash)*/ {
		p.hits++
		// Return the requested block.
		defer p.Unlock()
		return p.current.msgBlock, p.current.headerResult, nil
	}

	// If the block is already fetched, and next, return it and retarget with a
	// new range starting at this block's height.
	if p.next.hash == *hash /*p.haveBlockHash(*hash)*/ {
		// Grab the result before retarget() changes p.next (via fetcher ->
		// RetrieveAndStoreNext -> storeNext).
		msgBlock, headerResult := p.next.msgBlock, p.next.headerResult
		go retargetAndUnlock(p.next.headerResult.NextHash)
		p.hits++
		// Return the requested block.
		return msgBlock, headerResult, nil
	}

	p.misses++

	// Immediately retrieve msgBlock and header verbose result while fetcher is
	// blocked by the Mutex.
	msgBlock, headerResult, _, err := p.retrieveBlockAndHeaderResult(hash)
	if err != nil {
		p.Unlock()
		return nil, nil, err
	}

	// Leaving the mutex locked, fire off a goroutine to retarget to the next
	// block. The fetcher goroutine and other locking methods will stay blocked
	// until the mutex unlocks, but the msgBlock can be returned right away.
	go retargetAndUnlock(headerResult.NextHash)

	return msgBlock, headerResult, err
}
890005
func handleGetHashesPerSec(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	return int64(s.cfg.CPUMiner.HashesPerSecond()), nil
}
862432
func (apic *APICache) GetCachedBlockByHash(hash chainhash.Hash) *CachedBlock {
	// validate the chainhash.Hash
	if _, err := chainhash.NewHashFromStr(hash.String()); err != nil {
		fmt.Printf("that's not a real hash!")
		return nil
	}

	apic.mtx.Lock()
	defer apic.mtx.Unlock()
	return apic.getCachedBlockByHash(hash)
}
590618
func (s *NeutrinoClient) GetBlockHeader(
	blockHash *chainhash.Hash) (*wire.BlockHeader, error) {
	return s.CS.GetBlockHeader(blockHash)
}
327581
func (c *Client) GetBlockHeaderVerbose(blockHash *chainhash.Hash) (*btcjson.GetBlockHeaderVerboseResult, error) {
	return c.GetBlockHeaderVerboseAsync(blockHash).Receive()
}
1259493
func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
	return bc.hc.GetHeaderByHash(hash)
}
559943
func (pgb *ChainDB) GetBlockHash(idx int64) (string, error) {
	ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
	defer cancel()
	hash, err := RetrieveBlockHash(ctx, pgb.db, idx)
	if err != nil {
		log.Errorf("Unable to get block hash for block number %d: %v", idx, err)
		return "", pgb.replaceCancelError(err)
	}
	return hash, nil
}
833549
func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int {
	number := hc.GetBlockNumber(hash)
	if number == nil {
		return nil
	}
	return hc.GetTd(hash, *number)
}