// xorTxid performs the transformation needed to transform an OutPoint into a
// ChannelID. To do this, we expect the cid parameter to contain the txid
// unaltered and the outputIndex to be the output index
973008
func xorTxid(cid *ChannelID, outputIndex uint16) {
	var buf [32]byte
	binary.BigEndian.PutUint16(buf[30:], outputIndex)

	cid[30] = cid[30] ^ buf[30]
	cid[31] = cid[31] ^ buf[31]
}
1026722
func (pgb *ChainDB) nonMergedTxnCount(addr string, txnView dbtypes.AddrTxnViewType) (int, error) {
	bal, _, err := pgb.AddressBalance(addr)
	if err != nil {
		return 0, err
	}
	var count int64
	switch txnView {
	case dbtypes.AddrTxnAll:
		count = (bal.NumSpent * 2) + bal.NumUnspent
	case dbtypes.AddrTxnCredit:
		count = bal.NumSpent + bal.NumUnspent
	case dbtypes.AddrTxnDebit:
		count = bal.NumSpent
	default:
		return 0, fmt.Errorf("NonMergedTxnCount: requested count for merged view")
	}
	return int(count), nil
}
603768
func (ps Points) SearchNextIndex(x float64) int {
	sf := func(i int) bool {
		return x < ps[i].X()
	}
	return sort.Search(len(ps), sf)
}
1008973
func PgCastByOid(db XODB, oid pgtypes.Oid) (*PgCast, error) {
	var err error

	// sql query
	const sqlstr = `SELECT ` +
		`tableoid, cmax, xmax, cmin, xmin, oid, ctid, castsource, casttarget, castfunc, castcontext, castmethod ` +
		`FROM pg_catalog.pg_cast ` +
		`WHERE oid = $1`

	// run query
	XOLog(sqlstr, oid)
	pc := PgCast{}

	err = db.QueryRow(sqlstr, oid).Scan(&pc.Tableoid, &pc.Cmax, &pc.Xmax, &pc.Cmin, &pc.Xmin, &pc.Oid, &pc.Ctid, &pc.Castsource, &pc.Casttarget, &pc.Castfunc, &pc.Castcontext, &pc.Castmethod)
	if err != nil {
		return nil, err
	}

	return &pc, nil
}
974344
func FindScriptOutputIndex(tx *wire.MsgTx, script []byte) (bool, uint32) {
	found := false
	index := uint32(0)
	for i, txOut := range tx.TxOut {
		if bytes.Equal(txOut.PkScript, script) {
			found = true
			index = uint32(i)
			break
		}
	}

	return found, index
}
757379
func Xidsend(db XODB, v0 pgtypes.Xid) ([]byte, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.xidsend($1)`

	// run query
	var ret []byte
	XOLog(sqlstr, v0)
	err = db.QueryRow(sqlstr, v0).Scan(&ret)
	if err != nil {
		return nil, err
	}

	return ret, nil
}
497129
func (view *UtxoViewpoint) fetchUtxos(db database.DB, outpoints map[wire.OutPoint]struct{}) error {
	// Nothing to do if there are no requested outputs.
	if len(outpoints) == 0 {
		return nil
	}

	// Filter entries that are already in the view.
	neededSet := make(map[wire.OutPoint]struct{})
	for outpoint := range outpoints {
		// Already loaded into the current view.
		if _, ok := view.entries[outpoint]; ok {
			continue
		}

		neededSet[outpoint] = struct{}{}
	}

	// Request the input utxos from the database.
	return view.fetchUtxosMain(db, neededSet)
}
1180898
func (self *VDI) Unexpose() (err error) {

	disk_uuid, err := self.GetUuid()

	if err != nil {
		return err
	}

	hosts, err := self.Client.GetHosts()

	if err != nil {
		err = errors.New(fmt.Sprintf("Could not retrieve hosts in the pool: %s", err.Error()))
		return err
	}

	host := hosts[0]

	args := make(map[string]string)
	args["vdi_uuid"] = disk_uuid

	result, err := host.CallPlugin("transfer", "unexpose", args)

	if err != nil {
		return err
	}

	log.Println(fmt.Sprintf("Unexpose result: %s", result))

	return nil
}
112249
func (c *respClient) handleXSelectCmd() error {
	if len(c.args) <= 2 {
		// invalid command format
		return fmt.Errorf("invalid format for XSELECT, must XSELECT db THEN your command")
	}

	if hack.String(upperSlice(c.args[1])) != "THEN" {
		// invalid command format, just resturn here
		return fmt.Errorf("invalid format for XSELECT, must XSELECT db THEN your command")
	}

	index, err := strconv.Atoi(hack.String(c.args[0]))
	if err != nil {
		return fmt.Errorf("invalid db for XSELECT, err %v", err)
	}

	db, err := c.app.ldb.Select(index)
	if err != nil {
		return fmt.Errorf("invalid db for XSELECT, err %v", err)
	}

	c.db = db

	c.cmd = hack.String(lowerSlice(c.args[2]))
	c.args = c.args[3:]

	return nil
}
944598
func (d *DB) FetchClosedChannelForID(cid lnwire.ChannelID) (
	*ChannelCloseSummary, error) {

	var chanSummary *ChannelCloseSummary
	if err := d.View(func(tx *bbolt.Tx) error {
		closeBucket := tx.Bucket(closedChannelBucket)
		if closeBucket == nil {
			return ErrClosedChannelNotFound
		}

		// The first 30 bytes of the channel ID and outpoint will be
		// equal.
		cursor := closeBucket.Cursor()
		op, c := cursor.Seek(cid[:30])

		// We scan over all possible candidates for this channel ID.
		for ; op != nil && bytes.Compare(cid[:30], op[:30]) <= 0; op, c = cursor.Next() {
			var outPoint wire.OutPoint
			err := readOutpoint(bytes.NewReader(op), &outPoint)
			if err != nil {
				return err
			}

			// If the found outpoint does not correspond to this
			// channel ID, we continue.
			if !cid.IsChanPoint(&outPoint) {
				continue
			}

			// Deserialize the close summary and return.
			r := bytes.NewReader(c)
			chanSummary, err = deserializeCloseChannelSummary(r)
			if err != nil {
				return err
			}

			return nil
		}
		return ErrClosedChannelNotFound
	}); err != nil {
		return nil, err
	}

	return chanSummary, nil
}
1252265
func (db *DB) Queryx(query string, args ...interface{}) (*Rows, error) {
	r, err := db.DB.Query(query, args...)
	if err != nil {
		return nil, err
	}
	return &Rows{Rows: r, unsafe: db.unsafe, Mapper: db.Mapper}, err
}
837556
func ComputeTxID(nonce, creator []byte) (string, error) {
	// TODO: Get the Hash function to be used from
	// channel configuration
	digest, err := factory.GetDefault().Hash(
		append(nonce, creator...),
		&bccsp.SHA256Opts{})
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(digest), nil
}
618952
func sysContextID(fs fs, cid *uint32) error {
	f, err := fs.Open(devVsock)
	if err != nil {
		return err
	}
	defer f.Close()

	// Retrieve the context ID of this machine from /dev/vsock.
	return fs.Ioctl(f.Fd(), unix.IOCTL_VM_SOCKETS_GET_LOCAL_CID, unsafe.Pointer(cid))
}
100852
func (_m *DataStore) GetTxPvtRWSetByTxid(txid string, filter ledger.PvtNsCollFilter) (transientstore.RWSetScanner, error) {
	ret := _m.Called(txid, filter)

	var r0 transientstore.RWSetScanner
	if rf, ok := ret.Get(0).(func(string, ledger.PvtNsCollFilter) transientstore.RWSetScanner); ok {
		r0 = rf(txid, filter)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(transientstore.RWSetScanner)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(string, ledger.PvtNsCollFilter) error); ok {
		r1 = rf(txid, filter)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
518418
func (pgb *ChainDB) VinsForTx(dbTx *dbtypes.Tx) ([]dbtypes.VinTxProperty, []string, []uint16, error) {
	// Retrieve the pkScript and script version for the previous outpoint of
	// each vin.
	prevPkScripts := make([]string, 0, len(dbTx.VinDbIds))
	versions := make([]uint16, 0, len(dbTx.VinDbIds))
	for _, id := range dbTx.VinDbIds {
		pkScript, ver, err := pgb.PkScriptByVinID(id)
		if err != nil {
			return nil, nil, nil, fmt.Errorf("PkScriptByVinID: %v", err)
		}
		prevPkScripts = append(prevPkScripts, hex.EncodeToString(pkScript))
		versions = append(versions, ver)
	}

	// Retrieve the vins row data.
	ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
	defer cancel()
	vins, err := RetrieveVinsByIDs(ctx, pgb.db, dbTx.VinDbIds)
	if err != nil {
		err = fmt.Errorf("RetrieveVinsByIDs: %v", err)
	}
	return vins, prevPkScripts, versions, pgb.replaceCancelError(err)
}
1068153
func fetchInputTxos(s *rpcServer, tx *wire.MsgTx) (map[wire.OutPoint]wire.TxOut, error) {
	mp := s.cfg.TxMemPool
	originOutputs := make(map[wire.OutPoint]wire.TxOut)
	for txInIndex, txIn := range tx.TxIn {
		// Attempt to fetch and use the referenced transaction from the
		// memory pool.
		origin := &txIn.PreviousOutPoint
		originTx, err := mp.FetchTransaction(&origin.Hash)
		if err == nil {
			txOuts := originTx.MsgTx().TxOut
			if origin.Index >= uint32(len(txOuts)) {
				errStr := fmt.Sprintf("unable to find output "+
					"%v referenced from transaction %s:%d",
					origin, tx.TxHash(), txInIndex)
				return nil, internalRPCError(errStr, "")
			}

			originOutputs[*origin] = *txOuts[origin.Index]
			continue
		}

		// Look up the location of the transaction.
		blockRegion, err := s.cfg.TxIndex.TxBlockRegion(&origin.Hash)
		if err != nil {
			context := "Failed to retrieve transaction location"
			return nil, internalRPCError(err.Error(), context)
		}
		if blockRegion == nil {
			return nil, rpcNoTxInfoError(&origin.Hash)
		}

		// Load the raw transaction bytes from the database.
		var txBytes []byte
		err = s.cfg.DB.View(func(dbTx database.Tx) error {
			var err error
			txBytes, err = dbTx.FetchBlockRegion(blockRegion)
			return err
		})
		if err != nil {
			return nil, rpcNoTxInfoError(&origin.Hash)
		}

		// Deserialize the transaction
		var msgTx wire.MsgTx
		err = msgTx.Deserialize(bytes.NewReader(txBytes))
		if err != nil {
			context := "Failed to deserialize transaction"
			return nil, internalRPCError(err.Error(), context)
		}

		// Add the referenced output to the map.
		if origin.Index >= uint32(len(msgTx.TxOut)) {
			errStr := fmt.Sprintf("unable to find output %v "+
				"referenced from transaction %s:%d", origin,
				tx.TxHash(), txInIndex)
			return nil, internalRPCError(errStr, "")
		}
		originOutputs[*origin] = *msgTx.TxOut[origin.Index]
	}

	return originOutputs, nil
}
532626
func fixupTxnOp(rawOp interface{}) error {
	rawMap, ok := rawOp.(map[string]interface{})
	if !ok {
		return fmt.Errorf("unexpected raw op type: %T", rawOp)
	}
	for k, v := range rawMap {
		switch strings.ToLower(k) {
		case "kv":
			if v == nil {
				return nil
			}
			return decodeValue(v)
		}
	}
	return nil
}