feat(wallet): schema v26 for spends from a group's wallet (Phase 6)
FrostSigningSession.subject, NOT NULL with a default of EVENTS, says what a session's items are messages of; FrostSigningItem.inputIndex names the input a transaction item signs, with message and payload as getters over the existing columns. GroupTransaction holds a spend from proposal on: the PSBT, written once with IGNORE, the txid fixed before signing, and the signed transaction, broadcast, seen and confirmed. AutoMigration(25, 26) is three ADD COLUMNs and a CREATE TABLE -- no rebuild of either signing table, so no cascade fires. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
24d06d2eee
commit
f7a9e05bbc
9 files changed
+6316
-1
No files matched your search
File diff suppressed because it is too large.
Load diff
+13
-1
@@ -1,5 +1,7 @@
|
||||
package com.machankura.bennu.compose.database
|
||||
|
||||
import com.machankura.bennu.compose.database.model.GroupTransaction
|
||||
import com.machankura.bennu.compose.database.dao.GroupTransactionDao
|
||||
import androidx.room3.ColumnTypeConverters
|
||||
import androidx.room3.AutoMigration
|
||||
import androidx.room3.ConstructedBy
|
||||
@@ -147,6 +149,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
|
||||
GiftWrapPayload::class,
|
||||
GroupKeyState::class,
|
||||
GroupSignedEvent::class,
|
||||
GroupTransaction::class,
|
||||
InReplyToRelation::class,
|
||||
MantraArtifact::class,
|
||||
MantraArtifactVersion::class,
|
||||
@@ -187,7 +190,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
|
||||
UnsignedNostrEvent::class,
|
||||
Zap::class
|
||||
],
|
||||
version = 25,
|
||||
version = 26,
|
||||
autoMigrations = [
|
||||
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
|
||||
// generate the migration itself — nothing existing changes shape.
|
||||
@@ -368,6 +371,13 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
|
||||
// backfilled -- a session that has never been resent reads null, which
|
||||
// is what every session before the column was.
|
||||
AutoMigration(from = 24, to = 25),
|
||||
// v26 is the group wallet's spends (docs/group-chain-wallet.md, Phase 6):
|
||||
// the GroupTransaction table, FrostSigningSession.subject -- NOT NULL with
|
||||
// a default of EVENTS, which is what every session before it was -- and
|
||||
// the nullable FrostSigningItem.inputIndex. Nothing is backfilled and
|
||||
// nothing is rebuilt; a rebuild of either signing table would fire the
|
||||
// cascades from FrostSigningSession, see docs/frost-batch-signing.md.
|
||||
AutoMigration(from = 25, to = 26),
|
||||
]
|
||||
)
|
||||
@ConstructedBy(BennuDatabaseConstructor::class)
|
||||
@@ -402,6 +412,8 @@ abstract class BennuDatabase: RoomDatabase() {
|
||||
|
||||
abstract fun groupSignedEventDao(): GroupSignedEventDao
|
||||
|
||||
abstract fun groupTransactionDao(): GroupTransactionDao
|
||||
|
||||
abstract fun connectionDao(): ConnectionDao
|
||||
|
||||
abstract fun giftWrapMessageDao(): GiftWrapMessageDao
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.machankura.bennu.compose.database.dao
|
||||
|
||||
import androidx.room3.Dao
|
||||
import androidx.room3.Insert
|
||||
import androidx.room3.OnConflictStrategy
|
||||
import androidx.room3.Query
|
||||
import androidx.room3.Upsert
|
||||
import com.machankura.bennu.compose.database.model.GroupTransaction
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
abstract class GroupTransactionDao {
|
||||
@Query("SELECT * FROM GroupTransaction WHERE frostSigningSessionId = :sessionId")
|
||||
abstract suspend fun getBySessionId(sessionId: String): GroupTransaction?
|
||||
|
||||
@Query("SELECT * FROM GroupTransaction WHERE frostSigningSessionId = :sessionId")
|
||||
abstract fun observeBySessionId(sessionId: String): Flow<GroupTransaction?>
|
||||
|
||||
@Query("SELECT * FROM GroupTransaction WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC")
|
||||
abstract suspend fun getByChatRoomId(chatRoomId: String): List<GroupTransaction>
|
||||
|
||||
@Query("SELECT * FROM GroupTransaction WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC")
|
||||
abstract fun observeByChatRoomId(chatRoomId: String): Flow<List<GroupTransaction>>
|
||||
|
||||
/**
|
||||
* The first write, at proposal or acceptance. Ignores a second: the PSBT is
|
||||
* write-once, and a row for this session already holds the one every item's
|
||||
* sighash was computed from.
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.IGNORE)
|
||||
abstract suspend fun insertIfAbsent(transaction: GroupTransaction): Long
|
||||
|
||||
/** Every later write -- signed, broadcast, seen, confirmed -- over the row [insertIfAbsent] made. */
|
||||
@Upsert
|
||||
abstract suspend fun upsert(transaction: GroupTransaction)
|
||||
}
|
||||
+28
@@ -82,7 +82,35 @@ data class FrostSigningItem(
|
||||
|
||||
/** Result: the finished 64-byte BIP-340 signature over [eventId], hex. */
|
||||
val signature: HexKey? = null,
|
||||
|
||||
/**
|
||||
* For a [com.machankura.bennu.compose.database.model.types.FrostSigningSubject.TRANSACTION]
|
||||
* session, the transaction input this item signs; null for an event.
|
||||
*
|
||||
* Equal to [itemIndex] whenever it is set -- a transaction's items are its
|
||||
* inputs, in input order -- and stored anyway, so that what an item is
|
||||
* signing does not depend on a convention two pieces of code have to keep.
|
||||
*/
|
||||
val inputIndex: Int? = null,
|
||||
) {
|
||||
/** Whether the group has produced this item's signature. */
|
||||
fun isSigned(): Boolean = signature != null
|
||||
|
||||
/**
|
||||
* The 32 bytes this item's nonce is committed to: an event id, or a BIP341
|
||||
* sighash. [eventId] under the name that is true of both.
|
||||
*
|
||||
* An alias and not a renamed column. `eventId` is spelled the same way in
|
||||
* thirty files that have nothing to do with this table, and a rename that a
|
||||
* search-and-replace cannot tell apart from them is a rename that is not
|
||||
* worth the column it would save.
|
||||
*/
|
||||
val message: HexKey get() = eventId
|
||||
|
||||
/**
|
||||
* What [message] was computed from: the unsigned event, or the input's place
|
||||
* under the wallet's account as `{"change":1,"index":4}`. [unsignedEventJson]
|
||||
* under the name that is true of both.
|
||||
*/
|
||||
val payload: String get() = unsignedEventJson
|
||||
}
|
||||
+14
@@ -1,5 +1,7 @@
|
||||
package com.machankura.bennu.compose.database.model
|
||||
|
||||
import androidx.room3.ColumnInfo
|
||||
import com.machankura.bennu.compose.database.model.types.FrostSigningSubject
|
||||
import androidx.room3.Entity
|
||||
import androidx.room3.ForeignKey
|
||||
import androidx.room3.Index
|
||||
@@ -167,6 +169,18 @@ data class FrostSigningSession(
|
||||
*/
|
||||
val resentAt: Instant? = null,
|
||||
|
||||
/**
|
||||
* What this session's items are messages of: events, or the inputs of one
|
||||
* transaction from the group's wallet.
|
||||
*
|
||||
* Written at proposal and never again. Every session before the column reads
|
||||
* back as [FrostSigningSubject.EVENTS], which is what they all were, and a
|
||||
* build that predates it never sees a transaction session at all -- the
|
||||
* proposal travels on a kind that build does not route.
|
||||
*/
|
||||
@ColumnInfo(defaultValue = "EVENTS")
|
||||
val subject: FrostSigningSubject = FrostSigningSubject.EVENTS,
|
||||
|
||||
override val createdAt: Instant = Clock.System.now(),
|
||||
override val updatedAt: Instant = createdAt,
|
||||
override val savedAt: Instant = createdAt,
|
||||
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package com.machankura.bennu.compose.database.model
|
||||
|
||||
import androidx.room3.Entity
|
||||
import androidx.room3.ForeignKey
|
||||
import androidx.room3.Index
|
||||
import androidx.room3.PrimaryKey
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* One transaction from a group's wallet, from the moment it is proposed.
|
||||
*
|
||||
* Written whole at acceptance and then filled in: the signed transaction when
|
||||
* the session completes, and when it was broadcast and seen confirmed after.
|
||||
* It can be written whole because a segwit txid excludes the witnesses -- the
|
||||
* [txid] is fixed before anybody signs, and it is what the transcript, the
|
||||
* proposal list and the chain all key on.
|
||||
*/
|
||||
@Entity(
|
||||
foreignKeys = [
|
||||
ForeignKey(
|
||||
entity = FrostSigningSession::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["frostSigningSessionId"],
|
||||
onDelete = ForeignKey.CASCADE,
|
||||
),
|
||||
ForeignKey(
|
||||
entity = ChatRoom::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["chatRoomId"],
|
||||
onDelete = ForeignKey.CASCADE,
|
||||
),
|
||||
],
|
||||
indices = [
|
||||
Index("chatRoomId"),
|
||||
Index("txid"),
|
||||
],
|
||||
)
|
||||
data class GroupTransaction(
|
||||
@PrimaryKey
|
||||
val frostSigningSessionId: String,
|
||||
|
||||
val chatRoomId: String,
|
||||
|
||||
/** The network, as `GroupWalletStatementEvent.chainName` writes it. */
|
||||
val chain: String,
|
||||
|
||||
/** The wallet account the inputs are under. From the room's statement, never from the proposal. */
|
||||
val account: Long,
|
||||
|
||||
/**
|
||||
* The PSBT as proposed, base64. Write-once: it is what every item's sighash
|
||||
* was computed from, and a second proposal under the same session id that
|
||||
* differs anywhere in its unsigned transaction is ignored.
|
||||
*/
|
||||
val psbt: String,
|
||||
|
||||
/** The unsigned transaction's id -- which is the signed one's too. */
|
||||
val txid: String,
|
||||
|
||||
/** The finished transaction, hex, once the session completes and it has passed `correctlySpends`. */
|
||||
val signedTransaction: String? = null,
|
||||
|
||||
/**
|
||||
* When this device last handed it to Electrum. Not when it reached the
|
||||
* network: Electrum's broadcast reports success whatever the server said,
|
||||
* so [seenAt] is the only evidence that it did.
|
||||
*/
|
||||
val broadcastAt: Instant? = null,
|
||||
|
||||
/** When this device's wallet first saw the transaction -- in the mempool or in a block. */
|
||||
val seenAt: Instant? = null,
|
||||
|
||||
/** When its first confirmation was seen. */
|
||||
val confirmedAt: Instant? = null,
|
||||
|
||||
/** The txid of a later spend of the same coins that confirmed instead, if one did. */
|
||||
val replacedByTxid: String? = null,
|
||||
|
||||
val createdAt: Instant = Clock.System.now(),
|
||||
)
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.machankura.bennu.compose.database.model.types
|
||||
|
||||
/**
|
||||
* What a signing session's items are messages *of*.
|
||||
*
|
||||
* A column rather than an inference. A session could be recognised as a
|
||||
* transaction by the presence of its `GroupTransaction` row, and the code that
|
||||
* decides what a nonce is committed to should not be a join away from the answer.
|
||||
*/
|
||||
enum class FrostSigningSubject {
|
||||
/** Nostr events: each item's message is an event id, its payload the unsigned event. */
|
||||
EVENTS,
|
||||
|
||||
/**
|
||||
* One bitcoin transaction from the group's wallet: each item is one input, its
|
||||
* message that input's BIP341 sighash, its payload where under the wallet's
|
||||
* account the coin it spends is.
|
||||
*/
|
||||
TRANSACTION,
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
package com.machankura.bennu.compose.database.dao
|
||||
|
||||
import androidx.room3.Room
|
||||
import com.machankura.bennu.compose.database.BennuDatabase
|
||||
import com.machankura.bennu.compose.database.builder.getRoomDatabase
|
||||
import com.machankura.bennu.compose.database.model.ChatRoom
|
||||
import com.machankura.bennu.compose.database.model.FrostSigningItem
|
||||
import com.machankura.bennu.compose.database.model.FrostSigningSession
|
||||
import com.machankura.bennu.compose.database.model.GroupTransaction
|
||||
import com.machankura.bennu.compose.database.model.NostrEvent
|
||||
import com.machankura.bennu.compose.database.model.Profile
|
||||
import com.machankura.bennu.compose.database.model.types.FrostSigningSubject
|
||||
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlin.test.AfterTest
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* A spend from the group's wallet, as the database holds it: a signing session
|
||||
* whose subject is a transaction, one item per input, and the transaction row
|
||||
* beside it.
|
||||
*
|
||||
* The write-once property is the one worth pinning. The PSBT is what every
|
||||
* item's sighash was computed from, so a second write at acceptance -- a
|
||||
* redelivered proposal, or a different one under the same session id -- must
|
||||
* leave the first in place.
|
||||
*/
|
||||
class GroupTransactionDaoJvmTest {
|
||||
private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder<BennuDatabase>())
|
||||
|
||||
@AfterTest
|
||||
fun closeDb() = db.close()
|
||||
|
||||
private val user = KeyPair().pubKey.toHexKey()
|
||||
private val room = "11".repeat(32)
|
||||
|
||||
private suspend fun seedRoom() {
|
||||
val nostrEventId = "c".repeat(64)
|
||||
db.nostrEventDao().upsert(NostrEvent(id = nostrEventId, pubKey = user, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
|
||||
db.profileDao().upsert(Profile(publicKey = user, userName = "user", nostrEventId = nostrEventId))
|
||||
db.chatRoomDao().upsert(ChatRoom(id = room, userPublicKey = user, subject = null, description = null, mlsGroupState = null))
|
||||
}
|
||||
|
||||
private suspend fun spend(id: String, inputs: Int = 2): FrostSigningSession {
|
||||
val session = FrostSigningSession(
|
||||
id = id,
|
||||
chatRoomId = room,
|
||||
coordinatorPublicKey = user,
|
||||
userPublicKey = user,
|
||||
dkgSessionId = "dkg-1",
|
||||
threshold = 2,
|
||||
participantCount = 3,
|
||||
signerId = 0,
|
||||
subject = FrostSigningSubject.TRANSACTION,
|
||||
createdAt = Instant.fromEpochSeconds(1_000),
|
||||
)
|
||||
db.frostSigningSessionDao().upsert(session)
|
||||
db.frostSigningSessionDao().upsertItems(
|
||||
(0 until inputs).map { input ->
|
||||
FrostSigningItem(
|
||||
sessionId = id,
|
||||
itemIndex = input,
|
||||
unsignedEventJson = """{"change":0,"index":$input}""",
|
||||
eventId = input.toString().repeat(64).take(64),
|
||||
nonceRandom = "${input + 1}".repeat(64).take(64),
|
||||
inputIndex = input,
|
||||
)
|
||||
}
|
||||
)
|
||||
return session
|
||||
}
|
||||
|
||||
private fun transaction(sessionId: String, psbt: String = "cHNidP8=", txid: String = "ab".repeat(32)) = GroupTransaction(
|
||||
frostSigningSessionId = sessionId,
|
||||
chatRoomId = room,
|
||||
chain = "regtest",
|
||||
account = 0,
|
||||
psbt = psbt,
|
||||
txid = txid,
|
||||
createdAt = Instant.fromEpochSeconds(1_000),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `a transaction session reads back as one, with an item per input`() = runBlocking {
|
||||
seedRoom()
|
||||
spend("spend-1")
|
||||
|
||||
val session = assertNotNull(db.frostSigningSessionDao().getSessionById("spend-1"))
|
||||
assertEquals(FrostSigningSubject.TRANSACTION, session.subject)
|
||||
|
||||
val items = db.frostSigningSessionDao().getItems("spend-1")
|
||||
assertEquals(listOf(0, 1), items.map { it.inputIndex })
|
||||
assertEquals("""{"change":0,"index":1}""", items[1].payload)
|
||||
assertEquals(items[1].eventId, items[1].message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an event session written without a subject is an event session`() = runBlocking {
|
||||
seedRoom()
|
||||
db.frostSigningSessionDao().upsert(
|
||||
FrostSigningSession(
|
||||
id = "events-1", chatRoomId = room, coordinatorPublicKey = user, userPublicKey = user,
|
||||
dkgSessionId = "dkg-1", threshold = 2, participantCount = 3, signerId = 0,
|
||||
)
|
||||
)
|
||||
|
||||
assertEquals(FrostSigningSubject.EVENTS, db.frostSigningSessionDao().getSessionById("events-1")?.subject)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the proposed psbt is written once`() = runBlocking {
|
||||
seedRoom()
|
||||
spend("spend-1")
|
||||
|
||||
db.groupTransactionDao().insertIfAbsent(transaction("spend-1", psbt = "first"))
|
||||
db.groupTransactionDao().insertIfAbsent(transaction("spend-1", psbt = "second"))
|
||||
|
||||
assertEquals("first", db.groupTransactionDao().getBySessionId("spend-1")?.psbt)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `later writes fill the row in`() = runBlocking {
|
||||
seedRoom()
|
||||
spend("spend-1")
|
||||
db.groupTransactionDao().insertIfAbsent(transaction("spend-1"))
|
||||
|
||||
val signed = db.groupTransactionDao().getBySessionId("spend-1")!!
|
||||
.copy(signedTransaction = "02000000", broadcastAt = Instant.fromEpochSeconds(2_000))
|
||||
db.groupTransactionDao().upsert(signed)
|
||||
|
||||
assertEquals(signed, db.groupTransactionDao().getBySessionId("spend-1"))
|
||||
assertEquals(listOf(signed), db.groupTransactionDao().getByChatRoomId(room))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a room's transactions go with it`() = runBlocking {
|
||||
seedRoom()
|
||||
spend("spend-1")
|
||||
db.groupTransactionDao().insertIfAbsent(transaction("spend-1"))
|
||||
|
||||
// @Delete matches on the primary key, so the row as it was seeded is enough.
|
||||
db.chatRoomDao().delete(ChatRoom(id = room, userPublicKey = user, subject = null, description = null, mlsGroupState = null))
|
||||
|
||||
assertNull(db.groupTransactionDao().getBySessionId("spend-1"))
|
||||
assertEquals(emptyList(), db.frostSigningSessionDao().getItems("spend-1"))
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,8 @@ kept as written; where the build chose differently the table below says so.
|
||||
| members who can sign see *Open a group wallet* on the group's screen; others see nothing | every member sees a *Group wallet* row, saying *Open on mainnet* or *Not opened yet*; the open action lives on the wallet screen's empty state, behind the same `canSign` gate, with Phase 10's sentence about unencrypted shares above the button |
|
||||
| the wallet's network is the identity's | `NodeParamsManager.chain`, read statically. An nsec or npub profile has no node, and still has to know which network's statement to look for |
|
||||
| `GroupChainWallets` started under the identity's `collectLatest` | made in `BennuNavHost`, remembered on the identity's `PhoenixBusiness` and stopped in a `DisposableEffect` when it changes — the same lifetime, held where the business already is |
|
||||
| `FrostSigningItem.eventId` and `unsignedEventJson` renamed in Kotlin to `message` and `payload` with `@ColumnInfo(name = …)` | not renamed: `message` and `payload` are getters over them. `eventId` is spelled the same way in thirty files that have nothing to do with this table, and a rename a search cannot tell apart from them is not worth what it would tidy |
|
||||
| `GroupTransaction` has `broadcastAt` and `confirmedAt` | and `seenAt`, because Electrum's broadcast reports success whatever the server said: sent and seen are the two facts there are, and confirmed is a third. Inserted with `IGNORE` so the proposed PSBT is write-once at the database, not only in the manager |
|
||||
|
||||
The headline: **the best path is BIP86's own unhardened tail, `/<change>/<index>`,
|
||||
hung under an account key the group's threshold key is tweaked to, with the
|
||||
|
||||
Reference in new issue
Block a user