// chainAddressRowToManaged returns a new managed address based on chained
// address data loaded from the database.
//
// This function MUST be called with the manager lock held for writes.
429542
func (s *ScopedKeyManager) chainAddressRowToManaged(ns walletdb.ReadBucket,
	row *dbChainAddressRow) (ManagedAddress, error) {

	// Since the manger's mutex is assumed to held when invoking this
	// function, we use the internal isLocked to avoid a deadlock.
	isLocked := s.rootManager.isLocked()

	addressKey, err := s.deriveKeyFromPath(
		ns, row.account, row.branch, row.index, !isLocked,
	)
	if err != nil {
		return nil, err
	}

	return s.keyToManaged(addressKey, row.account, row.branch, row.index)
}
356105
func MacAddress() string {
	blocks := []string{}
	for i := 0; i < 6; i++ {
		number := fmt.Sprintf("%02x", privateRand.Intn(255))
		blocks = append(blocks, number)
	}

	return strings.Join(blocks, ":")
}
7134
func InsertSpendingAddressRow(db *sql.DB, fundingTxHash string,
	fundingTxVoutIndex uint32, fundingTxTree int8, spendingTxHash string,
	spendingTxVinIndex uint32, vinDbID uint64, utxoData *dbtypes.UTXOData,
	checked, updateExisting, isValidMainchain bool,
	txType int16, updateFundingRow bool, spendingTXBlockTime dbtypes.TimeDef) (int64, error) {
	// Only allow atomic transactions to happen
	dbtx, err := db.Begin()
	if err != nil {
		return 0, fmt.Errorf(`unable to begin database transaction: %v`, err)
	}

	c, err := insertSpendingAddressRow(dbtx, fundingTxHash, fundingTxVoutIndex,
		fundingTxTree, spendingTxHash, spendingTxVinIndex, vinDbID, utxoData, checked,
		updateExisting, isValidMainchain, txType, updateFundingRow, spendingTXBlockTime)
	if err != nil {
		return 0, fmt.Errorf(`RowsAffected: %v + %v (rollback)`,
			err, dbtx.Rollback())
	}

	return c, dbtx.Commit()
}
1271980
func NewAddressWitnessPubKeyHash(witnessProg []byte, net *chaincfg.Params) (*AddressWitnessPubKeyHash, error) {
	return newAddressWitnessPubKeyHash(net.Bech32HRPSegwit, witnessProg)
}
1165961
func markAddressUsed(ns walletdb.ReadWriteBucket, scope *KeyScope,
	addressID []byte) error {

	scopedBucket, err := fetchWriteScopeBucket(ns, scope)
	if err != nil {
		return err
	}

	bucket := scopedBucket.NestedReadWriteBucket(usedAddrBucketName)

	addrHash := sha256.Sum256(addressID)
	val := bucket.Get(addrHash[:])
	if val != nil {
		return nil
	}

	err = bucket.Put(addrHash[:], []byte{0})
	if err != nil {
		str := fmt.Sprintf("failed to mark address used %x", addressID)
		return managerError(ErrDatabase, str, err)
	}

	return nil
}
860910
func (a *managedAddress) AddrHash() []byte {
	var hash []byte

	switch n := a.address.(type) {
	case *btcutil.AddressPubKeyHash:
		hash = n.Hash160()[:]
	case *btcutil.AddressScriptHash:
		hash = n.Hash160()[:]
	case *btcutil.AddressWitnessPubKeyHash:
		hash = n.Hash160()[:]
	}

	return hash
}
703688
func (ac *AddressCache) NumRows(addr string) (int, *BlockID) {
	aci := ac.addressCacheItem(addr)
	if aci == nil {
		return -1, nil
	}
	return aci.NumRows()
}
972429
func (_m *DBClient) GetAddressableById(id string) (models.Addressable, error) {
	ret := _m.Called(id)

	var r0 models.Addressable
	if rf, ok := ret.Get(0).(func(string) models.Addressable); ok {
		r0 = rf(id)
	} else {
		r0 = ret.Get(0).(models.Addressable)
	}

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

	return r0, r1
}
1190028
func CompactRows(rows []*AddressRow) []AddressRowCompact {
	compact := make([]AddressRowCompact, 0, len(rows))
	for _, r := range rows {
		hash, err := chainhash.NewHashFromStr(r.TxHash)
		if err != nil {
			fmt.Println("Bad hash", r.TxHash)
			return nil
		}
		mhash, _ := chainhash.NewHashFromStr(r.MatchingTxHash) // zero array on error
		compact = append(compact, AddressRowCompact{
			Address:        r.Address,
			TxBlockTime:    r.TxBlockTime.UNIX(),
			MatchingTxHash: *mhash,
			TxHash:         *hash,
			TxVinVoutIndex: r.TxVinVoutIndex,
			TxType:         r.TxType,
			ValidMainChain: r.ValidMainChain,
			IsFunding:      r.IsFunding,
			Value:          r.Value,
		})
	}
	return compact
}
581305
func (pgb *ChainDB) AddressHistory(address string, N, offset int64,
	txnView dbtypes.AddrTxnViewType) ([]*dbtypes.AddressRow, *dbtypes.AddressBalance, error) {
	// Try the address rows cache.
	hash, height := pgb.BestBlock()
	addressRows, validBlock, err := pgb.AddressCache.Transactions(address, N, offset, txnView)
	if err != nil {
		return nil, nil, err
	}

	cacheCurrent := validBlock != nil && validBlock.Hash == *hash
	if !cacheCurrent {
		log.Debugf("Address rows (view=%s) cache MISS for %s.",
			txnView.String(), address)

		// Update or wait for an update to the cached AddressRows.
		addressRows, _, err = pgb.updateAddressRows(address)
		// See if another caller ran the update, in which case we were just
		// waiting to avoid a simultaneous query. With luck the cache will be
		// updated with this data, although it may not be. Try again.
		if err != nil && err != sql.ErrNoRows {
			if err.Error() == "retry" {
				// Try again, starting with cache.
				return pgb.AddressHistory(address, N, offset, txnView)
			}
			return nil, nil, err
		}
	}
	log.Debugf("Address rows (view=%s) cache HIT for %s.",
		txnView.String(), address)

	// addressRows is now present and current. Proceed to get the balance.

	// Try the address balance cache.
	balance, validBlock := pgb.AddressCache.Balance(address)
	cacheCurrent = validBlock != nil && validBlock.Hash == *hash
	if cacheCurrent {
		log.Debugf("Address balance cache HIT for %s.", address)
		return addressRows, balance, nil
	}
	log.Debugf("Address balance cache MISS for %s.", address)

	// Short cut: we have all txs when the total number of fetched txs is less
	// than the limit, txtype is AddrTxnAll, and Offset is zero.
	if len(addressRows) < int(N) && offset == 0 && txnView == dbtypes.AddrTxnAll {
		log.Debugf("Taking balance shortcut since address rows includes all.")
		// Zero balances and txn counts when rows is zero length.
		if len(addressRows) == 0 {
			balance = &dbtypes.AddressBalance{
				Address: address,
			}
		} else {
			addrInfo, fromStake, toStake := dbtypes.ReduceAddressHistory(addressRows)
			if addrInfo == nil {
				return addressRows, nil,
					fmt.Errorf("ReduceAddressHistory failed. len(addressRows) = %d",
						len(addressRows))
			}

			balance = &dbtypes.AddressBalance{
				Address:      address,
				NumSpent:     addrInfo.NumSpendingTxns,
				NumUnspent:   addrInfo.NumFundingTxns - addrInfo.NumSpendingTxns,
				TotalSpent:   int64(addrInfo.AmountSent),
				TotalUnspent: int64(addrInfo.AmountUnspent),
				FromStake:    fromStake,
				ToStake:      toStake,
			}
		}
		// Update balance cache.
		blockID := cache.NewBlockID(hash, height)
		pgb.AddressCache.StoreBalance(address, balance, blockID)
	} else {
		// Count spent/unspent amounts and transactions.
		log.Debugf("Obtaining balance via DB query.")
		balance, _, err = pgb.AddressBalance(address)
		if err != nil && err != sql.ErrNoRows {
			return nil, nil, err
		}
	}

	log.Infof("%s: %d spent totalling %f DCR, %d unspent totalling %f DCR",
		address, balance.NumSpent, dcrutil.Amount(balance.TotalSpent).ToCoin(),
		balance.NumUnspent, dcrutil.Amount(balance.TotalUnspent).ToCoin())
	log.Infof("Receive count for address %s: count = %d at block %d.",
		address, balance.NumSpent+balance.NumUnspent, height)

	return addressRows, balance, nil
}
718698
func AllDebitAddressRows(rows []*dbtypes.AddressRow) []*dbtypes.AddressRow {
	_, numDebitRows := CountCreditDebitRows(rows)
	out := make([]*dbtypes.AddressRow, numDebitRows)
	if numDebitRows == 0 {
		return out
	}
	for _, r := range rows {
		if !r.IsFunding {
			out = append(out, r)
		}
	}
	return out
}
827358
func putAddress(ns walletdb.ReadWriteBucket, scope *KeyScope,
	addressID []byte, row *dbAddressRow) error {

	scopedBucket, err := fetchWriteScopeBucket(ns, scope)
	if err != nil {
		return err
	}

	bucket := scopedBucket.NestedReadWriteBucket(addrBucketName)

	// Write the serialized value keyed by the hash of the address.  The
	// additional hash is used to conceal the actual address while still
	// allowed keyed lookups.
	addrHash := sha256.Sum256(addressID)
	err = bucket.Put(addrHash[:], serializeAddressRow(row))
	if err != nil {
		str := fmt.Sprintf("failed to store address %x", addressID)
		return managerError(ErrDatabase, str, err)
	}

	// Update address account index
	return putAddrAccountIndex(ns, scope, row.account, addrHash[:])
}
1007560
func (_m *DBClient) GetAddressablesByTopic(t string) ([]models.Addressable, error) {
	ret := _m.Called(t)

	var r0 []models.Addressable
	if rf, ok := ret.Get(0).(func(string) []models.Addressable); ok {
		r0 = rf(t)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]models.Addressable)
		}
	}

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

	return r0, r1
}
611687
func serializeChainedAddress(branch, index uint32) []byte {
	// The serialized chain address raw data format is:
	//   <branch><index>
	//
	// 4 bytes branch + 4 bytes address index
	rawData := make([]byte, 8)
	binary.LittleEndian.PutUint32(rawData[0:4], branch)
	binary.LittleEndian.PutUint32(rawData[4:8], index)
	return rawData
}
595979
func deserializeAddressRow(serializedAddress []byte) (*dbAddressRow, error) {
	// The serialized address format is:
	//   <addrType><account><addedTime><syncStatus><rawdata>
	//
	// 1 byte addrType + 4 bytes account + 8 bytes addTime + 1 byte
	// syncStatus + 4 bytes raw data length + raw data

	// Given the above, the length of the entry must be at a minimum
	// the constant value sizes.
	if len(serializedAddress) < 18 {
		str := "malformed serialized address"
		return nil, managerError(ErrDatabase, str, nil)
	}

	row := dbAddressRow{}
	row.addrType = addressType(serializedAddress[0])
	row.account = binary.LittleEndian.Uint32(serializedAddress[1:5])
	row.addTime = binary.LittleEndian.Uint64(serializedAddress[5:13])
	row.syncStatus = syncStatus(serializedAddress[13])
	rdlen := binary.LittleEndian.Uint32(serializedAddress[14:18])
	row.rawData = make([]byte, rdlen)
	copy(row.rawData, serializedAddress[18:18+rdlen])

	return &row, nil
}
20079
func (m *Manager) MarkUsed(ns walletdb.ReadWriteBucket, address btcutil.Address) error {
	m.mtx.RLock()
	defer m.mtx.RUnlock()

	// Run through all the known scoped managers, and attempt to mark the
	// address as used for each one.

	// First, we'll figure out which scoped manager this address belong to.
	for _, scopedMgr := range m.scopedManagers {
		if _, err := scopedMgr.Address(ns, address); err != nil {
			continue
		}

		// We've found the manager that this address belongs to, so we
		// can mark the address as used and return.
		return scopedMgr.MarkUsed(ns, address)
	}

	// If we get to this point, then we weren't able to find the address in
	// any of the managers, so we'll exit with an error.
	str := fmt.Sprintf("unable to find key for addr %v", address)
	return managerError(ErrAddressNotFound, str, nil)
}
286956
func (w *Wallet) AccountAddresses(account uint32) (addrs []btcutil.Address, err error) {
	err = walletdb.View(w.db, func(tx walletdb.ReadTx) error {
		addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
		return w.Manager.ForEachAccountAddress(addrmgrNs, account, func(maddr waddrmgr.ManagedAddress) error {
			addrs = append(addrs, maddr.Address())
			return nil
		})
	})
	return
}