// UpdateVotesMainchain sets the is_mainchain column for the votes in the
// specified block.
961047
func UpdateVotesMainchain(db *sql.DB, blockHash string, isMainchain bool) (int64, error) {
	numRows, err := sqlExec(db, internal.UpdateVotesMainchainByBlock,
		"failed to update votes is_mainchain: ", isMainchain, blockHash)
	if err != nil {
		return 0, err
	}
	return numRows, 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
}
71939
func (tx *Tx) UpdateBySql(query string, value ...interface{}) *UpdateStmt {
	b := UpdateBySql(query, value...)
	b.runner = tx
	b.EventReceiver = tx.EventReceiver
	b.Dialect = tx.Dialect
	return b
}
1207588
func (ro *rescanOptions) updateFilter(chain ChainSource, update *updateOptions,
	curStamp *waddrmgr.BlockStamp, curHeader *wire.BlockHeader) (bool, error) {

	ro.watchAddrs = append(ro.watchAddrs, update.addrs...)
	ro.watchInputs = append(ro.watchInputs, update.inputs...)

	for _, addr := range update.addrs {
		script, err := txscript.PayToAddrScript(addr)
		if err != nil {
			return false, err
		}

		ro.watchList = append(ro.watchList, script)
	}
	for _, input := range update.inputs {
		ro.watchList = append(ro.watchList, input.PkScript)
	}
	for _, txid := range update.txIDs {
		ro.watchList = append(ro.watchList, txid[:])
	}

	// If we don't need to rewind, then we can exit early.
	if update.rewind == 0 {
		return false, nil
	}

	var (
		header  *wire.BlockHeader
		height  uint32
		rewound bool
		err     error
	)

	// If we need to rewind, then we'll walk backwards in the chain until
	// we arrive at the block _just_ before the rewind.
	for curStamp.Height > int32(update.rewind) {
		if ro.ntfn.OnBlockDisconnected != nil &&
			!update.disableDisconnectedNtfns {
			ro.ntfn.OnBlockDisconnected(&curStamp.Hash,
				curStamp.Height, curHeader.Timestamp)
		}
		if ro.ntfn.OnFilteredBlockDisconnected != nil &&
			!update.disableDisconnectedNtfns {
			ro.ntfn.OnFilteredBlockDisconnected(curStamp.Height,
				curHeader)
		}

		// We just disconnected a block above, so we're now in rewind
		// mode. We set this to true here so we properly send
		// notifications even if it was just a 1 block rewind.
		rewound = true

		// Rewind and continue.
		header, height, err = chain.GetBlockHeader(&curHeader.PrevBlock)
		if err != nil {
			return rewound, err
		}

		*curHeader = *header
		curStamp.Height = int32(height)
		curStamp.Hash = curHeader.BlockHash()
	}

	return rewound, nil
}
59354
func (d *Database) Update(db DB, table string, src interface{}) error {
	// gather the query parts
	names, err := d.Columns(src, false)
	if err != nil {
		return err
	}
	placeholders, err := d.Placeholders(src, false)
	if err != nil {
		return err
	}
	values, err := d.Values(src, false)
	if err != nil {
		return err
	}

	// form the column=placeholder pairs
	var pairs []string
	for i := 0; i < len(names) && i < len(placeholders); i++ {
		pair := fmt.Sprintf("%s=%s", d.quoted(names[i]), placeholders[i])
		pairs = append(pairs, pair)
	}

	pkName, pkValue, err := d.PrimaryKey(src)
	if err != nil {
		return err
	}
	if pkName == "" {
		return fmt.Errorf("meddler.Update: no primary key field")
	}
	if pkValue < 1 {
		return fmt.Errorf("meddler.Update: primary key must be an integer > 0")
	}
	ph := d.placeholder(len(placeholders) + 1)

	// run the query
	q := fmt.Sprintf("UPDATE %s SET %s WHERE %s=%s", d.quoted(table),
		strings.Join(pairs, ","),
		d.quoted(pkName), ph)
	values = append(values, pkValue)

	if _, err := db.Exec(q, values...); err != nil {
		return &dbErr{msg: "meddler.Update: DB error in Exec", err: err}
	}

	return nil
}
1135471
func updateAllTicketsMainchain(db *sql.DB) (rowsUpdated int64, err error) {
	return sqlExec(db, internal.UpdateTicketsMainchainAll,
		"failed to update tickets and mainchain status")
}
304610
func (r *run) updatePrimaryPhoto(photoNode *importer.Object) error {
	photoId := photoNode.Attr(attrFlickrId)
	for album, photo := range r.primaryPhoto {
		if photoId != photo {
			continue
		}
		setsNode, err := r.getTopLevelNode("sets", "Sets")
		if err != nil {
			return fmt.Errorf("could not set %v as primary photo of %v, no root sets: %v", photoId, album, err)
		}
		setNode, err := setsNode.ChildPathObject(album)
		if err != nil {
			return fmt.Errorf("could not set %v as primary photo of %v, no album: %v", photoId, album, err)
		}
		fileRef := photoNode.Attr(nodeattr.CamliContent)
		if fileRef == "" {
			return fmt.Errorf("could not set %v as primary photo of %v: fileRef of photo is unknown", photoId, album)
		}
		if err := setNode.SetAttr(nodeattr.CamliContentImage, fileRef); err != nil {
			return fmt.Errorf("could not set %v as primary photo of %v: %v", photoId, album, err)
		}
		delete(r.primaryPhoto, album)
	}
	return nil
}
1315573
func (el *EndpointsLock) Update(ler LeaderElectionRecord) error {
	if el.e == nil {
		return errors.New("endpoint not initialized, call get or create first")
	}
	recordBytes, err := json.Marshal(ler)
	if err != nil {
		return err
	}
	el.e.Annotations[LeaderElectionRecordAnnotationKey] = string(recordBytes)
	el.e, err = el.Client.Endpoints(el.EndpointsMeta.Namespace).Update(el.e)
	return err
}
835232
func (s *MemoryStore) Update(cb func(Tx) error) error {
	return s.update(s.proposer, cb)
}
1358695
func (pq *BlockPriorityQueue) updateMinMax(h uint32) (updated bool) {
	if int64(h) > pq.maxHeight {
		pq.maxHeight = int64(h)
		updated = true
	}
	if int64(h) < pq.minHeight {
		pq.minHeight = int64(h)
		updated = true
	}
	return
}
258647
func UpdateLastAddressesValid(db *sql.DB, blockHash string, isValid bool) error {
	// The queries in this function should not timeout or (probably) canceled,
	// so use a background context.
	ctx := context.Background()

	// Get the row ids of all vins and vouts of regular txns in this block.
	onlyRegularTxns := true
	vinDbIDsBlk, voutDbIDsBlk, _, err := RetrieveTxnsVinsVoutsByBlock(ctx, db, blockHash, onlyRegularTxns)
	if err != nil {
		return fmt.Errorf("unable to retrieve vin data for block %s: %v", blockHash, err)
	}
	// Using vins and vouts row ids, update the valid_mainchain colume of the
	// rows of the address table referring to these vins and vouts.
	numAddrSpending, numAddrFunding, err := UpdateAddressesMainchainByIDs(db,
		vinDbIDsBlk, voutDbIDsBlk, isValid)
	if err != nil {
		log.Errorf("Failed to set addresses rows in block %s as sidechain: %v", blockHash, err)
	}
	addrsUpdated := numAddrSpending + numAddrFunding
	log.Debugf("Rows of addresses table updated: %d", addrsUpdated)
	return err
}
602590
func (t *Store) UpdateUserToken(token string, source TokenSource) {
	t.l.Lock()
	t.userToken = token
	t.userTokenSource = source
	t.l.Unlock()
}
626386
func (ipt *IPTables) RenameChain(table, oldChain, newChain string) error {
	return ipt.run("-t", table, "-E", oldChain, newChain)
}
504667
func (b *BigIP) UpdatePoolMembers(pool string, pm *[]PoolMember) error {
	config := &poolMembers{
		Members: *pm,
	}
	return b.put(config, uriLtm, uriPool, pool)
}
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
}
825455
func UpdateTransactionsMainchain(db *sql.DB, blockHash string, isMainchain bool) (int64, []uint64, error) {
	rows, err := db.Query(internal.UpdateTxnsMainchainByBlock, isMainchain, blockHash)
	if err != nil {
		return 0, nil, fmt.Errorf("failed to update transactions is_mainchain: %v", err)
	}
	defer closeRows(rows)

	var numRows int64
	var txRowIDs []uint64
	for rows.Next() {
		var id uint64
		err = rows.Scan(&id)
		if err != nil {
			break
		}

		txRowIDs = append(txRowIDs, id)
		numRows++
	}

	return numRows, txRowIDs, nil
}
39871
func (db *TXDatabaseOverlay) update() (string, error) {
	newestFBlock, err := fblockHead()
	if err != nil {
		return "", err
	}

	start, err := db.FetchNextFBlockHeight()
	if err != nil {
		return "", err
	}

	// Make sure we didn't switch networks
	genesis, err := db.DBO.FetchFBlockByHeight(0)
	if err != nil {
		return "", err
	}
	if genesis != nil {
		genesis2, err := getdblockbyheight(0)
		if err != nil {
			return "", err
		}

		var gensisFBlockKeyMr interfaces.IHash
		for _, e := range genesis2.GetDBEntries() {
			if e.GetChainID().String() == "000000000000000000000000000000000000000000000000000000000000000f" {
				gensisFBlockKeyMr = e.GetKeyMR()
				break
			}
		}

		if gensisFBlockKeyMr == nil {
			return "", fmt.Errorf("unable to fetch the genesis block via the api")
		}

		if !gensisFBlockKeyMr.IsSameAs(genesis.GetKeyMR()) {
			start = 0
		}
	}

	newestHeight := newestFBlock.GetDatabaseHeight()

	// If the newest block in the tx cashe has a greater height than the newest
	// fblock then clear the cashe and start from 0.
	if start >= newestHeight {
		return newestFBlock.GetKeyMR().String(), nil
	}

	db.DBO.StartMultiBatch()
	for i := start; i <= newestHeight; i++ {
		if i%1000 == 0 {
			if newestHeight-start > 1000 {
				fmt.Printf("Fetching block %v/%v\n", i, newestHeight)
			}
		}
		fblock, err := getfblockbyheight(i)
		if err != nil {
			db.DBO.ExecuteMultiBatch()
			return "", err
		}
		db.DBO.ProcessFBlockMultiBatch(fblock)

		// Save to DB every 500 blocks
		if i%500 == 0 {
			db.DBO.ExecuteMultiBatch()
			db.DBO.StartMultiBatch()
		}

		// If the wallet is stopped, this process becomes hard to kill. Have it exit
		if db.quit {
			break
		}
	}

	if !db.quit {
		fmt.Printf("Fetching block %v/%v\n", newestHeight, newestHeight)
	}

	// Save the remaining blocks
	if err = db.DBO.ExecuteMultiBatch(); err != nil {
		return "", err
	}

	return newestFBlock.GetKeyMR().String(), nil
}