feat(db): schema 30 keeps a member wallet's key and its spends (Phase 5)

MemberWallet holds the random key of a guarded wallet one member holds
and a group guards, with the request that asked for it; MemberWalletSpend
the transactions the member signed alone. Whether a wallet is certified
is read off the group's signed events each time, so there is no column
for it. Neither table has a foreign key: deleting a group's room on this
device must never delete a key that coins may sit behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-10-24 07:27:33 +02:00
1 parent 52390e27cf
commit d6c2b1b20e
6 files changed
+4983 -1

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -2,6 +2,7 @@ package com.machankura.bennu.compose.database
import com.machankura.bennu.compose.database.model.GroupTransaction
import com.machankura.bennu.compose.database.dao.GroupTransactionDao
import com.machankura.bennu.compose.database.dao.MemberWalletDao
import androidx.room3.ColumnTypeConverters
import androidx.room3.AutoMigration
import androidx.room3.ConstructedBy
@@ -78,6 +79,8 @@ import com.machankura.bennu.compose.database.model.MarmotPublishObligation
import com.machankura.bennu.compose.database.model.MarmotOutboundGate
import com.machankura.bennu.compose.managers.MarmotEngine
import com.machankura.bennu.compose.database.model.MarmotRetainedEpochSecret
import com.machankura.bennu.compose.database.model.MemberWallet
import com.machankura.bennu.compose.database.model.MemberWalletSpend
import com.machankura.bennu.compose.database.model.Mention
import com.machankura.bennu.compose.database.model.NegentropySynchronizeRequest
import com.machankura.bennu.compose.database.model.NegentropySynchronizeResult
@@ -135,6 +138,8 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
MarmotPublishObligation::class,
MarmotOutboundGate::class,
MarmotRetainedEpochSecret::class,
MemberWallet::class,
MemberWalletSpend::class,
Mention::class,
NegentropySynchronizeRequest::class,
NegentropySynchronizeResult::class,
@@ -153,7 +158,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
UnsignedNostrEvent::class,
Zap::class
],
version = 29,
version = 30,
autoMigrations = [
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
// generate the migration itself — nothing existing changes shape.
@@ -355,6 +360,12 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
// subgroup's ceremony was proposed under (docs/subgroup-wallet-policy.md,
// Phase 2). Every ceremony before it chose none, which is what null means.
AutoMigration(from = 28, to = 29),
// v30 adds MemberWallet and MemberWalletSpend: the random key of a
// guarded wallet one member holds and a group guards, and the spends the
// member signed alone from it (docs/member-guarded-wallets.md, Phase 5).
// New tables, and no foreign keys -- deleting a group's room must never
// delete a key coins may sit behind.
AutoMigration(from = 29, to = 30),
]
)
@ConstructedBy(BennuDatabaseConstructor::class)
@@ -391,6 +402,8 @@ abstract class BennuDatabase: RoomDatabase() {
abstract fun groupTransactionDao(): GroupTransactionDao
abstract fun memberWalletDao(): MemberWalletDao
abstract fun connectionDao(): ConnectionDao
abstract fun giftWrapMessageDao(): GiftWrapMessageDao
@@ -0,0 +1,46 @@
package com.machankura.bennu.compose.database.dao
import androidx.room3.Dao
import androidx.room3.Query
import androidx.room3.Upsert
import com.machankura.bennu.compose.database.model.MemberWallet
import com.machankura.bennu.compose.database.model.MemberWalletSpend
import kotlinx.coroutines.flow.Flow
@Dao
abstract class MemberWalletDao {
@Query("SELECT * FROM MemberWallet WHERE ownerPublicKey = :ownerPublicKey ORDER BY createdAt DESC")
abstract suspend fun getByOwner(ownerPublicKey: String): List<MemberWallet>
@Query("SELECT * FROM MemberWallet WHERE ownerPublicKey = :ownerPublicKey ORDER BY createdAt DESC")
abstract fun observeByOwner(ownerPublicKey: String): Flow<List<MemberWallet>>
@Query("SELECT * FROM MemberWallet WHERE walletId = :walletId")
abstract suspend fun getById(walletId: String): MemberWallet?
@Query("SELECT * FROM MemberWallet WHERE guardingChatRoomId = :chatRoomId ORDER BY createdAt DESC")
abstract suspend fun getByGuardingChatRoomId(chatRoomId: String): List<MemberWallet>
@Upsert
abstract suspend fun upsert(wallet: MemberWallet)
/**
* Deletes a wallet's key. `MemberWalletManager.discard` is the only caller,
* and only for a wallet no group has certified: before then no address was
* ever offered, so no coin can be behind the key.
*/
@Query("DELETE FROM MemberWallet WHERE walletId = :walletId")
abstract suspend fun delete(walletId: String)
@Query("SELECT * FROM MemberWalletSpend WHERE walletId = :walletId ORDER BY createdAt DESC")
abstract suspend fun getSpends(walletId: String): List<MemberWalletSpend>
@Query("SELECT * FROM MemberWalletSpend WHERE walletId = :walletId ORDER BY createdAt DESC")
abstract fun observeSpends(walletId: String): Flow<List<MemberWalletSpend>>
@Query("SELECT * FROM MemberWalletSpend WHERE txid = :txid")
abstract suspend fun getSpend(txid: String): MemberWalletSpend?
@Upsert
abstract suspend fun upsertSpend(spend: MemberWalletSpend)
}
@@ -0,0 +1,68 @@
package com.machankura.bennu.compose.database.model
import androidx.room3.Entity
import androidx.room3.Index
import androidx.room3.PrimaryKey
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlin.time.Clock
import kotlin.time.Instant
/**
* A guarded wallet this device holds the key of: one member's random key, and
* the request that asked a group to guard it. `docs/member-guarded-wallets.md`.
*
* The key is why there is a table at all. Everything else about a member's
* wallet is read off signed events -- whether it is certified is whether the
* group's room holds a 30334 for [walletId] that verifies, read again each time
* the way `GroupWallet` reads statements -- so there is no *certified* column to
* disagree with the signature.
*
* ### `guardingChatRoomId` is a plain column, never a foreign key
*
* The argument `docs/subgroups.md` makes against cascading `parentChatRoomId`,
* with money at the end of it. Deleting the group's room on this device must
* never delete a private key that coins may sit behind; and a member who leaves
* the group keeps a wallet the group still guards.
*
* ### One database holds every profile
*
* So every read is scoped by [ownerPublicKey], the profile the key belongs to.
*/
@Entity(
indices = [
Index("ownerPublicKey"),
Index("guardingChatRoomId"),
],
)
data class MemberWallet(
/** `W`: `MemberWalletDerivation.walletId` of the wallet key. */
@PrimaryKey
val walletId: String,
/** The profile the wallet belongs to: the npub that signed the request. */
val ownerPublicKey: HexKey,
/** The group asked to guard it. */
val guardingChatRoomId: String,
/** The network, as `GroupWalletStatementEvent.chainName` writes it. */
val chain: String,
/**
* `k`, hex. Stored as `DkgSession.secretShare` is, in the profile's database;
* never logged, never sent. Lost with the device unless exported -- and then
* the guardians can still move the coins after 12 blocks.
*/
val walletPrivateKey: HexKey,
/** The member's name for it, as the request carries it. */
val label: String? = null,
/** The signed 30335, whole: kept so a request the group did not sign can be asked again, unchanged. */
val requestJson: String,
val createdAt: Instant = Clock.System.now(),
) {
override fun toString(): String =
"MemberWallet(walletId=$walletId, owner=$ownerPublicKey, guardedBy=$guardingChatRoomId, chain=$chain, key=<redacted>)"
}
@@ -0,0 +1,53 @@
package com.machankura.bennu.compose.database.model
import androidx.room3.Entity
import androidx.room3.Index
import androidx.room3.PrimaryKey
import kotlin.time.Clock
import kotlin.time.Instant
/**
* One transaction a member signed alone from their guarded wallet.
*
* The subset of [GroupTransaction] a spend with no signing session needs.
* `GroupTransaction` cannot hold it: its foreign keys are to a session and a
* room, and a member's own spend has neither. Written whole when it is signed,
* then filled in as the chain answers.
*
* No foreign key to [MemberWallet] either. A spend is a fact about the chain,
* and a row that cascaded away with its wallet would take the record of where
* the coins went with it.
*/
@Entity(
indices = [
Index("walletId"),
],
)
data class MemberWalletSpend(
/** The transaction's id, which a segwit spend fixes before it is signed. */
@PrimaryKey
val txid: String,
/** `W`, the wallet the inputs are under. */
val walletId: String,
/** The PSBT as built, base64: what every input's sighash was computed from. */
val psbt: String,
/** The finished transaction, hex, once it has passed `correctlySpends`. */
val signedTransaction: String,
/** When this device last handed it to Electrum -- which reports success whatever the server said. */
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(),
)
@@ -0,0 +1,76 @@
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.MemberWallet
import com.machankura.bennu.compose.database.model.MemberWalletSpend
import com.machankura.bennu.compose.managers.GroupFixtures
import kotlinx.coroutines.runBlocking
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.time.Instant
/**
* Schema 30's two tables round-trip, are scoped by profile, and -- the property
* that matters most -- outlive the room of the group that guards them.
*/
class MemberWalletDaoJvmTest {
private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder<BennuDatabase>())
@AfterTest
fun closeDb() = db.close()
private val group = "6a".repeat(32)
private val alice = "a1".repeat(32)
private val bob = "b0".repeat(32)
private fun wallet(id: String, owner: String = alice) = MemberWallet(
walletId = id,
ownerPublicKey = owner,
guardingChatRoomId = group,
chain = "regtest",
walletPrivateKey = "11".repeat(32),
label = "Savings",
requestJson = "{}",
createdAt = Instant.fromEpochSeconds(1_700_000_000),
)
@Test
fun `a wallet round-trips and is listed for its owner only`(): Unit = runBlocking {
val dao = db.memberWalletDao()
dao.upsert(wallet("01".repeat(32)))
dao.upsert(wallet("02".repeat(32), owner = bob))
assertEquals(wallet("01".repeat(32)), dao.getById("01".repeat(32)))
assertEquals(listOf("01".repeat(32)), dao.getByOwner(alice).map { it.walletId })
assertEquals(2, dao.getByGuardingChatRoomId(group).size)
assertFalse(wallet("01".repeat(32)).toString().contains("11".repeat(32)), "the key is never in a log line")
}
@Test
fun `deleting the group's room leaves the key`(): Unit = runBlocking {
GroupFixtures.seedRoom(db, group)
db.memberWalletDao().upsert(wallet("01".repeat(32)))
db.chatRoomDao().delete(assertNotNull(db.chatRoomDao().findChatRoomById(group)).chatRoom)
assertNull(db.chatRoomDao().findChatRoomById(group))
assertNotNull(db.memberWalletDao().getById("01".repeat(32)))
}
@Test
fun `a spend round-trips and is filled in`(): Unit = runBlocking {
val dao = db.memberWalletDao()
val spend = MemberWalletSpend(txid = "aa".repeat(32), walletId = "01".repeat(32), psbt = "cHNidP8=", signedTransaction = "00")
dao.upsertSpend(spend)
dao.upsertSpend(spend.copy(seenAt = Instant.fromEpochSeconds(1_700_000_100)))
assertEquals(Instant.fromEpochSeconds(1_700_000_100), dao.getSpend("aa".repeat(32))?.seenAt)
assertEquals(1, dao.getSpends("01".repeat(32)).size)
}
}