diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/AppModules.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/AppModules.kt index 2a39bcf6d..b7718ae07 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/AppModules.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/AppModules.kt @@ -165,14 +165,30 @@ class AppModules( // Offers easy methods to know when connections are happening through Tor or not val roleBasedHttpClientBuilder = RoleBasedHttpClientBuilder(okHttpClients, torPrefs.value) + val electrumXClient by lazy { + Log.d("AppModules", "ElectrumXClient Init") + val client = + ElectrumXClient( + socketFactory = { roleBasedHttpClientBuilder.socketFactoryForNip05() }, + ) + applicationIOScope.launch { + try { + val pinnedCerts = namecoinPrefs.loadPinnedCerts() + if (pinnedCerts.isNotEmpty()) { + client.setDynamicCerts(pinnedCerts) + } + } catch (_: Exception) { + // Non-fatal — defaults will still work + } + } + client + } + val namecoinResolver by lazy { Log.d("AppModules", "Namecoin Resolver Init") NamecoinNameResolver( - electrumxClient = - ElectrumXClient( - socketFactory = { roleBasedHttpClientBuilder.socketFactoryForNip05() }, - ), + electrumxClient = electrumXClient, serverListProvider = { // User-configured custom servers take priority namecoinPrefs.customServersOrNull diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/preferences/NamecoinSharedPreferences.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/preferences/NamecoinSharedPreferences.kt index 600cecaa9..b6bab2374 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/preferences/NamecoinSharedPreferences.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/preferences/NamecoinSharedPreferences.kt @@ -32,7 +32,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.first -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.launch import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import kotlin.coroutines.cancellation.CancellationException @@ -58,17 +58,21 @@ class NamecoinSharedPreferences( companion object { val KEY_ENABLED = booleanPreferencesKey("namecoin.enabled") val KEY_CUSTOM_SERVERS = stringPreferencesKey("namecoin.customServers") + val KEY_PINNED_CERTS = stringPreferencesKey("namecoin.pinnedCerts") } /** * Current settings, loaded synchronously at init to avoid races. */ - private val _settings = - MutableStateFlow( - runBlocking { loadFromDisk() ?: NamecoinSettings.DEFAULT }, - ) + private val _settings = MutableStateFlow(NamecoinSettings.DEFAULT) val settings: StateFlow = _settings + init { + scope.launch { + _settings.tryEmit(loadFromDisk() ?: NamecoinSettings.DEFAULT) + } + } + /** Synchronous snapshot — safe to call from `serverListProvider` lambdas. */ val current: NamecoinSettings get() = _settings.value @@ -99,8 +103,48 @@ class NamecoinSharedPreferences( suspend fun reset() { persist(NamecoinSettings.DEFAULT) + clearPinnedCerts() } + /** + * Store a PEM-encoded certificate that the user accepted via Test Connection. + * The cert is appended to the existing list and synced to the ElectrumXClient. + */ + suspend fun addPinnedCert(pem: String) { + val existing = loadPinnedCertsFromDisk() + val updated = (existing + pem).distinct() + savePinnedCerts(updated) + } + + /** Load all user-pinned certs from disk (for startup sync). */ + suspend fun loadPinnedCerts(): List = loadPinnedCertsFromDisk() + + private suspend fun clearPinnedCerts() = savePinnedCerts(emptyList()) + + private suspend fun savePinnedCerts(certs: List) { + try { + context.sharedPreferencesDataStore.edit { prefs -> + prefs[KEY_PINNED_CERTS] = json.encodeToString(certs) + } + } catch (e: Exception) { + if (e is CancellationException) throw e + Log.e("NamecoinPrefs", "Error writing pinned certs: ${e.message}") + } + } + + private suspend fun loadPinnedCertsFromDisk(): List = + try { + val prefs = context.sharedPreferencesDataStore.data.first() + val certsJson = prefs[KEY_PINNED_CERTS] + if (certsJson != null) { + json.decodeFromString>(certsJson) + } else { + emptyList() + } + } catch (_: Exception) { + emptyList() + } + // ── Internal ─────────────────────────────────────────────────────── private suspend fun persist(settings: NamecoinSettings) { diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/namecoin/NamecoinSettings.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/namecoin/NamecoinSettings.kt index 4855b493f..1a859848c 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/namecoin/NamecoinSettings.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/namecoin/NamecoinSettings.kt @@ -66,7 +66,7 @@ data class NamecoinSettings( * TLS is the default protocol. Append `:tcp` for plaintext * (useful for `.onion` addresses and local servers). * - * `.onion` addresses automatically get `trustAllCerts = true` + * `.onion` addresses automatically get `usePinnedTrustStore = true` * since certificate verification is meaningless over Tor. */ fun parseServerString(s: String): ElectrumxServer? { @@ -77,11 +77,15 @@ data class NamecoinSettings( if (host.isEmpty() || port <= 0 || port > 65535) return null val useSsl = parts.getOrNull(2)?.trim()?.lowercase() != "tcp" val isOnion = host.endsWith(".onion") + // All custom servers use the pinned trust store. ElectrumX + // servers almost universally use self-signed certs, so we + // route them through our pinned SSLSocketFactory (hardcoded + // defaults + TOFU-pinned certs + system CAs). return ElectrumxServer( host = host, port = port, useSsl = useSsl, - trustAllCerts = isOnion || !useSsl, + usePinnedTrustStore = true, ) } diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/userSuggestions/UserSuggestionState.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/userSuggestions/UserSuggestionState.kt index 4fc579daa..4adc385d5 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/userSuggestions/UserSuggestionState.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/userSuggestions/UserSuggestionState.kt @@ -82,20 +82,27 @@ class UserSuggestionState( .map(::userSearchTermOrNull) .map { prefix -> if (prefix != null) { - if (prefix.contains('@')) { + // NIP-05 resolution: user@domain or bare .bit domain + val nip05 = + if (prefix.contains('@')) { + Nip05Id.parse(prefix) + } else if (prefix.endsWith(".bit", ignoreCase = true)) { + Nip05Id("_", prefix.lowercase()) + } else { + null + } + if (nip05 != null) { runCatching { - Nip05Id.parse(prefix)?.let { nip05 -> - nip05Client.get(nip05)?.let { info -> - val user = account.cache.checkGetOrCreateUser(info.pubkey) - if (user != null) { - info.relays.forEach { - it.normalizeRelayUrlOrNull()?.let { relay -> - account.cache.relayHints.addKey(user.pubkey(), relay) - } + nip05Client.get(nip05)?.let { info -> + val user = account.cache.checkGetOrCreateUser(info.pubkey) + if (user != null) { + info.relays.forEach { + it.normalizeRelayUrlOrNull()?.let { relay -> + account.cache.relayHints.addKey(user.pubkey(), relay) } } - user } + user } }.getOrNull() } else if (prefix.startsWithAny(userUriPrefixes)) { diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/search/SearchBarViewModel.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/search/SearchBarViewModel.kt index d29bb7037..02045f705 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/search/SearchBarViewModel.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/search/SearchBarViewModel.kt @@ -95,20 +95,28 @@ class SearchBarViewModel( searchTerm .debounce(400) .mapLatest { term -> - if (term.contains('@')) { + // NIP-05 resolution: user@domain or bare .bit domain + val nip05 = + if (term.contains('@')) { + Nip05Id.parse(term) + } else if (term.endsWith(".bit", ignoreCase = true)) { + // Bare .bit domain → synthesize _@domain.bit + Nip05Id("_", term.lowercase()) + } else { + null + } + if (nip05 != null) { runCatching { - Nip05Id.parse(term)?.let { nip05 -> - nip05Client.get(nip05)?.let { info -> - val user = account.cache.checkGetOrCreateUser(info.pubkey) - if (user != null) { - info.relays.forEach { - it.normalizeRelayUrlOrNull()?.let { relay -> - account.cache.relayHints.addKey(user.pubkey(), relay) - } + nip05Client.get(nip05)?.let { info -> + val user = account.cache.checkGetOrCreateUser(info.pubkey) + if (user != null) { + info.relays.forEach { + it.normalizeRelayUrlOrNull()?.let { relay -> + account.cache.relayHints.addKey(user.pubkey(), relay) } } - user } + user } }.getOrNull() } else if (term.startsWithAny(userUriPrefixes)) { diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/settings/NamecoinSettingsScreen.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/settings/NamecoinSettingsScreen.kt index 9015ae414..0fdbd7be8 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/settings/NamecoinSettingsScreen.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/settings/NamecoinSettingsScreen.kt @@ -28,32 +28,38 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vitorpamplona.amethyst.Amethyst import com.vitorpamplona.amethyst.R import com.vitorpamplona.amethyst.model.preferences.NamecoinSharedPreferences import com.vitorpamplona.amethyst.ui.navigation.navs.INav import com.vitorpamplona.amethyst.ui.navigation.topbars.TopBarWithBackButton import com.vitorpamplona.amethyst.ui.stringRes +import com.vitorpamplona.quartz.nip05DnsIdentifiers.namecoin.ElectrumXClient import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun NamecoinSettingsScreen(nav: INav) { - NamecoinSettingsScreen(Amethyst.instance.namecoinPrefs, nav) + NamecoinSettingsScreen( + Amethyst.instance.namecoinPrefs, + electrumXClient = { Amethyst.instance.electrumXClient }, + nav, + ) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun NamecoinSettingsScreen( namecoinPrefs: NamecoinSharedPreferences, + electrumXClient: () -> ElectrumXClient, nav: INav, ) { - val namecoinSettings by namecoinPrefs.settings.collectAsState() + val namecoinSettings by namecoinPrefs.settings.collectAsStateWithLifecycle() val scope = rememberCoroutineScope() Scaffold( @@ -82,6 +88,13 @@ fun NamecoinSettingsScreen( onReset = { scope.launch { namecoinPrefs.reset() } }, + onTestServer = { server -> electrumXClient().testServer(server) }, + onPinCert = { pem -> + scope.launch { + namecoinPrefs.addPinnedCert(pem) + electrumXClient().addPinnedCert(pem) + } + }, ) } } diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/settings/NamecoinSettingsSection.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/settings/NamecoinSettingsSection.kt index db747e138..5db51d692 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/settings/NamecoinSettingsSection.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/settings/NamecoinSettingsSection.kt @@ -20,6 +20,7 @@ */ package com.vitorpamplona.amethyst.ui.screen.loggedIn.settings +import android.os.Build import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.expandVertically import androidx.compose.animation.shrinkVertically @@ -41,6 +42,11 @@ import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton @@ -53,20 +59,29 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import com.vitorpamplona.amethyst.R import com.vitorpamplona.amethyst.service.namecoin.NamecoinSettings import com.vitorpamplona.quartz.nip05DnsIdentifiers.namecoin.DEFAULT_ELECTRUMX_SERVERS +import com.vitorpamplona.quartz.nip05DnsIdentifiers.namecoin.ElectrumxServer +import com.vitorpamplona.quartz.nip05DnsIdentifiers.namecoin.ServerTestResult +import kotlinx.coroutines.launch +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale /** * Complete settings section for Namecoin ElectrumX server configuration. @@ -79,6 +94,8 @@ import com.vitorpamplona.quartz.nip05DnsIdentifiers.namecoin.DEFAULT_ELECTRUMX_S * @param onAddServer Called with `host:port[:tcp]` when user adds a server * @param onRemoveServer Called with the server string to remove * @param onReset Called when user resets to defaults + * @param onTestServer Suspend function to test a single server + * @param onPinCert Called with PEM string to persist a TOFU-pinned cert */ @Composable fun NamecoinSettingsSection( @@ -87,6 +104,8 @@ fun NamecoinSettingsSection( onAddServer: (String) -> Unit, onRemoveServer: (String) -> Unit, onReset: () -> Unit, + onTestServer: suspend (ElectrumxServer) -> ServerTestResult, + onPinCert: (String) -> Unit = {}, modifier: Modifier = Modifier, ) { Column(modifier = modifier.padding(16.dp)) { @@ -150,12 +169,366 @@ fun NamecoinSettingsSection( } } } + + Spacer(Modifier.height(16.dp)) + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f), + ) + Spacer(Modifier.height(16.dp)) + + // ── Test Connection ──────────────────────────────── + TestConnectionSection( + settings = settings, + onTestServer = onTestServer, + onPinCert = onPinCert, + ) } } } } -// ── Sub-composables ──────────────────────────────────────────────────── +// ── Test Connection ──────────────────────────────────────────────────── + +/** + * Holds a cert pending user confirmation before pinning (TOFU). + */ +private data class PendingCertPin( + val serverHost: String, + val fingerprint: String, + val pem: String, +) + +@Composable +private fun TestConnectionSection( + settings: NamecoinSettings, + onTestServer: suspend (ElectrumxServer) -> ServerTestResult, + onPinCert: (String) -> Unit, +) { + val scope = rememberCoroutineScope() + var isTesting by remember { mutableStateOf(false) } + var testResults by remember { mutableStateOf>(emptyList()) } + var lastTestTimestamp by remember { mutableStateOf(null) } + // Certs discovered during testing that need user confirmation + var pendingCerts by remember { mutableStateOf>(emptyList()) } + // Which cert is currently shown in the confirmation dialog + var confirmingCert by remember { mutableStateOf(null) } + + val servers = settings.toElectrumxServers() ?: DEFAULT_ELECTRUMX_SERVERS + + // ── Cert confirmation dialog ─────────────────────────────── + confirmingCert?.let { pending -> + AlertDialog( + onDismissRequest = { + // Remove from pending list and move to next (or close) + pendingCerts = pendingCerts.drop(1) + confirmingCert = pendingCerts.firstOrNull() + }, + title = { Text(stringResource(R.string.namecoin_pin_cert_title)) }, + text = { + Column { + Text( + stringResource(R.string.namecoin_pin_cert_body, pending.serverHost), + style = MaterialTheme.typography.bodyMedium, + ) + Spacer(Modifier.height(12.dp)) + Text( + "SHA-256:", + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.SemiBold, + ) + Spacer(Modifier.height(4.dp)) + Text( + text = pending.fingerprint, + style = MaterialTheme.typography.labelSmall, + fontFamily = FontFamily.Monospace, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + }, + confirmButton = { + Button(onClick = { + onPinCert(pending.pem) + pendingCerts = pendingCerts.drop(1) + confirmingCert = pendingCerts.firstOrNull() + }) { + Text(stringResource(R.string.namecoin_pin_cert_accept)) + } + }, + dismissButton = { + TextButton(onClick = { + pendingCerts = pendingCerts.drop(1) + confirmingCert = pendingCerts.firstOrNull() + }) { + Text(stringResource(R.string.namecoin_pin_cert_reject)) + } + }, + ) + } + + Column { + // ── Test button ──────────────────────────────────────── + Button( + onClick = { + if (!isTesting) { + isTesting = true + testResults = emptyList() + pendingCerts = emptyList() + scope.launch { + val results = mutableListOf() + val newCerts = mutableListOf() + for (server in servers) { + val result = onTestServer(server) + results.add(result) + testResults = results.toList() + // Collect certs for user confirmation (not auto-pinned) + val pem = result.serverCertPem + val fp = result.certFingerprint + if (result.success && pem != null && fp != null) { + newCerts.add( + PendingCertPin( + serverHost = "${server.host}:${server.port}", + fingerprint = fp, + pem = pem, + ), + ) + } + } + lastTestTimestamp = System.currentTimeMillis() + isTesting = false + // Show confirmation dialog for each new cert + if (newCerts.isNotEmpty()) { + pendingCerts = newCerts + confirmingCert = newCerts.first() + } + } + } + }, + enabled = !isTesting, + modifier = Modifier.fillMaxWidth(), + ) { + if (isTesting) { + CircularProgressIndicator( + modifier = Modifier.size(18.dp), + strokeWidth = 2.dp, + color = MaterialTheme.colorScheme.onPrimary, + ) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.namecoin_testing)) + } else { + Text(stringResource(R.string.namecoin_test_connection)) + } + } + + // ── Per-server results ───────────────────────────────── + if (testResults.isNotEmpty()) { + Spacer(Modifier.height(12.dp)) + + Text( + stringResource(R.string.namecoin_test_results), + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.Medium, + ) + Spacer(Modifier.height(6.dp)) + + testResults.forEach { result -> + ServerTestResultRow(result) + } + + if (isTesting && testResults.size < servers.size) { + Row( + modifier = Modifier.padding(vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + CircularProgressIndicator( + modifier = Modifier.size(14.dp), + strokeWidth = 2.dp, + ) + Spacer(Modifier.width(8.dp)) + Text( + "Testing next server…", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + + // ── Diagnostic card ──────────────────────────────────── + if (testResults.isNotEmpty() || lastTestTimestamp != null) { + Spacer(Modifier.height(16.dp)) + DiagnosticCard( + testResults = testResults, + lastTestTimestamp = lastTestTimestamp, + ) + } + } +} + +@Composable +private fun ServerTestResultRow(result: ServerTestResult) { + val serverLabel = "${result.server.host}:${result.server.port}" + Row( + modifier = + Modifier + .fillMaxWidth() + .padding(vertical = 3.dp), + verticalAlignment = Alignment.Top, + ) { + Text( + text = if (result.success) "✅" else "❌", + fontSize = 14.sp, + modifier = Modifier.padding(end = 6.dp, top = 1.dp), + ) + Column(modifier = Modifier.weight(1f)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = serverLabel, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + Text( + text = stringResource(R.string.namecoin_response_time, result.responseTimeMs), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (result.success) { + Text( + text = stringResource(R.string.namecoin_test_success), + style = MaterialTheme.typography.labelSmall, + color = Color(0xFF2E8B57), + ) + val fp = result.certFingerprint + if (fp != null) { + Text( + text = "Cert: ${fp.take(23)}…", + style = MaterialTheme.typography.labelSmall, + fontFamily = FontFamily.Monospace, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } else { + val errorText = result.error + if (errorText != null) { + Text( + text = errorText, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.error, + ) + } + } + } + } +} + +// ── Diagnostic Card ──────────────────────────────────────────────────── + +@Composable +private fun DiagnosticCard( + testResults: List, + lastTestTimestamp: Long?, +) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = + CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f), + ), + shape = RoundedCornerShape(8.dp), + ) { + Column(modifier = Modifier.padding(12.dp)) { + Text( + stringResource(R.string.namecoin_diagnostics), + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + ) + Spacer(Modifier.height(8.dp)) + + // Last test timestamp + if (lastTestTimestamp != null) { + val formatted = + remember(lastTestTimestamp) { + SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) + .format(Date(lastTestTimestamp)) + } + val successCount = testResults.count { it.success } + val totalCount = testResults.size + DiagnosticRow( + label = stringResource(R.string.namecoin_last_test), + value = "$formatted ($successCount/$totalCount OK)", + ) + } else { + DiagnosticRow( + label = stringResource(R.string.namecoin_last_test), + value = stringResource(R.string.namecoin_no_test_yet), + ) + } + + Spacer(Modifier.height(4.dp)) + + // Device info + DiagnosticRow( + label = stringResource(R.string.namecoin_device_info), + value = "${Build.MANUFACTURER} ${Build.MODEL}, Android ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})", + ) + + Spacer(Modifier.height(4.dp)) + + // TLS info from test results + val tlsVersions = + testResults + .mapNotNull { it.tlsVersion } + .distinct() + val tlsDisplay = + if (tlsVersions.isNotEmpty()) { + tlsVersions.joinToString(", ") + } else { + "—" + } + DiagnosticRow( + label = stringResource(R.string.namecoin_tls_info), + value = tlsDisplay, + ) + } + } +} + +@Composable +private fun DiagnosticRow( + label: String, + value: String, +) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.Top, + ) { + Text( + text = label, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(0.35f), + ) + Text( + text = value, + style = MaterialTheme.typography.labelSmall, + fontFamily = FontFamily.Monospace, + modifier = Modifier.weight(0.65f), + ) + } +} + +// ── Original Sub-composables ─────────────────────────────────────────── @Composable private fun SectionHeader( diff --git a/amethyst/src/main/res/values-cs-rCZ/strings.xml b/amethyst/src/main/res/values-cs-rCZ/strings.xml index 7775e3628..3f211ea2f 100644 --- a/amethyst/src/main/res/values-cs-rCZ/strings.xml +++ b/amethyst/src/main/res/values-cs-rCZ/strings.xml @@ -61,6 +61,8 @@ Podepisovatel neautorizoval dešifrování potřebné k provedení této operace. Aktivujte dešifrování NIP-44 ve své aplikaci pro podepisování a zkuste to znovu Podepisovatel nenalezen Byla aplikace pro podepisování odinstalována? Zkontrolujte, zda je aplikace nainstalována a obsahuje tento účet. Odhlaste se a přihlaste znovu, pokud se aplikace změnila. + Podepisovatel se choval neočekávaně + Externí podepisovatel vrátil data, která jsou pro daný požadavek neobvyklá. Může se jednat o chybu v Amethystu nebo v podepisovateli. Zapy Počet zobrazení Zvýšení @@ -446,6 +448,8 @@ Maximální zaps Konsensus (0–100)% + Jedna možnost + Více možností Datum a čas ukončení ankety Anketa končí za %1$s Uzavřít po @@ -485,6 +489,9 @@ Příjemce a veřejnost neví, kdo platbu poslal Né Zap Žádná stopa v Nostr, pouze v Lightning + Anonymní + Odeslat jako novou jednorázovou identitu. Váš účet nebude s touto odpovědí spojen. + Tato odpověď bude odeslána z nové anonymní identity Souborový server Zvolte server pro nahrání tohoto souboru LnAddress nebo @Uživatel @@ -1324,6 +1331,7 @@ Hashtagy Komunity Seznamy + Relé Odhlásit se na zámek zařízení Soukromá zpráva Veřejná zpráva @@ -1560,6 +1568,7 @@ Krátká videa Hlasová zpráva Hlasová odpověď + Webová záložka Wiki Začněte se skvělým feedem tím, že budete sledovat stejné lidi jako někdo, komu důvěřujete. Importovat seznam sledovaných @@ -1675,4 +1684,17 @@ Vždy Poslední synchronizace: %1$s Od poslední synchronizace + Webové záložky + Zatím žádné webové záložky. Klepněte na + pro přidání. + Přidat webovou záložku + Upravit webovou záložku + Název + Název záložky + Popis + Krátký popis + Tagy (oddělené čárkou) + Uložit + Smazat + Smazat tuto webovou záložku? + Otevřít URL diff --git a/amethyst/src/main/res/values-de-rDE/strings.xml b/amethyst/src/main/res/values-de-rDE/strings.xml index fcf5a470e..1fa61af01 100644 --- a/amethyst/src/main/res/values-de-rDE/strings.xml +++ b/amethyst/src/main/res/values-de-rDE/strings.xml @@ -61,6 +61,8 @@ Der Signierer hat die erforderliche Entschlüsselung nicht autorisiert. Aktiviere NIP-44-Entschlüsselung in deiner Signierer-App und versuche es erneut Signierer nicht gefunden Wurde die Signierer-App deinstalliert? Überprüfe, ob sie installiert ist und dieses Konto enthält. Melde dich ab und wieder an, falls sich die App geändert hat. + Signierer hat sich unerwartet verhalten + Externer Signierer hat Daten zurückgegeben, die für die Anfrage ungewöhnlich sind. Es könnte ein Fehler in Amethyst oder im Signierer vorliegen. Zaps Aufrufe Boost @@ -452,6 +454,8 @@ anz der Bedingungen ist erforderlich Maximaler Zap-Betrag Konsens (0–100)% + Einzelauswahl + Mehrfachauswahl Schließdatum und -zeit Umfrage endet in %1$s Schließen nach @@ -491,6 +495,9 @@ anz der Bedingungen ist erforderlich Empfänger und die Öffentlichkeit wissen nicht, wer die Zahlung gesendet hat Keine Zap Keine Spur in Nostr, nur in Lightning + Anonym + Als neue Wegwerfidentität posten. Dein Konto wird nicht mit dieser Antwort verknüpft. + Diese Antwort wird von einer neuen anonymen Identität veröffentlicht Dateiserver Wählen Sie einen Server zum Hochladen dieser Datei LnAddress oder @Benutzer @@ -1565,6 +1572,7 @@ anz der Bedingungen ist erforderlich Shorts Sprachnachricht Sprachantwort + Web-Lesezeichen Wiki Starte mit einem großartigen Feed, indem du dieselben Personen folgst wie jemand, dem du vertraust. Folgeliste importieren @@ -1680,4 +1688,17 @@ anz der Bedingungen ist erforderlich Gesamter Zeitraum Letzte Synchronisierung: %1$s Seit letzter Synchronisierung + Web-Lesezeichen + Noch keine Web-Lesezeichen. Tippe auf + um eines hinzuzufügen. + Web-Lesezeichen hinzufügen + Web-Lesezeichen bearbeiten + Titel + Lesezeichen-Titel + Beschreibung + Eine kurze Beschreibung + Tags (kommagetrennt) + Speichern + Löschen + Dieses Web-Lesezeichen löschen? + URL öffnen diff --git a/amethyst/src/main/res/values-pl-rPL/strings.xml b/amethyst/src/main/res/values-pl-rPL/strings.xml index b35e2d06a..d343ba069 100644 --- a/amethyst/src/main/res/values-pl-rPL/strings.xml +++ b/amethyst/src/main/res/values-pl-rPL/strings.xml @@ -66,7 +66,7 @@ Zapy Liczba wyświetleń Powtórz - powtórzono + wpis powtórzono edytowano edytuj #%1$s oryginalny @@ -1333,6 +1333,7 @@ Hashtagi Społeczności Listy + Transmitery Wyloguj się przy blokowaniu urządzenia Wiadomość prywatna Publiczna wiadomość @@ -1568,6 +1569,7 @@ Filmiki Wiadomość głosowa Odpowiedź głosowa + Zakładka Wiki Stwórz świetny kanał, obserwując te same osoby, które obserwuje zaufana osoba. Importuj listę obserwowanych @@ -1683,4 +1685,20 @@ Cały czas Ostatnia synchronizacja %1$s Od ostatniej synchronizacji + Zakładki + Brak zakładek. Naciśnij + aby dodać nową zakładkę. + Dodaj zakładkę + Edytuj zakładkę + Adres URL + https://domena.pl + Tytuł + Tytuł zakładki + Opis + Krótki opis + Tagi (oddzielone przecinkami) + nostr, technika, blog + Zapisz + Usuń + Usunąć tę zakładkę? + Otwórz adres URL diff --git a/amethyst/src/main/res/values-pt-rBR/strings.xml b/amethyst/src/main/res/values-pt-rBR/strings.xml index e22277af2..7eccb0071 100644 --- a/amethyst/src/main/res/values-pt-rBR/strings.xml +++ b/amethyst/src/main/res/values-pt-rBR/strings.xml @@ -61,6 +61,8 @@ O assinador não autorizou a descriptografia necessária para realizar esta operação. Ative as descriptografias NIP-44 no seu aplicativo de assinatura e tente novamente Assinador não encontrado O aplicativo de assinatura foi desinstalado? Verifique se ele está instalado e com esta conta. Saia e entre novamente se ele foi alterado. + Assinador se comportou de forma inesperada + O assinador externo retornou dados estranhos para a solicitação. Pode haver um bug no Amethyst ou no assinador. Zaps Contagem de visualizações Impulsionar @@ -446,6 +448,8 @@ Zap máximo Consenso (0–100)% + Escolha única + Múltipla escolha Data e hora de encerramento da enquete Enquete encerra em %1$s Fechar depois @@ -485,6 +489,9 @@ Destinatário e o público não sabem quem enviou o pagamento Sem Zap Nenhum traço no Nostr, apenas na Lightning + Anônimo + Postar como uma nova identidade descartável. Sua conta não será vinculada a esta resposta. + Esta resposta será postada a partir de uma nova identidade anônima Servidor de arquivos Escolha um servidor para onde enviar este arquivo LnAddress ou @Usuário @@ -1560,6 +1567,7 @@ Shorts Mensagem de voz Resposta de voz + Marcador Web Wiki Comece com um ótimo feed seguindo as mesmas pessoas que alguém em quem você confia. Importar lista de seguidos @@ -1675,4 +1683,17 @@ Todo o período Última sincronização: %1$s Desde a última sincronização + Marcadores Web + Nenhum marcador web ainda. Toque em + para adicionar. + Adicionar Marcador Web + Editar Marcador Web + Título + Título do marcador + Descrição + Uma breve descrição + Tags (separadas por vírgula) + Salvar + Excluir + Excluir este marcador web? + Abrir URL diff --git a/amethyst/src/main/res/values-sl-rSI/strings.xml b/amethyst/src/main/res/values-sl-rSI/strings.xml index da5af6739..758e15e19 100644 --- a/amethyst/src/main/res/values-sl-rSI/strings.xml +++ b/amethyst/src/main/res/values-sl-rSI/strings.xml @@ -72,6 +72,8 @@ Za podpisovanje se je potrebno prijaviti s privatnim ključem Podpisnik ni odobril dešifriranja, ki je potrebno za to operacijo. V aplikaciji za podpisovanje aktivirajte NIP-44 možnost dešifriranja in poskusite znova Ne najdem podpisnika Ali je bila aplikacija za podpisovanje odstranjena? Preverite, ali je aplikacija za podpisovanje nameščena in ima dostop do tega računa. Odjavite se in ponovno prijavite, če se je aplikacija morda spremenila. + Napačno delovanje podpisnika + Zunanji podpisnik je vrnil neobičajen odgovor. Morda gre za napako v aplikaciji Amethyst ali v podpisniku. Zapi Števec vpogledov Pošlji naprej @@ -118,7 +120,7 @@ Za podpisovanje se je potrebno prijaviti s privatnim ključem Nov kanal Ime kanala Moja vrhunska skupina - Url slike + URL slike URL slike (Neobvezno) Opis Ne najdem opisa @@ -193,7 +195,7 @@ Za podpisovanje se je potrebno prijaviti s privatnim ključem Anonimiziraj Prilagodi višino tona svojega glasu: Opomba: osnovne spremembe višine tona lahko poslušalci potencialno razveljavijo. Uporabnik nima nastavljenega \"lightning\" naslova za sprejem satoshi-jev - "odgovori tukaj.. " + "odgovori tukaj… " Kopira ID zapiska v odložišče za deljenje v Nostr Kopiraj ID kanala (zapisek) v odložišče Uredi metapodatke kanala @@ -301,6 +303,7 @@ Za podpisovanje se je potrebno prijaviti s privatnim ključem Nostr naslov t. i. Nip-05 nikoli zdaj + sekunde h m d @@ -387,7 +390,7 @@ Za podpisovanje se je potrebno prijaviti s privatnim ključem Ročno razdeli zape Zaznamki Privzeti zaznamki - Tvoje privzeti zaznamki, ki jih podpira veliko Nostr odjemalcev. + Tvoje privzeti zaznamki, ki jih podpira veliko Nostr odjemalcev Osnutki Privatni zaznamki Javni zaznamki @@ -441,7 +444,7 @@ Za podpisovanje se je potrebno prijaviti s privatnim ključem Napredno: ročni vnos podatkov o povezavi Zneski za hitre zape Prikaže se ob pritisku na gumb za zappe. Tapnite znesek, da ga odstranite. Če pustite prazno, se bo ob vsakem zappu odprlo okno za vnos poljubnega zneska. - Zap zasebnost + Zasebnost zapov Določa, kako je prikazana vaša identiteta, ko pošljete zap. Poveži denarnico Pogled v vsebino releja @@ -458,6 +461,8 @@ Za podpisovanje se je potrebno prijaviti s privatnim ključem Zap maksimum Soglasje (0–100)% + Ena izbira + Več izbire Datum in čas konca glasovanja Anketa se zaključi %1$s Zapri po @@ -497,6 +502,9 @@ Za podpisovanje se je potrebno prijaviti s privatnim ključem Prejemnik in javnost ne vejo kdo je poslal plačilo Ni-Zap Brez sledi v Nostr, samo v Lightning + Anonimno + Objavite z novo začasno identiteto. Vaš račun ne bo povezan s tem odgovorom. + Ta odgovor bo objavljen z novo anonimno identiteto Datotečni strežnik Izberi strežnik za nalaganje te datoteke LnNaslov ali @Uporabnik @@ -753,7 +761,7 @@ Za podpisovanje se je potrebno prijaviti s privatnim ključem Nadzor dostopa Minimalen PoW Auth - Potrebna avtentikacija + Potrebna je avtentikacija Plačilo Potrebno je plačilo Največja dolžina sporočila @@ -826,7 +834,7 @@ Za podpisovanje se je potrebno prijaviti s privatnim ključem Slog galerije profila Izberi slog galerije Naloži sliko - Pošiljatelji nezaželjenih vsebin + Pošiljatelji nezaželenih vsebin Utišano. Klikni za vklop zvoka Zvok je prižgan. Klikni da ga utišaš Skoči nazaj za %d sekund @@ -1260,6 +1268,7 @@ Za podpisovanje se je potrebno prijaviti s privatnim ključem OTS: %1$s Dokaz časovnega žiga Obstaja dokaz, da je bil ta zapisek podpisan pred %1$s. Dokaz je bil ožigosan v Bitcoin verigi blokov na ta datum in čas. + Uredi članek Uredi objavo Prošnja za izboljšavo objave Povzetek sprememb @@ -1339,6 +1348,7 @@ Za podpisovanje se je potrebno prijaviti s privatnim ključem Ključniki Skupnosti Seznami + Releji Odjava ob zaklepu naprave Zasebno sporočilo Javno sporočilo @@ -1575,6 +1585,7 @@ Za podpisovanje se je potrebno prijaviti s privatnim ključem Kratki videoposnetki Zvočno sporočilo Zvočni odgovori + Spletni zaznamek Wiki Zagotovite si odličen vir objav tako, da sledite istim ljudem kot nekdo, ki mu zaupate. Uvozi seznam sledenih @@ -1690,4 +1701,20 @@ Za podpisovanje se je potrebno prijaviti s privatnim ključem Vse do zdaj Zadnja sinhronizacija: %1$s Od zadnje sinhronizacije + Spletni zaznamki + Seznam spletnih zaznamkov je prazen. Dodajte ga s pritiskom na +. + Dodaj spletni zaznamek + Uredi spletni zaznamek + URL + https://primer.si + Naslov + Naslov zaznamka + Opis + Kratek opis + Oznake (Ločite z vejicami) + nostr, tehnika , blog + Shrani + Izbriši + Izbriši ta spletni zaznamek + Odpri URL diff --git a/amethyst/src/main/res/values-sv-rSE/strings.xml b/amethyst/src/main/res/values-sv-rSE/strings.xml index 777f8fa18..640a888bc 100644 --- a/amethyst/src/main/res/values-sv-rSE/strings.xml +++ b/amethyst/src/main/res/values-sv-rSE/strings.xml @@ -61,6 +61,8 @@ Signatären har inte godkänt den dekryptering som krävs. Aktivera NIP-44-dekryptering i din signeringsapp och försök igen Signatör saknas Har signeringsappen avinstallerats? Kontrollera om den är installerad och innehåller det här kontot. Logga ut och in igen om den har ändrats. + Signatären betedde sig oväntat + Extern signatär returnerade data som är ovanliga för begäran. Det kan finnas en bugg i antingen Amethyst eller signatären. Zaps Antal visningar Boosta @@ -446,6 +448,8 @@ Maximal Zap Konsensus (0–100)% + Enkelt val + Flerval Stängningsdatum och tid Omröstningen stänger om %1$s Avsluta efter @@ -485,6 +489,9 @@ Mottagaren och allmänheten vet inte vem som skickade betalningen Ingen Zap Inga spår i Nostr, bara i Lightning + Anonym + Publicera som en ny engångsidentitet. Ditt konto kommer inte att kopplas till detta svar. + Detta svar kommer att publiceras från en ny anonym identitet Fil Server Välj en server att ladda upp denna fil till LnAdress eller @Användare @@ -1323,6 +1330,7 @@ Hashtaggar Gemenskaper Listor + Reläer Logga ut när enheten låses Privat meddelande Offentligt meddelande @@ -1559,6 +1567,7 @@ Shorts Röstmeddelande Röstsvar + Webbbokmärke Wiki Kom igång med ett bra flöde genom att följa samma personer som någon du litar på. Importera följarlista @@ -1674,4 +1683,17 @@ All tid Senaste synkronisering: %1$s Sedan senaste synkronisering + Webbbokmärken + Inga webbbokmärken ännu. Tryck på + för att lägga till. + Lägg till webbbokmärke + Redigera webbbokmärke + Titel + Bokmärkets titel + Beskrivning + En kort beskrivning + Taggar (kommaseparerade) + Spara + Radera + Radera detta webbbokmärke? + Öppna URL diff --git a/amethyst/src/main/res/values-zh-rCN/strings.xml b/amethyst/src/main/res/values-zh-rCN/strings.xml index 38d929d10..a334d9e2a 100644 --- a/amethyst/src/main/res/values-zh-rCN/strings.xml +++ b/amethyst/src/main/res/values-zh-rCN/strings.xml @@ -28,8 +28,8 @@ 中继器图标 未知作者 复制文本 - 复制作者@npub - 复制笔记ID + 复制作者公钥 ID + 复制笔记 ID 广播 获取公开时间戳 OpenTimestamps:待确认 @@ -61,6 +61,8 @@ 签名器没有授权解密操作,请在签名器中授予 NIP-44 解密权限并重试。 未找到签名器 签名器被卸载?请检查是否已经安装了签名器以及其中是否存在该账户。变更签名器需要注销后重新登录。 + 签名器行为异常 + 外部签名器对该请求返回了不正常的载荷。这可能是 Amethyst 或签名器上的错误。 打闪 浏览次数 提升 @@ -70,7 +72,7 @@ 原版 引用 复刻 - 提议编辑 + 提出修改建议 新的聪金额 添加 "回复 " @@ -114,7 +116,7 @@ "关于我们.. " 你在想什么? 写一条消息… - 发布 + 贴文 保存 创建 重命名 @@ -183,7 +185,7 @@ 更改您的音高。注意:听众如果下定决定也许能逆转基础音高更改。 用户尚未设置闪电地址以接收聪 "🔏在此回复… " - 复制笔记ID到剪贴板,供分享 + 复制笔记ID到剪贴板以便于在 Nostr 中分享 复制频道ID(笔记)到剪贴板 修改频道元数据 加入 @@ -196,7 +198,7 @@ Mod 队列 笔记 回复 - 你的 + 互动 相册 "关注" "举报" @@ -326,7 +328,7 @@ 你收到了新的徽章奖励 徽章奖励授予 文本已复制到剪贴板 - 复制作者的 @npub 到剪贴板 + 已复制作者公钥 ID 到剪贴板 已复制笔记ID (@note1) 到剪贴板 选择文本 "<无法解密私密消息>\n\n;你被 %1$s 和 %2$s 之间的私人/加密会话引用。" @@ -597,7 +599,7 @@ Orbot Socks 端口 启动 Tor - 使用内置的版本或者 Orbot + 使用内置 Tor 或者 Orbot Tor 和隐私预设 快速修改下方的设置 Onion 链接或中继地址 @@ -1131,7 +1133,7 @@ 调整顺序 回复 回复此笔记 - Boost + 提升 转发或引用此笔记 点赞 使用表情符号回应笔记 @@ -1334,6 +1336,7 @@ 话题标签 社区 列表 + 中继 当设备锁定时注销 私信 公开消息 @@ -1570,6 +1573,7 @@ 短篇 语音消息 语音回复 + 网络书签 维基 关注你信任的人所关注的人来开启优质的源。 导入关注列表 @@ -1639,7 +1643,7 @@ 私信 个人资料 中继设置 - 上次看见在 %1$s 秒前 + %1$s 前活跃 <%1$s 连接中 下载中 @@ -1685,4 +1689,20 @@ 全部时间 上次同步: %1$s 自上次同步后 + 网络书签 + 暂无网络书签。点击 + 添加一个。 + 添加网络书签 + 编辑网络书签 + URL + https://example.com + 标题 + 书签标题 + 描述 + 一段简短描述 + 标签(以逗号分隔) + nostr, tech, blog + 保存 + 删除 + 删除该网络书签? + 打开 URL diff --git a/amethyst/src/main/res/values/strings.xml b/amethyst/src/main/res/values/strings.xml index 03022e303..7c4e50619 100644 --- a/amethyst/src/main/res/values/strings.xml +++ b/amethyst/src/main/res/values/strings.xml @@ -1827,7 +1827,7 @@ Select Users to Follow Profile to import from search, npub1…, alice@example.com - Supports npub, nprofile, NIP-05, hex, and namecoin (.bit, d/, id/) + Supports npub, nprofile, NIP-05, hex, and Namecoin (.bit) Look Up Follow List Tip %1$d accounts found @@ -1849,6 +1849,21 @@ Select All %1$d%% uptime Namecoin Settings + Test Connection + Testing servers… + Connected + Failed + Test Results + Diagnostics + Last test + Device Info + TLS Info + No test run yet + %dms + Trust Server Certificate? + The server %1$s presented a certificate not yet in your trust store. Verify the fingerprint below matches what the server operator published, then choose whether to trust it for future connections. + Trust + Reject Relay Sync Relay Sync Re-publish your events across all known relays to keep your outbox, inbox, and DM relays up to date. Requires Wi-Fi — this may use a lot of data. diff --git a/amethyst/src/test/java/com/vitorpamplona/amethyst/service/namecoin/NamecoinSettingsTest.kt b/amethyst/src/test/java/com/vitorpamplona/amethyst/service/namecoin/NamecoinSettingsTest.kt index 4eb495af6..661caca6e 100644 --- a/amethyst/src/test/java/com/vitorpamplona/amethyst/service/namecoin/NamecoinSettingsTest.kt +++ b/amethyst/src/test/java/com/vitorpamplona/amethyst/service/namecoin/NamecoinSettingsTest.kt @@ -56,7 +56,7 @@ class NamecoinSettingsTest { assertEquals("abc123def.onion", s!!.host) assertEquals(50001, s.port) assertFalse(s.useSsl) - assertTrue(s.trustAllCerts) + assertTrue(s.usePinnedTrustStore) } @Test @@ -131,7 +131,7 @@ class NamecoinSettingsTest { assertTrue(servers[0].useSsl) assertEquals("server2.onion", servers[1].host) assertFalse(servers[1].useSsl) - assertTrue(servers[1].trustAllCerts) + assertTrue(servers[1].usePinnedTrustStore) } @Test diff --git a/quartz/src/commonMain/kotlin/com/vitorpamplona/quartz/nip05DnsIdentifiers/namecoin/ElectrumXServer.kt b/quartz/src/commonMain/kotlin/com/vitorpamplona/quartz/nip05DnsIdentifiers/namecoin/ElectrumXServer.kt index f31edfe7d..4c6c96937 100644 --- a/quartz/src/commonMain/kotlin/com/vitorpamplona/quartz/nip05DnsIdentifiers/namecoin/ElectrumXServer.kt +++ b/quartz/src/commonMain/kotlin/com/vitorpamplona/quartz/nip05DnsIdentifiers/namecoin/ElectrumXServer.kt @@ -44,8 +44,14 @@ data class ElectrumxServer( val host: String, val port: Int, val useSsl: Boolean = true, - /** If true, accept any certificate (self-signed, expired, etc.) */ - val trustAllCerts: Boolean = false, + /** + * If true, use the pinned trust store (hardcoded + TOFU-pinned certs + * plus system CAs) instead of the default system-only trust store. + * + * Required for ElectrumX servers that use self-signed certificates, + * which is the norm for the Namecoin ElectrumX ecosystem. + */ + val usePinnedTrustStore: Boolean = false, ) /** @@ -72,12 +78,27 @@ sealed class NamecoinLookupException( ) : NamecoinLookupException("All ElectrumX servers unreachable", lastError) } +/** + * Result of testing connectivity to a single ElectrumX server. + */ +data class ServerTestResult( + val server: ElectrumxServer, + val success: Boolean, + val responseTimeMs: Long, + val error: String? = null, + val tlsVersion: String? = null, + /** PEM-encoded server certificate, captured during test for TOFU pinning. */ + val serverCertPem: String? = null, + /** SHA-256 fingerprint of the server certificate. */ + val certFingerprint: String? = null, +) + /** Well-known public Namecoin ElectrumX servers (clearnet). */ val DEFAULT_ELECTRUMX_SERVERS = listOf( - ElectrumxServer("electrumx.testls.space", 50002, useSsl = true, trustAllCerts = true), - ElectrumxServer("nmc2.bitcoins.sk", 57002, useSsl = true, trustAllCerts = true), - ElectrumxServer("46.229.238.187", 57002, useSsl = true, trustAllCerts = true), + ElectrumxServer("electrumx.testls.space", 50002, useSsl = true, usePinnedTrustStore = true), + ElectrumxServer("nmc2.bitcoins.sk", 57002, useSsl = true, usePinnedTrustStore = true), + ElectrumxServer("46.229.238.187", 57002, useSsl = true, usePinnedTrustStore = true), ) /** Tor-preferred server list: onion primary, clearnet fallback. */ @@ -87,8 +108,8 @@ val TOR_ELECTRUMX_SERVERS = "i665jpwsq46zlsdbnj4axgzd3s56uzey5uhotsnxzsknzbn36jaddsid.onion", 50002, useSsl = true, - trustAllCerts = true, + usePinnedTrustStore = true, ), - ElectrumxServer("electrumx.testls.space", 50002, useSsl = true, trustAllCerts = true), - ElectrumxServer("nmc2.bitcoins.sk", 57002, useSsl = true, trustAllCerts = true), + ElectrumxServer("electrumx.testls.space", 50002, useSsl = true, usePinnedTrustStore = true), + ElectrumxServer("nmc2.bitcoins.sk", 57002, useSsl = true, usePinnedTrustStore = true), ) diff --git a/quartz/src/jvmAndroid/kotlin/com/vitorpamplona/quartz/nip05DnsIdentifiers/namecoin/ElectrumXClient.kt b/quartz/src/jvmAndroid/kotlin/com/vitorpamplona/quartz/nip05DnsIdentifiers/namecoin/ElectrumXClient.kt index b0ba1d6b7..f8e0e3152 100644 --- a/quartz/src/jvmAndroid/kotlin/com/vitorpamplona/quartz/nip05DnsIdentifiers/namecoin/ElectrumXClient.kt +++ b/quartz/src/jvmAndroid/kotlin/com/vitorpamplona/quartz/nip05DnsIdentifiers/namecoin/ElectrumXClient.kt @@ -38,19 +38,22 @@ import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.put import java.io.BufferedReader +import java.io.ByteArrayInputStream import java.io.InputStreamReader import java.io.PrintWriter import java.net.InetSocketAddress import java.net.Socket +import java.security.KeyStore import java.security.MessageDigest import java.security.SecureRandom -import java.security.cert.X509Certificate +import java.security.cert.CertificateFactory import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicInteger import javax.net.SocketFactory import javax.net.ssl.SSLContext import javax.net.ssl.SSLSocketFactory import javax.net.ssl.TrustManager +import javax.net.ssl.TrustManagerFactory import javax.net.ssl.X509TrustManager /** @@ -87,25 +90,6 @@ class ElectrumXClient( private val requestId = AtomicInteger(0) private val serverMutexes = ConcurrentHashMap() - companion object { - private const val PROTOCOL_VERSION = "1.4" - - /** - * Namecoin names expire this many blocks after their last update. - * From chainparams.cpp: consensus.nNameExpirationDepth = 36000 - * (~250 days at ~10 min/block). - */ - const val NAME_EXPIRE_DEPTH = 36_000 - - // Namecoin script opcodes - private const val OP_NAME_UPDATE: Byte = 0x53 // OP_3 repurposed by Namecoin - private const val OP_2DROP: Byte = 0x6d - private const val OP_DROP: Byte = 0x75 - private const val OP_RETURN: Byte = 0x6a - private const val OP_PUSHDATA1: Byte = 0x4c - private const val OP_PUSHDATA2: Byte = 0x4d - } - /** * Perform a name_show lookup against the given ElectrumX server. * @@ -167,6 +151,162 @@ class ElectrumXClient( throw NamecoinLookupException.ServersUnreachable(lastError) } + /** + * Test connectivity to a single ElectrumX server. + * + * Connects, negotiates protocol version, and optionally resolves a test + * name. Returns detailed results including response time, TLS version, + * and human-readable error messages. + * + * @param server The server to test + * @param testName Optional name to resolve (e.g. "d/testls") + * @return [ServerTestResult] with success/failure details + */ + suspend fun testServer( + server: ElectrumxServer, + testName: String? = "d/testls", + ): ServerTestResult = + withContext(Dispatchers.IO) { + val startTime = System.currentTimeMillis() + try { + val socket = createSocket(server) + socket.soTimeout = readTimeoutMs.toInt() + + var tlsVersion: String? = null + var serverCertPem: String? = null + var certFingerprint: String? = null + + if (socket is javax.net.ssl.SSLSocket) { + tlsVersion = socket.session.protocol + // Capture the server's leaf certificate for TOFU pinning + try { + val peerCerts = socket.session.peerCertificates + if (peerCerts.isNotEmpty() && peerCerts[0] is java.security.cert.X509Certificate) { + val x509 = peerCerts[0] as java.security.cert.X509Certificate + // PEM encode + val encoded = + java.util.Base64 + .getMimeEncoder(76, "\n".toByteArray()) + .encodeToString(x509.encoded) + serverCertPem = "-----BEGIN CERTIFICATE-----\n$encoded-----END CERTIFICATE-----" + // SHA-256 fingerprint + val digest = MessageDigest.getInstance("SHA-256").digest(x509.encoded) + certFingerprint = digest.joinToString(":") { "%02X".format(it) } + } + } catch (_: Exception) { + // Non-fatal — cert capture is best-effort + } + } + + val writer = PrintWriter(socket.getOutputStream(), true) + val reader = BufferedReader(InputStreamReader(socket.getInputStream())) + + try { + // Negotiate protocol version + val versionReq = + buildRpcRequest( + "server.version", + listOf("AmethystNMC/0.1", PROTOCOL_VERSION), + ) + writer.println(versionReq) + val versionResponse = + reader.readLine() + ?: return@withContext ServerTestResult( + server = server, + success = false, + responseTimeMs = System.currentTimeMillis() - startTime, + error = "Server returned empty response", + tlsVersion = tlsVersion, + ) + + // If a test name is provided, try to resolve it + if (testName != null) { + val nameScript = + buildNameIndexScript(testName.toByteArray(Charsets.US_ASCII)) + val scriptHash = electrumScriptHash(nameScript) + val historyReq = + buildRpcRequest( + "blockchain.scripthash.get_history", + listOf(scriptHash), + ) + writer.println(historyReq) + reader.readLine() // consume response + } + + val elapsed = System.currentTimeMillis() - startTime + ServerTestResult( + server = server, + success = true, + responseTimeMs = elapsed, + tlsVersion = tlsVersion, + serverCertPem = serverCertPem, + certFingerprint = certFingerprint, + ) + } finally { + runCatching { writer.close() } + runCatching { reader.close() } + runCatching { socket.close() } + } + } catch (e: java.net.ConnectException) { + ServerTestResult( + server = server, + success = false, + responseTimeMs = System.currentTimeMillis() - startTime, + error = "Connection refused", + ) + } catch (e: java.net.SocketTimeoutException) { + ServerTestResult( + server = server, + success = false, + responseTimeMs = System.currentTimeMillis() - startTime, + error = "Connection timed out after ${connectTimeoutMs / 1000}s", + ) + } catch (e: java.net.UnknownHostException) { + ServerTestResult( + server = server, + success = false, + responseTimeMs = System.currentTimeMillis() - startTime, + error = "Server unreachable (DNS resolution failed)", + ) + } catch (e: javax.net.ssl.SSLHandshakeException) { + val detail = + if (e.message?.contains("self-signed", ignoreCase = true) == true || + e.message?.contains("anchor", ignoreCase = true) == true + ) { + "TLS handshake failed (self-signed certificate rejected)" + } else { + "TLS handshake failed: ${e.message?.take(100) ?: "unknown error"}" + } + ServerTestResult( + server = server, + success = false, + responseTimeMs = System.currentTimeMillis() - startTime, + error = detail, + ) + } catch (e: javax.net.ssl.SSLException) { + ServerTestResult( + server = server, + success = false, + responseTimeMs = System.currentTimeMillis() - startTime, + error = "TLS error: ${e.message?.take(100) ?: "unknown"}", + ) + } catch (e: java.io.IOException) { + ServerTestResult( + server = server, + success = false, + responseTimeMs = System.currentTimeMillis() - startTime, + error = "I/O error: ${e.message?.take(100) ?: "unknown"}", + ) + } catch (e: Exception) { + ServerTestResult( + server = server, + success = false, + responseTimeMs = System.currentTimeMillis() - startTime, + error = e.message?.take(150) ?: "Unknown error", + ) + } + } + // ── internals ────────────────────────────────────────────────────── private fun connectAndQuery( @@ -461,41 +601,298 @@ class ElectrumXClient( if (!server.useSsl) return baseSocket // Upgrade to TLS over the already-connected (possibly proxied) socket. + // When usePinnedTrustStore is set, we use a pinned trust store that + // contains the known ElectrumX server certs plus system CAs. This is + // required because Samsung One UI 7 (Android 16) and GrapheneOS + // reject connections that use a no-op "trust-all" X509TrustManager. val sslFactory = - if (server.trustAllCerts) { - trustAllSslFactory() + if (server.host.endsWith(".onion")) { + // .onion addresses: prefer the pinned factory (the .onion server's + // cert is already in PINNED_ELECTRUMX_CERTS). Fall back to trust-all + // only if the pinned handshake fails — this keeps compatibility with + // .onion servers whose certs aren't pinned yet, while avoiding a + // blanket trust-all that hardened TLS stacks (GrapheneOS, Samsung + // Knox) may reject at the Conscrypt/BoringSSL layer. + cachedPinnedSslFactory() + } else if (server.usePinnedTrustStore) { + cachedPinnedSslFactory() } else { SSLSocketFactory.getDefault() as SSLSocketFactory } - return sslFactory.createSocket(baseSocket, server.host, server.port, true) + val sslSocket: Socket + try { + sslSocket = sslFactory.createSocket(baseSocket, server.host, server.port, true) + } catch (e: javax.net.ssl.SSLHandshakeException) { + if (server.host.endsWith(".onion")) { + // Pinned factory failed for .onion — fall back to trust-all. + // This is safe: Tor provides E2E authentication via the onion + // address, and the proxied socket bypasses Knox/GrapheneOS + // trust-all rejection in practice. + val fallbackSocket = onionSslFactory().createSocket(baseSocket, server.host, server.port, true) + if (fallbackSocket is javax.net.ssl.SSLSocket) { + val supported = fallbackSocket.supportedProtocols + val modern = supported.filter { it == "TLSv1.2" || it == "TLSv1.3" } + if (modern.isNotEmpty()) { + fallbackSocket.enabledProtocols = modern.toTypedArray() + } + } + return fallbackSocket + } + throw e + } + + // Enforce TLSv1.2+ — some OEM Conscrypt forks (Xiaomi MIUI, OnePlus ColorOS) + // may negotiate TLS 1.0/1.1 by default for raw socket upgrades. + if (sslSocket is javax.net.ssl.SSLSocket) { + val supported = sslSocket.supportedProtocols + val modern = supported.filter { it == "TLSv1.2" || it == "TLSv1.3" } + if (modern.isNotEmpty()) { + sslSocket.enabledProtocols = modern.toTypedArray() + } + } + + return sslSocket } /** - * Create an SSLSocketFactory that accepts any certificate. - * Used for servers with self-signed certificates. + * Fallback SSLSocketFactory for .onion addresses when the pinned + * factory fails (e.g. cert rotated, unknown .onion server). + * + * Only used as a last resort after cachedPinnedSslFactory() throws + * SSLHandshakeException. This is safe because: + * 1. The connection is already end-to-end encrypted by Tor. + * 2. The onion address IS the server's identity proof (public key hash). + * 3. Proxied sockets via Tor SOCKS typically bypass OEM trust-all + * rejection (Samsung Knox, GrapheneOS hardened Conscrypt). + * + * Note: GrapheneOS or future Android versions may reject trust-all + * TrustManagers even for proxied sockets. If this fallback stops + * working, the .onion server's cert should be added to + * PINNED_ELECTRUMX_CERTS (it's already there for the known server). */ - private fun trustAllSslFactory(): SSLSocketFactory { - val trustAllCerts = + private fun onionSslFactory(): SSLSocketFactory { + val trustAll = arrayOf( object : X509TrustManager { override fun checkClientTrusted( - chain: Array, + chain: Array, authType: String, ) {} override fun checkServerTrusted( - chain: Array, + chain: Array, authType: String, ) {} - override fun getAcceptedIssuers(): Array = arrayOf() + override fun getAcceptedIssuers(): Array = arrayOf() }, ) - val sslContext = SSLContext.getInstance("TLS") - sslContext.init(null, trustAllCerts, SecureRandom()) + val ctx = + try { + SSLContext.getInstance("TLSv1.2") + } catch (_: Exception) { + SSLContext.getInstance("TLS") + } + ctx.init(null, trustAll, SecureRandom()) + return ctx.socketFactory + } + + /** User-supplied PEM certificates for custom servers (TOFU-pinned). */ + private val dynamicCerts = mutableListOf() + + /** Lazy-cached SSLSocketFactory for pinned certs. Thread-safe via volatile + DCL. */ + @Volatile + private var pinnedFactory: SSLSocketFactory? = null + + private fun cachedPinnedSslFactory(): SSLSocketFactory { + pinnedFactory?.let { return it } + synchronized(this) { + pinnedFactory?.let { return it } + return buildPinnedSslFactory().also { pinnedFactory = it } + } + } + + /** + * Add a PEM-encoded certificate to the dynamic trust store. + * Typically called after the user confirms a cert fingerprint via + * the "Test Connection" flow in settings. + * + * Invalidates the cached factory so the next connection picks it up. + */ + fun addPinnedCert(pem: String) { + synchronized(this) { + dynamicCerts.add(pem) + pinnedFactory = null // force rebuild + } + } + + /** + * Replace all dynamic certs (e.g. loaded from preferences on startup). + */ + fun setDynamicCerts(pems: List) { + synchronized(this) { + dynamicCerts.clear() + dynamicCerts.addAll(pems) + pinnedFactory = null + } + } + + /** + * Build an SSLSocketFactory that trusts the pinned ElectrumX server + * certificates plus the system CA store. + * + * Previous versions used a "trust-all" TrustManager, but Samsung + * devices running One UI 7 (Android 16) silently reject connections + * that use a no-op X509TrustManager. Pinning the known self-signed + * certs avoids this while maintaining security. + * + * Also handles OEM-specific quirks: + * - Xiaomi MIUI/HyperOS: KeyStore.getDefaultType() may return unexpected + * types; we try the default first, then fall back to "PKCS12". + * - OnePlus ColorOS: some versions require explicit TLSv1.2 protocol. + * - All OEMs: SSLContext("TLSv1.2") is preferred over ("TLS") which may + * resolve to TLS 1.0 on older Conscrypt forks. + */ + private fun buildPinnedSslFactory(): SSLSocketFactory { + val ks = + try { + KeyStore.getInstance(KeyStore.getDefaultType()).apply { load(null, null) } + } catch (_: Exception) { + // Fallback for Xiaomi devices where getDefaultType() returns an unsupported type + KeyStore.getInstance("PKCS12").apply { load(null, null) } + } + + val cf = CertificateFactory.getInstance("X.509") + + // Load hardcoded + dynamic pinned certificates into the keystore + val allCerts = PINNED_ELECTRUMX_CERTS + dynamicCerts + for ((index, pem) in allCerts.withIndex()) { + try { + val cert = cf.generateCertificate(ByteArrayInputStream(pem.toByteArray(Charsets.US_ASCII))) + ks.setCertificateEntry("electrumx_$index", cert) + } catch (_: Exception) { + // Skip malformed certs — the remaining ones may still work + } + } + + // Also load system CA certificates so that servers with real certs work too + val systemTmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) + systemTmf.init(null as KeyStore?) // null = system default + val systemTm = systemTmf.trustManagers.filterIsInstance().firstOrNull() + if (systemTm != null) { + for ((index, issuer) in systemTm.acceptedIssuers.withIndex()) { + try { + ks.setCertificateEntry("system_$index", issuer) + } catch (_: Exception) { + // Some OEMs return certs that can't be re-inserted; skip + } + } + } + + val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) + tmf.init(ks) + + // Prefer TLSv1.2 explicitly — SSLContext.getInstance("TLS") can resolve + // to TLS 1.0 on some OEM Conscrypt forks (Xiaomi, OnePlus). + val sslContext = + try { + SSLContext.getInstance("TLSv1.2") + } catch (_: Exception) { + SSLContext.getInstance("TLS") + } + sslContext.init(null, tmf.trustManagers, SecureRandom()) return sslContext.socketFactory } + companion object { + private const val PROTOCOL_VERSION = "1.4" + + /** + * Namecoin names expire this many blocks after their last update. + * From chainparams.cpp: consensus.nNameExpirationDepth = 36000 + * (~250 days at ~10 min/block). + */ + const val NAME_EXPIRE_DEPTH = 36_000 + + // Namecoin script opcodes + private const val OP_NAME_UPDATE: Byte = 0x53 // OP_3 repurposed by Namecoin + private const val OP_2DROP: Byte = 0x6d + private const val OP_DROP: Byte = 0x75 + private const val OP_RETURN: Byte = 0x6a + private const val OP_PUSHDATA1: Byte = 0x4c + private const val OP_PUSHDATA2: Byte = 0x4d + + /** + * PEM-encoded certificates for the well-known Namecoin ElectrumX servers. + * + * These are self-signed certificates that cannot be verified by the + * system CA store. We pin them explicitly so that connections succeed + * on devices with strict TLS enforcement (e.g. Samsung One UI 7). + * + * To update: `echo | openssl s_client -connect HOST:PORT 2>/dev/null | openssl x509 -outform PEM` + * For .onion: `python3 -c "import socks,ssl,socket,base64; s=socks.socksocket(); s.set_proxy(socks.SOCKS5,'127.0.0.1',9050); s.connect(('HOST',PORT)); ctx=ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT); ctx.check_hostname=False; ctx.verify_mode=ssl.CERT_NONE; ss=ctx.wrap_socket(s); print(base64.encodebytes(ss.getpeercert(True)).decode())"` + */ + private val PINNED_ELECTRUMX_CERTS = + listOf( + // electrumx.testls.space:50002 — expires 2027-05-04 + // Also covers the .onion hidden service (same operator, same cert): + // i665jpwsq46zlsdbnj4axgzd3s56uzey5uhotsnxzsknzbn36jaddsid.onion:50002 + // SHA-256: 53:65:D5:BB:26:19:F5:40:1C:D8:8E:FC:AF:FB:A5:B2:A0:EA:7A:99:2D:F7:0F:05:7E:9B:CD:50:36:C7:79:9C + """ +-----BEGIN CERTIFICATE----- +MIIDwzCCAqsCFGGKT5mjh7oN98aNyjOCiqafL8VyMA0GCSqGSIb3DQEBCwUAMIGd +MQswCQYDVQQGEwJVUzEQMA4GA1UECAwHQ2hpY2FnbzEQMA4GA1UEBwwHQ2hpY2Fn +bzESMBAGA1UECgwJSW50ZXJuZXRzMQ8wDQYDVQQLDAZJbnRlcncxHjAcBgNVBAMM +FWVsZWN0cnVtLnRlc3Rscy5zcGFjZTElMCMGCSqGSIb3DQEJARYWbWpfZ2lsbF84 +OUBob3RtYWlsLmNvbTAeFw0yMjA1MDUwNjIzNDFaFw0yNzA1MDQwNjIzNDFaMIGd +MQswCQYDVQQGEwJVUzEQMA4GA1UECAwHQ2hpY2FnbzEQMA4GA1UEBwwHQ2hpY2Fn +bzESMBAGA1UECgwJSW50ZXJuZXRzMQ8wDQYDVQQLDAZJbnRlcncxHjAcBgNVBAMM +FWVsZWN0cnVtLnRlc3Rscy5zcGFjZTElMCMGCSqGSIb3DQEJARYWbWpfZ2lsbF84 +OUBob3RtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAO4H ++PKCdiiz3jNOA77aAmS2YaU7eOQ8ZGliEVr/PlLcgF5gmthb2DI6iK4KhC1ad34G +1n9IhkXPhkVJ94i8wB3uoTBlA7mI5h59m01yhzSkJAoYoU/i6DM9ipbakqWFCTEp +P+yE216NTU5MbYwThZdRSAIIABe9RyIliMSidyrwHvKBLfnJPFScghW6rhBWN7PG +PA8k0MFGzf+HXbpnV/jAvz08ZC34qiBIjkJrTgh49JweyoZKdppyJcH4UbkslJ2t +YUJR3oURBvrPj+D7TwLVRbX36ul7r4+dP3IjgmljsSAHDK4N/PfWrCBdlj9Pc1Cp +yX+ZDh8X2NrL4ukHoVMCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAeVj6VZNmY/Vb +nhzrC7xBSHqVWQ1wkLOClLsdvgKP8cFFJuUoCMQU5bPMi7nWnkfvvsIKH4Eibk5K +fqiA9jVsY0FHvQ8gP3KMk1LVuUf/sTcRe5itp3guBOSk/zXZUD5tUz/oRk3k+rdc +MsInqhomjNy/dqYmD6Wm4DNPjZh6fWy+AVQKVNOI2t4koaVdpoi8Uv8h4gFGPbdI +sVmtoGiIGkKNIWum+6mnF6PfynNrLk+ztH4TrdacVNeoJUPYEAxOuesWXFy3H4r+ +HKBqA4xAzyjgKLPqoWnjSu7gxj1GIjBhnDxkM6wUOnDq8A0EqxR+A17OcXW9sZ2O +2ZIVwmtnyA== +-----END CERTIFICATE----- + """.trimIndent(), + // nmc2.bitcoins.sk:57002 / 46.229.238.187:57002 — expires 2030-10-22 + """ +-----BEGIN CERTIFICATE----- +MIID+TCCAuGgAwIBAgIUdmJGukmfPvqmAYpTfuGcjRoYHJ8wDQYJKoZIhvcNAQEL +BQAwgYsxCzAJBgNVBAYTAlNLMREwDwYDVQQIDAhTbG92YWtpYTETMBEGA1UEBwwK +QnJhdGlzbGF2YTEUMBIGA1UECgwLYml0Y29pbnMuc2sxGTAXBgNVBAMMEG5tYzIu +Yml0Y29pbnMuc2sxIzAhBgkqhkiG9w0BCQEWFGRlYWZib3lAY2ljb2xpbmEub3Jn +MB4XDTIwMTAyNDE5MjQzOVoXDTMwMTAyMjE5MjQzOVowgYsxCzAJBgNVBAYTAlNL +MREwDwYDVQQIDAhTbG92YWtpYTETMBEGA1UEBwwKQnJhdGlzbGF2YTEUMBIGA1UE +CgwLYml0Y29pbnMuc2sxGTAXBgNVBAMMEG5tYzIuYml0Y29pbnMuc2sxIzAhBgkq +hkiG9w0BCQEWFGRlYWZib3lAY2ljb2xpbmEub3JnMIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEAzBUkZNDfaz7kc28l5tDKohJjekWmz1ynzfGx3ZLsqOZE +c+kNfcMaWU+zT/j0mV6pX6KSH7G9pPAku+8PRdKRq+d63wiJDEjGSaFztQWKW6L1 +vTxgCK5gu+Eir3BkTagJObsrLKS+T6qH610/3+btGgoR3lunB5TzCgB/9oQanjDW +zjg2CwmxgR5Iw1Eqfenx7zkSK33FSXSF2SvbUs1Atj2oPU4DLivyrx0RaUmaPemn +cmcpnax+py4pQeB6dJWU1INhzXt3hTJRyoqsSGY3vCECIKIBIkh8GsYjAX4z+Y9y +6pJx0da2b88qPWdsoxaIMvrQiuWknDrSJwAyw2Yd8QIDAQABo1MwUTAdBgNVHQ4E +FgQUT2J83B2/9jxGGdFeWrxMohTzHNwwHwYDVR0jBBgwFoAUT2J83B2/9jxGGdFe +WrxMohTzHNwwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAsbxX +wN8tZaXOybImMZCQS7zfxmKl2IAcqu+R01KPfnIfrFqXPsGDDl3rYLkwh1O4/hYQ +NKNW9KTxoJxuBmAkm7EXQQh1XUUzajdEDqDBVRyvR0Z2MdMYnMSAiiMXMl2wUZnc +QXYftBo0HbtfsaJjImQdDjmlmRPSzE/RW6iUe+1cesKBC7e8nVf69Yu/fxO4m083 +VWwAstlWJfk1GyU7jzVc8svealg/oIiDoOMe6CFSLx1BDv2FeHSpRdqd3fn+AC73 +bK2N2smrHUOQnFijuiFw3WOrjERi0eMhjVNfVu9W9ZYa/Wd6SdIzV55LbG+NpmSf +5W7ix41hRvdT6cTAJA== +-----END CERTIFICATE----- + """.trimIndent(), + ) + } + private fun buildRpcRequest( method: String, params: List,