Modern Apps git

← Modern-Apps.git

euicc: OpenEUICC parity for eSIM install path

Commit
60db344462c0796ba5134f7ebbece9794a9e8632
Author
vayun-mathur <[email protected]>
When
2026-09-27 01:28 UTC (2 months ago)
Parents
ce649c7

Diff

Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex b528fc849e..212d65e9b7 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1252,6 +1252,7 @@ dependencies = [  "jni_http",  "log",  "serde_json",+ "sha2 0.11.0", ]  [[package]]
euicc/src/main/AndroidManifest.xml
diff --git a/euicc/src/main/AndroidManifest.xml b/euicc/src/main/AndroidManifest.xmlindex 37f41115f7..5f52bcc1a0 100644--- a/euicc/src/main/AndroidManifest.xml+++ b/euicc/src/main/AndroidManifest.xml@@ -7,6 +7,8 @@     <uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE" />     <uses-permission android:name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.CAMERA" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+    <uses-permission android:name="android.permission.WAKE_LOCK" />     <uses-feature android:name="android.hardware.camera.any" android:required="false" />      <application@@ -48,6 +50,7 @@                 <action android:name="android.service.euicc.action.MANAGE_EMBEDDED_SUBSCRIPTIONS" />                 <action android:name="android.service.euicc.action.PROVISION_EMBEDDED_SUBSCRIPTION" />                 <category android:name="android.intent.category.DEFAULT" />+                <category android:name="android.service.euicc.category.EUICC_UI" />             </intent-filter>         </activity> @@ -78,16 +81,34 @@                     android:host="esimsetup.android.com"                     android:path="/esim_qrcode_provisioning" />             </intent-filter>+            <!-- Raw `lpa:` activation-code deep link alongside the universal link. -->+            <intent-filter>+                <action android:name="android.intent.action.VIEW" />+                <category android:name="android.intent.category.DEFAULT" />+                <category android:name="android.intent.category.BROWSABLE" />+                <data android:scheme="lpa" />+            </intent-filter>         </activity>          <service             android:name=".service.EuiccManagerService"             android:exported="true"             android:permission="android.permission.BIND_EUICC_SERVICE">-            <intent-filter android:priority="10">+            <intent-filter android:priority="100">                 <action android:name="android.service.euicc.EuiccService" />             </intent-filter>         </service>++        <!--+          Foreground lifetime guard for the BPP install phase (shortService:+          no extra permission beyond FOREGROUND_SERVICE, ~3 min budget, which+          covers a profile install; the wake lock has its own 10-min backstop).+          Started by EuiccViewModel around nativeFinishDownload, never exported.+        -->+        <service+            android:name=".service.DownloadService"+            android:exported="false"+            android:foregroundServiceType="shortService" />     </application>  </manifest>
euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt b/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.ktindex 31763c6f72..ba4f93a5be 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt@@ -68,6 +68,53 @@ object EuiccNative {      * Runs the full SGP.22 download for an activation code and returns a JSON      * `{"success":Boolean,"message":String}` string. Must be called while the      * ISD-R channel is open (inside `withIsdrChannel`).+     *+     * Kept for the `EuiccManagerService` platform path; the UI flow uses the+     * split-phase [nativeAuthenticate] / [nativeFinishDownload] /+     * [nativeCancelDownload] entries so it can preview the carrier, confirm,+     * and collect a confirmation code mid-download.      */     external fun nativeDownloadProfile(activationCode: String): String++    /**+     * Authenticates both sides up to AuthenticateClient and returns a JSON session:+     * `{"error":String?, "transactionId":String?, "carrier":String?,+     * "profileName":String?, "iccid":String?, "ccRequired":Boolean}`.+     * No eUICC profile-store write has happened; cancel via [nativeCancelDownload].+     *+     * @param confirmationCode already-known confirmation code, or "" when unknown.+     * @param tacHex 8 hex digits of the device TAC, or "" for the default.+     * @param imei device IMEI digits for ctxParams1, or "" to omit.+     */+    external fun nativeAuthenticate(+        activationCode: String,+        confirmationCode: String,+        tacHex: String,+        imei: String,+    ): String++    /** Progress sink for [nativeFinishDownload]: return false to abort the install. */+    interface DownloadProgressCallback {+        fun onProgress(done: Int, total: Int): Boolean+    }++    /**+     * Finishes an authenticated session (PrepareDownload with hashCc, BPP fetch,+     * segment install with [callback] progress) and returns+     * `{"success":Boolean,"message":String}`. Consumes the session.+     */+    external fun nativeFinishDownload(+        transactionId: String,+        confirmationCode: String,+        callback: DownloadProgressCallback,+    ): String++    /**+     * Cancels an authenticated-but-unfinished session (ES10 CancelSession + ES9++     * cancelSession). Best-effort; always consumes the session.+     *+     * @param reason 0 end-user rejection, 1 postponed, 2 timeout, 3 PPR,+     * 4 metadata mismatch, 5 BPP execution error.+     */+    external fun nativeCancelDownload(transactionId: String, reason: Int): Boolean }
euicc/src/main/java/com/vayunmathur/euicc/Navigation.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/Navigation.kt b/euicc/src/main/java/com/vayunmathur/euicc/Navigation.ktindex bd4f50133d..ded0e8bed3 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/Navigation.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/Navigation.kt@@ -76,9 +76,17 @@ fun Navigation(viewModel: EuiccViewModel, start: Route? = null) {         entry<Route.Download> { route ->             DownloadScreen(                 activationCode = route.activationCode,+                imei = route.imei,+                confirmationCode = route.confirmationCode,                 state = viewModel.download,                 backStack = backStack,                 onStart = viewModel::startDownload,+                onConfirm = viewModel::confirmDownload,+                onSubmitCode = viewModel::submitConfirmationCode,+                onCancelSession = {+                    viewModel.cancelDownload()+                    finishActivation()+                },                 onDone = ::finishActivation,             )         }
euicc/src/main/java/com/vayunmathur/euicc/Route.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/Route.kt b/euicc/src/main/java/com/vayunmathur/euicc/Route.ktindex 8d686afb4d..59bf4c16f1 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/Route.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/Route.kt@@ -39,7 +39,15 @@ sealed interface Route : NavKey {      * than places the user can navigate between. Which one shows is decided by      * [com.vayunmathur.euicc.platform.DownloadState], so the screen cannot drift out of      * sync with the session driving it.+     *+     * [imei] and [confirmationCode] come from the wizard (manual entry collects them+     * up front); QR/universal-link entries leave them null and the flow collects the+     * confirmation code mid-download when the SM-DP+ demands one.      */     @Serializable-    data class Download(val activationCode: String) : Route+    data class Download(+        val activationCode: String,+        val imei: String? = null,+        val confirmationCode: String? = null,+    ) : Route }
euicc/src/main/java/com/vayunmathur/euicc/platform/AddEsimActivity.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/platform/AddEsimActivity.kt b/euicc/src/main/java/com/vayunmathur/euicc/platform/AddEsimActivity.ktindex 141f34661d..8cd4422903 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/platform/AddEsimActivity.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/platform/AddEsimActivity.kt@@ -35,7 +35,14 @@ class AddEsimActivity : ComponentActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         enableEdgeToEdge()-        val code = intent?.data?.getQueryParameter(EsimLink.CARDDATA_PARAM)?.trim().orEmpty()+        // Universal link (`...?carddata=<code>`) or raw `lpa:<code>` deep link.+        val carddata = intent?.data?.getQueryParameter(EsimLink.CARDDATA_PARAM)?.trim().orEmpty()+        val rawLpa = if (intent?.data?.scheme.equals("lpa", ignoreCase = true)) {+            intent?.data?.schemeSpecificPart?.trim().orEmpty()+        } else {+            ""+        }+        val code = carddata.ifEmpty { rawLpa }         val start: Route =             if (looksLikeActivationCode(code)) Route.Download(code) else Route.AddSim         setContent { DynamicTheme { Navigation(viewModel, start) } }
euicc/src/main/java/com/vayunmathur/euicc/platform/DownloadState.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/platform/DownloadState.kt b/euicc/src/main/java/com/vayunmathur/euicc/platform/DownloadState.ktindex 284f8fdeb6..92c201e8dd 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/platform/DownloadState.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/platform/DownloadState.kt@@ -8,11 +8,9 @@ package com.vayunmathur.euicc.platform  * exactly one download in flight at a time, and the screen has to show whichever phase it  * is actually in.  *- * [Confirm] and [AwaitingConfirmationCode] are declared but unreachable until the native- * core can report profile metadata and pause for a confirmation code - today's- * `nativeDownloadProfile` is a single atomic call, so a download runs- * [Preparing] -> [Installing] -> [Complete]/[Failed]. They are here now so the UI that- * renders them is written once.+ * [Confirm] slows the flow after AuthenticateClient so the user accepts the+ * carrier the SM-DP+ named before anything is written; [AwaitingConfirmationCode]+ * collects the second secret for `ccRequiredFlag` profiles.  */ sealed interface DownloadState {     /** No download in flight. */@@ -23,13 +21,14 @@ sealed interface DownloadState {      /**      * The SM-DP+ has named the profile and is waiting for the user to accept it.-     * Unreachable until the native core parses ProfileMetadata.+     * Reached after AuthenticateClient parses ProfileMetadata; cancelling here+     * frees the server session.      */     data class Confirm(val carrier: String?, val profileName: String?) : DownloadState      /**      * The profile is confirmation-code protected. [error] is set after a rejected attempt.-     * Unreachable until the native core threads a confirmation code into PrepareDownload.+     * Reached when the activation code or the SM-DP+ sets `ccRequiredFlag`.      */     data class AwaitingConfirmationCode(         val carrier: String?,@@ -37,8 +36,8 @@ sealed interface DownloadState {     ) : DownloadState      /**-     * The profile is being written to the eUICC. [progress] is null while the native core-     * reports no progress, which is every download until the BPP segment loop calls back.+     * The profile is being written to the eUICC. [progress] is null during+     * authentication, then 0..1 across the BPP segment stream.      */     data class Installing(val progress: Float? = null) : DownloadState 
euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.kt b/euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.ktindex 186266e078..f631b4e883 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.kt@@ -11,6 +11,7 @@ import com.vayunmathur.euicc.EuiccNative import com.vayunmathur.euicc.data.EuiccInfo import com.vayunmathur.euicc.data.Notification import com.vayunmathur.euicc.data.Profile+import com.vayunmathur.euicc.service.DownloadService import com.vayunmathur.euicc.telephony.EuiccChannelManager import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle@@ -35,8 +36,27 @@ data class EuiccScreenState( @kotlinx.serialization.Serializable private data class DownloadResult(val success: Boolean = false, val message: String = "") +/** Native authenticate-session outcome (see `EuiccNative.nativeAuthenticate`). */[email protected]+private data class AuthSession(+    val error: String? = null,+    val transactionId: String? = null,+    val carrier: String? = null,+    val profileName: String? = null,+    val iccid: String? = null,+    val ccRequired: Boolean = false,+)+ private const val TAG = "EuiccViewModel" +/** Switch focus to the confirmation-code screen after a `8.2.7` refusal. */+private fun isConfirmationCodeRefusal(message: String?): Boolean =+    message != null && (+        "Confirmation Code is refused" in message ||+            "maximum number of retries for the Confirmation Code" in message ||+            "Confirmation Code is missing" in message+        )+ class EuiccViewModel(app: Application) : AndroidViewModel(app) {     private val channelManager = EuiccChannelManager(app)     private val json = Json { ignoreUnknownKeys = true }@@ -52,6 +72,19 @@ class EuiccViewModel(app: Application) : AndroidViewModel(app) {     var download by mutableStateOf<DownloadState>(DownloadState.Idle)         private set +    /**+     * Authenticated-but-unfinished SM-DP+ session (opaque transaction handle+     * from `nativeAuthenticate`), plus the inputs that produced it. Kept so+     * Confirm → finish, confirmation-code resume, and cancel can all address+     * the same server session.+     */+    private var pendingTransaction: String? = null+    private var pendingActivation: String? = null+    private var pendingImei: String? = null+    private var pendingConfirmationCode: String? = null+    /** Carrier preview from AuthenticateClient, for Complete after install. */+    private var pendingCarrier: String? = null+     init {         // SM-DP+ servers authenticate TLS under the GSMA CI PKI as well as public         // CAs, so downloads need the ESIM bundle (system roots + GSMA CI root).@@ -61,23 +94,103 @@ class EuiccViewModel(app: Application) : AndroidViewModel(app) {     }      /**-     * Runs the download for [activationCode].+     * Runs the download for [activationCode] in split phases, mirroring the+     * lpac-jni `downloadProfile` state split:+     * authenticate → [DownloadState.Confirm] → optional+     * [DownloadState.AwaitingConfirmationCode] → [DownloadState.Installing]+     * (with progress) → [DownloadState.Complete]/[DownloadState.Failed].+     *+     * Nothing is written to the eUICC's profile store before the user confirms;+     * cancelling from Confirm (or a confirm timeout) frees the server session+     * via `nativeCancelDownload` instead of orphaning it.      *-     * Goes straight from [DownloadState.Preparing] to [DownloadState.Installing] because-     * `nativeDownloadProfile` is atomic - it authenticates, binds and installs in one call,-     * with no point in between where it can report the carrier or ask for a confirmation-     * code. Splitting it is what makes those states reachable.+     * @param imei device IMEI for ctxParams1 (user-editable, optional).+     * @param confirmationCode already-known confirmation code, or null.      */-    fun startDownload(activationCode: String) {-        if (download is DownloadState.Preparing || download is DownloadState.Installing) return+    fun startDownload(activationCode: String, imei: String? = null, confirmationCode: String? = null) {+        // A session is already driving the flow in every non-terminal state;+        // Failed/Complete/Idle are the only re-entry points (retry / fresh start).+        if (download !is DownloadState.Idle &&+            download !is DownloadState.Failed &&+            download !is DownloadState.Complete+        ) {+            return+        }         download = DownloadState.Preparing         viewModelScope.launch {-            download = DownloadState.Installing()-            val outcome = withContext(Dispatchers.IO) {+            val session = withContext(Dispatchers.IO) {                 runCatching {-                    channelManager.withIsdrChannel { EuiccNative.nativeDownloadProfile(activationCode) }+                    channelManager.withIsdrChannel {+                        EuiccNative.nativeAuthenticate(+                            activationCode,+                            confirmationCode.orEmpty(),+                            tacHex = "",+                            imei = imei.orEmpty(),+                        )+                    }                 }             }+            val auth = session.fold(+                onSuccess = { raw ->+                    runCatching { json.decodeFromString<AuthSession>(raw) }.getOrNull()+                },+                onFailure = {+                    Log.e(TAG, "download authenticate failed: ${it.message}", it)+                    null+                },+            )+            if (auth == null || auth.transactionId == null) {+                val message = auth?.error+                Log.e(TAG, "download failed: ${message.ifNullOrBlank()}")+                download = DownloadState.Failed(message?.ifBlank { null })+                reload()+                return@launch+            }+            // Stash the handle for confirm / finish / cancel.+            pendingTransaction = auth.transactionId+            pendingActivation = activationCode+            pendingImei = imei+            pendingCarrier = auth.carrier+            if (auth.ccRequired && confirmationCode.isNullOrEmpty()) {+                download = DownloadState.AwaitingConfirmationCode(auth.carrier)+            } else {+                download = DownloadState.Confirm(auth.carrier, auth.profileName)+            }+        }+    }++    /** The user accepted the carrier preview: run PrepareDownload → BPP → install. */+    fun confirmDownload(confirmationCode: String? = null) {+        val transactionId = pendingTransaction ?: return+        val code = confirmationCode ?: pendingConfirmationCode+        if (download !is DownloadState.Confirm && download !is DownloadState.AwaitingConfirmationCode) return+        download = DownloadState.Installing(0f)+        viewModelScope.launch {+            val callback = object : EuiccNative.DownloadProgressCallback {+                override fun onProgress(done: Int, total: Int): Boolean {+                    // Progress 0.5 → 0.95 across the segment stream; the+                    // authenticate half already accounts for the first 0.5.+                    val fraction = if (total <= 0) 0f else done.toFloat() / total.toFloat()+                    download = DownloadState.Installing(0.5f + 0.45f * fraction)+                    return true+                }+            }+            // Foreground guard for the eUICC write: keeps process importance up+            // (and the CPU awake) until the install settles either way.+            val app = getApplication<Application>()+            DownloadService.start(app)+            val outcome = try {+                withContext(Dispatchers.IO) {+                    runCatching {+                        channelManager.withIsdrChannel {+                            EuiccNative.nativeFinishDownload(transactionId, code.orEmpty(), callback)+                        }+                    }+                }+            } finally {+                DownloadService.stop(app)+            }+            pendingTransaction = null             download = outcome.fold(                 onSuccess = { raw ->                     val result = runCatching { json.decodeFromString<DownloadResult>(raw) }.getOrNull()@@ -87,7 +200,14 @@ class EuiccViewModel(app: Application) : AndroidViewModel(app) {                             Log.e(TAG, "download failed: unreadable native result")                             DownloadState.Failed(null)                         }-                        result.success -> DownloadState.Complete(null)+                        result.success -> DownloadState.Complete(pendingCarrier)+                        isConfirmationCodeRefusal(result.message) -> {+                            // A wrong code is retryable without re-authenticating+                            // only when the session survives; ours is consumed,+                            // so re-authenticate and land back on the code screen.+                            Log.e(TAG, "download failed: ${result.message}")+                            relaunchForConfirmationCode(result.message)+                        }                         else -> {                             Log.e(TAG, "download failed: ${result.message.ifBlank { "<empty>" }}")                             DownloadState.Failed(result.message.ifBlank { null })@@ -105,11 +225,78 @@ class EuiccViewModel(app: Application) : AndroidViewModel(app) {         }     } +    /** The user submitted a confirmation code: resume the install with it. */+    fun submitConfirmationCode(code: String) {+        pendingConfirmationCode = code+        confirmDownload(code)+    }++    /**+     * Cancels an in-flight download: frees the server session (when one is+     * authenticated but unfinished) and returns to idle. Safe to call from any+     * state; a no-op without a pending transaction.+     */+    fun cancelDownload(reason: Int = 0) {+        val transactionId = pendingTransaction+        pendingTransaction = null+        pendingConfirmationCode = null+        if (transactionId != null) {+            viewModelScope.launch(Dispatchers.IO) {+                runCatching {+                    channelManager.withIsdrChannel {+                        EuiccNative.nativeCancelDownload(transactionId, reason)+                    }+                }+            }+        }+        download = DownloadState.Idle+    }+     /** Clears the activation flow, so leaving and re-entering it starts clean. */     fun clearDownload() {+        // Leaving mid-authentication orphans the server session unless freed.+        if (pendingTransaction != null) cancelDownload()+        pendingActivation = null+        pendingImei = null+        pendingConfirmationCode = null+        pendingCarrier = null         download = DownloadState.Idle     } +    /**+     * Re-authenticates after a confirmation-code refusal and lands back on the+     * code screen with the server's wording. The refused session is consumed,+     * so a fresh AuthenticateClient round trip is required before retrying —+     * retrying finish on the dead handle would only report "session expired".+     */+    private suspend fun relaunchForConfirmationCode(serverMessage: String): DownloadState {+        val activation = pendingActivation+        pendingTransaction = null+        if (activation == null) return DownloadState.Failed(serverMessage)+        val raw = withContext(Dispatchers.IO) {+            runCatching {+                channelManager.withIsdrChannel {+                    EuiccNative.nativeAuthenticate(+                        activation,+                        pendingConfirmationCode.orEmpty(),+                        tacHex = "",+                        imei = pendingImei.orEmpty(),+                    )+                }+            }.getOrNull()+        }+        val auth = raw?.let { runCatching { json.decodeFromString<AuthSession>(it) }.getOrNull() }+        if (auth?.transactionId == null) {+            return DownloadState.Failed(auth?.error ?: serverMessage)+        }+        pendingTransaction = auth.transactionId+        pendingConfirmationCode = null+        pendingCarrier = auth.carrier ?: pendingCarrier+        return DownloadState.AwaitingConfirmationCode(pendingCarrier, error = true)+    }++    private fun String?.ifNullOrBlank(): String = if (this.isNullOrBlank()) "<empty>" else this+     /** Reads EID, eUICC info, profiles, and notifications in one channel session. */     fun reload() {         val carryMessage = state.message
euicc/src/main/java/com/vayunmathur/euicc/service/DownloadService.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/service/DownloadService.kt b/euicc/src/main/java/com/vayunmathur/euicc/service/DownloadService.ktnew file mode 100644index 0000000000..fa3682d9ce--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/service/DownloadService.kt@@ -0,0 +1,106 @@+package com.vayunmathur.euicc.service++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.Build+import android.os.IBinder+import android.os.PowerManager+import androidx.core.app.NotificationCompat+import com.vayunmathur.euicc.R+import java.util.concurrent.atomic.AtomicBoolean++/**+ * Foreground lifetime guard for the BPP install phase.+ *+ * Streaming a Bound Profile Package into the eUICC takes minutes on slow+ * links; without foreground importance the process is killable while the+ * eUICC is mid-write, which is exactly the half-installed state+ * `DownloadScreen` swallows Back to avoid. This service holds a partial wake+ * lock and a `shortService` foreground notification for the duration of the+ * install, mirroring OpenEUICC's+ * `EuiccChannelManagerService.launchProfileDownloadTask` (single-task guard,+ * wake lock, `shortService`).+ *+ * It performs no protocol work itself: the [com.vayunmathur.euicc.platform.EuiccViewModel]+ * still drives `nativeFinishDownload` (and so survives rotation), and starts+ * this service just before the install and stops it right after. If the+ * service is somehow already running, the second start is a no-op.+ */+class DownloadService : Service() {+    private val running = AtomicBoolean(false)+    private var wakeLock: PowerManager.WakeLock? = null++    override fun onBind(intent: Intent?): IBinder? = null++    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+        if (intent?.action != ACTION_GUARD || !running.compareAndSet(false, true)) {+            return START_NOT_STICKY+        }+        val power = getSystemService(POWER_SERVICE) as PowerManager+        wakeLock = power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_TAG).apply {+            // Absolute backstop: a stuck install must not pin the CPU forever.+            acquire(WAKE_LOCK_TIMEOUT_MS)+        }+        ensureChannel()+        val notification = NotificationCompat.Builder(this, CHANNEL_ID)+            .setContentTitle(getString(R.string.installing_title))+            .setContentText(getString(R.string.installing_text))+            .setSmallIcon(android.R.drawable.stat_sys_download)+            .setOngoing(true)+            .setProgress(0, 0, true)+            .build()+        if (Build.VERSION.SDK_INT >= 34) {+            startForeground(+                FOREGROUND_ID,+                notification,+                ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE,+            )+        } else {+            @Suppress("DEPRECATION")+            startForeground(FOREGROUND_ID, notification)+        }+        return START_NOT_STICKY+    }++    override fun onDestroy() {+        running.set(false)+        runCatching { wakeLock?.release() }+        wakeLock = null+    }++    private fun ensureChannel() {+        val manager = getSystemService(NotificationManager::class.java) ?: return+        if (manager.getNotificationChannel(CHANNEL_ID) == null) {+            manager.createNotificationChannel(+                NotificationChannel(+                    CHANNEL_ID,+                    getString(R.string.installing_title),+                    NotificationManager.IMPORTANCE_LOW,+                ),+            )+        }+    }++    companion object {+        private const val CHANNEL_ID = "esim_install"+        private const val FOREGROUND_ID = 1001+        private const val WAKE_LOCK_TAG = "euicc:install"+        private const val WAKE_LOCK_TIMEOUT_MS = 10 * 60 * 1000L+        private const val ACTION_GUARD = "com.vayunmathur.euicc.action.GUARD_INSTALL"++        /** Starts the install guard (no-op when already running). */+        fun start(context: Context) {+            context.startForegroundService(Intent(context, DownloadService::class.java).setAction(ACTION_GUARD))+        }++        /** Releases the install guard. */+        fun stop(context: Context) {+            context.stopService(Intent(context, DownloadService::class.java))+        }+    }+}
euicc/src/main/java/com/vayunmathur/euicc/service/EuiccManagerService.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/service/EuiccManagerService.kt b/euicc/src/main/java/com/vayunmathur/euicc/service/EuiccManagerService.ktindex f4bbb5dfa6..b09cf194e4 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/service/EuiccManagerService.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/service/EuiccManagerService.kt@@ -67,10 +67,26 @@ class EuiccManagerService : EuiccService() {     }      override fun onSwitchToSubscription(slotId: Int, iccid: String?, forceDeactivateSim: Boolean): Int {-        if (iccid == null) return RESULT_FIRST_USER+        // Null ICCID means "disable the active profile" (OpenEUICC parity).+        if (iccid == null) {+            return runCatching {+                channelManager.withIsdrChannel {+                    val active = EuiccNative.nativeGetProfiles()+                        ?.let { json.decodeFromString<List<Profile>>(it) }+                        ?.firstOrNull { it.isEnabled }+                        ?: return@withIsdrChannel RESULT_FIRST_USER+                    if (EuiccNative.nativeDisableProfile(active.iccid) == 0) RESULT_OK+                    else RESULT_FIRST_USER+                }+            }.getOrDefault(RESULT_FIRST_USER)+        }         return runProfileOp(iccid) { raw -> EuiccNative.nativeEnableProfile(raw) }     } +    // Single-port eUICC: there is no onSwitchToSubscriptionWithPort in the+    // framework base this module builds against, and the soldered eUICC has+    // exactly one implicit port — the unported switch above is the whole API.+     override fun onUpdateSubscriptionNickname(slotId: Int, iccid: String, nickname: String?): Int =         runProfileOp(iccid) { raw -> EuiccNative.nativeSetNickname(raw, nickname.orEmpty()) } @@ -81,11 +97,20 @@ class EuiccManagerService : EuiccService() {         forceDeactivateSim: Boolean,     ): Int {         val code = subscription.encodedActivationCode ?: return RESULT_FIRST_USER-        return runCatching {+        val downloaded = runCatching {             val raw = channelManager.withIsdrChannel { EuiccNative.nativeDownloadProfile(code) }-            val result = json.decodeFromString<DownloadOutcome>(raw)-            if (result.success) RESULT_OK else RESULT_FIRST_USER-        }.getOrDefault(RESULT_FIRST_USER)+            json.decodeFromString<DownloadOutcome>(raw)+        }.getOrNull() ?: return RESULT_FIRST_USER+        if (!downloaded.success) return RESULT_FIRST_USER+        // Honor switch-after-download when the caller asked for it; the LUI+        // flow leaves the profile disabled for the user to enable in Settings.+        if (switchAfterDownload && !forceDeactivateSim && hasActiveProfile()) {+            return RESULT_MUST_DEACTIVATE_SIM+        }+        if (switchAfterDownload) {+            enableNewestProfile()+        }+        return RESULT_OK     }      override fun onEraseSubscriptions(slotId: Int): Int = RESULT_FIRST_USER@@ -114,6 +139,21 @@ class EuiccManagerService : EuiccService() {             EuiccNative.nativeGetProfiles()?.let { json.decodeFromString<List<Profile>>(it) } ?: emptyList()         } +    /** Whether any profile is currently enabled (for MUST_DEACTIVATE_SIM). */+    private fun hasActiveProfile(): Boolean =+        runCatching { loadProfiles() }.getOrNull()?.any { it.isEnabled } == true++    /** Enables the most recently added profile (best-effort, for switch-after-download). */+    private fun enableNewestProfile() {+        runCatching {+            channelManager.withIsdrChannel {+                val profiles = EuiccNative.nativeGetProfiles()+                    ?.let { json.decodeFromString<List<Profile>>(it) } ?: emptyList()+                profiles.lastOrNull()?.let { EuiccNative.nativeEnableProfile(it.iccid) }+            }+        }+    }+     /** Resolves the framework ICCID to our raw ICCID and runs [op] in one channel session. */     private fun runProfileOp(iccid: String, op: (String) -> Int): Int = runCatching {         channelManager.withIsdrChannel {
euicc/src/main/java/com/vayunmathur/euicc/ui/ActivationCodeScreen.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/ActivationCodeScreen.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/ActivationCodeScreen.ktindex 233d95053f..930eb42bba 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/ActivationCodeScreen.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/ActivationCodeScreen.kt@@ -1,13 +1,20 @@ package com.vayunmathur.euicc.ui +import android.Manifest+import android.content.Context+import android.content.pm.PackageManager+import android.telephony.TelephonyManager import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource+import androidx.core.content.ContextCompat import com.vayunmathur.euicc.R import com.vayunmathur.euicc.Route import com.vayunmathur.library.ui.IconQrCode@@ -21,16 +28,31 @@ import com.vayunmathur.library.util.NavBackStack /**  * Manual activation-code entry, for when there is no QR code to point a camera at.  *- * The code is only sanity-checked ([looksLikeActivationCode] in `QrScannerScreen.kt`),- * not parsed: an SGP.22 activation code is `LPA:1$<smdp>$<matchingId>`, and the native- * core does the real parsing. Rejecting anything more aggressively here risks turning- * a working code into an unexplained refusal.+ * The code is only sanity-checked ([looksLikeActivationCode]), not parsed: an SGP.22+ * activation code is `LPA:1$<smdp>$<matchingId>`, and the native core does the real+ * parsing (format version, matching-ID charset, SM-DP+ hostname). Rejecting anything+ * more aggressively here risks turning a working code into an unexplained refusal.+ *+ * IMEI is prefilled from telephony (when readable) and stays user-editable: some+ * carriers bind the profile to the device, and the value rides in ctxParams1.+ * The confirmation-code field is collected up front when the activation code's+ * flag (`...$1`) says the profile needs one, matching OpenEUICC's+ * `DownloadWizardDetailsFragment`.  */ @Composable fun ActivationCodeScreen(backStack: NavBackStack<Route>) {+    val context = LocalContext.current     var code by remember { mutableStateOf("") }+    var imei by remember { mutableStateOf<String?>(null) }+    var confirmationCode by remember { mutableStateOf("") }     val trimmed = code.trim() +    LaunchedEffect(Unit) {+        if (imei == null) imei = readDeviceImei(context).orEmpty()+    }++    val flagSet = trimmed.split('$').getOrNull(4)?.trim() == "1"+     SetupScaffold(         title = stringResource(R.string.activation_code_title),         subtitle = stringResource(R.string.activation_code_text),@@ -38,7 +60,15 @@ fun ActivationCodeScreen(backStack: NavBackStack<Route>) {         backStack = backStack,         primaryAction = SetupAction(             label = stringResource(R.string.continue_button),-            onClick = { backStack.add(Route.Download(trimmed)) },+            onClick = {+                backStack.add(+                    Route.Download(+                        activationCode = trimmed,+                        imei = imei?.trim()?.ifEmpty { null },+                        confirmationCode = confirmationCode.trim().ifEmpty { null },+                    ),+                )+            },             enabled = looksLikeActivationCode(trimmed),         ),         secondaryAction = SetupAction(@@ -55,5 +85,42 @@ fun ActivationCodeScreen(backStack: NavBackStack<Route>) {             singleLine = true,             modifier = Modifier.fillMaxWidth(),         )+        OutlinedTextField(+            value = imei.orEmpty(),+            onValueChange = { imei = it },+            label = { Text(stringResource(R.string.device_imei_label)) },+            supportingText = { Text(stringResource(R.string.device_imei_hint)) },+            singleLine = true,+            modifier = Modifier.fillMaxWidth(),+        )+        OutlinedTextField(+            value = confirmationCode,+            onValueChange = { confirmationCode = it },+            label = { Text(stringResource(R.string.wizard_confirmation_code_label)) },+            supportingText = {+                Text(+                    if (flagSet) stringResource(R.string.confirmation_code_title)+                    else stringResource(R.string.wizard_confirmation_code_hint),+                )+            },+            singleLine = true,+            modifier = Modifier.fillMaxWidth(),+        )+    }+}++/**+ * Best-effort IMEI for ctxParams1: readable only with READ_PHONE_STATE /+ * READ_PRIVILEGED_PHONE_STATE, so a denial just leaves the field for the user.+ */+private fun readDeviceImei(context: Context): String? {+    if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) !=+        PackageManager.PERMISSION_GRANTED+    ) {+        return null     }+    return runCatching {+        val telephony = context.getSystemService(TelephonyManager::class.java) ?: return null+        telephony.imei?.takeIf { it.isNotBlank() }+    }.getOrNull() }
euicc/src/main/java/com/vayunmathur/euicc/ui/DownloadScreen.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/DownloadScreen.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/DownloadScreen.ktindex 7c7cb2248a..373b01387a 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/DownloadScreen.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/DownloadScreen.kt@@ -20,18 +20,24 @@ import com.vayunmathur.library.util.NavBackStack  * steps of a single eUICC session: going "back" from installing to the carrier  * confirmation would leave the session running with nothing driving it. Back is suppressed  * outright while the eUICC is being written to, which is the one point where interrupting- * can leave a half-installed profile behind.+ * can leave a half-installed profile behind. Cancelling from Confirm (or from the+ * confirmation-code screen) frees the server session via `onCancelSession`.  */ @Composable fun DownloadScreen(     activationCode: String,+    imei: String?,+    confirmationCode: String?,     state: DownloadState,     backStack: NavBackStack<Route>,-    onStart: (String) -> Unit,+    onStart: (String, String?, String?) -> Unit,+    onConfirm: (String?) -> Unit,+    onSubmitCode: (String) -> Unit,+    onCancelSession: () -> Unit,     onDone: () -> Unit, ) {     LaunchedEffect(activationCode) {-        if (state is DownloadState.Idle) onStart(activationCode)+        if (state is DownloadState.Idle) onStart(activationCode, imei, confirmationCode)     }      val busy = state is DownloadState.Preparing || state is DownloadState.Installing@@ -48,19 +54,16 @@ fun DownloadScreen(                 ConfirmCarrierContent(                     carrier = current.carrier,                     profileName = current.profileName,-                    onConfirm = { onStart(activationCode) },-                    onCancel = onDone,+                    onConfirm = { onConfirm(null) },+                    onCancel = onCancelSession,                 )              is DownloadState.AwaitingConfirmationCode ->                 ConfirmationCodeContent(                     carrier = current.carrier,                     error = current.error,-                    // The code is accepted by the UI but has nowhere to go until the native-                    // core can resume a paused download with it; retrying the whole-                    // activation code is the only thing that exists today.-                    onSubmit = { onStart(activationCode) },-                    onCancel = onDone,+                    onSubmit = onSubmitCode,+                    onCancel = onCancelSession,                 )              is DownloadState.Installing -> InstallingContent(progress = current.progress)@@ -74,7 +77,7 @@ fun DownloadScreen(             is DownloadState.Failed ->                 FailedContent(                     message = current.message,-                    onRetry = { onStart(activationCode) },+                    onRetry = { onStart(activationCode, imei, confirmationCode) },                     onCancel = onDone,                 )         }
euicc/src/main/java/com/vayunmathur/euicc/ui/QrScannerScreen.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/QrScannerScreen.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/QrScannerScreen.ktindex a87809578b..746fad3daa 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/QrScannerScreen.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/QrScannerScreen.kt@@ -149,9 +149,28 @@ private fun CameraScanner(onResult: (String) -> Unit) { /**  * Whether [code] is worth handing to the native parser. Shared with the manual entry  * screen so a typed code and a scanned one are held to the same standard.+ *+ * Case-insensitive `LPA:` gate (already correct), plus the structural checks the+ * native parser enforces: format `1`, non-blank SM-DP+ host with a dot, non-blank+ * `alnum|-` matching ID. A bare `lpa:` link body (no `$`) is accepted here and+ * resolved downstream — it is a deep link, not a full activation code.  */-internal fun looksLikeActivationCode(code: String): Boolean =-    code.startsWith("LPA:", ignoreCase = true) || code.contains('$')+internal fun looksLikeActivationCode(code: String): Boolean {+    val trimmed = code.trim()+    if (trimmed.isEmpty()) return false+    // Deep link form: lpa:<anything> hands off to the download flow's parser.+    if (trimmed.startsWith("lpa:", ignoreCase = true)) return true+    val body = trimmed.removePrefix("LPA:").removePrefix("lpa:")+    if (!trimmed.startsWith("LPA:", ignoreCase = true) && '$' !in trimmed) return false+    val parts = body.split('$')+    if (parts.size < 3) return false+    if (parts[0].trim() != "1") return false+    val smdp = parts[1].trim()+    val matchingId = parts[2].trim()+    if (smdp.isEmpty() || '.' !in smdp) return false+    if (matchingId.isEmpty()) return false+    return matchingId.all { it.isLetterOrDigit() || it == '-' }+}  /** ImageAnalysis analyzer that decodes QR codes with ZXing. */ private class QrCodeAnalyzer(private val onDecoded: (String) -> Unit) : ImageAnalysis.Analyzer {
euicc/src/main/res/values/strings.xml
diff --git a/euicc/src/main/res/values/strings.xml b/euicc/src/main/res/values/strings.xmlindex 602d6d5937..f6f1ac345e 100644--- a/euicc/src/main/res/values/strings.xml+++ b/euicc/src/main/res/values/strings.xml@@ -69,6 +69,10 @@     <string name="activation_code_text">You should have a code from your carrier. Enter it to connect to the network.</string>     <string name="activation_code_hint">Look for a code from your carrier that starts with 1$ or LPA:1$</string>     <string name="activation_code_label">Activation code</string>+    <string name="device_imei_label">IMEI (optional)</string>+    <string name="device_imei_hint">Prefilled from this device. Some carriers bind the profile to it.</string>+    <string name="wizard_confirmation_code_label">Confirmation code (if your carrier gave you one)</string>+    <string name="wizard_confirmation_code_hint">Required when the activation code ends in $1.</string>     <string name="continue_button">Continue</string>     <string name="cancel">Cancel</string>     <string name="scan_qr_title">Scan QR code</string>
euicc/src/main/rust/Cargo.toml
diff --git a/euicc/src/main/rust/Cargo.toml b/euicc/src/main/rust/Cargo.tomlindex 81ea986239..8c285b1120 100644--- a/euicc/src/main/rust/Cargo.toml+++ b/euicc/src/main/rust/Cargo.toml@@ -16,6 +16,7 @@ crate-type = ["cdylib", "rlib"] jni.workspace = true log.workspace = true serde_json.workspace = true+sha2.workspace = true # Rust reaches the SM-DP+ over HTTP through the flat-framed JNI bridge in # library:network, so no TLS is linked into libeuicc.so. jni_http = { path = "../../../../library/jni-http/src/main/rust" }
euicc/src/main/rust/src/asn1.rs
diff --git a/euicc/src/main/rust/src/asn1.rs b/euicc/src/main/rust/src/asn1.rsindex c44e03c4e9..9f83e1f38a 100644--- a/euicc/src/main/rust/src/asn1.rs+++ b/euicc/src/main/rust/src/asn1.rs@@ -132,6 +132,26 @@ pub fn tlv(tag: u32, value: &[u8]) -> Vec<u8> {     out } +/// Builds a bare TLV header: `tag || len(value_len)` with no value bytes.+///+/// Used when streaming constructed sequences (the BPP `88…`/`86…` element+/// lists) whose header the eUICC treats as a length prefix for the elements+/// that follow as separate STORE DATA payloads — mirroring lpac's split of+/// the A1/A3 header from its children.+pub fn header(tag: u32, value_len: usize) -> Vec<u8> {+    let mut out = encode_tag(tag);+    out.extend_from_slice(&encode_len(value_len));+    out+}++/// Re-wraps an already-parsed value in its tag+length header (`tag || len ||+/// value`). The encoder is canonical DER (minimal length form), so re-wrapping+/// a value taken from canonical eUICC output reproduces the original bytes —+/// what lpac's `pack_alloc` round trip also yields.+pub fn wrap(tag: u32, value: &[u8]) -> Vec<u8> {+    tlv(tag, value)+}+ #[cfg(test)] mod tests {     use super::*;
euicc/src/main/rust/src/download.rs
diff --git a/euicc/src/main/rust/src/download.rs b/euicc/src/main/rust/src/download.rsindex 7dc3957dd7..447541ec04 100644--- a/euicc/src/main/rust/src/download.rs+++ b/euicc/src/main/rust/src/download.rs@@ -1,21 +1,27 @@ //! Profile download orchestration (SGP.22 Common Mutual Authentication + //! Profile Download and Installation). //!-//! Ties the eUICC-side ES10b commands ([`crate::es10`]) to the SM-DP+-side ES9++//! Ties the eUICC-side ES10b commands ([`crate::es10b`]) to the SM-DP+-side ES9+ //! calls ([`crate::es9p`]). The LPA only relays DER blobs: the eUICC verifies the //! server, agrees keys, decrypts the Bound Profile Package, and installs it; the //! SM-DP+ produces the signed material. This module sequences the exchange. //! //! The full flow requires a live SM-DP+, a real eUICC, and a platform-signed-//! install, so it cannot be exercised in host tests. Only-//! [`parse_activation_code`] is unit-tested here.+//! install, so it cannot be exercised in host tests. The pure pieces are:+//! [`parse_activation_code`], [`hash_confirmation_code`], and+//! [`es10b::extract_transaction_id`].  use jni::JNIEnv;  use crate::jni::store_data;-use crate::{asn1, es10, es9p};+use crate::{asn1, es10, es10b, es9p}; -/// A parsed SGP.22 activation code.+/// A parsed SGP.22 activation code (`LPA:1$smdp$matchingId[$oid][$flag]`).+///+/// Validation mirrors lpac's `download.c:applet_main`: the format field must be+/// `"1"`, the matching id is `alnum|-` only, and a confirmation-required flag+/// without a separately supplied code is a local error — fail fast instead of+/// sending a malformed order to the SM-DP+. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ActivationCode {     /// SM-DP+ FQDN (no scheme).@@ -34,13 +40,33 @@ pub fn parse_activation_code(code: &str) -> Result<ActivationCode, String> {     if parts.len() < 3 {         return Err("Activation code must be LPA:1$smdp$matchingId".to_string());     }-    // parts[0] is the format version ("1").+    if parts[0].trim() != "1" {+        return Err(format!(+            "Unsupported activation code format '{}' (expected '1')",+            parts[0].trim()+        ));+    }     let smdp = parts[1].trim();     let matching_id = parts[2].trim();     if smdp.is_empty() {         return Err("Activation code is missing the SM-DP+ address".to_string());     }-    let confirmation_code_required = parts.get(4).map(|s| *s == "1").unwrap_or(false);+    if matching_id.is_empty() {+        return Err("Activation code is missing the matching ID".to_string());+    }+    if !matching_id+        .bytes()+        .all(|b| b.is_ascii_alphanumeric() || b == b'-')+    {+        return Err(+            "Matching ID has an invalid format (only letters, digits and '-' are allowed)"+                .to_string(),+        );+    }+    if !is_plausible_smdp(smdp) {+        return Err(format!("SM-DP+ address '{smdp}' does not look like a hostname"));+    }+    let confirmation_code_required = parts.get(4).map(|s| s.trim() == "1").unwrap_or(false);     Ok(ActivationCode {         smdp: smdp.to_string(),         matching_id: matching_id.to_string(),@@ -48,6 +74,39 @@ pub fn parse_activation_code(code: &str) -> Result<ActivationCode, String> {     }) } +/// Minimal FQDN sanity check for the SM-DP+ address (lpac leaves a bad address+/// to fail at TLS; we fail fast with the offending value named).+fn is_plausible_smdp(smdp: &str) -> bool {+    let host = smdp+        .trim()+        .trim_start_matches("https://")+        .trim_start_matches("http://")+        .trim_end_matches('/')+        .split(':')+        .next()+        .unwrap_or("");+    !host.is_empty()+        && host.contains('.')+        && host+            .bytes()+            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.')+        && !host.starts_with('.')+        && !host.starts_with('-')+        && !host.ends_with('.')+}++/// `hashCc = SHA256(SHA256(code) || transactionIdBin)`, where `transactionIdBin`+/// is tag `0x80` inside `smdpSigned2` — mirroring lpac's+/// `es10b_prepare_download_r`.+pub fn hash_confirmation_code(code: &str, transaction_id: &[u8]) -> [u8; 32] {+    use sha2::{Digest, Sha256};+    let inner = Sha256::digest(code.as_bytes());+    let mut outer = Sha256::new();+    outer.update(inner);+    outer.update(transaction_id);+    outer.finalize().into()+}+ /// The key bytes of a CI public-key identifier field, unwrapping one DER TLV /// layer when the server sends the full TLV rather than the bare value. fn pkid_value(field: &[u8]) -> &[u8] {@@ -69,16 +128,84 @@ fn ci_key_known(verification_list: &[String], field: &[u8]) -> bool { /// Runs the full download for an activation code, driving the eUICC over the /// already-open ISD-R channel (via [`store_data`]) and the SM-DP+ over HTTP. ///-/// Confirmation-code-protected profiles are not yet supported; such downloads-/// will be rejected by the eUICC at PrepareDownload.+/// Thin wrapper over the split-phase session below for callers that do not+/// need progress, metadata preview, or confirmation-code resume. pub fn download_profile(     env: &mut JNIEnv,     activation_code: &str,-) -> Result<es10::InstallResult, String> {+) -> Result<es10b::InstallResult, String> {+    download_profile_with_options(env, activation_code, &DownloadOptions::default())+}++/// Download inputs beyond the activation code itself.+#[derive(Debug, Clone, PartialEq, Eq, Default)]+pub struct DownloadOptions {+    /// Confirmation code for `ccRequiredFlag` profiles (`None` when the profile+    /// does not need one or the code is not known yet).+    pub confirmation_code: Option<String>,+    /// Device TAC (4 bytes). Defaults to [`es10b::DEFAULT_TAC`] like lpac.+    pub tac: Option<[u8; 4]>,+    /// Device IMEI digits for `ctxParams1` (user-editable, optional).+    pub imei: Option<String>,+}++/// Progress reporting for the BPP segment loop. Returning `false` aborts the+/// download (the caller is expected to cancel the server session).+///+/// `env` is passed per call (rather than stored in the callback) so JNI+/// progress sinks do not alias the eUICC channel's `&mut JNIEnv` borrow.+pub trait ProgressCallback {+    /// Called with `done`/`total` segments transmitted. Returns whether to continue.+    fn on_progress(&mut self, env: &mut JNIEnv, done: usize, total: usize) -> bool;+}++/// A no-op progress sink for the atomic entry point.+struct NoProgress;+impl ProgressCallback for NoProgress {+    fn on_progress(&mut self, _env: &mut JNIEnv, _done: usize, _total: usize) -> bool {+        true+    }+}++/// One in-flight download session: everything the LPA learns before touching+/// the eUICC's profile store, so the UI can preview the carrier, confirm, and+/// collect a confirmation code before any install happens.+///+/// Mirrors the lpac-jni `downloadProfile` state split+/// (Preparing → Connecting → Authenticating → ConfirmingDownload →+/// Downloading → Finalizing).+pub struct DownloadSession {+    /// Parsed activation code.+    pub activation: ActivationCode,+    /// SM-DP+ transaction id (JSON string form, for ES9+ calls).+    pub transaction_id: String,+    /// Binary transaction id (tag `0x80` inside `serverSigned1`), for `hashCc`+    /// and CancelSession.+    pub transaction_id_bin: Vec<u8>,+    /// Carrier preview parsed from `profileMetadata`.+    pub metadata: es10b::ProfileMetadata,+    /// Whether the SM-DP+ demands a confirmation code (`ccRequiredFlag`).+    pub cc_required: bool,+    /// Options captured at authenticate time (TAC/IMEI/confirmation code).+    options: DownloadOptions,+    server_signed2: Vec<u8>,+    server_signature2: Vec<u8>,+    server_certificate2: Vec<u8>,+}++/// Authenticates both sides up to `AuthenticateClient` and returns the session+/// plus carrier preview — no eUICC profile-store write has happened yet, so+/// cancelling here costs nothing (the server session should still be freed via+/// [`cancel_session`]).+pub fn authenticate(+    env: &mut JNIEnv,+    activation_code: &str,+    options: &DownloadOptions,+) -> Result<DownloadSession, String> {     let ac = parse_activation_code(activation_code)?;      // 1. eUICC challenge + info for the server's authentication.-    let challenge = es10::parse_euicc_challenge(&store_data(env, &es10::build_get_euicc_challenge())?)?;+    let challenge = es10b::parse_euicc_challenge(&store_data(env, &es10b::build_get_euicc_challenge())?)?;     let euicc_info1 = store_data(env, &es10::build_get_euicc_info1())?;      // 2. Server authentication material.@@ -102,9 +229,11 @@ pub fn download_profile(         }     } -    // 3. eUICC authenticates the server and signs its own material.-    let ctx = es10::build_ctx_params1(&ac.matching_id, &[0, 0, 0, 0]);-    let auth_req = es10::build_authenticate_server(+    // 3. eUICC authenticates the server and signs its own material. TAC+    // defaults to lpac's constant; IMEI is user-supplied and optional.+    let tac = options.tac.unwrap_or(es10b::DEFAULT_TAC);+    let ctx = es10b::build_ctx_params1(&ac.matching_id, &tac, options.imei.as_deref());+    let auth_req = es10b::build_authenticate_server(         &r1.server_signed1,         &r1.server_signature1,         &r1.euicc_ci_pkid,@@ -113,32 +242,147 @@ pub fn download_profile(     );     let auth_resp = store_data(env, &auth_req)?; +    // Binary transaction id for hashCc / CancelSession (the JSON string form+    // stays the ES9+ correlator).+    let transaction_id_bin = es10b::extract_transaction_id(&r1.server_signed1)?;+     // 4. SM-DP+ binds the profile to this eUICC.     let r2 = es9p::authenticate_client(&ac.smdp, &r1.transaction_id, &auth_resp)?; +    let metadata = es10b::parse_profile_metadata(&r2.profile_metadata)?;+    let cc_required = ac.confirmation_code_required || es10b::cc_required(&r2.smdp_signed2);++    Ok(DownloadSession {+        activation: ac,+        transaction_id: r1.transaction_id,+        transaction_id_bin,+        metadata,+        cc_required,+        options: options.clone(),+        server_signed2: r2.smdp_signed2,+        server_signature2: r2.smdp_signature2,+        server_certificate2: r2.smdp_certificate,+    })+}++/// Finishes an authenticated session: PrepareDownload (with `hashCc` when a+/// confirmation code is present), BPP fetch, and segment install with progress.+///+/// Aborts on the first failing segment (like lpac's per-`tx` BF37 check) and+/// reports the typed `bppCommandId/errorReason` instead of cascading one+/// failure into every later segment.+pub fn finish_download(+    env: &mut JNIEnv,+    session: &DownloadSession,+    confirmation_code: Option<&str>,+    progress: &mut dyn ProgressCallback,+) -> Result<es10b::InstallResult, String> {     // 5. eUICC prepares to receive the profile.-    let prep_req =-        es10::build_prepare_download(&r2.smdp_signed2, &r2.smdp_signature2, None, &r2.smdp_certificate);+    let code = confirmation_code+        .filter(|c| !c.is_empty())+        .or(session.options.confirmation_code.as_deref());+    if session.cc_required && code.is_none() {+        return Err(+            "This profile needs a confirmation code (ccRequiredFlag is set) — supply it and retry"+                .to_string(),+        );+    }+    let tx_bin = es10b::extract_transaction_id(&session.server_signed2)?;+    let hash = code.map(|c| hash_confirmation_code(c, &tx_bin));+    let hash_ref = hash.as_ref().map(|h| &h[..]);+    let prep_req = es10b::build_prepare_download(+        &session.server_signed2,+        &session.server_signature2,+        hash_ref,+        &session.server_certificate2,+    );     let prep_resp = store_data(env, &prep_req)?;      // 6. Fetch the (encrypted) Bound Profile Package.-    let bpp = es9p::get_bound_profile_package(&ac.smdp, &r1.transaction_id, &prep_resp)?;+    let bpp = es9p::get_bound_profile_package(+        &session.activation.smdp,+        &session.transaction_id,+        &prep_resp,+    )?; -    // 7. Stream the BPP into the eUICC segment by segment; the last segment-    //    returns the ProfileInstallationResult.-    let segments = es10::segment_bpp(&bpp)?;+    // 7. Stream the BPP into the eUICC segment by segment, aborting on the+    // first error response. The last segment returns the+    // ProfileInstallationResult — but a mid-stream BF37 error must stop the+    // loop immediately so one failure does not cascade.+    let segments = es10b::segment_bpp(&bpp)?;+    let total = segments.len();     let mut last = Vec::new();-    for segment in &segments {+    for (i, segment) in segments.iter().enumerate() {         last = store_data(env, segment)?;+        if !progress.on_progress(env, i + 1, total) {+            return Err("Download cancelled".to_string());+        }+        // Intermediate BF37 error results abort the stream (lpac parity): a+        // typed mid-stream failure must stop the loop, not cascade.+        if i + 1 < total {+            if let Ok(probe) = es10b::parse_install_result(&last) {+                if !probe.success+                    && (probe.bpp_command_id.is_some() || probe.error_reason.is_some())+                {+                    return Err(probe.message);+                }+            }+        }     }-    let result = es10::parse_install_result(&last)?;+    let result = es10b::parse_install_result(&last)?; -    // 8. Deliver the install notification (best-effort).-    let _ = es9p::handle_notification(&ac.smdp, &result.notification);+    // 8. Deliver the install notification (best-effort): retrieve the pending+    // notification to learn its delivery address, post it there, then remove+    // it from the eUICC list — the lpac `notification process` sequence.+    deliver_notification(env, &session.activation.smdp, result.seq_number, &result.notification);      Ok(result) } +/// Retrieve → handle → remove for one install notification. Best-effort: the+/// eUICC keeps the notification until acknowledged, so delivery failure must+/// not fail the install itself.+fn deliver_notification(env: &mut JNIEnv, smdp: &str, seq_number: i64, fallback: &[u8]) {+    let Ok(seq) = u32::try_from(seq_number.max(0)) else {+        return;+    };+    let Ok(retrieved) = store_data(env, &es10b::build_retrieve_notification(seq))+        .and_then(|resp| es10b::parse_retrieved_notification(&resp))+    else {+        // Fall back to posting the raw result to the download server.+        let _ = es9p::handle_notification(smdp, fallback);+        return;+    };+    let (address, pending) = retrieved;+    let target = if address.is_empty() { smdp } else { address.as_str() };+    if es9p::handle_notification_at(target, &pending).is_ok() {+        let _ = store_data(env, &es10::build_remove_notification(seq))+            .and_then(|resp| es10::parse_remove_result(&resp));+    }+}++/// Frees an authenticated-but-unfinished server session (user cancel,+/// metadata mismatch, confirmation timeout). ES10 CancelSession first, then+/// ES9+ cancelSession — mirroring lpac-download's error path+/// (`es10b_cancel_session` + `es9p_cancel_session`). Best-effort.+pub fn cancel_session(env: &mut JNIEnv, session: &DownloadSession, reason: es10b::CancelReason) {+    let es10_req = es10b::build_cancel_session(&session.transaction_id_bin, reason);+    let cancel_resp = store_data(env, &es10_req).unwrap_or_default();+    let _ = es9p::cancel_session(&session.activation.smdp, &session.transaction_id, &cancel_resp);+}++/// Full download with options: authenticate → prepare (with `hashCc`) →+/// fetch → install with progress → notify.+pub fn download_profile_with_options(+    env: &mut JNIEnv,+    activation_code: &str,+    options: &DownloadOptions,+) -> Result<es10b::InstallResult, String> {+    let session = authenticate(env, activation_code, options)?;+    let mut sink = NoProgress;+    finish_download(env, &session, None, &mut sink)+}+ #[cfg(test)] mod tests {     use super::*;@@ -163,6 +407,26 @@ mod tests {     fn rejects_short_codes() {         assert!(parse_activation_code("LPA:1$smdp.example.com").is_err());         assert!(parse_activation_code("garbage").is_err());+        assert!(parse_activation_code("LPA:1$smdp.example.com$").is_err());+    }++    #[test]+    fn rejects_bad_format_version() {+        assert!(parse_activation_code("LPA:2$smdp.example.com$ABC").is_err());+    }++    #[test]+    fn rejects_bad_matching_id_charset() {+        // lpac parity: alnum and '-' only.+        assert!(parse_activation_code("LPA:1$smdp.example.com$ABC_DEF").is_err());+        assert!(parse_activation_code("LPA:1$smdp.example.com$ABC DEF").is_err());+        assert!(parse_activation_code("LPA:1$smdp.example.com$ABC-123").is_ok());+    }++    #[test]+    fn rejects_implausible_smdp() {+        assert!(parse_activation_code("LPA:1$notahost$ABC-123").is_err());+        assert!(parse_activation_code("LPA:1$$ABC-123").is_err());     }      #[test]@@ -175,4 +439,40 @@ mod tests {         assert!(!ci_key_known(&list, &[0xDD]));         assert!(!ci_key_known(&[], &[0xAA, 0xBB, 0xCC]));     }++    #[test]+    fn hash_cc_vector() {+        // hashCc = SHA256(SHA256(code) || transactionId), like lpac's+        // es10b_prepare_download_r. Independent re-computation with sha2 must+        // agree with the helper.+        use sha2::{Digest, Sha256};+        let tx = [0x01u8, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];+        let inner = Sha256::digest(b"1234");+        let mut outer = Sha256::new();+        outer.update(inner);+        outer.update(tx);+        let expected: [u8; 32] = outer.finalize().into();+        assert_eq!(hash_confirmation_code("1234", &tx), expected);+        // Different codes / transactions differ.+        assert_ne!(+            hash_confirmation_code("1234", &tx),+            hash_confirmation_code("4321", &tx)+        );+        assert_ne!(+            hash_confirmation_code("1234", &tx),+            hash_confirmation_code("1234", &[0x09])+        );+    }++    #[test]+    fn transaction_id_extraction() {+        let mut seq = crate::asn1::tlv(0x80, &[0xDE, 0xAD, 0xBE, 0xEF]);+        seq.extend(crate::asn1::tlv(0x01, &[0x00]));+        let signed = crate::asn1::tlv(0x30, &seq);+        assert_eq!(+            es10b::extract_transaction_id(&signed).unwrap(),+            vec![0xDE, 0xAD, 0xBE, 0xEF]+        );+        assert!(es10b::extract_transaction_id(&[0x30, 0x00]).is_err());+    } }
euicc/src/main/rust/src/es10.rs
diff --git a/euicc/src/main/rust/src/es10.rs b/euicc/src/main/rust/src/es10.rsindex 5eba0d8e3f..93bebc1376 100644--- a/euicc/src/main/rust/src/es10.rs+++ b/euicc/src/main/rust/src/es10.rs@@ -1,5 +1,9 @@ //! ES10 local ISD-R command builders and response parsers (SGP.22). //!+//! The ES10c local ops (EID, info, profiles, enable/disable/delete/nickname)+//! plus the ES10b notification list/remove helpers. The ES10b download flow+//! (challenge → install → metadata → cancel) lives in [`crate::es10b`].+//! //! Pure protocol logic: each function either builds a request TLV (to be wrapped //! in STORE DATA APDUs and transmitted by the transport layer) or parses a //! response TLV. No JNI or transport here, so it is fully host-testable.@@ -21,7 +25,7 @@ const TAG_CI_PKID_SIGNING: u32 = 0xAA; // [10] SEQUENCE OF SubjectKeyIdentifier const TAG_PROFILE_INFO_LIST: u32 = 0xBF2D; // ES10c GetProfilesInfo request/response const TAG_PROFILE_LIST_OK: u32 = 0xA0; // [0] SEQUENCE OF ProfileInfo const TAG_PROFILE_INFO: u32 = 0xE3; // [PRIVATE 3] ProfileInfo-const TAG_ICCID: u32 = 0x5A; // [APPLICATION 26] ICCID (same numeric tag as EID)+pub(crate) const TAG_ICCID: u32 = 0x5A; // [APPLICATION 26] ICCID (shared with es10b metadata) const TAG_ISDP_AID: u32 = 0x4F; // [APPLICATION 15] ISD-P AID const TAG_PROFILE_STATE: u32 = 0x9F70; // [112] ProfileState const TAG_NICKNAME: u32 = 0x90; // [16] profileNickname UTF8String@@ -36,37 +40,72 @@ const TAG_SET_NICKNAME: u32 = 0xBF29; // ES10c SetNickname const TAG_REFRESH_FLAG: u32 = 0x81; // [1] refreshFlag BOOLEAN const TAG_RESULT: u32 = 0x80; // [0] result INTEGER (enable/disable/delete/setNickname) +// Notification list/remove tags, shared with the es10b retrieve path. const TAG_LIST_NOTIFICATION: u32 = 0xBF28; // ES10b ListNotification-const TAG_NOTIFICATION_LIST: u32 = 0xA0; // [0] SEQUENCE OF NotificationMetadata-const TAG_NOTIFICATION_METADATA: u32 = 0xBF2F; // [47] NotificationMetadata-const TAG_SEQ_NUMBER: u32 = 0x80; // [0] seqNumber INTEGER+pub(crate) const TAG_NOTIFICATION_LIST: u32 = 0xA0; // [0] SEQUENCE OF NotificationMetadata+pub(crate) const TAG_NOTIFICATION_METADATA: u32 = 0xBF2F; // [47] NotificationMetadata+pub(crate) const TAG_SEQ_NUMBER: u32 = 0x80; // [0] seqNumber INTEGER const TAG_NOTIFICATION_EVENT: u32 = 0x81; // [1] profileManagementOperation BIT STRING-const TAG_NOTIFICATION_ADDRESS: u32 = 0x82; // [2] notificationAddress UTF8String+// notificationAddress UTF8String. SGP.22 tags it 0x0C (like lpac parses); it is+// NOT context-[2] despite sitting in second position of NotificationMetadata.+pub(crate) const TAG_NOTIFICATION_ADDRESS: u32 = 0x0C; const TAG_REMOVE_NOTIFICATION: u32 = 0xBF30; // ES10b RemoveNotificationFromList -const TAG_GET_EUICC_CHALLENGE: u32 = 0xBF2E; // ES10b GetEUICCChallenge-const TAG_EUICC_CHALLENGE: u32 = 0x80; // [0] euiccChallenge Octet16-const TAG_AUTHENTICATE_SERVER: u32 = 0xBF38; // ES10b AuthenticateServer-const TAG_PREPARE_DOWNLOAD: u32 = 0xBF21; // ES10b PrepareDownload-const TAG_HASH_CC: u32 = 0x04; // hashCc Octet32 (confirmation code)-const TAG_BPP: u32 = 0xBF36; // BoundProfilePackage-const TAG_INITIALISE_SECURE_CHANNEL: u32 = 0xBF23; // initialiseSecureChannelRequest-const TAG_BPP_SEQ_87: u32 = 0xA0; // firstSequenceOf87-const TAG_BPP_SEQ_88: u32 = 0xA1; // sequenceOf88-const TAG_BPP_SEQ_87B: u32 = 0xA2; // secondSequenceOf87-const TAG_BPP_SEQ_86: u32 = 0xA3; // sequenceOf86-const TAG_PROFILE_INSTALL_RESULT: u32 = 0xBF37; // ProfileInstallationResult-const TAG_PIR_DATA: u32 = 0xBF27; // profileInstallationResultData-const TAG_FINAL_RESULT: u32 = 0xA2; // [2] finalResult-const TAG_SUCCESS_RESULT: u32 = 0xA0; // [0] successResult-const TAG_ERROR_RESULT: u32 = 0xA1; // [1] errorResult--// ctxParams1 / DeviceInfo construction tags.-const TAG_CTX_PARAMS_COMMON: u32 = 0xA0; // [0] ctxParamsForCommonAuthentication-const TAG_MATCHING_ID: u32 = 0x80; // [0] matchingId UTF8String-const TAG_DEVICE_INFO: u32 = 0xA1; // [1] deviceInfo (IMPLICIT replaces SEQUENCE tag)-const TAG_TAC: u32 = 0x80; // [0] tac Octet4-const TAG_DEVICE_CAPS: u32 = 0xA1; // [1] deviceCapabilities SEQUENCE+/// ASN.1 scalar helpers shared with [`crate::es10b`].+pub(crate) fn first_byte(v: &[u8]) -> Option<u8> {+    v.first().copied()+}++pub(crate) fn utf8(v: &[u8]) -> String {+    String::from_utf8_lossy(v).into_owned()+}++/// Parses a (short) two's-complement BER INTEGER into i64.+pub(crate) fn parse_int(v: &[u8]) -> i64 {+    if v.is_empty() {+        return 0;+    }+    let mut acc: i64 = if v[0] & 0x80 != 0 { -1 } else { 0 };+    for &b in v {+        acc = (acc << 8) | b as i64;+    }+    acc+}++/// Minimal unsigned big-endian INTEGER encoding (always at least one byte, with+/// a leading zero when the top bit would otherwise make it negative).+pub(crate) fn encode_int_minimal(mut v: u32) -> Vec<u8> {+    if v == 0 {+        return vec![0];+    }+    let mut bytes = Vec::new();+    while v > 0 {+        bytes.insert(0, (v & 0xFF) as u8);+        v >>= 8;+    }+    if bytes[0] & 0x80 != 0 {+        bytes.insert(0, 0x00);+    }+    bytes+}++/// Decodes an SGP.22 ICCID (BCD, nibble-swapped, F-padded) into decimal digits.+pub(crate) fn decode_iccid(raw: &[u8]) -> String {+    let mut s = String::with_capacity(raw.len() * 2);+    for &b in raw {+        let lo = b & 0x0F;+        let hi = b >> 4;+        for nib in [lo, hi] {+            if nib == 0x0F {+                continue;+            }+            if nib < 10 {+                s.push((b'0' + nib) as char);+            }+        }+    }+    s+}  /// Parsed subset of EUICCInfo1 useful for display. #[derive(Debug, Clone, PartialEq, Eq)]@@ -308,144 +347,5 @@ pub fn parse_remove_result(response: &[u8]) -> Result<i64, String> {     Ok(parse_int(code)) } -// ----------------------------------------------------------------------------// Download flow (ES10b): challenge, AuthenticateServer, PrepareDownload,-// LoadBoundProfilePackage-// -----------------------------------------------------------------------------/// Outcome of installing a Bound Profile Package.-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct InstallResult {-    pub success: bool,-    pub message: String,-    /// The raw ProfileInstallationResult (BF37) to deliver via HandleNotification.-    pub notification: Vec<u8>,-}--/// Builds the ES10b GetEUICCChallenge request (empty BF2E).-pub fn build_get_euicc_challenge() -> Vec<u8> {-    asn1::tlv(TAG_GET_EUICC_CHALLENGE, &[])-}--/// Parses a GetEUICCChallenge response into the 16-byte challenge.-pub fn parse_euicc_challenge(response: &[u8]) -> Result<Vec<u8>, String> {-    let body = asn1::find(response, TAG_GET_EUICC_CHALLENGE).ok_or("GetEUICCChallenge: missing BF2E")?;-    let challenge = asn1::find(body, TAG_EUICC_CHALLENGE).ok_or("GetEUICCChallenge: missing challenge")?;-    Ok(challenge.to_vec())-}--/// Builds ctxParams1 for common authentication: matchingId + a minimal DeviceInfo.-///-/// `tac` is the 4-byte Type Allocation Code; deviceCapabilities is sent empty.-pub fn build_ctx_params1(matching_id: &str, tac: &[u8; 4]) -> Vec<u8> {-    let mut device_info_val = asn1::tlv(TAG_TAC, tac);-    device_info_val.extend(asn1::tlv(TAG_DEVICE_CAPS, &[])); // empty DeviceCapabilities-    let device_info = asn1::tlv(TAG_DEVICE_INFO, &device_info_val);--    let mut common = asn1::tlv(TAG_MATCHING_ID, matching_id.as_bytes());-    common.extend(device_info);-    asn1::tlv(TAG_CTX_PARAMS_COMMON, &common)-}--/// Builds the ES10b AuthenticateServer request by concatenating the server blobs-/// (each already a complete DER TLV) with ctxParams1, wrapped in BF38.-pub fn build_authenticate_server(-    server_signed1: &[u8],-    server_signature1: &[u8],-    euicc_ci_pkid: &[u8],-    server_certificate: &[u8],-    ctx_params1: &[u8],-) -> Vec<u8> {-    let mut v = Vec::new();-    v.extend_from_slice(server_signed1);-    v.extend_from_slice(server_signature1);-    v.extend_from_slice(euicc_ci_pkid);-    v.extend_from_slice(server_certificate);-    v.extend_from_slice(ctx_params1);-    asn1::tlv(TAG_AUTHENTICATE_SERVER, &v)-}--/// Builds the ES10b PrepareDownload request from the SM-DP+ blobs (each a-/// complete DER TLV), wrapped in BF21.-pub fn build_prepare_download(-    smdp_signed2: &[u8],-    smdp_signature2: &[u8],-    hash_cc: Option<&[u8]>,-    smdp_certificate: &[u8],-) -> Vec<u8> {-    let mut v = Vec::new();-    v.extend_from_slice(smdp_signed2);-    v.extend_from_slice(smdp_signature2);-    if let Some(cc) = hash_cc {-        v.extend(asn1::tlv(TAG_HASH_CC, cc));-    }-    v.extend_from_slice(smdp_certificate);-    asn1::tlv(TAG_PREPARE_DOWNLOAD, &v)-}--/// Segments a Bound Profile Package (BF36) into the ordered list of TLVs the LPA-/// must transmit to the eUICC via STORE DATA: the initialiseSecureChannelRequest-/// followed by each element of the 87/88/87/86 sequences.-pub fn segment_bpp(bpp: &[u8]) -> Result<Vec<Vec<u8>>, String> {-    let body = asn1::find(bpp, TAG_BPP).ok_or("BoundProfilePackage: missing BF36")?;-    let mut segments = Vec::new();-    for child in asn1::children(body).ok_or("BoundProfilePackage: malformed")? {-        match child.tag {-            TAG_INITIALISE_SECURE_CHANNEL => {-                segments.push(asn1::tlv(child.tag, child.value));-            }-            TAG_BPP_SEQ_87 | TAG_BPP_SEQ_88 | TAG_BPP_SEQ_87B | TAG_BPP_SEQ_86 => {-                for element in asn1::children(child.value).ok_or("BPP: malformed sequence")? {-                    segments.push(asn1::tlv(element.tag, element.value));-                }-            }-            other => {-                // Unknown top-level element: forward it verbatim to be safe.-                segments.push(asn1::tlv(other, child.value));-            }-        }-    }-    Ok(segments)-}--/// Parses a ProfileInstallationResult (BF37) into an [`InstallResult`].-pub fn parse_install_result(response: &[u8]) -> Result<InstallResult, String> {-    let body = asn1::find(response, TAG_PROFILE_INSTALL_RESULT)-        .ok_or("ProfileInstallationResult: missing BF37")?;-    let data = asn1::find(body, TAG_PIR_DATA).ok_or("ProfileInstallationResult: missing BF27")?;-    let final_result = asn1::find(data, TAG_FINAL_RESULT)-        .ok_or("ProfileInstallationResult: missing finalResult")?;--    let (success, message) = if asn1::find(final_result, TAG_SUCCESS_RESULT).is_some() {-        (true, "Profile installed".to_string())-    } else if let Some(err) = asn1::find(final_result, TAG_ERROR_RESULT) {-        // errorResult ::= SEQUENCE { bppCommandId INTEGER, errorReason ENUMERATED, ... }-        let reason = asn1::children(err)-            .and_then(|kids| kids.get(1).map(|k| parse_int(k.value)))-            .unwrap_or(-1);-        (false, format!("Install failed (errorReason {reason})"))-    } else {-        (false, "Install failed (unknown result)".to_string())-    };--    Ok(InstallResult {-        success,-        message,-        notification: response.to_vec(),-    })-}--// ----------------------------------------------------------------------------// Helpers-// -----------------------------------------------------------------------------/// Lowercase hex encoding.-pub fn hex(bytes: &[u8]) -> String {-    let mut s = String::with_capacity(bytes.len() * 2);-    for b in bytes {-        s.push_str(&format!("{b:02x}"));-    }-    s-} -include!("es10_part1.rs");\ No newline at end of file+include!("es10_part1.rs");
euicc/src/main/rust/src/es10_part1.rs
diff --git a/euicc/src/main/rust/src/es10_part1.rs b/euicc/src/main/rust/src/es10_part1.rsindex e3ba636a2f..ff82fc6d2d 100644--- a/euicc/src/main/rust/src/es10_part1.rs+++ b/euicc/src/main/rust/src/es10_part1.rs@@ -18,57 +18,11 @@ pub fn hex_decode(s: &str) -> Vec<u8> {     out } -fn first_byte(v: &[u8]) -> Option<u8> {-    v.first().copied()-}--fn utf8(v: &[u8]) -> String {-    String::from_utf8_lossy(v).into_owned()-}--/// Parses a (short) two's-complement BER INTEGER into i64.-fn parse_int(v: &[u8]) -> i64 {-    if v.is_empty() {-        return 0;-    }-    let mut acc: i64 = if v[0] & 0x80 != 0 { -1 } else { 0 };-    for &b in v {-        acc = (acc << 8) | b as i64;-    }-    acc-}--/// Minimal unsigned big-endian INTEGER encoding (always at least one byte, with-/// a leading zero when the top bit would otherwise make it negative).-fn encode_int_minimal(mut v: u32) -> Vec<u8> {-    if v == 0 {-        return vec![0];-    }-    let mut bytes = Vec::new();-    while v > 0 {-        bytes.insert(0, (v & 0xFF) as u8);-        v >>= 8;-    }-    if bytes[0] & 0x80 != 0 {-        bytes.insert(0, 0x00);-    }-    bytes-}--/// Decodes an SGP.22 ICCID (BCD, nibble-swapped, F-padded) into decimal digits.-fn decode_iccid(raw: &[u8]) -> String {-    let mut s = String::with_capacity(raw.len() * 2);-    for &b in raw {-        let lo = b & 0x0F;-        let hi = b >> 4;-        for nib in [lo, hi] {-            if nib == 0x0F {-                continue;-            }-            if nib < 10 {-                s.push((b'0' + nib) as char);-            }-        }+/// Lowercase hex encoding.+pub fn hex(bytes: &[u8]) -> String {+    let mut s = String::with_capacity(bytes.len() * 2);+    for b in bytes {+        s.push_str(&format!("{b:02x}"));     }     s }@@ -100,26 +54,6 @@ mod tests {         assert_eq!(build_get_eid(), vec![0xBF, 0x3E, 0x03, 0x5C, 0x01, 0x5A]);     } -    #[test]-    fn ctx_params1_tags_match_sgp22() {-        // CtxParamsForCommonAuthentication: matchingId [0] IMPLICIT, deviceInfo-        // [1] IMPLICIT (constructed). A bare SEQUENCE tag (0x30) on deviceInfo is-        // malformed — the SM-DP+ cannot verify the AuthenticateServer response-        // built over it (seen as an empty authenticateClient reply).-        let ctx = build_ctx_params1("ABC", &[0x35, 0x29, 0x06, 0x11]);-        let body = asn1::find(&ctx, TAG_CTX_PARAMS_COMMON).expect("outer A0");-        let kids = asn1::children(body).expect("two children");-        assert_eq!(kids.len(), 2);-        assert_eq!(kids[0].tag, 0x80); // matchingId-        assert_eq!(kids[0].value, b"ABC");-        assert_eq!(kids[1].tag, 0xA1); // deviceInfo [1], NOT 0x30 SEQUENCE-        let dev = asn1::children(kids[1].value).expect("deviceInfo children");-        assert_eq!(dev.len(), 2);-        assert_eq!(dev[0].tag, 0x80); // tac-        assert_eq!(dev[0].value, &[0x35, 0x29, 0x06, 0x11]);-        assert_eq!(dev[1].tag, 0xA1); // deviceCapabilities-    }-     #[test]     fn parse_eid_from_response() {         let mut inner = vec![0x5A, 0x10];@@ -232,6 +166,8 @@ mod tests {         let mut m = Vec::new();         m.extend(asn1::tlv(TAG_SEQ_NUMBER, &[0x03]));         m.extend(asn1::tlv(TAG_NOTIFICATION_EVENT, &[0x00, 0x40])); // enable+        // notificationAddress is tag 0x0C per SGP.22 (not context-[2]).+        assert_eq!(TAG_NOTIFICATION_ADDRESS, 0x0C);         m.extend(asn1::tlv(TAG_NOTIFICATION_ADDRESS, "smdp.example.com".as_bytes()));         let meta = asn1::tlv(TAG_NOTIFICATION_METADATA, &m);         let list = asn1::tlv(TAG_NOTIFICATION_LIST, &meta);@@ -243,72 +179,4 @@ mod tests {         assert_eq!(notes[0].operation, "enable");         assert_eq!(notes[0].address, "smdp.example.com");     }--    #[test]-    fn euicc_challenge_roundtrip() {-        assert_eq!(build_get_euicc_challenge(), vec![0xBF, 0x2E, 0x00]);-        let challenge = [0x11u8; 16];-        let inner = asn1::tlv(TAG_EUICC_CHALLENGE, &challenge);-        let resp = asn1::tlv(TAG_GET_EUICC_CHALLENGE, &inner);-        assert_eq!(parse_euicc_challenge(&resp).unwrap(), challenge.to_vec());-    }--    #[test]-    fn ctx_params1_shape() {-        let ctx = build_ctx_params1("MID-123", &[0, 0, 0, 0]);-        // A0 { 80 <mid> 30 { 80 04 <tac> A1 00 } }-        let common = asn1::find(&ctx, TAG_CTX_PARAMS_COMMON).unwrap();-        assert_eq!(asn1::find(common, TAG_MATCHING_ID).unwrap(), b"MID-123");-        let di = asn1::find(common, TAG_DEVICE_INFO).unwrap();-        assert_eq!(asn1::find(di, TAG_TAC).unwrap(), &[0, 0, 0, 0]);-        assert_eq!(asn1::find(di, TAG_DEVICE_CAPS).unwrap(), &[] as &[u8]);-    }--    #[test]-    fn authenticate_server_concatenates_blobs() {-        let req = build_authenticate_server(&[0x30, 0x01, 0xAA], &[0x5F, 0x37, 0x01, 0xBB], &[0x04, 0x01, 0xCC], &[0x30, 0x01, 0xDD], &[0xA0, 0x00]);-        let body = asn1::find(&req, TAG_AUTHENTICATE_SERVER).unwrap();-        assert_eq!(body, &[0x30, 0x01, 0xAA, 0x5F, 0x37, 0x01, 0xBB, 0x04, 0x01, 0xCC, 0x30, 0x01, 0xDD, 0xA0, 0x00]);-    }--    #[test]-    fn segment_bpp_orders_elements() {-        let isc = asn1::tlv(TAG_INITIALISE_SECURE_CHANNEL, &[0x01]);-        let seq87 = asn1::tlv(TAG_BPP_SEQ_87, &asn1::tlv(0x87, &[0x11, 0x22]));-        let mut seq88_inner = asn1::tlv(0x88, &[0x33]);-        seq88_inner.extend(asn1::tlv(0x88, &[0x44]));-        let seq88 = asn1::tlv(TAG_BPP_SEQ_88, &seq88_inner);-        let seq86 = asn1::tlv(TAG_BPP_SEQ_86, &asn1::tlv(0x86, &[0x55]));-        let mut body = Vec::new();-        body.extend(isc);-        body.extend(seq87);-        body.extend(seq88);-        body.extend(seq86);-        let bpp = asn1::tlv(TAG_BPP, &body);--        let segments = segment_bpp(&bpp).unwrap();-        assert_eq!(segments.len(), 5); // BF23, 87, 88, 88, 86-        assert_eq!(segments[0], vec![0xBF, 0x23, 0x01, 0x01]);-        assert_eq!(segments[1], vec![0x87, 0x02, 0x11, 0x22]);-        assert_eq!(segments[2], vec![0x88, 0x01, 0x33]);-        assert_eq!(segments[3], vec![0x88, 0x01, 0x44]);-        assert_eq!(segments[4], vec![0x86, 0x01, 0x55]);-    }--    #[test]-    fn install_result_success_and_error() {-        let ok_final = asn1::tlv(TAG_FINAL_RESULT, &asn1::tlv(TAG_SUCCESS_RESULT, &[]));-        let ok_data = asn1::tlv(TAG_PIR_DATA, &ok_final);-        let ok = asn1::tlv(TAG_PROFILE_INSTALL_RESULT, &ok_data);-        assert!(parse_install_result(&ok).unwrap().success);--        let mut err_inner = asn1::tlv(TAG_RESULT, &[0x00]); // bppCommandId-        err_inner.extend(asn1::tlv(0x81, &[0x05])); // errorReason = 5-        let err_final = asn1::tlv(TAG_FINAL_RESULT, &asn1::tlv(TAG_ERROR_RESULT, &err_inner));-        let err_data = asn1::tlv(TAG_PIR_DATA, &err_final);-        let err = asn1::tlv(TAG_PROFILE_INSTALL_RESULT, &err_data);-        let r = parse_install_result(&err).unwrap();-        assert!(!r.success);-        assert!(r.message.contains('5'));-    } }
euicc/src/main/rust/src/es10b.rs
diff --git a/euicc/src/main/rust/src/es10b.rs b/euicc/src/main/rust/src/es10b.rsnew file mode 100644index 0000000000..5b701822e3--- /dev/null+++ b/euicc/src/main/rust/src/es10b.rs@@ -0,0 +1,441 @@+//! ES10b download-flow command builders and response parsers (SGP.22).+//!+//! The AuthenticateServer → PrepareDownload → LoadBoundProfilePackage sequence+//! plus profile-metadata preview, notification retrieval, and CancelSession.+//! Split from [`crate::es10`] (which keeps the ES10c local ops) along module+//! lines; shared tags and ASN.1 scalar helpers live there and are imported.+//!+//! Pure protocol logic, fully host-testable. Reimplemented for this repo,+//! following the open-source OpenEUICC / lpac (GPL-3.0-only).++use crate::asn1;+use crate::es10::{+    TAG_ICCID, TAG_NOTIFICATION_ADDRESS, TAG_NOTIFICATION_LIST, TAG_NOTIFICATION_METADATA,+    TAG_SEQ_NUMBER, decode_iccid, encode_int_minimal, first_byte, parse_int, utf8,+};++// --- Tags (SGP.22) ---+const TAG_GET_EUICC_CHALLENGE: u32 = 0xBF2E; // ES10b GetEUICCChallenge+const TAG_EUICC_CHALLENGE: u32 = 0x80; // [0] euiccChallenge Octet16+const TAG_AUTHENTICATE_SERVER: u32 = 0xBF38; // ES10b AuthenticateServer+const TAG_PREPARE_DOWNLOAD: u32 = 0xBF21; // ES10b PrepareDownload+const TAG_HASH_CC: u32 = 0x04; // hashCc Octet32 (confirmation code)+const TAG_BPP: u32 = 0xBF36; // BoundProfilePackage+const TAG_INITIALISE_SECURE_CHANNEL: u32 = 0xBF23; // initialiseSecureChannelRequest+const TAG_BPP_SEQ_87: u32 = 0xA0; // firstSequenceOf87+const TAG_BPP_SEQ_88: u32 = 0xA1; // sequenceOf88+const TAG_BPP_SEQ_87B: u32 = 0xA2; // secondSequenceOf87+const TAG_BPP_SEQ_86: u32 = 0xA3; // sequenceOf86+const TAG_PROFILE_INSTALL_RESULT: u32 = 0xBF37; // ProfileInstallationResult+const TAG_PIR_DATA: u32 = 0xBF27; // profileInstallationResultData+const TAG_FINAL_RESULT: u32 = 0xA2; // [2] finalResult+const TAG_SUCCESS_RESULT: u32 = 0xA0; // [0] successResult+const TAG_ERROR_RESULT: u32 = 0xA1; // [1] errorResult+const TAG_BPP_COMMAND_ID: u32 = 0x80; // [0] bppCommandId INTEGER inside errorResult+const TAG_ERROR_REASON: u32 = 0x81; // [1] errorReason ENUMERATED inside errorResult++// ctxParams1 / DeviceInfo construction tags.+const TAG_CTX_PARAMS_COMMON: u32 = 0xA0; // [0] ctxParamsForCommonAuthentication+const TAG_MATCHING_ID: u32 = 0x80; // [0] matchingId UTF8String+const TAG_DEVICE_INFO: u32 = 0xA1; // [1] deviceInfo (IMPLICIT replaces SEQUENCE tag)+const TAG_TAC: u32 = 0x80; // [0] tac Octet4+const TAG_DEVICE_CAPS: u32 = 0xA1; // [1] deviceCapabilities SEQUENCE+const TAG_IMEI: u32 = 0x82; // imei Octet8, GSM-BCD, inside deviceInfo after capabilities++/// Default Type Allocation Code used when the device IMEI is unknown, matching+/// lpac (`euicc/es10b.c:es10b_authenticate_server_r`).+pub const DEFAULT_TAC: [u8; 4] = [0x35, 0x29, 0x06, 0x11];++// Profile metadata (ES8P StoreMetadata, tag BF25) and session tags.+const TAG_PROFILE_METADATA: u32 = 0xBF25; // StoreMetadata inside authenticateClient+const TAG_METADATA_SPN: u32 = 0x91; // serviceProviderName UTF8String+const TAG_METADATA_NAME: u32 = 0x92; // profileName UTF8String+const TAG_METADATA_CLASS: u32 = 0x95; // profileClass INTEGER+const TAG_RETRIEVE_NOTIFICATIONS: u32 = 0xBF2B; // ES10b RetrieveNotificationsList+const TAG_SEARCH_CRITERIA: u32 = 0xA0; // [0] searchCriteria+const TAG_CANCEL_SESSION: u32 = 0xBF41; // ES10b CancelSessionRequest+const TAG_CANCEL_REASON: u32 = 0x81; // [1] reason ENUMERATED+const TAG_TX_ID: u32 = 0x80; // [0] transactionId (inside signed SEQUENCEs)+const TAG_CC_FLAG: u32 = 0x01; // ccRequiredFlag BOOLEAN (inside smdpSigned2)+const TAG_SIGNED_SEQUENCE: u32 = 0x30; // SEQUENCE wrapping serverSigned1/smdpSigned2++// ---------------------------------------------------------------------------+// Download flow (ES10b): challenge, AuthenticateServer, PrepareDownload,+// LoadBoundProfilePackage+// ---------------------------------------------------------------------------++/// Outcome of installing a Bound Profile Package.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct InstallResult {+    pub success: bool,+    pub message: String,+    /// Sequence number from the result's NotificationMetadata (for retrieve/remove).+    pub seq_number: i64,+    /// Failing BPP command id (0-5) on error, `None` on success.+    pub bpp_command_id: Option<i64>,+    /// SGP.22 install error reason on error, `None` on success.+    pub error_reason: Option<i64>,+    /// The raw ProfileInstallationResult (BF37) to deliver via HandleNotification.+    pub notification: Vec<u8>,+}++/// BPP command id names, matching lpac's `euicc_bppcommandid2str`.+pub fn bpp_command_name(id: i64) -> &'static str {+    match id {+        0 => "initialise_secure_channel",+        1 => "configure_isdp",+        2 => "store_metadata",+        3 => "store_metadata2",+        4 => "replace_session_keys",+        5 => "load_profile_elements",+        _ => "unknown",+    }+}++/// SGP.22 install error reason names, matching lpac's `euicc_errorreason2str`.+pub fn error_reason_name(reason: i64) -> &'static str {+    match reason {+        1 => "incorrect_input_values",+        2 => "invalid_signature",+        3 => "invalid_transaction_id",+        4 => "unsupported_crt_values",+        5 => "unsupported_remote_operation_type",+        6 => "unsupported_profile_class",+        7 => "scp03t_structure_error",+        8 => "scp03t_security_error",+        9 => "install_failed_due_to_iccid_already_exists_on_euicc",+        10 => "install_failed_due_to_insufficient_memory_for_profile",+        11 => "install_failed_due_to_interruption",+        12 => "install_failed_due_to_pe_processing_error",+        13 => "install_failed_due_to_data_mismatch",+        14 => "test_profile_install_failed_due_to_invalid_naa_key",+        15 => "ppr_not_allowed",+        127 => "install_failed_due_to_unknown_error",+        _ => "unknown",+    }+}++/// Builds the ES10b GetEUICCChallenge request (empty BF2E).+pub fn build_get_euicc_challenge() -> Vec<u8> {+    asn1::tlv(TAG_GET_EUICC_CHALLENGE, &[])+}++/// Parses a GetEUICCChallenge response into the 16-byte challenge.+pub fn parse_euicc_challenge(response: &[u8]) -> Result<Vec<u8>, String> {+    let body = asn1::find(response, TAG_GET_EUICC_CHALLENGE).ok_or("GetEUICCChallenge: missing BF2E")?;+    let challenge = asn1::find(body, TAG_EUICC_CHALLENGE).ok_or("GetEUICCChallenge: missing challenge")?;+    Ok(challenge.to_vec())+}++/// Builds ctxParams1 for common authentication: matchingId + a minimal DeviceInfo.+///+/// `tac` is the 4-byte Type Allocation Code; deviceCapabilities is sent empty.+/// `imei` is the optional 15-digit IMEI string, GSM-BCD encoded as tag `0x82`+/// after the capabilities, matching lpac+/// (`euicc/es10b.c:es10b_authenticate_server_r`). An invalid IMEI is dropped+/// rather than failing the download.+pub fn build_ctx_params1(matching_id: &str, tac: &[u8; 4], imei: Option<&str>) -> Vec<u8> {+    let mut device_info_val = asn1::tlv(TAG_TAC, tac);+    device_info_val.extend(asn1::tlv(TAG_DEVICE_CAPS, &[])); // empty DeviceCapabilities+    if let Some(digits) = imei.and_then(encode_imei_gsm_bcd) {+        device_info_val.extend(asn1::tlv(TAG_IMEI, &digits));+    }+    let device_info = asn1::tlv(TAG_DEVICE_INFO, &device_info_val);++    let mut common = asn1::tlv(TAG_MATCHING_ID, matching_id.as_bytes());+    common.extend(device_info);+    asn1::tlv(TAG_CTX_PARAMS_COMMON, &common)+}++/// GSM-BCD-encodes a 15-digit IMEI string into 8 octets (pair-swapped nibbles,+/// `F`-padded when odd), matching lpac's `euicc_hexutil_gsmbcd2bin`. Returns+/// `None` when the input is not 14-16 ASCII digits.+pub fn encode_imei_gsm_bcd(imei: &str) -> Option<Vec<u8>> {+    let digits = imei.trim();+    if !(14..=16).contains(&digits.len()) || !digits.bytes().all(|b| b.is_ascii_digit()) {+        return None;+    }+    let mut nibbles: Vec<u8> = digits.bytes().map(|b| b - b'0').collect();+    if !nibbles.len().is_multiple_of(2) {+        nibbles.push(0x0F);+    }+    let mut out = Vec::with_capacity(nibbles.len() / 2);+    let mut i = 0;+    while i < nibbles.len() {+        out.push((nibbles[i + 1] << 4) | nibbles[i]);+        i += 2;+    }+    Some(out)+}++/// Builds the ES10b AuthenticateServer request by concatenating the server blobs+/// (each already a complete DER TLV) with ctxParams1, wrapped in BF38.+pub fn build_authenticate_server(+    server_signed1: &[u8],+    server_signature1: &[u8],+    euicc_ci_pkid: &[u8],+    server_certificate: &[u8],+    ctx_params1: &[u8],+) -> Vec<u8> {+    let mut v = Vec::new();+    v.extend_from_slice(server_signed1);+    v.extend_from_slice(server_signature1);+    v.extend_from_slice(euicc_ci_pkid);+    v.extend_from_slice(server_certificate);+    v.extend_from_slice(ctx_params1);+    asn1::tlv(TAG_AUTHENTICATE_SERVER, &v)+}++/// Builds the ES10b PrepareDownload request from the SM-DP+ blobs (each a+/// complete DER TLV), wrapped in BF21.+pub fn build_prepare_download(+    smdp_signed2: &[u8],+    smdp_signature2: &[u8],+    hash_cc: Option<&[u8]>,+    smdp_certificate: &[u8],+) -> Vec<u8> {+    let mut v = Vec::new();+    v.extend_from_slice(smdp_signed2);+    v.extend_from_slice(smdp_signature2);+    if let Some(cc) = hash_cc {+        v.extend(asn1::tlv(TAG_HASH_CC, cc));+    }+    v.extend_from_slice(smdp_certificate);+    asn1::tlv(TAG_PREPARE_DOWNLOAD, &v)+}++/// Segments a Bound Profile Package (BF36) into the ordered list of TLVs the LPA+/// must transmit to the eUICC via STORE DATA, mirroring lpac+/// (`euicc/es10b.c:es10b_load_bound_profile_package_r`):+/// `[BF23][A0 whole][A1 header + 88 elements...][A2 whole if present][A3+/// header + 86 elements...]`.+///+/// The wrapper TLVs are sent whole (tag + length + value); the `88…`/`86…`+/// element sequences are sent header-first (tag + length, without the value)+/// then element by element, because the eUICC uses the header as a length+/// prefix for the stream that follows.+pub fn segment_bpp(bpp: &[u8]) -> Result<Vec<Vec<u8>>, String> {+    let body = asn1::find(bpp, TAG_BPP).ok_or("BoundProfilePackage: missing BF36")?;+    let mut segments = Vec::new();++    // initialiseSecureChannelRequest (BF23): sent whole.+    let isc = asn1::find(body, TAG_INITIALISE_SECURE_CHANNEL)+        .ok_or("BoundProfilePackage: missing BF23")?;+    segments.push(asn1::tlv(TAG_INITIALISE_SECURE_CHANNEL, isc));++    // firstSequenceOf87 (A0): sent whole.+    let seq87 = asn1::find(body, TAG_BPP_SEQ_87).ok_or("BoundProfilePackage: missing A0")?;+    segments.push(asn1::tlv(TAG_BPP_SEQ_87, seq87));++    // sequenceOf88 (A1): header first, then each 88 element.+    let seq88 = asn1::find(body, TAG_BPP_SEQ_88).ok_or("BoundProfilePackage: missing A1")?;+    segments.push(asn1::header(TAG_BPP_SEQ_88, seq88.len()));+    for element in asn1::children(seq88).ok_or("BPP: malformed A1 sequence")? {+        segments.push(asn1::tlv(element.tag, element.value));+    }++    // secondSequenceOf87 (A2): optional, sent whole when present.+    if let Some(seq87b) = asn1::find(body, TAG_BPP_SEQ_87B) {+        segments.push(asn1::tlv(TAG_BPP_SEQ_87B, seq87b));+    }++    // sequenceOf86 (A3): header first, then each 86 element.+    let seq86 = asn1::find(body, TAG_BPP_SEQ_86).ok_or("BoundProfilePackage: missing A3")?;+    segments.push(asn1::header(TAG_BPP_SEQ_86, seq86.len()));+    for element in asn1::children(seq86).ok_or("BPP: malformed A3 sequence")? {+        segments.push(asn1::tlv(element.tag, element.value));+    }++    Ok(segments)+}++/// Parses a ProfileInstallationResult (BF37) into an [`InstallResult`].+///+/// Matches fields by tag — `bppCommandId 0x80`, `errorReason 0x81` — like lpac's+/// `es10b_load_bound_profile_package_tx`, because extra result-data fields shift+/// any positional read. Also extracts the NotificationMetadata `seqNumber` so the+/// caller can retrieve/remove the notification by sequence.+pub fn parse_install_result(response: &[u8]) -> Result<InstallResult, String> {+    let body = asn1::find(response, TAG_PROFILE_INSTALL_RESULT)+        .ok_or("ProfileInstallationResult: missing BF37")?;+    let data = asn1::find(body, TAG_PIR_DATA).ok_or("ProfileInstallationResult: missing BF27")?;+    let final_result = asn1::find(data, TAG_FINAL_RESULT)+        .ok_or("ProfileInstallationResult: missing finalResult")?;++    let seq_number = asn1::find(data, TAG_NOTIFICATION_METADATA)+        .and_then(|m| asn1::find(m, TAG_SEQ_NUMBER))+        .map(parse_int)+        .unwrap_or(-1);++    let base = InstallResult {+        success: false,+        message: String::new(),+        seq_number,+        bpp_command_id: None,+        error_reason: None,+        notification: response.to_vec(),+    };++    if asn1::find(final_result, TAG_SUCCESS_RESULT).is_some() {+        return Ok(InstallResult {+            success: true,+            message: "Profile installed".to_string(),+            ..base+        });+    }+    if let Some(err) = asn1::find(final_result, TAG_ERROR_RESULT) {+        // errorResult ::= SEQUENCE { bppCommandId INTEGER, errorReason ENUMERATED, ... }+        let kids = asn1::children(err).unwrap_or_default();+        let find_int = |tag: u32| {+            kids.iter()+                .find(|k| k.tag == tag)+                .map(|k| parse_int(k.value))+        };+        let cmd = find_int(TAG_BPP_COMMAND_ID);+        let reason = find_int(TAG_ERROR_REASON);+        let detail = match (cmd, reason) {+            (Some(c), Some(r)) => format!("{} ({})", bpp_command_name(c), error_reason_name(r)),+            (None, Some(r)) => error_reason_name(r).to_string(),+            (Some(c), None) => bpp_command_name(c).to_string(),+            (None, None) => "unknown".to_string(),+        };+        return Ok(InstallResult {+            message: format!("Install failed ({detail})"),+            bpp_command_id: cmd,+            error_reason: reason,+            ..base+        });+    }+    Ok(InstallResult {+        message: "Install failed (unknown result)".to_string(),+        ..base+    })+}++// ---------------------------------------------------------------------------+// Metadata, transaction extraction, retrieve-notifications, cancel-session+// ---------------------------------------------------------------------------++/// Parsed carrier preview from the `profileMetadata` (StoreMetadata BF25) the+/// SM-DP+ returns inside AuthenticateClient, mirroring lpac's+/// `es8p_metadata_parse` display subset.+#[derive(Debug, Clone, PartialEq, Eq, Default)]+pub struct ProfileMetadata {+    /// BCD-decoded ICCID digits.+    pub iccid_display: String,+    /// Carrier name (`serviceProviderName`, tag `0x91`).+    pub service_provider: String,+    /// Profile display name (tag `0x92`).+    pub profile_name: String,+    /// "test" / "provisioning" / "operational" / "unknown".+    pub class: String,+}++/// Parses the `profileMetadata` StoreMetadata (BF25) blob into its display+/// subset. Unknown tags are skipped, matching lpac.+pub fn parse_profile_metadata(metadata: &[u8]) -> Result<ProfileMetadata, String> {+    let body = asn1::find(metadata, TAG_PROFILE_METADATA)+        .ok_or("ProfileMetadata: missing BF25")?;+    let kids = asn1::children(body).ok_or("ProfileMetadata: malformed")?;+    let mut out = ProfileMetadata::default();+    for k in &kids {+        match k.tag {+            TAG_ICCID => out.iccid_display = decode_iccid(k.value),+            TAG_METADATA_SPN => out.service_provider = utf8(k.value),+            TAG_METADATA_NAME => out.profile_name = utf8(k.value),+            TAG_METADATA_CLASS => {+                out.class = match first_byte(k.value) {+                    Some(0) => "test",+                    Some(1) => "provisioning",+                    Some(2) => "operational",+                    _ => "unknown",+                }+                .into();+            }+            _ => {}+        }+    }+    Ok(out)+}++/// Extracts the binary `transactionId` (tag `0x80` inside the signed SEQUENCE)+/// from `serverSigned1` (AuthenticateServer path) or `smdpSigned2`+/// (PrepareDownload path). Needed for `hashCc` and CancelSession; lpac keeps+/// the same bytes (`es10b.c` unpacks `0x80` out of the `0x30` SEQUENCE).+pub fn extract_transaction_id(signed: &[u8]) -> Result<Vec<u8>, String> {+    let seq = asn1::find(signed, TAG_SIGNED_SEQUENCE).ok_or("signed blob: missing SEQUENCE")?;+    asn1::find(seq, TAG_TX_ID)+        .map(<[u8]>::to_vec)+        .ok_or_else(|| "signed blob: missing transactionId (80)".to_string())+}++/// Reads the `ccRequiredFlag` (tag `0x01` inside `smdpSigned2`). Any non-zero+/// first byte means the profile needs a confirmation code, like lpac's+/// `convert_bin2long` truthiness check.+pub fn cc_required(smdp_signed2: &[u8]) -> bool {+    asn1::find(smdp_signed2, TAG_SIGNED_SEQUENCE)+        .and_then(|seq| asn1::find(seq, TAG_CC_FLAG))+        .is_some_and(|v| v.first().copied().unwrap_or(0) != 0)+}++/// Builds the ES10b RetrieveNotificationsList request (BF2B) for one sequence+/// number, mirroring lpac's `es10b_retrieve_notifications_list`.+pub fn build_retrieve_notification(seq: u32) -> Vec<u8> {+    let seq_tlv = asn1::tlv(TAG_SEQ_NUMBER, &encode_int_minimal(seq));+    let criteria = asn1::tlv(TAG_SEARCH_CRITERIA, &seq_tlv);+    asn1::tlv(TAG_RETRIEVE_NOTIFICATIONS, &criteria)+}++/// Parses a RetrieveNotificationsList response into the server address (tag+/// `0x0C` inside NotificationMetadata) and the raw pending-notification TLV+/// (BF37 or `0x30` otherSignedNotification, sent whole).+pub fn parse_retrieved_notification(response: &[u8]) -> Result<(String, Vec<u8>), String> {+    let body = asn1::find(response, TAG_RETRIEVE_NOTIFICATIONS)+        .ok_or("RetrieveNotifications: missing BF2B")?;+    let list = asn1::find(body, TAG_NOTIFICATION_LIST)+        .ok_or("RetrieveNotifications: error result (no A0)")?;+    let notif = asn1::children(list)+        .ok_or("RetrieveNotifications: malformed list")?+        .into_iter()+        .find(|k| k.tag == TAG_PROFILE_INSTALL_RESULT || k.tag == TAG_SIGNED_SEQUENCE)+        .ok_or("RetrieveNotifications: no pending notification")?;+    let notif_raw = asn1::wrap(notif.tag, notif.value);+    let meta_body = if notif.tag == TAG_PROFILE_INSTALL_RESULT {+        let data = asn1::find(notif.value, TAG_PIR_DATA)+            .ok_or("RetrieveNotifications: missing BF27")?;+        asn1::find(data, TAG_NOTIFICATION_METADATA)+            .ok_or("RetrieveNotifications: missing BF2F")?+            .to_vec()+    } else {+        asn1::find(notif.value, TAG_NOTIFICATION_METADATA)+            .ok_or("RetrieveNotifications: missing BF2F")?+            .to_vec()+    };+    let address = asn1::find(&meta_body, TAG_NOTIFICATION_ADDRESS)+        .map(utf8)+        .unwrap_or_default();+    Ok((address, notif_raw))+}++/// Cancel-session reasons, matching lpac's `es10b_cancel_session_reason`+/// (`euicc/es10b.h`). The LPA reports the end-user-visible cause.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum CancelReason {+    #[default]+    EndUserRejection = 0,+    Postponed = 1,+    Timeout = 2,+    PprNotAllowed = 3,+    MetadataMismatch = 4,+    LoadBppExecutionError = 5,+}++/// Builds the ES10b CancelSession request (BF41): the binary transaction id+/// plus a reason, mirroring lpac's `es10b_cancel_session_r`.+pub fn build_cancel_session(transaction_id: &[u8], reason: CancelReason) -> Vec<u8> {+    let mut v = asn1::tlv(TAG_TX_ID, transaction_id);+    v.extend(asn1::tlv(TAG_CANCEL_REASON, &[reason as u8]));+    asn1::tlv(TAG_CANCEL_SESSION, &v)+}++include!("es10b_part1.rs");
euicc/src/main/rust/src/es10b_part1.rs
diff --git a/euicc/src/main/rust/src/es10b_part1.rs b/euicc/src/main/rust/src/es10b_part1.rsnew file mode 100644index 0000000000..c921803b7a--- /dev/null+++ b/euicc/src/main/rust/src/es10b_part1.rs@@ -0,0 +1,183 @@+#[cfg(test)]+mod tests {+    use super::*;+    use crate::asn1;+    use crate::es10::{TAG_ICCID, TAG_SEQ_NUMBER, TAG_NOTIFICATION_ADDRESS, TAG_NOTIFICATION_LIST,+        TAG_NOTIFICATION_METADATA};++    #[test]+    fn euicc_challenge_roundtrip() {+        assert_eq!(build_get_euicc_challenge(), vec![0xBF, 0x2E, 0x00]);+        let challenge = [0x11u8; 16];+        let inner = asn1::tlv(TAG_EUICC_CHALLENGE, &challenge);+        let resp = asn1::tlv(TAG_GET_EUICC_CHALLENGE, &inner);+        assert_eq!(parse_euicc_challenge(&resp).unwrap(), challenge.to_vec());+    }++    #[test]+    fn ctx_params1_tags_match_sgp22() {+        // CtxParamsForCommonAuthentication: matchingId [0] IMPLICIT, deviceInfo+        // [1] IMPLICIT (constructed). A bare SEQUENCE tag (0x30) on deviceInfo is+        // malformed — the SM-DP+ cannot verify the AuthenticateServer response+        // built over it (seen as an empty authenticateClient reply).+        let ctx = build_ctx_params1("ABC", &[0x35, 0x29, 0x06, 0x11], None);+        let body = asn1::find(&ctx, TAG_CTX_PARAMS_COMMON).expect("outer A0");+        let kids = asn1::children(body).expect("two children");+        assert_eq!(kids.len(), 2);+        assert_eq!(kids[0].tag, 0x80); // matchingId+        assert_eq!(kids[0].value, b"ABC");+        assert_eq!(kids[1].tag, 0xA1); // deviceInfo [1], NOT 0x30 SEQUENCE+        let dev = asn1::children(kids[1].value).expect("deviceInfo children");+        assert_eq!(dev.len(), 2);+        assert_eq!(dev[0].tag, 0x80); // tac+        assert_eq!(dev[0].value, &[0x35, 0x29, 0x06, 0x11]);+        assert_eq!(dev[1].tag, 0xA1); // deviceCapabilities+    }++    #[test]+    fn ctx_params1_shape() {+        let ctx = build_ctx_params1("MID-123", &[0, 0, 0, 0], None);+        // A0 { 80 <mid> 30 { 80 04 <tac> A1 00 } }+        let common = asn1::find(&ctx, TAG_CTX_PARAMS_COMMON).unwrap();+        assert_eq!(asn1::find(common, TAG_MATCHING_ID).unwrap(), b"MID-123");+        let di = asn1::find(common, TAG_DEVICE_INFO).unwrap();+        assert_eq!(asn1::find(di, TAG_TAC).unwrap(), &[0, 0, 0, 0]);+        assert_eq!(asn1::find(di, TAG_DEVICE_CAPS).unwrap(), &[] as &[u8]);+    }++    #[test]+    fn authenticate_server_concatenates_blobs() {+        let req = build_authenticate_server(&[0x30, 0x01, 0xAA], &[0x5F, 0x37, 0x01, 0xBB], &[0x04, 0x01, 0xCC], &[0x30, 0x01, 0xDD], &[0xA0, 0x00]);+        let body = asn1::find(&req, TAG_AUTHENTICATE_SERVER).unwrap();+        assert_eq!(body, &[0x30, 0x01, 0xAA, 0x5F, 0x37, 0x01, 0xBB, 0x04, 0x01, 0xCC, 0x30, 0x01, 0xDD, 0xA0, 0x00]);+    }++    #[test]+    fn segment_bpp_wraps_and_splits_like_lpac() {+        // lpac framing: [BF23][A0 whole][A1 header + 88s][A2 whole][A3 header + 86s].+        let isc = asn1::tlv(TAG_INITIALISE_SECURE_CHANNEL, &[0x01]);+        let seq87 = asn1::tlv(TAG_BPP_SEQ_87, &asn1::tlv(0x87, &[0x11]));+        let mut seq88_inner = asn1::tlv(0x88, &[0x33]);+        seq88_inner.extend(asn1::tlv(0x88, &[0x44]));+        let seq88 = asn1::tlv(TAG_BPP_SEQ_88, &seq88_inner);+        let seq87b = asn1::tlv(TAG_BPP_SEQ_87B, &asn1::tlv(0x87, &[0x66]));+        let seq86 = asn1::tlv(TAG_BPP_SEQ_86, &asn1::tlv(0x86, &[0x55]));+        let mut body = Vec::new();+        body.extend(isc);+        body.extend(seq87);+        body.extend(seq88);+        body.extend(seq87b);+        body.extend(seq86);+        let bpp = asn1::tlv(TAG_BPP, &body);++        let segments = segment_bpp(&bpp).unwrap();+        // BF23, A0 whole, A1 header, 88, 88, A2 whole, A3 header, 86.+        assert_eq!(segments.len(), 8);+        assert_eq!(segments[0], vec![0xBF, 0x23, 0x01, 0x01]);+        // A1 header: tag + length only, no value bytes.+        assert_eq!(segments[2], asn1::header(TAG_BPP_SEQ_88, seq88_inner.len()));+        assert_eq!(segments[3], vec![0x88, 0x01, 0x33]);+        assert_eq!(segments[4], vec![0x88, 0x01, 0x44]);+        assert_eq!(segments[7], vec![0x86, 0x01, 0x55]);+    }++    #[test]+    fn install_result_success_and_error() {+        let ok_final = asn1::tlv(TAG_FINAL_RESULT, &asn1::tlv(TAG_SUCCESS_RESULT, &[]));+        let ok_data = asn1::tlv(TAG_PIR_DATA, &ok_final);+        let ok = asn1::tlv(TAG_PROFILE_INSTALL_RESULT, &ok_data);+        assert!(parse_install_result(&ok).unwrap().success);++        // Extra fields before the reason must not shift the parse: tags win.+        // bppCommandId is tag 0x80 (same numeric value as es10c's result tag).+        let mut err_inner = asn1::tlv(TAG_BPP_COMMAND_ID, &[0x00]);+        err_inner.extend(asn1::tlv(0x82, &[0xAA])); // unrelated extra field+        err_inner.extend(asn1::tlv(TAG_ERROR_REASON, &[0x05])); // errorReason = 5+        let err_final = asn1::tlv(TAG_FINAL_RESULT, &asn1::tlv(TAG_ERROR_RESULT, &err_inner));+        let err_data = asn1::tlv(TAG_PIR_DATA, &err_final);+        let err = asn1::tlv(TAG_PROFILE_INSTALL_RESULT, &err_data);+        let r = parse_install_result(&err).unwrap();+        assert!(!r.success);+        assert_eq!(r.bpp_command_id, Some(0));+        assert_eq!(r.error_reason, Some(5));+        assert!(r.message.contains("unsupported_remote_operation_type"), "{}", r.message);+    }++    #[test]+    fn ctx_params1_embeds_gsmbcd_imei() {+        // 490154203237518 (classic test IMEI): pair-swapped nibbles, F-padded.+        let ctx = build_ctx_params1("MID", &DEFAULT_TAC, Some("490154203237518"));+        let common = asn1::find(&ctx, TAG_CTX_PARAMS_COMMON).unwrap();+        let di = asn1::find(common, TAG_DEVICE_INFO).unwrap();+        let imei = asn1::find(di, TAG_IMEI).expect("imei tag 0x82");+        assert_eq!(imei, &[0x94, 0x10, 0x45, 0x02, 0x23, 0x73, 0x15, 0xF8]);+        // Default TAC lands when no explicit one is supplied.+        let di_tac = asn1::find(di, TAG_TAC).unwrap();+        assert_eq!(di_tac, DEFAULT_TAC);+        // Garbage IMEIs are dropped, not fatal.+        let ctx2 = build_ctx_params1("MID", &DEFAULT_TAC, Some("not-an-imei!!"));+        let di2 = asn1::find(asn1::find(&ctx2, TAG_CTX_PARAMS_COMMON).unwrap(), TAG_DEVICE_INFO).unwrap();+        assert!(asn1::find(di2, TAG_IMEI).is_none());+    }++    #[test]+    fn profile_metadata_parse_subset() {+        let mut body = Vec::new();+        body.extend(asn1::tlv(TAG_ICCID, &[0x98, 0x10, 0x32]));+        body.extend(asn1::tlv(TAG_METADATA_SPN, "Carrier".as_bytes()));+        body.extend(asn1::tlv(TAG_METADATA_NAME, "Plan 5G".as_bytes()));+        body.extend(asn1::tlv(TAG_METADATA_CLASS, &[0x02]));+        body.extend(asn1::tlv(0x93, &[0x01])); // iconType: skipped+        let meta = asn1::tlv(TAG_PROFILE_METADATA, &body);+        let parsed = parse_profile_metadata(&meta).unwrap();+        assert_eq!(parsed.iccid_display, "890123");+        assert_eq!(parsed.service_provider, "Carrier");+        assert_eq!(parsed.profile_name, "Plan 5G");+        assert_eq!(parsed.class, "operational");+        assert!(parse_profile_metadata(&[0x30, 0x00]).is_err());+    }++    #[test]+    fn retrieve_notification_request_shape() {+        assert_eq!(+            build_retrieve_notification(7),+            vec![0xBF, 0x2B, 0x05, 0xA0, 0x03, 0x80, 0x01, 0x07],+        );+    }++    #[test]+    fn retrieved_notification_address_and_blob() {+        // BF2B { A0 { BF37 { BF27 { BF2F { 0C addr, 80 seq } A2 { A0 {} } } } } }+        // NotificationMetadata and finalResult are siblings inside BF27.+        let mut meta = asn1::tlv(TAG_NOTIFICATION_ADDRESS, "smdp.example.com".as_bytes());+        meta.extend(asn1::tlv(TAG_SEQ_NUMBER, &[0x03]));+        let mut inner = asn1::tlv(TAG_NOTIFICATION_METADATA, &meta);+        inner.extend(asn1::tlv(+            TAG_FINAL_RESULT,+            &asn1::tlv(TAG_SUCCESS_RESULT, &[]),+        ));+        let notif = asn1::tlv(+            TAG_PROFILE_INSTALL_RESULT,+            &asn1::tlv(TAG_PIR_DATA, &inner),+        );+        let resp = asn1::tlv(+            TAG_RETRIEVE_NOTIFICATIONS,+            &asn1::tlv(TAG_NOTIFICATION_LIST, &notif),+        );+        let (address, blob) = parse_retrieved_notification(&resp).unwrap();+        assert_eq!(address, "smdp.example.com");+        assert_eq!(blob, notif);+    }++    #[test]+    fn cancel_session_request_shape() {+        assert_eq!(+            build_cancel_session(&[0xDE, 0xAD], CancelReason::EndUserRejection),+            vec![0xBF, 0x41, 0x07, 0x80, 0x02, 0xDE, 0xAD, 0x81, 0x01, 0x00],+        );+        assert_eq!(+            build_cancel_session(&[0x01], CancelReason::MetadataMismatch),+            vec![0xBF, 0x41, 0x06, 0x80, 0x01, 0x01, 0x81, 0x01, 0x04],+        );+    }+}
euicc/src/main/rust/src/es9p.rs
diff --git a/euicc/src/main/rust/src/es9p.rs b/euicc/src/main/rust/src/es9p.rsindex b0bcd93246..1bc178a0f8 100644--- a/euicc/src/main/rust/src/es9p.rs+++ b/euicc/src/main/rust/src/es9p.rs@@ -29,6 +29,8 @@ pub struct InitiateAuthResult {  /// Result of ES9+.AuthenticateClient. pub struct AuthenticateClientResult {+    /// Raw StoreMetadata (BF25) DER for the carrier-confirm preview.+    pub profile_metadata: Vec<u8>,     pub smdp_signed2: Vec<u8>,     pub smdp_signature2: Vec<u8>,     pub smdp_certificate: Vec<u8>,@@ -57,7 +59,8 @@ pub fn initiate_authentication( }  /// AuthenticateClient: forwards the eUICC's AuthenticateServer response; gets the-/// SM-DP+'s signed profile-binding material.+/// SM-DP+'s signed profile-binding material plus the `profileMetadata` preview+/// (like lpac's `es9p_authenticate_client_r`, which requests all four fields). pub fn authenticate_client(     smdp: &str,     transaction_id: &str,@@ -69,6 +72,7 @@ pub fn authenticate_client(     });     let v = post("authenticateClient", &endpoint(smdp, "authenticateClient"), &body, true)?;     Ok(AuthenticateClientResult {+        profile_metadata: get_b64(&v, "profileMetadata")?,         smdp_signed2: get_b64(&v, "smdpSigned2")?,         smdp_signature2: get_b64(&v, "smdpSignature2")?,         smdp_certificate: get_b64(&v, "smdpCertificate")?,@@ -95,15 +99,46 @@ pub fn get_bound_profile_package(     get_b64(&v, "boundProfilePackage") } +/// ES9+ cancelSession: frees the server-side RSP session identified by+/// `transaction_id` after a failed, cancelled, or superseded download, mirroring+/// lpac's `es9p_cancel_session_r` (`{transactionId, cancelSessionResponse}`).+/// Best-effort: a failure to cancel must not mask the download's own outcome.+pub fn cancel_session(+    smdp: &str,+    transaction_id: &str,+    cancel_session_response: &[u8],+) -> Result<(), String> {+    let body = json!({+        "transactionId": transaction_id,+        "cancelSessionResponse": base64::encode(cancel_session_response),+    });+    let _ = post("cancelSession", &endpoint(smdp, "cancelSession"), &body, false)?;+    Ok(())+} /// HandleNotification: delivers a pending notification to the SM-DP+. Best-effort; /// the eUICC keeps the notification until acknowledged, so a failure is not fatal.-pub fn handle_notification(smdp: &str, pending_notification: &[u8]) -> Result<(), String> {+///+/// The caller resolves the delivery address from the notification itself (lpac's+/// `notification process` reads it out of RetrieveNotificationsList and posts+/// there, not to the download's SM-DP+), falling back to the download server.+pub fn handle_notification_at(address: &str, pending_notification: &[u8]) -> Result<(), String> {     let body = json!({ "pendingNotification": base64::encode(pending_notification) });     // A 204/empty body is normal here; ignore the parsed value.-    let _ = post("handleNotification", &endpoint(smdp, "handleNotification"), &body, false)?;+    let _ = post(+        "handleNotification",+        &endpoint(address, "handleNotification"),+        &body,+        false,+    )?;     Ok(()) } +/// HandleNotification to the download's own SM-DP+ (the common case when the+/// notification carries no explicit address).+pub fn handle_notification(smdp: &str, pending_notification: &[u8]) -> Result<(), String> {+    handle_notification_at(smdp, pending_notification)+}+ // --------------------------------------------------------------------------- // HTTP + helpers // ---------------------------------------------------------------------------@@ -111,7 +146,9 @@ pub fn handle_notification(smdp: &str, pending_notification: &[u8]) -> Result<() fn post(function: &str, url: &str, body: &Value, expect_body: bool) -> Result<Value, String> {     let headers = [         ("Content-Type".to_string(), "application/json".to_string()),-        ("X-Admin-Protocol".to_string(), "gsma/rsp/v2.2.0".to_string()),+        // lpac sends v2.2.2 (`euicc/es9p.c:lpa_header`); behaviour-gating+        // SM-DP+ servers key off this version.+        ("X-Admin-Protocol".to_string(), "gsma/rsp/v2.2.2".to_string()),         ("User-Agent".to_string(), "gsma-rsp-lpad".to_string()),         ("Accept".to_string(), "application/json".to_string()),     ];@@ -142,6 +179,10 @@ fn post(function: &str, url: &str, body: &Value, expect_body: bool) -> Result<Va /// Like lpac, a missing `header`/`functionExecutionStatus` object is itself an /// error: per SGP.22 every ES9+ reply carries one, so its absence means the /// server did not answer the function at all (rather than a field-level gap).+///+/// On failure the message keeps the server's `subjectCode / subjectIdentifier /+/// message` wording (with lpac's `es9p_error_message` table as fallback) so+/// triage sees the real cause instead of just `{state} ({reasonCode})`. fn check_function_execution_status(v: &Value) -> Result<(), String> {     let status = v         .get("header")@@ -154,16 +195,88 @@ fn check_function_execution_status(v: &Value) -> Result<(), String> {         return Err("SM-DP+ reply has functionExecutionStatus without status".to_string());     }     if state != "Executed-Success" {-        let reason = status-            .get("statusCodeData")-            .and_then(|d| d.get("reasonCode"))-            .and_then(Value::as_str)-            .unwrap_or("unknown");-        return Err(format!("SM-DP+ {state} ({reason})"));+        return Err(format!("SM-DP+ {state}: {}", status_detail(status)));     }     Ok(()) } +/// Renders an ES9+ status block as+/// `subjectCode X / subjectIdentifier Y / reasonCode Z: message`, pulling the+/// human wording from the server's `message` field or lpac's+/// `es9p_errors` table when the server sends none.+fn status_detail(status: &Value) -> String {+    let data = status.get("statusCodeData");+    let field = |key: &str| {+        data.and_then(|d| d.get(key))+            .and_then(Value::as_str)+            .unwrap_or("")+    };+    let (subject, identifier, reason, message) = (+        field("subjectCode"),+        field("subjectIdentifier"),+        field("reasonCode"),+        field("message"),+    );+    let wording = if message.is_empty() {+        es9p_error_message(subject, reason).unwrap_or("unknown error")+    } else {+        message+    };+    format!("subjectCode {subject} / subjectIdentifier {identifier} / reasonCode {reason}: {wording}")+}++/// lpac's `es9p_errors` table (`euicc/es9p_errors.c`): (subjectCode,+/// reasonCode) → human cause. Consulted when the server sends no `message`.+fn es9p_error_message(subject: &str, reason: &str) -> Option<&'static str> {+    match (subject, reason) {+        ("8.1", "4.8") => Some("eUICC does not have sufficient space for this Profile"),+        ("8.1", "6.1") => Some("eUICC signature is invalid or serverChallenge is invalid"),+        ("8.1.1", "2.2") => Some("EID is missing (SM-DS address provided or MatchingID empty)"),+        ("8.1.1", "3.1") => Some("a different EID is already associated with this ICCID"),+        ("8.1.1", "3.8") => Some("EID doesn't match the expected value"),+        ("8.1.2", "6.1") => Some("EUM Certificate is invalid"),+        ("8.1.2", "6.3") => Some("EUM Certificate has expired"),+        ("8.1.3", "6.1") => Some("eUICC Certificate is invalid"),+        ("8.1.3", "6.3") => Some("eUICC Certificate has expired"),+        ("8.2", "1.2") => Some("Profile has not yet been released"),+        ("8.2", "3.7") => Some("BPP is not available for a new binding"),+        ("8.2.1", "1.2") => Some("caller is not allowed to perform this function on the target Profile"),+        ("8.2.1", "3.1") => Some("a different EID is associated with this ICCID"),+        ("8.2.1", "3.3") => Some("the Profile identified by the provided ICCID is not available"),+        ("8.2.1", "3.5") => Some("the target Profile cannot be released"),+        ("8.2.1", "3.9") => Some("the Profile Type is unknown to the SM-DP+"),+        ("8.2.5", "1.2") => Some("caller is not allowed to perform this function on the Profile Type"),+        ("8.2.5", "3.7") => Some("No more Profile available for the requested Profile Type"),+        ("8.2.5", "3.8") => Some("Profile Type is not aligned with the Profile identified by the ICCID"),+        ("8.2.5", "3.9") => Some("the Profile Type is unknown to the SM-DP+"),+        ("8.2.5", "4.3") => Some("No eligible Profile for this eUICC/Device"),+        ("8.2.6", "3.1") => Some("a different MatchingID is associated with this ICCID"),+        ("8.2.6", "3.3") => Some("Conflicting MatchingID value"),+        ("8.2.6", "3.8") => Some("MatchingID (AC_Token or EventID) is refused"),+        ("8.2.7", "2.2") => Some("Confirmation Code is missing"),+        ("8.2.7", "3.8") => Some("Confirmation Code is refused"),+        ("8.2.7", "6.4") => Some("The maximum number of retries for the Confirmation Code has been exceeded"),+        ("8.8", "3.1") => Some("The provided SM-DP+ OID is invalid"),+        ("8.8.1", "3.8") => Some("Invalid SM-DP+ Address"),+        ("8.8.2", "3.1") => Some("None of the proposed Public Key Identifiers is supported by the SM-DP+"),+        ("8.8.3", "3.1") => Some("The Specification Version Number indicated by the eUICC is not supported by the SM-DP+"),+        ("8.8.4", "3.7") => Some("The SM-DP+ has no CERT.DPauth.ECDSA signed by one of the CI Public Key supported by the eUICC"),+        ("8.8.5", "4.1") => Some("The Download order has expired"),+        ("8.8.5", "6.4") => Some("The maximum number of retries for the Profile download order has been exceeded"),+        ("8.9", "4.2") => Some("Root SM-DS has raised an error"),+        ("8.9", "5.1") => Some("Root SM-DS was unavailable"),+        ("8.9.1", "3.8") => Some("Invalid SM-DS Address"),+        ("8.9.2", "3.1") => Some("None of the proposed Public Key Identifiers is supported by the SM-DS"),+        ("8.9.3", "3.1") => Some("The Specification Version Number indicated by the eUICC is not supported by the SM-DS"),+        ("8.9.4", "3.7") => Some("The SM-DS has no CERT.DS.ECDSA signed by one of the GSMA CI Public Key supported by the eUICC"),+        ("8.9.5", "3.3") => Some("The Event Record already exists in the SM-DS (EventID duplicated)"),+        ("8.9.5", "3.9") => Some("No Event identified by the Event ID for the EID exists"),+        ("8.10.1", "3.9") => Some("The RSP session identified by the TransactionID is unknown"),+        ("8.11.1", "3.9") => Some("Unknown CI Public Key. The CI used by the EUM Certificate is not a trusted root."),+        _ => None,+    }+}+ /// Builds the full ES9+ endpoint URL for a function. fn endpoint(smdp: &str, function: &str) -> String {     format!("{}{ES9P_PATH}{function}", base_url(smdp))
euicc/src/main/rust/src/jni.rs
diff --git a/euicc/src/main/rust/src/jni.rs b/euicc/src/main/rust/src/jni.rsindex ff2fea1408..994cff8e38 100644--- a/euicc/src/main/rust/src/jni.rs+++ b/euicc/src/main/rust/src/jni.rs@@ -46,14 +46,31 @@ fn transmit_apdu(env: &mut JNIEnv, apdu: &[u8]) -> Result<Vec<u8>, String> { }  /// Sends an ES10 command TLV to the ISD-R via GlobalPlatform STORE DATA,-/// splitting into ≤255-byte blocks, and returns the final response TLV with the+/// splitting into small blocks, and returns the final response TLV with the /// trailing `90 00` status stripped.+///+/// Block size is 63 bytes like OpenEUICC's default chunk (`PreferenceUtils`;+/// lpac's `euicc_init` falls back to 120) rather than the APDU maximum: only+/// multi-KB download payloads stress this path, and conservative chunking is+/// what the reference LPAs ship. pub(crate) fn store_data(env: &mut JNIEnv, command: &[u8]) -> Result<Vec<u8>, String> {+    store_data_chunked(env, command, STORE_DATA_CHUNK)+}++/// STORE DATA payload bytes per APDU. OpenEUICC default; see [`store_data`].+pub(crate) const STORE_DATA_CHUNK: usize = 63;++pub(crate) fn store_data_chunked(+    env: &mut JNIEnv,+    command: &[u8],+    chunk: usize,+) -> Result<Vec<u8>, String> {+    let chunk = chunk.clamp(1, 255);     // A zero-length command still sends one (empty) block.     let blocks: Vec<&[u8]> = if command.is_empty() {         vec![&command[0..0]]     } else {-        command.chunks(255).collect()+        command.chunks(chunk).collect()     };     let last = blocks.len() - 1; @@ -63,6 +80,9 @@ pub(crate) fn store_data(env: &mut JNIEnv, command: &[u8]) -> Result<Vec<u8>, St         let p1 = if i == last { 0x91 } else { 0x11 };         let mut apdu = vec![0x80u8, 0xE2, p1, i as u8, block.len() as u8];         apdu.extend_from_slice(block);+        // Only the last block's response carries the ES10 reply: intermediate+        // STORE DATA responses are per-block statuses (61xx chaining is+        // already resolved per APDU by the Kotlin transport). Keep the last.         response = transmit_apdu(env, &apdu)?;     } @@ -77,7 +97,7 @@ pub(crate) fn store_data(env: &mut JNIEnv, command: &[u8]) -> Result<Vec<u8>, St }  /// Returns `s` as a new Java string, or null (used on the error path).-fn new_jstring(env: &JNIEnv, s: &str) -> jstring {+pub(crate) fn new_jstring(env: &JNIEnv, s: &str) -> jstring {     match env.new_string(s) {         Ok(js) => js.into_raw(),         Err(_) => std::ptr::null_mut(),@@ -85,7 +105,7 @@ fn new_jstring(env: &JNIEnv, s: &str) -> jstring { }  /// Reads a Java string into a Rust `String`, or `None` on error.-fn read_string(env: &mut JNIEnv, s: &JString) -> Option<String> {+pub(crate) fn read_string(env: &mut JNIEnv, s: &JString) -> Option<String> {     env.get_string(s).ok().map(|js| js.into()) } @@ -232,29 +252,6 @@ pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeRemoveNotifi     } } -/// `nativeDownloadProfile(activationCode)` — runs the full SGP.22 download for-/// an activation code and returns a JSON `{success, message}` string. Must be-/// called while the ISD-R channel is open (inside `withIsdrChannel`).-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeDownloadProfile<'l>(-    mut env: JNIEnv<'l>,-    _class: JClass<'l>,-    activation_code: JString<'l>,-) -> jstring {-    // Resolve the HTTP bridge (library:network) once; harmless if already done.-    jni_http::init(&mut env);--    let Some(code) = read_string(&mut env, &activation_code) else {-        let json = serde_json::json!({ "success": false, "message": "Invalid activation code" });-        return new_jstring(&env, &json.to_string());-    };--    let json = match crate::download::download_profile(&mut env, &code) {-        Ok(result) => serde_json::json!({ "success": result.success, "message": result.message }),-        Err(message) => serde_json::json!({ "success": false, "message": message }),-    };-    new_jstring(&env, &json.to_string())-}  /// `nativeVersion()` — native core version string. #[no_mangle]
euicc/src/main/rust/src/jni_download.rs
diff --git a/euicc/src/main/rust/src/jni_download.rs b/euicc/src/main/rust/src/jni_download.rsnew file mode 100644index 0000000000..c2b1b83093--- /dev/null+++ b/euicc/src/main/rust/src/jni_download.rs@@ -0,0 +1,274 @@+//! Split-phase download JNI entries: authenticate / finish / cancel plus the+//! atomic download entry kept for the platform service path.+//!+//! Split from `jni.rs` along module lines. The STORE DATA transport and string+//! helpers stay there and are imported; the session store and option parsing+//! live here with the entries that use them.++use jni::objects::{JClass, JString, JValue};+use jni::sys::{jboolean, jint, jstring};+use jni::JNIEnv;++use std::cell::RefCell;+use std::collections::HashMap;++use crate::download;+use crate::es10;+use crate::es10b;+use crate::jni::{new_jstring, read_string};++/// Authenticated sessions awaiting confirm / confirmation-code / finish, keyed+/// by the SM-DP+ transaction id (opaque to Kotlin).+///+/// The split-phase flow opens one ISD-R channel per phase (each native entry+/// runs inside its own `withIsdrChannel`), so the session must survive across+/// JNI calls on the same thread. The map holds at most a handful of small+/// blobs (signed material + ids); finish/cancel consume.+const MAX_SESSIONS: usize = 4;++thread_local! {+    static SESSION: RefCell<HashMap<String, download::DownloadSession>> =+        RefCell::new(HashMap::new());+}++/// `nativeDownloadProfile(activationCode)` — runs the full SGP.22 download for+/// an activation code and returns a JSON `{success, message}` string. Must be+/// called while the ISD-R channel is open (inside `withIsdrChannel`).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeDownloadProfile<'l>(+    mut env: JNIEnv<'l>,+    _class: JClass<'l>,+    activation_code: JString<'l>,+) -> jstring {+    // Resolve the HTTP bridge (library:network) once; harmless if already done.+    jni_http::init(&mut env);++    let Some(code) = read_string(&mut env, &activation_code) else {+        let json = serde_json::json!({ "success": false, "message": "Invalid activation code" });+        return new_jstring(&env, &json.to_string());+    };++    let json = match crate::download::download_profile(&mut env, &code) {+        Ok(result) => serde_json::json!({ "success": result.success, "message": result.message }),+        Err(message) => serde_json::json!({ "success": false, "message": message }),+    };+    new_jstring(&env, &json.to_string())+}++/// `nativeAuthenticate(activationCode, confirmationCode, tacHex, imei)` —+/// runs InitiateAuthentication → AuthenticateServer → AuthenticateClient and+/// returns a JSON session `{error, transactionId, carrier, profileName, iccid,+/// ccRequired}` without touching the eUICC's profile store. The opaque+/// `transactionId` handle feeds `nativeFinishDownload` / `nativeCancelDownload`.+///+/// `tacHex` is

Diff truncated.