feat(wallet): change goes to an address the group can find (Phase 3)
Two open spends with change both paid to the first unused change address, since a spend waiting for signatures has not used it yet. Change indices are now reserved like coins: reservedChangeIndices reads the claims of every open spend, and the builder takes the lowest watched, unused, unheld index. It chooses among generated addresses only, so change never lands outside the window; CHANGE_LOOKAHEAD rises to 10 and past it a spend with change returns TooManyOpen. The change branch not having answered is FindingChange rather than NothingToSpend, and change too small to send back is reported as Built.absorbed and said in the preview. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bc348419bc
commit
5c77853cfa
14 files changed
+327
-76
No files matched your search
@@ -657,6 +657,8 @@
|
||||
<string name="sats_are_whole_numbers">Sats are whole numbers: there is nothing smaller than a sat to send.</string>
|
||||
<string name="that_is_more_sats_than_there_will_ever_be">That is more sats than there will ever be.</string>
|
||||
<string name="that_isn_t_an_amount_in_sats">That isn't an amount in sats.</string>
|
||||
<string name="s_sats_left_over_go_to_the_fee">%1$s sats left over are too few to come back as change, and go to the fee.</string>
|
||||
<string name="too_many_spends_are_open_with_change">The group has too many spends with change waiting for signatures. Wait for one to settle, or send everything.</string>
|
||||
<string name="couldn_t_ask_the_group_to_send">Couldn't ask the group to send.</string>
|
||||
<string name="sending_needs_a_share_and_a_node">Sending needs a share of the group's key, and a wallet of your own on this profile to see the group's coins with.</string>
|
||||
<string name="nothing_leaves_until_a_quorum_signs">Nothing leaves the wallet until a quorum of members has seen this spend and signed it.</string>
|
||||
|
||||
+8
@@ -21,6 +21,7 @@ import com.machankura.bennu.compose.database.model.intermdiate.FrostSignerTally
|
||||
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
|
||||
import com.machankura.bennu.compose.database.model.intermdiate.LocalFrostSigningSession
|
||||
import com.machankura.bennu.compose.managers.FrostSigningManager
|
||||
import com.machankura.bennu.compose.managers.GroupWalletDerivation
|
||||
import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents
|
||||
import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents
|
||||
import com.machankura.bennu.compose.repository.FrostSigningRepository
|
||||
@@ -161,6 +162,13 @@ class DatabaseFrostSigningRepository(
|
||||
emptySet()
|
||||
}
|
||||
|
||||
override suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set<Long> = try {
|
||||
FrostSigningManager.reservedChangeIndices(database, chatRoomId, account)
|
||||
} catch (e: Throwable) {
|
||||
logger.e("Error reading the change addresses reserved in $chatRoomId", e)
|
||||
emptySet()
|
||||
}
|
||||
|
||||
override fun observeGroupTransactions(chatRoomId: String): Flow<List<GroupTransaction>> =
|
||||
database.groupTransactionDao().observeByChatRoomId(chatRoomId)
|
||||
|
||||
|
||||
+22
-2
@@ -866,10 +866,30 @@ object FrostSigningManager {
|
||||
* the coins are still unspent as far as Electrum can say.
|
||||
*/
|
||||
suspend fun reservedOutPoints(database: BennuDatabase, chatRoomId: String): Set<OutPoint> =
|
||||
openSpends(database, chatRoomId)
|
||||
.flatMap { psbt -> psbt.global.tx.txIn.map { it.outPoint } }
|
||||
.toSet()
|
||||
|
||||
/**
|
||||
* The change addresses a room's open spends pay back to, under [account],
|
||||
* which a new spend should not pay to as well. Held by the same sessions as
|
||||
* [reservedOutPoints], for the same reason: until a spend is on chain, its
|
||||
* change address reads as unused, and the next spend would pick it again.
|
||||
*/
|
||||
suspend fun reservedChangeIndices(
|
||||
database: BennuDatabase,
|
||||
chatRoomId: String,
|
||||
account: GroupWalletDerivation.Account,
|
||||
): Set<Long> =
|
||||
openSpends(database, chatRoomId)
|
||||
.flatMap { GroupSpend.claimedChangeIndices(it, account) }
|
||||
.toSet()
|
||||
|
||||
/** The PSBT of every spend in the room whose session has not failed. */
|
||||
private suspend fun openSpends(database: BennuDatabase, chatRoomId: String): List<Psbt> =
|
||||
database.groupTransactionDao().getByChatRoomId(chatRoomId)
|
||||
.filter { database.frostSigningSessionDao().getSessionById(it.frostSigningSessionId)?.stage != FrostSigningStage.FAILED }
|
||||
.flatMap { transaction -> GroupSpend.decode(transaction.psbt)?.global?.tx?.txIn?.map { it.outPoint }.orEmpty() }
|
||||
.toSet()
|
||||
.mapNotNull { GroupSpend.decode(it.psbt) }
|
||||
|
||||
/**
|
||||
* A spend seen confirmed: recorded, and every other spend of the same coins
|
||||
|
||||
+5
@@ -1,6 +1,7 @@
|
||||
package com.machankura.bennu.compose.repository
|
||||
|
||||
import com.machankura.bennu.compose.database.model.GroupTransaction
|
||||
import com.machankura.bennu.compose.managers.GroupWalletDerivation
|
||||
import com.machankura.bennu.compose.wallet.GroupSpend
|
||||
import fr.acinq.bitcoin.Chain
|
||||
import fr.acinq.bitcoin.OutPoint
|
||||
@@ -246,6 +247,9 @@ interface FrostSigningRepository {
|
||||
/** The coins the room's open spends are already spending. */
|
||||
suspend fun reservedOutPoints(chatRoomId: String): Set<OutPoint>
|
||||
|
||||
/** The change indices under [account] the room's open spends already pay back to. */
|
||||
suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set<Long>
|
||||
|
||||
/** Every spend the room has proposed, newest first, as it moves from proposed to confirmed. */
|
||||
fun observeGroupTransactions(chatRoomId: String): Flow<List<GroupTransaction>>
|
||||
|
||||
@@ -326,6 +330,7 @@ interface FrostSigningRepository {
|
||||
override suspend fun checkedSpend(sessionId: String): GroupSpend.Checked? = null
|
||||
|
||||
override suspend fun reservedOutPoints(chatRoomId: String): Set<OutPoint> = emptySet()
|
||||
override suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set<Long> = emptySet()
|
||||
|
||||
override fun observeGroupTransactions(chatRoomId: String): Flow<List<GroupTransaction>> = flowOf(emptyList())
|
||||
|
||||
|
||||
+16
-5
@@ -57,6 +57,8 @@ import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent
|
||||
import com.machankura.bennu.compose.repository.ChatRepository
|
||||
import com.machankura.bennu.compose.repository.FrostSigningRepository
|
||||
import bennu.composeapp.generated.resources.sats_are_whole_numbers
|
||||
import bennu.composeapp.generated.resources.s_sats_left_over_go_to_the_fee
|
||||
import bennu.composeapp.generated.resources.too_many_spends_are_open_with_change
|
||||
import bennu.composeapp.generated.resources.that_is_more_sats_than_there_will_ever_be
|
||||
import bennu.composeapp.generated.resources.that_isn_t_an_amount_in_sats
|
||||
import com.machankura.bennu.compose.text.GroupedSats
|
||||
@@ -208,12 +210,13 @@ fun GroupSendScreen(
|
||||
label = { Text(stringResource(Res.string.feerate_in_sats_per_byte)) },
|
||||
)
|
||||
|
||||
if (state.walletState == null) {
|
||||
LoadingDataIndicator(fillScreen = false, text = stringResource(Res.string.finding_the_group_s_coins))
|
||||
}
|
||||
|
||||
// Still finding change is still finding coins: neither is anything to correct.
|
||||
val preview = groupSendViewModel.preview()
|
||||
preview?.let { SendPreview(it, chain) }
|
||||
if (state.walletState == null || preview == GroupSpendBuilder.Result.FindingChange) {
|
||||
LoadingDataIndicator(fillScreen = false, text = stringResource(Res.string.finding_the_group_s_coins))
|
||||
} else {
|
||||
preview?.let { SendPreview(it, chain) }
|
||||
}
|
||||
|
||||
Text(
|
||||
text = stringResource(Res.string.nothing_leaves_until_a_quorum_signs),
|
||||
@@ -266,6 +269,13 @@ private fun SendPreview(result: GroupSpendBuilder.Result, chain: Chain) {
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (result.absorbed.sat > 0) {
|
||||
Text(
|
||||
text = stringResource(Res.string.s_sats_left_over_go_to_the_fee, result.absorbed.grouped()),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
else -> Text(
|
||||
@@ -274,6 +284,7 @@ private fun SendPreview(result: GroupSpendBuilder.Result, chain: Chain) {
|
||||
stringResource(Res.string.that_isn_t_an_address_on_s, GroupWalletStatementEvent.chainName(chain))
|
||||
GroupSpendBuilder.Result.NothingToSpend -> stringResource(Res.string.the_group_has_nothing_confirmed_to_spend)
|
||||
GroupSpendBuilder.Result.NotEnough -> stringResource(Res.string.the_group_doesn_t_have_that_much_confirmed)
|
||||
GroupSpendBuilder.Result.TooManyOpen -> stringResource(Res.string.too_many_spends_are_open_with_change)
|
||||
is GroupSpendBuilder.Result.OverCap -> stringResource(Res.string.while_the_wallet_is_new_at_most_s_sats, result.cap.grouped())
|
||||
is GroupSpendBuilder.Result.InvalidAmount -> when (result.input) {
|
||||
SatsInput.NotWhole -> stringResource(Res.string.sats_are_whole_numbers)
|
||||
|
||||
+2
-1
@@ -78,6 +78,7 @@ class GroupSendViewModel(
|
||||
wallet = wallet,
|
||||
walletState = null,
|
||||
reserved = frostSigningRepository.reservedOutPoints(chatRoomId),
|
||||
reservedChange = frostSigningRepository.reservedChangeIndices(chatRoomId, wallet.account),
|
||||
)
|
||||
groupSendUIState = ready
|
||||
|
||||
@@ -123,7 +124,7 @@ class GroupSendViewModel(
|
||||
val built = if (amount == null) {
|
||||
GroupSpendBuilder.sendAll(walletState, address, feerate, state.reserved)
|
||||
} else {
|
||||
GroupSpendBuilder.send(walletState, address, amount, feerate, state.reserved)
|
||||
GroupSpendBuilder.send(walletState, address, amount, feerate, state.reserved, state.reservedChange)
|
||||
}
|
||||
return GroupSpendBuilder.capped(built, GroupWalletRollout.capFor(chain))
|
||||
}
|
||||
|
||||
+2
@@ -16,6 +16,8 @@ sealed interface GroupSendUIState {
|
||||
val walletState: GroupWalletState?,
|
||||
/** The coins open spends already hold, which a new one leaves alone. */
|
||||
val reserved: Set<OutPoint>,
|
||||
/** The change indices open spends already pay back to, which a new one pays past. */
|
||||
val reservedChange: Set<Long> = emptySet(),
|
||||
): GroupSendUIState
|
||||
|
||||
/** A room this device cannot propose from -- no wallet, no share, or no node. */
|
||||
|
||||
+23
-4
@@ -87,8 +87,13 @@ class GroupOnchainWallet(
|
||||
*/
|
||||
const val RECEIVE_LOOKAHEAD: UInt = 10u
|
||||
|
||||
/** Change addresses are only ever chosen by a spend, one at a time. */
|
||||
const val CHANGE_LOOKAHEAD: UInt = 3u
|
||||
/**
|
||||
* Change addresses watched, counting the first unused one. Each open
|
||||
* spend with change holds one until it confirms, and several members
|
||||
* can each have one open, so this is how many such spends a group can
|
||||
* have at once before the next is told to wait.
|
||||
*/
|
||||
const val CHANGE_LOOKAHEAD: UInt = 10u
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,8 +145,22 @@ data class GroupWalletState(
|
||||
*/
|
||||
val receiveAddress: String? get() = receive.firstUnusedDerivedAddress?.first
|
||||
|
||||
/** The change index a spend should pay back to, or null until Electrum has answered. */
|
||||
val nextChangeIndex: Long? get() = change.firstUnusedDerivedAddress?.second?.index?.toLong()
|
||||
/** Whether Electrum has answered for any change address yet: before it has, there is no next one to name. */
|
||||
val changeKnown: Boolean get() = change.addresses.values.any { !it.alreadyUsed }
|
||||
|
||||
/**
|
||||
* The change index a spend should pay back to: the lowest this wallet
|
||||
* watches that is unused and not in [reserved] -- the indices open spends
|
||||
* already pay to. Null when there is none: before Electrum has answered,
|
||||
* or when open spends hold every one inside the watched window, past which
|
||||
* change would land on an address nobody is watching.
|
||||
*/
|
||||
fun nextChangeIndex(reserved: Set<Long> = emptySet()): Long? =
|
||||
change.addresses.values
|
||||
.filterNot { it.alreadyUsed }
|
||||
.mapNotNull { it.meta.indexOrNull?.toLong() }
|
||||
.filterNot { it in reserved }
|
||||
.minOrNull()
|
||||
|
||||
/** How many confirmations [utxo] has: 0 in the mempool, and 0 until the tip is known. */
|
||||
fun confirmations(utxo: GroupUtxo): Int {
|
||||
|
||||
@@ -194,6 +194,20 @@ object GroupSpend {
|
||||
return Result.Ok(Checked(account = account, psbt = psbt, inputs = inputs, outputs = outputs, fee = fee, weight = weight))
|
||||
}
|
||||
|
||||
/**
|
||||
* The change indices under [account] that [psbt]'s outputs claim: what an
|
||||
* open spend holds, so the next one pays its change somewhere else. Claims,
|
||||
* not checked derivations -- a spend this device would refuse still keeps
|
||||
* its index from being handed out twice, and holding one too many costs
|
||||
* nothing.
|
||||
*/
|
||||
fun claimedChangeIndices(psbt: Psbt, account: GroupWalletDerivation.Account): Set<Long> =
|
||||
psbt.outputs
|
||||
.flatMap { it.taprootDerivationPaths.values }
|
||||
.filter { it.masterKeyFingerprint == account.fingerprint }
|
||||
.mapNotNull { path -> path.keyPath.path.takeIf { it.size == 2 && it[0] == GroupWalletDerivation.CHANGE }?.get(1) }
|
||||
.toSet()
|
||||
|
||||
/**
|
||||
* The one derivation under [account] a PSBT field names, or null when it names
|
||||
* none, several, or one this wallet will not walk.
|
||||
|
||||
+23
-6
@@ -28,9 +28,20 @@ object GroupSpendBuilder {
|
||||
val DUST: Satoshi = Satoshi(546)
|
||||
|
||||
sealed interface Result {
|
||||
data class Built(val psbt: Psbt, val amount: Satoshi, val fee: Satoshi, val change: Satoshi?) : Result
|
||||
data class Built(
|
||||
val psbt: Psbt,
|
||||
val amount: Satoshi,
|
||||
val fee: Satoshi,
|
||||
val change: Satoshi?,
|
||||
/** What [fee] holds beyond the feerate: change too small to send back, paid to the miner instead. */
|
||||
val absorbed: Satoshi = Satoshi(0),
|
||||
) : Result
|
||||
data object NotAnAddress : Result
|
||||
data object NothingToSpend : Result
|
||||
/** Electrum has not yet said which change addresses are used, so there is none to name. */
|
||||
data object FindingChange : Result
|
||||
/** Open spends already pay change to every change address the wallet watches. */
|
||||
data object TooManyOpen : Result
|
||||
data object NotEnough : Result
|
||||
data object BelowDust : Result
|
||||
/** A bump has to pay more than the spend it replaces. */
|
||||
@@ -65,7 +76,8 @@ object GroupSpendBuilder {
|
||||
|
||||
/**
|
||||
* [amount] to [address], largest coins first, with what is left over paid
|
||||
* back to the next change address -- or to fees, when it would be dust.
|
||||
* back to the next change address no open spend holds -- or to fees, when
|
||||
* it would be dust.
|
||||
*/
|
||||
fun send(
|
||||
state: GroupWalletState,
|
||||
@@ -73,14 +85,16 @@ object GroupSpendBuilder {
|
||||
amount: Satoshi,
|
||||
feeratePerVbyte: Long,
|
||||
reserved: Set<OutPoint>,
|
||||
reservedChange: Set<Long> = emptySet(),
|
||||
): Result {
|
||||
val script = scriptOf(state, address) ?: return Result.NotAnAddress
|
||||
if (amount < DUST) return Result.BelowDust
|
||||
val changeIndex = state.nextChangeIndex ?: return Result.NothingToSpend
|
||||
val change = GroupWalletDerivation.derive(state.account, GroupWalletDerivation.CHANGE, changeIndex)
|
||||
|
||||
val coins = spendable(state, reserved).sortedByDescending { it.amount.sat }.ifEmpty { return Result.NothingToSpend }
|
||||
|
||||
if (!state.changeKnown) return Result.FindingChange
|
||||
val changeIndex = state.nextChangeIndex(reservedChange) ?: return Result.TooManyOpen
|
||||
val change = GroupWalletDerivation.derive(state.account, GroupWalletDerivation.CHANGE, changeIndex)
|
||||
|
||||
val chosen = mutableListOf<GroupUtxo>()
|
||||
for (coin in coins) {
|
||||
chosen += coin
|
||||
@@ -97,7 +111,10 @@ object GroupSpendBuilder {
|
||||
val withoutChange = feeOf(chosen, listOf(script), feeratePerVbyte)
|
||||
if (total - amount >= withoutChange) {
|
||||
val tx = transaction(chosen, listOf(TxOut(amount, script)))
|
||||
return Result.Built(psbtOf(state, tx, chosen, emptyMap()), amount, total - amount, change = null)
|
||||
return Result.Built(
|
||||
psbtOf(state, tx, chosen, emptyMap()), amount, total - amount, change = null,
|
||||
absorbed = total - amount - withoutChange,
|
||||
)
|
||||
}
|
||||
}
|
||||
return Result.NotEnough
|
||||
|
||||
Reference in new issue
Block a user