From 7b2e23188418b0a8bf13a75c9b1b13fda2235da9 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Mon, 19 Oct 2026 10:26:48 -0700 Subject: [PATCH 1/3] feat(dashpay): contested username fee follows the Platform protocol version (#1583) * feat(dashpay): contested username fee follows the Platform protocol version (MO-1067) Platform protocol version 14 (v4.2) lowers the prefunded voting balance a contested username pays from 0.2 to 0.1 DASH, so creating an identity with a contested name drops from 0.25 to 0.15 DASH. ContestedUsernameFees replaces the DASH_PAY_FEE_CONTESTED(_NAME) constants and derives both fees from the protocol version learned via the new PlatformRepo.refreshProtocolVersion() (dash-sdk 4.2.0-SNAPSHOT). The version is refreshed when the username/invite screens open and right before CreateIdentityService sizes the asset lock. Until it is known, the higher pre-v14 fees apply: over-funding only leaves identity credits, while under-funding would make the registration fail. The "You need to have 0.25 DASH" requirement text was hardcoded in every locale; it now takes the fee as an argument (and shows the non-contested fee for non-contested names). Co-Authored-By: Claude Opus 5.5 * chore: update Platform SDK to 5.0.0-SNAPSHOT * fix: refresh username affordability and amounts when protocol fees change * fix: refresh invitation labels without delaying non-contested invites * feat: configure wallet devnet flavor for Sakura * fix(dashpay): dark mode text in the create username confirmation dialog OffsetDialog parented from Theme.Design.Light.BottomSheetDialog with no values-night override, so android:textColorPrimary inside every offset bottom sheet stayed the light theme near-black. The sheet background already follows the night palette via @color/background_secondary, which left any view that relies on the theme for its colour dark-on-dark. Most TextViews escaped this because their style sets android:textColor="@color/content_primary", a colour resource that does have a night variant. The confirmation message and the "I accept" label in dialog_confirm_username_request carried no style at all, fell through to the theme, and rendered black on the dark sheet. Base.OffsetDialog now holds the parent and is overridden in values-night with Theme.Design.BottomSheetDialog. The two Material themes carry identical items and differ only in their AppCompat palette, so nothing structural about the sheet changes. Keeping every on OffsetDialog means the two configurations cannot drift apart - duplicating the style per configuration is what invites this bug back. No layout in the app reads theme-attribute colours and none of the 36 offset sheet layouts hardcodes a light background, so there is no white-on-white inverse of this bug to introduce. The theme fix also covers the unstyled CheckBox tint in the same dialog and the same class of bug in the other offset sheets. The two TextViews additionally get style="@style/Body2", matching the convention every sibling dialog already follows. Co-Authored-By: Claude Opus 5 (1M context) * fix(ci): point devnet distribution at the real Firebase app The devnet app id matched no app in dash-wallet-firebase, so every QA upload for that flavor failed the build and then 404'd: App Distribution halted because it had a problem uploading the APK. (Invalid request, status_code: 404) The flavor builds as org.dash.wallet.devnet, whose app is 1:1039839682638:android:fdff563e24b69c5fea631f. Fixed in the workflow too, which carried the same bad id and would have failed the same way. Note that org.dash.dashpay.devnet is a second, older app with the same "DashPay [devnet]" display name, left over from before the applicationId changed. It is not the one we distribute to. Co-Authored-By: Claude Opus 5 (1M context) * fix: prevent crashes if google-service.json is missing * revert: devnet flavor app id * docs: update sakura-devnet.md * chore: update dashj to 24.0.0-SNAPSHOT * revert: use 22.0.5 dashj --------- Co-authored-by: Claude Opus 5.5 --- .github/workflows/manual_distribution.yml | 2 +- build.gradle | 4 +- .../services/analytics/AnalyticsService.kt | 20 +++-- common/src/main/res/values-night/styles.xml | 27 +++++++ common/src/main/res/values/styles.xml | 10 ++- docs/sakura-devnet.md | 37 +++++++++ fastlane/Fastfile | 2 +- wallet/build.gradle | 27 ++++++- wallet/devnet/res/values/strings-extra.xml | 2 +- .../service/platform/NetworkPlatform.kt | 11 +++ .../dialog_confirm_username_request.xml | 2 + .../res/layout/fragment_request_username.xml | 3 +- wallet/res/values-de/strings-dashpay.xml | 2 +- wallet/res/values-el/strings-dashpay.xml | 2 +- wallet/res/values-es/strings-dashpay.xml | 2 +- wallet/res/values-fa/strings-dashpay.xml | 2 +- wallet/res/values-fil/strings-dashpay.xml | 2 +- wallet/res/values-fr/strings-dashpay.xml | 2 +- wallet/res/values-id/strings-dashpay.xml | 2 +- wallet/res/values-it/strings-dashpay.xml | 2 +- wallet/res/values-ja/strings-dashpay.xml | 2 +- wallet/res/values-ko/strings-dashpay.xml | 2 +- wallet/res/values-nl/strings-dashpay.xml | 2 +- wallet/res/values-pl/strings-dashpay.xml | 2 +- wallet/res/values-pt/strings-dashpay.xml | 2 +- wallet/res/values-ru/strings-dashpay.xml | 2 +- wallet/res/values-sk/strings-dashpay.xml | 2 +- wallet/res/values-tr/strings-dashpay.xml | 2 +- wallet/res/values-uk/strings-dashpay.xml | 2 +- wallet/res/values-zh-rTW/strings-dashpay.xml | 2 +- wallet/res/values-zh/strings-dashpay.xml | 2 +- wallet/res/values/strings-dashpay.xml | 2 +- .../src/de/schildbach/wallet/Constants.java | 10 +-- .../wallet/network/SakuraDevNetParams.java | 41 ++++++++++ .../service/platform/ContestedUsernameFees.kt | 79 +++++++++++++++++++ .../service/platform/PlatformService.kt | 7 +- .../service/platform/TopUpRepository.kt | 2 +- .../ui/dashpay/CreateIdentityService.kt | 7 +- .../wallet/ui/dashpay/PlatformRepo.kt | 21 +++++ .../ui/invite/InvitationFeeDialogFragment.kt | 29 +++++-- .../ui/invite/InvitationFragmentViewModel.kt | 2 + .../wallet/ui/more/AboutViewModel.kt | 3 + .../request/ConfirmUserNameDialogViewModel.kt | 21 ++++- .../request/RequestUserNameViewModel.kt | 49 ++++++++---- .../request/RequestUsernameFragment.kt | 16 +++- .../request/WelcomeToDashPayFragment.kt | 6 +- .../service/platform/NetworkPlatform.kt | 6 ++ .../network/SakuraDevNetParamsTest.java | 50 ++++++++++++ .../platform/ContestedUsernameFeesTest.kt | 66 ++++++++++++++++ .../PlatformRepoProtocolVersionTest.kt | 67 ++++++++++++++++ .../ConfirmUserNameDialogViewModelTest.kt | 55 +++++++++++++ .../request/RequestUserNameViewModelTest.kt | 46 ++++++++++- 52 files changed, 696 insertions(+), 74 deletions(-) create mode 100644 common/src/main/res/values-night/styles.xml create mode 100644 docs/sakura-devnet.md create mode 100644 wallet/devnet/src/de/schildbach/wallet/service/platform/NetworkPlatform.kt create mode 100644 wallet/src/de/schildbach/wallet/network/SakuraDevNetParams.java create mode 100644 wallet/src/de/schildbach/wallet/service/platform/ContestedUsernameFees.kt create mode 100644 wallet/standard/src/de/schildbach/wallet/service/platform/NetworkPlatform.kt create mode 100644 wallet/test/de/schildbach/wallet/network/SakuraDevNetParamsTest.java create mode 100644 wallet/test/de/schildbach/wallet/service/platform/ContestedUsernameFeesTest.kt create mode 100644 wallet/test/de/schildbach/wallet/ui/dashpay/PlatformRepoProtocolVersionTest.kt create mode 100644 wallet/test/de/schildbach/wallet/ui/username/request/ConfirmUserNameDialogViewModelTest.kt diff --git a/.github/workflows/manual_distribution.yml b/.github/workflows/manual_distribution.yml index 9b0dcaf73b..055a226781 100644 --- a/.github/workflows/manual_distribution.yml +++ b/.github/workflows/manual_distribution.yml @@ -38,7 +38,7 @@ jobs: "firebase_app_id": "1:1039839682638:android:bbcfa8c9939ee993ea631f" }, "devnet": { - "firebase_app_id": "1:1039839682638:android:12d2ad31cc39093cea631f" + "firebase_app_id": "1:1039839682638:android:fdff563e24b69c5fea631f" } } diff --git a/build.gradle b/build.gradle index ffd9107263..d8b161b5ed 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ buildscript { coroutinesVersion = '1.6.4' ok_http_version = '4.12.0' dashjVersion = '22.0.5' - dppVersion = "4.0.1" + dppVersion = "5.0.0-SNAPSHOT" hiltVersion = '2.53' hiltCompilerVersion = '1.2.0' hiltWorkVersion = '1.2.0' @@ -86,4 +86,4 @@ allprojects { force 'com.google.android.recaptcha:recaptcha:18.4.0' } } -} \ No newline at end of file +} diff --git a/common/src/main/java/org/dash/wallet/common/services/analytics/AnalyticsService.kt b/common/src/main/java/org/dash/wallet/common/services/analytics/AnalyticsService.kt index 042f2c031d..e27233dde3 100644 --- a/common/src/main/java/org/dash/wallet/common/services/analytics/AnalyticsService.kt +++ b/common/src/main/java/org/dash/wallet/common/services/analytics/AnalyticsService.kt @@ -22,6 +22,7 @@ import androidx.core.os.bundleOf import com.google.firebase.analytics.ktx.analytics import com.google.firebase.crashlytics.ktx.crashlytics import com.google.firebase.ktx.Firebase +import com.google.firebase.FirebaseApp import org.dash.wallet.common.BuildConfig import javax.inject.Inject @@ -31,11 +32,18 @@ interface AnalyticsService { } class FirebaseAnalyticsServiceImpl @Inject constructor() : AnalyticsService { - private val firebaseAnalytics = Firebase.analytics - private val crashlytics = Firebase.crashlytics + // Local debug builds can omit google-services.json. + private val firebaseEnabled = !BuildConfig.DEBUG || try { + FirebaseApp.getInstance() + true + } catch (_: IllegalStateException) { + false + } + private val firebaseAnalytics = if (firebaseEnabled) Firebase.analytics else null + private val crashlytics = if (firebaseEnabled) Firebase.crashlytics else null init { - crashlytics.setCrashlyticsCollectionEnabled(!BuildConfig.DEBUG) + crashlytics?.setCrashlyticsCollectionEnabled(!BuildConfig.DEBUG) } override fun logEvent(event: String, params: Map) { @@ -50,7 +58,7 @@ class FirebaseAnalyticsServiceImpl @Inject constructor() : AnalyticsService { } try { - firebaseAnalytics.logEvent(event, bundleOf(*params.map { it.key.paramName to it.value }.toTypedArray())) + firebaseAnalytics?.logEvent(event, bundleOf(*params.map { it.key.paramName to it.value }.toTypedArray())) } catch (ex: Exception) { logError(ex) } @@ -63,7 +71,7 @@ class FirebaseAnalyticsServiceImpl @Inject constructor() : AnalyticsService { return } - details?.let { crashlytics.log(details) } - crashlytics.recordException(error) + details?.let { crashlytics?.log(details) } + crashlytics?.recordException(error) } } diff --git a/common/src/main/res/values-night/styles.xml b/common/src/main/res/values-night/styles.xml new file mode 100644 index 0000000000..8ca9d9820d --- /dev/null +++ b/common/src/main/res/values-night/styles.xml @@ -0,0 +1,27 @@ + + + + + - diff --git a/docs/sakura-devnet.md b/docs/sakura-devnet.md new file mode 100644 index 0000000000..a546f1e9d1 --- /dev/null +++ b/docs/sakura-devnet.md @@ -0,0 +1,37 @@ +# Sakura Devnet + +The `devnet` flavor targets `devnet-sakura`. Its application ID is +`org.dash.wallet.devnet`, reusing the existing Firebase-registered devnet app. +Only one devnet is supported at a time; this ID shares app storage with any +previously installed wallet using the same ID, but is separate from testnet and mainnet. +Wallet, chain, and bootstrap filenames use the existing `-sakura` suffix mechanism. +No DashJ release or key-derivation changes are required. + +## Prerequisites + +- An updated `5.0.0-SNAPSHOT` Platform SDK containing `NetworkConfiguration` + and the explicit-network native constructor, including rebuilt Android libraries. + The previously published snapshot without those APIs is not sufficient. +- Set `sakuraSporkAddress` in local.properties or with `-PsakuraSporkAddress=...`. + This is the operator's public signing address, never a private key. No other + devnet's address is substituted. Missing values fail the devnet build; malformed + addresses are also rejected when constructing the network parameters. +- Core port defaults to `20001` by assumption; override with `-PsakuraCorePort=...`. + +Build with `./gradlew :wallet:assembleDevnetDebug` after installing the updated SDK. +The local, Git-ignored `wallet/google-services.json` must contain +`org.dash.wallet.devnet` so Firebase-dependent startup workers can initialize. + +## Validation Still Required + +Core peers come from the Sakura status page's 13 validator IP addresses. +The SDK supplies HTTPS DAPI endpoints on port 1443. Core protocol is 70240. +DashJ's default devnet quorum and activation settings are retained as an explicit +testing assumption, not verified Sakura consensus configuration. + +Before funding the wallet, confirm Core synchronization, refresh the Platform +protocol version, check fresh block timestamps, and fetch a data contract with +proof verification enabled. The existing masternode-list quorum callback remains +in use; no proof verification or TLS validation is bypassed. + +Source: https://status.testnet.networks.dash.org/n/devnet-sakura/connect diff --git a/fastlane/Fastfile b/fastlane/Fastfile index 94aa0eb102..726ce4045c 100644 --- a/fastlane/Fastfile +++ b/fastlane/Fastfile @@ -21,7 +21,7 @@ FIREBASE_APP_IDS = { "prod" => "1:1039839682638:android:989eecd6db36de6a", "_testNet3" => "1:1039839682638:android:3202b16d460a1a88", "staging" => "1:1039839682638:android:bbcfa8c9939ee993ea631f", - "devnet" => "1:1039839682638:android:12d2ad31cc39093cea631f" + "devnet" => "1:1039839682638:android:fdff563e24b69c5fea631f" }.freeze def repo_root diff --git a/wallet/build.gradle b/wallet/build.gradle index 837809de55..ebfc4e2d9b 100644 --- a/wallet/build.gradle +++ b/wallet/build.gradle @@ -227,6 +227,25 @@ if (file("../local.properties").exists()) { file("../local.properties").withInputStream { localProps.load(it) } } +def sakuraSporkAddress = providers.gradleProperty("sakuraSporkAddress") + .getOrElse(localProps.getProperty("sakuraSporkAddress", "")) +def sakuraCorePort = providers.gradleProperty("sakuraCorePort").getOrElse("20001").toInteger() +def validateSakuraConfiguration = tasks.register("validateSakuraConfiguration") { + doLast { + if (sakuraSporkAddress.trim().isEmpty()) { + throw new GradleException("Set sakuraSporkAddress to Sakura's public spork address before building devnet") + } + if (sakuraCorePort < 1 || sakuraCorePort > 65535) { + throw new GradleException("sakuraCorePort must be between 1 and 65535") + } + } +} +tasks.configureEach { + if (name.startsWith("preDevnet") && name.endsWith("Build")) { + dependsOn(validateSakuraConfiguration) + } +} + // Year of the most recent commit on the current branch, used for the copyright notice. // Uses providers.exec so it stays compatible with the Gradle configuration cache. // Falls back to the current year if git is unavailable (e.g. building from a source tarball). @@ -275,6 +294,8 @@ android { } buildConfigField("String", "DASHJ_VERSION", "\"$dashjVersion\"") buildConfigField("int", "COMMIT_YEAR", "$commitYear") + buildConfigField("String", "SAKURA_SPORK_ADDRESS", groovy.json.JsonOutput.toJson(sakuraSporkAddress)) + buildConfigField("int", "SAKURA_CORE_PORT", sakuraCorePort.toString()) } buildTypes { @@ -327,16 +348,20 @@ android { } prod { manifest.srcFile 'prod/AndroidManifest.xml' + java.srcDirs += ['standard/src'] } _testNet3 { manifest.srcFile 'testNet3/AndroidManifest.xml' + java.srcDirs += ['standard/src'] res.srcDirs = ["testNet3/res"] } staging { res.srcDirs = ["staging/res"] + java.srcDirs += ['standard/src'] } devnet { res.srcDirs = ["devnet/res"] + java.srcDirs += ['devnet/src'] } } flavorDimensions "default" @@ -423,7 +448,7 @@ android { buildConfigField("String", "APPSFLYER_BRAND_DOMAIN", "\"dashpaytest.onelink.me\"") } devnet { - applicationId = "org.dash.dashpay.devnet" + applicationId = "org.dash.wallet.devnet" def imgurClientId = props.getProperty("UPHOLD_CLIENT_ID_SANDBOX") def imgurClientSecret = props.getProperty("UPHOLD_CLIENT_SECRET_SANDBOX") if (imgurClientId == null) { diff --git a/wallet/devnet/res/values/strings-extra.xml b/wallet/devnet/res/values/strings-extra.xml index 16c4ddbaa9..568f71927e 100644 --- a/wallet/devnet/res/values/strings-extra.xml +++ b/wallet/devnet/res/values/strings-extra.xml @@ -1,4 +1,4 @@ - Devnet + Sakura Devnet diff --git a/wallet/devnet/src/de/schildbach/wallet/service/platform/NetworkPlatform.kt b/wallet/devnet/src/de/schildbach/wallet/service/platform/NetworkPlatform.kt new file mode 100644 index 0000000000..4ab2b6ebdf --- /dev/null +++ b/wallet/devnet/src/de/schildbach/wallet/service/platform/NetworkPlatform.kt @@ -0,0 +1,11 @@ +package de.schildbach.wallet.service.platform + +import de.schildbach.wallet.network.SakuraDevNetParams +import org.bitcoinj.core.NetworkParameters +import org.dashj.platform.sdk.client.NetworkConfiguration +import org.dashj.platform.sdk.platform.Platform + +internal fun createNetworkPlatform(params: NetworkParameters): Platform { + require(params is SakuraDevNetParams) { "The devnet flavor requires Sakura parameters" } + return Platform(params, NetworkConfiguration.sakura()) +} diff --git a/wallet/res/layout/dialog_confirm_username_request.xml b/wallet/res/layout/dialog_confirm_username_request.xml index d523143119..a1df71f8d3 100644 --- a/wallet/res/layout/dialog_confirm_username_request.xml +++ b/wallet/res/layout/dialog_confirm_username_request.xml @@ -42,6 +42,7 @@ android:text="@string/confirm" /> diff --git a/wallet/res/layout/fragment_request_username.xml b/wallet/res/layout/fragment_request_username.xml index dbfb79026c..00c76b35d7 100644 --- a/wallet/res/layout/fragment_request_username.xml +++ b/wallet/res/layout/fragment_request_username.xml @@ -188,10 +188,11 @@ /> diff --git a/wallet/res/values-de/strings-dashpay.xml b/wallet/res/values-de/strings-dashpay.xml index 282f3e0cff..12f314c300 100644 --- a/wallet/res/values-de/strings-dashpay.xml +++ b/wallet/res/values-de/strings-dashpay.xml @@ -456,7 +456,7 @@ Benutzernamen + was ist die Abstimmung über Nutzernamen\? Nur Buchstaben, Zahlen und Bindestriche Nummern 2-9 - Du benötigst 0,25 DASH um einen Benutzernamen erstellen zu können + Du benötigst %s DASH um einen Benutzernamen erstellen zu können Der Nutzername muss eine dieser Kriterien entsprechen Der Nutzername muss diesen Kriterien entsprechen Zwischen 3 und 23 Zeichen diff --git a/wallet/res/values-el/strings-dashpay.xml b/wallet/res/values-el/strings-dashpay.xml index deabae9d52..a97e280dd9 100644 --- a/wallet/res/values-el/strings-dashpay.xml +++ b/wallet/res/values-el/strings-dashpay.xml @@ -448,7 +448,7 @@ + τι είναι η ψηφοφορία ονόματος χρήστη; Μόνο γράμματα, αριθμοί και παύλες Αριθμοί 2-9 - Πρέπει να έχετε 0,25 DASH για να δημιουργήσετε αυτό το όνομα χρήστη + Πρέπει να έχετε %s DASH για να δημιουργήσετε αυτό το όνομα χρήστη Το όνομα χρήστη πρέπει να πληροί ένα από τα ακόλουθα κριτήρια Το όνομα χρήστη πρέπει να πληροί τα εξής κριτήρια Μεταξύ 3 και 23 χαρακτήρων diff --git a/wallet/res/values-es/strings-dashpay.xml b/wallet/res/values-es/strings-dashpay.xml index c18472bd92..eda5e7e4ad 100644 --- a/wallet/res/values-es/strings-dashpay.xml +++ b/wallet/res/values-es/strings-dashpay.xml @@ -456,7 +456,7 @@ de Dash + ¿Qué es la votación por nombre de usuario\? Solo letras, números y guiones Números 2-9 - Necesitas tener 0,25 DASH para crear este nombre de usuario + Necesitas tener %s DASH para crear este nombre de usuario El usuario debe someterse a uno de estos criterios El usuario debe someterse a estos criterios Entre 3 y 23 caracteres diff --git a/wallet/res/values-fa/strings-dashpay.xml b/wallet/res/values-fa/strings-dashpay.xml index 9df64aa8cd..d7bdf9f2d8 100644 --- a/wallet/res/values-fa/strings-dashpay.xml +++ b/wallet/res/values-fa/strings-dashpay.xml @@ -447,7 +447,7 @@ + رای‌گیری نام کاربری چیست حرف، عدد و خط‌تیره اعداد ۲ تا ۹ - برا ایجاد نام کاربری باید ۰.۲۵ دش داشته باشید + برا ایجاد نام کاربری باید %s دش داشته باشید نام کاربری باید یکی از معیارهای زیر را شامل شود نام کاربری باید معیارهای زیر را شامل شود بین ۳ تا ۲۳ کاراکتر diff --git a/wallet/res/values-fil/strings-dashpay.xml b/wallet/res/values-fil/strings-dashpay.xml index 32b3541a84..302ef05fa3 100644 --- a/wallet/res/values-fil/strings-dashpay.xml +++ b/wallet/res/values-fil/strings-dashpay.xml @@ -448,7 +448,7 @@ Username + ano ang pagboto ng username\? Mga titik, numero at gitling lamang Bilang 2-9 - Kailangan mong magkaroon ng 0.25 DASH para magawa ang username na ito + Kailangan mong magkaroon ng %s DASH para magawa ang username na ito Dapat matugunan ng username ang isa sa mga pamantayang ito Dapat matugunan ng username ang mga pamantayang ito Sa pagitan ng 3 at 23 na mga karakter diff --git a/wallet/res/values-fr/strings-dashpay.xml b/wallet/res/values-fr/strings-dashpay.xml index 4cea1b509c..c04e374743 100644 --- a/wallet/res/values-fr/strings-dashpay.xml +++ b/wallet/res/values-fr/strings-dashpay.xml @@ -455,7 +455,7 @@ + qu\'est-ce que le vote de nom d\'utilisateur \? Lettres, chiffres et tirets seulement Chiffres 2 à 9 - Vous devez avoir 0,25 dashs pour créer ce nom d\'utilisateur + Vous devez avoir %s dashs pour créer ce nom d\'utilisateur Le nom d\'utilisateur doit répondre à un de ces critères Le nom d\'utilisateur doit répondre à ces critères entre 3 et 23 caractères diff --git a/wallet/res/values-id/strings-dashpay.xml b/wallet/res/values-id/strings-dashpay.xml index 0bbd5596cb..e1e6727414 100644 --- a/wallet/res/values-id/strings-dashpay.xml +++ b/wallet/res/values-id/strings-dashpay.xml @@ -448,7 +448,7 @@ Dash anda + apa itu voting nama pengguna\? Hanya huruf, angka, dan tanda hubung Nomor 2-9 - Anda perlu memiliki 0.25 DASH untuk membuat nama pengguna ini + Anda perlu memiliki %s DASH untuk membuat nama pengguna ini Nama pengguna harus memenuhi salah satu kriteria berikut Nama pengguna harus memenuhi kriteria berikut Antara 3 dan 23 karakter diff --git a/wallet/res/values-it/strings-dashpay.xml b/wallet/res/values-it/strings-dashpay.xml index d5de68337d..269c032709 100644 --- a/wallet/res/values-it/strings-dashpay.xml +++ b/wallet/res/values-it/strings-dashpay.xml @@ -456,7 +456,7 @@ Username + cos\'è la votazione del nome utente\? Solo lettere, numeri e trattini Numeri 2-9 - Devi avere 0,25 DASH per creare questo nome utente + Devi avere %s DASH per creare questo nome utente Lo Username deve soddisfare uno di questi criteri Lo username deve soddisfare questi criteri Tra 3 e 23 caratteri diff --git a/wallet/res/values-ja/strings-dashpay.xml b/wallet/res/values-ja/strings-dashpay.xml index 73f0088e8c..abe9921b81 100644 --- a/wallet/res/values-ja/strings-dashpay.xml +++ b/wallet/res/values-ja/strings-dashpay.xml @@ -447,7 +447,7 @@ +ユーザー名投票とは\? 英字、数字、ハイフンのみ 2〜9の数字 - このユーザー名を作成するには、0.25DASHが必要です + このユーザー名を作成するには、%sDASHが必要です ユーザー名は、このいずれかの要件を満たす必要があります ユーザー名は、これらの要件を全て満たす必要があります 3〜23文字以内 diff --git a/wallet/res/values-ko/strings-dashpay.xml b/wallet/res/values-ko/strings-dashpay.xml index 4c6cd9b0d1..ec7e4fce03 100644 --- a/wallet/res/values-ko/strings-dashpay.xml +++ b/wallet/res/values-ko/strings-dashpay.xml @@ -448,7 +448,7 @@ + 사용자 이름 투표란 무엇인가요\? 글자, 숫자 및 하이픈만 사용할 수 있습니다. 숫자 2-9 - 이 사용자 이름을 생성하기 위해서는 0.25 DASH가 필요합니다 + 이 사용자 이름을 생성하기 위해서는 %s DASH가 필요합니다 사용자 이름은 다음의 조건 중 하나를 충족해야 합니다 사용자 이름은 다음의 조건을 충족해야 합니다 3에서 23글자 사이 diff --git a/wallet/res/values-nl/strings-dashpay.xml b/wallet/res/values-nl/strings-dashpay.xml index 4716093999..ea3778a328 100644 --- a/wallet/res/values-nl/strings-dashpay.xml +++ b/wallet/res/values-nl/strings-dashpay.xml @@ -449,7 +449,7 @@ gebruikersnaam + wat is stemmen met gebruikersnaam\? Alleen letters, cijfers en koppeltekens Cijfers 2-9 - Je hebt 0,25 DASH nodig om deze gebruikersnaam aan te maken + Je hebt %s DASH nodig om deze gebruikersnaam aan te maken De gebruikersnaam moet aan een van deze criteria voldoen De gebruikersnaam moet aan deze criteria voldoen Tussen 3 en 23 tekens diff --git a/wallet/res/values-pl/strings-dashpay.xml b/wallet/res/values-pl/strings-dashpay.xml index 0d426c75b1..39170e77a9 100644 --- a/wallet/res/values-pl/strings-dashpay.xml +++ b/wallet/res/values-pl/strings-dashpay.xml @@ -455,7 +455,7 @@ + Czym jest głosowanie na nazwę użytkownika\? Tylklko litery, cyfry i myślniki są dozwolone Numer 2-9 - Aby stworzyć tę nazwę użytkownika, musisz mieć 0,25 DASH + Aby stworzyć tę nazwę użytkownika, musisz mieć %s DASH Nazwa użytkownika musi spełniać jedno z tych kryterii Nazwa użytkownika musi spełniać te kryteria Pomiędzy 3 a 23 znakami diff --git a/wallet/res/values-pt/strings-dashpay.xml b/wallet/res/values-pt/strings-dashpay.xml index ab1713e643..6960706573 100644 --- a/wallet/res/values-pt/strings-dashpay.xml +++ b/wallet/res/values-pt/strings-dashpay.xml @@ -456,7 +456,7 @@ Dash + o que é votação de nome de usuário\?  Apenas letras, números e hífens Números 2-9 - Você precisa ter 0,25 DASH para criar este nome de usuário + Você precisa ter %s DASH para criar este nome de usuário O nome de usuário deve atender a um dos seguintes critérios O nome de usuário deve atender a estes critérios Entre 3 e 23 caracteres diff --git a/wallet/res/values-ru/strings-dashpay.xml b/wallet/res/values-ru/strings-dashpay.xml index 161d498acb..d98380a7f4 100644 --- a/wallet/res/values-ru/strings-dashpay.xml +++ b/wallet/res/values-ru/strings-dashpay.xml @@ -456,7 +456,7 @@ Dash + что такое голосование за имя пользователя\? Только буквы, цифры и дефисы Цифры 2-9 - Чтобы создать это имя пользователя, у вас должно быть 0.25 DASH + Чтобы создать это имя пользователя, у вас должно быть %s DASH Имя пользователя должно соответствовать одному из этих условий: Имя пользователя должно соответствовать этим условиям: От 3 до 23 символов diff --git a/wallet/res/values-sk/strings-dashpay.xml b/wallet/res/values-sk/strings-dashpay.xml index a8de58ee1f..d54b13940b 100644 --- a/wallet/res/values-sk/strings-dashpay.xml +++ b/wallet/res/values-sk/strings-dashpay.xml @@ -448,7 +448,7 @@ používateľské meno + čo je to hlasovanie o používateľskom mene\? Iba písmená, čísla a spojovníky Čísla 2-9 - Na vytvorenie tohto používateľského mena potrebujete mať 0,25 DASH + Na vytvorenie tohto používateľského mena potrebujete mať %s DASH Používateľské meno musí spĺňať jedno z týchto kritérií Používateľské meno musí spĺňať tieto kritériá Medzi 3 a 23 znakmi diff --git a/wallet/res/values-tr/strings-dashpay.xml b/wallet/res/values-tr/strings-dashpay.xml index 42b9116695..b05bc44489 100644 --- a/wallet/res/values-tr/strings-dashpay.xml +++ b/wallet/res/values-tr/strings-dashpay.xml @@ -385,7 +385,7 @@ + kullanıcı adı oylaması nedir\? Yalnızca harfler, sayılar ve kısa çizgiler - Bu kullanıcı adını oluşturmak için 0.25 DASH\'a sahip olmanız gerekiyor + Bu kullanıcı adını oluşturmak için %s DASH\'a sahip olmanız gerekiyor 3 ile 23 karakter arasında Kabul ediyorum Al diff --git a/wallet/res/values-uk/strings-dashpay.xml b/wallet/res/values-uk/strings-dashpay.xml index 0bfdf00c87..95fc60b12b 100644 --- a/wallet/res/values-uk/strings-dashpay.xml +++ b/wallet/res/values-uk/strings-dashpay.xml @@ -447,7 +447,7 @@ + що таке голосування за імʼя користувача\? Лише літери, цифри та дефіси Числа 2-9 - Для створення цього імені користувача потрібно мати 0,25 DASH + Для створення цього імені користувача потрібно мати %s DASH Ім’я користувача повинно відповідати одному з цих критеріїв Ім’я користувача повинно відповідати цим критеріям Від 3 до 23 символів diff --git a/wallet/res/values-zh-rTW/strings-dashpay.xml b/wallet/res/values-zh-rTW/strings-dashpay.xml index 8dabe8a48d..38170a3c8c 100644 --- a/wallet/res/values-zh-rTW/strings-dashpay.xml +++ b/wallet/res/values-zh-rTW/strings-dashpay.xml @@ -448,7 +448,7 @@ + 什麼是用戶名投票\? 僅限字母、數字和連字符 數字 2-9 - 您需要 0.25 DASH 才能建立此使用這個用戶名 + 您需要 %s DASH 才能建立此用戶名 用戶名必須符合以下標準之一 用戶名必須符合這些標準 名稱介乎3 到 23 個字元之間 diff --git a/wallet/res/values-zh/strings-dashpay.xml b/wallet/res/values-zh/strings-dashpay.xml index 585e5be0e5..fdb865bd99 100644 --- a/wallet/res/values-zh/strings-dashpay.xml +++ b/wallet/res/values-zh/strings-dashpay.xml @@ -448,7 +448,7 @@ + 什么是用户名投票\? 仅限字母, 数字和连字符 数字 2-9 - 您需要拥有 0.25 DASH 来创建此用户名 + 您需要拥有 %s DASH 来创建此用户名 用户名必须符合以下任一条件 用户名必须符合以下条件 3-23个字符之间 diff --git a/wallet/res/values/strings-dashpay.xml b/wallet/res/values/strings-dashpay.xml index 9fbcf158ed..bedb55b089 100644 --- a/wallet/res/values/strings-dashpay.xml +++ b/wallet/res/values/strings-dashpay.xml @@ -459,7 +459,7 @@ + what is username voting? Letters, numbers and hyphens only Numbers 2-9 - You need to have 0.25 DASH to create this username + You need to have %s DASH to create this username The username must meet one of these criteria The username must meet these criteria Between 3 and 23 characters diff --git a/wallet/src/de/schildbach/wallet/Constants.java b/wallet/src/de/schildbach/wallet/Constants.java index 3a441caae2..f4a4c44dab 100644 --- a/wallet/src/de/schildbach/wallet/Constants.java +++ b/wallet/src/de/schildbach/wallet/Constants.java @@ -31,7 +31,7 @@ import org.bitcoinj.crypto.ChildNumber; import org.bitcoinj.params.DevNetParams; import org.bitcoinj.params.MainNetParams; -import org.bitcoinj.params.OuzoDevNetParams; +import de.schildbach.wallet.network.SakuraDevNetParams; import org.bitcoinj.params.TestNet3Params; import org.bitcoinj.utils.MonetaryFormat; import org.bitcoinj.wallet.DeterministicKeyChain; @@ -132,7 +132,8 @@ public final class Constants { } case "devnet": { BIP44_PATH = DeterministicKeyChain.BIP44_ACCOUNT_ZERO_PATH_TESTNET; - NETWORK_PARAMETERS = OuzoDevNetParams.get(); + NETWORK_PARAMETERS = SakuraDevNetParams.create( + BuildConfig.SAKURA_SPORK_ADDRESS, BuildConfig.SAKURA_CORE_PORT); String devNetName = ((DevNetParams)NETWORK_PARAMETERS).getDevNetName(); devNetName = devNetName.substring(devNetName.indexOf("-") + 1); DNS_SEED = NETWORK_PARAMETERS.getDnsSeeds(); @@ -146,7 +147,7 @@ public final class Constants { SUPPORTS_CONNECT = true; SYNC_FLAGS.add(MasternodeSync.SYNC_FLAGS.SYNC_HEADERS_MN_LIST_FIRST); SYNC_FLAGS.add(MasternodeSync.SYNC_FLAGS.SYNC_BLOCKS_AFTER_PREPROCESSING); - org.dash.wallet.common.util.Constants.FAUCET_URL = String.format("http://faucet.%s.networks.dash.org/", devNetName); + org.dash.wallet.common.util.Constants.FAUCET_URL = String.format("https://faucet.%s.networks.dash.org/", devNetName); org.dash.wallet.common.util.Constants.INSTANCE.setEXPLORE_GC_FILE_PATH("explore/explore-v3-devnet.db"); break; } @@ -317,9 +318,6 @@ public final static class Files { //Backup Warnings (true = both seed and backup file, false = seed only) public static final boolean SUPPORT_BOTH_BACKUP_WARNINGS = false; - // 2,500,000,000 credits - public static final Coin DASH_PAY_FEE_CONTESTED = Coin.parseCoin("0.25"); - public static final Coin DASH_PAY_FEE_CONTESTED_NAME = Coin.parseCoin("0.20"); public static final Coin DASH_PAY_FEE = Coin.parseCoin("0.03"); // 150,000,000 diff --git a/wallet/src/de/schildbach/wallet/network/SakuraDevNetParams.java b/wallet/src/de/schildbach/wallet/network/SakuraDevNetParams.java new file mode 100644 index 0000000000..16e6d9b0ef --- /dev/null +++ b/wallet/src/de/schildbach/wallet/network/SakuraDevNetParams.java @@ -0,0 +1,41 @@ +package de.schildbach.wallet.network; + +import org.bitcoinj.core.Address; +import org.bitcoinj.params.DevNetParams; + +/** Wallet-local configuration; consensus defaults are inherited from DashJ. */ +public final class SakuraDevNetParams extends DevNetParams { + private static final String[] PEERS = { + "68.67.122.86", "68.67.122.87", "68.67.122.240", "68.67.122.241", + "68.67.122.88", "68.67.122.89", "68.67.122.90", "68.67.122.91", + "68.67.122.92", "68.67.122.93", "68.67.122.94", "68.67.122.95", + "68.67.122.232" + }; + + private SakuraDevNetParams(String sporkAddress, int port) { + super("sakura", sporkAddress, port, PEERS.clone(), true, 70240); + Address.fromBase58(this, sporkAddress); + } + + public static synchronized SakuraDevNetParams create(String sporkAddress, int port) { + if (sporkAddress == null || sporkAddress.trim().isEmpty()) { + throw new IllegalArgumentException("Set sakuraSporkAddress to Sakura's public spork address"); + } + if (port < 1 || port > 65535) { + throw new IllegalArgumentException("sakuraCorePort must be between 1 and 65535"); + } + SakuraDevNetParams params = new SakuraDevNetParams(sporkAddress, port); + DevNetParams.add(params); + return params; + } + + @Override + public String[] getDefaultMasternodeList() { + return PEERS.clone(); + } + + @Override + public String[] getDefaultHPMasternodeList() { + return PEERS.clone(); + } +} diff --git a/wallet/src/de/schildbach/wallet/service/platform/ContestedUsernameFees.kt b/wallet/src/de/schildbach/wallet/service/platform/ContestedUsernameFees.kt new file mode 100644 index 0000000000..8a47d157b8 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/ContestedUsernameFees.kt @@ -0,0 +1,79 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.service.platform + +import androidx.annotation.VisibleForTesting +import org.bitcoinj.core.Coin +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlin.math.max + +/** + * What a contested (DPNS) username costs, which depends on the Platform protocol + * version the network runs. + * + * A contested name prefunds its vote resolution with 0.2 DASH through protocol + * version 13; protocol version 14 (Platform v4.2) lowers that to 0.1 DASH. The + * protocol version is learned from the network by [PlatformRepo.refreshProtocolVersion]. + * Until it is known the older, higher fees apply: funding an identity above the fee + * only leaves the surplus as identity credits, while funding it below makes the + * registration fail. + */ +object ContestedUsernameFees { + const val REDUCED_FEE_PROTOCOL_VERSION = 14 + + // 2,500,000,000 credits: 0.2 DASH prefunded voting balance + identity/document fees + private val FEE_BEFORE_V14: Coin = Coin.parseCoin("0.25") + private val NAME_FEE_BEFORE_V14: Coin = Coin.parseCoin("0.20") + + // 1,500,000,000 credits: 0.1 DASH prefunded voting balance + identity/document fees + private val FEE: Coin = Coin.parseCoin("0.15") + private val NAME_FEE: Coin = Coin.parseCoin("0.10") + + private val protocolVersion = MutableStateFlow(0) + val protocolVersions = protocolVersion.asStateFlow() + + /** The highest Platform protocol version seen so far, 0 if none. */ + val currentProtocolVersion: Int + get() = protocolVersion.value + + /** Records a protocol version from the network. The stored version only goes up. */ + fun updateProtocolVersion(version: Int) { + protocolVersion.update { max(it, version) } + } + + /** Creating an identity together with a contested username: the asset lock amount. */ + val fee: Coin + get() = feeFor(currentProtocolVersion) + + /** Registering a contested username for an identity that already exists. */ + val nameFee: Coin + get() = nameFeeFor(currentProtocolVersion) + + fun feeFor(protocolVersion: Int): Coin = + if (protocolVersion >= REDUCED_FEE_PROTOCOL_VERSION) FEE else FEE_BEFORE_V14 + + fun nameFeeFor(protocolVersion: Int): Coin = + if (protocolVersion >= REDUCED_FEE_PROTOCOL_VERSION) NAME_FEE else NAME_FEE_BEFORE_V14 + + @VisibleForTesting + fun reset() { + protocolVersion.value = 0 + } +} diff --git a/wallet/src/de/schildbach/wallet/service/platform/PlatformService.kt b/wallet/src/de/schildbach/wallet/service/platform/PlatformService.kt index dae3d182a5..1dea9b726c 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/PlatformService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/PlatformService.kt @@ -104,7 +104,7 @@ class PlatformServiceImplementation @Inject constructor( val walletDataProvider: WalletDataProvider ) : PlatformService { // none of the following should be initialized if platform is not supported - private val _platform by platformLazy { Platform(Constants.NETWORK_PARAMETERS) } + private val _platform by platformLazy { createNetworkPlatform(Constants.NETWORK_PARAMETERS) } override val platform: Platform get() = _platform!! private val _profiles by platformLazy { Profiles(platform) } @@ -190,7 +190,12 @@ class PlatformServiceImplementation @Inject constructor( override fun setMasternodeListManager(masternodeListManager: SimplifiedMasternodeListManager) { this.masternodeListManager = masternodeListManager + val configuredAddresses = platform.client.dapiAddressListProvider platform.setMasternodeListManager(masternodeListManager) + if (params is de.schildbach.wallet.network.SakuraDevNetParams) { + // Keep Sakura's explicit HTTPS ports; the SDK's legacy discovery replaces them. + platform.client.dapiAddressListProvider = configuredAddresses + } } override fun getContactIdentity(userId: Identifier): Identity? = diff --git a/wallet/src/de/schildbach/wallet/service/platform/TopUpRepository.kt b/wallet/src/de/schildbach/wallet/service/platform/TopUpRepository.kt index 6e1e98b65c..866012f9bc 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/TopUpRepository.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/TopUpRepository.kt @@ -193,7 +193,7 @@ class TopUpRepositoryImpl @Inject constructor( // not remove the outpoints it already chose. pendingPaymentVerifier.awaitRestored() val fee = if (Names.isUsernameContestable(username)) { - Constants.DASH_PAY_FEE_CONTESTED + ContestedUsernameFees.fee } else { Constants.DASH_PAY_FEE } diff --git a/wallet/src/de/schildbach/wallet/ui/dashpay/CreateIdentityService.kt b/wallet/src/de/schildbach/wallet/ui/dashpay/CreateIdentityService.kt index 74b6c37c40..ef2c9c3c31 100644 --- a/wallet/src/de/schildbach/wallet/ui/dashpay/CreateIdentityService.kt +++ b/wallet/src/de/schildbach/wallet/ui/dashpay/CreateIdentityService.kt @@ -7,6 +7,7 @@ import android.os.PowerManager import androidx.lifecycle.LifecycleService import com.google.android.gms.common.internal.Preconditions.checkState import dagger.hilt.android.AndroidEntryPoint +import de.schildbach.wallet.service.platform.ContestedUsernameFees import de.schildbach.wallet.Constants import de.schildbach.wallet.WalletApplication import de.schildbach.wallet.data.CoinJoinConfig @@ -405,6 +406,8 @@ class CreateIdentityService : LifecycleService() { // // Step 2: Create and send the credit funding transaction // + // the contested username fee depends on the platform protocol version + platformRepo.refreshProtocolVersion() // check to see if the funding transaction exists val useCoinJoin = coinJoinConfig.getMode() != CoinJoinMode.NONE if (blockchainIdentity.assetLockTransaction == null) { @@ -422,14 +425,14 @@ class CreateIdentityService : LifecycleService() { // don't use platformRepo.getIdentityBalance() because platformRepo.blockchainIdentity is not initialized val balanceInfo = blockchainIdentityData.identity?.let { platformRepo.getIdentityBalance(it.id) } val balanceRequirement = if (Names.isUsernameContestable(blockchainIdentityData.username!!)) { - Constants.DASH_PAY_FEE_CONTESTED + ContestedUsernameFees.fee } else { Constants.DASH_PAY_FEE } if (balanceInfo != null && balanceInfo.balance < balanceRequirement.value * 1000) { val topupValue = if (Names.isUsernameContestable(blockchainIdentityData.username!!)) { - Constants.DASH_PAY_FEE_CONTESTED_NAME + ContestedUsernameFees.nameFee } else { Constants.DASH_PAY_FEE } diff --git a/wallet/src/de/schildbach/wallet/ui/dashpay/PlatformRepo.kt b/wallet/src/de/schildbach/wallet/ui/dashpay/PlatformRepo.kt index a256e0533a..7d56e2f91c 100644 --- a/wallet/src/de/schildbach/wallet/ui/dashpay/PlatformRepo.kt +++ b/wallet/src/de/schildbach/wallet/ui/dashpay/PlatformRepo.kt @@ -40,6 +40,7 @@ import de.schildbach.wallet.livedata.SeriousErrorListener import de.schildbach.wallet.livedata.Status import de.schildbach.wallet.security.SecurityGuard import de.schildbach.wallet.security.SecurityGuardException +import de.schildbach.wallet.service.platform.ContestedUsernameFees import de.schildbach.wallet.service.platform.PlatformService import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig import io.grpc.StatusRuntimeException @@ -535,4 +536,24 @@ class PlatformRepo @Inject constructor( CreditBalanceInfo(platform.client.getIdentityBalance(identifier)) } } + + /** + * Asks the network which Platform protocol version it runs and records it in + * [ContestedUsernameFees]. A failure is logged and leaves the last known version, + * so fees fall back to the higher, pre-v14 amounts until a refresh succeeds. + */ + suspend fun refreshProtocolVersion(): Int { + return withContext(Dispatchers.IO) { + try { + val version = platform.client.refreshProtocolVersion() + ContestedUsernameFees.updateProtocolVersion(version) + log.info("platform protocol version: {}", version) + } catch (e: kotlinx.coroutines.CancellationException) { + throw e + } catch (e: Exception) { + log.warn("unable to refresh the platform protocol version", e) + } + ContestedUsernameFees.currentProtocolVersion + } + } } diff --git a/wallet/src/de/schildbach/wallet/ui/invite/InvitationFeeDialogFragment.kt b/wallet/src/de/schildbach/wallet/ui/invite/InvitationFeeDialogFragment.kt index 788c8de474..d7e1ae16c2 100644 --- a/wallet/src/de/schildbach/wallet/ui/invite/InvitationFeeDialogFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/invite/InvitationFeeDialogFragment.kt @@ -20,15 +20,18 @@ package de.schildbach.wallet.ui.invite import android.os.Bundle import android.view.View import androidx.fragment.app.viewModels +import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import dagger.hilt.android.AndroidEntryPoint import de.schildbach.wallet.Constants import org.bitcoinj.core.Coin +import de.schildbach.wallet.service.platform.ContestedUsernameFees import de.schildbach.wallet.ui.CheckPinDialog import de.schildbach.wallet_test.R import de.schildbach.wallet_test.databinding.DialogInvitationFeeBinding import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch import org.dash.wallet.common.ui.dialogs.OffsetDialogFragment import org.dash.wallet.common.ui.viewBinding import org.dash.wallet.common.util.observe @@ -36,8 +39,9 @@ import org.dash.wallet.common.util.observe @AndroidEntryPoint class InvitationFeeDialogFragment : OffsetDialogFragment(R.layout.dialog_invitation_fee) { private val binding by viewBinding(DialogInvitationFeeBinding::bind) - private var selectedFee = Constants.DASH_PAY_FEE_CONTESTED + private var selectedFee = ContestedUsernameFees.fee private var spendableBalance = Coin.ZERO + private var protocolVersionRefreshed = false @OptIn(ExperimentalCoroutinesApi::class) private val viewModel by viewModels() private val args by navArgs() @@ -45,10 +49,11 @@ class InvitationFeeDialogFragment : OffsetDialogFragment(R.layout.dialog_invitat @OptIn(ExperimentalCoroutinesApi::class) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) + protocolVersionRefreshed = false setMode(true) binding.mixButton.setOnClickListener { CheckPinDialog.show(requireActivity()) { pin -> - if (pin != null) { + if (pin != null && canContinue()) { findNavController().navigate( InvitationFeeDialogFragmentDirections.toConfirmInviteDialog(selectedFee.value, args.source) ) @@ -59,7 +64,7 @@ class InvitationFeeDialogFragment : OffsetDialogFragment(R.layout.dialog_invitat } viewModel.walletData.observeSpendableBalance().observe(viewLifecycleOwner) { walletBalance -> spendableBalance = walletBalance - binding.contestedName.isEnabled = walletBalance >= Constants.DASH_PAY_FEE_CONTESTED + binding.contestedName.isEnabled = walletBalance >= ContestedUsernameFees.fee updateContinueButton() } binding.contestedName.setOnClickListener { @@ -69,13 +74,24 @@ class InvitationFeeDialogFragment : OffsetDialogFragment(R.layout.dialog_invitat binding.nonContestedName.setOnClickListener { setMode(false) } + ContestedUsernameFees.protocolVersions.observe(viewLifecycleOwner) { + binding.contestedName.isEnabled = spendableBalance >= ContestedUsernameFees.fee + setMode(binding.contestedName.isSelected) + } + viewLifecycleOwner.lifecycleScope.launch { + // the contested fee depends on the platform protocol version + viewModel.refreshProtocolVersion() + protocolVersionRefreshed = true + binding.contestedName.isEnabled = spendableBalance >= ContestedUsernameFees.fee + setMode(binding.contestedName.isSelected) + } } private fun setMode(isContestedName: Boolean) { if (isContestedName) { binding.contestedName.isSelected = true binding.nonContestedName.isSelected = false - selectedFee = Constants.DASH_PAY_FEE_CONTESTED + selectedFee = ContestedUsernameFees.fee } else { binding.contestedName.isSelected = false binding.nonContestedName.isSelected = true @@ -85,6 +101,9 @@ class InvitationFeeDialogFragment : OffsetDialogFragment(R.layout.dialog_invitat } private fun updateContinueButton() { - binding.mixButton.isEnabled = spendableBalance >= selectedFee + binding.mixButton.isEnabled = canContinue() } + + private fun canContinue(): Boolean = + (!binding.contestedName.isSelected || protocolVersionRefreshed) && spendableBalance >= selectedFee } diff --git a/wallet/src/de/schildbach/wallet/ui/invite/InvitationFragmentViewModel.kt b/wallet/src/de/schildbach/wallet/ui/invite/InvitationFragmentViewModel.kt index 7bd512d855..55286c2b71 100644 --- a/wallet/src/de/schildbach/wallet/ui/invite/InvitationFragmentViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/invite/InvitationFragmentViewModel.kt @@ -177,6 +177,8 @@ open class InvitationFragmentViewModel @Inject constructor( suspend fun getInvitedUserProfile(): DashPayProfile? = dashPayProfileDao.loadByUserId(identityId.value!!) + suspend fun refreshProtocolVersion(): Int = platformRepo.refreshProtocolVersion() + override fun onCleared() { super.onCleared() workerJob.cancel() diff --git a/wallet/src/de/schildbach/wallet/ui/more/AboutViewModel.kt b/wallet/src/de/schildbach/wallet/ui/more/AboutViewModel.kt index 3d1a599cf7..eef635dea0 100644 --- a/wallet/src/de/schildbach/wallet/ui/more/AboutViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/more/AboutViewModel.kt @@ -19,6 +19,8 @@ package de.schildbach.wallet.ui.more import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import com.google.firebase.FirebaseApp +import de.schildbach.wallet_test.BuildConfig import com.google.firebase.installations.FirebaseInstallations import com.google.firebase.messaging.FirebaseMessaging import dagger.hilt.android.lifecycle.HiltViewModel @@ -96,6 +98,7 @@ class AboutViewModel @Inject constructor( } private fun loadFirebaseIds() { + if (BuildConfig.DEBUG && FirebaseApp.getApps(walletApplication).isEmpty()) return FirebaseInstallations.getInstance().id.addOnCompleteListener { task -> val id = if (task.isSuccessful) task.result ?: "" else "" _uiState.update { it.copy(firebaseInstallationId = id) } diff --git a/wallet/src/de/schildbach/wallet/ui/username/request/ConfirmUserNameDialogViewModel.kt b/wallet/src/de/schildbach/wallet/ui/username/request/ConfirmUserNameDialogViewModel.kt index c0be866f0e..01dcdd7163 100644 --- a/wallet/src/de/schildbach/wallet/ui/username/request/ConfirmUserNameDialogViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/username/request/ConfirmUserNameDialogViewModel.kt @@ -19,12 +19,14 @@ package de.schildbach.wallet.ui.username.request import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel +import de.schildbach.wallet.service.platform.ContestedUsernameFees import de.schildbach.wallet.Constants import de.schildbach.wallet.ui.username.UsernameType import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.launchIn @@ -56,16 +58,29 @@ class ConfirmUserNameDialogViewModel @Inject constructor( private val walletUIConfig: WalletUIConfig ) : ViewModel() { + private var latestExchangeRate: ExchangeRate? = null var usernameType: UsernameType = UsernameType.Primary + set(value) { + field = value + latestExchangeRate?.let(::updateFees) + } var isContestableUsername: Boolean = false + set(value) { + field = value + latestExchangeRate?.let(::updateFees) + } var hasIdentity: Boolean = false + set(value) { + field = value + latestExchangeRate?.let(::updateFees) + } private val _uiState = MutableStateFlow(ConfirmUserNameUIState()) val uiState: StateFlow = _uiState.asStateFlow() private val amount: Coin get() = when { usernameType == UsernameType.Secondary -> Coin.ZERO - isContestableUsername && !hasIdentity -> Constants.DASH_PAY_FEE_CONTESTED - isContestableUsername && hasIdentity -> Constants.DASH_PAY_FEE_CONTESTED_NAME + isContestableUsername && !hasIdentity -> ContestedUsernameFees.fee + isContestableUsername && hasIdentity -> ContestedUsernameFees.nameFee else -> Constants.DASH_PAY_FEE } init { @@ -76,6 +91,7 @@ class ConfirmUserNameDialogViewModel @Inject constructor( exchangeRatesProvider.observeExchangeRate(code) .filterNotNull() } + .combine(ContestedUsernameFees.protocolVersions) { rate, _ -> rate } .onEach { updateFees(it) } @@ -84,6 +100,7 @@ class ConfirmUserNameDialogViewModel @Inject constructor( private fun updateFees(exchangeRateData: ExchangeRate) { + latestExchangeRate = exchangeRateData val amountStr = MonetaryFormat.BTC.noCode().format(amount).toString() val exchangeRate = exchangeRateData.run { diff --git a/wallet/src/de/schildbach/wallet/ui/username/request/RequestUserNameViewModel.kt b/wallet/src/de/schildbach/wallet/ui/username/request/RequestUserNameViewModel.kt index 45280d4be5..b7eb97cc0e 100644 --- a/wallet/src/de/schildbach/wallet/ui/username/request/RequestUserNameViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/username/request/RequestUserNameViewModel.kt @@ -19,6 +19,7 @@ package de.schildbach.wallet.ui.username.request import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel +import de.schildbach.wallet.service.platform.ContestedUsernameFees import de.schildbach.wallet.Constants import de.schildbach.wallet.WalletApplication import de.schildbach.wallet.data.CoinJoinConfig @@ -48,6 +49,7 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.launchIn @@ -87,6 +89,7 @@ data class RequestUserNameUIState( /** The name the availability flags above were checked for, or null when there is no current result. */ val checkedUsername: String? = null, val enoughBalance: Boolean = false, + val feeProtocolVersion: Int = 0, val usernameNonContestedChars: Boolean = false, val usernameNonContestedLength: Boolean = false, val votingPeriodStart: Long = System.currentTimeMillis() @@ -106,7 +109,8 @@ class RequestUserNameViewModel @Inject constructor( ) : ViewModel() { companion object { private val log = LoggerFactory.getLogger(RequestUserNameViewModel::class.java) - private val CONTEST_DOCUMENT_FEE = Coin.valueOf(0, 20).value * 1000 + private val CONTEST_DOCUMENT_FEE: Long + get() = ContestedUsernameFees.nameFee.value * 1000 private val NON_CONTEST_DOCUMENT_FEE = Coin.valueOf(1000000).value * 1000 } @@ -205,7 +209,7 @@ class RequestUserNameViewModel @Inject constructor( val credits = _identityBalance.value credits > CONTEST_DOCUMENT_FEE } else { - _walletBalance.value >= Constants.DASH_PAY_FEE_CONTESTED + _walletBalance.value >= ContestedUsernameFees.fee } } @@ -214,6 +218,16 @@ class RequestUserNameViewModel @Inject constructor( private val _myUsernameRequest = MutableStateFlow(null) init { + // learn the platform protocol version early; the contested username fee depends on it + viewModelScope.launch { platformRepo.refreshProtocolVersion() } + combine(ContestedUsernameFees.protocolVersions, _walletBalance, _identityBalance, _inviteBalance) { + version, _, _, _ -> version + }.onEach { version -> + // A fee or balance change must not invalidate the username availability result. + _uiState.update { + it.copy(enoughBalance = hasEnoughBalance(it.usernameContestable), feeProtocolVersion = version) + } + }.launchIn(viewModelScope) viewModelScope.launch { _requestedUserNameLink.value = withContext(Dispatchers.IO) { identityConfig.get(BlockchainIdentityConfig.REQUESTED_USERNAME_LINK) @@ -522,20 +536,7 @@ class RequestUserNameViewModel @Inject constructor( val (validCharacters, startOrEndWithHyphen) = validateUsernameCharacters(username) val contestable = Names.isUsernameContestable(username) - val identityBalance = _identityBalance.value - val walletBalance = _walletBalance.value - val inviteBalance = _inviteBalance.value - val enoughBalance = when { - isUsingInvite() && contestable -> inviteBalance >= Constants.DASH_PAY_FEE_CONTESTED - isUsingInvite() && !contestable -> inviteBalance >= Constants.DASH_PAY_FEE - identityBalance > 0L && contestable -> (Coin.valueOf(identityBalance / 1000) + walletBalance) > Coin.valueOf( - CONTEST_DOCUMENT_FEE / 1000) - identityBalance > 0L && !contestable -> (Coin.valueOf(identityBalance / 1000) + walletBalance) > Coin.valueOf( - NON_CONTEST_DOCUMENT_FEE / 1000) - identityBalance == 0L && contestable -> walletBalance >= Constants.DASH_PAY_FEE_CONTESTED - identityBalance == 0L && !contestable -> walletBalance >= Constants.DASH_PAY_FEE - else -> false // how can we get here? - } + val enoughBalance = hasEnoughBalance(contestable) _uiState.update { it.copy( usernameLengthValid = validLength, @@ -554,6 +555,20 @@ class RequestUserNameViewModel @Inject constructor( return validCharacters && validLength } + private fun hasEnoughBalance(contestable: Boolean): Boolean { + val identityBalance = _identityBalance.value + val walletBalance = _walletBalance.value + val inviteBalance = _inviteBalance.value + return when { + isUsingInvite() && contestable -> inviteBalance >= ContestedUsernameFees.fee + isUsingInvite() -> inviteBalance >= Constants.DASH_PAY_FEE + identityBalance > 0L -> (Coin.valueOf(identityBalance / 1000) + walletBalance) > Coin.valueOf( + (if (contestable) CONTEST_DOCUMENT_FEE else NON_CONTEST_DOCUMENT_FEE) / 1000) + identityBalance == 0L -> walletBalance >= if (contestable) ContestedUsernameFees.fee else Constants.DASH_PAY_FEE + else -> false + } + } + @Throws(NullPointerException::class) fun isUsernameContestable(): Boolean { return Names.isUsernameContestable(requestedUserName!!) @@ -607,7 +622,7 @@ class RequestUserNameViewModel @Inject constructor( } ?: Coin.ZERO } - fun isInviteForContestedNames(): Boolean = getInvitationAmount() >= Constants.DASH_PAY_FEE_CONTESTED + fun isInviteForContestedNames(): Boolean = getInvitationAmount() >= ContestedUsernameFees.fee private suspend fun isInviteMixed(): Unit = withContext(Dispatchers.IO) { _isInviteMixed.value = inviteAssetLockTx.value?.let { diff --git a/wallet/src/de/schildbach/wallet/ui/username/request/RequestUsernameFragment.kt b/wallet/src/de/schildbach/wallet/ui/username/request/RequestUsernameFragment.kt index 0f429358f0..c1bdf969b3 100644 --- a/wallet/src/de/schildbach/wallet/ui/username/request/RequestUsernameFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/username/request/RequestUsernameFragment.kt @@ -15,14 +15,17 @@ import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.navArgs import com.google.android.material.textfield.TextInputLayout import dagger.hilt.android.AndroidEntryPoint +import de.schildbach.wallet.Constants import de.schildbach.wallet.database.entity.IdentityCreationState import de.schildbach.wallet.database.entity.UsernameRequest +import de.schildbach.wallet.service.platform.ContestedUsernameFees import de.schildbach.wallet.ui.dashpay.DashPayViewModel import de.schildbach.wallet.ui.username.CreateUsernameActions import de.schildbach.wallet.ui.username.UsernameType import de.schildbach.wallet_test.R import de.schildbach.wallet_test.databinding.FragmentRequestUsernameBinding import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch import org.dash.wallet.common.InteractionAwareActivity import org.dash.wallet.common.ui.dialogs.AdaptiveDialog @@ -215,6 +218,12 @@ open class RequestUsernameFragment : Fragment(R.layout.fragment_request_username // binding.walletBalanceContainer.isVisible = !it.enoughBalance if ((!requestUserNameViewModel.isUsingInvite() || isInviteContested) && usernameType != UsernameType.Secondary) { binding.walletBalanceContainer.isVisible = !it.enoughBalance + val requiredFee = if (it.usernameContestable) ContestedUsernameFees.fee else Constants.DASH_PAY_FEE + binding.balanceRequirement.text = getString( + R.string.request_username_balance_requirement, + java.text.NumberFormat.getNumberInstance(resources.configuration.locales[0]) + .format(requiredFee.toPlainString().toBigDecimal()) + ) if (it.usernameContestable || it.usernameContested) { val startDate = Date(it.votingPeriodStart) @@ -317,9 +326,10 @@ open class RequestUsernameFragment : Fragment(R.layout.fragment_request_username } else { binding.inviteWithUnmixedFunds.isVisible = false } - requestUserNameViewModel.inviteBalance.observe(viewLifecycleOwner) { - val isInviteForContestedNames = requestUserNameViewModel.isInviteForContestedNames() - val isInviteContested = requestUserNameViewModel.isUsingInvite() && requestUserNameViewModel.isInviteForContestedNames() + combine(requestUserNameViewModel.inviteBalance, ContestedUsernameFees.protocolVersions) { _, _ -> + requestUserNameViewModel.isInviteForContestedNames() + }.observe(viewLifecycleOwner) { isInviteForContestedNames -> + val isInviteContested = requestUserNameViewModel.isUsingInvite() && isInviteForContestedNames binding.charLengthRequirement.text = getString( if (isInviteContested) { R.string.request_username_length_requirement diff --git a/wallet/src/de/schildbach/wallet/ui/username/request/WelcomeToDashPayFragment.kt b/wallet/src/de/schildbach/wallet/ui/username/request/WelcomeToDashPayFragment.kt index 68953ff350..2592b62550 100644 --- a/wallet/src/de/schildbach/wallet/ui/username/request/WelcomeToDashPayFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/username/request/WelcomeToDashPayFragment.kt @@ -6,6 +6,7 @@ import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import dagger.hilt.android.AndroidEntryPoint +import de.schildbach.wallet.service.platform.ContestedUsernameFees import de.schildbach.wallet.Constants import de.schildbach.wallet_test.R import de.schildbach.wallet_test.databinding.FragmentWelcomeToDashpayBinding @@ -32,6 +33,9 @@ class WelcomeToDashPayFragment : Fragment(R.layout.fragment_welcome_to_dashpay) requestUserNameViewModel.identityBalance.observe(viewLifecycleOwner) { updateView() } + ContestedUsernameFees.protocolVersions.observe(viewLifecycleOwner) { + updateView() + } } fun updateView() { @@ -45,7 +49,7 @@ class WelcomeToDashPayFragment : Fragment(R.layout.fragment_welcome_to_dashpay) binding.balanceRequirementDisclaimer.text = getString( R.string.welcome_request_username_min_balance_disclaimer_all, requestUserNameViewModel.walletBalance.value.toPlainString(), - Constants.DASH_PAY_FEE_CONTESTED.toPlainString() + ContestedUsernameFees.fee.toPlainString() ) } binding.balanceRequirementDisclaimer.isVisible = !requestUserNameViewModel.canAffordContestedUsername() diff --git a/wallet/standard/src/de/schildbach/wallet/service/platform/NetworkPlatform.kt b/wallet/standard/src/de/schildbach/wallet/service/platform/NetworkPlatform.kt new file mode 100644 index 0000000000..6af3831f60 --- /dev/null +++ b/wallet/standard/src/de/schildbach/wallet/service/platform/NetworkPlatform.kt @@ -0,0 +1,6 @@ +package de.schildbach.wallet.service.platform + +import org.bitcoinj.core.NetworkParameters +import org.dashj.platform.sdk.platform.Platform + +internal fun createNetworkPlatform(params: NetworkParameters): Platform = Platform(params) diff --git a/wallet/test/de/schildbach/wallet/network/SakuraDevNetParamsTest.java b/wallet/test/de/schildbach/wallet/network/SakuraDevNetParamsTest.java new file mode 100644 index 0000000000..1d628c6a66 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/network/SakuraDevNetParamsTest.java @@ -0,0 +1,50 @@ +package de.schildbach.wallet.network; + +import org.bitcoinj.core.Address; +import org.bitcoinj.core.NetworkParameters; +import org.bitcoinj.params.DevNetParams; +import org.bitcoinj.params.TestNet3Params; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class SakuraDevNetParamsTest { + // A synthetic public address for constructor tests, not Sakura's signing key. + private String testAddress() { + return Address.fromPubKeyHash(TestNet3Params.get(), new byte[20]).toBase58(); + } + + @Test + public void usesSakuraIdentityAndRegistersParameters() { + SakuraDevNetParams params = SakuraDevNetParams.create(testAddress(), 20001); + assertEquals("devnet-sakura", params.getDevNetName()); + assertEquals(20001, params.getPort()); + assertEquals(70240, params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT)); + assertSame(params, DevNetParams.get("sakura")); + assertEquals(13, params.getDefaultMasternodeList().length); + assertArrayEquals(params.getDefaultMasternodeList(), params.getDefaultHPMasternodeList()); + } + + @Test + public void peersAreDefensivelyCopiedAndPortCanBeOverridden() { + SakuraDevNetParams params = SakuraDevNetParams.create(testAddress(), 20002); + params.getDefaultMasternodeList()[0] = "127.0.0.1"; + assertEquals("68.67.122.86", params.getDefaultMasternodeList()[0]); + assertEquals(20002, params.getPort()); + } + + @Test(expected = IllegalArgumentException.class) + public void rejectsMissingSporkAddress() { + SakuraDevNetParams.create("", 20001); + } + + @Test(expected = IllegalArgumentException.class) + public void rejectsInvalidPort() { + SakuraDevNetParams.create(testAddress(), 65536); + } + + @Test(expected = IllegalArgumentException.class) + public void rejectsInvalidSporkAddress() { + SakuraDevNetParams.create("not-an-address", 20001); + } +} diff --git a/wallet/test/de/schildbach/wallet/service/platform/ContestedUsernameFeesTest.kt b/wallet/test/de/schildbach/wallet/service/platform/ContestedUsernameFeesTest.kt new file mode 100644 index 0000000000..e92b66427f --- /dev/null +++ b/wallet/test/de/schildbach/wallet/service/platform/ContestedUsernameFeesTest.kt @@ -0,0 +1,66 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.service.platform + +import org.bitcoinj.core.Coin +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Test + +class ContestedUsernameFeesTest { + + @After + fun tearDown() { + ContestedUsernameFees.reset() + } + + @Test + fun unknownProtocolVersion_usesTheHigherPreV14Fees() { + assertEquals(0, ContestedUsernameFees.currentProtocolVersion) + assertEquals(Coin.parseCoin("0.25"), ContestedUsernameFees.fee) + assertEquals(Coin.parseCoin("0.20"), ContestedUsernameFees.nameFee) + } + + @Test + fun protocolVersion13_usesPreV14Fees() { + ContestedUsernameFees.updateProtocolVersion(13) + assertEquals(Coin.parseCoin("0.25"), ContestedUsernameFees.fee) + assertEquals(Coin.parseCoin("0.20"), ContestedUsernameFees.nameFee) + } + + @Test + fun protocolVersion14_usesReducedFees() { + ContestedUsernameFees.updateProtocolVersion(14) + assertEquals(Coin.parseCoin("0.15"), ContestedUsernameFees.fee) + assertEquals(Coin.parseCoin("0.10"), ContestedUsernameFees.nameFee) + } + + @Test + fun laterProtocolVersions_keepTheReducedFees() { + assertEquals(Coin.parseCoin("0.15"), ContestedUsernameFees.feeFor(15)) + assertEquals(Coin.parseCoin("0.10"), ContestedUsernameFees.nameFeeFor(15)) + } + + @Test + fun protocolVersion_neverGoesDown() { + ContestedUsernameFees.updateProtocolVersion(14) + ContestedUsernameFees.updateProtocolVersion(13) + assertEquals(14, ContestedUsernameFees.currentProtocolVersion) + assertEquals(Coin.parseCoin("0.15"), ContestedUsernameFees.fee) + } +} diff --git a/wallet/test/de/schildbach/wallet/ui/dashpay/PlatformRepoProtocolVersionTest.kt b/wallet/test/de/schildbach/wallet/ui/dashpay/PlatformRepoProtocolVersionTest.kt new file mode 100644 index 0000000000..b85f52d1aa --- /dev/null +++ b/wallet/test/de/schildbach/wallet/ui/dashpay/PlatformRepoProtocolVersionTest.kt @@ -0,0 +1,67 @@ +package de.schildbach.wallet.ui.dashpay + +import android.app.Application +import de.schildbach.wallet.service.platform.ContestedUsernameFees +import de.schildbach.wallet.service.platform.PlatformService +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.runBlocking +import org.bitcoinj.core.Coin +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(application = Application::class, sdk = [28], manifest = Config.NONE) +class PlatformRepoProtocolVersionTest { + private val platform = mockk(relaxed = true) + private lateinit var repository: PlatformRepo + + @Before + fun setUp() { + ContestedUsernameFees.reset() + repository = PlatformRepo(mockk(relaxed = true), mockk(relaxed = true), platform, + mockk(relaxed = true), mockk(relaxed = true)) + } + + @After + fun tearDown() { + ContestedUsernameFees.reset() + } + + @Test + fun successfulRefresh_updatesAndReturnsVersion() = runBlocking { + every { platform.client.refreshProtocolVersion() } returns 14 + assertEquals(14, repository.refreshProtocolVersion()) + assertEquals(14, ContestedUsernameFees.protocolVersions.value) + assertEquals(Coin.parseCoin("0.15"), ContestedUsernameFees.fee) + } + + @Test + fun failedInitialRefresh_retainsHigherFees() = runBlocking { + every { platform.client.refreshProtocolVersion() } throws IllegalStateException("offline") + assertEquals(0, repository.refreshProtocolVersion()) + assertEquals(Coin.parseCoin("0.25"), ContestedUsernameFees.fee) + } + + @Test + fun failedRefresh_preservesPreviouslyLearnedVersion() = runBlocking { + every { platform.client.refreshProtocolVersion() } returns 14 + repository.refreshProtocolVersion() + every { platform.client.refreshProtocolVersion() } throws IllegalStateException("offline") + assertEquals(14, repository.refreshProtocolVersion()) + assertEquals(Coin.parseCoin("0.15"), ContestedUsernameFees.fee) + } + + @Test(expected = CancellationException::class) + fun cancellation_isNotTreatedAsNetworkFailure() = runBlocking { + every { platform.client.refreshProtocolVersion() } throws CancellationException("cancelled") + repository.refreshProtocolVersion() + Unit + } +} diff --git a/wallet/test/de/schildbach/wallet/ui/username/request/ConfirmUserNameDialogViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/username/request/ConfirmUserNameDialogViewModelTest.kt new file mode 100644 index 0000000000..70abcf783d --- /dev/null +++ b/wallet/test/de/schildbach/wallet/ui/username/request/ConfirmUserNameDialogViewModelTest.kt @@ -0,0 +1,55 @@ +package de.schildbach.wallet.ui.username.request + +import android.app.Application +import androidx.lifecycle.viewModelScope +import de.schildbach.wallet.service.platform.ContestedUsernameFees +import de.schildbach.wallet.util.viewModels.MainCoroutineRule +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.dash.wallet.common.data.WalletUIConfig +import org.dash.wallet.common.data.entity.ExchangeRate +import org.dash.wallet.common.services.ExchangeRatesProvider +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(application = Application::class, sdk = [28], manifest = Config.NONE) +class ConfirmUserNameDialogViewModelTest { + @get:Rule + val mainCoroutineRule = MainCoroutineRule() + + @Test + fun feeRefresh_updatesAmountWithoutAnotherExchangeRateEmission() = runTest { + ContestedUsernameFees.reset() + val config = mockk() + every { config.observe(WalletUIConfig.SELECTED_CURRENCY) } returns flowOf("USD") + val rates = mockk() + every { rates.observeExchangeRate("USD") } returns flowOf(ExchangeRate("USD", "100")) + val viewModel = ConfirmUserNameDialogViewModel(mockk(relaxed = true), rates, config) + try { + viewModel.isContestableUsername = true + runCurrent() + assertEquals("0.25", viewModel.uiState.value.amountStr) + + ContestedUsernameFees.updateProtocolVersion(14) + runCurrent() + assertEquals("0.15", viewModel.uiState.value.amountStr) + + viewModel.hasIdentity = true + assertEquals("0.10", viewModel.uiState.value.amountStr) + } finally { + viewModel.viewModelScope.cancel() + ContestedUsernameFees.reset() + } + } +} diff --git a/wallet/test/de/schildbach/wallet/ui/username/request/RequestUserNameViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/username/request/RequestUserNameViewModelTest.kt index abc6e769ed..b8720f1737 100644 --- a/wallet/test/de/schildbach/wallet/ui/username/request/RequestUserNameViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/username/request/RequestUserNameViewModelTest.kt @@ -31,6 +31,8 @@ import de.schildbach.wallet.database.entity.BlockchainIdentityData import de.schildbach.wallet.database.entity.IdentityCreationState import de.schildbach.wallet.livedata.Resource import de.schildbach.wallet.service.platform.TopUpRepository +import de.schildbach.wallet.service.platform.ContestedUsernameFees +import de.schildbach.wallet.service.CoinJoinMode import de.schildbach.wallet.ui.dashpay.CreateIdentityService import de.schildbach.wallet.ui.dashpay.PlatformRepo import de.schildbach.wallet.ui.username.UsernameType @@ -42,8 +44,12 @@ import io.mockk.slot import io.mockk.verify import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.withTimeout import org.dash.wallet.common.WalletDataProvider import org.dash.wallet.common.services.analytics.AnalyticsService @@ -58,6 +64,10 @@ import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Before +import org.junit.After +import org.bitcoinj.core.Coin +import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.cancel import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -90,9 +100,11 @@ class RequestUserNameViewModelTest { private lateinit var platformRepo: PlatformRepo private lateinit var walletApplication: WalletApplication private lateinit var viewModel: RequestUserNameViewModel + private val balance = MutableStateFlow(Coin.ZERO) @Before fun setUp() { + ContestedUsernameFees.reset() identityConfig = mockk(relaxed = true) every { identityConfig.observe(IDENTITY_ID) } returns emptyFlow() coEvery { identityConfig.get(BlockchainIdentityConfig.REQUESTED_USERNAME_LINK) } returns null @@ -101,12 +113,14 @@ class RequestUserNameViewModelTest { walletApplication = mockk(relaxed = true) val coinJoinConfig = mockk(relaxed = true) - every { coinJoinConfig.observeMode() } returns emptyFlow() + every { coinJoinConfig.observeMode() } returns flowOf(CoinJoinMode.NONE) + val walletData = mockk(relaxed = true) + every { walletData.observeBalance(any()) } returns balance viewModel = RequestUserNameViewModel( walletApplication, identityConfig, - mockk(relaxed = true), + walletData, platformRepo, mockk(relaxed = true), coinJoinConfig, @@ -117,6 +131,34 @@ class RequestUserNameViewModelTest { // --- checkUsername --- + @After + fun tearDown() { + viewModel.viewModelScope.cancel() + ContestedUsernameFees.reset() + } + + @Test + fun reducedFee_recomputesAffordabilityWithoutLosingAvailability() = runTest { + balance.value = Coin.parseCoin("0.20") + runCurrent() + withTimeout(5_000) { viewModel.walletBalance.first { it == balance.value } } + viewModel.checkUsernameValid(username, UsernameType.Primary) + nameLookupReturns(null) + every { platformRepo.getVoteContendersOrNull(username) } returns contenders() + assertFalse(checkUsername().enoughBalance) + + ContestedUsernameFees.updateProtocolVersion(14) + val state = withTimeout(5_000) { viewModel.uiState.first { it.feeProtocolVersion == 14 } } + + assertTrue(state.enoughBalance) + assertTrue(viewModel.hasAvailableResultFor(username)) + assertEquals(username, state.checkedUsername) + + balance.value = Coin.parseCoin("0.10") + withTimeout(5_000) { viewModel.uiState.first { !it.enoughBalance } } + assertTrue(viewModel.hasAvailableResultFor(username)) + } + @Test fun checkUsername_lookupFails_isNotReportedAsChecked() { every { platformRepo.getUsername(username) } returns Resource.error("DAPI unavailable", null) From cdaf542b61147c204064ca74a9e3dc65dd2044f5 Mon Sep 17 00:00:00 2001 From: abaranouski <40296510+abaranouski@users.noreply.github.com> Date: Thu, 22 Oct 2026 20:56:03 +0200 Subject: [PATCH 2/3] chore(claude): /pre-review skill and an opt-in push gate (#1634) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore(claude): /pre-review skill and an opt-in push gate thepastaclaw re-reviews the whole PR range on every pushed commit and approves only at zero findings, so each push with a finding we could have seen costs a round. The skill runs the bot's own model (GPT-6.1 Sol via the Codex CLI) with its public review prompts, fetched at run time from a pinned commit, over merge_base..HEAD; Claude then verifies each finding against the code and fixes the whole class of it. Verdicts are cached per commit in ~/.cache/prereview and count only for a range that covers the commit's merge base with the PR's base. The push gate is off unless a clone turns it on (prereview.sh --install, a pre-push hook copied into .git/hooks), so nobody needs the Codex CLI unless they opt in. From a terminal the hook runs a missing review; from a non-interactive shell it refuses and says to run /pre-review first. test_prereview.sh covers the gate with a fake codex. Co-Authored-By: Claude Opus 5.5 * docs(pre-review): how to give Codex access to ChatGPT The script only checks that Codex has a login; nothing said how to make one. README.md (and the script's header and error messages) now name the two ways: `codex login` with a ChatGPT plan (--device-auth without a browser), or an OpenAI API key in OPENAI_API_KEY (or stored with `codex login --with-api-key`), with the one-line check, the CLI version the model needs, and where a key must never go. The skill tells Claude never to ask for the key in the chat. Co-Authored-By: Claude Opus 5.5 * fix(pre-review): no pinned prompts, no verdict; tests clean up and ignore the caller's env - With the pinned review prompts unreachable, the review used to fall back to this repository's guidance and cache a zero-count answer as clean, which the gate then trusted. A review by other rules must not stand in for the bot's: it now ends "not reviewed" (found by the skill's own pre-review of this change). - From CodeRabbit's review: every test run left its temporary repositories behind, and an inherited OPENAI_API_KEY (or PREREVIEW_BASE / PREREVIEW_TIMEOUT) changed what the cases test — with a key set, the logged-out case passed for the wrong reason. An EXIT trap removes the run's folder, and the variables are unset before the cases run. Co-Authored-By: Claude Opus 5.5 * fix(pre-review): a verdict is for exactly its range; the API key codex exec reads From thepastaclaw's review of this PR: - A cached verdict was accepted when its base was any ancestor of the current merge base. That is not the same diff: a branch that undoes a change the base made after the reviewed base shows the undo in the current range and not in the reviewed one. The recorded base must now equal the current merge base; a base that moved means a new review. Regression test: master advances to the branch's first commit, the same tip goes stale, master back, clean again. - codex exec (0.163) reads an API key from CODEX_API_KEY; OPENAI_API_KEY alone is ignored, so the documented environment-only setup passed the check and then failed in Codex. The check accepts CODEX_API_KEY, copies OPENAI_API_KEY into it, and the docs name CODEX_API_KEY. - --status exits 0 when HEAD has no report; a blank line before the new CLAUDE.md heading. From this change's own pre-review (the skill, on itself, three rounds at effort high): - the hook and --status checked the merge base against the local copy of the base, so a base that moved on origin since the last fetch did not make a verdict stale: the base is fetched first, into its remote-tracking ref (a single-branch clone's plain fetch updates only FETCH_HEAD), and a fetch that fails refuses the push (the range is unknown) — unless the push only deletes; - GIT_DIR / GIT_WORK_TREE, which git exports to its hooks, reached the review's worktree and would have made git there resolve the checkout's HEAD: cleared at the top, as githooks(5) says; - a signal to the script did not reach the review it had started: the lock holder ran on and could publish a verdict after the cancellation. INT/TERM/HUP are forwarded to it, and it runs codex in the background so its trap fires at once, stops codex and cleans up; - the test harness went on after a failed cd and would have made its fixture commits in the caller's checkout: setup steps now abort the run; - the docs said the bot re-reviews the whole range on every push; its pinned policy reviews the whole range once and later pushes against the findings it carries forward. The whole-range pass here is this skill's choice, said so. - The review runs at reasoning effort high (PREREVIEW_EFFORT), the bot's own setting for this model; codex exec's default is lower, which is one reason it missed these. Co-Authored-By: Claude Fable 5.1 * fix(pre-review): the model's commands never see the reviewer's credentials From thepastaclaw's second review (security-auditor): codex's default shell_environment_policy hands the whole environment to every command the model runs, so a branch under review could make the reviewer run `printenv CODEX_API_KEY` and put the key in its answer, which this script prints and keeps. And its read-only sandbox lets those commands read the whole disk, ~/.codex/auth.json included, so a stored login was exposed the same way. Both confirmed on codex 0.163 with canary values: visible by default, gone with the changes below. The commands the model runs now get an explicit environment allowlist (include_only, applied last, so a `set` entry in the user's own codex config cannot bring a credential back), git pointed at an empty global config (the user's may carry a PAT in a url.insteadOf or an extraheader), a scratch folder of the review's own as TMPDIR (not the shared temp dirs, where another review keeps its files), and a permission profile instead of -s read-only (the two do not compose; a sandbox_mode in the user's config is fine — the session's default_permissions wins, checked): they may read the review's own --shared clone of the commit (not a linked worktree: codex resolves a linked worktree's project trust through the main checkout, and a trusted one would load the reviewed tree's .codex/config.toml), the object stores it borrows (alternates, recursively — a --shared or --reference checkout needs them), the pinned prompts and the minimal system paths. Codex's ways out of the sandbox are switched off and read back: the user's MCP servers by name with a complete entry (`-c mcp_servers={}` merges instead of clearing, and a partial `.enabled=false` for a server the desktop app provides breaks codex's config load), the implicit Apps connector, browser and computer use and web search through `features.*` and `web_search`. A copy of the login in a private CODEX_HOME is not the way either: codex rotates refresh tokens, and a copy left behind by a cancelled review would break the user's login. The clone carries the base as origin has it (its origin/ would be the checkout's stale local branch), and a verdict records that base tip: a base that moved on, even without changing the merge base, was never checked against the branch, so the verdict goes stale. codex older than 0.163.0 (no permission profiles) or a capability that does not read back as off make the review refuse. A failed removal of an earlier verdict is no longer ignored: removed, or emptied, or the review refuses and says the gate still trusts it. The prompt asks for a static review — the first real pass ran the test suite in the sandbox until the 25-minute cap. The report is scrubbed of the key's value, README prefers `codex login --with-api-key` over an environment variable, and --install and --uninstall refuse under a shared core.hooksPath: the gate is per clone. From CodeRabbit: "for every pushed commit" read as a review per commit; one review of merge_base..tip covers the commits in between. Reworded in SKILL.md, README.md and the header. From this change's own pre-review: - the lock's descriptor was inherited by every child that can outlive a cancelled review (git fetch and clone, curl, codex and its probes), so a stray one kept the commit locked after the cancellation: they all start without it, in the background with a wait so a signal reaches the trap at once even while a fetch or a probe stalls (probes write to files, never `$(…)`: a foreground subshell defers the trap), and cleanup and cancellation traps are set from the first step; tests cancel during a stalled fetch, a stalled probe, and with a timeout that does not kill the group; - the test harness inherited the caller's git configuration and git's environment overrides: with a global or GIT_CONFIG_COUNT-supplied core.hooksPath its --install and --uninstall would have written to, and deleted from, the caller's real hooks folder, and a GIT_INDEX_FILE would have taken the fixture's `git add`. All of it cleared for the run; - a push of several refs: a ref accepted against the base as fetched, then the next ref's own review fetches a base that moved meanwhile — every tip is checked once more at the end (the test calls the hook directly: git puts its exec path first in a hook's PATH, so a wrapper never reaches it); the cleanup tests look at the review's folder itself, not `git worktree list`; - the review tree was cloned and checked out with the user's git config in force: a relative core.hooksPath (.githooks) resolves inside the clone, and the reviewed commit's own post-checkout hook would have run there, outside every restriction — hooks are off while the tree is made; - a cancelled automatic review inside the hook let the loop start the next ref's review: the hook stops on it; an empty `codex --version` skipped the version guard: refused. The skill reviewed this change nine times. Each round found a real but smaller hole in the previous fix, which is the pattern the tool exists for, seen from the other side — so SKILL.md now says: at most two rounds per push, then push and let the bot judge. Co-Authored-By: Claude Fable 5.1 * fix(pre-review): check for the Codex CLI before probing it; scope the test's pkill to its own hook From CodeRabbit: the version probe ran before the existence check, so a missing CLI ended in "gave no version" and the install guidance was unreachable — the check comes first now; and the cancellation test's pkill matched any "hooks/pre-push origin" on the machine, a real push's hook in another clone included — it matches this run's hook path only. Co-Authored-By: Claude Fable 5.1 * test(pre-review): escape the hook path before pkill -f (CodeRabbit) Co-Authored-By: Claude Fable 5.1 * fix(pre-review): no execpolicy rules or user config for the review; MCP roster read from the clone From thepastaclaw's third review: - the user's execpolicy allow rules (~/.codex/rules) could let a matching command run outside the sandbox, and the user's config.toml came along: codex exec runs with --ignore-rules and --ignore-user-config (the login still loads), and ~/.codex is an explicit deny in the profile — an allow rule for `cat` did not reach a canary file on 0.163 in a test, the flags are defence in depth; - MCP discovery and verification ran in the source checkout while exec runs in the review clone — different configuration contexts (a trusted checkout's own .codex/config.toml could mask a global server): both probes now run from the clone (-C); - the hook fetches the base once more before its final recheck, so a base that moved during a minutes-long review is seen. Co-Authored-By: Claude Fable 5.1 * docs(pre-review): the rules of the loop — PR scope, 2–3 local rounds, blocking/major only, push back Co-Authored-By: Claude Fable 5.1 * fix(pre-review): checkout under no user git config; probes and exec from inside the clone; keep config.toml From thepastaclaw's fourth review: - the review tree was checked out with the user's global/system git config in force, so a filter..smudge registered there ran for paths the reviewed commit's .gitattributes selects — the commit's code, outside every restriction: clone and checkout run with GIT_CONFIG_GLOBAL=/dev/null, GIT_CONFIG_NOSYSTEM=1 and no environment-supplied config (hooks stay off); a test registers such a filter and checks it stays quiet; - codex's -C does not move `mcp list`'s configuration context, so the probes still read the caller's checkout: the probes and exec now run with their working directory inside the review clone; - --ignore-user-config dropped a keyring-backed login (cli_auth_credentials_store): removed rather than carrying the store setting over. What config.toml could open is switched off and read back in the same context — MCP servers by name, apps/browser/computer use/web search — and --ignore-rules keeps the execpolicy allow rules out. Also the four rules of the loop in SKILL.md: only the PR's own code, two local rounds per push, locally blocking/major only, push back when a finding is out of scope or immaterial. Co-Authored-By: Claude Opus 5.5 * fix(pre-review): MCP servers disabled in their own transport; lifecycle hooks off; the tool's scope written down From thepastaclaw's fifth review: - the disable entry `{ command = "/bin/sh", enabled = false }` merged with an HTTP server's `url`, and codex refused the configuration ("url is not supported for stdio") — the review could not start for anyone with an HTTP MCP server. The entry now follows the server's transport (`url` for http), checked on codex 0.163; the fake codex models the rejection; - codex lifecycle hooks from the user's trusted config ran outside the sandbox in the review clone: features.hooks=false, read back with the other capabilities. And the scope, in README and SKILL.md: the review is for our own branches before push — code the developer already builds and runs. It is not a sandbox for a hostile branch; the isolation it does apply is defence in depth. Findings of the class "a branch written to attack the reviewer escapes the review's isolation" are answered with this scope rather than with another isolation layer; a defect that breaks the review for an ordinary user is fixed. Co-Authored-By: Claude Opus 5.5 * fix(pre-review): TOML-escape paths in the codex configuration; python3 checked and documented From thepastaclaw's sixth review (no blocking findings left; two suggestions): - paths (CODEX_HOME, the review's temp folders, the prompt cache, alternate object stores) went into the permission profile and the env `set` as raw TOML strings, so a quote or backslash in one made the configuration invalid: each is encoded with JSON string escapes, valid in TOML basic strings; a test reviews with a TMPDIR holding both and parses the result back with tomllib; - python3 does the verdict lookup, the lock, the JSON work: the script checks for it first and says so, and README lists it with git. Co-Authored-By: Claude Opus 5.5 * fix(pre-review): any MCP server name codex accepts; literal UTF-8 in TOML paths; tomllib optional in tests From thepastaclaw's seventh review, the narrowest fix for each: - the name filter ^[A-Za-z0-9_-]+$ refused valid names (docs.internal, npm:@scope/x), so the review never started for those users: the filter is gone, and the servers are switched off in one `mcp_servers={ "" = {…}, … }` table with quoted keys — codex splits a dotted -c path on every dot, so the per-server form could not address them. Checked on codex 0.163; - json.dumps escaped non-BMP characters as UTF-16 surrogates, which TOML rejects: ensure_ascii=False; the path round-trip test now has an emoji in it; - that test needs tomllib (3.11+) while the script needs 3.8: it is skipped on an older python3, and README says so. Also rule 5 in SKILL.md: fix a bot's suggestion only when it is a line or two of the existing code — two of these three came from the previous round's suggestion fixes. Co-Authored-By: Claude Opus 5.5 * test(pre-review): unset the fake codex's controls before the cases run From thepastaclaw's eighth review (no blocking findings; one suggestion, a one-line fix): FAKE_* variables inherited from the caller could steer unrelated cases. Checked by running the suite with FAKE_LOGIN_RC=1, FAKE_FEAT_STUBBORN=1 and FAKE_LAST set in the caller's environment: all pass. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: andreika-baranouski Co-authored-by: Claude Opus 5.5 --- .claude/skills/pre-review/README.md | 83 ++++ .claude/skills/pre-review/SKILL.md | 93 +++++ .claude/skills/pre-review/prereview.sh | 420 ++++++++++++++++++++ .claude/skills/pre-review/test_prereview.sh | 302 ++++++++++++++ CLAUDE.md | 9 +- 5 files changed, 906 insertions(+), 1 deletion(-) create mode 100644 .claude/skills/pre-review/README.md create mode 100644 .claude/skills/pre-review/SKILL.md create mode 100755 .claude/skills/pre-review/prereview.sh create mode 100755 .claude/skills/pre-review/test_prereview.sh diff --git a/.claude/skills/pre-review/README.md b/.claude/skills/pre-review/README.md new file mode 100644 index 0000000000..6503bf6ca7 --- /dev/null +++ b/.claude/skills/pre-review/README.md @@ -0,0 +1,83 @@ +# pre-review + +Review a dash-wallet branch the way thepastaclaw will, before it is pushed. The review runs GPT-6.1 "Sol", the +model of the bot's second phase, through the Codex CLI, with the bot's public review prompts. In Claude Code, run +`/pre-review`. In a terminal, run `.claude/skills/pre-review/prereview.sh`. `SKILL.md` describes what Claude +does with the findings. + +## Setup: give Codex access to ChatGPT + +The script never reads a key from this repository and never asks for one. Codex keeps its own login, and the +script only checks that one exists (`codex login status`, or `CODEX_API_KEY` in the environment). Pick one of +the options below. + +```bash +npm i -g @openai/codex@latest # 0.163.0 or newer (the script checks): permission profiles and the model on a ChatGPT plan +``` +`python3` (3.8 or newer) and `git` must be on `PATH` as well; the script checks for `python3` before anything else. +(`test_prereview.sh` skips its one TOML round-trip check on a python3 older than 3.11, which has no `tomllib`.) + +**A. A ChatGPT plan (Plus, Pro, Team).** No key: the review uses the plan's quota. +```bash +codex login # opens a browser; sign in with the ChatGPT account +codex login --device-auth # on a machine without a browser (over SSH): prints a link and a one-time code +``` +Codex stores the login in `~/.codex/auth.json` (mode 600) and refreshes it. The plan has to serve the model. +Check: +```bash +codex exec --skip-git-repo-check -m gpt-6.1-sol "Reply: OK" +``` +"The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account" means the CLI is too old, or +the plan does not include the model. + +**B. An OpenAI API key** from platform.openai.com. This is billed per request. +```bash +printenv CODEX_API_KEY | codex login --with-api-key # store it in Codex's own login (~/.codex/auth.json), then unset it +``` +`CODEX_API_KEY` in the environment works too (`OPENAI_API_KEY` is copied into it), but prefer the stored login. Keep +the key out of your shell profile (a login shell would put it back), this repository, `local.properties`, +`service.properties`, commits, issues and chats. + +**What it is for, and what it does not defend against.** The review is for your own branches before you push +them: the code under review is code you already build and run on this machine (Gradle runs its build scripts, the +tests run its classes). It is not a sandbox for reviewing a hostile branch. Codex runs with your Codex login and +loads your `config.toml`; a branch written to attack the reviewer is out of scope, the same as for building it. +Review someone else's untrusted branch only in a throwaway environment. + +Within that scope the review still keeps the model away from what it does not need, as defence in depth: the +commands the model runs get a bare environment with the key names excluded, +and a Codex permission profile instead of the read-only sandbox (whose reads cover the whole disk): they may read +the review's own clone of the commit (not a linked worktree: Codex would resolve its project trust through this +checkout), the repository's object store it borrows, the pinned prompts and the minimal system paths, and write only +under a scratch folder of the review's own. Your MCP servers (Codex starts those outside the sandbox) are switched off +by name for the review and the roster is read back; if one stays enabled, the script does not review. They do not +see your git configuration either (a PAT in a `url.insteadOf` or an `extraheader` would be readable): git in there +runs with an empty global config, and the commands' environment is an explicit allowlist. Codex runs with `--ignore-rules`: your execpolicy allow rules +(`~/.codex/rules`, a matching command may skip the sandbox) stay out of the review. Your `config.toml` does load (it +may choose a keyring login store); what it could open is switched off and read back from inside the review clone, +the same context the review runs in (lifecycle hooks included). `~/.codex` is an explicit deny in the profile, and the tree is checked out under +none of your git configuration (no hooks, no `filter.*` commands). Codex's other ways out of the sandbox — the implicit Apps connector, browser and computer use, +web search — are switched off for the review and read back. The report is scrubbed of the key's value as well. + +`codex logout` removes a stored login. `codex login status` shows which one is active. + +## Use + +```bash +.claude/skills/pre-review/prereview.sh # review HEAD against origin/master +PREREVIEW_BASE=origin/release-x .claude/skills/pre-review/prereview.sh # a PR into another branch +.claude/skills/pre-review/prereview.sh --status # the cached verdict of HEAD, and where its report is +.claude/skills/pre-review/prereview.sh --install # turn the push gate on for this clone +.claude/skills/pre-review/prereview.sh --uninstall # turn it off +``` + +| Variable | Default | | +|---|---|---| +| `PREREVIEW_BASE` | `origin/master` | the PR's base. Set it for the push too when the PR targets another branch | +| `PREREVIEW_MODEL` | `gpt-6.1-sol` | the model passed to `codex exec -m` | +| `PREREVIEW_EFFORT` | `high` | the model's reasoning effort (thepastaclaw's phase 2 runs at high); `xhigh` is deeper and slower | +| `PREREVIEW_TIMEOUT` | `1500` | seconds before a review is abandoned (needs `timeout`) | +| `CODEX_API_KEY` | unset | option B above; prefer the stored login (`OPENAI_API_KEY` is copied into it when set) | + +Reports and verdicts are kept per commit in `~/.cache/prereview/.{md,json}`. The pinned review prompts are +cached in `~/.cache/pastaclaw//`. `test_prereview.sh` tests the script offline with a fake `codex`. diff --git a/.claude/skills/pre-review/SKILL.md b/.claude/skills/pre-review/SKILL.md new file mode 100644 index 0000000000..c9c798ae82 --- /dev/null +++ b/.claude/skills/pre-review/SKILL.md @@ -0,0 +1,93 @@ +--- +name: pre-review +description: Review this branch the way thepastaclaw will, before pushing it — GPT-6.1 "Sol" (the bot's own model) through the Codex CLI with the bot's public review prompts over merge_base..HEAD, then verify each finding against the code and fix the whole class of each one. Use before every push of a PR branch, when the user says "pre-review", "review before push", "will PastaClaw approve this", or when a push is denied by the pre-review gate. +--- + +# pre-review + +thepastaclaw reviews the whole PR range on its first pass, then each pushed commit against the findings it carries +forward, and approves only when nothing is left at any severity: blocking, suggestion or nitpick. Most later-round +findings sit on code written to fix the earlier ones. So review the whole range (this skill's choice: the net diff +is what lands) with the same model and the same rules first, and push only when it is clean. + +The review runs in `.claude/skills/pre-review/prereview.sh`. It caches the verdict per commit, so a push right +after a clean review is instant. The push gate (below) checks that cache. + +## Run it + +1. Commit first. The review covers `merge-base(origin/master, HEAD)..HEAD`, committed work only. For a PR into + another branch, set `PREREVIEW_BASE=origin/`. +2. Start the review **in the background**, because it takes a few minutes and is longer than a Bash call may wait: + ```bash + .claude/skills/pre-review/prereview.sh + ``` + Use `run_in_background: true` and wait for it to finish. Do not poll it. +3. If it exits 2 (not reviewed), the message says why: the Codex CLI is missing, it has no access to ChatGPT, + or the login does not serve the model. Tell the user how to set it up (`README.md` → Setup: `codex login` + with a ChatGPT plan, or `CODEX_API_KEY`) and stop. Never ask for the key in the chat or write it anywhere. Do not + review the range yourself under its name: a Claude review shares Claude's blind spots, which is why this runs + on the bot's model. + +## Act on it + +The report is printed and kept in `~/.cache/prereview/.md`; `--status` shows the verdict of HEAD. + +- **Verify every finding** against the code at HEAD: open the lines and walk the sequence it describes. Drop a + finding the code does not support, and say why. Keep one even if it looks unlikely. +- **Fix the class, not the line.** Name the rule each finding breaks, then `git grep` every other place it must + hold: callers, legacy / resume / retry / restore / background paths, the other screen that shows the same value. + A sibling the review did not name is the next round's finding. +- **Prefer narrowing or reverting to adding a mechanism.** A new cap, latch, mutex or persistence layer is + reviewed again at funds-safety depth. +- **Suggestions and nitpicks count.** Any open one withholds the bot's approval, and most are cheap. +- Show the user a table (severity · file:line · finding · verified? · fix) before you change code, and follow the + repository's conventions (CLAUDE.md, `.claude/agents/DEVELOPMENT-PATTERNS.md`). +- After the fixes, commit and run the review again. The new commit is a new range. **At most two rounds per + push.** A fix adds code, and the next round reads that code with the same eyes: on a long-running change the + rounds stop converging (this skill's own branch took 9 rounds on one of the bot's findings, each round a real + but smaller hole in the previous fix). After the second round, push what is there and let thepastaclaw be the + judge — its round is cheaper than ours, it runs four passes, and it carries findings forward anyway. Say in + the PR what the last round still listed. +- A pre-existing problem the change neither introduced nor is responsible for is not a finding: the bot leaves + those out too, so drop it. A finding that IS in scope but that the user decides to defer needs a tracking issue + linked on the PR, or the bot keeps reporting it. Draft that issue for the user; do not open it yourself. + +## Scope + +This reviews **our own branches before we push them**. The branch is code the developer already builds and runs here, +so it is not treated as hostile: Codex runs with the developer's login and Codex config. The isolation the script +does apply (permission profile, environment allowlist, MCP servers and other out-of-sandbox capabilities off) is +defence in depth, not a sandbox for hostile code. A finding of the class "a branch written to attack the reviewer +escapes the review's isolation" is outside this scope: answer it with that, per rule 4 below, rather than adding +another isolation layer. A defect that breaks the review for an ordinary user (it fails to start, it loses the +login) is in scope and gets fixed. + +## The rules of the loop + +1. **Only the PR's own code.** A finding on code this change does not touch is not fixed quietly: answer the + reviewer with why it is not this change's concern. (Its scope rule says a change is responsible for a sibling + path it affects — then either fix that path or argue the point, on the thread.) +2. **Two local rounds per push, three at most.** When each round finds holes in the previous fix, get out with + the smallest change, or ask the user what to do next. +3. **Locally, blocking and major only.** Suggestions and nitpicks wait for the bot's own round, where they are + cheap to close and where its approval needs them closed. +4. **Push back when a comment is not about our code or does not matter in our case**: reply with the reasons, + do not resolve the thread — the bot re-checks on reply. +5. **The narrowest fix, never a new mechanism for a suggestion.** Fix a bot's suggestion only when it is a line or + two of the existing code; otherwise answer it and defer. On this skill's own PR, two of the three blockers of a + round came from the previous round's suggestion fixes. + +Pushing is the user's call. Push only when asked. + +## The push gate (per clone, opt-in) + +```bash +.claude/skills/pre-review/prereview.sh --install # on: a git pre-push hook (a copy under .git/hooks) +.claude/skills/pre-review/prereview.sh --uninstall # off +``` +With the gate on, a push to dash-wallet needs, for each pushed ref's tip, a review with no blocking findings of +exactly its range over `origin/master` (or `PREREVIEW_BASE`) — one review covers the commits in between; a base that +moved means a new review. From a terminal the hook runs a +missing review itself. From a non-interactive shell (Claude Code included) it refuses at once and says to run the +review first: then run this skill and push again. `git push --no-verify` is the deliberate bypass. Run +`--install` again after this script changes, because the hook is a copy. diff --git a/.claude/skills/pre-review/prereview.sh b/.claude/skills/pre-review/prereview.sh new file mode 100755 index 0000000000..c3e26d62fb --- /dev/null +++ b/.claude/skills/pre-review/prereview.sh @@ -0,0 +1,420 @@ +#!/usr/bin/env bash +# Pre-review a branch the way thepastaclaw will, before it is pushed: OpenAI's GPT-6.1 "Sol" (the model of the bot's +# second phase) through the Codex CLI, with the bot's own public prompts, over merge_base..HEAD. +# +# Why: the bot reviews the whole range on its first pass, then every pushed commit against the findings it carries +# forward, and approves only at zero findings, so every push with a finding we could have seen costs a round. One +# review of the whole range (the net diff is what lands) before the push is the cheap round. +# +# prereview.sh review HEAD against origin/master (PREREVIEW_BASE=origin/ for another base; +# PREREVIEW_EFFORT=xhigh for a deeper, slower pass, default high) +# prereview.sh --status the cached verdict of HEAD +# prereview.sh --install turn the push gate on for this clone (a git pre-push hook) +# prereview.sh --uninstall turn it off again +# (as .git/hooks/pre-push) (git) +# +# Access to ChatGPT (README.md, "Setup") is Codex's own login, never a key in this repository: +# npm i -g @openai/codex@latest, then ONE of +# codex login a ChatGPT plan (browser); `codex login --device-auth` without a browser +# printenv CODEX_API_KEY | codex login --with-api-key an OpenAI API key, stored in Codex's own login (preferred: +# CODEX_API_KEY / OPENAI_API_KEY in the environment work too, but see README.md) +# check: codex exec --skip-git-repo-check -m gpt-6.1-sol "Reply: OK" +# +# The gate is per clone and off by default. With it on, a push to dash-wallet needs, for each pushed ref's tip, a +# cached review of exactly merge_base(base, tip)..tip with no blocking findings (one review covers the commits in +# between) — a base that moved means a new review: an older range hides what the branch undoes of the base's later +# changes. +# From a terminal the hook runs a missing review itself; from a non-interactive push (an agent's shell) it refuses +# at once and says to run the review first. Reviews are cached per commit in ~/.cache/prereview/.{json,md}. The +# base is PREREVIEW_BASE, else origin/master — set it for the push too when the PR targets another branch. The +# hook is a copy under .git/, so checking out a branch without this script keeps the gate; --install again after +# the script changes. A deliberate bypass is `git push --no-verify`. +set -uo pipefail +# git exports these to its hooks; left in place they make every git command inside the review's worktree (and the +# model's) resolve the ORIGINAL checkout's HEAD and index. Cleared first, as githooks(5) says a hook must. +unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_COMMON_DIR GIT_PREFIX GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES + +PC_SHA=65ecda75023b16e72406963bebd2ac141223df43 # thepastaclaw/skills, pinned; move it in a commit of its own +MODEL="${PREREVIEW_MODEL:-gpt-6.1-sol}" +EFFORT="${PREREVIEW_EFFORT:-high}" # the bot's phase 2 runs the model at high; codex exec's default is lower +MIN_CODEX=0.163.0 # permission profiles (0.138+) and the model on a ChatGPT plan (0.163+) +CACHE="${XDG_CACHE_HOME:-$HOME/.cache}" +PC="$CACHE/pastaclaw/$PC_SHA" +VERDICTS="$CACHE/prereview" +SELF="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")" +export PREREVIEW_VERDICTS="$VERDICTS" +say() { printf 'pre-review: %s\n' "$*" >&2; } +# python3 does the verdict lookup, the lock, the JSON parsing and publication: without it nothing here is reliable +command -v python3 >/dev/null || { say "python3 is required (README.md, Setup)"; exit 2; } +# a path as a TOML basic string: JSON string escapes (\" \\ \uXXXX …) are valid TOML ones, and json.dumps leaves / alone +toml_str() { python3 -c 'import json,sys; print(json.dumps(sys.argv[1], ensure_ascii=False))' "$1"; } # literal UTF-8: TOML rejects \ud83d-style surrogate escapes +# every child that can outlive a cancelled review (git fetch and clone, curl, codex) starts without the review's lock +# descriptor (review() takes it, see PREREVIEW_LOCK_FD): the lock is the review's own, and nothing left behind keeps it +nolock() { ( [[ "${PREREVIEW_LOCK_FD:-}" =~ ^[0-9]+$ ]] && eval "exec $PREREVIEW_LOCK_FD>&-"; exec "$@" ); } +codex_() { nolock codex "$@"; } +# a child in the background + wait, so a signal reaches this shell's trap at once (bash defers traps while a foreground +# child runs) and the trap can stop the child; a stalled fetch must not keep a cancelled review, and its lock, alive +CHILD_PID="" +waitfor() { + local rc; nolock "$@" & CHILD_PID=$! + wait "$CHILD_PID"; rc=$? + while [[ $rc -gt 128 ]] && kill -0 "$CHILD_PID" 2>/dev/null; do wait "$CHILD_PID"; rc=$?; done + CHILD_PID=""; return $rc +} + +is_dash_wallet() { [[ "$1" =~ [/:]dash-wallet(\.git)?/?$ ]]; } +base_ref() { printf '%s' "${PREREVIEW_BASE:-origin/master}"; } +# the base as origin has it now: a verdict is checked against the CURRENT merge base, so a stale local copy of the +# base must not stand in (the base may have moved since the last fetch). Fetched INTO its remote-tracking ref: a +# single-branch clone's fetch mapping covers only its own branch, and a plain `fetch origin ` there updates +# FETCH_HEAD, not origin/, which merge-base reads. +refresh_base() { + local base b; base=$(base_ref); [[ "$base" == origin/* ]] || return 0 # a local ref as the base is taken as it is + b=${base#origin/}; waitfor git -C "$1" fetch -q origin "+refs/heads/$b:refs/remotes/origin/$b" 2>/dev/null +} + +# verdict → clean | suggestions | blocking | stale (reviewed, but not over merge_base(base, sha)..sha +# against the base's current tip: another base, or the base moved) | none +read -r -d '' VERDICT_PY <<'PY' +import json, os, subprocess, sys +repo, sha = sys.argv[1:3] +base = os.environ.get("PREREVIEW_BASE") or "origin/master" +def git(*a): + r = subprocess.run(["git", "-C", repo, *a], capture_output=True, text=True) + return r, r.stdout.strip() +try: + rec = json.load(open(os.path.join(os.environ["PREREVIEW_VERDICTS"], sha + ".json"))) +except Exception: + print("none"); sys.exit() +_, need = git("merge-base", base, sha) +_, tip = git("rev-parse", "--verify", "-q", base + "^{commit}") +# the review must have been of exactly need..sha AND against the base as it is now. An older base is not enough even +# when it is an ancestor of need: a branch that undoes a change the base made after it shows the undo in need..sha +# only. And a base that moved on without changing the merge base was never checked against this branch. +ok = bool(need) and bool(tip) and (rec.get("base") or "") == need and (rec.get("base_tip") or "") == tip +print((rec.get("verdict") or "none") if ok else "stale") +PY +verdict() { python3 -c "$VERDICT_PY" "$@"; } + +fetch_prompts() { + mkdir -p "$PC" + local f ok=1 + for f in prompts/review-agent.md prompts/verifier-agent.md prompts/security-auditor.md \ + skills/dash-wallet/review.md skills/dash-wallet/project.md; do + [[ -s "$PC/$(basename "$f")" ]] && continue + # to a temporary name of its own (reviews of other commits may fetch at the same time), renamed only when + # complete: a cut-off download must not pass for the pinned prompt later + local part; part=$(mktemp "$PC/.$(basename "$f").XXXXXX") || { ok=0; continue; } + if waitfor curl -fsSL --max-time 30 "https://raw.githubusercontent.com/thepastaclaw/skills/$PC_SHA/$f" -o "$part" \ + && mv -f "$part" "$PC/$(basename "$f")"; then :; else rm -f "$part"; ok=0; fi + done + return $((1 - ok)) +} + +# review : writes $VERDICTS/.json + .md; 0 = no blocking findings, 1 = blocking, 2 = not reviewed. +# One review per commit at a time, so a slower, older review cannot publish over a newer one: python takes an exclusive +# flock(2) on $VERDICTS/..lock and then BECOMES this script (exec, the descriptor inherited), so the lock lives +# exactly as long as the review itself; the kernel releases it when that process exits or dies. +review() { + mkdir -p "$VERDICTS" + local pid rc + # a child, so the hook loop can go on; a signal to THIS process is forwarded to it, or a cancelled review + # would run on, hold the lock and publish a verdict nobody waits for + python3 -c ' +import fcntl, os, sys +fd = os.open(sys.argv[1], os.O_WRONLY | os.O_CREAT, 0o644) +try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) +except OSError: + print("pre-review: a review of this commit is already running", file=sys.stderr); sys.exit(2) +os.set_inheritable(fd, True) +os.environ["PREREVIEW_LOCK_FD"] = str(fd) # so the review can keep the lock to itself (closed for codex) +os.execv(sys.argv[2], sys.argv[2:])' "$VERDICTS/.$2.lock" "$SELF" --locked-review "$@" & pid=$! + trap 'kill -TERM "$pid" 2>/dev/null' INT TERM HUP + wait "$pid"; rc=$? + while [[ $rc -gt 128 ]] && kill -0 "$pid" 2>/dev/null; do wait "$pid"; rc=$?; done # wait was interrupted, not done + trap - INT TERM HUP + return $rc +} + +review_locked() { + local repo=$1 sha=$2 base mb out log json rc + # cleanup and cancellation from the first step on: what is allocated below is recorded as it comes + CLEANUP_WT="" CLEANUP_OUT="" CLEANUP_LOG="" CLEANUP_PROBE="" CODEX_PID="" + trap '[[ -n "$CLEANUP_WT" ]] && rm -rf "$CLEANUP_WT"; [[ -n "$CLEANUP_OUT" ]] && rm -f "$CLEANUP_OUT" "$CLEANUP_LOG"; [[ -n "$CLEANUP_PROBE" ]] && rm -f "$CLEANUP_PROBE"' EXIT + trap 'kill -TERM "${CODEX_PID:-}" "${CHILD_PID:-}" 2>/dev/null; exit 130' INT TERM HUP + # first: a re-review that fails at any step must not leave an earlier verdict standing — removed, or at least emptied + # (an unwritable cache folder), and if neither works the record stays and so does the push gate's trust in it: say so + local old + for old in "$VERDICTS/$sha.json" "$VERDICTS/$sha.md"; do + rm -f "$old" 2>/dev/null; [[ -e "$old" ]] && : > "$old" 2>/dev/null + [[ -s "$old" ]] && { say "cannot drop the earlier record $old (permissions?): the push gate still trusts it — fix that first"; return 2; } + done + base=$(base_ref) + refresh_base "$repo" || { say "cannot fetch $base from origin, so the range to review is unknown: not reviewed"; return 2; } + mb=$(git -C "$repo" merge-base "$base" "$sha") || { say "no merge base of $sha and $base"; return 2; } + mkdir -p "$VERDICTS" + if [[ "$mb" == "$sha" ]]; then # the commit is on the base: nothing of ours in the range (the record keeps that base) + printf '{"verdict": "clean", "counts": {}, "base": "%s", "base_tip": "%s", "base_ref": "%s", "model": "none: no commits over the base"}' \ + "$mb" "$(git -C "$repo" rev-parse --verify -q "$base^{commit}")" "$base" > "$VERDICTS/.$sha.json.$$" && mv "$VERDICTS/.$sha.json.$$" "$VERDICTS/$sha.json" + say "${sha:0:10} has no commits over $base, nothing to review"; return 0 + fi + # an older codex accepts the permission-profile settings below without applying them: full-disk reads again + # probes run under waitfor into files, never in $(…): a command substitution is a foreground subshell, and bash + # defers the cancellation trap until it returns — a stalled probe would keep the lock + command -v codex >/dev/null || { say "the Codex CLI is not installed: npm i -g @openai/codex@latest (README.md, Setup)"; return 2; } + local probe ver; probe=$(mktemp); CLEANUP_PROBE=$probe + waitfor codex --version > "$probe" 2>/dev/null; ver=$(grep -oE '[0-9]+\.[0-9]+\.[0-9]+' "$probe" | head -1) + [[ -n "$ver" ]] || { say "codex --version gave no version: not reviewing"; return 2; } + if [[ "$(printf '%s\n' "$ver" "$MIN_CODEX" | sort -t. -k1,1n -k2,2n -k3,3n | head -1)" != "$MIN_CODEX" ]]; then + say "codex-cli $ver is older than $MIN_CODEX, which ignores the permission profile this review relies on: npm i -g @openai/codex@latest"; return 2 + fi + # codex exec (0.163) reads an API key from CODEX_API_KEY, not OPENAI_API_KEY; the familiar name is accepted and copied + [[ -n "${OPENAI_API_KEY:-}" && -z "${CODEX_API_KEY:-}" ]] && export CODEX_API_KEY="$OPENAI_API_KEY" + waitfor codex login status >/dev/null 2>&1 || [[ -n "${CODEX_API_KEY:-}" ]] \ + || { say "Codex has no access to ChatGPT: codex login (a ChatGPT plan) or CODEX_API_KEY (an API key); README.md, Setup"; return 2; } + # the bot's own rules or no verdict: a review by other rules must not be cached as one the gate trusts + fetch_prompts || { say "cannot fetch the pinned review prompts (thepastaclaw/skills@${PC_SHA:0:10}): not reviewed, try again"; return 2; } + local rules="these files exactly: $PC/review-agent.md (scope, required checks, severities), $PC/review.md and \ +$PC/project.md (dash-wallet rules), and for money, keys, identities, persistence or dependency changes $PC/security-auditor.md" + local wt; wt=$(mktemp -d "${TMPDIR:-/tmp}/prereview.XXXXXX"); out=$(mktemp); log=$(mktemp) + # this runs as its own process (review() execs it), so process-level traps clean up on Ctrl-C and kill too + CLEANUP_WT=$wt CLEANUP_OUT=$out CLEANUP_LOG=$log # one path each, always quoted: TMPDIR may hold spaces + # a clone of its own, not a linked worktree: codex resolves a linked worktree's project trust through the main + # checkout, and a trusted one would let the reviewed tree's .codex/config.toml into the configuration. --shared: + # the objects stay in the repository (read through alternates, granted below), only the files are checked out + # no hooks while the tree is materialized: a relative core.hooksPath in the user's config (.githooks) would resolve + # inside the review clone, and the reviewed commit's own post-checkout hook would run here, outside every restriction + # and none of the user's git configuration: a filter..smudge/process registered there runs on checkout for + # every path the reviewed commit's .gitattributes points at it — the commit's own code, outside every restriction + waitfor env -u GIT_CONFIG_COUNT -u GIT_CONFIG_PARAMETERS GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ + git -c core.hooksPath=/dev/null clone -q --shared --no-checkout "$repo" "$wt/tree" 2>/dev/null \ + && env -u GIT_CONFIG_COUNT -u GIT_CONFIG_PARAMETERS GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ + git -c core.hooksPath=/dev/null -C "$wt/tree" checkout -q --detach "$sha" 2>/dev/null \ + || { say "cannot check out ${sha:0:10} to review it"; return 2; } + # the clone's origin/ would be the checkout's LOCAL branch of that name (behind, or absent in a single-branch + # checkout); the review needs the base as origin has it, fetched above: set that in the clone, name it in the prompt + local base_tip; base_tip=$(git -C "$repo" rev-parse --verify -q "$base^{commit}") \ + && git -c core.hooksPath=/dev/null -C "$wt/tree" update-ref "refs/remotes/origin/${base#origin/}" "$base_tip" 2>/dev/null \ + || { say "cannot resolve $base in the checkout"; return 2; } + # what the model's commands may read: the tree, the object stores it borrows (alternates, recursively), the pinned + # prompts and the minimal system paths; writes only in its own scratch folder (macOS git's xcrun cache). Not the user's + # git configuration: a PAT in a url.insteadOf or an http.extraheader would be readable — git in there gets an empty + # global config of its own instead (GIT_CONFIG_GLOBAL below) + : > "$wt/gitconfig" + # the user's MCP servers would start outside the sandbox (a filesystem server for ~ hands auth.json over), and + # `-c mcp_servers={}` merges instead of clearing: every effective server (plugins' included) is switched off by name, + # and the roster is read back — anything still enabled means no review. Listed and verified from the review clone + # (its working directory: codex's -C does not move `mcp list`'s configuration context), as codex exec runs: a + # trusted source checkout's own .codex/config.toml could mask a server there, or point an HTTP one at an attacker + local mcp_off=() mcp_tab="" name + waitfor sh -c 'cd "$1" && shift && exec "$@"' sh "$wt/tree" codex mcp list --json > "$probe" 2>/dev/null + local transport + while IFS=$'\t' read -r name transport; do + [[ -n "$name" ]] || continue + # a complete entry, not `.enabled=false` alone: a server another layer provides (the desktop app's) is not in + # config.toml, and a partial override of it leaves an entry without a command — codex then fails to load at all. + # Of the server's own transport: the entry merges with the existing one, and a `command` next to an http + # server's `url` is rejected ("url is not supported for stdio") + # one `mcp_servers` table with quoted keys, not `-c mcp_servers.=…`: names may hold `.` `:` `@` `/`, and codex + # splits a dotted -c path on every dot; the table merges into the existing servers like the per-server form did + if [[ "$transport" == stdio ]]; then mcp_tab+="${mcp_tab:+, }$(toml_str "$name") = { command = \"/bin/sh\", enabled = false }" + else mcp_tab+="${mcp_tab:+, }$(toml_str "$name") = { url = \"http://127.0.0.1:9/\", enabled = false }"; fi + done < <(python3 -c 'import json,sys +try: print("\n".join(e["name"] + "\t" + str((e.get("transport") or {}).get("type") or "stdio") for e in json.load(open(sys.argv[1])) if e.get("enabled"))) +except Exception: pass' "$probe") + [[ -n "$mcp_tab" ]] && mcp_off=(-c "mcp_servers={ $mcp_tab }") + waitfor sh -c 'cd "$1" && shift && exec "$@"' sh "$wt/tree" codex ${mcp_off[@]+"${mcp_off[@]}"} mcp list --json > "$probe" 2>/dev/null + if [[ -n "$(python3 -c 'import json,sys +try: print("".join(e["name"] for e in json.load(open(sys.argv[1])) if e.get("enabled"))) +except Exception: print("?")' "$probe")" ]]; then say "an MCP server stays enabled for codex: not reviewing"; return 2; fi + # codex's other ways out of the sandbox: the implicit Apps connector (never in `mcp list`), browser and computer use, + # web search (a query can carry data out), lifecycle hooks. Off for the review, and read back: each must show false + local feat_off=(-c features.apps=false -c features.browser_use=false -c features.browser_use_external=false \ + -c features.browser_use_full_cdp_access=false -c features.computer_use=false -c features.in_app_browser=false -c 'web_search="disabled"' \ + -c features.hooks=false) # lifecycle hooks: run outside the sandbox, in the clone, from the user's trusted config + waitfor sh -c 'cd "$1" && shift && exec "$@"' sh "$wt/tree" codex "${feat_off[@]}" features list > "$probe" 2>/dev/null + if [[ "$(awk '$1 ~ /^(apps|browser_use|browser_use_external|browser_use_full_cdp_access|computer_use|in_app_browser|hooks)$/ && $NF == "false"' "$probe" | wc -l | tr -d ' ')" != 7 ]]; then + say "a codex capability outside the sandbox (apps, browser or computer use, lifecycle hooks) does not read back as off: not reviewing"; return 2 + fi + # the model's scratch: its own folder (TMPDIR below), not the shared temp dirs where other reviews keep their files + mkdir -m 700 "$wt/tmp" || { say "cannot create $wt/tmp"; return 2; } + local fs alt queue=("$wt/tree/.git/objects") seen=" " + # an explicit deny on the codex home as well: codex skips the sandbox for a command an allow rule matches unless the + # profile holds an explicit Deny (an implicit one, a path simply not granted, does not count) + fs="\":minimal\" = \"read\", $(toml_str "$wt/tmp") = \"write\", $(toml_str "$wt/gitconfig") = \"read\", $(toml_str "$PC") = \"read\", $(toml_str "${CODEX_HOME:-$HOME/.codex}") = \"deny\"" + while [[ ${#queue[@]} -gt 0 ]]; do + local objs=${queue[0]}; queue=("${queue[@]:1}") + [[ -f "$objs/info/alternates" ]] || continue + while IFS= read -r alt; do + [[ -n "$alt" && "${alt:0:1}" != "#" ]] || continue + [[ "$alt" == /* ]] || alt=$(cd "$objs" && cd "$alt" 2>/dev/null && pwd) + [[ -n "$alt" && "$seen" != *" $alt "* ]] || continue + seen+="$alt "; fs+=", $(toml_str "$alt") = \"read\""; queue+=("$alt") + done < "$objs/info/alternates" + done + fs="{ $fs, \":workspace_roots\" = { \".\" = \"read\" } }" + say "reviewing $(git -C "$repo" rev-list --count "$mb..$sha") commit(s) ${mb:0:10}..${sha:0:10} with $MODEL (a few minutes)" + local tmo=(); command -v timeout >/dev/null && tmo=(timeout "${PREREVIEW_TIMEOUT:-1500}") + # in a subshell that first closes the lock's descriptor: the lock is this review's, not codex's — a child codex + # leaves behind (a timeout that could not kill the group, a stray helper) must not keep the commit locked + ( [[ "${PREREVIEW_LOCK_FD:-}" =~ ^[0-9]+$ ]] && eval "exec $PREREVIEW_LOCK_FD>&-" + # the branch under review is untrusted code, so the commands the model runs get (a) an environment that is an + # explicit allowlist, never the reviewer's credentials (codex's default hands them everything: printenv + # CODEX_API_KEY would answer; include_only is applied last, so it also drops a `set` entry from the user's own + # codex config), with git pointed at the empty config above, and (b) a permission profile instead of the read-only + # sandbox, whose reads cover the whole disk, ~/.codex/auth.json included + # --ignore-rules: the user's execpolicy allow rules (~/.codex/rules) let a matching command run OUTSIDE the sandbox. + # The user's config.toml does load (it may select a keyring login store); what it could open is closed above and + # read back in this same context: MCP servers off by name, apps/browser/computer use/web search off, environment + # an allowlist. Started from inside the clone, the context the probes read. + cd "$wt/tree" || exit 2 + exec ${tmo[@]+"${tmo[@]}"} codex exec --ignore-rules ${mcp_off[@]+"${mcp_off[@]}"} "${feat_off[@]}" -m "$MODEL" -c model_reasoning_effort="$EFFORT" -C "$wt/tree" -o "$out" \ + -c shell_environment_policy.inherit=core -c shell_environment_policy.ignore_default_excludes=false \ + -c 'shell_environment_policy.exclude=["CODEX_API_KEY","OPENAI_API_KEY","*_API_KEY","*TOKEN*","*SECRET*","*PASSWORD*"]' \ + -c "shell_environment_policy.set={ GIT_CONFIG_GLOBAL = $(toml_str "$wt/gitconfig"), GIT_CONFIG_NOSYSTEM = \"1\", TMPDIR = $(toml_str "$wt/tmp") }" \ + -c 'shell_environment_policy.include_only=["HOME","PATH","USER","LOGNAME","SHELL","TERM","LANG","LC_ALL","LC_CTYPE","TMPDIR","TMP","TEMP","PWD","GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM"]' \ + -c default_permissions=prereview -c "permissions.prereview.filesystem=$fs" \ + "$(cat <, "suggestion": , "nitpick": } +EOF +)" ) "$log" 2>&1 & # codex exec reads stdin until EOF; in the pre-push hook that is git's ref list + CODEX_PID=$!; wait "$CODEX_PID"; rc=$? # in the background + wait: bash runs a trap at once, not after a foreground child + while [[ $rc -gt 128 ]] && kill -0 "$CODEX_PID" 2>/dev/null; do wait "$CODEX_PID"; rc=$?; done + if [[ $rc -ne 0 || ! -s "$out" ]]; then + if [[ $rc -eq 124 ]]; then say "codex did not finish within ${PREREVIEW_TIMEOUT:-1500}s (PREREVIEW_TIMEOUT) — not reviewed"; else say "codex failed (exit $rc):"; tail -5 "$log" >&2; fi + [[ $rc -ne 124 ]] && grep -q "not supported when using Codex with a ChatGPT account" "$log" && say "this login does not serve $MODEL: \ +update the CLI (npm i -g @openai/codex@latest) and log in with a ChatGPT account that has it (README.md, Setup)" + rm -f "$out" "$log"; return 2 + fi + # belt and braces: a key that reached the answer by any other route is redacted before the report is shown or kept + python3 - "$out" <<'PY' +import os, sys +p = sys.argv[1]; t = open(p).read() +for v in ("CODEX_API_KEY", "OPENAI_API_KEY"): + k = os.environ.get(v, "") + if len(k) >= 8 and k in t: + t = t.replace(k, "[REDACTED " + v + "]") +open(p, "w").write(t) +PY + cat "$out"; echo + json=$(grep -v '^[[:space:]]*$' "$out" | tail -1) # the counts must be the LAST line + python3 - "$VERDICTS/$sha.json" "$json" "$mb" "$base" "$MODEL" "$out" "$base_tip" <<'PY' || { rm -f "$out" "$log"; return 2; } +import json, os, shutil, sys, tempfile, datetime +path, line, mb, base, model, report, base_tip = sys.argv[1:8] +try: + c = json.loads(line) + assert isinstance(c, dict) and all(isinstance(c.get(k), int) and not isinstance(c.get(k), bool) and c[k] >= 0 + for k in ("blocking", "suggestion", "nitpick")) +except Exception: + print("pre-review: the review did not end with a valid counts line, so it counts as not reviewed", file=sys.stderr) + sys.exit(1) +v = "blocking" if c["blocking"] else ("suggestions" if c["suggestion"] or c["nitpick"] else "clean") +def publish(target, write): # a temporary file in the same folder, then one rename: readers never see half a record + fd, tmp = tempfile.mkstemp(dir=os.path.dirname(target), prefix="." + os.path.basename(target) + ".") + with os.fdopen(fd, "w") as fh: + write(fh) + os.replace(tmp, target) +publish(path[:-5] + ".md", lambda fh: fh.write(open(report).read())) +publish(path, lambda fh: json.dump({"verdict": v, "counts": c, "base": mb, "base_tip": base_tip, "base_ref": base, "model": model, + "at": datetime.datetime.now(datetime.timezone.utc).isoformat()}, fh)) +print(f"pre-review: verdict {v} {c} (report: {path[:-5]}.md)", file=sys.stderr) +PY + rm -f "$out" "$log" + [[ "$(verdict "$repo" "$sha")" != blocking ]] || return 1 +} + +if [[ "${1:-}" == --locked-review ]]; then # review() runs this under the lock + shift; review_locked "$@"; exit $? +fi + +if [[ "$(basename "$0")" == pre-push ]]; then + is_dash_wallet "${2:-}" || exit 0 + repo=$(git rev-parse --show-toplevel) + zero=0000000000000000000000000000000000000000; refused=0; shas=() + while read -r _lref lsha _rref _rsha; do + [[ "$lsha" == "$zero" ]] && continue # a deletion sends no code + # an annotated tag arrives as the tag object: the code it carries is its commit + lsha=$(git -C "$repo" rev-parse -q --verify "$lsha^{commit}") || { say "a pushed ref is not a commit"; exit 1; } + shas+=("$lsha") + done + [[ ${#shas[@]} -eq 0 ]] && exit 0 # deletions only: nothing to review, and no need to reach origin + refresh_base "$repo" || { say "cannot fetch $(base_ref) from origin to check the pushed range: not pushing"; exit 1; } + for lsha in ${shas[@]+"${shas[@]}"}; do + v=$(verdict "$repo" "$lsha") + if [[ ( "$v" == none || "$v" == stale ) && -t 2 ]]; then + review "$repo" "$lsha" >&2; rc=$? + [[ $rc -gt 128 ]] && { say "cancelled: not pushing"; exit 1; } # a cancelled review must not start the next ref's + v=$(verdict "$repo" "$lsha") + fi + case "$v" in + clean) ;; + suggestions) say "${lsha:0:10}: suggestions only (the bot will comment, not approve); pushing" ;; + blocking) say "${lsha:0:10}: blocking findings, see $VERDICTS/$lsha.md"; refused=1 ;; + stale) say "${lsha:0:10}: reviewed over another range, or before $(base_ref) moved: run the review again \ +(/pre-review, or .claude/skills/pre-review/prereview.sh), then push"; refused=1 ;; + *) say "${lsha:0:10}: not reviewed: run /pre-review (or .claude/skills/pre-review/prereview.sh) on it, then push \ +(git push --no-verify pushes anyway, on purpose)"; refused=1 ;; + esac + done + # the base may have moved since an earlier ref was accepted against it, or during a review above: fetched once + # more, and every tip checked once more against the base as it is now + refresh_base "$repo" || { say "cannot fetch $(base_ref) from origin for the final check: not pushing"; exit 1; } + for lsha in ${shas[@]+"${shas[@]}"}; do + v=$(verdict "$repo" "$lsha") + [[ "$v" == clean || "$v" == suggestions ]] || { say "${lsha:0:10}: the base moved while this push was being reviewed ($v): run the review again, then push"; refused=1; } + done + exit $refused +fi + +case "${1:-}" in + --install|--uninstall) + repo=$(git rev-parse --show-toplevel) || exit 2 + hooks=$(git -C "$repo" rev-parse --path-format=absolute --git-path hooks) + mkdir -p "$hooks" || { say "cannot create $hooks"; exit 2; } + mark="# installed by .claude/skills/pre-review/prereview.sh --install" + if [[ -n "$(git -C "$repo" config --get core.hooksPath 2>/dev/null)" ]]; then # a shared hooks folder is not this clone's + say "core.hooksPath is set, so the hooks folder is shared with other clones; the gate is per clone — unset it here first"; exit 2 + fi + if [[ "$1" == --uninstall ]]; then + grep -qF "$mark" "$hooks/pre-push" 2>/dev/null && rm -f "$hooks/pre-push" + grep -qF "$mark" "$hooks/pre-push" 2>/dev/null && { say "could not remove $hooks/pre-push: the gate is still ON"; exit 2; } + say "push gate off for $repo"; exit 0 + fi + is_dash_wallet "$(git -C "$repo" remote get-url origin 2>/dev/null)" || { say "origin is not dash-wallet"; exit 2; } + if [[ -e "$hooks/pre-push" ]] && ! grep -qF "$mark" "$hooks/pre-push"; then + say "$hooks/pre-push exists and is not this script: not replacing it, so the gate is NOT on"; exit 2 + fi + if ! { { head -1 "$SELF"; echo "$mark"; tail -n +2 "$SELF"; } > "$hooks/pre-push.tmp" && chmod +x "$hooks/pre-push.tmp" \ + && mv -f "$hooks/pre-push.tmp" "$hooks/pre-push" && cmp -s <(tail -n +3 "$hooks/pre-push") <(tail -n +2 "$SELF"); }; then + rm -f "$hooks/pre-push.tmp"; say "could not write $hooks/pre-push: the gate is NOT on (or is an older copy)"; exit 2 + fi + say "push gate on for $repo ($hooks/pre-push, a copy: run --install again after this script changes)" + ;; + --status) + repo=$(git rev-parse --show-toplevel) || exit 2; sha=$(git -C "$repo" rev-parse HEAD) + refresh_base "$repo" || say "note: could not fetch $(base_ref); the verdict below is against the local copy of it" + hook=$(git -C "$repo" rev-parse --path-format=absolute --git-path hooks)/pre-push + printf 'gate: %s\nbase: %s\nHEAD %s: %s\n' "$(grep -qF 'prereview.sh --install' "$hook" 2>/dev/null && echo on || echo off)" \ + "$(base_ref)" "${sha:0:10}" \ + "$(verdict "$repo" "$sha")" + [[ -s "$VERDICTS/$sha.md" ]] && echo "report: $VERDICTS/$sha.md" + exit 0 # a status query that found no report is still a successful query + ;; + "") + repo=$(git rev-parse --show-toplevel) || exit 2 + is_dash_wallet "$(git -C "$repo" remote get-url origin)" || { say "origin is not dash-wallet"; exit 2; } + review "$repo" "$(git -C "$repo" rev-parse HEAD)" + ;; + *) sed -n 2,31p "$0"; exit 2 ;; +esac diff --git a/.claude/skills/pre-review/test_prereview.sh b/.claude/skills/pre-review/test_prereview.sh new file mode 100755 index 0000000000..7aca84d56f --- /dev/null +++ b/.claude/skills/pre-review/test_prereview.sh @@ -0,0 +1,302 @@ +#!/usr/bin/env bash +# Tests prereview.sh with a fake codex on PATH (no quota, no network). Run: bash ; non-zero on failure. +set -u +# setup must never fall through into the caller's checkout: a failed cd there would put the fixture's commits in it +cd() { builtin cd "$@" || { echo "FAIL: cannot cd $*" >&2; exit 1; }; } +need() { "$@" || { echo "FAIL: setup: $*" >&2; exit 1; }; } +P=${1:-"$(cd "$(dirname "$0")" && pwd)/prereview.sh"}; T=$(mktemp -d "${TMPDIR:-/tmp}/prtest.XXXXXX") || exit 1; export XDG_CACHE_HOME="$T/cache"; FAILS=0 +[[ -n "${KEEP:-}" ]] || trap 'chmod -R u+w "$T" 2>/dev/null; rm -rf "$T"' EXIT # this run's folder only, writable again first (the chmod tests); KEEP=1 leaves it for a look +# the cases set these themselves: an inherited API key would pass the logged-out case, a base or timeout would move others +unset OPENAI_API_KEY CODEX_API_KEY PREREVIEW_BASE PREREVIEW_TIMEOUT PREREVIEW_MODEL FAKE_LOGIN_RC FAKE_VERSION FAKE_FEAT_STUBBORN FAKE_MCP FAKE_MCP_STUBBORN FAKE_REFRESH FAKE_LAST +# the caller's git configuration stays out too: a global core.hooksPath would make the fixture's --install and +# --uninstall write to, and delete from, the caller's real hooks folder +export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 +# the reviews' own temp dirs land here, so their removal can be checked directly +need mkdir -p "$T/tmpdir"; export TMPDIR="$T/tmpdir" +leftovers() { ls -d "$T/tmpdir"/prereview.* 2>/dev/null | wc -l | tr -d ' '; } +# nor git's repository overrides: a GIT_INDEX_FILE pointing at another checkout would take the fixture's `git add` +unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_COMMON_DIR GIT_PREFIX GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES +unset GIT_CONFIG_COUNT GIT_CONFIG_PARAMETERS; for v in $(compgen -e | grep -E '^GIT_CONFIG_(KEY|VALUE)_'); do unset "$v"; done # env config survives GIT_CONFIG_GLOBAL +need mkdir -p "$T/bin" +cat > "$T/bin/codex" <<'EOF' +#!/usr/bin/env bash +[[ "$1" == --version ]] && { echo "codex-cli ${FAKE_VERSION:-0.163.0}"; exit 0; } +[[ "$1" == login ]] && exit "${FAKE_LOGIN_RC:-0}" +if [[ " $* " == *" features list "* ]]; then # the six capabilities, each off when its -c features.=false came + for n in apps browser_use browser_use_external browser_use_full_cdp_access computer_use in_app_browser hooks; do + if [[ -n "${FAKE_FEAT_STUBBORN:-}" || " $* " != *" features.$n=false "* ]]; then echo "$n stable true"; else echo "$n stable false"; fi + done; exit 0 +fi +if [[ " $* " == *" mcp list "* ]]; then # the effective servers (FAKE_MCP), each off when a -c mcp_servers..enabled=false came + printf '%s\n' "$@" > "${FAKE_CDIR}.mcpargs"; pwd -P > "${FAKE_CDIR}.mcpcwd" + python3 -c ' +import json, sys +# servers as name or name|http; the override is one `mcp_servers={ "" = {…}, … }` table, as the script passes it +ents = [e.split("|") + ["stdio"] for e in sys.argv[1].split(",") if e]; args = sys.argv[3:]; stubborn = sys.argv[2] == "1" +tab = " ".join(a for a in args if a.startswith("mcp_servers=")) +out = [] +for e in ents: + n, t = e[0], e[1]; key = json.dumps(n, ensure_ascii=False) + if t != "stdio" and (key + " = { command = \"/bin/sh\", enabled = false }") in tab: + print("Error: url is not supported for stdio", file=sys.stderr); sys.exit(1) + off = (key + " = { command = \"/bin/sh\", enabled = false }") if t == "stdio" else (key + " = { url = \"http://127.0.0.1:9/\", enabled = false }") + out.append({"name": n, "enabled": stubborn or off not in tab, "transport": {"type": "stdio" if t == "stdio" else "streamable_http"}}) +print(json.dumps(out))' "${FAKE_MCP:-}" "${FAKE_MCP_STUBBORN:-0}" "$@" + exit 0 +fi +printf '%s\n' "$@" > "${FAKE_CDIR}.args"; pwd -P > "${FAKE_CDIR}.execcwd" # before the loop below consumes them +while [[ $# -gt 0 ]]; do [[ "$1" == -o ]] && { out=$2; shift; }; [[ "$1" == -C ]] && { cdir=$2; echo "$2" > "$FAKE_CDIR"; shift; }; shift; done +echo "${CODEX_API_KEY:-}" > "${FAKE_CDIR}.key"; echo "${GIT_DIR:-unset}" > "${FAKE_CDIR}.gitdir" +git -C "$cdir" rev-parse HEAD > "${FAKE_CDIR}.head" 2>/dev/null # what git inside the review's folder sees +git -C "$cdir" rev-parse --path-format=absolute --git-common-dir > "${FAKE_CDIR}.commondir" 2>/dev/null +git -C "$cdir" rev-parse origin/master > "${FAKE_CDIR}.base" 2>/dev/null +echo "${CODEX_HOME:-unset}" > "${FAKE_CDIR}.home"; cat "${CODEX_HOME:-/nonexistent}/auth.json" > "${FAKE_CDIR}.auth" 2>/dev/null +[[ -e "${CODEX_HOME:-/nonexistent}/config.toml" ]] && echo yes > "${FAKE_CDIR}.cfg" || echo no > "${FAKE_CDIR}.cfg" +[[ -n "${FAKE_REFRESH:-}" ]] && echo "$FAKE_REFRESH" >> "${CODEX_HOME}/auth.json" +printf 'finding text\n%s\n' "$FAKE_LAST" > "$out" +EOF +chmod +x "$T/bin/codex"; export PATH="$T/bin:$PATH" FAKE_CDIR="$T/cdir" +PCSHA=$(sed -n 's/^PC_SHA=\([0-9a-f]*\).*/\1/p' "$P"); mkdir -p "$XDG_CACHE_HOME/pastaclaw/$PCSHA" # prompts seeded: no network +for f in review-agent verifier-agent security-auditor review project; do echo "# $f" > "$XDG_CACHE_HOME/pastaclaw/$PCSHA/$f.md"; done +# the user's codex home, with a dummy login and a config full of things the review must not load +export CODEX_HOME="$T/userhome"; need mkdir -m 700 "$CODEX_HOME" +printf '{"auth_mode":"apikey","OPENAI_API_KEY":"k-dummy-login"}\n' > "$CODEX_HOME/auth.json"; chmod 600 "$CODEX_HOME/auth.json" +printf '[mcp_servers.fs]\ncommand = "evil"\n' > "$CODEX_HOME/config.toml" +# tty : run with a terminal on stdin/stdout/stderr (script(1): BSD/macOS and util-linux take different arguments); +# its stdin stays open a while, so an early EOF cannot close the pty under the command +tty() { + if script --version 2>/dev/null | grep -q util-linux; then SHELL=$(command -v bash) script -qec "$(printf '%q ' "$@")" /dev/null < <(sleep 15) # util-linux runs the command through $SHELL; %q quoting is bash's + else script -q /dev/null "$@" < <(sleep 15); fi +} +ok() { if [[ "$2" == "$3" ]]; then echo "ok $1"; else echo "FAIL $1: got '$2', want '$3'"; FAILS=$((FAILS+1)); fi; } + +# a fake upstream with master and release, and a clone whose origin URL looks like dash-wallet +need git init -q --bare "$T/dash-wallet.git" +need git clone -q "$T/dash-wallet.git" "$T/seed" 2>/dev/null; cd "$T/seed" +g() { git -c user.email=t@t -c user.name=t "$@"; } +echo a > a; g add a; g commit -qm a; g push -q origin HEAD:master +g checkout -q -b release; echo r > r; g add r; g commit -qm r; g push -q origin release +g checkout -q master; echo b > b; g add b; g commit -qm b; g push -q origin master +need git clone -q "$T/dash-wallet.git" "$T/app"; cd "$T/app"; need git fetch -q origin release +g checkout -q -b feat origin/master; echo c > c; g add c; g commit -qm c; FEAT=$(git rev-parse HEAD) +g checkout -q -b other origin/master; echo d > d; g add d; g commit -qm d; OTHER=$(git rev-parse HEAD) +g checkout -q feat + +V() { PREREVIEW_VERDICTS="$XDG_CACHE_HOME/prereview" "$P" --status | sed -n 's/^HEAD [0-9a-f]*: //p'; } +FAKE_LAST='{"blocking": null, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok "null count → not reviewed (exit 2)" "$?" 2 +ok " … and no verdict cached" "$(V)" none +FAKE_LAST='no counts at all' "$P" >/dev/null 2>&1; ok "missing counts line → exit 2" "$?" 2 +FAKE_LAST=$'{"blocking": 0, "suggestion": 0, "nitpick": 0}\nreview incomplete' "$P" >/dev/null 2>&1; ok "counts not on the last line → exit 2" "$?" 2 +FAKE_LAST='{"blocking": -1, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok "negative count → exit 2" "$?" 2 +FAKE_LAST='{"blocking": 1, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok "blocking → exit 1" "$?" 1 +ok " … verdict blocking" "$(V)" blocking +FAKE_LAST='{"blocking": 0, "suggestion": 2, "nitpick": 0}' "$P" >/dev/null 2>&1; ok "suggestions → exit 0" "$?" 0 +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok "clean → exit 0" "$?" 0 +ok " … verdict clean" "$(V)" clean +GIT_DIR="$T/app/.git" GIT_WORK_TREE="$T/app" FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok "GIT_DIR/GIT_WORK_TREE from the caller (a hook's environment) do not reach the review" "$?:$(cat "$T/cdir.gitdir")" 0:unset +ok " … reviewed in a separate worktree, not the working tree" "$([[ "$(cat "$T/cdir")" != "$T/app" && "$(cat "$T/cdir")" == */tree ]] && echo yes)" yes +ok " … and the review's folder is gone after" "$(leftovers)" 0 +real() { python3 -c 'import os,sys; print(os.path.realpath(sys.argv[1]))' "$1"; } +ok " … it is a clone of its own, not a linked worktree (no trust inherited from this checkout)" "$(real "$(cat "$T/cdir.commondir")")" "$(real "$(cat "$T/cdir")")/.git" +FAKE_LAST='garbled' "$P" >/dev/null 2>&1; ok "a failed re-review drops the earlier clean verdict" "$(V)" none +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +FAKE_LOGIN_RC=1 "$P" >/dev/null 2>&1; ok "a re-review with Codex logged out → exit 2" "$?" 2 +ok " … and drops the earlier clean verdict too" "$(V)" none +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; chmod a-w "$XDG_CACHE_HOME/prereview" +FAKE_LOGIN_RC=1 "$P" >/dev/null 2>&1; ok "unwritable cache folder: a failed re-review still empties the earlier record" "$?:$(V)" 2:none +chmod u+w "$XDG_CACHE_HOME/prereview" +FAKE_LOGIN_RC=1 CODEX_API_KEY=k-codex FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok "logged out, CODEX_API_KEY set → reviewed with it" "$?:$(cat "$T/cdir.key")" 0:k-codex +FAKE_LOGIN_RC=1 OPENAI_API_KEY=k-openai FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok "logged out, OPENAI_API_KEY set → copied into CODEX_API_KEY for codex" "$?:$(cat "$T/cdir.key")" 0:k-openai +ok "the model's commands get a bare environment with the key excluded (codex policy flags)" "$(grep -c -e 'shell_environment_policy.inherit=core' -e 'CODEX_API_KEY","OPENAI_API_KEY' "$T/cdir.args")" 2 +ok " … and a permission profile: the tree, the repo's objects (alternates), the prompts, minimal system paths; no git config of the user's" \ + "$(grep -c 'default_permissions=prereview' "$T/cdir.args"):$(grep -c -e ":workspace_roots\" = { \".\" = \"read\" }" -e "\"$T/app/.git/objects\" = \"read\"" -e "pastaclaw/$PCSHA\" = \"read\"" "$T/cdir.args"):$(grep -c -e '~/.gitconfig" = ' -e '~/.config/git' -e '^-s$' "$T/cdir.args")" 1:1:0 +ok " … the commands' environment is an explicit allowlist, with git pointed at an empty config" \ + "$(grep -c 'shell_environment_policy.include_only=\["HOME"' "$T/cdir.args"):$(grep -c 'shell_environment_policy.set={ GIT_CONFIG_GLOBAL = ".*/gitconfig", GIT_CONFIG_NOSYSTEM = "1", TMPDIR = ' "$T/cdir.args")" 1:1 +need git clone -q --shared "$T/app" "$T/sharedclone" 2>/dev/null; cd "$T/sharedclone"; git remote set-url origin "$T/dash-wallet.git"; g checkout -q feat +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok "a --shared clone: its alternates and theirs are granted, recursively" "$?:$(grep -c 'sharedclone/.git/objects" = "read"' "$T/cdir.args"):$(grep -c 'app/.git/objects" = "read"' "$T/cdir.args")" 0:1:1 +cd "$T/app" +FAKE_FEAT_STUBBORN=1 FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok "a capability outside the sandbox that stays on (apps, browser, computer use) → not reviewed (exit 2)" "$?:$(V)" 2:none +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok "apps, browser and computer use, web search and lifecycle hooks are switched off for the review" "$?:$(grep -c -e '^features.apps=false$' -e '^features.computer_use=false$' -e '^web_search="disabled"$' -e '^features.hooks=false$' "$T/cdir.args")" 0:4 +FAKE_MCP="canaryfs,second" FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok "the user's MCP servers are switched off by name for the review" "$?:$(grep -c '^mcp_servers={ "canaryfs" = { command = "/bin/sh", enabled = false }, "second" = { command = "/bin/sh", enabled = false } }$' "$T/cdir.args")" 0:1 +FAKE_MCP="docs|http,loc" FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok " … an http server gets an entry of its own transport (a stdio one next to its url fails codex's config load)" "$?:$(grep -c '"docs" = { url = "http://127.0.0.1:9/", enabled = false }' "$T/cdir.args")" 0:1 +FAKE_MCP="stubborn" FAKE_MCP_STUBBORN=1 FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok " … one that stays enabled → not reviewed (exit 2), no verdict" "$?:$(V)" 2:none +FAKE_MCP="docs.internal|http,npm:@scope/seq.thinking" FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok " … names with . : @ / (accepted by codex) are switched off too, both transports" "$?:$(grep -c -e '"docs.internal" = { url = ' -e '"npm:@scope/seq.thinking" = { command = ' "$T/cdir.args")" 0:1 +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok "exec ignores the user's execpolicy rules but keeps config.toml (a keyring login store); the codex home is an explicit deny" \ + "$(grep -c '^--ignore-rules$' "$T/cdir.args"):$(grep -c '^--ignore-user-config$' "$T/cdir.args"):$(grep -c "\"$CODEX_HOME\" = \"deny\"" "$T/cdir.args")" 1:0:1 +CLONE=$(python3 -c 'import os,sys; print(os.path.realpath(sys.argv[1]))' "$(cat "$T/cdir")") +ok "MCP probes and exec run with their working directory inside the review clone (the same configuration context)" "$(cat "$T/cdir.mcpcwd"):$(cat "$T/cdir.execcwd")" "$CLONE:$CLONE" +ok "the model's scratch is the review's own folder, not the shared temp dirs" \ + "$(grep -c -e "\"$(dirname "$(cat "$T/cdir")")/tmp\" = \"write\"" "$T/cdir.args"):$(grep -c 'TMPDIR = ".*/tmp" }' "$T/cdir.args"):$(grep -c -e ':tmpdir' -e ':slash_tmp' "$T/cdir.args")" 1:1:0 +FAKE_VERSION=0.100.0 FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok "an older codex (no permission profiles) → not reviewed (exit 2)" "$?:$(V)" 2:none +FAKE_VERSION=0.163.0 FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok " … 0.163.0 → reviewed" "$?" 0 +FAKE_VERSION=" " FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok " … no version at all → not reviewed (exit 2)" "$?" 2 +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +CODEX_API_KEY=k-leak-me-4471 FAKE_LAST=$'leaked: k-leak-me-4471\n{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" > "$T/rep.out" 2>&1 +ok "a key that reaches the answer is redacted in the printed and in the kept report" "$(grep -l 'k-leak-me-4471' "$T/rep.out" "$XDG_CACHE_HOME/prereview/"*.md 2>/dev/null | wc -l | tr -d ' '):$(grep -c 'REDACTED CODEX_API_KEY' "$T/rep.out")" 0:1 +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +H=$(git rev-parse HEAD); python3 -c 'import fcntl,sys,time; f=open(sys.argv[1],"a"); fcntl.flock(f,fcntl.LOCK_EX); time.sleep(300)' \ + "$XDG_CACHE_HOME/prereview/.$H.lock" & LIVE=$!; sleep 1 +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok "a review of the same commit already running → exit 2, nothing touched (the running one owns the record)" "$?:$(V)" 2:clean +kill -9 $LIVE; wait $LIVE 2>/dev/null +FAKE_LAST='{"blocking": 1, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok "its holder was killed → the kernel released the lock, reviewed" "$?:$(V)" 1:blocking +# the lock lives as long as the review: hold it from inside a running review (a slow fake codex), then try another +printf '#!/usr/bin/env bash\n[[ "$1" == --version ]] && { echo codex-cli 0.163.0; exit 0; }\n[[ "$1" == login ]] && exit 0\n[[ " $* " == *" mcp list "* ]] && { echo "[]"; exit 0; }\n[[ " $* " == *" features list "* ]] && { for n in apps browser_use browser_use_external browser_use_full_cdp_access computer_use in_app_browser hooks; do echo "$n stable false"; done; exit 0; }\nsleep 4; while [[ $# -gt 0 ]]; do [[ "$1" == -o ]] && { echo "{\\"blocking\\": 0, \\"suggestion\\": 0, \\"nitpick\\": 0}" > "$2"; shift; }; shift; done\n' > "$T/bin/codex.slow" +chmod +x "$T/bin/codex.slow"; mkdir -p "$T/slow"; cp "$T/bin/codex.slow" "$T/slow/codex" +PATH="$T/slow:$PATH" "$P" >/dev/null 2>&1 & SLOW=$!; sleep 1 +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok "a second review while the first is inside codex → exit 2" "$?" 2 +wait $SLOW; ok " … the first one finishes and publishes" "$(V)" clean +# Ctrl-C signals the whole foreground process group: run the review in a group of its own and signal that +set -m; PATH="$T/slow:$PATH" "$P" >/dev/null 2>&1 & SLOW=$!; set +m; sleep 2; kill -INT -- -$SLOW 2>/dev/null; wait $SLOW 2>/dev/null; sleep 1 +ok "a review interrupted inside codex leaves no folder behind" "$(leftovers)" 0 +ok " … and no verdict (it was dropped when the review started)" "$(V)" none +PATH="$T/slow:$PATH" "$P" >/dev/null 2>&1 & SLOW=$!; sleep 2; kill -TERM $SLOW 2>/dev/null; wait $SLOW 2>/dev/null; sleep 1 +ok "TERM to the script's own pid alone → the review stops too (no folder, no verdict)" "$(leftovers):$(V)" 0:none +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok " … and a new review starts at once (the lock is free)" "$?" 0 +# cancelled while a codex probe stalls (login status here): the probe must not keep the lock either +need mkdir -p "$T/slowlogin"; printf '#!/usr/bin/env bash\n[[ "$1" == login ]] && { sleep 4; exit 0; }\nexec "%s/bin/codex" "$@"\n' "$T" > "$T/slowlogin/codex"; chmod +x "$T/slowlogin/codex" +PATH="$T/slowlogin:$PATH" "$P" >/dev/null 2>&1 & SLOW=$!; sleep 2; kill -TERM $SLOW 2>/dev/null; sleep 0.5 +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok "TERM during a stalled codex probe → the review stops at once, the lock is free" "$?" 0; wait $SLOW 2>/dev/null +# cancelled while still fetching the base: the fetch must not keep the lock either +REALGIT=$(command -v git); need mkdir -p "$T/slowgit"; printf '#!/usr/bin/env bash\n[[ " $* " == *" fetch "* ]] && sleep 4\nexec "%s" "$@"\n' "$REALGIT" > "$T/slowgit/git"; chmod +x "$T/slowgit/git" +PATH="$T/slowgit:$PATH" "$P" >/dev/null 2>&1 & SLOW=$!; sleep 2; kill -TERM $SLOW 2>/dev/null; sleep 0.5 +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok "TERM during a stalled base fetch → the review stops at once, the lock is free" "$?" 0; wait $SLOW 2>/dev/null +# a timeout that cannot kill the process group (or none at all): what codex leaves behind must not hold the lock +need mkdir -p "$T/faketimeout"; printf '#!/bin/sh\nshift; exec "$@"\n' > "$T/faketimeout/timeout"; chmod +x "$T/faketimeout/timeout" +PATH="$T/faketimeout:$T/slow:$PATH" "$P" >/dev/null 2>&1 & SLOW=$!; sleep 2; kill -TERM $SLOW 2>/dev/null; wait $SLOW 2>/dev/null; sleep 1 +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok " … same, with a timeout that does not kill the group: codex's leftover child holds no lock" "$?" 0 +mkdir -p "$T/tmp dir"; echo keep > "$T/tmp"; ( cd "$T" && TMPDIR="$T/tmp dir" FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 ) /dev/null 2>&1 +ok "TMPDIR with a space: cleanup removes only its own files" "$(cat "$T/tmp" 2>/dev/null):$(ls -A "$T/tmp dir" | wc -l | tr -d ' ')" keep:0 +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 # back to clean for what follows +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok "reviewed against master, required against release → stale" "$(PREREVIEW_BASE=origin/release V)" stale + +# a commit on the base: cached clean only for that base +g checkout -q -B onbase origin/master; "$P" >/dev/null 2>&1 +ok "commit on the base → clean for that base" "$(V)" clean +ok " … stale for a base it is not on" "$(PREREVIEW_BASE=origin/release V)" stale +# the base advances to a commit of the branch (its first commit landed): the same tip now has another net diff +MASTER=$(git rev-parse origin/master); g checkout -q -b two origin/master +echo p > p; g add p; g commit -qm p; FIRST=$(git rev-parse HEAD); echo q > q; g add q; g commit -qm q +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok "two-commit branch → clean" "$(V)" clean +git push -q origin "$FIRST:master"; ok " … master advanced on origin (not fetched here) → stale: the check refreshes the base" "$(V)" stale +git push -q -f origin "$MASTER:master"; ok " … master back → clean again" "$(V)" clean +# the base moves on without changing the merge base: what changed on it was never checked against this branch +( cd "$T/seed" && g checkout -q master && echo m2 > m2 && g add m2 && g commit -qm m2 && git push -q origin master ) 2>/dev/null +ok "origin/master moved independently (same merge base) → stale" "$(V)" stale +git push -q -f origin "$MASTER:master"; ok " … master back → clean again" "$(V)" clean +# the review clone must carry the base as origin has it, not this checkout's stale local master +g checkout -q -b drift origin/master; echo d2 > d2; g add d2; g commit -qm d2; git push -q origin "$FIRST:master" +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok "origin's master moved, local master stale → the review clone's origin/master is the fresh tip" "$?:$(cat "$T/cdir.base")" "0:$FIRST" +git push -q -f origin "$MASTER:master" +g checkout -q -b fresh origin/master; echo z > z; g add z; g commit -qm z +"$P" --status >/dev/null 2>&1; ok "--status of an unreviewed HEAD → exit 0" "$?" 0 +# a single-branch clone has no origin/master: the refresh must create it (a fetch into the tracking ref, not FETCH_HEAD) +need git clone -q --single-branch -b release "$T/dash-wallet.git" "$T/single" 2>/dev/null; cd "$T/single" +echo s > s; g add s; g commit -qm s +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1; ok "single-branch clone without origin/master → the base is fetched, reviewed" "$?:$(V)" 0:clean +cd "$T/app" +g checkout -q feat + +# the git pre-push hook (a copy under .git/hooks) +git push -q origin other 2>/dev/null; ok "no gate → git push passes" "$?" 0 +git config core.hooksPath "$T/sharedhooks"; "$P" --install >/dev/null 2>&1; ok "a shared hooks folder (core.hooksPath) → install refuses (exit 2), nothing written there" "$?:$([[ -e "$T/sharedhooks/pre-push" ]] && echo written || echo nothing)" 2:nothing +need mkdir -p "$T/sharedhooks"; printf '#!/bin/sh\n# installed by .claude/skills/pre-review/prereview.sh --install\n' > "$T/sharedhooks/pre-push" +"$P" --uninstall >/dev/null 2>&1; ok " … and uninstall refuses too, another clone's shared gate stays" "$?:$([[ -e "$T/sharedhooks/pre-push" ]] && echo stays || echo gone)" 2:stays +git config --unset core.hooksPath +"$P" --install >/dev/null 2>&1; ok "install" "$?" 0 +grep -q 'prereview.sh --install' .git/hooks/pre-push; ok " … the hook is a marked copy, not a symlink" "$?$([[ -L .git/hooks/pre-push ]] && echo L)" 0 +git push -q origin feat 2>/dev/null; ok "clean feat → pushed" "$?" 0 +g checkout -q -b other2 origin/master; echo e > e; g add e; g commit -qm e +s=$(date +%s); FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' git push -q origin other2 2>/dev/null +ok "unreviewed, non-interactive → refused, no review run" "$?:$(V)" 1:none +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' tty git push -q origin other2 > "$T/tty.log" 2>&1 +ok "unreviewed, from a terminal → the hook reviews it, clean → pushed" "$?:$(V)" 0:clean +g checkout -q -b other3 origin/master; echo f > f; g add f; g commit -qm f +FAKE_LAST='{"blocking": 2, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +git push -q origin other3 2>/dev/null; ok "blocking → refused" "$?" 1 +git push -q origin --delete feat 2>/dev/null; ok "deletion → allowed" "$?" 0 +# origin unreachable: a deletion to another dash-wallet remote needs no base and must pass; an update must not +need mkdir -p "$T/alt"; need git init -q --bare "$T/alt/dash-wallet.git"; git remote add alt "$T/alt/dash-wallet.git" +git push -q alt other3:refs/heads/doomed 2>/dev/null # other3 is reviewed (blocking) → refused; put the branch there without the hook +git push -q --no-verify alt other3:refs/heads/doomed 2>/dev/null +mv "$T/dash-wallet.git" "$T/dash-wallet.git.off" +git push -q alt --delete doomed 2>/dev/null; ok "origin down: deletion-only push to another remote → allowed (no fetch needed)" "$?" 0 +git push -q alt other3:refs/heads/x 2>/dev/null; ok "origin down: a push with code → refused (the range cannot be checked)" "$?" 1 +mv "$T/dash-wallet.git.off" "$T/dash-wallet.git" +g checkout -q -b other4 origin/master; echo h > h; g add h; g commit -qm h; g checkout -q other3 +FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' tty git push -q origin other4 > "$T/tty2.log" 2>&1 +ok "terminal push of a branch that is not checked out → reviewed (in its own worktree), pushed" "$?:$(g checkout -q other4; V; g checkout -q other3)" 0:clean +ok " … and git inside that worktree saw the pushed commit, not the checkout" "$(cat "$T/cdir.head")" "$(git rev-parse other4)" +g checkout -q other4; g tag -a v-test -m "annotated"; g checkout -q other3 +git push -q origin v-test 2>/dev/null; ok "an annotated tag on a reviewed commit → pushed" "$?" 0 +rm -rf "${XDG_CACHE_HOME:?}/pastaclaw"; mkdir -p "$T/bin2"; printf '#!/bin/sh\nfor a; do [ "$p" = -o ] && { echo partial > "$a"; exit 28; }; p=$a; done\n' > "$T/bin2/curl"; chmod +x "$T/bin2/curl" +g checkout -q other4; PATH="$T/bin2:$PATH" FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok "prompts cannot be fetched → not reviewed (exit 2), no verdict" "$?:$(V)" 2:none +ok " … and a cut-off download leaves nothing in the cache" "$(ls -A "$XDG_CACHE_HOME/pastaclaw/"* 2>/dev/null | wc -l | tr -d ' ')" 0 +need mkdir -p "$XDG_CACHE_HOME/pastaclaw/$PCSHA"; for f in review-agent verifier-agent security-auditor review project; do echo "# $f" > "$XDG_CACHE_HOME/pastaclaw/$PCSHA/$f.md"; done # seeded again: the cases below must not reach the network +# a reviewed commit carrying its own hooks, and a user config that points core.hooksPath at a relative folder: nothing may run +g checkout -q -b hooky origin/master; need mkdir -p .githooks; printf '#!/bin/sh\ntouch "%s/HOOK_RAN"\n' "$T" > .githooks/post-checkout; chmod +x .githooks/post-checkout; g add .githooks; g commit -qm hooky +printf '[core]\n\thooksPath = .githooks\n' > "$T/hookcfg" +GIT_CONFIG_GLOBAL="$T/hookcfg" FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok "the reviewed commit's own hooks do not run while its tree is checked out (relative core.hooksPath)" "$?:$([[ -e "$T/HOOK_RAN" ]] && echo RAN || echo quiet)" 0:quiet +# a smudge filter in the user's git config, selected by the reviewed commit's .gitattributes: it must not run either +g checkout -q -b filtery origin/master; echo '* filter=evil' > .gitattributes; echo payload > f.txt; g add .gitattributes f.txt; g commit -qm filtery +printf '[filter "evil"]\n\tsmudge = touch %s/FILTER_RAN; cat\n' "$T" > "$T/filtercfg" +GIT_CONFIG_GLOBAL="$T/filtercfg" FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok "a smudge filter from the user's git config does not run on the review's checkout" "$?:$([[ -e "$T/FILTER_RAN" ]] && echo RAN || echo quiet)" 0:quiet +# a TMPDIR whose path holds a double quote and a backslash: the profile and the env set stay valid TOML, one entry each +need mkdir -p "$T/q\"d\\ir😀"; g checkout -q other4; TMPDIR="$T/q\"d\\ir😀" FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +ok "paths with a quote, a backslash and a non-BMP character are valid TOML in the profile and the env set" "$?:$(python3 -c ' +import sys +try: import tomllib +except ImportError: print("2 True"); sys.exit() # tomllib is 3.11+; on an older python3 this check is skipped +args = open(sys.argv[1]).read().split("\n") +fs = [a for a in args if a.startswith("permissions.prereview.filesystem=")][0].split("=", 1)[1] +st = [a for a in args if a.startswith("shell_environment_policy.set=")][0].split("=", 1)[1] +t = tomllib.loads("x = " + fs); u = tomllib.loads("x = " + st) +print(sum(1 for k in t["x"] if "q\"d\\ir😀" in k), "q\"d\\ir😀" in u["x"]["TMPDIR"])' "$T/cdir.args" 2>&1)" "0:2 True" +g checkout -q feat +need mkdir -p "$T/nopy"; ln -sf "$(command -v dirname)" "$T/nopy/dirname" # all the script needs before its python3 check +env -i HOME="$HOME" PATH="$T/nopy" "$(command -v bash)" "$P" --status > "$T/nopy.log" 2>&1; ok "no python3 on PATH → a clear message, exit 2" "$?:$(grep -c 'python3 is required' "$T/nopy.log")" "2:1" +g checkout -q other4 +g checkout -q other3 +PREREVIEW_BASE=origin/release git push -q origin feat:refs/heads/feat2 2>/dev/null; ok "reviewed against master, PREREVIEW_BASE=release → refused (stale)" "$?" 1 +# two refs in one push: the first is accepted against the base as fetched, then the second's automatic review fetches a +# base that moved meanwhile — the first must be checked again (a git wrapper advances origin's master on the 2nd fetch) +g checkout -q -b other5 origin/master; echo i > i; g add i; g commit -qm i; g checkout -q feat +need mkdir -p "$T/racegit"; printf '#!/usr/bin/env bash\nif [[ " $* " == *" fetch "* ]]; then n=$(cat "%s/fetches" 2>/dev/null || echo 0); echo $((n+1)) > "%s/fetches"; [[ "$n" == 1 ]] && "%s" -C "%s/dash-wallet.git" update-ref refs/heads/master "%s"; fi\nexec "%s" "$@"\n' "$T" "$T" "$REALGIT" "$T" "$FIRST" "$REALGIT" > "$T/racegit/git"; chmod +x "$T/racegit/git" +# the hook is called directly with git's ref lines: git puts its own exec path first in PATH for hooks, so a wrapper +# named git on PATH never reaches a hook started by `git push` +HOOK=$(git rev-parse --path-format=absolute --git-path hooks)/pre-push; Z=0000000000000000000000000000000000000000 +printf 'refs/heads/feat %s refs/heads/feat-race %s\nrefs/heads/other5 %s refs/heads/other5 %s\n' "$(git rev-parse feat)" "$Z" "$(git rev-parse other5)" "$Z" > "$T/race.refs" +PATH="$T/racegit:$PATH" FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' tty bash -c "'$HOOK' origin '$T/dash-wallet.git' < '$T/race.refs'" > "$T/race.log" 2>&1 +# the refusal is read from the hook's own output: util-linux script(1) does not always hand the child's exit status on +ok "the base moved during the push's own review → the earlier ref is rechecked, push refused" "$(grep -c 'the base moved while this push' "$T/race.log"):$(cat "$T/fetches" 2>/dev/null)" 1:3 # fetches: up front, the review's, the final check's +g checkout -q other5; ok " … the later ref itself was reviewed against the moved base" "$(V)" clean; g checkout -q feat +# two unreviewed refs, cancelled during the first's review: the hook stops, the second is never started +g checkout -q -b c1 origin/master; echo c1 > c1; g add c1; g commit -qm c1; g checkout -q -b c2 origin/master; echo c2 > c2; g add c2; g commit -qm c2; g checkout -q feat +printf 'refs/heads/c1 %s refs/heads/c1 %s\nrefs/heads/c2 %s refs/heads/c2 %s\n' "$(git rev-parse c1)" "$Z" "$(git rev-parse c2)" "$Z" > "$T/cancel.refs" +PATH="$T/slow:$PATH" tty bash -c "'$HOOK' origin '$T/dash-wallet.git' < '$T/cancel.refs'" > "$T/cancel.log" 2>&1 & HK=$!; sleep 2; pkill -TERM -f "$(printf '%s' "$HOOK origin" | sed 's/[][\\.*^$+?(){}|]/\\&/g')" 2>/dev/null; wait $HK 2>/dev/null; sleep 1 +g checkout -q c2; ok "cancelled during the first ref's review → the hook stops, the second ref is never reviewed" "$(V):$(grep -c 'cancelled: not pushing' "$T/cancel.log")" none:1; g checkout -q feat +git -C "$T/dash-wallet.git" update-ref refs/heads/master "$MASTER"; FAKE_LAST='{"blocking": 0, "suggestion": 0, "nitpick": 0}' "$P" >/dev/null 2>&1 +cp "$P" "$T/moved.sh"; "$P" --uninstall >/dev/null 2>&1; "$T/moved.sh" --install >/dev/null 2>&1; mv "$T/moved.sh" "$T/gone.sh" +git push -q origin other3 2>/dev/null; ok "the installed script's source is gone → still gated" "$?" 1 +echo '#!/bin/sh' > .git/hooks/pre-push; "$P" --install >/dev/null 2>&1; ok "someone else's pre-push hook → install refuses (exit 2)" "$?" 2 +grep -q 'prereview' .git/hooks/pre-push; ok " … and leaves it alone" "$?" 1 +echo '#!/bin/sh' > .git/hooks/pre-push.keep; mv .git/hooks/pre-push.keep .git/hooks/pre-push; "$P" --uninstall >/dev/null 2>&1 +ok "uninstall leaves a foreign hook" "$(head -1 .git/hooks/pre-push)" '#!/bin/sh' +rm -f .git/hooks/pre-push; chmod a-w .git/hooks; "$P" --install >/dev/null 2>&1; ok "unwritable hooks folder → install fails (exit 2)" "$?" 2 +chmod u+w .git/hooks; "$P" --install >/dev/null 2>&1; ok " … writable again → installed" "$?" 0 +chmod a-w .git/hooks; "$P" --uninstall >/dev/null 2>&1; ok "unremovable hook → uninstall fails (exit 2)" "$?" 2; chmod u+w .git/hooks +echo "fails: $FAILS"; [[ -n "${KEEP:-}" ]] && echo "kept: $T"; exit $FAILS diff --git a/CLAUDE.md b/CLAUDE.md index 5ec039d771..3bda32b86a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -112,4 +112,11 @@ The app follows **MVVM (Model-View-ViewModel)** architecture with the following - The app supports both mainnet and testnet Dash networks - Exchange rate data comes from multiple sources (CTX, BitPay, Dash Central, etc.) - Supports NFC for Dash payment requests -- Uses dashj library for Dash-specific blockchain operations \ No newline at end of file +- Uses dashj library for Dash-specific blockchain operations + +## Before pushing a PR branch +PRs are reviewed by thepastaclaw, which approves only at zero findings and carries every finding forward across pushes. +Run `/pre-review` (`.claude/skills/pre-review/`) on the committed branch first: the same model with the bot's +prompts, findings verified and fixed by class. It needs the Codex CLI with access to ChatGPT (`codex login`, or +`CODEX_API_KEY`; see `.claude/skills/pre-review/README.md`). Turn on its push gate (a git pre-push hook) for a +clone with `.claude/skills/pre-review/prereview.sh --install`. From 050e5134e53f5d234b41f911ed52befa00569136 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 27 Oct 2026 15:35:42 -0700 Subject: [PATCH 3/3] docs(sakura): name the pinned SDK versions instead of 5.0.0-SNAPSHOT Co-Authored-By: Claude Opus 5.5 --- docs/sakura-devnet.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/sakura-devnet.md b/docs/sakura-devnet.md index a546f1e9d1..5384327a68 100644 --- a/docs/sakura-devnet.md +++ b/docs/sakura-devnet.md @@ -9,16 +9,17 @@ No DashJ release or key-derivation changes are required. ## Prerequisites -- An updated `5.0.0-SNAPSHOT` Platform SDK containing `NetworkConfiguration` - and the explicit-network native constructor, including rebuilt Android libraries. - The previously published snapshot without those APIs is not sufficient. +- No manual SDK install. The root `build.gradle` pins the legacy Platform SDK + (`dppVersion`, `5.0.0-20261016.200955-3`), which already has `NetworkConfiguration.sakura()` + and the explicit-network constructor, and the Kotlin SDK (`dashSdkVersion`, + `5.0.0-int31-20261019.192942-1`). Gradle resolves both from the snapshots repository. - Set `sakuraSporkAddress` in local.properties or with `-PsakuraSporkAddress=...`. This is the operator's public signing address, never a private key. No other devnet's address is substituted. Missing values fail the devnet build; malformed addresses are also rejected when constructing the network parameters. - Core port defaults to `20001` by assumption; override with `-PsakuraCorePort=...`. -Build with `./gradlew :wallet:assembleDevnetDebug` after installing the updated SDK. +Build with `./gradlew :wallet:assembleDevnetDebug`. The local, Git-ignored `wallet/google-services.json` must contain `org.dash.wallet.devnet` so Firebase-dependent startup workers can initialize.