// Sets the is_mainchain field to false for the given block in the database.
7653
func (db *DB) setHeightToSideChain(height int64) error {
	_, err := db.Exec(db.setHeightToSideChainSQL, height)
	return db.filterError(err)
}
538763
func loadBlockDB() (database.DB, error) {
	// The database name is based on the database type.
	dbName := blockDbNamePrefix + "_" + cfg.DbType
	dbPath := filepath.Join(cfg.DataDir, dbName)

	log.Infof("Loading block database from '%s'", dbPath)
	db, err := database.Open(cfg.DbType, dbPath, activeNetParams.Net)
	if err != nil {
		// Return the error if it's not because the database doesn't
		// exist.
		if dbErr, ok := err.(database.Error); !ok || dbErr.ErrorCode !=
			database.ErrDbDoesNotExist {

			return nil, err
		}

		// Create the db if it does not exist.
		err = os.MkdirAll(cfg.DataDir, 0700)
		if err != nil {
			return nil, err
		}
		db, err = database.Create(cfg.DbType, dbPath, activeNetParams.Net)
		if err != nil {
			return nil, err
		}
	}

	log.Info("Block database loaded")
	return db, nil
}
915471
func (pgb *ChainDB) BlockFlagsNoCancel(hash string) (bool, bool, error) {
	return pgb.blockFlags(context.Background(), hash)
}
233596
func (b *BtcWallet) GetBestBlock() (*chainhash.Hash, int32, error) {
	return b.chain.GetBestBlock()
}
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
}
983889
func (u *ubiTweak) setFirstBlock(value bool) {
    if value {
        u.tweak[1] |= t1FlagFirst
    } else {
        u.tweak[1] &^= t1FlagFirst
    }
}
1227865
func (s *Ethereum) isLocalBlock(block *types.Block) bool {
	author, err := s.engine.Author(block.Header())
	if err != nil {
		log.Warn("Failed to retrieve block author", "number", block.NumberU64(), "hash", block.Hash(), "err", err)
		return false
	}
	// Check whether the given address is etherbase.
	s.lock.RLock()
	etherbase := s.etherbase
	s.lock.RUnlock()
	if author == etherbase {
		return true
	}
	// Check whether the given address is specified by `txpool.local`
	// CLI flag.
	for _, account := range s.config.TxPool.Locals {
		if account == author {
			return true
		}
	}
	return false
}
577336
func (db *DirBlock) Set(other Block) {
	otherDb := other.(*DirBlock)
	dbCopy := otherDb.DeepCopy()
	db.Children = dbCopy.Children
	db.IPtrs = dbCopy.IPtrs
	db.ToCommonBlock().Set(dbCopy.ToCommonBlock())
}
539857
func (pgb *ChainDB) handleBlocksTableMainchainUpgrade(bestBlock string) (int64, error) {
	// Start at best block, upgrade, and move to previous block. Stop after
	// genesis, which previous block hash is the zero hash.
	var blocksUpdated int64
	previousHash, thisBlockHash := bestBlock, bestBlock
	for !bytes.Equal(zeroHashStringBytes, []byte(previousHash)) {
		// set is_mainchain=1 and get previous_hash
		var err error
		previousHash, err = SetMainchainByBlockHash(pgb.db, thisBlockHash, true)
		if err != nil {
			return blocksUpdated, fmt.Errorf("SetMainchainByBlockHash for block %s failed: %v",
				thisBlockHash, err)
		}
		blocksUpdated++

		// genesis is not in the block_chain table.  All done!
		if bytes.Equal(zeroHashStringBytes, []byte(previousHash)) {
			break
		}

		// patch block_chain table
		err = UpdateBlockNextByHash(pgb.db, previousHash, thisBlockHash)
		if err != nil {
			log.Errorf("Failed to update next_hash in block_chain for block %s", previousHash)
		}

		thisBlockHash = previousHash
	}
	return blocksUpdated, nil
}
1224621
func (pgb *ChainDB) SideChainBlocks() ([]*dbtypes.BlockStatus, error) {
	ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
	defer cancel()
	scb, err := RetrieveSideChainBlocks(ctx, pgb.db)
	return scb, pgb.replaceCancelError(err)
}
604788
func (db *PublicRecord) InsertBlockHead(blk *btcutil.Block) (error, bool) {
	tx, err := db.conn.Begin()
	if err != nil {
		return err, false
	}

	err = db.insertBlockHead(tx, blk)
	if err != nil {
		return tx.Rollback(), false
	}

	if err = tx.Commit(); err != nil {
		return err, true
	}

	return nil, true
}
709219
func (db *StakeDatabase) dbPrevBlock() (*dcrutil.Block, error) {
	_, hash, err := db.dbState()
	if err != nil {
		return nil, err
	}

	parentHeader, err := db.NodeClient.GetBlockHeader(hash)
	if err != nil {
		return nil, err
	}

	return db.getBlock(&parentHeader.PrevBlock)
}
183109
func (db *WiredDB) ImportSideChains(collector *blockdata.Collector) error {
	tips, err := rpcutils.SideChains(db.client)
	if err != nil {
		return err
	}
	var hashlist []*chainhash.Hash
	for it := range tips {
		log.Tracef("Primary DB -> Getting base DB side chain with tip %s at %d.", tips[it].Hash, tips[it].Height)
		sideChain, err := rpcutils.SideChainFull(db.client, tips[it].Hash)
		if err != nil {
			log.Errorf("Primary DB -> Unable to get side chain blocks for chain tip %s: %v", tips[it].Hash, err)
			return err
		}

		// For each block in the side chain, check if it already stored.
		for is := range sideChain {
			// Check for the block hash in the DB.
			isMainchainNow, err := db.getMainchainStatus(sideChain[is])
			if isMainchainNow || err == sql.ErrNoRows {
				blockhash, err := chainhash.NewHashFromStr(sideChain[is])
				if err != nil {
					log.Errorf("Primary DB -> Invalid block hash %s: %v.", blockhash, err)
					continue
				}
				hashlist = append(hashlist, blockhash)
			}
		}
	}
	log.Infof("Primary DB -> %d new sidechain block(s) to import", len(hashlist))
	for _, blockhash := range hashlist {
		// Collect block data.
		blockDataBasic, _ := collector.CollectAPITypes(blockhash)
		log.Debugf("Primary DB -> Importing block %s (height %d) into primary DB.",
			blockhash.String(), blockDataBasic.Height)
		if blockDataBasic == nil {
			// Do not quit if unable to collect side chain block data.
			log.Error("Primary DB -> Unable to collect data for side chain block %s", blockhash.String())
			continue
		}
		err := db.StoreSideBlockSummary(blockDataBasic)
		if err != nil {
			log.Errorf("Primary DB -> Failed to store block %s", blockhash.String())
		}
	}
	return nil
}
1158268
func (p *ChainMonitor) switchToSideChain(reorgData *txhelpers.ReorgData) (int32, *chainhash.Hash, error) {
	if reorgData == nil || len(reorgData.NewChain) == 0 {
		return 0, nil, fmt.Errorf("no side chain")
	}

	// Time this process.
	defer func(start time.Time) {
		log.Infof("dcrpg: switchToSideChain completed in %v", time.Since(start))
	}(time.Now())

	newChain := reorgData.NewChain
	// newChain does not include the common ancestor.
	commonAncestorHeight := int64(reorgData.NewChainHeight) - int64(len(newChain))

	mainTip := p.db.bestBlock.Height()
	if mainTip != int64(reorgData.OldChainHeight) {
		log.Warnf("StakeDatabase height is %d, expected %d. Rewinding as "+
			"needed to complete reorg from ancestor at %d", mainTip,
			reorgData.OldChainHeight, commonAncestorHeight)
	}

	// Flag blocks from mainRoot+1 to mainTip as is_mainchain=false
	startTime := time.Now()
	mainRoot := reorgData.CommonAncestor.String()
	log.Infof("Moving %d blocks to side chain...", mainTip-commonAncestorHeight)
	newMainRoot, numBlocksmoved, err := p.db.TipToSideChain(mainRoot)
	if err != nil || mainRoot != newMainRoot {
		return 0, nil, fmt.Errorf("failed to flag blocks as side chain")
	}
	log.Infof("Moved %d blocks from the main chain to a side chain in %v.",
		numBlocksmoved, time.Since(startTime))

	// Verify the tip is now the previous common ancestor
	mainTip = p.db.bestBlock.Height()
	if mainTip != commonAncestorHeight {
		panic(fmt.Sprintf("disconnect blocks failed: tip height %d, expected %d",
			mainTip, commonAncestorHeight))
	}

	// Connect blocks in side chain onto main chain
	log.Debugf("Connecting %d blocks", len(newChain))
	currentHeight := commonAncestorHeight + 1
	var endHash chainhash.Hash
	var endHeight int32
	for i := range newChain {
		var msgBlock *wire.MsgBlock
		// Try to find block in stakedb cache
		block, found := p.db.stakeDB.BlockCached(currentHeight)
		if found {
			msgBlock = block.MsgBlock()
		}
		// Fetch the block by RPC if not found or wrong hash
		if !found || msgBlock.BlockHash() != newChain[i] {
			log.Debugf("block %v not found in stakedb cache, fetching from dcrd", newChain[i])
			// Request MsgBlock from dcrd
			msgBlock, err = p.db.Client.GetBlock(&newChain[i])
			if err != nil {
				return 0, nil,
					fmt.Errorf("unable to get side chain block %v", newChain[i])
			}
		}

		// Get current winning votes from stakedb
		tpi, found := p.db.stakeDB.PoolInfo(newChain[i])
		if !found {
			return 0, nil,
				fmt.Errorf("stakedb.PoolInfo failed to return info for: %v",
					newChain[i])
		}
		winners := tpi.Winners

		// Get the chainWork
		blockHash := msgBlock.BlockHash()
		chainWork, err := p.db.GetChainWork(&blockHash)
		if err != nil {
			return 0, nil, fmt.Errorf("GetChainWork failed (%s): %v", blockHash.String(), err)
		}

		// New blocks stored this way are considered part of mainchain. They are
		// also considered valid unless invalidated by the next block
		// (invalidation of previous handled inside StoreBlock).
		isValid, isMainChain, updateExisting := true, true, true
		_, _, _, err = p.db.StoreBlock(msgBlock, winners, isValid, isMainChain,
			updateExisting, true, true, chainWork)
		if err != nil {
			return int32(p.db.bestBlock.Height()), p.db.bestBlock.Hash(),
				fmt.Errorf("error connecting block %v", newChain[i])
		}

		endHeight = int32(msgBlock.Header.Height)
		endHash = msgBlock.BlockHash()

		log.Infof("Connected block %v (height %d) from side chain.", endHash, endHeight)

		currentHeight++
	}

	log.Infof("Moved %d blocks from a side chain to the main chain in %v.",
		numBlocksmoved, time.Since(startTime))

	mainTip = p.db.bestBlock.Height()
	if mainTip != int64(endHeight) {
		panic(fmt.Sprintf("connected block height %d not db tip height %d",
			endHeight, mainTip))
	}

	return endHeight, &endHash, nil
}
796848
func (u *ubiTweak) setFinalBlock(value bool) {
    if value {
        u.tweak[1] |= t1FlagFinal
    } else {
        u.tweak[1] &^= t1FlagFinal
    }
}
180636
func (ddb debugDB) SetNoLockSync(key []byte, value []byte) {
	fmt.Printf("%v.SetNoLockSync(%v, %v)\n", ddb.label,
		cmn.ColoredBytes(key, cmn.Yellow, cmn.Blue),
		cmn.ColoredBytes(value, cmn.Green, cmn.Blue))
	ddb.db.(atomicSetDeleter).SetNoLockSync(key, value)
}
1139042
func (bpr *bpRequester) setBlock(block *types.Block, peerID p2p.ID) bool {
	bpr.mtx.Lock()
	if bpr.block != nil || bpr.peerID != peerID {
		bpr.mtx.Unlock()
		return false
	}
	bpr.block = block
	bpr.mtx.Unlock()

	select {
	case bpr.gotBlockCh <- struct{}{}:
	default:
	}
	return true
}