diff --git a/common/src/main/res/values-ku/strings.xml b/common/src/main/res/values-ku/strings.xml index 29dee488..eec3c75d 100644 --- a/common/src/main/res/values-ku/strings.xml +++ b/common/src/main/res/values-ku/strings.xml @@ -2129,4 +2129,47 @@ %d Sepan %d Sepan + Navê .kurd + Bi zincîrê tê çareserkirin · ji motora lêgerînê re nayê şandin + Fermî + Tomarkirî + Nehat piştrastkirin + Ev malper nayê vekirin + Navên fermî tenê piştî ku bi zincîrê hatin piştrastkirin vedibin. Niha girêdana bi zincîrê re çênebû. + Nehat piştrastkirin + Ev nav bi zincîrê nehat kontrolkirin. Dibe ku malper ne ya xwediyê navî be. Li vir agahiyên xwe yên taybet nenivîse û tiştekî îmze neke. + Vegere + Dîsa jî veke + Navekî wiha tune ye + %s ne tomarkirî ye, an jî dema wê qediyaye. + Li ser vî navî malper tune + Nav tomarkirî ye, lê xwediyê wê malperek ku cîzdan dikare veke belav nekiriye. + Nehat barkirin + Ne zincîr ne jî neynik bi naverokeke ku bê piştrastkirin bersiv dan. + Fermî · navê dewletê + Li zincîrê tomarkirî ye + Bê piştrastkirin hate vekirin + Ji aliyê Meclîsê ve hatiye dayîn. Naveroka wê tenê piştî demeke li bendê diguhere; di wê demê de Meclîs dikare guhertinê rawestîne. + Ev nav hatiye kirîn. Naverok bi zincîrê hate piştrastkirin, lê kê ew malper çêkiriye nehat piştrastkirin. + Te hilbijart ku vî navî vekî, her çend bi zincîrê nehat kontrolkirin. Tiştê ku nîşan dide li ser gotina du girêkan e, ne li ser delîlekê. + Piştrastkirin + Bi zincîrê · blok #%s + Bi zincîrê + Du girêk li hev kirin, delîl tune + Xwedî + Saziya dewletê (multisig) + Naverok + Daneyên vê malperê jê bibe + Ev nav dişibe navekî fermî + Te nivîsî + Navê fermî + Malperên sexte navên nêzîkî navên fermî bi kar tînin da ku te bixapînin. + Biçe %s + Dîsa jî %s veke + Fermî + Kirî · ne fermî + Nehat piştrastkirin + Navê tevahî kontrol bike. Ev nav ji aliyê dewletê ve nehatiye dayîn. + Ev nav bi zincîrê nehat kontrolkirin. Tenê îmze bike heke tu bawer î ku ev malpera kê ye. + Guhertoyeke nûtir nehat dîtin — guhertoya li zincîrê tê nîşandan diff --git a/common/src/main/res/values-tr/strings.xml b/common/src/main/res/values-tr/strings.xml index a9199f3d..dc4b13b7 100644 --- a/common/src/main/res/values-tr/strings.xml +++ b/common/src/main/res/values-tr/strings.xml @@ -2126,4 +2126,47 @@ Referral kısmına bu adresi yapıştır: Müzik Rewshenbir Davet + .kurd adı + Zincirden çözülür · arama motoruna gönderilmez + Resmî + Kayıtlı + Doğrulanmadı + Bu site açılamaz + Resmî adlar yalnızca zincirde doğrulandıktan sonra açılır. Şu an zincire bağlanılamadı. + Doğrulanamadı + Bu ad zincirde denetlenemedi. Site, adın sahibine ait olmayabilir. Burada özel bilgilerini girme ve hiçbir şey imzalama. + Geri dön + Yine de aç + Böyle bir ad yok + %s kayıtlı değil ya da kaydının süresi doldu. + Bu adda site yok + Ad kayıtlı, ama sahibi cüzdanın açabileceği bir site yayımlamamış. + Yüklenemedi + Ne zincir ne de aynalar doğrulanabilir bir içerikle yanıt verdi. + Resmî · devlet adı + Zincirde kayıtlı + Doğrulanmadan açıldı + Meclis tarafından verildi. İçeriği yalnızca bir bekleme süresinden sonra değişir; bu sürede Meclis değişikliği durdurabilir. + Bu ad satın alındı. İçerik zincirde doğrulandı, ama siteyi kimin yaptığı doğrulanmadı. + Zincirde denetlenemese de bu adı açmayı seçtin. Gösterdiği yer bir kanıta değil, iki düğümün sözüne dayanıyor. + Doğrulama + Zincirde · blok #%s + Zincirde + İki düğüm uyuştu, kanıt yok + Sahip + Devlet kurumu (çoklu imza) + İçerik + Bu sitenin verilerini sil + Bu ad resmî bir ada benziyor + Yazdığın + Resmî ad + Sahte siteler seni kandırmak için resmî adlara yakın adlar kullanır. + %s adresine git + Yine de %s adresini aç + Resmî + Satın alınmış · resmî değil + Doğrulanmadı + Adın tamamını kontrol et. Bu ad devlet tarafından verilmedi. + Bu ad zincirde denetlenemedi. Yalnızca sitenin kime ait olduğundan eminsen imzala. + Daha yeni sürüm bulunamadı — zincirdeki sürüm gösteriliyor diff --git a/common/src/main/res/values/strings.xml b/common/src/main/res/values/strings.xml index 068a37b5..736db432 100644 --- a/common/src/main/res/values/strings.xml +++ b/common/src/main/res/values/strings.xml @@ -2854,4 +2854,47 @@ Music Rewshenbir Referral + .kurd name + Resolved on chain · never sent to a search engine + Official + Registered + Not verified + This site cannot be opened + Official names open only once they are verified on chain. The chain could not be reached just now. + Not verified + This name could not be checked on chain. The site may not be its owner\'s. Do not enter private information or sign anything here. + Go back + Open anyway + No such name + %s is not registered, or its registration has ended. + No site at this name + The name is registered, but its owner has not published a site the wallet can open. + Could not be loaded + Neither the chain nor the mirrors answered with content that could be verified. + Official · a state name + Registered on chain + Opened without verification + Given by Parliament. Its content changes only after a waiting period during which Parliament can stop the change. + This name was bought. Its content was verified on chain, but who made the site was not. + You chose to open this name although it could not be checked on chain. What it points to rests on two nodes\' word, not on a proof. + Verification + On chain · block #%s + On chain + Two nodes agreed, no proof + Owner + State institution (multisig) + Content + Clear this site\'s data + This name looks like an official one + You typed + Official name + Fake sites use names close to official ones to deceive you. + Go to %s + Open %s anyway + Official + Bought · not official + Not verified + Check the full name. This name was not given by the state. + This name could not be checked on chain. Sign only if you are sure whose site this is. + No newer version found — showing the version on chain diff --git a/feature-dapp-api/src/main/java/io/novafoundation/nova/feature_dapp_api/presentation/view/DAppView.kt b/feature-dapp-api/src/main/java/io/novafoundation/nova/feature_dapp_api/presentation/view/DAppView.kt index 8e044a0b..dd507e0d 100644 --- a/feature-dapp-api/src/main/java/io/novafoundation/nova/feature_dapp_api/presentation/view/DAppView.kt +++ b/feature-dapp-api/src/main/java/io/novafoundation/nova/feature_dapp_api/presentation/view/DAppView.kt @@ -63,6 +63,12 @@ class DAppView @JvmOverloads constructor( binder.itemDAppIcon.showDAppIcon(iconUrl, imageLoader) } + /** A bundled icon instead of a DApp's own, for entries that are not catalogue DApps. */ + fun setIconResource(@DrawableRes iconRes: Int, @ColorRes tintRes: Int?) { + binder.itemDAppIcon.setImageResource(iconRes) + binder.itemDAppIcon.setImageTintRes(tintRes) + } + fun setFavoriteIconVisible(visible: Boolean) { binder.itemDappFavorite.setVisible(visible) } diff --git a/feature-dapp-impl/build.gradle b/feature-dapp-impl/build.gradle index 1eeb7e1e..53928dd6 100644 --- a/feature-dapp-impl/build.gradle +++ b/feature-dapp-impl/build.gradle @@ -67,6 +67,7 @@ dependencies { implementation project(':feature-external-sign-api') implementation project(':feature-banners-api') implementation project(':runtime') + implementation androidxWebKit implementation project(':feature-deep-linking') implementation kotlinDep diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/di/DAppFeatureDependencies.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/di/DAppFeatureDependencies.kt index a07968bb..5cf440f3 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/di/DAppFeatureDependencies.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/di/DAppFeatureDependencies.kt @@ -40,6 +40,8 @@ import io.novafoundation.nova.feature_wallet_connect_api.presentation.WalletConn import io.novafoundation.nova.runtime.di.ExtrinsicSerialization import io.novafoundation.nova.runtime.multiNetwork.ChainRegistry import io.novafoundation.nova.runtime.multiNetwork.runtime.repository.RuntimeVersionsRepository +import io.novafoundation.nova.runtime.names.KurdNameResolver +import io.novafoundation.nova.runtime.names.content.KurdSiteServer interface DAppFeatureDependencies { @@ -101,6 +103,10 @@ interface DAppFeatureDependencies { fun chainRegistry(): ChainRegistry + fun kurdSiteServer(): KurdSiteServer + + fun kurdNameResolver(): KurdNameResolver + fun imageLoader(): ImageLoader fun feeLoaderMixinFactory(): FeeLoaderMixin.Factory diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/di/modules/BrowserTabsModule.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/di/modules/BrowserTabsModule.kt index 7b9fe5b1..55049768 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/di/modules/BrowserTabsModule.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/di/modules/BrowserTabsModule.kt @@ -1,5 +1,6 @@ package io.novafoundation.nova.feature_dapp_impl.di.modules +import io.novafoundation.nova.runtime.names.content.KurdSiteServer import android.content.Context import dagger.Module import dagger.Provides @@ -84,9 +85,10 @@ class BrowserTabsModule { fun providePageSessionFactory( compoundWeb3Injector: CompoundWeb3Injector, contextManager: ContextManager, - integrityCheckJSBridgeFactory: IntegrityCheckJSBridgeFactory + integrityCheckJSBridgeFactory: IntegrityCheckJSBridgeFactory, + kurdSiteServer: KurdSiteServer, ): BrowserTabSessionFactory { - return BrowserTabSessionFactory(compoundWeb3Injector, contextManager, integrityCheckJSBridgeFactory) + return BrowserTabSessionFactory(compoundWeb3Injector, contextManager, integrityCheckJSBridgeFactory, kurdSiteServer) } @FeatureScope diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/di/modules/web3/PolkadotJsModule.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/di/modules/web3/PolkadotJsModule.kt index e7775347..15d869e5 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/di/modules/web3/PolkadotJsModule.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/di/modules/web3/PolkadotJsModule.kt @@ -14,6 +14,7 @@ import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.PolkadotJsInject import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.PolkadotJsResponder import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.PolkadotJsTransportFactory import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.di.PolkadotJs +import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.rpc.ChainRegistryRpc import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.states.PolkadotJsStateFactory import io.novafoundation.nova.feature_dapp_impl.web3.session.Web3Session import io.novafoundation.nova.feature_dapp_impl.web3.webview.WebViewHolder @@ -74,6 +75,7 @@ class PolkadotJsModule { addressIconGenerator: AddressIconGenerator, web3Session: Web3Session, walletUiUseCase: WalletUiUseCase, + chainRegistry: ChainRegistry, ): PolkadotJsStateFactory { return PolkadotJsStateFactory( interactor = interactor, @@ -81,7 +83,8 @@ class PolkadotJsModule { resourceManager = resourceManager, addressIconGenerator = addressIconGenerator, web3Session = web3Session, - walletUiUseCase = walletUiUseCase + walletUiUseCase = walletUiUseCase, + chainRpc = ChainRegistryRpc(chainRegistry), ) } } diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/domain/search/DappSearchGroup.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/domain/search/DappSearchGroup.kt index 1009fd2a..bc7eb4d5 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/domain/search/DappSearchGroup.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/domain/search/DappSearchGroup.kt @@ -1,5 +1,5 @@ package io.novafoundation.nova.feature_dapp_impl.domain.search enum class DappSearchGroup { - DAPPS, SEARCH + KURD_NAME, DAPPS, SEARCH } diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/domain/search/DappSearchResult.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/domain/search/DappSearchResult.kt index ea634ff0..8c36943c 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/domain/search/DappSearchResult.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/domain/search/DappSearchResult.kt @@ -12,6 +12,13 @@ sealed interface DappSearchResult { override val isTrustedByNova: Boolean = false } + /** A `.kurd` name: resolved on chain when opened, never looked up on the web. */ + class KurdName(val name: io.novafoundation.nova.runtime.names.KurdName) : DappSearchResult { + override val isTrustedByNova: Boolean = true + + val url: String get() = "https://${name.name}/" + } + class Dapp(val dapp: DApp) : DappSearchResult { override val isTrustedByNova: Boolean = true } diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/domain/search/SearchDappInteractor.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/domain/search/SearchDappInteractor.kt index 4c96be0f..423a827e 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/domain/search/SearchDappInteractor.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/domain/search/SearchDappInteractor.kt @@ -8,10 +8,12 @@ import io.novafoundation.nova.feature_dapp_api.data.repository.DAppMetadataRepos import io.novafoundation.nova.feature_dapp_impl.data.repository.FavouritesDAppRepository import io.novafoundation.nova.feature_dapp_impl.domain.common.buildUrlToDappMapping import io.novafoundation.nova.feature_dapp_impl.domain.common.createDAppComparator +import io.novafoundation.nova.runtime.names.KurdName import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext +import java.net.URLEncoder class SearchDappInteractor( private val dAppMetadataRepository: DAppMetadataRepository, @@ -31,8 +33,12 @@ class SearchDappInteractor( .sortedWith(createDAppComparator()) .map(DappSearchResult::Dapp) + // A .kurd name is resolved on chain by the wallet: never a web address, never a search query + val kurdName = KurdName.parse(query).takeIf { KurdName.mentionsKurd(query) } + val searchGroupContent = when { query.isEmpty() -> null + KurdName.mentionsKurd(query) -> null Urls.isValidWebUrl(query) -> { val searchUrl = Urls.ensureHttpsProtocol(query) val searchUrlDomain = Urls.domainOf(searchUrl) @@ -44,6 +50,10 @@ class SearchDappInteractor( } buildMap { + kurdName?.let { + put(DappSearchGroup.KURD_NAME, listOf(DappSearchResult.KurdName(it))) + } + searchGroupContent?.let { put(DappSearchGroup.SEARCH, listOf(searchGroupContent)) } @@ -54,7 +64,7 @@ class SearchDappInteractor( } } - private fun searchUrlFor(query: String): String = "https://duckduckgo.com/?q=$query" + private fun searchUrlFor(query: String): String = "https://duckduckgo.com/?q=" + URLEncoder.encode(query, Charsets.UTF_8.name()) private suspend fun getDapps(categoryId: String?): Collection { val dApps = dAppMetadataRepository.getDAppCatalog() diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/DAppBrowserFragment.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/DAppBrowserFragment.kt index 10ebd6b0..03c7f8ec 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/DAppBrowserFragment.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/DAppBrowserFragment.kt @@ -5,21 +5,31 @@ import android.graphics.Bitmap import android.os.Bundle import android.transition.TransitionInflater import android.view.View +import android.webkit.CookieManager +import android.webkit.GeolocationPermissions import android.webkit.WebResourceRequest +import android.webkit.WebStorage import android.webkit.WebView import android.widget.ImageView import androidx.activity.OnBackPressedCallback import androidx.core.app.SharedElementCallback import androidx.core.os.bundleOf import androidx.core.transition.addListener +import androidx.lifecycle.lifecycleScope import androidx.lifecycle.viewModelScope import coil.ImageLoader import io.novafoundation.nova.common.base.BaseFragment import io.novafoundation.nova.common.di.FeatureUtils +import io.novafoundation.nova.common.utils.browser.fileChoosing.WebViewFileChooser +import io.novafoundation.nova.common.utils.browser.permissions.WebViewPermissionAsker import io.novafoundation.nova.common.utils.insets.applyNavigationBarInsets import io.novafoundation.nova.common.utils.insets.applyStatusBarInsets import io.novafoundation.nova.common.utils.makeGone import io.novafoundation.nova.common.utils.makeVisible +import io.novafoundation.nova.common.utils.setImageTintRes +import io.novafoundation.nova.common.utils.setVisible +import io.novafoundation.nova.common.utils.webView.WebViewRequestInterceptor +import io.novafoundation.nova.common.view.dialog.infoDialog import io.novafoundation.nova.feature_dapp_api.di.DAppFeatureApi import io.novafoundation.nova.feature_dapp_api.presentation.browser.main.DAppBrowserPayload import io.novafoundation.nova.feature_dapp_impl.R @@ -27,21 +37,21 @@ import io.novafoundation.nova.feature_dapp_impl.databinding.FragmentDappBrowserB import io.novafoundation.nova.feature_dapp_impl.di.DAppFeatureComponent import io.novafoundation.nova.feature_dapp_impl.domain.browser.isSecure import io.novafoundation.nova.feature_dapp_impl.presentation.browser.main.DappPendingConfirmation.Action +import io.novafoundation.nova.feature_dapp_impl.presentation.browser.main.kurd.KurdDetailsSheet +import io.novafoundation.nova.feature_dapp_impl.presentation.browser.main.kurd.KurdPageUi import io.novafoundation.nova.feature_dapp_impl.presentation.browser.main.sheets.AcknowledgePhishingBottomSheet import io.novafoundation.nova.feature_dapp_impl.presentation.browser.options.OptionsBottomSheetDialog import io.novafoundation.nova.feature_dapp_impl.presentation.common.favourites.setupRemoveFavouritesConfirmation import io.novafoundation.nova.feature_dapp_impl.utils.tabs.models.BrowserTabSession -import io.novafoundation.nova.feature_dapp_impl.web3.webview.Web3ChromeClient -import io.novafoundation.nova.feature_dapp_impl.web3.webview.CompoundWeb3Injector -import io.novafoundation.nova.feature_dapp_impl.web3.webview.Web3WebViewClient -import io.novafoundation.nova.common.utils.browser.fileChoosing.WebViewFileChooser -import io.novafoundation.nova.feature_dapp_impl.web3.webview.WebViewHolder -import io.novafoundation.nova.common.utils.browser.permissions.WebViewPermissionAsker -import io.novafoundation.nova.common.utils.webView.WebViewRequestInterceptor -import io.novafoundation.nova.common.view.dialog.infoDialog import io.novafoundation.nova.feature_dapp_impl.utils.tabs.models.SessionCallback +import io.novafoundation.nova.feature_dapp_impl.web3.webview.CompoundWeb3Injector +import io.novafoundation.nova.feature_dapp_impl.web3.webview.Web3ChromeClient +import io.novafoundation.nova.feature_dapp_impl.web3.webview.Web3WebViewClient +import io.novafoundation.nova.feature_dapp_impl.web3.webview.WebViewHolder import io.novafoundation.nova.feature_external_sign_api.presentation.externalSign.AuthorizeDappBottomSheet +import io.novafoundation.nova.runtime.names.KurdName import javax.inject.Inject +import kotlinx.coroutines.launch private const val OVERFLOW_TABS_COUNT = 100 @@ -222,11 +232,27 @@ class DAppBrowserFragment : BaseFragment + lifecycleScope.launch { + val owner = when (val owner = page.details.owner) { + KurdPageUi.Owner.Institution -> getString(R.string.dapp_kurd_owner_institution) + is KurdPageUi.Owner.Account -> viewModel.kurdOwnerAddress(owner.accountId) + } + KurdDetailsSheet(requireContext(), page, owner) { clearKurdSiteData(page.name) }.show() + } + } + + binder.dappBrowserKurdNotice.kurdNoticeSecondary.setOnClickListener { viewModel.kurdOpenAnyway() } + binder.dappBrowserKurdOnChainVersionRetry.setOnClickListener { viewModel.kurdRetry() } + viewModel.tabsCountFlow.observe { if (it >= OVERFLOW_TABS_COUNT) { binder.dappBrowserTabsIcon.makeVisible() @@ -335,4 +361,92 @@ class DAppBrowserFragment : BaseFragment Unit) + + val look = when (kind) { + KurdPageUi.NoticeKind.REFUSED -> Look( + R.drawable.ic_close_circle, + R.color.icon_negative, + R.string.dapp_kurd_refused_title, + getString(R.string.dapp_kurd_refused_message), + R.string.common_retry, + viewModel::kurdRetry + ) + KurdPageUi.NoticeKind.NEEDS_CONSENT -> Look( + R.drawable.ic_warning_filled, + R.color.icon_warning, + R.string.dapp_kurd_unverified_title, + getString(R.string.dapp_kurd_unverified_message), + R.string.dapp_kurd_back, + viewModel::kurdBack + ) + KurdPageUi.NoticeKind.NOT_REGISTERED -> Look( + R.drawable.ic_info, + R.color.icon_secondary, + R.string.dapp_kurd_not_registered_title, + getString(R.string.dapp_kurd_not_registered_message, page.name.name), + R.string.dapp_kurd_back, + viewModel::kurdBack + ) + KurdPageUi.NoticeKind.NO_SITE -> Look( + R.drawable.ic_info, + R.color.icon_secondary, + R.string.dapp_kurd_no_site_title, + getString(R.string.dapp_kurd_no_site_message), + R.string.dapp_kurd_back, + viewModel::kurdBack + ) + KurdPageUi.NoticeKind.UNAVAILABLE -> Look( + R.drawable.ic_warning_filled, + R.color.icon_warning, + R.string.dapp_kurd_unavailable_title, + getString(R.string.dapp_kurd_unavailable_message), + R.string.common_retry, + viewModel::kurdRetry + ) + } + + notice.kurdNoticeName.text = page.name.name + notice.kurdNoticeIcon.setImageResource(look.icon) + notice.kurdNoticeIcon.setImageTintRes(look.tint) + notice.kurdNoticeTitle.setText(look.title) + notice.kurdNoticeMessage.text = look.message + notice.kurdNoticePrimary.setText(look.primary) + notice.kurdNoticePrimary.setOnClickListener { look.primaryAction() } + notice.kurdNoticeSecondary.setVisible(kind == KurdPageUi.NoticeKind.NEEDS_CONSENT) + notice.kurdNoticeSecondary.setText(R.string.dapp_kurd_open_anyway) + } + + /** Storage, cookies and permissions the page kept under its name; then it loads afresh. */ + private fun clearKurdSiteData(name: KurdName) { + val origin = "https://${name.name}" + WebStorage.getInstance().deleteOrigin(origin) + GeolocationPermissions.getInstance().clear(origin) + + val cookies = CookieManager.getInstance() + cookies.getCookie(origin)?.split(';')?.map { it.substringBefore('=').trim() }?.filter { it.isNotEmpty() }?.forEach { cookieName -> + cookies.setCookie(origin, "$cookieName=; Max-Age=0") + } + cookies.flush() + + viewModel.reloadPage() + } } diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/DAppBrowserViewModel.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/DAppBrowserViewModel.kt index 381b44ec..e53415df 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/DAppBrowserViewModel.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/DAppBrowserViewModel.kt @@ -12,13 +12,14 @@ import io.novafoundation.nova.common.utils.removeHexPrefix import io.novafoundation.nova.common.utils.singleReplaySharedFlow import io.novafoundation.nova.feature_account_api.domain.interfaces.SelectedAccountUseCase import io.novafoundation.nova.feature_dapp_api.data.model.BrowserHostSettings -import io.novafoundation.nova.feature_dapp_impl.presentation.DAppRouter +import io.novafoundation.nova.feature_dapp_api.presentation.addToFavorites.AddToFavouritesPayload +import io.novafoundation.nova.feature_dapp_api.presentation.browser.main.DAppBrowserPayload import io.novafoundation.nova.feature_dapp_impl.domain.DappInteractor import io.novafoundation.nova.feature_dapp_impl.domain.browser.BrowserPage import io.novafoundation.nova.feature_dapp_impl.domain.browser.BrowserPageAnalyzed import io.novafoundation.nova.feature_dapp_impl.domain.browser.DappBrowserInteractor -import io.novafoundation.nova.feature_dapp_api.presentation.addToFavorites.AddToFavouritesPayload -import io.novafoundation.nova.feature_dapp_api.presentation.browser.main.DAppBrowserPayload +import io.novafoundation.nova.feature_dapp_impl.presentation.DAppRouter +import io.novafoundation.nova.feature_dapp_impl.presentation.browser.main.kurd.KurdPageUi import io.novafoundation.nova.feature_dapp_impl.presentation.browser.options.DAppOptionsPayload import io.novafoundation.nova.feature_dapp_impl.presentation.common.favourites.RemoveFavouritesPayload import io.novafoundation.nova.feature_dapp_impl.presentation.search.DAppSearchCommunicator @@ -33,6 +34,7 @@ import io.novafoundation.nova.feature_dapp_impl.web3.states.ExtensionStoreFactor import io.novafoundation.nova.feature_dapp_impl.web3.states.Web3ExtensionStateMachine.ExternalEvent import io.novafoundation.nova.feature_dapp_impl.web3.states.Web3StateMachineHost import io.novafoundation.nova.feature_dapp_impl.web3.states.hostApi.ConfirmTxResponse +import io.novafoundation.nova.feature_dapp_impl.web3.webview.WebViewWeb3JavaScriptInterface import io.novafoundation.nova.feature_external_sign_api.model.ExternalSignCommunicator import io.novafoundation.nova.feature_external_sign_api.model.ExternalSignRequester import io.novafoundation.nova.feature_external_sign_api.model.awaitConfirmation @@ -40,12 +42,19 @@ import io.novafoundation.nova.feature_external_sign_api.model.signPayload.Extern import io.novafoundation.nova.feature_external_sign_api.model.signPayload.ExternalSignRequest import io.novafoundation.nova.feature_external_sign_api.model.signPayload.ExternalSignWallet import io.novafoundation.nova.feature_external_sign_api.model.signPayload.SigningDappMetadata +import io.novafoundation.nova.feature_external_sign_api.model.signPayload.SiteNameKind import io.novafoundation.nova.feature_external_sign_api.model.signPayload.polkadot.genesisHash import io.novafoundation.nova.feature_external_sign_api.presentation.externalSign.AuthorizeDappBottomSheet +import io.novafoundation.nova.runtime.ext.addressOf import io.novafoundation.nova.runtime.ext.isDisabled import io.novafoundation.nova.runtime.multiNetwork.ChainRegistry import io.novafoundation.nova.runtime.multiNetwork.chainsById +import io.novafoundation.nova.runtime.multiNetwork.connection.light.LightClients +import io.novafoundation.nova.runtime.names.content.KurdSiteServer +import kotlin.coroutines.resume +import kotlin.coroutines.suspendCoroutine import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChangedBy @@ -53,13 +62,12 @@ import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterIsInstance import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -import kotlin.coroutines.resume -import kotlin.coroutines.suspendCoroutine enum class ConfirmationState { ALLOWED, REJECTED, CANCELLED @@ -78,7 +86,8 @@ class DAppBrowserViewModel( private val selectedAccountUseCase: SelectedAccountUseCase, private val actionAwaitableMixinFactory: ActionAwaitableMixin.Factory, private val chainRegistry: ChainRegistry, - private val browserTabService: BrowserTabService + private val browserTabService: BrowserTabService, + private val kurdSiteServer: KurdSiteServer, ) : BaseViewModel(), Web3StateMachineHost { val removeFromFavouritesConfirmation = actionAwaitableMixinFactory.confirmingAction() @@ -97,6 +106,16 @@ class DAppBrowserViewModel( override val externalEvents = singleReplaySharedFlow() + /** The `.kurd` name the tab shows and how: a badge on an open page, or a notice in its place. */ + val kurdPage: Flow = currentPage + .map { KurdPageUi.nameOf(it.url) } + .distinctUntilChanged() + .flatMapLatest { name -> if (name == null) flowOf(null) else kurdSiteServer.pageStates.map { KurdPageUi.from(name, it[name]) } } + .shareInBackground() + + private val _kurdDetailsEvent = MutableLiveData>() + val kurdDetailsEvent: LiveData> = _kurdDetailsEvent + private val _browserCommandEvent = MutableLiveData>() val browserCommandEvent: LiveData> = _browserCommandEvent @@ -151,7 +170,10 @@ class DAppBrowserViewModel( return mapConfirmationStateToAuthorizationState(confirmationState) } - override suspend fun confirmTx(request: ExternalSignRequest): ConfirmTxResponse { + override suspend fun confirmTx(request: ExternalSignRequest, origin: String): ConfirmTxResponse { + val pageUrl = currentPageAnalyzed.first().url + if (!WebViewWeb3JavaScriptInterface.sameOrigin(pageUrl, origin)) return ConfirmTxResponse.Rejected(request.id) + val chainId = request.extractChainId() val chain = chainRegistry.chainsById()[chainId] @@ -160,7 +182,7 @@ class DAppBrowserViewModel( } val response = withContext(Dispatchers.Main) { - signRequester.awaitConfirmation(mapSignExtrinsicRequestToPayload(request)) + signRequester.awaitConfirmation(mapSignExtrinsicRequestToPayload(request, origin, pageUrl)) } return when (response) { @@ -175,6 +197,32 @@ class DAppBrowserViewModel( _browserCommandEvent.postValue(BrowserCommand.Reload.event()) } + fun kurdRetry() = launch { + kurdPage.first()?.let { kurdSiteServer.forget(it.name) } + reloadPage() + } + + /** Only from the unverified notice: a refused name has no way past it. */ + fun kurdOpenAnyway() = launch { + val notice = kurdPage.first() as? KurdPageUi.Notice ?: return@launch + if (notice.kind != KurdPageUi.NoticeKind.NEEDS_CONSENT) return@launch + + kurdSiteServer.allowUnverified(notice.name) + reloadPage() + } + + fun kurdBack() { + _browserCommandEvent.value = BrowserCommand.GoBack.event() + } + + fun kurdBadgeClicked() = launch { + (kurdPage.first() as? KurdPageUi.Open)?.let { _kurdDetailsEvent.value = it.event() } + } + + suspend fun kurdOwnerAddress(accountId: ByteArray): String { + return chainRegistry.getChain(LightClients.ZAGROS_PEOPLE).addressOf(accountId) + } + fun detachCurrentSession() { browserTabService.detachCurrentSession() } @@ -296,15 +344,31 @@ class DAppBrowserViewModel( currentPage.emit(BrowserPage(url, title, synchronizedWithBrowser)) } - private suspend fun mapSignExtrinsicRequestToPayload(request: ExternalSignRequest): ExternalSignPayload { + private suspend fun mapSignExtrinsicRequestToPayload(request: ExternalSignRequest, origin: String, pageUrl: String): ExternalSignPayload { return ExternalSignPayload( signRequest = request, - dappMetadata = getDAppSignMetadata(currentPageAnalyzed.first().url), + dappMetadata = getDAppSignMetadata(origin, pageUrl), wallet = ExternalSignWallet.Current ) } - private suspend fun getDAppSignMetadata(dAppUrl: String): SigningDappMetadata { + /** Named after the page that asked ([origin]), never after whatever the tab shows by now. */ + private suspend fun getDAppSignMetadata(origin: String, dAppUrl: String): SigningDappMetadata { + val kurdName = KurdPageUi.nameOf(origin) + val kurdPage = kurdName?.let { KurdPageUi.from(it, kurdSiteServer.pageStates.value[it]) } + if (kurdName != null && kurdPage !is KurdPageUi.Open) { + // A .kurd page that is not open has no content that could have asked; say nothing official + return SigningDappMetadata(icon = null, name = kurdName.name, url = kurdName.name, siteNameKind = SiteNameKind.UNVERIFIED) + } + if (kurdPage is KurdPageUi.Open) { + val kind = when (kurdPage.badge) { + KurdPageUi.Badge.OFFICIAL -> SiteNameKind.OFFICIAL + KurdPageUi.Badge.REGISTERED -> SiteNameKind.REGISTERED + KurdPageUi.Badge.UNVERIFIED -> SiteNameKind.UNVERIFIED + } + return SigningDappMetadata(icon = null, name = kurdPage.name.name, url = kurdPage.name.name, siteNameKind = kind) + } + val dappMetadata = dAppInteractor.getDAppInfo(dAppUrl) return SigningDappMetadata( diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/di/DAppBrowserModule.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/di/DAppBrowserModule.kt index 4f555dd6..f98ebf28 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/di/DAppBrowserModule.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/di/DAppBrowserModule.kt @@ -12,29 +12,30 @@ import io.novafoundation.nova.common.di.viewmodel.ViewModelModule import io.novafoundation.nova.common.mixin.actionAwaitable.ActionAwaitableMixin import io.novafoundation.nova.common.resources.ContextManager import io.novafoundation.nova.common.utils.ToastMessageManager +import io.novafoundation.nova.common.utils.browser.fileChoosing.WebViewFileChooserFactory +import io.novafoundation.nova.common.utils.browser.permissions.WebViewPermissionAskerFactory +import io.novafoundation.nova.common.utils.webView.WebViewRequestInterceptor +import io.novafoundation.nova.common.utils.webView.interceptors.CompoundWebViewRequestInterceptor import io.novafoundation.nova.core_db.dao.BrowserHostSettingsDao import io.novafoundation.nova.feature_account_api.domain.interfaces.SelectedAccountUseCase import io.novafoundation.nova.feature_dapp_api.data.repository.BrowserHostSettingsRepository -import io.novafoundation.nova.feature_dapp_impl.presentation.DAppRouter import io.novafoundation.nova.feature_dapp_api.presentation.browser.main.DAppBrowserPayload import io.novafoundation.nova.feature_dapp_impl.data.repository.FavouritesDAppRepository import io.novafoundation.nova.feature_dapp_impl.data.repository.PhishingSitesRepository import io.novafoundation.nova.feature_dapp_impl.data.repository.RealBrowserHostSettingsRepository import io.novafoundation.nova.feature_dapp_impl.domain.DappInteractor import io.novafoundation.nova.feature_dapp_impl.domain.browser.DappBrowserInteractor +import io.novafoundation.nova.feature_dapp_impl.presentation.DAppRouter import io.novafoundation.nova.feature_dapp_impl.presentation.browser.main.DAppBrowserViewModel import io.novafoundation.nova.feature_dapp_impl.presentation.search.DAppSearchCommunicator import io.novafoundation.nova.feature_dapp_impl.utils.tabs.BrowserTabService import io.novafoundation.nova.feature_dapp_impl.web3.states.ExtensionStoreFactory -import io.novafoundation.nova.common.utils.browser.fileChoosing.WebViewFileChooserFactory -import io.novafoundation.nova.common.utils.browser.permissions.WebViewPermissionAskerFactory -import io.novafoundation.nova.common.utils.webView.WebViewRequestInterceptor -import io.novafoundation.nova.common.utils.webView.interceptors.CompoundWebViewRequestInterceptor import io.novafoundation.nova.feature_dapp_impl.web3.webview.interceptors.WalletConnectPairingInterceptor import io.novafoundation.nova.feature_dapp_impl.web3.webview.interceptors.Web3FallbackInterceptor import io.novafoundation.nova.feature_external_sign_api.model.ExternalSignCommunicator import io.novafoundation.nova.feature_wallet_connect_api.presentation.WalletConnectService import io.novafoundation.nova.runtime.multiNetwork.ChainRegistry +import io.novafoundation.nova.runtime.names.content.KurdSiteServer @Module(includes = [ViewModelModule::class]) class DAppBrowserModule { @@ -103,7 +104,8 @@ class DAppBrowserModule { dAppInteractor: DappInteractor, actionAwaitableMixinFactory: ActionAwaitableMixin.Factory, chainRegistry: ChainRegistry, - browserTabService: BrowserTabService + browserTabService: BrowserTabService, + kurdSiteServer: KurdSiteServer, ): ViewModel { return DAppBrowserViewModel( router = router, @@ -116,7 +118,8 @@ class DAppBrowserModule { extensionStoreFactory = extensionStoreFactory, actionAwaitableMixinFactory = actionAwaitableMixinFactory, chainRegistry = chainRegistry, - browserTabService = browserTabService + browserTabService = browserTabService, + kurdSiteServer = kurdSiteServer, ) } } diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/kurd/KurdDetailsSheet.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/kurd/KurdDetailsSheet.kt new file mode 100644 index 00000000..27cd4312 --- /dev/null +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/kurd/KurdDetailsSheet.kt @@ -0,0 +1,73 @@ +package io.novafoundation.nova.feature_dapp_impl.presentation.browser.main.kurd + +import android.content.Context +import android.os.Bundle +import android.view.LayoutInflater +import io.novafoundation.nova.common.utils.WithContextExtensions +import io.novafoundation.nova.common.utils.setImageTintRes +import io.novafoundation.nova.common.utils.setTextColorRes +import io.novafoundation.nova.common.view.bottomSheet.BaseBottomSheet +import io.novafoundation.nova.feature_dapp_impl.R +import io.novafoundation.nova.feature_dapp_impl.databinding.SheetKurdDetailsBinding + +/** What was verified about the `.kurd` page the tab shows, from its address bar badge. */ +class KurdDetailsSheet( + context: Context, + private val page: KurdPageUi.Open, + private val ownerText: String, + private val onClearSiteData: () -> Unit, +) : BaseBottomSheet(context, R.style.BottomSheetDialog), WithContextExtensions by WithContextExtensions(context) { + + override val binder: SheetKurdDetailsBinding = SheetKurdDetailsBinding.inflate(LayoutInflater.from(context)) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + val details = page.details + binder.kurdDetailsName.text = page.name.name + + when (details.badge) { + KurdPageUi.Badge.OFFICIAL -> { + binder.kurdDetailsIcon.setImageResource(R.drawable.shield_checkmark_outline) + binder.kurdDetailsIcon.setImageTintRes(R.color.icon_positive) + binder.kurdDetailsKind.setText(R.string.dapp_kurd_kind_official) + binder.kurdDetailsKind.setTextColorRes(R.color.text_positive) + binder.kurdDetailsExplanation.setText(R.string.dapp_kurd_official_explanation) + } + KurdPageUi.Badge.REGISTERED -> { + binder.kurdDetailsIcon.setImageResource(R.drawable.ic_lock) + binder.kurdDetailsIcon.setImageTintRes(R.color.icon_secondary) + binder.kurdDetailsKind.setText(R.string.dapp_kurd_kind_registered) + binder.kurdDetailsKind.setTextColorRes(R.color.text_secondary) + binder.kurdDetailsExplanation.setText(R.string.dapp_kurd_registered_explanation) + } + KurdPageUi.Badge.UNVERIFIED -> { + binder.kurdDetailsIcon.setImageResource(R.drawable.ic_warning_filled) + binder.kurdDetailsIcon.setImageTintRes(R.color.icon_warning) + binder.kurdDetailsKind.setText(R.string.dapp_kurd_kind_unverified) + binder.kurdDetailsKind.setTextColorRes(R.color.text_warning) + binder.kurdDetailsExplanation.setText(R.string.dapp_kurd_unverified_explanation) + } + } + + binder.kurdDetailsVerification.setTitle(R.string.dapp_kurd_details_verification) + binder.kurdDetailsVerification.showValue(verificationText(details)) + binder.kurdDetailsOwner.setTitle(R.string.dapp_kurd_details_owner) + binder.kurdDetailsOwner.showValue(ownerText) + binder.kurdDetailsContent.setTitle(R.string.dapp_kurd_details_content) + binder.kurdDetailsContent.showValue(shortened(details.contentId)) + + binder.kurdDetailsClearData.setOnClickListener { + onClearSiteData() + dismiss() + } + } + + private fun verificationText(details: KurdPageUi.Details): String = when { + details.badge == KurdPageUi.Badge.UNVERIFIED -> context.getString(R.string.dapp_kurd_verified_by_nodes) + details.provenAtBlock != null -> context.getString(R.string.dapp_kurd_verified_at_block, details.provenAtBlock.toString()) + else -> context.getString(R.string.dapp_kurd_verified_on_chain) + } + + private fun shortened(cid: String) = if (cid.length > 12) cid.take(4) + "…" + cid.takeLast(4) else cid +} diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/kurd/KurdPageUi.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/kurd/KurdPageUi.kt new file mode 100644 index 00000000..e655f47a --- /dev/null +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/kurd/KurdPageUi.kt @@ -0,0 +1,79 @@ +package io.novafoundation.nova.feature_dapp_impl.presentation.browser.main.kurd + +import io.novafoundation.nova.runtime.names.KurdName +import io.novafoundation.nova.runtime.names.NameRecord +import io.novafoundation.nova.runtime.names.content.KurdSiteServer.PageState +import java.net.URI + +/** What the browser shows for a `.kurd` page: a badge on an open page, or a notice in its place. */ +sealed interface KurdPageUi { + + val name: KurdName + + /** [onChainVersion]: a feed showing the release the chain names, as no newer one could be confirmed. */ + class Open(override val name: KurdName, val badge: Badge, val details: Details, val onChainVersion: Boolean = false) : KurdPageUi + + class Notice(override val name: KurdName, val kind: NoticeKind) : KurdPageUi + + enum class Badge { + /** Granted by Parliament, or under such a name: the state's own. */ + OFFICIAL, + + /** Bought: the content is verified, who made it is not. */ + REGISTERED, + + /** Opened by the reader's choice, on two RPC nodes' word. */ + UNVERIFIED, + } + + enum class NoticeKind { REFUSED, NEEDS_CONSENT, NOT_REGISTERED, NO_SITE, UNAVAILABLE } + + class Details( + val badge: Badge, + /** The finalized block the name was proven at; null when read through RPC or not reported. */ + val provenAtBlock: Long?, + val owner: Owner, + val contentId: String, + ) + + sealed interface Owner { + /** Parliament or an office: a state institution, acting through its multisig. */ + object Institution : Owner + + class Account(val accountId: ByteArray) : Owner + } + + companion object { + + /** The name a page URL is on, or null for any other page. */ + fun nameOf(pageUrl: String?): KurdName? { + val host = runCatching { URI(pageUrl ?: return null).host }.getOrNull() ?: return null + return if (KurdName.isKurdHost(host)) KurdName.parse(host) else null + } + + /** Null while the page's document has not been answered yet. */ + fun from(name: KurdName, state: PageState?): KurdPageUi? = when (state) { + null -> null + is PageState.Open -> { + val resolution = state.resolution + val badge = when { + !resolution.verified -> Badge.UNVERIFIED + resolution.official -> Badge.OFFICIAL + else -> Badge.REGISTERED + } + val owner = when (val owner = resolution.record.owner) { + is NameRecord.Owner.Account -> Owner.Account(owner.accountId) + is NameRecord.Owner.Office, NameRecord.Owner.Governance -> Owner.Institution + } + val provenAt = resolution.block.takeIf { resolution.verified } + + Open(name, badge, Details(badge, provenAt, owner, state.root.toString()), state.onChainVersion) + } + is PageState.NeedsConsent -> Notice(name, NoticeKind.NEEDS_CONSENT) + PageState.Refused -> Notice(name, NoticeKind.REFUSED) + PageState.NotRegistered -> Notice(name, NoticeKind.NOT_REGISTERED) + PageState.NoSite -> Notice(name, NoticeKind.NO_SITE) + PageState.Unavailable -> Notice(name, NoticeKind.UNAVAILABLE) + } + } +} diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/view/AddressBarView.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/view/AddressBarView.kt index 427fa25f..5196d79e 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/view/AddressBarView.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/view/AddressBarView.kt @@ -4,13 +4,17 @@ import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.widget.LinearLayout +import androidx.core.view.updateLayoutParams import io.novafoundation.nova.common.utils.WithContextExtensions +import io.novafoundation.nova.common.utils.dp import io.novafoundation.nova.common.utils.inflater +import io.novafoundation.nova.common.utils.makeVisible import io.novafoundation.nova.common.utils.setImageTintRes import io.novafoundation.nova.common.utils.setTextColorRes import io.novafoundation.nova.common.utils.setVisible import io.novafoundation.nova.feature_dapp_impl.R import io.novafoundation.nova.feature_dapp_impl.databinding.ViewAddressBarBinding +import io.novafoundation.nova.feature_dapp_impl.presentation.browser.main.kurd.KurdPageUi class AddressBarView @JvmOverloads constructor( context: Context, @@ -37,7 +41,41 @@ class AddressBarView @JvmOverloads constructor( binder.addressBarIcon.setVisible(shouldShow) } + /** + * The badge of a `.kurd` page, or none. It replaces the padlock: a `.kurd` page is not reached + * over the network the padlock speaks of, and the badge says what was verified instead. + */ + fun showKurdBadge(badge: KurdPageUi.Badge?, onClick: () -> Unit) { + val badgeView = binder.addressBarKurdBadge + badgeView.setVisible(badge != null) + binder.addressBarUrl.updateLayoutParams { marginEnd = (if (badge != null) 6 else 32).dp(context) } + if (badge == null) { + badgeView.setOnClickListener(null) + return + } + + val (textRes, colorRes, iconRes) = when (badge) { + KurdPageUi.Badge.OFFICIAL -> Triple(R.string.dapp_kurd_badge_official, R.color.text_positive, R.drawable.shield_checkmark_outline) + KurdPageUi.Badge.REGISTERED -> Triple(R.string.dapp_kurd_badge_registered, R.color.text_secondary, R.drawable.ic_lock) + KurdPageUi.Badge.UNVERIFIED -> Triple(R.string.dapp_kurd_badge_unverified, R.color.text_warning, R.drawable.ic_warning_filled) + } + val iconTint = when (badge) { + KurdPageUi.Badge.OFFICIAL -> R.color.icon_positive + KurdPageUi.Badge.REGISTERED -> R.color.icon_secondary + KurdPageUi.Badge.UNVERIFIED -> R.color.icon_warning + } + + badgeView.setText(textRes) + badgeView.setTextColorRes(colorRes) + binder.addressBarIcon.makeVisible() + binder.addressBarIcon.setImageResource(iconRes) + binder.addressBarIcon.setImageTintRes(iconTint) + binder.addressBarUrl.setTextColorRes(R.color.text_primary) + badgeView.setOnClickListener { onClick() } + } + fun showSecure(shouldShow: Boolean) { + binder.addressBarIcon.setImageResource(R.drawable.ic_lock) binder.addressBarIcon.setVisible(shouldShow) if (shouldShow) { diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/DAppSearchViewModel.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/DAppSearchViewModel.kt index 9825ca49..03767eee 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/DAppSearchViewModel.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/DAppSearchViewModel.kt @@ -13,20 +13,25 @@ import io.novafoundation.nova.common.utils.Event import io.novafoundation.nova.common.utils.inBackground import io.novafoundation.nova.common.utils.sendEvent import io.novafoundation.nova.common.utils.withSafeLoading -import io.novafoundation.nova.feature_dapp_impl.presentation.DAppRouter import io.novafoundation.nova.feature_dapp_api.presentation.browser.main.DAppBrowserPayload import io.novafoundation.nova.feature_dapp_impl.R import io.novafoundation.nova.feature_dapp_impl.domain.DappInteractor import io.novafoundation.nova.feature_dapp_impl.domain.search.DappSearchGroup import io.novafoundation.nova.feature_dapp_impl.domain.search.DappSearchResult import io.novafoundation.nova.feature_dapp_impl.domain.search.SearchDappInteractor +import io.novafoundation.nova.feature_dapp_impl.presentation.DAppRouter import io.novafoundation.nova.feature_dapp_impl.presentation.common.dappCategoryToUi import io.novafoundation.nova.feature_dapp_impl.presentation.search.model.DappSearchModel +import io.novafoundation.nova.runtime.names.KurdLookalikes +import io.novafoundation.nova.runtime.names.KurdName +import io.novafoundation.nova.runtime.names.KurdNameResolver +import io.novafoundation.nova.runtime.names.KurdResolution import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull @OptIn(ExperimentalCoroutinesApi::class) class DAppSearchViewModel( @@ -37,11 +42,14 @@ class DAppSearchViewModel( private val payload: SearchPayload, private val dAppSearchResponder: DAppSearchResponder, private val actionAwaitableMixinFactory: ActionAwaitableMixin.Factory, - private val appLinksProvider: AppLinksProvider + private val appLinksProvider: AppLinksProvider, + private val kurdNameResolver: KurdNameResolver, ) : BaseViewModel() { val dAppNotInCatalogWarning = actionAwaitableMixinFactory.confirmingAction() + val kurdLookalikeWarning = actionAwaitableMixinFactory.create() + val query = MutableStateFlow(payload.initialUrl.orEmpty()) private val _selectQueryTextEvent = MutableLiveData>() @@ -91,6 +99,7 @@ class DAppSearchViewModel( val content = when (searchGroup) { DappSearchGroup.DAPPS -> resourceManager.getString(R.string.dapp_dapps) DappSearchGroup.SEARCH -> resourceManager.getString(R.string.common_search) + DappSearchGroup.KURD_NAME -> resourceManager.getString(R.string.dapp_search_kurd_name) } return TextHeader(content) @@ -117,6 +126,14 @@ class DAppSearchViewModel( searchResult = searchResult, actionIcon = null ) + + is DappSearchResult.KurdName -> DappSearchModel( + title = searchResult.name.name, + description = resourceManager.getString(R.string.dapp_search_kurd_name_subtitle), + iconRes = R.drawable.shield_checkmark_outline, + searchResult = searchResult, + actionIcon = null + ) } } @@ -126,6 +143,7 @@ class DAppSearchViewModel( is DappSearchResult.Dapp -> searchResult.dapp.url is DappSearchResult.Search -> searchResult.searchUrl is DappSearchResult.Url -> searchResult.url + is DappSearchResult.KurdName -> urlAfterLookalikeCheck(searchResult.name) } if (!searchResult.isTrustedByNova) { @@ -143,6 +161,25 @@ class DAppSearchViewModel( } } + /** + * The typed name's address, unless a proven official name it imitates exists and the reader + * chooses that one. Looked up only when the typed name has such a candidate, and for a few + * seconds at most: the opened page still shows by its badge whether it is official. + */ + private suspend fun urlAfterLookalikeCheck(typed: KurdName): String { + val official = withTimeoutOrNull(LOOKALIKE_CHECK_MILLIS) { + KurdLookalikes.candidates(typed).firstOrNull { candidate -> + val resolution = kurdNameResolver.resolve(candidate) + resolution is KurdResolution.Resolved && resolution.verified && resolution.official + } + } ?: return DappSearchResult.KurdName(typed).url + + return when (kurdLookalikeWarning.awaitAction(KurdLookalikeWarning(typed, official))) { + KurdLookalikeChoice.GO_OFFICIAL -> DappSearchResult.KurdName(official).url + KurdLookalikeChoice.OPEN_TYPED -> DappSearchResult.KurdName(typed).url + } + } + private fun shouldReportResult() = when (payload.request) { SearchPayload.Request.GO_TO_URL -> true @@ -157,3 +194,5 @@ class DAppSearchViewModel( } } } + +private const val LOOKALIKE_CHECK_MILLIS = 8_000L diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/DappSearchFragment.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/DappSearchFragment.kt index 79d6c3c2..c0e80c55 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/DappSearchFragment.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/DappSearchFragment.kt @@ -108,6 +108,10 @@ class DappSearchFragment : BaseFragment + KurdLookalikeSheet(providedContext, event.payload, onChoice = event.onSuccess, onCancel = event.onCancel).show() + } + viewModel.dAppNotInCatalogWarning.awaitableActionLiveData.observeEvent { event -> warningDialog( context = providedContext, diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/KurdLookalikeSheet.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/KurdLookalikeSheet.kt new file mode 100644 index 00000000..96ed62ba --- /dev/null +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/KurdLookalikeSheet.kt @@ -0,0 +1,44 @@ +package io.novafoundation.nova.feature_dapp_impl.presentation.search + +import android.content.Context +import android.os.Bundle +import android.view.LayoutInflater +import io.novafoundation.nova.common.utils.WithContextExtensions +import io.novafoundation.nova.common.view.bottomSheet.BaseBottomSheet +import io.novafoundation.nova.feature_dapp_impl.R +import io.novafoundation.nova.feature_dapp_impl.databinding.SheetKurdLookalikeBinding +import io.novafoundation.nova.runtime.names.KurdName + +class KurdLookalikeWarning(val typed: KurdName, val official: KurdName) + +enum class KurdLookalikeChoice { GO_OFFICIAL, OPEN_TYPED } + +/** Before opening a typed name that a proven official name could be mistaken for. */ +class KurdLookalikeSheet( + context: Context, + private val warning: KurdLookalikeWarning, + private val onChoice: (KurdLookalikeChoice) -> Unit, + onCancel: () -> Unit, +) : BaseBottomSheet(context, R.style.BottomSheetDialog, onCancel), WithContextExtensions by WithContextExtensions(context) { + + override val binder: SheetKurdLookalikeBinding = SheetKurdLookalikeBinding.inflate(LayoutInflater.from(context)) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + binder.kurdLookalikeTyped.setTitle(R.string.dapp_kurd_lookalike_typed) + binder.kurdLookalikeTyped.showValue(warning.typed.name) + binder.kurdLookalikeOfficial.setTitle(R.string.dapp_kurd_lookalike_official) + binder.kurdLookalikeOfficial.showValue(warning.official.name, context.getString(R.string.dapp_kurd_badge_official)) + + binder.kurdLookalikeGoOfficial.text = context.getString(R.string.dapp_kurd_lookalike_go, warning.official.name) + binder.kurdLookalikeGoOfficial.setOnClickListener { choose(KurdLookalikeChoice.GO_OFFICIAL) } + binder.kurdLookalikeOpenAnyway.text = context.getString(R.string.dapp_kurd_lookalike_open_anyway, warning.typed.name) + binder.kurdLookalikeOpenAnyway.setOnClickListener { choose(KurdLookalikeChoice.OPEN_TYPED) } + } + + private fun choose(choice: KurdLookalikeChoice) { + onChoice(choice) + dismiss() + } +} diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/SearchDappAdapter.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/SearchDappAdapter.kt index 6add1b46..8c75472e 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/SearchDappAdapter.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/SearchDappAdapter.kt @@ -8,9 +8,10 @@ import io.novafoundation.nova.common.list.PayloadGenerator import io.novafoundation.nova.common.list.headers.TextHeader import io.novafoundation.nova.common.list.resolvePayload import io.novafoundation.nova.common.utils.inflater -import io.novafoundation.nova.feature_dapp_impl.domain.search.DappSearchResult import io.novafoundation.nova.feature_dapp_api.presentation.view.DAppView +import io.novafoundation.nova.feature_dapp_impl.R import io.novafoundation.nova.feature_dapp_impl.databinding.ItemDappSearchCategoryBinding +import io.novafoundation.nova.feature_dapp_impl.domain.search.DappSearchResult import io.novafoundation.nova.feature_dapp_impl.presentation.search.model.DappSearchModel class SearchDappAdapter( @@ -77,6 +78,7 @@ private object DiffCallback : BaseGroupedDiffCallback true is DappSearchResult.Url -> true + is DappSearchResult.KurdName -> true is DappSearchResult.Dapp -> false } } @@ -100,7 +102,7 @@ private class SearchHolder( } fun bind(item: DappSearchModel) = with(dAppView) { - setIconUrl(item.icon) + if (item.iconRes != null) setIconResource(item.iconRes, R.color.icon_positive) else setIconUrl(item.icon) bindTitle(item) setSubtitle(item.description) diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/di/DAppSearchModule.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/di/DAppSearchModule.kt index 3e9ebe81..ac881c3c 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/di/DAppSearchModule.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/di/DAppSearchModule.kt @@ -13,13 +13,14 @@ import io.novafoundation.nova.common.di.viewmodel.ViewModelModule import io.novafoundation.nova.common.mixin.actionAwaitable.ActionAwaitableMixin import io.novafoundation.nova.common.resources.ResourceManager import io.novafoundation.nova.feature_dapp_api.data.repository.DAppMetadataRepository -import io.novafoundation.nova.feature_dapp_impl.presentation.DAppRouter import io.novafoundation.nova.feature_dapp_impl.data.repository.FavouritesDAppRepository import io.novafoundation.nova.feature_dapp_impl.domain.DappInteractor import io.novafoundation.nova.feature_dapp_impl.domain.search.SearchDappInteractor +import io.novafoundation.nova.feature_dapp_impl.presentation.DAppRouter import io.novafoundation.nova.feature_dapp_impl.presentation.search.DAppSearchCommunicator import io.novafoundation.nova.feature_dapp_impl.presentation.search.DAppSearchViewModel import io.novafoundation.nova.feature_dapp_impl.presentation.search.SearchPayload +import io.novafoundation.nova.runtime.names.KurdNameResolver @Module(includes = [ViewModelModule::class]) class DAppSearchModule { @@ -47,7 +48,8 @@ class DAppSearchModule { searchResponder: DAppSearchCommunicator, payload: SearchPayload, actionAwaitableMixinFactory: ActionAwaitableMixin.Factory, - appLinksProvider: AppLinksProvider + appLinksProvider: AppLinksProvider, + kurdNameResolver: KurdNameResolver, ): ViewModel { return DAppSearchViewModel( router = router, @@ -57,7 +59,8 @@ class DAppSearchModule { payload = payload, actionAwaitableMixinFactory = actionAwaitableMixinFactory, appLinksProvider = appLinksProvider, - dappInteractor = dappInteractor + dappInteractor = dappInteractor, + kurdNameResolver = kurdNameResolver, ) } } diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/model/DappSearchModel.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/model/DappSearchModel.kt index 3cf5ce09..fd25da2d 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/model/DappSearchModel.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/model/DappSearchModel.kt @@ -8,5 +8,6 @@ class DappSearchModel( val description: String? = null, val icon: String? = null, @DrawableRes val actionIcon: Int?, + @DrawableRes val iconRes: Int? = null, val searchResult: DappSearchResult ) diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/utils/tabs/models/BrowserTabSession.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/utils/tabs/models/BrowserTabSession.kt index 3212bbd5..fd4e32e2 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/utils/tabs/models/BrowserTabSession.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/utils/tabs/models/BrowserTabSession.kt @@ -1,5 +1,6 @@ package io.novafoundation.nova.feature_dapp_impl.utils.tabs.models +import io.novafoundation.nova.runtime.names.content.KurdSiteServer import android.graphics.Bitmap import android.webkit.WebResourceRequest import android.webkit.WebView @@ -22,7 +23,8 @@ import kotlinx.coroutines.withContext class BrowserTabSessionFactory( private val compoundWeb3Injector: CompoundWeb3Injector, private val contextManager: ContextManager, - private val integrityCheckJSBridgeFactory: IntegrityCheckJSBridgeFactory + private val integrityCheckJSBridgeFactory: IntegrityCheckJSBridgeFactory, + private val kurdSiteServer: KurdSiteServer, ) { suspend fun create(tabId: String, startUrl: String, onPageChangedCallback: OnPageChangedCallback): BrowserTabSession { @@ -37,7 +39,8 @@ class BrowserTabSessionFactory( webView = webView, integrityCheckJSBridge = integrityCheckProvider, compoundWeb3Injector = compoundWeb3Injector, - onPageChangedCallback = onPageChangedCallback + onPageChangedCallback = onPageChangedCallback, + kurdSiteServer = kurdSiteServer, ) } } @@ -49,12 +52,14 @@ class BrowserTabSession( val webView: WebView, compoundWeb3Injector: CompoundWeb3Injector, private val onPageChangedCallback: OnPageChangedCallback, - private val integrityCheckJSBridge: IntegrityCheckJSBridge + private val integrityCheckJSBridge: IntegrityCheckJSBridge, + kurdSiteServer: KurdSiteServer, ) : PageCallback, CoroutineScope by CoroutineScope(Dispatchers.Main) { val webViewClient: Web3WebViewClient = Web3WebViewClient( webView = webView, - pageCallback = this + pageCallback = this, + kurdSiteServer = kurdSiteServer, ) var currentUrl: String = startUrl @@ -63,8 +68,9 @@ class BrowserTabSession( init { webView.injectWeb3(webViewClient) - webView.loadUrl(startUrl) + // Before the first load: the bridge is only exposed to documents loaded after it is added compoundWeb3Injector.initialInject(webView) + webView.loadUrl(startUrl) integrityCheckJSBridge.errorFlow .onEach { sessionCallback?.onPageError(it) } diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/Web3Transport.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/Web3Transport.kt index e28d99e1..22e0af58 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/Web3Transport.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/Web3Transport.kt @@ -8,6 +8,9 @@ interface Web3Transport> { interface Request { + /** The origin of the page that sent it, as the WebView reported it rather than the page. */ + val origin: String + fun accept(response: RESPONSE) fun reject(error: Throwable) diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/states/DefaultMetamaskState.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/states/DefaultMetamaskState.kt index 616475da..43ce5014 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/states/DefaultMetamaskState.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/states/DefaultMetamaskState.kt @@ -58,6 +58,11 @@ class DefaultMetamaskState( private val knownChains = mapOf(MetamaskChain.ETHEREUM.chainId to MetamaskChain.ETHEREUM) override suspend fun acceptRequest(request: MetamaskTransportRequest<*>, transition: StateMachineTransition) { + if (!isFromCurrentPage(request)) { + request.reject(MetamaskError.Rejected()) + return + } + when (request) { is MetamaskTransportRequest.RequestAccounts -> handleRequestAccounts(request, transition) is MetamaskTransportRequest.AddEthereumChain -> handleAddEthereumChain(request, transition) @@ -181,7 +186,7 @@ class DefaultMetamaskState( metamaskRequest: MetamaskTransportRequest, hostApiConfirmRequest: ExternalSignRequest.Evm ) { - when (val response = hostApi.confirmTx(hostApiConfirmRequest)) { + when (val response = hostApi.confirmTx(hostApiConfirmRequest, metamaskRequest.origin)) { is ConfirmTxResponse.Rejected -> metamaskRequest.reject(MetamaskError.Rejected()) is ConfirmTxResponse.Signed -> metamaskRequest.accept(response.signature) is ConfirmTxResponse.Sent -> metamaskRequest.accept(response.txHash) diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/transport/MetamaskInjector.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/transport/MetamaskInjector.kt index 86ffa6e7..321e9ae1 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/transport/MetamaskInjector.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/transport/MetamaskInjector.kt @@ -46,7 +46,7 @@ class MetamaskInjector( window.ethereum = new pezkuwi.Provider($providerConfigJson); window.web3 = new pezkuwi.Web3(window.ethereum); pezkuwi.postMessage = (jsonString) => { - ${jsInterfaceFullName(JS_INTERFACE_NAME)}.onNewMessage(JSON.stringify(jsonString)) + ${jsInterfaceFullName(JS_INTERFACE_NAME)}.postMessage(JSON.stringify(jsonString)) }; """.trimIndent() diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/transport/MetamaskTransport.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/transport/MetamaskTransport.kt index 2f5c997d..a8a0fc84 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/transport/MetamaskTransport.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/transport/MetamaskTransport.kt @@ -46,37 +46,37 @@ class MetamaskTransport( scope: CoroutineScope, ) : WebViewWeb3Transport>(scope, webViewWeb3JavaScriptInterface) { - override suspend fun messageToRequest(message: String): MetamaskTransportRequest<*>? = runCatching { + override suspend fun messageToRequest(message: String, origin: String): MetamaskTransportRequest<*>? = runCatching { val request = gson.fromJson(message) when (request.identifier) { MetamaskTransportRequest.Identifier.REQUEST_ACCOUNTS.id -> { - MetamaskTransportRequest.RequestAccounts(request.id, gson, responder) + MetamaskTransportRequest.RequestAccounts(request.id, origin, gson, responder) } MetamaskTransportRequest.Identifier.ADD_ETHEREUM_CHAIN.id -> { val chain = gson.fromParsedHierarchy(request.payload) - MetamaskTransportRequest.AddEthereumChain(request.id, gson, responder, chain) + MetamaskTransportRequest.AddEthereumChain(request.id, origin, gson, responder, chain) } MetamaskTransportRequest.Identifier.SWITCH_ETHEREUM_CHAIN.id -> { val switchChainRequest = gson.fromParsedHierarchy(request.payload) - MetamaskTransportRequest.SwitchEthereumChain(request.id, gson, responder, switchChainRequest.chainId) + MetamaskTransportRequest.SwitchEthereumChain(request.id, origin, gson, responder, switchChainRequest.chainId) } MetamaskTransportRequest.Identifier.SIGN_TRANSACTION.id -> { val transaction = gson.fromParsedHierarchy(request.payload) - MetamaskTransportRequest.SendTransaction(request.id, gson, responder, transaction) + MetamaskTransportRequest.SendTransaction(request.id, origin, gson, responder, transaction) } MetamaskTransportRequest.Identifier.SIGN_TYPED_MESSAGE.id -> { val typedMessage = gson.fromParsedHierarchy(request.payload) - MetamaskTransportRequest.SignTypedMessage(request.id, gson, responder, typedMessage) + MetamaskTransportRequest.SignTypedMessage(request.id, origin, gson, responder, typedMessage) } MetamaskTransportRequest.Identifier.PERSONAL_SIGN.id -> { val personalSignMessage = gson.fromParsedHierarchy(request.payload) - MetamaskTransportRequest.PersonalSign(request.id, gson, responder, personalSignMessage) + MetamaskTransportRequest.PersonalSign(request.id, origin, gson, responder, personalSignMessage) } else -> null } diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/transport/MetamaskTransportRequest.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/transport/MetamaskTransportRequest.kt index ef1cf6e0..3a37859c 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/transport/MetamaskTransportRequest.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/metamask/transport/MetamaskTransportRequest.kt @@ -12,6 +12,7 @@ import io.novafoundation.nova.feature_dapp_impl.web3.metamask.model.SignedMessag sealed class MetamaskTransportRequest( val id: String, + override val origin: String, private val gson: Gson, protected val responder: MetamaskResponder, ) : Web3Transport.Request { @@ -43,42 +44,48 @@ sealed class MetamaskTransportRequest( class RequestAccounts( id: String, + origin: String, gson: Gson, responder: MetamaskResponder - ) : MetamaskTransportRequest>(id, gson, responder) + ) : MetamaskTransportRequest>(id, origin, gson, responder) class AddEthereumChain( id: String, + origin: String, gson: Gson, responder: MetamaskResponder, val chain: MetamaskChain, - ) : MetamaskTransportRequest(id, gson, responder) + ) : MetamaskTransportRequest(id, origin, gson, responder) class SwitchEthereumChain( id: String, + origin: String, gson: Gson, responder: MetamaskResponder, val chainId: String - ) : MetamaskTransportRequest(id, gson, responder) + ) : MetamaskTransportRequest(id, origin, gson, responder) class SendTransaction( id: String, + origin: String, gson: Gson, responder: MetamaskResponder, val transaction: MetamaskTransaction - ) : MetamaskTransportRequest(id, gson, responder) + ) : MetamaskTransportRequest(id, origin, gson, responder) class SignTypedMessage( id: String, + origin: String, gson: Gson, responder: MetamaskResponder, val message: MetamaskTypedMessage - ) : MetamaskTransportRequest(id, gson, responder) + ) : MetamaskTransportRequest(id, origin, gson, responder) class PersonalSign( id: String, + origin: String, gson: Gson, responder: MetamaskResponder, val message: MetamaskPersonalSignMessage - ) : MetamaskTransportRequest(id, gson, responder) + ) : MetamaskTransportRequest(id, origin, gson, responder) } diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/PolkadotJsTransport.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/PolkadotJsTransport.kt index 250e4b6d..59e4efd2 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/PolkadotJsTransport.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/PolkadotJsTransport.kt @@ -7,6 +7,7 @@ import io.novafoundation.nova.common.utils.parseArbitraryObject import io.novafoundation.nova.feature_dapp_impl.web3.Web3Responder import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.model.mapRawPayloadToSignerPayloadJSON import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.model.mapRawPayloadToSignerPayloadRaw +import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.rpc.rpcCall import io.novafoundation.nova.feature_dapp_impl.web3.webview.WebViewWeb3JavaScriptInterface import io.novafoundation.nova.feature_dapp_impl.web3.webview.WebViewWeb3Transport import kotlinx.coroutines.CoroutineScope @@ -34,12 +35,13 @@ class PolkadotJsTransport( scope: CoroutineScope, ) : WebViewWeb3Transport>(scope, webViewWeb3JavaScriptInterface) { - override suspend fun messageToRequest(message: String): PolkadotJsTransportRequest<*>? { + override suspend fun messageToRequest(message: String, origin: String): PolkadotJsTransportRequest<*>? { Log.d(LOG_TAG, message) val parsedMessage = gson.parseArbitraryObject(message)!! - val url = parsedMessage["url"] as? String ?: return null + // The page writes its own url into the message; the WebView's word for the origin is used instead + val url = origin val requestId = parsedMessage["id"] as? String ?: return null return when (parsedMessage["msgType"]) { @@ -74,6 +76,24 @@ class PolkadotJsTransport( PolkadotJsTransportRequest.Identifier.PROVIDE_METADATA.id -> PolkadotJsTransportRequest.Single.ProvideMetadata(web3Responder, url, requestId) + PolkadotJsTransportRequest.Identifier.RPC_LIST_PROVIDERS.id -> + PolkadotJsTransportRequest.Rpc.ListProviders(web3Responder, url, requestId, gson) + + PolkadotJsTransportRequest.Identifier.RPC_START_PROVIDER.id -> (parsedMessage["request"] as? String)?.let { key -> + PolkadotJsTransportRequest.Rpc.StartProvider(web3Responder, url, requestId, key, gson) + } + + PolkadotJsTransportRequest.Identifier.RPC_SEND.id -> rpcCall(message)?.let { (method, params) -> + PolkadotJsTransportRequest.Rpc.Send(scope = this, web3Responder, url, requestId, method, params, gson) + } + + PolkadotJsTransportRequest.Identifier.RPC_SUBSCRIBE.id -> rpcCall(message)?.let { (method, params) -> + PolkadotJsTransportRequest.Rpc.Subscribe(scope = this, web3Responder, url, requestId, method, params, gson) + } + + PolkadotJsTransportRequest.Identifier.RPC_SUBSCRIBE_CONNECTED.id -> + PolkadotJsTransportRequest.Rpc.SubscribeConnected(scope = this, web3Responder, url, requestId) + else -> null } } diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/PolkadotJsTransportRequest.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/PolkadotJsTransportRequest.kt index cd0635e7..da4fcbd6 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/PolkadotJsTransportRequest.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/PolkadotJsTransportRequest.kt @@ -7,9 +7,11 @@ import io.novafoundation.nova.feature_dapp_impl.web3.Web3Transport import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.model.InjectedAccount import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.model.InjectedMetadataKnown import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.model.SignerPayload +import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.rpc.ProviderMeta import io.novafoundation.nova.feature_external_sign_api.model.signPayload.polkadot.PolkadotSignerResult import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach @@ -21,6 +23,9 @@ sealed class PolkadotJsTransportRequest( val requestId: String, ) : Web3Transport.Request { + /** [url] is the sender's origin as the WebView reported it; the page's own claim is not read. */ + override val origin: String get() = url + override fun reject(error: Throwable) { web3Responder.respondError(requestId, error) } @@ -33,6 +38,11 @@ sealed class PolkadotJsTransportRequest( LIST_METADATA("pub(metadata.list)"), PROVIDE_METADATA("pub(metadata.provide)"), SIGN_BYTES("pub(bytes.sign)"), + RPC_LIST_PROVIDERS("pub(rpc.listProviders)"), + RPC_START_PROVIDER("pub(rpc.startProvider)"), + RPC_SEND("pub(rpc.send)"), + RPC_SUBSCRIBE("pub(rpc.subscribe)"), + RPC_SUBSCRIBE_CONNECTED("pub(rpc.subscribeConnected)"), } sealed class Single( @@ -126,6 +136,95 @@ sealed class PolkadotJsTransportRequest( } } + /** The provider half of the extension API: the page's chain calls, answered over the wallet's connection. */ + sealed class Rpc( + web3Responder: Web3Responder, + url: String, + identifier: Identifier, + requestId: String, + ) : PolkadotJsTransportRequest(web3Responder, identifier, url, requestId) { + + class ListProviders( + web3Responder: Web3Responder, + url: String, + requestId: String, + private val gson: Gson, + ) : Rpc>(web3Responder, url, Identifier.RPC_LIST_PROVIDERS, requestId) { + + override fun accept(response: Map) { + web3Responder.respondResult(requestId, gson.toJson(response)) + } + } + + class StartProvider( + web3Responder: Web3Responder, + url: String, + requestId: String, + val key: String, + private val gson: Gson, + ) : Rpc(web3Responder, url, Identifier.RPC_START_PROVIDER, requestId) { + + override fun accept(response: ProviderMeta) { + web3Responder.respondResult(requestId, gson.toJson(response)) + } + } + + /** Answered off the request queue: a slow node must not hold up the page's other calls. */ + class Send( + val scope: CoroutineScope, + web3Responder: Web3Responder, + url: String, + requestId: String, + val method: String, + val params: List, + private val gson: Gson, + ) : Rpc(web3Responder, url, Identifier.RPC_SEND, requestId) { + + override fun accept(response: Any?) { + web3Responder.respondResult(requestId, gson.toJson(response)) + } + } + + /** Answers with a subscription id, then sends each notification's result to the page's callback. */ + class Subscribe( + private val scope: CoroutineScope, + web3Responder: Web3Responder, + url: String, + requestId: String, + val method: String, + val params: List, + private val gson: Gson, + ) : Rpc>(web3Responder, url, Identifier.RPC_SUBSCRIBE, requestId) { + + override fun accept(response: Flow) { + web3Responder.respondResult(requestId, gson.toJson(requestId)) + + response + .onEach { web3Responder.respondSubscription(requestId, gson.toJson(it)) } + .catch { web3Responder.respondError(requestId, it) } + .inBackground() + .launchIn(scope) + } + } + + class SubscribeConnected( + private val scope: CoroutineScope, + web3Responder: Web3Responder, + url: String, + requestId: String, + ) : Rpc>(web3Responder, url, Identifier.RPC_SUBSCRIBE_CONNECTED, requestId) { + + override fun accept(response: Flow) { + web3Responder.respondResult(requestId, "true") + + response + .onEach { web3Responder.respondSubscription(requestId, it.toString()) } + .inBackground() + .launchIn(scope) + } + } + } + sealed class Subscription( private val scope: CoroutineScope, requestId: String, diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/ChainRegistryRpc.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/ChainRegistryRpc.kt new file mode 100644 index 00000000..30ae651e --- /dev/null +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/ChainRegistryRpc.kt @@ -0,0 +1,29 @@ +package io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.rpc + +import io.novafoundation.nova.runtime.multiNetwork.ChainRegistry +import io.novafoundation.nova.runtime.multiNetwork.chain.model.ChainId +import io.novafoundation.nova.runtime.multiNetwork.getSocket +import io.novasama.substrate_sdk_android.wsrpc.executeAsync +import io.novasama.substrate_sdk_android.wsrpc.request.runtime.RuntimeRequest +import io.novasama.substrate_sdk_android.wsrpc.subscriptionFlow +import kotlinx.coroutines.channels.awaitClose +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.channelFlow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch + +/** Over each chain's own connection, which moves to the light client when its RPC nodes fail. */ +class ChainRegistryRpc(private val chainRegistry: ChainRegistry) : ChainRpc { + + override suspend fun send(chainId: ChainId, method: String, params: List): Any? { + val response = chainRegistry.getSocket(chainId).executeAsync(RuntimeRequest(method, params)) + response.error?.let { throw RpcBridgeException(it.message) } + return response.result + } + + override fun subscribe(chainId: ChainId, method: String, params: List, unsubscribeMethod: String): Flow = channelFlow { + val socket = chainRegistry.getSocket(chainId) + launch { socket.subscriptionFlow(RuntimeRequest(method, params), unsubscribeMethod).map { it.params.result }.collect { send(it) } } + awaitClose() + } +} diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/PolkadotJsRpcBridge.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/PolkadotJsRpcBridge.kt new file mode 100644 index 00000000..c8bb5c19 --- /dev/null +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/PolkadotJsRpcBridge.kt @@ -0,0 +1,114 @@ +package io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.rpc + +import io.novafoundation.nova.feature_dapp_impl.web3.webview.WebViewWeb3JavaScriptInterface +import io.novafoundation.nova.runtime.ext.ChainGeneses +import io.novafoundation.nova.runtime.multiNetwork.chain.model.ChainId +import io.novafoundation.nova.runtime.multiNetwork.connection.light.LightClients +import io.novafoundation.nova.runtime.names.KurdName +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.channelFlow +import kotlinx.coroutines.launch +import java.net.URI + +/** polkadot-js `ProviderMeta`, what `pub(rpc.listProviders)` and `pub(rpc.startProvider)` describe. */ +class ProviderMeta(val network: String, val node: String, val source: String, val transport: String) + +class RpcBridgeException(message: String) : Exception(message) + +/** The chain connections the bridge forwards to. */ +interface ChainRpc { + + suspend fun send(chainId: ChainId, method: String, params: List): Any? + + fun subscribe(chainId: ChainId, method: String, params: List, unsubscribeMethod: String): Flow +} + +/** + * The provider half of the polkadot-js extension API (`pub(rpc.*)`), for one tab. A `.kurd` page + * may not open connections of its own (the wallet's policy allows only its own name), so this is + * how it reaches the chain: over the wallet's connection, which falls back to the light client. + * Only methods that read state or submit an already signed extrinsic pass. + */ +class PolkadotJsRpcBridge(private val rpc: ChainRpc) { + + private var started: ChainId? = null + + fun providers(): Map = PROVIDERS.mapValues { (_, provider) -> provider.meta } + + fun start(key: String): ProviderMeta { + val provider = PROVIDERS[key] ?: throw RpcBridgeException("Unknown provider $key") + started = provider.chainId + return provider.meta + } + + suspend fun send(method: String, params: List): Any? { + if (method !in CALLS) throw RpcBridgeException("Method $method is not available") + return rpc.send(startedChain(), method, params) + } + + fun subscribe(method: String, params: List): Flow { + val unsubscribe = SUBSCRIPTIONS[method] ?: throw RpcBridgeException("Subscription $method is not available") + return rpc.subscribe(startedChain(), method, params, unsubscribe) + } + + private fun startedChain(): ChainId = started ?: throw RpcBridgeException("No provider started") + + private class Provider(val chainId: ChainId, val meta: ProviderMeta) + + companion object { + + private const val SOURCE = "pezkuwi-wallet" + + private const val ZAGROS_ASSET_HUB: ChainId = "063f739077881df9f291548de301b2e11d6a45cc545c24e7bf18d8a40f0ce182" + + private fun provider(chainId: ChainId, network: String): Provider { + return Provider(chainId, ProviderMeta(network, node = "full", source = SOURCE, transport = "WsProvider")) + } + + private val PROVIDERS = mapOf( + "pezkuwi" to provider(ChainGeneses.PEZKUWI, "Pezkuwi"), + "pezkuwi-asset-hub" to provider(ChainGeneses.PEZKUWI_ASSET_HUB, "Pezkuwi Asset Hub"), + "pezkuwi-people" to provider(ChainGeneses.PEZKUWI_PEOPLE, "Pezkuwi People"), + "zagros" to provider(LightClients.ZAGROS, "Zagros"), + "zagros-asset-hub" to provider(ZAGROS_ASSET_HUB, "Zagros Asset Hub"), + "zagros-people" to provider(LightClients.ZAGROS_PEOPLE, "Zagros People"), + ) + + /** Reads, fee estimates and submitting an extrinsic the user already signed in the wallet. */ + internal val CALLS = setOf( + "chain_getBlock", "chain_getBlockHash", "chain_getFinalizedHead", "chain_getHeader", + "state_call", "state_getKeysPaged", "state_getMetadata", "state_getRuntimeVersion", "state_getStorage", + "state_getStorageHash", "state_getStorageSize", "state_queryStorageAt", "state_getReadProof", + "system_accountNextIndex", "system_chain", "system_chainType", "system_health", "system_name", + "system_properties", "system_version", "rpc_methods", + "payment_queryInfo", "payment_queryFeeDetails", + "author_submitExtrinsic", + ) + + /** Subscriptions, each with the call that ends it. */ + internal val SUBSCRIPTIONS = mapOf( + "chain_subscribeNewHeads" to "chain_unsubscribeNewHeads", + "chain_subscribeFinalizedHeads" to "chain_unsubscribeFinalizedHeads", + "chain_subscribeAllHeads" to "chain_unsubscribeAllHeads", + "state_subscribeStorage" to "state_unsubscribeStorage", + "state_subscribeRuntimeVersion" to "state_unsubscribeRuntimeVersion", + "author_submitAndWatchExtrinsic" to "author_unwatchExtrinsic", + ) + } +} + +/** True when [pageUrl] is on a `.kurd` host. */ +fun isKurdPage(pageUrl: String): Boolean = KurdName.isKurdHost(runCatching { URI(pageUrl).host }.getOrNull()) + +fun sameOrigin(first: String, second: String): Boolean = WebViewWeb3JavaScriptInterface.sameOrigin(first, second) + +/** This flow until [signal] returns, then it completes and its upstream is cancelled. */ +fun Flow.until(signal: suspend () -> Unit): Flow = channelFlow { + val collector = launch { collect { send(it) } } + val watcher = launch { + signal() + collector.cancel() + } + collector.join() + watcher.cancel() +} diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/RpcCall.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/RpcCall.kt new file mode 100644 index 00000000..e0e216e5 --- /dev/null +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/RpcCall.kt @@ -0,0 +1,23 @@ +package io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.rpc + +import com.google.gson.JsonArray +import com.google.gson.JsonElement +import com.google.gson.JsonNull +import com.google.gson.JsonParser + +/** + * `{method, params}` of an RPC request in [message], or null when the page sent something else. + * Params stay JSON as the page wrote them: parsed into Kotlin values a block number would reach + * the node as `123.0`. + */ +fun rpcCall(message: String): Pair>? { + val request = runCatching { JsonParser.parseString(message).asJsonObject.get("request") }.getOrNull() + ?.takeIf { it.isJsonObject }?.asJsonObject ?: return null + val method = request.get("method")?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isString }?.asString ?: return null + val params = when (val raw = request.get("params")) { + null, is JsonNull -> emptyList() + is JsonArray -> raw.toList() + else -> return null + } + return method to params +} diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/states/DefaultPolkadotJsState.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/states/DefaultPolkadotJsState.kt index 5a190e25..633f50b1 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/states/DefaultPolkadotJsState.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/states/DefaultPolkadotJsState.kt @@ -8,6 +8,10 @@ import io.novafoundation.nova.feature_dapp_impl.domain.DappInteractor import io.novafoundation.nova.feature_dapp_impl.domain.browser.polkadotJs.PolkadotJsExtensionInteractor import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.PolkadotJsTransportRequest import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.model.mapPolkadotJsSignerPayloadToPolkadotPayload +import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.rpc.PolkadotJsRpcBridge +import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.rpc.isKurdPage +import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.rpc.sameOrigin +import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.rpc.until import io.novafoundation.nova.feature_dapp_impl.web3.session.Web3Session import io.novafoundation.nova.feature_dapp_impl.web3.states.BaseState import io.novafoundation.nova.feature_dapp_impl.web3.states.Web3ExtensionStateMachine.ExternalEvent @@ -17,7 +21,9 @@ import io.novafoundation.nova.feature_dapp_impl.web3.states.Web3StateMachineHost import io.novafoundation.nova.feature_dapp_impl.web3.states.hostApi.ConfirmTxResponse import io.novafoundation.nova.feature_external_sign_api.model.signPayload.ExternalSignRequest import io.novafoundation.nova.feature_external_sign_api.model.signPayload.polkadot.PolkadotSignerResult +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.launch class DefaultPolkadotJsState( private val interactor: PolkadotJsExtensionInteractor, @@ -27,6 +33,7 @@ class DefaultPolkadotJsState( web3Session: Web3Session, hostApi: Web3StateMachineHost, walletUiUseCase: WalletUiUseCase, + private val rpcBridge: PolkadotJsRpcBridge, ) : BaseState, PolkadotJsState>( commonInteractor = commonInteractor, resourceManager = resourceManager, @@ -38,6 +45,11 @@ class DefaultPolkadotJsState( PolkadotJsState { override suspend fun acceptRequest(request: PolkadotJsTransportRequest<*>, transition: StateMachineTransition) { + if (!isFromCurrentPage(request)) { + request.reject(NotAuthorizedException) + return + } + when (request) { is PolkadotJsTransportRequest.Single.AuthorizeTab -> authorizeTab(request) is PolkadotJsTransportRequest.Single.ListAccounts -> supplyAccountList(request) @@ -45,6 +57,7 @@ class DefaultPolkadotJsState( is PolkadotJsTransportRequest.Subscription.SubscribeAccounts -> supplyAccountListSubscription(request) is PolkadotJsTransportRequest.Single.ListMetadata -> suppleKnownMetadatas(request) is PolkadotJsTransportRequest.Single.ProvideMetadata -> handleProvideMetadata(request) + is PolkadotJsTransportRequest.Rpc<*> -> handleRpc(request) } } @@ -72,7 +85,7 @@ class DefaultPolkadotJsState( private suspend fun signExtrinsicWithConfirmation(request: PolkadotJsTransportRequest.Single.Sign) { val signRequest = ExternalSignRequest.Polkadot(request.requestId, mapPolkadotJsSignerPayloadToPolkadotPayload(request.signerPayload)) - when (val response = hostApi.confirmTx(signRequest)) { + when (val response = hostApi.confirmTx(signRequest, request.origin)) { is ConfirmTxResponse.Rejected -> request.reject(NotAuthorizedException) is ConfirmTxResponse.Sent -> throw IllegalStateException("Unexpected 'Sent' response for PolkadotJs extension") is ConfirmTxResponse.Signed -> request.accept(PolkadotSignerResult(response.requestId, response.signature, response.modifiedTransaction)) @@ -93,6 +106,36 @@ class DefaultPolkadotJsState( } } + /** + * Chain calls are offered to `.kurd` pages only, judged by the page the tab shows rather than + * anything the page says: elsewhere a page opens its own connections. A subscription ends when + * the tab leaves the page's origin. + */ + private suspend fun handleRpc(request: PolkadotJsTransportRequest.Rpc<*>) { + val pageUrl = hostApi.currentPageAnalyzed.first().url + if (!isKurdPage(pageUrl)) { + if (request is PolkadotJsTransportRequest.Rpc.ListProviders) request.accept(emptyMap()) else request.reject(NotAuthorizedException) + return + } + + runCatching { + when (request) { + is PolkadotJsTransportRequest.Rpc.ListProviders -> request.accept(rpcBridge.providers()) + is PolkadotJsTransportRequest.Rpc.StartProvider -> request.accept(rpcBridge.start(request.key)) + is PolkadotJsTransportRequest.Rpc.Send -> request.scope.launch { + runCatching { rpcBridge.send(request.method, request.params) } + .onSuccess(request::accept) + .onFailure(request::reject) + } + is PolkadotJsTransportRequest.Rpc.Subscribe -> { + val updates = rpcBridge.subscribe(request.method, request.params) + request.accept(updates.until { hostApi.currentPageAnalyzed.first { !sameOrigin(it.url, pageUrl) } }) + } + is PolkadotJsTransportRequest.Rpc.SubscribeConnected -> request.accept(flowOf(true)) + } + }.onFailure(request::reject) + } + private suspend fun handleProvideMetadata(request: PolkadotJsTransportRequest.Single.ProvideMetadata) = request.respondIfAllowed { false // we do not accept provided metadata since app handles metadata sync by its own } diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/states/PolkadotJsStateFactory.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/states/PolkadotJsStateFactory.kt index 5d828f42..0df70c4f 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/states/PolkadotJsStateFactory.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/states/PolkadotJsStateFactory.kt @@ -5,6 +5,8 @@ import io.novafoundation.nova.common.resources.ResourceManager import io.novafoundation.nova.feature_account_api.presenatation.account.wallet.WalletUiUseCase import io.novafoundation.nova.feature_dapp_impl.domain.DappInteractor import io.novafoundation.nova.feature_dapp_impl.domain.browser.polkadotJs.PolkadotJsExtensionInteractor +import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.rpc.ChainRpc +import io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.rpc.PolkadotJsRpcBridge import io.novafoundation.nova.feature_dapp_impl.web3.session.Web3Session import io.novafoundation.nova.feature_dapp_impl.web3.states.Web3StateMachineHost @@ -15,6 +17,7 @@ class PolkadotJsStateFactory( private val addressIconGenerator: AddressIconGenerator, private val web3Session: Web3Session, private val walletUiUseCase: WalletUiUseCase, + private val chainRpc: ChainRpc, ) { fun default(hostApi: Web3StateMachineHost): DefaultPolkadotJsState { @@ -25,7 +28,8 @@ class PolkadotJsStateFactory( addressIconGenerator = addressIconGenerator, web3Session = web3Session, hostApi = hostApi, - walletUiUseCase = walletUiUseCase + walletUiUseCase = walletUiUseCase, + rpcBridge = PolkadotJsRpcBridge(chainRpc), ) } } diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/states/BaseState.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/states/BaseState.kt index 90475566..0e3c221f 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/states/BaseState.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/states/BaseState.kt @@ -6,6 +6,7 @@ import io.novafoundation.nova.feature_account_api.presenatation.account.wallet.W import io.novafoundation.nova.feature_dapp_impl.domain.DappInteractor import io.novafoundation.nova.feature_dapp_impl.web3.Web3Transport import io.novafoundation.nova.feature_dapp_impl.web3.session.Web3Session +import io.novafoundation.nova.feature_dapp_impl.web3.webview.WebViewWeb3JavaScriptInterface import io.novafoundation.nova.feature_external_sign_api.presentation.externalSign.AuthorizeDappBottomSheet import kotlinx.coroutines.flow.first @@ -74,4 +75,13 @@ abstract class BaseState, S>( return authorizationState == Web3Session.Authorization.State.ALLOWED } + + /** + * True while the tab still shows the page that sent [request]. Requests are handled one at a + * time, so a page could otherwise ask and navigate away, leaving its request to be judged as + * the next page's. + */ + protected suspend fun isFromCurrentPage(request: R): Boolean { + return WebViewWeb3JavaScriptInterface.sameOrigin(request.origin, hostApi.currentPageAnalyzed.first().url) + } } diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/states/Web3ExtensionStateMachine.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/states/Web3ExtensionStateMachine.kt index 05b054cb..4767e473 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/states/Web3ExtensionStateMachine.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/states/Web3ExtensionStateMachine.kt @@ -50,7 +50,9 @@ interface Web3StateMachineHost { val externalEvents: Flow suspend fun authorizeDApp(payload: AuthorizeDappBottomSheet.Payload): Web3Session.Authorization.State - suspend fun confirmTx(request: ExternalSignRequest): ConfirmTxResponse + + /** [origin]: the page that asked, which must still be the page shown. */ + suspend fun confirmTx(request: ExternalSignRequest, origin: String): ConfirmTxResponse fun showError(text: String) diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/Web3WebViewClient.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/Web3WebViewClient.kt index a3b7b196..9150276e 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/Web3WebViewClient.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/Web3WebViewClient.kt @@ -2,9 +2,15 @@ package io.novafoundation.nova.feature_dapp_impl.web3.webview import android.graphics.Bitmap import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse import android.webkit.WebSettings import android.webkit.WebView import android.webkit.WebViewClient +import io.novafoundation.nova.runtime.names.KurdName +import io.novafoundation.nova.runtime.names.content.KurdSiteServer +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import java.io.ByteArrayInputStream interface PageCallback { @@ -19,7 +25,8 @@ interface PageCallback { class Web3WebViewClient( private val webView: WebView, - private val pageCallback: PageCallback + private val pageCallback: PageCallback, + private val kurdSiteServer: KurdSiteServer, ) : WebViewClient() { var desktopMode: Boolean = false @@ -40,6 +47,40 @@ class Web3WebViewClient( return super.shouldOverrideUrlLoading(view, request) } + /** + * Every request to a `.kurd` host -- a page, a frame, an image a page embeds -- ends here, before + * the network: such a host is a name on chain, and asking system DNS for it would tell the + * network which site the reader opens. The wallet serves it from verified content instead. + * `loadUrl` reaches this hook too, unlike [shouldOverrideUrlLoading]. Called off the main thread. + */ + override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? { + val host = request.url.host + if (!KurdName.isKurdHost(host)) return null + + if (request.method != "GET" || host == null) return emptyResponse(405, "Method Not Allowed") + + val response = runCatching { + runBlocking { + withTimeout(KURD_REQUEST_TIMEOUT_MILLIS) { + kurdSiteServer.serve(host, request.url.encodedPath.orEmpty(), mainFrame = request.isForMainFrame) + } + } + }.getOrNull() ?: return emptyResponse(504, "Gateway Timeout") + + return WebResourceResponse( + response.mimeType, + if (response.mimeType.startsWith("text/")) "utf-8" else null, + response.status, + response.reason, + response.headers, + ByteArrayInputStream(response.body) + ) + } + + private fun emptyResponse(status: Int, reason: String): WebResourceResponse { + return WebResourceResponse("text/plain", "utf-8", status, reason, emptyMap(), ByteArrayInputStream(ByteArray(0))) + } + override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) { pageCallback.onPageStarted(view, url, favicon) if (desktopMode) { @@ -70,6 +111,9 @@ class Web3WebViewClient( } } +/** A cold light client plus a gateway round trip, with room to spare. */ +private const val KURD_REQUEST_TIMEOUT_MILLIS = 60_000L + private fun WebView.changeUserAgentByDesktopMode(desktopMode: Boolean) { val defaultUserAgent = WebSettings.getDefaultUserAgent(context) diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewScriptInjector.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewScriptInjector.kt index b5e1e99d..b9c26500 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewScriptInjector.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewScriptInjector.kt @@ -1,8 +1,12 @@ package io.novafoundation.nova.feature_dapp_impl.web3.webview +import android.util.Log import android.webkit.WebView import androidx.annotation.RawRes +import androidx.webkit.WebViewCompat +import androidx.webkit.WebViewFeature import io.novafoundation.nova.common.resources.ResourceManager +import io.novafoundation.nova.common.utils.LOG_TAG private const val JAVASCRIPT_INTERFACE_PREFIX = "Pezkuwi" @@ -19,12 +23,24 @@ class WebViewScriptInjector( private val scriptCache: MutableMap = mutableMapOf() + /** + * Exposes `postMessage` to page scripts under the interface name. Through a web message listener + * rather than `addJavascriptInterface`, so each message arrives with its origin and frame; on a + * WebView too old to say, the bridge stays off rather than trusting the page. + */ fun injectJsInterface( into: WebView, jsInterface: WebViewWeb3JavaScriptInterface, interfaceName: String ) { - into.addJavascriptInterface(jsInterface, jsInterfaceFullName(interfaceName)) + if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) { + Log.w(LOG_TAG, "WebView cannot tell where a message came from; DApp bridge $interfaceName stays off") + return + } + + WebViewCompat.addWebMessageListener(into, jsInterfaceFullName(interfaceName), setOf("*")) { view, message, sourceOrigin, isMainFrame, _ -> + message.data?.let { jsInterface.onMessage(view, it, sourceOrigin, isMainFrame) } + } } fun injectScript( diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewWeb3JavaScriptInterface.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewWeb3JavaScriptInterface.kt index ef0f02ed..a94cc879 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewWeb3JavaScriptInterface.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewWeb3JavaScriptInterface.kt @@ -1,20 +1,58 @@ package io.novafoundation.nova.feature_dapp_impl.web3.webview +import android.net.Uri import android.util.Log -import android.webkit.JavascriptInterface +import android.webkit.WebView import io.novafoundation.nova.common.utils.LOG_TAG import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow +import java.net.URI +/** + * Receives what the bundled bridge scripts post. The WebView, not the page, says where a message + * came from: only the top frame of the page the tab is showing is heard, so a third-party frame + * inside an authorised DApp cannot ask for accounts or signatures in that DApp's name. + */ class WebViewWeb3JavaScriptInterface { - private val _messages = MutableSharedFlow(extraBufferCapacity = 3) - val messages: Flow = _messages + /** A bridge message and the origin of the page that sent it. */ + class Message(val json: String, val origin: String) - @JavascriptInterface - fun onNewMessage(message: String) { - Log.d(LOG_TAG, message) + private val _messages = MutableSharedFlow(extraBufferCapacity = 3) + val messages: Flow = _messages - _messages.tryEmit(message) + /** Called on the main thread, with the sender's origin and frame as the WebView knows them. */ + fun onMessage(view: WebView, message: String, sourceOrigin: Uri, isMainFrame: Boolean) { + val origin = originOf(sourceOrigin.toString()) + if (origin == null || !isFromShownPage(view.url, sourceOrigin.toString(), isMainFrame)) { + Log.w(LOG_TAG, "Ignoring a bridge message from $sourceOrigin, main frame $isMainFrame, page ${view.url}") + return + } + + _messages.tryEmit(Message(message, origin)) + } + + companion object { + + /** True for a message from the top frame whose origin is the origin of [pageUrl]. */ + fun isFromShownPage(pageUrl: String?, sourceOrigin: String, isMainFrame: Boolean): Boolean { + if (!isMainFrame) return false + val page = originOf(pageUrl ?: return false) ?: return false + return page == originOf(sourceOrigin) + } + + fun sameOrigin(first: String, second: String): Boolean { + val one = originOf(first) ?: return false + return one == originOf(second) + } + + /** `scheme://host[:port]`, lower-cased, default ports dropped; null for an opaque or host-less URL. */ + internal fun originOf(url: String): String? { + val uri = runCatching { URI(url) }.getOrNull() ?: return null + val scheme = uri.scheme?.lowercase() ?: return null + val host = uri.host?.lowercase() ?: return null + val port = uri.port.takeUnless { it == -1 || (scheme == "https" && it == 443) || (scheme == "http" && it == 80) } + return "$scheme://$host" + (port?.let { ":$it" } ?: "") + } } } diff --git a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewWeb3Transport.kt b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewWeb3Transport.kt index 639ef81e..372a9932 100644 --- a/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewWeb3Transport.kt +++ b/feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewWeb3Transport.kt @@ -13,8 +13,9 @@ abstract class WebViewWeb3Transport>( CoroutineScope by scope { override val requestsFlow = webViewWeb3JavaScriptInterface.messages - .mapNotNull(::messageToRequest) + .mapNotNull { messageToRequest(it.json, it.origin) } .shareIn(this, started = SharingStarted.Eagerly) - protected abstract suspend fun messageToRequest(message: String): R? + /** [origin]: where the message came from, as the WebView reported it. */ + protected abstract suspend fun messageToRequest(message: String, origin: String): R? } diff --git a/feature-dapp-impl/src/main/res/layout/fragment_dapp_browser.xml b/feature-dapp-impl/src/main/res/layout/fragment_dapp_browser.xml index cbebfc80..63b6457b 100644 --- a/feature-dapp-impl/src/main/res/layout/fragment_dapp_browser.xml +++ b/feature-dapp-impl/src/main/res/layout/fragment_dapp_browser.xml @@ -59,6 +59,47 @@ app:layout_constraintBottom_toTopOf="@+id/dappBrowserBottomNavigation" app:layout_constraintTop_toBottomOf="@+id/dappBrowserAddressBarGroup" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/feature-dapp-impl/src/main/res/layout/sheet_kurd_lookalike.xml b/feature-dapp-impl/src/main/res/layout/sheet_kurd_lookalike.xml new file mode 100644 index 00000000..d8f1aa90 --- /dev/null +++ b/feature-dapp-impl/src/main/res/layout/sheet_kurd_lookalike.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/feature-dapp-impl/src/main/res/layout/view_address_bar.xml b/feature-dapp-impl/src/main/res/layout/view_address_bar.xml index 60f9e778..e1612cc0 100644 --- a/feature-dapp-impl/src/main/res/layout/view_address_bar.xml +++ b/feature-dapp-impl/src/main/res/layout/view_address_bar.xml @@ -31,4 +31,18 @@ android:singleLine="true" android:textColor="@color/text_primary" tools:text="polkadot.js.org" /> + + \ No newline at end of file diff --git a/feature-dapp-impl/src/main/res/layout/view_kurd_notice.xml b/feature-dapp-impl/src/main/res/layout/view_kurd_notice.xml new file mode 100644 index 00000000..0c5148ba --- /dev/null +++ b/feature-dapp-impl/src/main/res/layout/view_kurd_notice.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + diff --git a/feature-dapp-impl/src/main/res/raw/javascript_interface_bridge.js b/feature-dapp-impl/src/main/res/raw/javascript_interface_bridge.js index 71227250..fa271433 100644 --- a/feature-dapp-impl/src/main/res/raw/javascript_interface_bridge.js +++ b/feature-dapp-impl/src/main/res/raw/javascript_interface_bridge.js @@ -9,6 +9,6 @@ window.addEventListener("message", ({ data, source }) => { if (data.origin === "dapp-request") { // should be in tact with PolkadotJsExtension.kt - Pezkuwi_PolkadotJs.onNewMessage(dataJson) + Pezkuwi_PolkadotJs.postMessage(dataJson) } }); \ No newline at end of file diff --git a/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/domain/search/SearchDappInteractorTest.kt b/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/domain/search/SearchDappInteractorTest.kt new file mode 100644 index 00000000..ade81b33 --- /dev/null +++ b/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/domain/search/SearchDappInteractorTest.kt @@ -0,0 +1,46 @@ +package io.novafoundation.nova.feature_dapp_impl.domain.search + +import io.novafoundation.nova.feature_dapp_api.data.model.DappCatalog +import io.novafoundation.nova.feature_dapp_api.data.repository.DAppMetadataRepository +import io.novafoundation.nova.feature_dapp_impl.data.model.FavouriteDApp +import io.novafoundation.nova.feature_dapp_impl.data.repository.FavouritesDAppRepository +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Test +import org.mockito.Mockito.mock + +class SearchDappInteractorTest { + + private val catalog = object : DAppMetadataRepository by mock(DAppMetadataRepository::class.java) { + override suspend fun getDAppCatalog() = DappCatalog(popular = emptyList(), categories = emptyList(), dApps = emptyList()) + } + + private val favourites = object : FavouritesDAppRepository by mock(FavouritesDAppRepository::class.java) { + override suspend fun getFavourites() = emptyList() + } + + private val interactor = SearchDappInteractor(catalog, favourites) + + @Test + fun `a kurd name is never offered as a web address or a search`() = runBlocking { + listOf("dks.kurd", "Serok.Gov.Kurd", "https://dks.kurd/path", "dks_news.kurd", "uni-x--edu.kurd").forEach { query -> + val results = interactor.searchDapps(query, categoryId = null) + + assertEquals(query, null, results[DappSearchGroup.SEARCH]) + } + } + + @Test + fun `a valid kurd name is offered as the name itself`() = runBlocking { + val offered = interactor.searchDapps("https://Serok.Gov.Kurd/", categoryId = null)[DappSearchGroup.KURD_NAME]!!.single() + + assertEquals("https://serok.gov.kurd/", (offered as DappSearchResult.KurdName).url) + } + + @Test + fun `an invalid kurd name is offered nowhere`() = runBlocking { + listOf("uni-x--edu.kurd", "dks_news.kurd", "a.b.c.d.e.kurd").forEach { query -> + assertEquals(query, emptyMap>(), interactor.searchDapps(query, categoryId = null)) + } + } +} diff --git a/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/kurd/KurdPageUiTest.kt b/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/kurd/KurdPageUiTest.kt new file mode 100644 index 00000000..299637d8 --- /dev/null +++ b/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/kurd/KurdPageUiTest.kt @@ -0,0 +1,87 @@ +package io.novafoundation.nova.feature_dapp_impl.presentation.browser.main.kurd + +import io.novafoundation.nova.runtime.names.KurdName +import io.novafoundation.nova.runtime.names.KurdResolution +import io.novafoundation.nova.runtime.names.NameRecord +import io.novafoundation.nova.runtime.names.NameStatus +import io.novafoundation.nova.runtime.names.content.Cid +import io.novafoundation.nova.runtime.names.content.KurdSiteServer.PageState +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class KurdPageUiTest { + + private val name = KurdName.parse("dks.kurd")!! + private val root = Cid.parse(byteArrayOf(0x01, 0x55, 0x12, 0x20) + ByteArray(32) { 7 }) + + @Test + fun `the badge says what was verified`() { + assertEquals(KurdPageUi.Badge.OFFICIAL, badgeOf(granted(), verified = true)) + assertEquals(KurdPageUi.Badge.REGISTERED, badgeOf(leased(), verified = true)) + // An unverified name never shows as official, whatever its record claims + assertEquals(KurdPageUi.Badge.UNVERIFIED, badgeOf(granted(), verified = false)) + } + + @Test + fun `a block is shown only for a proof`() { + val proven = open(leased(), verified = true, block = 1_284_551) + val reported = open(leased(), verified = false, block = 1_284_551) + + assertEquals(1_284_551L, proven.details.provenAtBlock) + assertNull(reported.details.provenAtBlock) + } + + @Test + fun `an office or Parliament owns as an institution, a person as an account`() { + assertTrue(open(granted(), verified = true).details.owner is KurdPageUi.Owner.Institution) + assertTrue(open(leased(), verified = true).details.owner is KurdPageUi.Owner.Account) + } + + @Test + fun `each state that is not a page is a notice`() { + val resolved = KurdResolution.Resolved(name, leased(), NameStatus.ACTIVE, verified = false) + + assertEquals(KurdPageUi.NoticeKind.NEEDS_CONSENT, noticeOf(PageState.NeedsConsent(resolved))) + assertEquals(KurdPageUi.NoticeKind.REFUSED, noticeOf(PageState.Refused)) + assertEquals(KurdPageUi.NoticeKind.NOT_REGISTERED, noticeOf(PageState.NotRegistered)) + assertEquals(KurdPageUi.NoticeKind.NO_SITE, noticeOf(PageState.NoSite)) + assertEquals(KurdPageUi.NoticeKind.UNAVAILABLE, noticeOf(PageState.Unavailable)) + assertNull(KurdPageUi.from(name, null)) + } + + @Test + fun `a feed showing the chain's version says so`() { + val resolution = KurdResolution.Resolved(name, leased(), NameStatus.ACTIVE, verified = true) + + assertTrue((KurdPageUi.from(name, PageState.Open(resolution, root, onChainVersion = true)) as KurdPageUi.Open).onChainVersion) + assertTrue(!(KurdPageUi.from(name, PageState.Open(resolution, root)) as KurdPageUi.Open).onChainVersion) + } + + @Test + fun `only pages on a kurd host have a name`() { + assertEquals("serok.gov.kurd", KurdPageUi.nameOf("https://serok.gov.kurd/news?x=1")!!.name) + assertNull(KurdPageUi.nameOf("https://dks.kurd.example.com/")) + assertNull(KurdPageUi.nameOf("https://app.pezkuwichain.io/")) + assertNull(KurdPageUi.nameOf(null)) + } + + private fun badgeOf(record: NameRecord, verified: Boolean) = open(record, verified).badge + + private fun open(record: NameRecord, verified: Boolean, block: Long? = null): KurdPageUi.Open { + val resolution = KurdResolution.Resolved(name, record, NameStatus.ACTIVE, verified, block) + return KurdPageUi.from(name, PageState.Open(resolution, root)) as KurdPageUi.Open + } + + private fun noticeOf(state: PageState) = (KurdPageUi.from(name, state) as KurdPageUi.Notice).kind + + private fun granted() = record(NameRecord.Owner.Governance, NameRecord.Kind.GRANTED, locked = true) + + private fun leased() = record(NameRecord.Owner.Account(ByteArray(32)), NameRecord.Kind.LEASED, locked = false) + + private fun record(owner: NameRecord.Owner, kind: NameRecord.Kind, locked: Boolean) = NameRecord( + label = "dks", parent = KurdName.KURD_NODE, parentReg = 0, reg = 1, owner = owner, kind = kind, + lockedTransfer = locked, expiry = null, account = null, content = null, + ) +} diff --git a/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/PolkadotJsBridgeTest.kt b/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/PolkadotJsBridgeTest.kt index 74a1a4e3..6aeb480a 100644 --- a/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/PolkadotJsBridgeTest.kt +++ b/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/PolkadotJsBridgeTest.kt @@ -13,7 +13,8 @@ class PolkadotJsBridgeTest { fun `bridge script calls the interface the injector registers`() { val bridge = File("src/main/res/raw/javascript_interface_bridge.js").readText() - val call = "${jsInterfaceFullName(POLKADOT_JS_INTERFACE_NAME)}.onNewMessage(" + // A web message listener object exposes postMessage, and nothing else + val call = "${jsInterfaceFullName(POLKADOT_JS_INTERFACE_NAME)}.postMessage(" assertTrue("bridge must call $call", bridge.contains(call)) } } diff --git a/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/PolkadotJsRpcBridgeTest.kt b/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/PolkadotJsRpcBridgeTest.kt new file mode 100644 index 00000000..09e0143d --- /dev/null +++ b/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/PolkadotJsRpcBridgeTest.kt @@ -0,0 +1,105 @@ +package io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.rpc + +import io.novafoundation.nova.runtime.multiNetwork.chain.model.ChainId +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.yield +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class PolkadotJsRpcBridgeTest { + + private val calls = mutableListOf>>() + private val unsubscribes = mutableListOf() + + private val rpc = object : ChainRpc { + override suspend fun send(chainId: ChainId, method: String, params: List): Any? { + calls += Triple(chainId, method, params) + return "ok" + } + + override fun subscribe(chainId: ChainId, method: String, params: List, unsubscribeMethod: String): Flow { + calls += Triple(chainId, method, params) + unsubscribes += unsubscribeMethod + return flowOf("head") + } + } + + private val bridge = PolkadotJsRpcBridge(rpc) + + @Test + fun `calls go to the chain of the started provider`() = runBlocking { + val meta = bridge.start("zagros-people") + + assertEquals("Zagros People", meta.network) + assertEquals("ok", bridge.send("state_getStorage", listOf("0x00"))) + assertEquals("c72b38f36affaeb2661018b201c2be02e8c09fc699640525d39200a10fd77878", calls.single().first) + } + + @Test + fun `nothing is sent before a provider is started or for an unknown one`() = runBlocking { + assertTrue(runCatching { bridge.send("chain_getHeader", emptyList()) }.exceptionOrNull() is RpcBridgeException) + assertTrue(runCatching { bridge.start("polkadot") }.exceptionOrNull() is RpcBridgeException) + assertTrue(calls.isEmpty()) + } + + @Test + fun `methods outside the list never reach the node`() = runBlocking { + bridge.start("pezkuwi") + + listOf("author_rotateKeys", "author_insertKey", "system_addReservedPeer", "state_getPairs", "offchain_localStorageSet", "eth_sendTransaction") + .forEach { method -> assertTrue(method, runCatching { bridge.send(method, emptyList()) }.exceptionOrNull() is RpcBridgeException) } + assertTrue(runCatching { bridge.subscribe("state_subscribeStorage_", emptyList()) }.exceptionOrNull() is RpcBridgeException) + assertTrue(calls.isEmpty()) + } + + @Test + fun `a subscription carries the call that ends it`() = runBlocking { + bridge.start("pezkuwi-asset-hub") + + assertEquals(listOf("head"), bridge.subscribe("chain_subscribeNewHeads", emptyList()).toList()) + assertEquals(listOf("chain_unsubscribeNewHeads"), unsubscribes) + } + + @Test + fun `every provider is listed with the wallet as its source`() { + val providers = bridge.providers() + + assertEquals(setOf("pezkuwi", "pezkuwi-asset-hub", "pezkuwi-people", "zagros", "zagros-asset-hub", "zagros-people"), providers.keys) + assertTrue(providers.values.all { it.source == "pezkuwi-wallet" }) + } + + @Test + fun `a subscription ends when its signal fires`() = runBlocking { + val upstream = MutableSharedFlow() + val left = CompletableDeferred() + val received = mutableListOf() + + val job = launch { upstream.until { left.await() }.collect { received += it } } + upstream.subscriptionCount.first { it > 0 } + upstream.emit(1) + while (received.isEmpty()) yield() + left.complete(Unit) + job.join() + + assertEquals(listOf(1), received) + assertEquals(0, upstream.subscriptionCount.value) + } + + @Test + fun `only kurd pages and same origins are recognised`() { + assertTrue(isKurdPage("https://dks.kurd/news/1")) + assertFalse(isKurdPage("https://dks.kurd.example.com/")) + assertFalse(isKurdPage("https://app.pezkuwichain.io/")) + assertTrue(sameOrigin("https://dks.kurd/a", "https://dks.kurd/b?c")) + assertFalse(sameOrigin("https://dks.kurd/", "https://serok.gov.kurd/")) + } +} diff --git a/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/RpcCallParsingTest.kt b/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/RpcCallParsingTest.kt new file mode 100644 index 00000000..db2f4446 --- /dev/null +++ b/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/RpcCallParsingTest.kt @@ -0,0 +1,28 @@ +package io.novafoundation.nova.feature_dapp_impl.web3.polkadotJs.rpc + +import com.google.gson.Gson +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class RpcCallParsingTest { + + @Test + fun `params reach the node as the page wrote them`() { + val message = """{"msgType":"pub(rpc.send)","request":{"method":"chain_getBlockHash","params":[123, "0x01", null, 18446744073709551615]}}""" + + val (method, params) = rpcCall(message)!! + + assertEquals("chain_getBlockHash", method) + assertEquals("""[123,"0x01",null,18446744073709551615]""", Gson().newBuilder().serializeNulls().create().toJson(params)) + } + + @Test + fun `missing params are none and anything malformed is no call`() { + assertEquals(emptyList(), rpcCall("""{"request":{"method":"system_health"}}""")!!.second) + assertNull(rpcCall("""{"request":{"method":"system_health","params":{"a":1}}}""")) + assertNull(rpcCall("""{"request":{"method":7}}""")) + assertNull(rpcCall("""{"request":"system_health"}""")) + assertNull(rpcCall("not json")) + } +} diff --git a/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewWeb3JavaScriptInterfaceTest.kt b/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewWeb3JavaScriptInterfaceTest.kt new file mode 100644 index 00000000..e4dc7ab9 --- /dev/null +++ b/feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewWeb3JavaScriptInterfaceTest.kt @@ -0,0 +1,38 @@ +package io.novafoundation.nova.feature_dapp_impl.web3.webview + +import io.novafoundation.nova.feature_dapp_impl.web3.webview.WebViewWeb3JavaScriptInterface.Companion.isFromShownPage +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class WebViewWeb3JavaScriptInterfaceTest { + + @Test + fun `the top frame of the shown page is heard`() { + assertTrue(isFromShownPage("https://app.pezkuwichain.io/staking?x=1", "https://app.pezkuwichain.io", isMainFrame = true)) + assertTrue(isFromShownPage("https://dks.kurd/", "https://dks.kurd", isMainFrame = true)) + assertTrue(isFromShownPage("https://App.Example:443/a", "https://app.example", isMainFrame = true)) + } + + @Test + fun `a frame inside the page is not, even from the same origin`() { + assertFalse(isFromShownPage("https://app.pezkuwichain.io/", "https://ads.example", isMainFrame = false)) + assertFalse(isFromShownPage("https://app.pezkuwichain.io/", "https://app.pezkuwichain.io", isMainFrame = false)) + } + + @Test + fun `a message from another origin than the page shown is not`() { + // A page still posting while the tab moves to an authorised DApp + assertFalse(isFromShownPage("https://trusted.example/", "https://evil.example", isMainFrame = true)) + assertFalse(isFromShownPage("https://trusted.example/", "http://trusted.example", isMainFrame = true)) + assertFalse(isFromShownPage("https://trusted.example/", "https://trusted.example:8443", isMainFrame = true)) + assertFalse(isFromShownPage("https://trusted.example.evil.example/", "https://trusted.example", isMainFrame = true)) + } + + @Test + fun `no page or an opaque origin is not`() { + assertFalse(isFromShownPage(null, "https://dks.kurd", isMainFrame = true)) + assertFalse(isFromShownPage("about:blank", "null", isMainFrame = true)) + assertFalse(isFromShownPage("data:text/html,hi", "null", isMainFrame = true)) + } +} diff --git a/feature-external-sign-api/src/main/java/io/novafoundation/nova/feature_external_sign_api/model/signPayload/ExternalSignPayload.kt b/feature-external-sign-api/src/main/java/io/novafoundation/nova/feature_external_sign_api/model/signPayload/ExternalSignPayload.kt index a3272d34..fdb665b1 100644 --- a/feature-external-sign-api/src/main/java/io/novafoundation/nova/feature_external_sign_api/model/signPayload/ExternalSignPayload.kt +++ b/feature-external-sign-api/src/main/java/io/novafoundation/nova/feature_external_sign_api/model/signPayload/ExternalSignPayload.kt @@ -16,9 +16,23 @@ class ExternalSignPayload( class SigningDappMetadata( val icon: String?, val name: String?, - val url: String + val url: String, + /** For a page on a `.kurd` name: what kind of name asks for the signature. */ + val siteNameKind: SiteNameKind? = null, ) : Parcelable +/** A `.kurd` name as the browser verified it, shown where the reader signs. */ +enum class SiteNameKind { + /** Given by Parliament, or under such a name. */ + OFFICIAL, + + /** Bought: anyone may hold it. */ + REGISTERED, + + /** Opened by the reader's choice without a proof. */ + UNVERIFIED, +} + sealed class ExternalSignWallet : Parcelable { @Parcelize diff --git a/feature-external-sign-impl/src/main/java/io/novafoundation/nova/feature_external_sign_impl/presentation/signExtrinsic/ExternalSignFragment.kt b/feature-external-sign-impl/src/main/java/io/novafoundation/nova/feature_external_sign_impl/presentation/signExtrinsic/ExternalSignFragment.kt index 154ac080..59b1dd54 100644 --- a/feature-external-sign-impl/src/main/java/io/novafoundation/nova/feature_external_sign_impl/presentation/signExtrinsic/ExternalSignFragment.kt +++ b/feature-external-sign-impl/src/main/java/io/novafoundation/nova/feature_external_sign_impl/presentation/signExtrinsic/ExternalSignFragment.kt @@ -1,7 +1,6 @@ package io.novafoundation.nova.feature_external_sign_impl.presentation.signExtrinsic import androidx.core.os.bundleOf - import coil.ImageLoader import io.novafoundation.nova.common.base.BaseFragment import io.novafoundation.nova.common.base.blockBackPressing @@ -15,18 +14,18 @@ import io.novafoundation.nova.common.view.setProgressState import io.novafoundation.nova.common.view.shape.addRipple import io.novafoundation.nova.common.view.shape.getBlockDrawable import io.novafoundation.nova.common.view.showValueOrHide -import io.novafoundation.nova.feature_account_api.view.showWallet import io.novafoundation.nova.feature_account_api.view.showAddress import io.novafoundation.nova.feature_account_api.view.showChain +import io.novafoundation.nova.feature_account_api.view.showWallet import io.novafoundation.nova.feature_external_sign_api.di.ExternalSignFeatureApi import io.novafoundation.nova.feature_external_sign_api.model.signPayload.ExternalSignPayload +import io.novafoundation.nova.feature_external_sign_api.model.signPayload.SiteNameKind import io.novafoundation.nova.feature_external_sign_api.presentation.dapp.showDAppIcon import io.novafoundation.nova.feature_external_sign_impl.R import io.novafoundation.nova.feature_external_sign_impl.databinding.FragmentConfirmSignExtrinsicBinding import io.novafoundation.nova.feature_external_sign_impl.di.ExternalSignFeatureComponent import io.novafoundation.nova.feature_wallet_api.presentation.mixin.fee.setupFeeLoading import io.novafoundation.nova.feature_wallet_api.presentation.view.FeeView - import javax.inject.Inject private const val PAYLOAD_KEY = "DAppSignExtrinsicFragment.Payload" @@ -90,6 +89,7 @@ class ExternalSignFragment : BaseFragment val actionsAllowed = !operationInProgress @@ -114,4 +114,19 @@ class ExternalSignFragment : BaseFragment R.string.dapp_kurd_sign_kind_official to null + SiteNameKind.REGISTERED -> R.string.dapp_kurd_sign_kind_registered to R.string.dapp_kurd_sign_note_registered + SiteNameKind.UNVERIFIED -> R.string.dapp_kurd_sign_kind_unverified to R.string.dapp_kurd_sign_note_unverified + } + binder.confirmSignExtinsicDappUrl.showValue(url, getString(kindRes)) + binder.confirmSignExtinsicSiteNameNote.setVisible(noteRes != null) + noteRes?.let(binder.confirmSignExtinsicSiteNameNote::setText) + } } diff --git a/feature-external-sign-impl/src/main/res/layout/fragment_confirm_sign_extrinsic.xml b/feature-external-sign-impl/src/main/res/layout/fragment_confirm_sign_extrinsic.xml index fab85205..079eeada 100644 --- a/feature-external-sign-impl/src/main/res/layout/fragment_confirm_sign_extrinsic.xml +++ b/feature-external-sign-impl/src/main/res/layout/fragment_confirm_sign_extrinsic.xml @@ -65,6 +65,16 @@ app:title="@string/dapp_dapp" /> + + , + chainRegistry: ChainRegistry, + connectionSecrets: ConnectionSecrets, + ): KurdNameResolver = RealKurdNameResolver( + // Names live on the testnet until the mainnet People chain is launched with the pallet + chainId = LightClients.ZAGROS_PEOPLE, + lightClients = lightClients, + socketProvider = socketProvider, + chainRegistry = chainRegistry, + connectionSecrets = connectionSecrets, + ) + + @Provides + @ApplicationScope + fun provideKurdSiteServer( + kurdNameResolver: KurdNameResolver, + networkApiCreator: NetworkApiCreator, + okHttpClient: OkHttpClient, + ): KurdSiteServer { + val gateways = RealKurdGateways(networkApiCreator.create(KurdGatewayListApi::class.java)) + val fetcher = KurdContentFetcher(gateways, OkHttpCarSource(okHttpClient)) + val feeds = KurdFeedResolver(gateways, OkHttpIpnsRecordSource(okHttpClient)) + return KurdSiteServer(kurdNameResolver, fetcher, feeds) + } + @Provides @ApplicationScope fun provideChainConnectionFactory( diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/di/RuntimeApi.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/di/RuntimeApi.kt index 97adb6cf..4323c584 100644 --- a/runtime/src/main/java/io/novafoundation/nova/runtime/di/RuntimeApi.kt +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/di/RuntimeApi.kt @@ -1,5 +1,7 @@ package io.novafoundation.nova.runtime.di +import io.novafoundation.nova.runtime.names.KurdNameResolver +import io.novafoundation.nova.runtime.names.content.KurdSiteServer import com.google.gson.Gson import io.novafoundation.nova.core.storage.StorageCache import io.novafoundation.nova.runtime.call.MultiChainRuntimeCallsApi @@ -62,6 +64,10 @@ interface RuntimeApi { fun chainRegistry(): ChainRegistry + fun kurdNameResolver(): KurdNameResolver + + fun kurdSiteServer(): KurdSiteServer + fun rpcCalls(): RpcCalls @ExtrinsicSerialization diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/di/RuntimeDependencies.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/di/RuntimeDependencies.kt index 732ea32e..10897783 100644 --- a/runtime/src/main/java/io/novafoundation/nova/runtime/di/RuntimeDependencies.kt +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/di/RuntimeDependencies.kt @@ -11,6 +11,7 @@ import io.novafoundation.nova.core_db.dao.ChainAssetDao import io.novafoundation.nova.core_db.dao.ChainDao import io.novafoundation.nova.core_db.dao.StorageDao import io.novasama.substrate_sdk_android.wsrpc.SocketService +import okhttp3.OkHttpClient interface RuntimeDependencies { @@ -35,4 +36,6 @@ interface RuntimeDependencies { fun assetsIconModeService(): AssetsIconModeRepository fun encryptedFirstDns(): EncryptedFirstDns + + fun okHttpClient(): OkHttpClient } diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/multiNetwork/connection/ChainConnection.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/multiNetwork/connection/ChainConnection.kt index 58ac4d08..094d9b1e 100644 --- a/runtime/src/main/java/io/novafoundation/nova/runtime/multiNetwork/connection/ChainConnection.kt +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/multiNetwork/connection/ChainConnection.kt @@ -208,7 +208,7 @@ class ChainConnection internal constructor( policy.onLightUnavailable(rpcNodeCount()) emit(latestRpc) } else if (policy.onRpcFailure(rpcNodeCount(), System.currentTimeMillis())) { - val url = lightClients.url(chain.value.id) + val url = lightClients.url(chain.value.id, holder = this@ChainConnection) Log.d(LIGHT_FALLBACK_TAG, "${chain.value.name}: light client url $url") if (url == null) { policy.onLightUnavailable(rpcNodeCount()) @@ -229,7 +229,7 @@ class ChainConnection internal constructor( if (policy.shouldReleaseLight(now)) { Log.d(LIGHT_FALLBACK_TAG, "${chain.value.name}: RPC is stable, releasing the light client") light = null - lightClients.release(chain.value.id) + lightClients.release(chain.value.id, holder = this@ChainConnection) } } } diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/multiNetwork/connection/light/LightClientLeases.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/multiNetwork/connection/light/LightClientLeases.kt new file mode 100644 index 00000000..a6ee6a1d --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/multiNetwork/connection/light/LightClientLeases.kt @@ -0,0 +1,30 @@ +package io.novafoundation.nova.runtime.multiNetwork.connection.light + +import io.novafoundation.nova.runtime.multiNetwork.chain.model.ChainId + +/** + * Who is using which light client chain. A chain is wanted by more than one reader at a time -- a + * connection that fell back to it, the `.kurd` resolver -- so one reader letting go must not stop + * it under another. Holders are compared by identity, so asking twice and releasing once balances. + */ +internal class LightClientLeases(private val relayOf: (ChainId) -> ChainId?) { + + private val holders = mutableMapOf>() + + fun acquire(chainId: ChainId, holder: Any) { + holders.getOrPut(chainId) { mutableSetOf() } += holder + } + + fun release(chainId: ChainId, holder: Any) { + val chainHolders = holders[chainId] ?: return + chainHolders -= holder + if (chainHolders.isEmpty()) holders -= chainId + } + + fun isHeld(chainId: ChainId): Boolean = holders[chainId].orEmpty().isNotEmpty() + + /** One of [registered] that nothing holds and that is not the relay of a registered chain. */ + fun nextUnused(registered: Set): ChainId? = registered.firstOrNull { key -> + !isHeld(key) && registered.none { relayOf(it) == key } + } +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/multiNetwork/connection/light/LightClients.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/multiNetwork/connection/light/LightClients.kt index 4dcb35eb..3c291442 100644 --- a/runtime/src/main/java/io/novafoundation/nova/runtime/multiNetwork/connection/light/LightClients.kt +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/multiNetwork/connection/light/LightClients.kt @@ -43,18 +43,21 @@ class LightClients( private val mutex = Mutex() private var baseUrl: String? = null private val registered = mutableSetOf() - private val inUse = mutableSetOf() + private val leases = LightClientLeases(relayOf = { chains.getValue(it).relay }) fun supports(chainId: ChainId): Boolean = chainId in chains - /** Loopback JSON-RPC URL of [chainId], or null when the light client cannot serve it. */ - suspend fun url(chainId: ChainId): String? = mutex.withLock { + /** + * Loopback JSON-RPC URL of [chainId], or null when the light client cannot serve it. The chain + * keeps syncing until every [holder] that asked for it has [release]d it. + */ + suspend fun url(chainId: ChainId, holder: Any): String? = mutex.withLock { withContext(Dispatchers.IO) { runCatching { if (!supports(chainId)) return@runCatching null val base = baseUrl ?: PezkuwiLight.start(File(context.filesDir, DATABASE_DIR), resolver()).also { baseUrl = it } register(chainId) - inUse += chainId + leases.acquire(chainId, holder) PezkuwiLight.chainUrl(base, chainId) }.onFailure { Log.w(TAG, "Light client unavailable for $chainId", it) @@ -63,14 +66,15 @@ class LightClients( } /** - * [chainId] no longer needs the light client, so it stops syncing: a synced chain costs data - * and CPU while nothing reads it. A relay chain goes once none of its teyrchains is in use. + * [holder] no longer needs [chainId]. Once no holder does, the chain stops syncing: a synced + * chain costs data and CPU while nothing reads it. A relay chain goes once none of its + * teyrchains is in use. */ - suspend fun release(chainId: ChainId) = mutex.withLock { + suspend fun release(chainId: ChainId, holder: Any) = mutex.withLock { withContext(Dispatchers.IO) { - inUse -= chainId + leases.release(chainId, holder) while (true) { - val unused = registered.firstOrNull { key -> key !in inUse && registered.none { chains.getValue(it).relay == key } } ?: break + val unused = leases.nextUnused(registered) ?: break // Still registered on failure, so a later url() does not register it twice runCatching { PezkuwiLight.removeChain(unused) } .onSuccess { registered -= unused } @@ -132,15 +136,15 @@ class LightClients( dns.lookup(host).mapNotNull { it.hostAddress }.toTypedArray() } - private companion object { + companion object { const val ZAGROS: ChainId = "1b0b4727bbb5e44ed587d1056b4ad537ffb330034509a58866a088d77e792cd5" const val ZAGROS_PEOPLE: ChainId = "c72b38f36affaeb2661018b201c2be02e8c09fc699640525d39200a10fd77878" // Not LOG_TAG: called inside a coroutine, it gives the coroutine class name - const val TAG = "LightClients" - const val DATABASE_DIR = "light-client" - const val SPECS_DIR = "light-client-specs" - const val BUNDLED_DIR = "light-client/" - const val SPEC_SOURCE = "https://raw.githubusercontent.com/pezkuwichain/pezkuwi-wallet-utils/master/light-client/" + private const val TAG = "LightClients" + private const val DATABASE_DIR = "light-client" + private const val SPECS_DIR = "light-client-specs" + private const val BUNDLED_DIR = "light-client/" + private const val SPEC_SOURCE = "https://raw.githubusercontent.com/pezkuwichain/pezkuwi-wallet-utils/master/light-client/" } } diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdLookalikes.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdLookalikes.kt new file mode 100644 index 00000000..0d7e84db --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdLookalikes.kt @@ -0,0 +1,29 @@ +package io.novafoundation.nova.runtime.names + +/** + * Official names a typed one could be mistaken for. Zone names are institutional by construction + * (`*.gov.kurd`, `*.edu.kurd`, …), and the commonest imitation flattens the zone into the label: + * `serok-gov.kurd` or `serokgov.kurd` for `serok.gov.kurd`. Candidates are only guesses: a warning + * is shown once one of them resolves, proven, as an official name. + */ +object KurdLookalikes { + + /** Zones created at genesis (decisions D6, D13). */ + val ZONES = listOf("gov", "edu", "mil", "int", "org", "net") + + fun candidates(name: KurdName): List { + val top = name.top + if (top in ZONES) return emptyList() + + return ZONES.mapNotNull { zone -> + val prefix = when { + top.endsWith("-$zone") -> top.removeSuffix("-$zone") + top.endsWith(zone) -> top.removeSuffix(zone) + else -> return@mapNotNull null + } + if (!KurdName.isValidLabel(prefix)) return@mapNotNull null + + KurdName.parse((name.labels.dropLast(1) + prefix + zone).joinToString(".") + KurdName.SUFFIX) + }.distinct() + } +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdName.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdName.kt new file mode 100644 index 00000000..9fac537b --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdName.kt @@ -0,0 +1,91 @@ +package io.novafoundation.nova.runtime.names + +import io.novasama.substrate_sdk_android.hash.Hasher.blake2b256 + +/** + * A `.kurd` name in the canonical form the Navnisan pallet keys records by. + * + * The chain does not normalise: it accepts canonical bytes or refuses them. So the wallet lower-cases + * ASCII first and then applies the pallet's label rules (`label::validate`, `Use::Sub`); input that + * fails them is never looked up anywhere, and in particular never handed to a search engine. + */ +class KurdName private constructor( + /** Labels from the leftmost down to the one directly under `.kurd`: `dks.gov.kurd` is `[dks, gov]`. */ + val labels: List, +) { + + val name: String = labels.joinToString(".") + SUFFIX + + /** The top-level label: `gov` for `dks.gov.kurd`. */ + val top: String get() = labels.last() + + /** `node(name)`, as `pezpallet_navnisan::Pallet::node_of` computes it. */ + val node: ByteArray by lazy { labels.foldRight(KURD_NODE) { label, parent -> childNode(parent, label) } } + + /** Nodes of this name and each ancestor, this name first, the top-level name last. */ + fun nodesUpward(): List = labels.indices.map { from -> KurdName(labels.drop(from)).node } + + override fun equals(other: Any?) = other is KurdName && other.name == name + + override fun hashCode() = name.hashCode() + + override fun toString() = name + + companion object { + + const val SUFFIX = ".kurd" + + const val MAX_LABEL = 63 + const val MAX_DEPTH = 4 + const val MAX_NAME = 253 + + /** `node("kurd")`: never stored, every top-level name's parent. */ + val KURD_NODE: ByteArray = (ByteArray(32) + "kurd".toByteArray().blake2b256()).blake2b256() + + /** True for `kurd` and any host under it, valid name or not: none of them may reach system DNS. */ + fun isKurdHost(host: String?): Boolean { + val normalized = host?.lowercase(java.util.Locale.ROOT)?.trimEnd('.') ?: return false + return normalized == "kurd" || normalized.endsWith(SUFFIX) + } + + /** + * True when [input] names a `.kurd` host, valid name or not, with or without a scheme or path: + * such input is never treated as a web address or a search query. + */ + fun mentionsKurd(input: String): Boolean { + val afterScheme = input.trim().substringAfter("://") + val authority = afterScheme.takeWhile { it !in "/?#" } + val host = authority.substringAfterLast('@').substringBefore(':') + return isKurdHost(host) + } + + /** + * The name in [input], or null when it is not a valid `.kurd` name. Accepts surrounding + * whitespace, a trailing dot or slash and an `https://` prefix; anything else around the + * name (a path, a port, user info) makes it invalid rather than being ignored. + */ + fun parse(input: String): KurdName? { + var text = input.trim() + if (text.startsWith("https://", ignoreCase = true)) text = text.substring("https://".length) + text = text.trimEnd('/').trimEnd('.') + if (text.any { it.code > 0x7f }) return null + text = text.lowercase(java.util.Locale.ROOT) + + if (text.length > MAX_NAME || !text.endsWith(SUFFIX)) return null + val labels = text.removeSuffix(SUFFIX).split('.') + if (labels.size > MAX_DEPTH || !labels.all(::isValidLabel)) return null + + return KurdName(labels) + } + + /** `a-z`, `0-9` and `-`, 1 to 63 bytes, no hyphen at either end and no `--` anywhere. */ + fun isValidLabel(label: String): Boolean { + if (label.isEmpty() || label.length > MAX_LABEL) return false + if (!label.all { it in 'a'..'z' || it in '0'..'9' || it == '-' }) return false + if (label.first() == '-' || label.last() == '-') return false + return "--" !in label + } + + fun childNode(parent: ByteArray, label: String): ByteArray = (parent + label.toByteArray().blake2b256()).blake2b256() + } +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdNameResolver.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdNameResolver.kt new file mode 100644 index 00000000..3e2ab13b --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdNameResolver.kt @@ -0,0 +1,164 @@ +package io.novafoundation.nova.runtime.names + +import android.util.Log +import io.novafoundation.nova.common.data.network.runtime.calls.GetFinalizedHeadRequest +import io.novafoundation.nova.common.utils.awaitConnected +import io.novafoundation.nova.runtime.multiNetwork.ChainRegistry +import io.novafoundation.nova.runtime.multiNetwork.chain.model.Chain +import io.novafoundation.nova.runtime.multiNetwork.chain.model.ChainId +import io.novafoundation.nova.runtime.multiNetwork.connection.ConnectionSecrets +import io.novafoundation.nova.runtime.multiNetwork.connection.light.LightClients +import io.novafoundation.nova.runtime.multiNetwork.connection.saturateNodeUrl +import io.novasama.substrate_sdk_android.extensions.fromHex +import io.novasama.substrate_sdk_android.extensions.toHexString +import io.novasama.substrate_sdk_android.wsrpc.SocketService +import io.novasama.substrate_sdk_android.wsrpc.executeAsync +import io.novasama.substrate_sdk_android.wsrpc.mappers.nonNull +import io.novasama.substrate_sdk_android.wsrpc.mappers.pojo +import io.novasama.substrate_sdk_android.wsrpc.request.runtime.RuntimeRequest +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withTimeout +import java.net.URI +import javax.inject.Provider + +/** + * Resolves `.kurd` names from `Navnisan` on [chainId]: through the light client first, so a name + * is proven rather than reported, and only when it cannot answer through two RPC nodes that must + * agree (architecture §5.2). + * + * The chain's own connection is RPC first and moves to the light client only once every node + * fails, so it is not used here: a name read through it would be the node's word. + */ +class RealKurdNameResolver( + private val chainId: ChainId, + private val lightClients: LightClients, + private val socketProvider: Provider, + private val chainRegistry: ChainRegistry, + private val connectionSecrets: ConnectionSecrets, +) : KurdNameResolver { + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private val leaseMutex = Mutex() + private var leaseRelease: Job? = null + + override suspend fun resolve(name: KurdName): KurdResolution { + val light = runCatching { readThroughLightClient(name) } + .onFailure { Log.w(TAG, "Light client could not resolve $name", it) } + .getOrNull() + if (light != null) return judge(name, light, verified = true) + + val urls = rpcUrls() + if (urls.size < AGREEING_NODES) return refuseOrGiveUp(name) + + val lookups = runCatching { + coroutineScope { + urls.take(AGREEING_NODES).map { url -> async { withSocket(url) { NameLookup.read(SocketStorageReader(it), name) } } }.awaitAll() + } + }.onFailure { Log.w(TAG, "RPC nodes could not resolve $name", it) }.getOrNull() ?: return refuseOrGiveUp(name) + + val first = lookups.first() + if (!lookups.all { it.agreesWith(first) }) return refuseOrGiveUp(name) + + return judge(name, first, verified = false) + } + + private suspend fun readThroughLightClient(name: KurdName): NameLookup { + val url = holdLightClient() ?: error("Light client unavailable") + return withTimeout(LIGHT_TIMEOUT_MILLIS) { + withSocket(url) { NameLookup.read(SocketStorageReader(it), name) } + } + } + + /** + * Keeps the names chain syncing between lookups, so a second name does not wait for a cold + * start, and lets it go once nothing has been resolved for a while. + */ + private suspend fun holdLightClient(): String? = leaseMutex.withLock { + leaseRelease?.cancel() + val url = lightClients.url(chainId, holder = this) + leaseRelease = scope.launch { + delay(LIGHT_IDLE_MILLIS) + lightClients.release(chainId, holder = this@RealKurdNameResolver) + } + url + } + + /** RPC node URLs of the names chain, at most one per host, so agreement is not one server twice. */ + private suspend fun rpcUrls(): List { + val chain = chainRegistry.getChain(chainId) + return chain.nodes.nodes + .filter { it.connectionType == Chain.Node.ConnectionType.WSS } + .mapNotNull { it.saturateNodeUrl(connectionSecrets)?.saturatedUrl } + .distinctBy { runCatching { URI(it).host }.getOrNull() ?: it } + } + + private suspend fun withSocket(url: String, block: suspend (SocketService) -> T): T { + val socket = socketProvider.get() + socket.start(url) + return try { + socket.awaitConnected() + block(socket) + } finally { + socket.stop() + } + } + + private class SocketStorageReader(private val socket: SocketService) : NameStorageReader { + + override suspend fun finalizedHead(): String = socket.executeAsync(GetFinalizedHeadRequest, mapper = pojo().nonNull()) + + override suspend fun storage(key: ByteArray, at: String): ByteArray? { + val request = RuntimeRequest(method = "state_getStorage", params = listOf(key.toHexString(withPrefix = true), at)) + return socket.executeAsync(request, mapper = pojo()).result?.fromHex() + } + + override suspend fun blockNumber(at: String): Long? { + val header = socket.executeAsync(RuntimeRequest(method = "chain_getHeader", params = listOf(at))).result as? Map<*, *> + return (header?.get("number") as? String)?.removePrefix("0x")?.toLongOrNull(16) + } + } + + companion object { + + /** + * D18: a proven answer stands; an unproven one opens only for a name nobody could take for an + * institution's, and with a warning. + */ + internal fun judge(name: KurdName, lookup: NameLookup, verified: Boolean): KurdResolution = when (lookup) { + NameLookup.NotFound, NameLookup.Lapsed -> KurdResolution.NotFound(name, verified) + is NameLookup.Found -> when { + verified -> KurdResolution.Resolved(name, lookup.record, lookup.status, verified = true, block = lookup.block) + mustBeVerified(name, lookup) -> KurdResolution.Refused(name) + else -> KurdResolution.Resolved(name, lookup.record, lookup.status, verified = false, block = lookup.block) + } + } + + /** No answer at all: a zone name is known to be institutional without one. */ + internal fun refuseOrGiveUp(name: KurdName) = if (name.top in ZONES) KurdResolution.Refused(name) else KurdResolution.Unavailable(name) + + private fun mustBeVerified(name: KurdName, found: NameLookup.Found): Boolean { + return name.top in ZONES || found.locked || found.record.isOfficial || found.record.isInstitutional + } + + /** Zones created at genesis: every name under them belongs to an institution (decisions D6, D13). */ + val ZONES = setOf("gov", "edu", "mil", "int", "org", "net") + + private const val AGREEING_NODES = 2 + + /** A cold light client within the acceptance target (architecture §1, criterion 2). */ + private const val LIGHT_TIMEOUT_MILLIS = 30_000L + private const val LIGHT_IDLE_MILLIS = 5 * 60_000L + + private const val TAG = "KurdNameResolver" + } +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdResolution.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdResolution.kt new file mode 100644 index 00000000..b5fd426e --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdResolution.kt @@ -0,0 +1,41 @@ +package io.novafoundation.nova.runtime.names + +sealed interface KurdResolution { + + val name: KurdName + + /** + * [verified]: read through the light client, which checks every value against the chain's + * finalized state. Otherwise two independent RPC nodes returned the same records, and the + * name is shown with a "not verified" warning. + */ + class Resolved( + override val name: KurdName, + val record: NameRecord, + val status: NameStatus, + val verified: Boolean, + /** The finalized block the name was read at, when known. */ + val block: Long? = null, + ) : KurdResolution { + + /** "Official" badge: only granted names and their descendants; a bought name never shows it. */ + val official: Boolean get() = record.isOfficial + } + + /** Not registered, expired, or orphaned by its parent's re-registration. */ + class NotFound(override val name: KurdName, val verified: Boolean) : KurdResolution + + /** + * Not verified, and a name that must never open unverified: official, institutional, reserved + * or under a zone (decision D18). + */ + class Refused(override val name: KurdName) : KurdResolution + + /** Neither the light client nor two agreeing RPC nodes could answer. */ + class Unavailable(override val name: KurdName) : KurdResolution +} + +interface KurdNameResolver { + + suspend fun resolve(name: KurdName): KurdResolution +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/NameLookup.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/NameLookup.kt new file mode 100644 index 00000000..7d3c9b44 --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/NameLookup.kt @@ -0,0 +1,129 @@ +package io.novafoundation.nova.runtime.names + +import io.novasama.substrate_sdk_android.extensions.toHexString +import io.novasama.substrate_sdk_android.hash.Hasher.xxHash128 +import java.math.BigInteger + +/** Raw storage of the chain that keeps `.kurd` names, all read at one block. */ +interface NameStorageReader { + + suspend fun finalizedHead(): String + + /** The raw value at [key] in block [at], or null when nothing is stored there. */ + suspend fun storage(key: ByteArray, at: String): ByteArray? + + /** The number of block [at], shown to the reader as where a name was read. */ + suspend fun blockNumber(at: String): Long? +} + +enum class NameStatus { + ACTIVE, + + /** The lease has ended; the site still resolves and only the last owner may renew. */ + GRACE, +} + +/** What one source says about a name. */ +sealed interface NameLookup { + + /** Two sources agree when they return the same records byte for byte and judge them the same. */ + fun agreesWith(other: NameLookup): Boolean = when (this) { + is Found -> other is Found && rawChain == other.rawChain && status == other.status && locked == other.locked + else -> this === other + } + + object NotFound : NameLookup + + /** Registered once but no longer valid: expired, or an ancestor was registered anew. */ + object Lapsed : NameLookup + + data class Found( + val record: NameRecord, + val status: NameStatus, + /** Every record from this name up to its top-level name, raw, for comparing sources. */ + val rawChain: List, + /** Some label of the name is in `Navnisan::Locked`: reserved, never for sale. */ + val locked: Boolean, + /** The finalized block it was read at, when the source said; not part of agreement. */ + val block: Long? = null, + ) : NameLookup + + companion object { + + private val NAMES_PREFIX = "Navnisan".toByteArray().xxHash128() + "Names".toByteArray().xxHash128() + private val LOCKED_PREFIX = "Navnisan".toByteArray().xxHash128() + "Locked".toByteArray().xxHash128() + private val TIMESTAMP_NOW = "Timestamp".toByteArray().xxHash128() + "Now".toByteArray().xxHash128() + + /** `NavnisanGracePeriod`: 30 days after a lease ends the name still resolves (decision D11). */ + const val GRACE_PERIOD_MILLIS = 30L * 24 * 60 * 60 * 1000 + + fun namesKey(node: ByteArray) = NAMES_PREFIX + node + + fun lockedKey(node: ByteArray) = LOCKED_PREFIX + node + + val timestampNowKey: ByteArray get() = TIMESTAMP_NOW.copyOf() + + /** + * Reads [name] the way `Pallet::effective_status` judges it, all at one finalized block: the + * record, then each ancestor. Each record must sit under the parent its name implies and + * carry the label the name has, so a source cannot answer for one name with another's record. + */ + suspend fun read(reader: NameStorageReader, name: KurdName): NameLookup { + val at = reader.finalizedHead() + val now = reader.storage(TIMESTAMP_NOW, at)?.let(::decodeMoment) ?: error("Chain time is missing") + + val nodes = name.nodesUpward() + val parents = nodes.drop(1) + listOf(KurdName.KURD_NODE) + val records = mutableListOf>() + + for (level in nodes.indices) { + val raw = reader.storage(namesKey(nodes[level]), at) ?: return if (level == 0) NotFound else Lapsed + val record = NameRecord.decode(raw) + check(record.label == name.labels[level] && record.parent.contentEquals(parents[level])) { + "Record of ${name.labels[level]} does not belong to $name" + } + records += record to raw.toHexString() + } + + val status = effectiveStatus(records.map { it.first }, now) ?: return Lapsed + val locked = nodes.any { reader.storage(lockedKey(it), at) != null } + + val block = runCatching { reader.blockNumber(at) }.getOrNull() + + return Found(records.first().first, status, records.map { it.second }, locked, block) + } + + /** + * [chain] is a name's record followed by every ancestor's. A subname is valid only while + * each ancestor is, under the registration it was set against; a grace period anywhere + * above makes the whole name graced. + */ + fun effectiveStatus(chain: List, now: Long): NameStatus? { + var status = ownStatus(chain.first(), now) ?: return null + for (index in 0 until chain.lastIndex) { + val record = chain[index] + if (record.kind != NameRecord.Kind.SUB) return status + + val parent = chain[index + 1] + if (parent.reg != record.parentReg) return null + if ((ownStatus(parent, now) ?: return null) == NameStatus.GRACE) status = NameStatus.GRACE + } + + return status.takeIf { chain.last().kind != NameRecord.Kind.SUB } + } + + fun ownStatus(record: NameRecord, now: Long): NameStatus? { + val end = record.expiry ?: return NameStatus.ACTIVE + return when { + now < end -> NameStatus.ACTIVE + record.kind == NameRecord.Kind.LEASED && now < end + GRACE_PERIOD_MILLIS -> NameStatus.GRACE + else -> null + } + } + + private fun decodeMoment(raw: ByteArray): Long { + require(raw.size == 8) { "Chain time is not a u64" } + return BigInteger(1, raw.reversedArray()).toLong() + } + } +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/NameRecord.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/NameRecord.kt new file mode 100644 index 00000000..b654b73e --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/NameRecord.kt @@ -0,0 +1,134 @@ +package io.novafoundation.nova.runtime.names + +import java.math.BigInteger + +/** + * `pezpallet_navnisan::NameRecord`, decoded from the raw value of `Navnisan::Names[node]`. + * + * Decoded by hand rather than through runtime metadata: the resolver reads it through the light + * client, before and independently of the chain's runtime being loaded. + */ +class NameRecord( + val label: String, + val parent: ByteArray, + val parentReg: Long, + val reg: Long, + val owner: Owner, + val kind: Kind, + val lockedTransfer: Boolean, + /** Milliseconds, chain time. Null for names that never expire. */ + val expiry: Long?, + val account: ByteArray?, + val content: Content?, +) { + + sealed interface Owner { + class Account(val accountId: ByteArray) : Owner + class Office(val tiki: Int) : Owner + object Governance : Owner + } + + enum class Kind { LEASED, GRANTED, SUB } + + sealed interface Content { + /** An EIP-1577 contenthash: `0xe3` then a CIDv1. */ + class Ipfs(val contenthash: ByteArray) : Content + + class Feed(val publisher: ByteArray, val anchorer: ByteArray, val anchor: ByteArray, val seq: BigInteger) : Content + } + + /** `NameRecord::is_official`: granted, or descended from a granted name. */ + val isOfficial: Boolean get() = lockedTransfer || kind == Kind.GRANTED + + /** `NameRecord::is_institutional`: changes to it wait out the institution delay. */ + val isInstitutional: Boolean get() = lockedTransfer || owner !is Owner.Account + + companion object { + + private const val ACCOUNT_ID = 32 + + fun decode(bytes: ByteArray): NameRecord { + val reader = ScaleReader(bytes) + val record = with(reader) { + NameRecord( + label = String(byteVec(), Charsets.US_ASCII), + parent = bytes(32), + parentReg = u64().toLong(), + reg = u64().toLong(), + owner = when (val index = u8()) { + 0 -> Owner.Account(bytes(ACCOUNT_ID)) + 1 -> Owner.Office(u8()) + 2 -> Owner.Governance + else -> error("Unknown owner variant $index") + }, + kind = when (val index = u8()) { + 0 -> Kind.LEASED + 1 -> Kind.GRANTED + 2 -> Kind.SUB + else -> error("Unknown kind variant $index") + }, + lockedTransfer = bool(), + expiry = option { u64().toLong() }, + account = option { bytes(ACCOUNT_ID) }, + content = option { + when (val index = u8()) { + 0 -> Content.Ipfs(byteVec()) + 1 -> Content.Feed(publisher = bytes(32), anchorer = bytes(ACCOUNT_ID), anchor = byteVec(), seq = u64()) + else -> error("Unknown content variant $index") + } + }, + ).also { + // deposit: Option<(AccountId, Balance)>, read only so a trailing byte is noticed + option { bytes(ACCOUNT_ID + 16) } + } + } + require(reader.isExhausted) { "Trailing bytes after a name record" } + + return record + } + } +} + +/** The few SCALE shapes a name record uses. */ +internal class ScaleReader(private val data: ByteArray) { + + private var position = 0 + + val isExhausted: Boolean get() = position == data.size + + fun u8(): Int { + require(position < data.size) { "Unexpected end of SCALE input" } + return data[position++].toInt() and 0xff + } + + fun bytes(count: Int): ByteArray { + require(count >= 0 && position + count <= data.size) { "Unexpected end of SCALE input" } + return data.copyOfRange(position, position + count).also { position += count } + } + + fun bool(): Boolean = when (val byte = u8()) { + 0 -> false + 1 -> true + else -> error("Invalid bool byte $byte") + } + + fun u64(): BigInteger = BigInteger(1, bytes(8).reversedArray()) + + fun compact(): Int { + val first = u8() + return when (first and 0b11) { + 0 -> first ushr 2 + 1 -> (first or (u8() shl 8)) ushr 2 + 2 -> ((first or (u8() shl 8) or (u8() shl 16) or (u8() shl 24)) ushr 2).also { require(it >= 0) } + else -> error("Big compact lengths are not used by name records") + } + } + + fun byteVec(): ByteArray = bytes(compact()) + + fun option(read: ScaleReader.() -> T): T? = when (val tag = u8()) { + 0 -> null + 1 -> read() + else -> error("Invalid option tag $tag") + } +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/Cid.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/Cid.kt new file mode 100644 index 00000000..0c11de4c --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/Cid.kt @@ -0,0 +1,159 @@ +package io.novafoundation.nova.runtime.names.content + +import java.security.MessageDigest + +/** + * A content identifier, limited to what `.kurd` sites are built from: CIDv1 or CIDv0, codec dag-pb + * or raw, hash sha2-256 or identity (inlined tiny blocks). Anything else is refused when parsed, + * so a block can only ever be accepted by checking its bytes against the digest. + */ +class Cid private constructor( + /** The CID's binary form, as it appears in links and in a CAR. */ + val bytes: ByteArray, + val codec: Codec, + private val hash: Hash, + private val digest: ByteArray, +) { + + enum class Codec(val code: Int) { DAG_PB(0x70), RAW(0x55) } + + private enum class Hash(val code: Int) { IDENTITY(0x00), SHA2_256(0x12) } + + /** True when [block] is the content this CID names. */ + fun matches(block: ByteArray): Boolean = when (hash) { + Hash.IDENTITY -> MessageDigest.isEqual(digest, block) + Hash.SHA2_256 -> MessageDigest.isEqual(digest, MessageDigest.getInstance("SHA-256").digest(block)) + } + + /** An identity CID carries its block; nothing needs to be fetched for it. */ + val inlineBlock: ByteArray? get() = digest.copyOf().takeIf { hash == Hash.IDENTITY } + + /** Multibase base32 (`b…`), the form gateways take in a path. */ + override fun toString(): String = "b" + base32(bytes) + + override fun equals(other: Any?) = other is Cid && other.bytes.contentEquals(bytes) + + override fun hashCode() = bytes.contentHashCode() + + companion object { + + private const val SHA2_256_LENGTH = 32 + + /** An inlined block is meant for a few bytes; a larger one is not something a publisher makes. */ + private const val MAX_IDENTITY_LENGTH = 128 + + /** + * The CID in an EIP-1577 contenthash as `Navnisan` stores it, or null when it is not an + * `ipfs-ns` (`0xe3 0x01`) hash of a supported CID. `ipns-ns` is not content but a pointer + * that needs its own signed record, so it is not accepted here. + */ + fun fromContenthash(contenthash: ByteArray): Cid? { + if (contenthash.size < 2 || contenthash[0] != 0xe3.toByte() || contenthash[1] != 0x01.toByte()) return null + val reader = ByteReader(contenthash, 2) + return runCatching { read(reader) }.getOrNull()?.takeIf { reader.isExhausted && it.hash == Hash.SHA2_256 } + } + + /** The CID that fills [bytes] exactly. */ + fun parse(bytes: ByteArray): Cid { + val reader = ByteReader(bytes, 0) + return read(reader).also { require(reader.isExhausted) { "Trailing bytes after a CID" } } + } + + /** Reads one CID at the reader's position: CIDv0 is a bare sha2-256 multihash (`0x12 0x20`). */ + internal fun read(reader: ByteReader): Cid { + val start = reader.position + if (reader.peek() == Hash.SHA2_256.code) { + val digest = readMultihashDigest(reader, Hash.SHA2_256) + return Cid(reader.slice(start), Codec.DAG_PB, Hash.SHA2_256, digest) + } + + require(reader.varint() == 1L) { "Unsupported CID version" } + val codecCode = reader.varint() + val codec = Codec.values().firstOrNull { it.code.toLong() == codecCode } ?: throw IllegalArgumentException("Unsupported codec $codecCode") + val hashCode = reader.varint() + val hash = Hash.values().firstOrNull { it.code.toLong() == hashCode } ?: throw IllegalArgumentException("Unsupported hash $hashCode") + val digest = readDigest(reader, hash) + + return Cid(reader.slice(start), codec, hash, digest) + } + + private fun readMultihashDigest(reader: ByteReader, expected: Hash): ByteArray { + require(reader.varint() == expected.code.toLong()) { "Unexpected hash" } + return readDigest(reader, expected) + } + + private fun readDigest(reader: ByteReader, hash: Hash): ByteArray { + val length = reader.varint() + when (hash) { + Hash.SHA2_256 -> require(length == SHA2_256_LENGTH.toLong()) { "Bad sha2-256 length" } + Hash.IDENTITY -> require(length in 0..MAX_IDENTITY_LENGTH) { "Identity block too long" } + } + return reader.bytes(length.toInt()) + } + + private const val BASE32 = "abcdefghijklmnopqrstuvwxyz234567" + + private fun base32(data: ByteArray): String { + val out = StringBuilder() + var buffer = 0 + var bits = 0 + for (byte in data) { + buffer = (buffer shl 8) or (byte.toInt() and 0xff) + bits += 8 + while (bits >= 5) { + out.append(BASE32[(buffer shr (bits - 5)) and 31]) + bits -= 5 + } + } + if (bits > 0) out.append(BASE32[(buffer shl (5 - bits)) and 31]) + return out.toString() + } + } +} + +/** Bounded reads over bytes that came from the network: every read checks it stays inside. */ +internal class ByteReader(private val data: ByteArray, start: Int = 0, private val end: Int = data.size) { + + var position = start + private set + + val isExhausted: Boolean get() = position == end + + val remaining: Int get() = end - position + + fun peek(): Int { + require(position < end) { "Unexpected end of input" } + return data[position].toInt() and 0xff + } + + fun byte(): Int = peek().also { position++ } + + fun bytes(count: Int): ByteArray { + require(count in 0..remaining) { "Unexpected end of input" } + return data.copyOfRange(position, position + count).also { position += count } + } + + /** Unsigned LEB128, at most 63 bits and minimally encoded, as multiformats require. */ + fun varint(): Long { + var value = 0L + var shift = 0 + while (true) { + val byte = byte() + require(shift < 63) { "Varint too long" } + value = value or ((byte and 0x7f).toLong() shl shift) + if (byte and 0x80 == 0) { + require(byte != 0 || shift == 0) { "Varint not minimally encoded" } + return value + } + shift += 7 + } + } + + /** A reader over the next [count] bytes; this reader moves past them. */ + fun sub(count: Int): ByteReader { + require(count in 0..remaining) { "Unexpected end of input" } + return ByteReader(data, position, position + count).also { position += count } + } + + fun slice(from: Int): ByteArray = data.copyOfRange(from, position) +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/IpnsRecord.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/IpnsRecord.kt new file mode 100644 index 00000000..10452258 --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/IpnsRecord.kt @@ -0,0 +1,213 @@ +package io.novafoundation.nova.runtime.names.content + +import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters +import org.bouncycastle.crypto.signers.Ed25519Signer +import java.math.BigInteger +import java.time.Instant + +/** A feed release: the content root its publisher signed, and the release's number. */ +class IpnsRecord(val root: Cid, val sequence: Long) + +/** + * Verifies IPNS records (ipfs/specs `ipns-record`, V2) against a feed's publisher key as the chain + * gives it. The key in the record or in its name is never used: a mirror cannot answer for a feed + * with a record signed by someone else. + */ +object IpnsRecords { + + /** The spec's ceiling: a larger record is refused unread. */ + const val MAX_RECORD = 10 * 1024 + + private val SIGNATURE_PREFIX = "ipns-signature:".toByteArray() + + /** + * The release in [record], or null when it is not one [publisherKey] (ed25519) signed, has + * expired by [now], or points anywhere but at an immutable `/ipfs/` root. + */ + fun verify(record: ByteArray, publisherKey: ByteArray, now: Instant): IpnsRecord? = runCatching { + require(record.size <= MAX_RECORD && publisherKey.size == 32) + val entry = IpnsEntry.decode(record) + val data = entry.data ?: return null + val signature = entry.signatureV2 ?: return null + + val signer = Ed25519Signer().apply { + init(false, Ed25519PublicKeyParameters(publisherKey, 0)) + update(SIGNATURE_PREFIX, 0, SIGNATURE_PREFIX.size) + update(data, 0, data.size) + } + if (!signer.verifySignature(signature)) return null + + val signed = Cbor.decodeMap(data) + val value = signed["Value"] as? ByteArray ?: return null + val validity = signed["Validity"] as? ByteArray ?: return null + val validityType = signed["ValidityType"] as? BigInteger ?: return null + val sequence = signed["Sequence"] as? BigInteger ?: return null + + // Legacy copies outside the signed data must say the same, or they would be read instead of it + entry.value?.let { if (!it.contentEquals(value)) return null } + entry.validity?.let { if (!it.contentEquals(validity)) return null } + entry.validityType?.let { if (it != validityType.toLong()) return null } + entry.sequence?.let { if (it != sequence.toLong()) return null } + + // EOL is the only validity type there is + if (validityType != BigInteger.ZERO) return null + if (!Instant.parse(String(validity, Charsets.US_ASCII)).isAfter(now)) return null + + val path = String(value, Charsets.UTF_8) + if (!path.startsWith("/ipfs/")) return null + val root = CidText.parse(path.removePrefix("/ipfs/").substringBefore('/')) ?: return null + + IpnsRecord(root, sequence.longValueExact()) + }.getOrNull() + + /** The IPNS name of an ed25519 key: `k`-base36 CIDv1, codec libp2p-key, identity multihash of its protobuf form. */ + fun nameOf(publisherKey: ByteArray): String { + val protobufKey = byteArrayOf(0x08, 0x01, 0x12, 0x20) + publisherKey + val cid = byteArrayOf(0x01, 0x72, 0x00, protobufKey.size.toByte()) + protobufKey + return "k" + base36(cid) + } + + private fun base36(data: ByteArray): String { + val zeros = data.takeWhile { it == 0.toByte() }.size + val digits = BigInteger(1, data).toString(36).takeUnless { it == "0" }.orEmpty() + return "0".repeat(zeros) + digits + } + + private class IpnsEntry( + val value: ByteArray?, + val validityType: Long?, + val validity: ByteArray?, + val sequence: Long?, + val signatureV2: ByteArray?, + val data: ByteArray?, + ) { + companion object { + fun decode(bytes: ByteArray): IpnsEntry { + var value: ByteArray? = null + var validityType: Long? = null + var validity: ByteArray? = null + var sequence: Long? = null + var signatureV2: ByteArray? = null + var data: ByteArray? = null + + val reader = ByteReader(bytes) + while (!reader.isExhausted) { + val key = reader.varint() + when (key and 7) { + 0L -> { + val number = reader.varint() + when (key ushr 3) { + 3L -> validityType = number + 5L -> sequence = number + } + } + 2L -> { + val length = reader.varint() + require(length in 0..reader.remaining.toLong()) + val field = reader.bytes(length.toInt()) + when (key ushr 3) { + 1L -> value = field + 4L -> validity = field + 8L -> signatureV2 = field + 9L -> data = field + } + } + else -> throw IllegalArgumentException("Unsupported wire type") + } + } + return IpnsEntry(value, validityType, validity, sequence, signatureV2, data) + } + } + } +} + +/** The DAG-CBOR an IPNS record signs: one map of text keys to byte strings, text and unsigned integers. */ +internal object Cbor { + + fun decodeMap(bytes: ByteArray): Map { + val reader = ByteReader(bytes) + val (major, count) = head(reader) + require(major == 5) { "Not a map" } + val map = mutableMapOf() + repeat(count.toInt()) { + val key = item(reader) as? String ?: throw IllegalArgumentException("Map key is not text") + map[key] = item(reader) + } + require(reader.isExhausted) { "Trailing bytes after the map" } + return map + } + + private fun item(reader: ByteReader): Any { + val (major, argument) = head(reader) + return when (major) { + 0 -> argument + 2 -> reader.bytes(length(reader, argument)) + 3 -> String(reader.bytes(length(reader, argument)), Charsets.UTF_8) + else -> throw IllegalArgumentException("Unsupported CBOR major type $major") + } + } + + private fun length(reader: ByteReader, argument: BigInteger): Int { + require(argument <= BigInteger.valueOf(reader.remaining.toLong())) { "Length past the end" } + return argument.toInt() + } + + private fun head(reader: ByteReader): Pair { + val initial = reader.byte() + val major = initial ushr 5 + val info = initial and 0x1f + val argument = when { + info < 24 -> BigInteger.valueOf(info.toLong()) + info == 24 -> BigInteger.valueOf(reader.byte().toLong()) + info == 25 -> BigInteger(1, reader.bytes(2)) + info == 26 -> BigInteger(1, reader.bytes(4)) + info == 27 -> BigInteger(1, reader.bytes(8)) + else -> throw IllegalArgumentException("Indefinite or reserved CBOR length") + } + return major to argument + } +} + +/** A CID as text in a path: multibase base32 (`b…`) or a CIDv0 in base58btc (`Qm…`). */ +internal object CidText { + + private const val BASE32 = "abcdefghijklmnopqrstuvwxyz234567" + private const val BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + + fun parse(text: String): Cid? = runCatching { + when { + text.startsWith("Qm") && text.length == 46 -> Cid.parse(base58(text)) + text.startsWith("b") -> Cid.parse(base32(text.substring(1))) + else -> null + } + }.getOrNull() + + private fun base32(text: String): ByteArray { + val out = java.io.ByteArrayOutputStream() + var buffer = 0 + var bits = 0 + for (char in text) { + val value = BASE32.indexOf(char) + require(value >= 0) { "Not base32" } + buffer = (buffer shl 5) or value + bits += 5 + if (bits >= 8) { + out.write((buffer shr (bits - 8)) and 0xff) + bits -= 8 + } + } + return out.toByteArray() + } + + private fun base58(text: String): ByteArray { + var number = BigInteger.ZERO + for (char in text) { + val value = BASE58.indexOf(char) + require(value >= 0) { "Not base58" } + number = number.multiply(BigInteger.valueOf(58)).add(BigInteger.valueOf(value.toLong())) + } + val bytes = number.toByteArray().dropWhile { it == 0.toByte() }.toByteArray() + val zeros = text.takeWhile { it == '1' }.length + return ByteArray(zeros) + bytes + } +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/KurdContentFetcher.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/KurdContentFetcher.kt new file mode 100644 index 00000000..49627856 --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/KurdContentFetcher.kt @@ -0,0 +1,151 @@ +package io.novafoundation.nova.runtime.names.content + +import android.util.Log +import retrofit2.http.GET +import retrofit2.http.Url + +/** Where `.kurd` content is fetched from: IPFS trustless gateways that answer `?format=car`. */ +interface KurdGateways { + + /** Base URLs, `https://host`, in the order they are tried. */ + suspend fun list(): List +} + +interface KurdGatewayListApi { + + /** A file of the config repository, checked against its signed targets by the app's HTTP client. */ + @GET + suspend fun gateways(@Url url: String): GatewayListRemote +} + +class GatewayListRemote(val gateways: List?) { + + class GatewayRemote(val url: String?) +} + +/** + * The signed list from the config repository when it can be read, the built-in one otherwise. The + * list can only add or reorder gateways: whatever a gateway sends is verified block by block, so a + * bad entry costs time, never content. + */ +class RealKurdGateways( + private val api: KurdGatewayListApi, + private val refreshMillis: Long = 30 * 60_000L, + private val clock: () -> Long = System::currentTimeMillis, +) : KurdGateways { + + @Volatile + private var remote: Pair>? = null + + override suspend fun list(): List { + val cached = remote + if (cached != null && clock() - cached.first < refreshMillis) return cached.second + + val fetched = runCatching { api.gateways(LIST_URL).gateways.orEmpty().mapNotNull { it.url?.let(::normalized) } } + .onFailure { Log.w(TAG, "Signed gateway list unavailable, using the built-in one", it) } + .getOrNull() + ?.takeIf { it.isNotEmpty() } + + if (fetched != null) remote = clock() to fetched + return fetched ?: cached?.second ?: BUILT_IN + } + + companion object { + + const val LIST_URL = "https://raw.githubusercontent.com/pezkuwichain/pezkuwi-wallet-utils/master/kurd/gateways.json" + + /** Measured reachable from Türkiye (architecture, M0); our own mirrors join through the signed list. */ + val BUILT_IN = listOf("https://ipfs.io", "https://dweb.link") + + private const val TAG = "KurdGateways" + + /** `https://host[:port]` only: a path or query in an entry would change what is asked for. */ + internal fun normalized(url: String): String? { + val match = Regex("^https://([a-z0-9.-]+)(:[0-9]{1,5})?/?$").matchEntire(url.trim().lowercase()) ?: return null + return "https://" + match.groupValues[1] + match.groupValues[2] + } + } +} + +/** One gateway's answer for a CAR request: the bytes, or null when it has none (404 and the like). */ +fun interface CarSource { + + suspend fun car(gateway: String, root: Cid, path: List): ByteArray? +} + +/** + * Fetches a path under a content root from the gateways, in order, and keeps the first answer that + * verifies. A gateway that fails, times out, withholds a block or sends a changed one is skipped. + */ +class KurdContentFetcher( + private val gateways: KurdGateways, + private val source: CarSource, + private val maxFileSize: Int = UnixFsReader.DEFAULT_MAX_FILE, +) { + + sealed interface Result { + + class File(val bytes: ByteArray, val path: List) : Result + + /** Proven absent: the parent directory was verified and does not have the name. */ + object NotFound : Result + + /** No gateway gave a verifiable answer. */ + object Unavailable : Result + } + + /** The file at [path] under [root]; a directory gives its `index.html`. */ + suspend fun fetch(root: Cid, path: List): Result { + return when (val entry = entry(root, path)) { + is Lookup.Found -> when (val found = entry.entry) { + is UnixFsReader.Entry.File -> Result.File(found.bytes, path) + is UnixFsReader.Entry.Directory -> when (val index = entry(root, path + INDEX)) { + is Lookup.Found -> (index.entry as? UnixFsReader.Entry.File)?.let { Result.File(it.bytes, path + INDEX) } ?: Result.NotFound + Lookup.Absent -> Result.NotFound + Lookup.Unavailable -> Result.Unavailable + } + } + Lookup.Absent -> Result.NotFound + Lookup.Unavailable -> Result.Unavailable + } + } + + private sealed interface Lookup { + class Found(val entry: UnixFsReader.Entry) : Lookup + object Absent : Lookup + object Unavailable : Lookup + } + + private suspend fun entry(root: Cid, path: List): Lookup { + for (gateway in gateways.list()) { + val entry = runCatching { read(gateway, root, path) } + .onFailure { Log.w(TAG, "Gateway $gateway gave no verifiable answer for $root", it) } + .getOrNull() + if (entry != null) return entry + } + return Lookup.Unavailable + } + + /** Null when this gateway could not answer; [Lookup.Absent] only once absence is verified. */ + private suspend fun read(gateway: String, root: Cid, path: List): Lookup? { + val car = source.car(gateway, root, path) + if (car != null) { + val entry = UnixFsReader(VerifiedBlocks.fromCar(car), maxFileSize).read(root, path) ?: return null + return Lookup.Found(entry) + } + + // A gateway that says "not found" may be withholding: check the parent directory says so + if (path.isEmpty()) return null + val parentCar = source.car(gateway, root, path.dropLast(1)) ?: return null + val reader = UnixFsReader(VerifiedBlocks.fromCar(parentCar), maxFileSize) + if (reader.read(root, path.dropLast(1)) !is UnixFsReader.Entry.Directory) return null + return if (reader.read(root, path) == null) Lookup.Absent else null + } + + companion object { + + const val INDEX = "index.html" + + private const val TAG = "KurdContentFetcher" + } +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/KurdFeedResolver.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/KurdFeedResolver.kt new file mode 100644 index 00000000..eeb23f69 --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/KurdFeedResolver.kt @@ -0,0 +1,74 @@ +package io.novafoundation.nova.runtime.names.content + +import io.novafoundation.nova.runtime.names.NameRecord +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.withContext +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import okhttp3.OkHttpClient +import okhttp3.Request +import java.time.Instant + +/** One gateway's IPNS record for a name, or null when it has none. */ +fun interface IpnsRecordSource { + + suspend fun record(gateway: String, name: String): ByteArray? +} + +class OkHttpIpnsRecordSource(private val client: OkHttpClient) : IpnsRecordSource { + + override suspend fun record(gateway: String, name: String): ByteArray? = withContext(Dispatchers.IO) { + val url = gateway.toHttpUrlOrNull()?.newBuilder() + ?.addPathSegment("ipns") + ?.addPathSegment(name) + ?.addQueryParameter("format", "ipns-record") + ?.build() + ?: return@withContext null + val request = Request.Builder().url(url).header("Accept", "application/vnd.ipfs.ipns-record").build() + + client.newCall(request).execute().use { response -> + if (!response.isSuccessful) return@withContext null + val source = response.body?.source() ?: return@withContext null + if (source.request(IpnsRecords.MAX_RECORD + 1L)) return@withContext null + source.buffer.readByteArray() + } + } +} + +/** + * The release a feed name serves: the newest one its publisher signed that any gateway has, never + * older than the release the chain was last told of (its anchor), and the anchor itself when no + * gateway has a record to show. + */ +class KurdFeedResolver( + private val gateways: KurdGateways, + private val source: IpnsRecordSource, + private val clock: () -> Instant = Instant::now, +) { + + /** [onChainVersion]: no gateway confirmed a release at or past the anchor, so newer ones may exist. */ + class Release(val root: Cid, val onChainVersion: Boolean) + + suspend fun resolve(feed: NameRecord.Content.Feed): Release? { + val anchor = Cid.fromContenthash(feed.anchor) ?: return null + val floor = feed.seq + val name = IpnsRecords.nameOf(feed.publisher) + val now = clock() + + val records = coroutineScope { + gateways.list().map { gateway -> + async { runCatching { source.record(gateway, name) }.getOrNull()?.let { IpnsRecords.verify(it, feed.publisher, now) } } + }.awaitAll() + } + val newest = records.filterNotNull().filter { it.sequence.toBigInteger() >= floor }.maxByOrNull { it.sequence } + + return when { + newest == null -> Release(anchor, onChainVersion = true) + // The release the chain already names: its root is the chain's word, not a gateway's + newest.sequence.toBigInteger() == floor -> Release(anchor, onChainVersion = false) + else -> Release(newest.root, onChainVersion = false) + } + } +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/KurdSiteServer.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/KurdSiteServer.kt new file mode 100644 index 00000000..b9cd1013 --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/KurdSiteServer.kt @@ -0,0 +1,189 @@ +package io.novafoundation.nova.runtime.names.content + +import io.novafoundation.nova.runtime.names.KurdName +import io.novafoundation.nova.runtime.names.KurdNameResolver +import io.novafoundation.nova.runtime.names.KurdResolution +import io.novafoundation.nova.runtime.names.NameRecord +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.update +import java.util.concurrent.ConcurrentHashMap + +/** + * Answers the DApp browser's requests to `https://.kurd/...`: the name is resolved on chain, + * its content root fetched from gateways and verified, and only then served. The page's origin is + * the full name, so cookies, storage and permissions belong to that name alone. + */ +class KurdSiteServer( + private val resolver: KurdNameResolver, + private val fetcher: KurdContentFetcher, + private val feeds: KurdFeedResolver? = null, + private val resolutionTtlMillis: Long = 60_000L, + private val clock: () -> Long = System::currentTimeMillis, +) { + + class Response(val status: Int, val reason: String, val mimeType: String, val body: ByteArray) { + + /** The policy the wallet writes for every `.kurd` page: nothing loads or connects outside the name. */ + val headers: Map = mapOf( + "Content-Security-Policy" to CONTENT_SECURITY_POLICY, + "X-Content-Type-Options" to "nosniff", + "Referrer-Policy" to "no-referrer", + "Cache-Control" to "no-store", + ) + } + + /** How the browser shows a `.kurd` page: set by its top-level document, read by the address bar and notices. */ + sealed interface PageState { + + /** + * Content verified and served. [resolution] says how the name itself was read; for a feed, + * [onChainVersion] means no gateway confirmed a release past the one the chain names. + */ + class Open(val resolution: KurdResolution.Resolved, val root: Cid, val onChainVersion: Boolean = false) : PageState + + /** Read through RPC nodes only; the content waits until the reader chooses to open it. */ + class NeedsConsent(val resolution: KurdResolution.Resolved) : PageState + + /** Official or institutional and not verifiable now: never opened (decision D18). */ + object Refused : PageState + + object NotRegistered : PageState + + /** Registered, but no site: no content, or content of a kind this wallet does not serve. */ + object NoSite : PageState + + object Unavailable : PageState + } + + private val resolutions = ConcurrentHashMap>() + private val consented: MutableSet = ConcurrentHashMap.newKeySet() + + private val _pageStates = MutableStateFlow>(emptyMap()) + val pageStates: StateFlow> = _pageStates + + /** + * The reader chose to open [name] although only RPC nodes vouched for it; holds until the app + * restarts. Never offered for a name that must be verified, which is [PageState.Refused]. + */ + fun allowUnverified(name: KurdName) { + consented += name + resolutions -= name + } + + /** Forgets [name]'s resolution, so a retry reads the chain again. */ + fun forget(name: KurdName) { + resolutions -= name + } + + /** [mainFrame]: the page's own document, whose outcome becomes the name's [PageState]. */ + suspend fun serve(host: String, encodedPath: String, mainFrame: Boolean = false): Response { + val name = KurdName.parse(host) ?: return status(404, "Not Found") + val segments = decodePath(encodedPath) ?: return status(400, "Bad Request") + + val (state, response) = handle(name, segments) + if (mainFrame) _pageStates.update { it + (name to state) } + return response + } + + private suspend fun handle(name: KurdName, segments: List): Pair { + val resolution = when (val resolved = resolve(name)) { + is KurdResolution.Resolved -> resolved + is KurdResolution.NotFound -> return PageState.NotRegistered to status(404, "Not Found") + is KurdResolution.Refused -> return PageState.Refused to status(403, "Forbidden") + is KurdResolution.Unavailable -> return PageState.Unavailable to status(502, "Bad Gateway") + } + + if (resolution.record.content == null) return PageState.NoSite to status(404, "Not Found") + if (!resolution.verified && name !in consented) return PageState.NeedsConsent(resolution) to status(428, "Precondition Required") + + val (root, onChainVersion) = when (val content = resolution.record.content) { + is NameRecord.Content.Ipfs -> { + val cid = Cid.fromContenthash(content.contenthash) ?: return PageState.NoSite to status(415, "Unsupported Media Type") + cid to false + } + is NameRecord.Content.Feed -> { + val release = feeds?.resolve(content) ?: return PageState.NoSite to status(415, "Unsupported Media Type") + release.root to release.onChainVersion + } + null -> return PageState.NoSite to status(404, "Not Found") + } + + val open = PageState.Open(resolution, root, onChainVersion) + return when (val result = fetcher.fetch(root, segments)) { + is KurdContentFetcher.Result.File -> open to Response(200, "OK", mimeTypeOf(result.path.lastOrNull()), result.bytes) + KurdContentFetcher.Result.NotFound -> open to status(404, "Not Found") + KurdContentFetcher.Result.Unavailable -> PageState.Unavailable to status(502, "Bad Gateway") + } + } + + private suspend fun resolve(name: KurdName): KurdResolution { + val now = clock() + resolutions[name]?.let { (at, resolution) -> if (now - at < resolutionTtlMillis) return resolution } + return resolver.resolve(name).also { resolutions[name] = now to it } + } + + private fun status(code: Int, reason: String) = Response(code, reason, "text/plain", ByteArray(0)) + + companion object { + + const val CONTENT_SECURITY_POLICY = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; " + + "img-src 'self' data: blob:; media-src 'self' blob:; font-src 'self' data:; connect-src 'self'; " + + "worker-src 'none'; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" + + /** + * Path segments, percent-decoded one by one. Null for a malformed escape, a non-UTF-8 byte + * sequence, or a segment that is `.`, `..` or holds an encoded `/`: none names a file. + */ + fun decodePath(encodedPath: String): List? { + val segments = encodedPath.substringBefore('?').substringBefore('#').split('/').filter { it.isNotEmpty() } + return segments.map { encoded -> + percentDecode(encoded)?.takeIf { it != "." && it != ".." && '/' !in it && it.isNotEmpty() } ?: return null + } + } + + private fun percentDecode(segment: String): String? { + val out = java.io.ByteArrayOutputStream() + var index = 0 + while (index < segment.length) { + val char = segment[index] + if (char == '%') { + if (index + 3 > segment.length) return null + val high = hexValue(segment[index + 1]) + val low = hexValue(segment[index + 2]) + if (high < 0 || low < 0) return null + out.write(high * 16 + low) + index += 3 + } else { + out.write(char.toString().toByteArray(Charsets.UTF_8)) + index++ + } + } + val bytes = out.toByteArray() + val decoder = Charsets.UTF_8.newDecoder() + return runCatching { decoder.decode(java.nio.ByteBuffer.wrap(bytes)).toString() }.getOrNull() + } + + /** ASCII hex only: `Character.digit` would also take other scripts' digits. */ + private fun hexValue(char: Char): Int = when (char) { + in '0'..'9' -> char - '0' + in 'a'..'f' -> char - 'a' + 10 + in 'A'..'F' -> char - 'A' + 10 + else -> -1 + } + + private val MIME_TYPES = mapOf( + "html" to "text/html", "htm" to "text/html", "css" to "text/css", "js" to "text/javascript", "mjs" to "text/javascript", + "json" to "application/json", "map" to "application/json", "txt" to "text/plain", "xml" to "application/xml", + "svg" to "image/svg+xml", "png" to "image/png", "jpg" to "image/jpeg", "jpeg" to "image/jpeg", "gif" to "image/gif", + "webp" to "image/webp", "avif" to "image/avif", "ico" to "image/x-icon", "woff" to "font/woff", "woff2" to "font/woff2", + "ttf" to "font/ttf", "otf" to "font/otf", "wasm" to "application/wasm", "mp3" to "audio/mpeg", "ogg" to "audio/ogg", + "mp4" to "video/mp4", "webm" to "video/webm", "pdf" to "application/pdf", + ) + + fun mimeTypeOf(fileName: String?): String { + val extension = fileName?.substringAfterLast('.', missingDelimiterValue = "")?.lowercase().orEmpty() + return MIME_TYPES[extension] ?: "application/octet-stream" + } + } +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/OkHttpCarSource.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/OkHttpCarSource.kt new file mode 100644 index 00000000..d5bf0c14 --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/OkHttpCarSource.kt @@ -0,0 +1,44 @@ +package io.novafoundation.nova.runtime.names.content + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import okhttp3.OkHttpClient +import okhttp3.Request +import java.io.IOException + +/** + * Asks a trustless gateway for the blocks of one path as a CAR (`dag-scope=entity`: the path's + * directories and the whole file or directory at its end), never more than [maxCarBytes]. + */ +class OkHttpCarSource( + private val client: OkHttpClient, + private val maxCarBytes: Long = UnixFsReader.DEFAULT_MAX_FILE + 8L * 1024 * 1024, +) : CarSource { + + override suspend fun car(gateway: String, root: Cid, path: List): ByteArray? = withContext(Dispatchers.IO) { + val url = gateway.toHttpUrlOrNull()?.newBuilder() + ?.addPathSegment("ipfs") + ?.addPathSegment(root.toString()) + ?.apply { path.forEach(::addPathSegment) } + ?.addQueryParameter("format", "car") + ?.addQueryParameter("dag-scope", "entity") + ?.build() + ?: return@withContext null + + val request = Request.Builder() + .url(url) + .header("Accept", "application/vnd.ipld.car;version=1;order=dfs;dups=y") + .build() + + client.newCall(request).execute().use { response -> + if (!response.isSuccessful) return@withContext null + val body = response.body ?: return@withContext null + if (body.contentLength() > maxCarBytes) throw IOException("CAR larger than $maxCarBytes bytes") + + val source = body.source() + if (source.request(maxCarBytes + 1)) throw IOException("CAR larger than $maxCarBytes bytes") + source.buffer.readByteArray() + } + } +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/UnixFs.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/UnixFs.kt new file mode 100644 index 00000000..ab47525b --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/UnixFs.kt @@ -0,0 +1,106 @@ +package io.novafoundation.nova.runtime.names.content + +/** A dag-pb node: `PBNode { repeated PBLink Links = 2; optional bytes Data = 1; }`, fields in any order. */ +internal class PbNode(val links: List, val data: ByteArray?) { + + class PbLink(val cid: Cid, val name: String?, val size: Long?) + + companion object { + + fun decode(block: ByteArray): PbNode { + val links = mutableListOf() + var data: ByteArray? = null + val reader = ByteReader(block) + while (!reader.isExhausted) { + when (val key = reader.varint()) { + // Data + (1L shl 3) or 2 -> { + require(data == null) { "Data twice" } + data = reader.bytes(lengthOf(reader)) + } + // Links + (2L shl 3) or 2 -> links += decodeLink(reader.sub(lengthOf(reader))) + else -> throw IllegalArgumentException("Unknown dag-pb field $key") + } + } + return PbNode(links, data) + } + + private fun decodeLink(reader: ByteReader): PbLink { + var cid: Cid? = null + var name: String? = null + var size: Long? = null + while (!reader.isExhausted) { + when (val key = reader.varint()) { + (1L shl 3) or 2 -> cid = Cid.parse(reader.bytes(lengthOf(reader))) + (2L shl 3) or 2 -> name = String(reader.bytes(lengthOf(reader)), Charsets.UTF_8) + (3L shl 3) or 0 -> size = reader.varint() + else -> throw IllegalArgumentException("Unknown dag-pb link field $key") + } + } + return PbLink(cid ?: throw IllegalArgumentException("Link without a hash"), name, size) + } + } +} + +/** UnixFS `Data`, the payload of a dag-pb node that is part of a file system. */ +internal class UnixFsData( + val type: Type, + val data: ByteArray?, + val fileSize: Long?, + val blockSizes: List, + val hashType: Long?, + val fanout: Long?, +) { + + enum class Type { RAW, DIRECTORY, FILE, METADATA, SYMLINK, HAMT_SHARD } + + companion object { + + fun decode(bytes: ByteArray): UnixFsData { + var type: Type? = null + var data: ByteArray? = null + var fileSize: Long? = null + val blockSizes = mutableListOf() + var hashType: Long? = null + var fanout: Long? = null + + val reader = ByteReader(bytes) + while (!reader.isExhausted) { + val key = reader.varint() + val field = key ushr 3 + when (key and 7) { + 0L -> { + val value = reader.varint() + when (field) { + 1L -> type = Type.values().getOrNull(value.toInt()) ?: throw IllegalArgumentException("Unknown UnixFS type $value") + 3L -> fileSize = value + 4L -> blockSizes += value + 5L -> hashType = value + 6L -> fanout = value + // mode (7) and other scalar metadata do not change what is served + } + } + 2L -> { + val value = reader.bytes(lengthOf(reader)) + when (field) { + 2L -> data = value + // packed blocksizes + 4L -> ByteReader(value).let { packed -> while (!packed.isExhausted) blockSizes += packed.varint() } + // mtime (8) and other nested metadata do not change what is served + } + } + else -> throw IllegalArgumentException("Unsupported UnixFS wire type") + } + } + + return UnixFsData(type ?: throw IllegalArgumentException("UnixFS without a type"), data, fileSize, blockSizes, hashType, fanout) + } + } +} + +private fun lengthOf(reader: ByteReader): Int { + val length = reader.varint() + require(length in 0..reader.remaining.toLong()) { "Length past the end" } + return length.toInt() +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/UnixFsReader.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/UnixFsReader.kt new file mode 100644 index 00000000..e7ce2cc6 --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/UnixFsReader.kt @@ -0,0 +1,197 @@ +package io.novafoundation.nova.runtime.names.content + +/** + * Walks a UnixFS tree held in [blocks] and assembles files from it. Every block was checked + * against its CID when the CAR was read, and every step here follows a CID taken from a block + * already checked, so what comes out is exactly what the root CID names. + */ +class UnixFsReader(private val blocks: VerifiedBlocks, private val maxFileSize: Int = DEFAULT_MAX_FILE) { + + sealed interface Entry { + class File(val bytes: ByteArray) : Entry + class Directory(val cid: Cid) : Entry + } + + /** The entry at [path] (segments, already split and decoded) under [root]. Null when nothing is there. */ + fun read(root: Cid, path: List): Entry? = verify { + var cid = root + for (segment in path) { + require(segment.isNotEmpty() && segment != "." && segment != ".." && '/' !in segment) { "Bad path segment" } + cid = child(cid, segment) ?: return@verify null + } + entry(cid) + } + + private fun entry(cid: Cid): Entry { + if (cid.codec == Cid.Codec.RAW) return Entry.File(blocks.get(cid).also(::checkSize)) + + val node = PbNode.decode(blocks.get(cid)) + val unixFs = UnixFsData.decode(node.data ?: throw IllegalArgumentException("dag-pb node without UnixFS data")) + return when (unixFs.type) { + UnixFsData.Type.FILE, UnixFsData.Type.RAW -> Entry.File(assemble(node, unixFs)) + UnixFsData.Type.DIRECTORY, UnixFsData.Type.HAMT_SHARD -> Entry.Directory(cid) + UnixFsData.Type.SYMLINK, UnixFsData.Type.METADATA -> throw ContentVerificationException("Unsupported UnixFS entry ${unixFs.type}") + } + } + + private fun child(directory: Cid, name: String): Cid? { + if (directory.codec != Cid.Codec.DAG_PB) return null + val node = PbNode.decode(blocks.get(directory)) + val unixFs = UnixFsData.decode(node.data ?: throw IllegalArgumentException("dag-pb node without UnixFS data")) + + return when (unixFs.type) { + UnixFsData.Type.DIRECTORY -> node.links.singleOrNull { it.name == name }?.cid + UnixFsData.Type.HAMT_SHARD -> shardLookup(node, unixFs, name, HashBits(murmur3x64_64(name.toByteArray(Charsets.UTF_8))), depth = 0) + else -> null + } + } + + /** + * HAMT directory lookup, as `go-unixfs`/`boxo` shard: each level consumes log2(fanout) bits of + * the name's murmur3-x64-64 hash, most significant first; a link named by the bucket index + * alone (upper-case hex) is a child shard, one named by index plus the entry name is the entry. + */ + private fun shardLookup(node: PbNode, unixFs: UnixFsData, name: String, bits: HashBits, depth: Int): Cid? { + require(unixFs.hashType == MURMUR3_X64_64) { "Unsupported HAMT hash" } + val fanout = unixFs.fanout ?: throw IllegalArgumentException("HAMT without fanout") + require(fanout in 2..MAX_FANOUT && fanout and (fanout - 1) == 0L) { "Bad HAMT fanout" } + val width = java.lang.Long.numberOfTrailingZeros(fanout) + require(depth < 64 / width) { "HAMT deeper than its hash" } + + val padLength = (fanout - 1).toString(16).length + val prefix = bits.next(width).toString(16).uppercase().padStart(padLength, '0') + + for (link in node.links) { + val linkName = link.name ?: continue + if (!linkName.startsWith(prefix)) continue + if (linkName.length == padLength) { + val shard = PbNode.decode(blocks.get(link.cid)) + val shardData = UnixFsData.decode(shard.data ?: throw IllegalArgumentException("Shard without data")) + require(shardData.type == UnixFsData.Type.HAMT_SHARD && shardData.fanout == fanout) { "Inconsistent HAMT shard" } + return shardLookup(shard, shardData, name, bits, depth + 1) + } + if (linkName.substring(padLength) == name) return link.cid + } + return null + } + + private fun assemble(node: PbNode, unixFs: UnixFsData): ByteArray { + val out = java.io.ByteArrayOutputStream() + appendFile(node, unixFs, out, depth = 0) + return out.toByteArray() + } + + /** A file node's own data comes first, then its children in link order. */ + private fun appendFile(node: PbNode, unixFs: UnixFsData, out: java.io.ByteArrayOutputStream, depth: Int) { + require(depth < MAX_FILE_DEPTH) { "File tree too deep" } + unixFs.data?.let { append(out, it) } + + for (link in node.links) { + if (link.cid.codec == Cid.Codec.RAW) { + append(out, blocks.get(link.cid)) + continue + } + val child = PbNode.decode(blocks.get(link.cid)) + val childData = UnixFsData.decode(child.data ?: throw IllegalArgumentException("File part without data")) + require(childData.type == UnixFsData.Type.FILE || childData.type == UnixFsData.Type.RAW) { "File part is not a file" } + appendFile(child, childData, out, depth + 1) + } + } + + private fun append(out: java.io.ByteArrayOutputStream, bytes: ByteArray) { + checkSize(out.size().toLong() + bytes.size) + out.write(bytes) + } + + private fun checkSize(bytes: ByteArray) = checkSize(bytes.size.toLong()) + + private fun checkSize(size: Long) { + if (size > maxFileSize) throw ContentVerificationException("File larger than $maxFileSize bytes") + } + + private inline fun verify(block: () -> T): T = try { + block() + } catch (e: IllegalArgumentException) { + throw ContentVerificationException("Malformed UnixFS: ${e.message}") + } + + /** The bits of a hash, most significant first. */ + private class HashBits(private val hash: Long) { + + private var used = 0 + + fun next(count: Int): Long { + require(used + count <= 64) { "HAMT hash exhausted" } + val value = (hash ushr (64 - used - count)) and ((1L shl count) - 1) + used += count + return value + } + } + + companion object { + + const val DEFAULT_MAX_FILE = 32 * 1024 * 1024 + + /** Multicodec `murmur3-x64-64`, the only hash UnixFS shards use. */ + private const val MURMUR3_X64_64 = 0x22L + private const val MAX_FANOUT = 1024L + private const val MAX_FILE_DEPTH = 32 + + /** The first 64 bits of MurmurHash3 x64 128 with seed 0 (`murmur3.New64` in Go). */ + internal fun murmur3x64_64(data: ByteArray): Long { + val c1 = -0x783c846eeebdac2bL // 0x87c37b91114253d5 + val c2 = 0x4cf5ad432745937fL + var h1 = 0L + var h2 = 0L + + fun littleEndian(offset: Int, count: Int): Long { + var value = 0L + for (i in count - 1 downTo 0) value = (value shl 8) or (data[offset + i].toLong() and 0xff) + return value + } + + val blocks = data.size / 16 + for (block in 0 until blocks) { + var k1 = littleEndian(block * 16, 8) + var k2 = littleEndian(block * 16 + 8, 8) + + k1 *= c1; k1 = java.lang.Long.rotateLeft(k1, 31); k1 *= c2; h1 = h1 xor k1 + h1 = java.lang.Long.rotateLeft(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729 + + k2 *= c2; k2 = java.lang.Long.rotateLeft(k2, 33); k2 *= c1; h2 = h2 xor k2 + h2 = java.lang.Long.rotateLeft(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5 + } + + val tail = blocks * 16 + val tailLength = data.size - tail + if (tailLength > 8) { + var k2 = littleEndian(tail + 8, tailLength - 8) + k2 *= c2; k2 = java.lang.Long.rotateLeft(k2, 33); k2 *= c1; h2 = h2 xor k2 + } + if (tailLength > 0) { + var k1 = littleEndian(tail, minOf(tailLength, 8)) + k1 *= c1; k1 = java.lang.Long.rotateLeft(k1, 31); k1 *= c2; h1 = h1 xor k1 + } + + h1 = h1 xor data.size.toLong() + h2 = h2 xor data.size.toLong() + h1 += h2 + h2 += h1 + h1 = fmix(h1) + h2 = fmix(h2) + h1 += h2 + + return h1 + } + + private fun fmix(value: Long): Long { + var k = value + k = k xor (k ushr 33) + k *= -0xae502812aa7333L // 0xff51afd7ed558ccd + k = k xor (k ushr 33) + k *= -0x3b314601e57a13adL // 0xc4ceb9fe1a85ec53 + k = k xor (k ushr 33) + return k + } + } +} diff --git a/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/VerifiedBlocks.kt b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/VerifiedBlocks.kt new file mode 100644 index 00000000..6bd660c7 --- /dev/null +++ b/runtime/src/main/java/io/novafoundation/nova/runtime/names/content/VerifiedBlocks.kt @@ -0,0 +1,67 @@ +package io.novafoundation.nova.runtime.names.content + +class ContentVerificationException(message: String) : Exception(message) + +/** + * Blocks whose bytes have each been checked against their CID. Built only from a CAR the network + * sent, so a mirror can leave blocks out (the read then fails) but cannot change one. + */ +class VerifiedBlocks private constructor(private val blocks: Map) { + + /** The block named by [cid], or a failure when no mirror sent it. */ + fun get(cid: Cid): ByteArray = cid.inlineBlock ?: blocks[cid] ?: throw ContentVerificationException("Missing block $cid") + + val size: Int get() = blocks.size + + companion object { + + /** A block larger than this is not one IPFS tooling produces (its limit is 1 MiB, plus framing). */ + const val MAX_BLOCK = 2 * 1024 * 1024 + + private const val MAX_HEADER = 1024 + + /** + * Reads a CARv1 stream. Every block must match its CID or the whole CAR is refused: a mirror + * that changes one byte is not a mirror. The header's roots are not trusted; the caller + * starts from the CID the chain gave. + */ + fun fromCar(car: ByteArray): VerifiedBlocks { + val reader = ByteReader(car) + try { + val headerLength = reader.varint() + require(headerLength in 1..MAX_HEADER) { "Bad CAR header length" } + requireCarV1(reader.bytes(headerLength.toInt())) + + val blocks = mutableMapOf() + while (!reader.isExhausted) { + val sectionLength = reader.varint() + require(sectionLength in 1..(MAX_BLOCK + 128).toLong()) { "Bad CAR section length" } + val section = reader.sub(sectionLength.toInt()) + val cid = Cid.read(section) + val block = section.bytes(section.remaining) + if (!cid.matches(block)) throw ContentVerificationException("Block does not match $cid") + blocks[cid] = block + } + + return VerifiedBlocks(blocks) + } catch (e: IllegalArgumentException) { + throw ContentVerificationException("Malformed CAR: ${e.message}") + } + } + + /** Header is the dag-cbor map `{roots: [...], version: 1}`; only the version is read. */ + private fun requireCarV1(header: ByteArray) { + val versionKey = byteArrayOf(0x67) + "version".toByteArray() + val at = indexOf(header, versionKey) + require(at >= 0 && at + versionKey.size < header.size && header[at + versionKey.size] == 0x01.toByte()) { "Not a CARv1" } + } + + private fun indexOf(haystack: ByteArray, needle: ByteArray): Int { + outer@ for (start in 0..haystack.size - needle.size) { + for (offset in needle.indices) if (haystack[start + offset] != needle[offset]) continue@outer + return start + } + return -1 + } + } +} diff --git a/runtime/src/test/java/android/util/Log.java b/runtime/src/test/java/android/util/Log.java index 12627f4d..94e03307 100644 --- a/runtime/src/test/java/android/util/Log.java +++ b/runtime/src/test/java/android/util/Log.java @@ -17,6 +17,11 @@ public class Log { return 0; } + public static int w(String tag, String msg, Throwable tr) { + System.out.println("WARN: " + tag + ": " + msg + ": " + tr); + return 0; + } + public static int e(String tag, String msg) { System.out.println("ERROR: " + tag + ": " + msg); return 0; diff --git a/runtime/src/test/java/io/novafoundation/nova/runtime/multiNetwork/connection/light/LightClientLeasesTest.kt b/runtime/src/test/java/io/novafoundation/nova/runtime/multiNetwork/connection/light/LightClientLeasesTest.kt new file mode 100644 index 00000000..7424529b --- /dev/null +++ b/runtime/src/test/java/io/novafoundation/nova/runtime/multiNetwork/connection/light/LightClientLeasesTest.kt @@ -0,0 +1,47 @@ +package io.novafoundation.nova.runtime.multiNetwork.connection.light + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class LightClientLeasesTest { + + private val leases = LightClientLeases(relayOf = { if (it == PEOPLE) RELAY else null }) + private val registered = setOf(RELAY, PEOPLE) + + @Test + fun `a chain stays while any holder still uses it`() { + val connection = Any() + val resolver = Any() + leases.acquire(PEOPLE, connection) + leases.acquire(PEOPLE, resolver) + + leases.release(PEOPLE, connection) + assertNull(leases.nextUnused(registered)) + + leases.release(PEOPLE, resolver) + assertEquals(PEOPLE, leases.nextUnused(registered)) + } + + @Test + fun `asking twice and releasing once frees the chain`() { + val connection = Any() + leases.acquire(PEOPLE, connection) + leases.acquire(PEOPLE, connection) + + leases.release(PEOPLE, connection) + + assertEquals(PEOPLE, leases.nextUnused(registered)) + } + + @Test + fun `a relay goes only after its teyrchains`() { + assertEquals(PEOPLE, leases.nextUnused(registered)) + assertEquals(RELAY, leases.nextUnused(setOf(RELAY))) + } + + private companion object { + const val RELAY = "relay" + const val PEOPLE = "people" + } +} diff --git a/runtime/src/test/java/io/novafoundation/nova/runtime/names/KurdLookalikesTest.kt b/runtime/src/test/java/io/novafoundation/nova/runtime/names/KurdLookalikesTest.kt new file mode 100644 index 00000000..198e03cc --- /dev/null +++ b/runtime/src/test/java/io/novafoundation/nova/runtime/names/KurdLookalikesTest.kt @@ -0,0 +1,30 @@ +package io.novafoundation.nova.runtime.names + +import org.junit.Assert.assertEquals +import org.junit.Test + +class KurdLookalikesTest { + + @Test + fun `a zone flattened into the label suggests the zone name`() { + assertEquals(listOf("serok.gov.kurd"), candidates("serok-gov.kurd")) + assertEquals(listOf("serok.gov.kurd"), candidates("serokgov.kurd")) + assertEquals(listOf("zanko.edu.kurd"), candidates("zanko-edu.kurd")) + assertEquals(listOf("nuce.darayi.gov.kurd"), candidates("nuce.darayi-gov.kurd")) + } + + @Test + fun `ordinary and official names suggest nothing`() { + assertEquals(emptyList(), candidates("dks.kurd")) + assertEquals(emptyList(), candidates("serok.gov.kurd")) + assertEquals(emptyList(), candidates("gov.kurd")) + } + + @Test + fun `a guess that would not be a valid name is dropped`() { + // five labels are too deep + assertEquals(emptyList(), candidates("a.b.c.d-gov.kurd")) + } + + private fun candidates(name: String): List = KurdName.parse(name)?.let { KurdLookalikes.candidates(it).map(KurdName::name) } ?: emptyList() +} diff --git a/runtime/src/test/java/io/novafoundation/nova/runtime/names/KurdNameTest.kt b/runtime/src/test/java/io/novafoundation/nova/runtime/names/KurdNameTest.kt new file mode 100644 index 00000000..a3af36fd --- /dev/null +++ b/runtime/src/test/java/io/novafoundation/nova/runtime/names/KurdNameTest.kt @@ -0,0 +1,87 @@ +package io.novafoundation.nova.runtime.names + +import io.novasama.substrate_sdk_android.extensions.toHexString +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class KurdNameTest { + + // The vectors pinned by pezpallet-navnisan's `namehash_vectors_are_pinned` + @Test + fun `nodes match the pallet's pinned vectors`() { + assertEquals("011fc4e97a5ef275bd399ccbe8fca90e5f7a907c010663259364a9fb4b1d64d9", KurdName.KURD_NODE.toHexString()) + assertEquals("a10d2f1372dde3c6b1853b3f14f883fdd6a3ca08944d24e85b56c71249441ed5", node("ahmet.kurd")) + assertEquals("c5c21a8e620900b2c976bc0919a91167b427de09f025bb24bf46f91a39a62907", node("gov.kurd")) + assertEquals("3569b4cc564de96e00781bee7ad6cda51a65006529208b32e99d3be61ac7708e", node("dks.gov.kurd")) + } + + @Test + fun `nodes upward run from the name to its top-level name`() { + val nodes = KurdName.parse("dks.gov.kurd")!!.nodesUpward().map { it.toHexString() } + + assertEquals(listOf(node("dks.gov.kurd"), node("gov.kurd")), nodes) + } + + @Test + fun `input is lower-cased and may carry a scheme, a trailing dot or slash`() { + assertEquals("dks.kurd", KurdName.parse(" DKS.Kurd ")!!.name) + assertEquals("serok.gov.kurd", KurdName.parse("https://Serok.Gov.Kurd/")!!.name) + assertEquals("dks.kurd", KurdName.parse("dks.kurd.")!!.name) + assertEquals(listOf("serok", "gov"), KurdName.parse("serok.gov.kurd")!!.labels) + assertEquals("gov", KurdName.parse("serok.gov.kurd")!!.top) + } + + @Test + fun `names the pallet refuses are never parsed`() { + listOf( + "uni-x--edu.kurd", // `--` anywhere + "-dks.kurd", + "dks-.kurd", + "dks.gov.com", + "dks", + ".kurd", + "a..kurd", + "dks_news.kurd", + "dêrsim.kurd", // not ASCII: never lower-cased into something else + "a.b.c.d.e.kurd", // deeper than four labels + "dks.kurd/path", + "dks.kurd:443", + "http://dks.kurd", + "user@dks.kurd", + "a".repeat(64) + ".kurd", + ).forEach { assertNull(it, KurdName.parse(it)) } + } + + @Test + fun `a label of 63 bytes and a name of four labels are accepted`() { + assertEquals(63, KurdName.parse("a".repeat(63) + ".kurd")!!.labels.single().length) + assertEquals(4, KurdName.parse("a.b.c.d.kurd")!!.labels.size) + } + + @Test + fun `any input naming a kurd host is recognised, valid name or not`() { + listOf( + "Uni-X--Edu.KURD/", + "dks_news.kurd", + "user@dks.kurd", + "dks.kurd/path?q=1", + "http://dks.kurd", + "https://serok.gov.kurd:443/x", + "dks.kurd.", + ).forEach { + assertEquals(it, true, KurdName.mentionsKurd(it)) + } + listOf("kurd.com", "https://kurd.com/a.kurd/", "dkskurd", "duckduckgo.com/?q=dks").forEach { + assertEquals(it, false, KurdName.mentionsKurd(it)) + } + } + + @Test + fun `kurd hosts include the bare suffix and a trailing dot`() { + listOf("kurd", "dks.kurd", "DKS.KURD.", "a.b.gov.kurd").forEach { assertEquals(it, true, KurdName.isKurdHost(it)) } + listOf(null, "kurd.com", "notkurd", "dks.kurd.com").forEach { assertEquals(it.toString(), false, KurdName.isKurdHost(it)) } + } + + private fun node(name: String) = KurdName.parse(name)!!.node.toHexString() +} diff --git a/runtime/src/test/java/io/novafoundation/nova/runtime/names/KurdResolutionJudgeTest.kt b/runtime/src/test/java/io/novafoundation/nova/runtime/names/KurdResolutionJudgeTest.kt new file mode 100644 index 00000000..cd5650b7 --- /dev/null +++ b/runtime/src/test/java/io/novafoundation/nova/runtime/names/KurdResolutionJudgeTest.kt @@ -0,0 +1,52 @@ +package io.novafoundation.nova.runtime.names + +import io.novafoundation.nova.runtime.names.RealKurdNameResolver.Companion.judge +import io.novafoundation.nova.runtime.names.RealKurdNameResolver.Companion.refuseOrGiveUp +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class KurdResolutionJudgeTest { + + private val dks = KurdName.parse("dks.kurd")!! + private val ahmet = KurdName.parse("ahmet.kurd")!! + + @Test + fun `a proven official name resolves as official`() { + val resolution = judge(dks, found(NameFixtures.DKS), verified = true) as KurdResolution.Resolved + + assertTrue(resolution.verified) + assertTrue(resolution.official) + } + + @Test + fun `an unproven official, institutional, reserved or zone name never opens`() { + assertTrue(judge(dks, found(NameFixtures.DKS), verified = false) is KurdResolution.Refused) + assertTrue(judge(ahmet, found(leased(), locked = true), verified = false) is KurdResolution.Refused) + assertTrue(judge(KurdName.parse("ahmet.edu.kurd")!!, found(leased()), verified = false) is KurdResolution.Refused) + assertTrue(judge(ahmet, found(leased(owner = NameRecord.Owner.Governance)), verified = false) is KurdResolution.Refused) + } + + @Test + fun `an unproven bought name opens with the warning and never as official`() { + val resolution = judge(ahmet, found(leased()), verified = false) as KurdResolution.Resolved + + assertFalse(resolution.verified) + assertFalse(resolution.official) + } + + @Test + fun `with no answer a zone name is refused and any other is unavailable`() { + assertTrue(refuseOrGiveUp(KurdName.parse("serok.gov.kurd")!!) is KurdResolution.Refused) + assertTrue(refuseOrGiveUp(ahmet) is KurdResolution.Unavailable) + } + + private fun found(raw: ByteArray, locked: Boolean = false) = found(NameRecord.decode(raw), locked) + + private fun found(record: NameRecord, locked: Boolean = false) = NameLookup.Found(record, NameStatus.ACTIVE, listOf("raw"), locked) + + private fun leased(owner: NameRecord.Owner = NameRecord.Owner.Account(ByteArray(32))) = NameRecord( + label = "ahmet", parent = KurdName.KURD_NODE, parentReg = 0, reg = 9, owner = owner, kind = NameRecord.Kind.LEASED, + lockedTransfer = false, expiry = Long.MAX_VALUE, account = null, content = null, + ) +} diff --git a/runtime/src/test/java/io/novafoundation/nova/runtime/names/NameFixtures.kt b/runtime/src/test/java/io/novafoundation/nova/runtime/names/NameFixtures.kt new file mode 100644 index 00000000..63a36004 --- /dev/null +++ b/runtime/src/test/java/io/novafoundation/nova/runtime/names/NameFixtures.kt @@ -0,0 +1,26 @@ +package io.novafoundation.nova.runtime.names + +import io.novasama.substrate_sdk_android.extensions.fromHex + +/** Raw `Navnisan::Names` values read from Zagros People (spec 1020024) on 2026-11-05. */ +internal object NameFixtures { + + val GOV = "0x0c676f76011fc4e97a5ef275bd399ccbe8fca90e5f7a907c010663259364a9fb4b1d64d90000000000000000010000000000000002010100000000".fromHex() + + val DKS = "0x0c646b73011fc4e97a5ef275bd399ccbe8fca90e5f7a907c010663259364a9fb4b1d64d90000000000000000190000000000000002010100000000".fromHex() + + val SEROK_GOV = hex( + "0x147365726f6bc5c21a8e620900b2c976bc0919a91167b427de09f025bb24bf46f91a39a629070100000000000000070000000000000001030201000192b5", + "e877ed42d604c921154f456dd2effe85991d07c1577b9709beb7dee411190000", + ) + + val DARAYI_GOV = hex( + "0x18646172617969c5c21a8e620900b2c976bc0919a91167b427de09f025bb24bf46f91a39a6290701000000000000000b00000000000000012502010001", + "eaa3a59fbd6a4795ac240a00d00b4f6c1cc288934679cb9a1e6557be4ae972480000", + ) + + /** `Timestamp::Now` at the block the records were read from. */ + const val NOW = 0x01_a1_ac_c3_49_d0L + + private fun hex(vararg parts: String) = parts.joinToString("").fromHex() +} diff --git a/runtime/src/test/java/io/novafoundation/nova/runtime/names/NameLookupTest.kt b/runtime/src/test/java/io/novafoundation/nova/runtime/names/NameLookupTest.kt new file mode 100644 index 00000000..dcda2668 --- /dev/null +++ b/runtime/src/test/java/io/novafoundation/nova/runtime/names/NameLookupTest.kt @@ -0,0 +1,141 @@ +package io.novafoundation.nova.runtime.names + +import io.novasama.substrate_sdk_android.extensions.toHexString +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class NameLookupTest { + + private val gov = KurdName.parse("gov.kurd")!! + private val serok = KurdName.parse("serok.gov.kurd")!! + + @Test + fun `a ministry subname resolves with its zone under the live records`() = runBlocking { + val reader = FakeReader().put(gov, NameFixtures.GOV).put(serok, NameFixtures.SEROK_GOV) + + val found = NameLookup.read(reader, serok) as NameLookup.Found + + assertEquals("serok", found.record.label) + assertEquals(NameStatus.ACTIVE, found.status) + assertEquals(2, found.rawChain.size) + assertFalse(found.locked) + assertEquals(1_284_551L, found.block) + } + + @Test + fun `every read is made at the finalized block`() = runBlocking { + val reader = FakeReader().put(gov, NameFixtures.GOV).put(serok, NameFixtures.SEROK_GOV) + + NameLookup.read(reader, serok) + + assertEquals(setOf(FakeReader.HEAD), reader.blocksRead) + } + + @Test + fun `an unregistered name is not found and a missing ancestor lapses it`() = runBlocking { + assertSame(NameLookup.NotFound, NameLookup.read(FakeReader(), serok)) + assertSame(NameLookup.Lapsed, NameLookup.read(FakeReader().put(serok, NameFixtures.SEROK_GOV), serok)) + } + + @Test + fun `a subname set against an earlier registration of its parent lapses`() = runBlocking { + val reRegisteredGov = NameFixtures.GOV.copyOf().also { it[1 + 3 + 32 + 8] = 2 } // reg 1 -> 2 + val reader = FakeReader().put(gov, reRegisteredGov).put(serok, NameFixtures.SEROK_GOV) + + assertSame(NameLookup.Lapsed, NameLookup.read(reader, serok)) + } + + @Test + fun `a record stored under another name's key is refused`() = runBlocking { + val dks = KurdName.parse("dks.kurd")!! + val reader = FakeReader().put(dks, NameFixtures.GOV) + + assertTrue(runCatching { NameLookup.read(reader, dks) }.isFailure) + } + + @Test + fun `a reserved label is reported`() = runBlocking { + val dks = KurdName.parse("dks.kurd")!! + val reader = FakeReader().put(dks, NameFixtures.DKS).lock(dks) + + assertTrue((NameLookup.read(reader, dks) as NameLookup.Found).locked) + } + + @Test + fun `a lease is graced for thirty days after it ends, a grant is not`() { + val end = 1_000L + val leased = record(kind = NameRecord.Kind.LEASED, expiry = end) + val granted = record(kind = NameRecord.Kind.GRANTED, expiry = end) + + assertEquals(NameStatus.ACTIVE, NameLookup.ownStatus(leased, end - 1)) + assertEquals(NameStatus.GRACE, NameLookup.ownStatus(leased, end)) + assertEquals(NameStatus.GRACE, NameLookup.ownStatus(leased, end + NameLookup.GRACE_PERIOD_MILLIS - 1)) + assertEquals(null, NameLookup.ownStatus(leased, end + NameLookup.GRACE_PERIOD_MILLIS)) + assertEquals(null, NameLookup.ownStatus(granted, end)) + } + + @Test + fun `a parent in grace graces its subname, an expired parent lapses it`() { + val sub = record(kind = NameRecord.Kind.SUB, expiry = null, parentReg = 7) + val parent = { expiry: Long -> record(kind = NameRecord.Kind.LEASED, expiry = expiry, reg = 7) } + + assertEquals(NameStatus.GRACE, NameLookup.effectiveStatus(listOf(sub, parent(500)), now = 600)) + assertEquals(null, NameLookup.effectiveStatus(listOf(sub, parent(500)), now = 500 + NameLookup.GRACE_PERIOD_MILLIS)) + assertEquals(NameStatus.ACTIVE, NameLookup.effectiveStatus(listOf(sub, parent(700)), now = 600)) + } + + @Test + fun `a chain that ends in a subname is not valid`() { + val sub = record(kind = NameRecord.Kind.SUB, expiry = null) + + assertEquals(null, NameLookup.effectiveStatus(listOf(sub), now = 0)) + } + + @Test + fun `sources agree only on identical records`() = runBlocking { + val one = FakeReader().put(gov, NameFixtures.GOV).put(serok, NameFixtures.SEROK_GOV) + val other = FakeReader().put(gov, NameFixtures.GOV).put(serok, NameFixtures.SEROK_GOV.copyOf()) + val differs = FakeReader().put(gov, NameFixtures.GOV).put(serok, NameFixtures.SEROK_GOV.copyOf().also { it[it.size - 3] = 0x55 }) + + val first = NameLookup.read(one, serok) + assertTrue(first.agreesWith(NameLookup.read(other, serok))) + assertFalse(first.agreesWith(NameLookup.read(differs, serok))) + assertFalse(first.agreesWith(NameLookup.NotFound)) + } + + private fun record(kind: NameRecord.Kind, expiry: Long?, reg: Long = 1, parentReg: Long = 1) = NameRecord( + label = "x", parent = ByteArray(32), parentReg = parentReg, reg = reg, owner = NameRecord.Owner.Governance, kind = kind, + lockedTransfer = false, expiry = expiry, account = null, content = null, + ) + + private class FakeReader : NameStorageReader { + + private val values = mutableMapOf() + val blocksRead = mutableSetOf() + + init { + values[NameLookup.timestampNowKey.toHexString()] = ByteArray(8) { (NameFixtures.NOW ushr (8 * it)).toByte() } + } + + fun put(name: KurdName, record: ByteArray) = apply { values[NameLookup.namesKey(name.node).toHexString()] = record } + + fun lock(name: KurdName) = apply { values[NameLookup.lockedKey(name.node).toHexString()] = byteArrayOf(0) } + + override suspend fun finalizedHead() = HEAD + + override suspend fun blockNumber(at: String): Long = 1_284_551 + + override suspend fun storage(key: ByteArray, at: String): ByteArray? { + blocksRead += at + return values[key.toHexString()] + } + + companion object { + const val HEAD = "0xfinalized" + } + } +} diff --git a/runtime/src/test/java/io/novafoundation/nova/runtime/names/NameRecordTest.kt b/runtime/src/test/java/io/novafoundation/nova/runtime/names/NameRecordTest.kt new file mode 100644 index 00000000..3a962521 --- /dev/null +++ b/runtime/src/test/java/io/novafoundation/nova/runtime/names/NameRecordTest.kt @@ -0,0 +1,60 @@ +package io.novafoundation.nova.runtime.names + +import io.novasama.substrate_sdk_android.extensions.toHexString +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class NameRecordTest { + + @Test + fun `a zone granted at genesis decodes as governance owned and official`() { + val gov = NameRecord.decode(NameFixtures.GOV) + + assertEquals("gov", gov.label) + assertEquals(KurdName.KURD_NODE.toHexString(), gov.parent.toHexString()) + assertEquals(1L, gov.reg) + assertTrue(gov.owner is NameRecord.Owner.Governance) + assertEquals(NameRecord.Kind.GRANTED, gov.kind) + assertTrue(gov.lockedTransfer) + assertNull(gov.expiry) + assertNull(gov.account) + assertNull(gov.content) + assertTrue(gov.isOfficial) + assertTrue(gov.isInstitutional) + } + + @Test + fun `a ministry subname decodes as office owned with its account`() { + val serok = NameRecord.decode(NameFixtures.SEROK_GOV) + + assertEquals("serok", serok.label) + assertEquals(KurdName.parse("gov.kurd")!!.node.toHexString(), serok.parent.toHexString()) + assertEquals(1L, serok.parentReg) + assertEquals(3, (serok.owner as NameRecord.Owner.Office).tiki) + assertEquals(NameRecord.Kind.SUB, serok.kind) + assertEquals(32, serok.account!!.size) + assertTrue(serok.isOfficial) + + assertEquals(0x25, (NameRecord.decode(NameFixtures.DARAYI_GOV).owner as NameRecord.Owner.Office).tiki) + } + + @Test + fun `a trailing byte is refused rather than ignored`() { + val result = runCatching { NameRecord.decode(NameFixtures.DKS + byteArrayOf(0)) } + + assertFalse(result.isSuccess) + } + + @Test + fun `content variants decode`() { + val cid = byteArrayOf(0xe3.toByte(), 1, 2, 3) + val withIpfs = NameFixtures.DKS.copyOf(NameFixtures.DKS.size - 2) + byteArrayOf(1, 0, (cid.size shl 2).toByte()) + cid + byteArrayOf(0) + + val content = NameRecord.decode(withIpfs).content as NameRecord.Content.Ipfs + + assertEquals(cid.toHexString(), content.contenthash.toHexString()) + } +} diff --git a/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/CidTest.kt b/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/CidTest.kt new file mode 100644 index 00000000..a0d0ac81 --- /dev/null +++ b/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/CidTest.kt @@ -0,0 +1,59 @@ +package io.novafoundation.nova.runtime.names.content + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class CidTest { + + private val root = cid("bafybeietjm63oynimmv5yyqay33nui4y4wx6u3peezwetxgiwvfmelutzu") + + @Test + fun `base32 form round trips`() { + assertEquals("bafybeietjm63oynimmv5yyqay33nui4y4wx6u3peezwetxgiwvfmelutzu", root.toString()) + assertEquals(Cid.Codec.DAG_PB, root.codec) + assertEquals(Cid.Codec.RAW, cid("bafkreifjjcie6lypi6ny7amxnfftagclbuxndqonfipmb64f2km2devei4").codec) + } + + @Test + fun `an ipfs contenthash as Navnisan stores it gives its CID`() { + assertEquals(root, Cid.fromContenthash(byteArrayOf(0xe3.toByte(), 0x01) + root.bytes)) + } + + @Test + fun `other contenthashes are not content`() { + assertNull("ipns", Cid.fromContenthash(byteArrayOf(0xe5.toByte(), 0x01) + root.bytes)) + assertNull("trailing byte", Cid.fromContenthash(byteArrayOf(0xe3.toByte(), 0x01) + root.bytes + 0)) + assertNull("truncated", Cid.fromContenthash(byteArrayOf(0xe3.toByte(), 0x01) + root.bytes.copyOf(10))) + // An identity CID would put the site in the record itself; a root must be a real hash + assertNull("identity root", Cid.fromContenthash(byteArrayOf(0xe3.toByte(), 0x01, 0x01, 0x55, 0x00, 0x02, 0x68, 0x69))) + } + + @Test + fun `a block matches only its own CID`() { + val hello = cid("bafkreifjjcie6lypi6ny7amxnfftagclbuxndqonfipmb64f2km2devei4") + + assertTrue(hello.matches("hello world\n".toByteArray())) + assertFalse(hello.matches("hello world!".toByteArray())) + } + + @Test + fun `unsupported codecs and hashes are refused`() { + // dag-cbor (0x71) + assertTrue(runCatching { Cid.parse(byteArrayOf(0x01, 0x71, 0x12, 0x20) + ByteArray(32)) }.isFailure) + // sha2-512 (0x13) + assertTrue(runCatching { Cid.parse(byteArrayOf(0x01, 0x55, 0x13, 0x40) + ByteArray(64)) }.isFailure) + // sha2-256 with a short digest + assertTrue(runCatching { Cid.parse(byteArrayOf(0x01, 0x55, 0x12, 0x10) + ByteArray(16)) }.isFailure) + } + + @Test + fun `an inlined block needs no fetch and is its own content`() { + val inline = Cid.parse(byteArrayOf(0x01, 0x55, 0x00, 0x02, 0x68, 0x69)) + + assertEquals("hi", String(inline.inlineBlock!!)) + assertTrue(inline.matches("hi".toByteArray())) + } +} diff --git a/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/IpnsRecordTest.kt b/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/IpnsRecordTest.kt new file mode 100644 index 00000000..f2b51868 --- /dev/null +++ b/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/IpnsRecordTest.kt @@ -0,0 +1,66 @@ +package io.novafoundation.nova.runtime.names.content + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Test +import java.math.BigInteger +import java.time.Instant + +/** Against records Kubo signed (`src/test/resources/kurd-ipns`, from ipfs/gateway-conformance). */ +class IpnsRecordTest { + + private val now = Instant.parse("2026-11-05T00:00:00Z") + + @Test + fun `a V2 record and one carrying matching V1 copies verify`() { + val v2 = verify("k51qzi5uqu5dit2ku9mutlfgwyz8u730on38kd10m97m36bjt66my99hb6103f_v2")!! + assertEquals("bafkqadtwgiww63tmpeqhezldn5zgi", v2.root.toString()) + + assertEquals("bafkqaddwgevxmmraojswg33smq", verify("k51qzi5uqu5dlkw8pxuw9qmqayfdeh4kfebhmreauqdc6a7c3y7d5i9fi8mk9w_v1-v2")!!.root.toString()) + } + + @Test + fun `a broken legacy signature does not matter, the V2 one does`() { + assertNotNull(verify("k51qzi5uqu5dilgf7gorsh9vcqqq4myo6jd4zmqkuy9pxyxi5fua3uf7axph4y_v1-v2-broken-signature-v1")) + assertNull(verify("k51qzi5uqu5diamp7qnnvs1p1gzmku3eijkeijs3418j23j077zrkok63xdm8c_v1-v2-broken-signature-v2")) + } + + @Test + fun `a V1-only record or one whose legacy value disagrees is refused`() { + assertNull(verify("k51qzi5uqu5dm4tm0wt8srkg9h9suud4wuiwjimndrkydqm81cqtlb5ak6p7ku_v1")) + assertNull(verify("k51qzi5uqu5dlmit2tuwdvnx4sbnyqgmvbxftl0eo3f33wwtb9gr7yozae9kpw_v1-v2-broken-v1-value")) + } + + @Test + fun `only the chain's publisher key is accepted`() { + val record = resource("k51qzi5uqu5dit2ku9mutlfgwyz8u730on38kd10m97m36bjt66my99hb6103f_v2") + val otherKey = keyOf("k51qzi5uqu5dlkw8pxuw9qmqayfdeh4kfebhmreauqdc6a7c3y7d5i9fi8mk9w") + + assertNull(IpnsRecords.verify(record, otherKey, now)) + } + + @Test + fun `an expired record is refused`() { + val name = "k51qzi5uqu5dit2ku9mutlfgwyz8u730on38kd10m97m36bjt66my99hb6103f" + + assertNull(IpnsRecords.verify(resource("${name}_v2"), keyOf(name), Instant.parse("2123-08-14T12:17:04Z"))) + } + + @Test + fun `the name of a key round trips`() { + val name = "k51qzi5uqu5dit2ku9mutlfgwyz8u730on38kd10m97m36bjt66my99hb6103f" + + assertEquals(name, IpnsRecords.nameOf(keyOf(name))) + } + + private fun verify(file: String): IpnsRecord? = IpnsRecords.verify(resource(file), keyOf(file.substringBefore('_')), now) + + private fun resource(file: String): ByteArray = IpnsRecordTest::class.java.getResourceAsStream("/kurd-ipns/$file.ipns-record")!!.use { it.readBytes() } + + /** The ed25519 key inside a `k`-base36 IPNS name. */ + private fun keyOf(name: String): ByteArray { + val bytes = BigInteger(name.substring(1), 36).toByteArray().dropWhile { it == 0.toByte() }.toByteArray() + return bytes.copyOfRange(bytes.size - 32, bytes.size) + } +} diff --git a/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/KurdContentFetcherTest.kt b/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/KurdContentFetcherTest.kt new file mode 100644 index 00000000..8918b493 --- /dev/null +++ b/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/KurdContentFetcherTest.kt @@ -0,0 +1,78 @@ +package io.novafoundation.nova.runtime.names.content + +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class KurdContentFetcherTest { + + private val root = cid("bafybeietjm63oynimmv5yyqay33nui4y4wx6u3peezwetxgiwvfmelutzu") + private val car = resource("subdir-with-two-single-block-files.car") + private val tampered = car.copyOf().also { it[it.size - 2] = (it[it.size - 2] + 1).toByte() } + + @Test + fun `a gateway that changed a block is skipped for the next one`() = runBlocking { + val asked = mutableListOf() + val source = CarSource { gateway, _, _ -> + asked += gateway + if (gateway == "https://bad") tampered else car + } + + val result = KurdContentFetcher(gateways("https://bad", "https://good"), source).fetch(root, listOf("subdir", "hello.txt")) + + assertEquals("hello world\n", String((result as KurdContentFetcher.Result.File).bytes)) + assertEquals(listOf("https://bad", "https://good"), asked) + } + + @Test + fun `not found is believed only when the parent directory proves it`() = runBlocking { + // Withholds the file although its directory lists it: not an answer, so the next gateway is asked + val withholding = CarSource { gateway, _, path -> if (gateway == "https://withholding" && path.size == 2) null else car } + + val result = KurdContentFetcher(gateways("https://withholding", "https://good"), withholding).fetch(root, listOf("subdir", "hello.txt")) + assertTrue(result is KurdContentFetcher.Result.File) + + val honest = CarSource { _, _, path -> if (path.size == 2) null else car } + assertSame(KurdContentFetcher.Result.NotFound, KurdContentFetcher(gateways("https://one"), honest).fetch(root, listOf("subdir", "missing.txt"))) + } + + @Test + fun `a directory is served through its index and without one is not found`() = runBlocking { + val source = CarSource { _, _, path -> if (path.lastOrNull() == KurdContentFetcher.INDEX) null else car } + + assertSame(KurdContentFetcher.Result.NotFound, KurdContentFetcher(gateways("https://one"), source).fetch(root, listOf("subdir"))) + } + + @Test + fun `no verifiable answer anywhere is unavailable`() = runBlocking { + val result = KurdContentFetcher(gateways("https://a", "https://b"), CarSource { _, _, _ -> tampered }).fetch(root, listOf("subdir", "hello.txt")) + + assertSame(KurdContentFetcher.Result.Unavailable, result) + } + + @Test + fun `gateway entries are origins only`() { + assertEquals("https://ipfs.io", RealKurdGateways.normalized("https://IPFS.io/")) + assertEquals("https://mirror.example:8443", RealKurdGateways.normalized("https://mirror.example:8443")) + listOf("http://ipfs.io", "https://ipfs.io/ipfs/", "https://ipfs.io?x=1", "https://user@ipfs.io", "ipfs.io").forEach { + assertEquals(it, null, RealKurdGateways.normalized(it)) + } + } + + @Test + fun `the built-in list stands when the signed one cannot be read`() = runBlocking { + val failing = object : KurdGatewayListApi { + override suspend fun gateways(url: String): GatewayListRemote = throw java.io.IOException("offline") + } + val signed = object : KurdGatewayListApi { + override suspend fun gateways(url: String) = GatewayListRemote( + listOf(GatewayListRemote.GatewayRemote("https://mirror.pezkuwi.example"), GatewayListRemote.GatewayRemote("http://plain")) + ) + } + + assertEquals(RealKurdGateways.BUILT_IN, RealKurdGateways(failing).list()) + assertEquals(listOf("https://mirror.pezkuwi.example"), RealKurdGateways(signed).list()) + } +} diff --git a/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/KurdFeedResolverTest.kt b/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/KurdFeedResolverTest.kt new file mode 100644 index 00000000..3e5963d8 --- /dev/null +++ b/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/KurdFeedResolverTest.kt @@ -0,0 +1,139 @@ +package io.novafoundation.nova.runtime.names.content + +import io.novafoundation.nova.runtime.names.NameRecord +import kotlinx.coroutines.runBlocking +import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator +import org.bouncycastle.crypto.params.Ed25519KeyGenerationParameters +import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters +import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters +import org.bouncycastle.crypto.signers.Ed25519Signer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.math.BigInteger +import java.security.SecureRandom +import java.time.Instant + +class KurdFeedResolverTest { + + private val keys = Ed25519KeyPairGenerator().apply { init(Ed25519KeyGenerationParameters(SecureRandom())) }.generateKeyPair() + private val publisher = (keys.public as Ed25519PublicKeyParameters).encoded + private val anchor = cid("bafkreifjjcie6lypi6ny7amxnfftagclbuxndqonfipmb64f2km2devei4") + private val newer = cid("bafkreifkam6ns4aoolg3wedr4uzrs3kvq5m6wzyijeswb3htqhmc6itmi4") + private val now = Instant.parse("2026-11-05T00:00:00Z") + + @Test + fun `a newer release a gateway has is served`() = runBlocking { + val release = resolve(floor = 5, records = mapOf("https://a" to record(seq = 7, newer)))!! + + assertEquals(newer, release.root) + assertFalse(release.onChainVersion) + } + + @Test + fun `the newest of several gateways wins`() = runBlocking { + val records = mapOf("https://a" to record(seq = 6, anchor), "https://b" to record(seq = 9, newer)) + + assertEquals(newer, resolve(floor = 5, records = records)!!.root) + } + + @Test + fun `a release older than the chain's anchor is never served`() = runBlocking { + val release = resolve(floor = 5, records = mapOf("https://a" to record(seq = 4, newer)))!! + + assertEquals(anchor, release.root) + assertTrue(release.onChainVersion) + } + + @Test + fun `the anchored release itself is the chain's word`() = runBlocking { + val release = resolve(floor = 5, records = mapOf("https://a" to record(seq = 5, newer)))!! + + assertEquals(anchor, release.root) + assertFalse(release.onChainVersion) + } + + @Test + fun `a record signed by another key is ignored`() = runBlocking { + val stranger = Ed25519KeyPairGenerator().apply { init(Ed25519KeyGenerationParameters(SecureRandom())) }.generateKeyPair() + val forged = record(seq = 99, newer, signer = stranger.private as Ed25519PrivateKeyParameters) + + assertTrue(resolve(floor = 5, records = mapOf("https://a" to forged))!!.onChainVersion) + } + + @Test + fun `no gateway answering leaves the chain's version`() = runBlocking { + val release = resolve(floor = 5, records = emptyMap())!! + + assertEquals(anchor, release.root) + assertTrue(release.onChainVersion) + } + + @Test + fun `the feed is asked for by its publisher's IPNS name`() = runBlocking { + val asked = mutableListOf() + KurdFeedResolver(gateways("https://a"), { _, name -> asked += name; null }, clock = { now }).resolve(feed(floor = 1)) + + assertEquals(listOf(IpnsRecords.nameOf(publisher)), asked) + } + + private suspend fun resolve(floor: Long, records: Map): KurdFeedResolver.Release? { + val source = IpnsRecordSource { gateway, _ -> records[gateway] } + return KurdFeedResolver(gateways(*records.keys.ifEmpty { setOf("https://a") }.toTypedArray()), source, clock = { now }).resolve(feed(floor)) + } + + private fun feed(floor: Long) = NameRecord.Content.Feed( + publisher = publisher, + anchorer = ByteArray(32), + anchor = byteArrayOf(0xe3.toByte(), 0x01) + anchor.bytes, + seq = BigInteger.valueOf(floor), + ) + + /** A V2 IPNS record, built here only to exercise release selection; signing is tested against Kubo's records. */ + private fun record(seq: Long, root: Cid, signer: Ed25519PrivateKeyParameters = keys.private as Ed25519PrivateKeyParameters): ByteArray { + val value = "/ipfs/$root".toByteArray() + val validity = "2030-01-01T00:00:00Z".toByteArray() + val data = cborMap( + "Sequence" to cborUint(seq), + "TTL" to cborUint(0), + "Validity" to cborBytes(validity), + "ValidityType" to cborUint(0), + "Value" to cborBytes(value), + ) + val signature = Ed25519Signer().run { + init(true, signer) + val message = "ipns-signature:".toByteArray() + data + update(message, 0, message.size) + generateSignature() + } + return protobufBytes(8, signature) + protobufBytes(9, data) + } + + private fun protobufBytes(field: Int, bytes: ByteArray) = byteArrayOf(((field shl 3) or 2).toByte()) + varint(bytes.size.toLong()) + bytes + + private fun varint(value: Long): ByteArray { + val out = java.io.ByteArrayOutputStream() + var rest = value + while (rest >= 0x80) { + out.write(((rest and 0x7f) or 0x80).toInt()) + rest = rest ushr 7 + } + out.write(rest.toInt()) + return out.toByteArray() + } + + private fun cborHead(major: Int, value: Long): ByteArray = when { + value < 24 -> byteArrayOf(((major shl 5) or value.toInt()).toByte()) + value < 256 -> byteArrayOf(((major shl 5) or 24).toByte(), value.toByte()) + else -> byteArrayOf(((major shl 5) or 27).toByte()) + ByteArray(8) { (value ushr (56 - 8 * it)).toByte() } + } + + private fun cborUint(value: Long) = cborHead(0, value) + + private fun cborBytes(bytes: ByteArray) = cborHead(2, bytes.size.toLong()) + bytes + + private fun cborMap(vararg entries: Pair): ByteArray { + return entries.fold(cborHead(5, entries.size.toLong())) { acc, (key, value) -> acc + cborHead(3, key.length.toLong()) + key.toByteArray() + value } + } +} diff --git a/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/KurdSiteServerTest.kt b/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/KurdSiteServerTest.kt new file mode 100644 index 00000000..d5863d3f --- /dev/null +++ b/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/KurdSiteServerTest.kt @@ -0,0 +1,158 @@ +package io.novafoundation.nova.runtime.names.content + +import io.novafoundation.nova.runtime.names.KurdName +import io.novafoundation.nova.runtime.names.KurdNameResolver +import io.novafoundation.nova.runtime.names.KurdResolution +import io.novafoundation.nova.runtime.names.NameRecord +import io.novafoundation.nova.runtime.names.NameStatus +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class KurdSiteServerTest { + + private val siteRoot = cid("bafybeietjm63oynimmv5yyqay33nui4y4wx6u3peezwetxgiwvfmelutzu") + private val siteCar = resource("subdir-with-two-single-block-files.car") + + @Test + fun `a file of a resolved name is served with the wallet's policy`() = runBlocking { + val response = server(resolved(ipfs(siteRoot))).serve("dks.kurd", "/subdir/hello.txt") + + assertEquals(200, response.status) + assertEquals("text/plain", response.mimeType) + assertEquals("hello world\n", String(response.body)) + assertEquals(KurdSiteServer.CONTENT_SECURITY_POLICY, response.headers["Content-Security-Policy"]) + } + + @Test + fun `each resolution outcome has its status`() = runBlocking { + val name = KurdName.parse("dks.kurd")!! + + assertEquals(404, server { KurdResolution.NotFound(it, verified = true) }.serve("dks.kurd", "/").status) + assertEquals(403, server { KurdResolution.Refused(it) }.serve("dks.kurd", "/").status) + assertEquals(502, server { KurdResolution.Unavailable(it) }.serve("dks.kurd", "/").status) + assertEquals(404, server(resolved(content = null)).serve(name.name, "/").status) + } + + @Test + fun `content the server cannot verify is not served`() = runBlocking { + val ipns = NameRecord.Content.Ipfs(byteArrayOf(0xe5.toByte(), 0x01) + siteRoot.bytes) + val feed = NameRecord.Content.Feed(ByteArray(32), ByteArray(32), siteRoot.bytes, java.math.BigInteger.ONE) + + assertEquals(415, server(resolved(ipns)).serve("dks.kurd", "/").status) + assertEquals(415, server(resolved(feed)).serve("dks.kurd", "/").status) + } + + @Test + fun `an invalid name or path is refused before any lookup`() = runBlocking { + val server = server { error("must not resolve") } + + assertEquals(404, server.serve("uni-x--edu.kurd", "/").status) + assertEquals(400, server.serve("dks.kurd", "/%2e%2e/secret").status) + assertEquals(400, server.serve("dks.kurd", "/a%2Fb").status) + assertEquals(400, server.serve("dks.kurd", "/%zz").status) + } + + @Test + fun `a name is resolved once while its resolution is fresh`() = runBlocking { + var calls = 0 + var now = 0L + val server = KurdSiteServer( + resolver = resolverOf { calls++; resolved(ipfs(siteRoot))(it) }, + fetcher = fetcher(CarSource { _, _, _ -> siteCar }), + resolutionTtlMillis = 1_000, + clock = { now }, + ) + + server.serve("dks.kurd", "/subdir/hello.txt") + server.serve("dks.kurd", "/subdir/ascii.txt") + assertEquals(1, calls) + + now = 1_000 + server.serve("dks.kurd", "/subdir/hello.txt") + assertEquals(2, calls) + } + + @Test + fun `a name read through RPC only waits for the reader's choice`() = runBlocking { + val server = server(resolved(ipfs(siteRoot), verified = false)) + val name = KurdName.parse("ahmet.kurd")!! + + assertEquals(428, server.serve("ahmet.kurd", "/subdir/hello.txt", mainFrame = true).status) + assertTrue(server.pageStates.value[name] is KurdSiteServer.PageState.NeedsConsent) + + server.allowUnverified(name) + + assertEquals(200, server.serve("ahmet.kurd", "/subdir/hello.txt", mainFrame = true).status) + assertTrue(server.pageStates.value[name] is KurdSiteServer.PageState.Open) + } + + @Test + fun `only the page's own document sets its state`() = runBlocking { + val server = server(resolved(ipfs(siteRoot))) + val name = KurdName.parse("dks.kurd")!! + + server.serve("dks.kurd", "/subdir/hello.txt", mainFrame = false) + assertNull(server.pageStates.value[name]) + + server.serve("dks.kurd", "/subdir/hello.txt", mainFrame = true) + assertEquals(siteRoot, (server.pageStates.value[name] as KurdSiteServer.PageState.Open).root) + } + + @Test + fun `each outcome sets the page state the browser shows`() = runBlocking { + val name = KurdName.parse("dks.kurd")!! + suspend fun stateFor(resolve: (KurdName) -> KurdResolution): KurdSiteServer.PageState? { + val server = server(resolve) + server.serve("dks.kurd", "/", mainFrame = true) + return server.pageStates.value[name] + } + + assertSame(KurdSiteServer.PageState.Refused, stateFor { KurdResolution.Refused(it) }) + assertSame(KurdSiteServer.PageState.NotRegistered, stateFor { KurdResolution.NotFound(it, verified = true) }) + assertSame(KurdSiteServer.PageState.Unavailable, stateFor { KurdResolution.Unavailable(it) }) + assertSame(KurdSiteServer.PageState.NoSite, stateFor(resolved(content = null))) + } + + @Test + fun `paths decode per segment and only as UTF-8`() { + assertEquals(listOf("a b", "ç.html"), KurdSiteServer.decodePath("/a%20b/%C3%A7.html?x=1#top")) + assertEquals(emptyList(), KurdSiteServer.decodePath("/")) + assertNull(KurdSiteServer.decodePath("/%C3")) + assertNull(KurdSiteServer.decodePath("/%+f")) + assertNull(KurdSiteServer.decodePath("/%٣٣")) + } + + @Test + fun `types follow the extension`() { + assertEquals("text/html", KurdSiteServer.mimeTypeOf("index.HTML")) + assertEquals("text/javascript", KurdSiteServer.mimeTypeOf("app.mjs")) + assertEquals("application/octet-stream", KurdSiteServer.mimeTypeOf("README")) + assertEquals("application/octet-stream", KurdSiteServer.mimeTypeOf(null)) + } + + private fun server(resolve: (KurdName) -> KurdResolution) = KurdSiteServer(resolverOf(resolve), fetcher(CarSource { _, _, _ -> siteCar })) + + private fun resolverOf(resolve: (KurdName) -> KurdResolution) = object : KurdNameResolver { + override suspend fun resolve(name: KurdName) = resolve(name) + } + + private fun fetcher(source: CarSource) = KurdContentFetcher(gateways("https://one"), source) + + private fun ipfs(cid: Cid) = NameRecord.Content.Ipfs(byteArrayOf(0xe3.toByte(), 0x01) + cid.bytes) + + private fun resolved(content: NameRecord.Content?, verified: Boolean = true): (KurdName) -> KurdResolution = { name -> + val record = NameRecord( + label = name.labels.first(), parent = KurdName.KURD_NODE, parentReg = 0, reg = 1, owner = NameRecord.Owner.Governance, + kind = NameRecord.Kind.GRANTED, lockedTransfer = true, expiry = null, account = null, content = content, + ) + KurdResolution.Resolved(name, record, NameStatus.ACTIVE, verified = verified) + } +} + +internal fun gateways(vararg urls: String) = object : KurdGateways { + override suspend fun list() = urls.toList() +} diff --git a/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/UnixFsReaderTest.kt b/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/UnixFsReaderTest.kt new file mode 100644 index 00000000..0c5fd00d --- /dev/null +++ b/runtime/src/test/java/io/novafoundation/nova/runtime/names/content/UnixFsReaderTest.kt @@ -0,0 +1,139 @@ +package io.novafoundation.nova.runtime.names.content + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Against CARs Kubo produced (`src/test/resources/kurd-content`, from ipfs/gateway-conformance). */ +class UnixFsReaderTest { + + @Test + fun `files in a nested directory are read`() { + val reader = reader("subdir-with-two-single-block-files.car") + val root = cid("bafybeietjm63oynimmv5yyqay33nui4y4wx6u3peezwetxgiwvfmelutzu") + + assertEquals("hello world\n", text(reader.read(root, listOf("subdir", "hello.txt")))) + assertEquals("hello application/vnd.ipld.car\n", text(reader.read(root, listOf("subdir", "ascii.txt")))) + assertTrue(reader.read(root, listOf("subdir")) is UnixFsReader.Entry.Directory) + assertTrue(reader.read(root, emptyList()) is UnixFsReader.Entry.Directory) + assertNull(reader.read(root, listOf("subdir", "missing.txt"))) + } + + @Test + fun `a file chunked into several blocks is assembled in order`() { + val reader = reader("dir-with-files.car") + val root = cid("bafybeihchr7vmgjaasntayyatmp5sv6xza57iy2h4xj7g46bpjij6yhrmy") + + val text = text(reader.read(root, listOf("multiblock.txt"))) + + assertEquals(1026, text.length) + assertTrue(text.startsWith("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")) + assertTrue(text.endsWith("Pellentesque habitant amet.")) + assertEquals(text(reader.read(root, listOf("ascii.txt"))), text(reader.read(root, listOf("ascii-copy.txt")))) + } + + @Test + fun `a sharded directory is looked up by the name's hash`() { + val reader = reader("single-layer-hamt-with-multi-block-files.car") + val root = cid("bafybeidbclfqleg2uojchspzd4bob56dqetqjsj27gy2cq3klkkgxtpn4i") + + listOf("470.txt", "742.txt", "448.txt", "499.txt").forEach { name -> + assertTrue(name, text(reader.read(root, listOf(name))).startsWith("Lorem ipsum")) + } + assertNull(reader.read(root, listOf("6E470.txt"))) + } + + @Test + fun `node fields in either order and shards with one entry read the same`() { + val reader = reader("pbnode-field-orders.car") + + listOf( + "bafybeigqvyloizmfcdy6scaxnyltftzptaruqa3hnnplfzsbf4sqteiwlm", + "bafybeigdcg7pksx2zk5336vrfsktjodlr4rbfz37qr3koc5xboxe5ekv24", + "bafybeicwgy2rlqmqqu3yy2tqvm2wbgdvy3snu4sbbv4wqpvpnoplpzxz74", + "bafybeicjwkfslu7gwyywffvqgse5kiibojtktxcdqhgv7ldj5fjdacuceq", + ).forEach { root -> assertEquals(root, "hello\n", text(reader.read(cid(root), listOf("hello.txt")))) } + } + + @Test + fun `a file with a block no mirror sent is not served`() { + val reader = reader("file-3k-and-3-blocks-missing-block.car") + val root = Cid.parse(hex("122099fd9f8119c50b421e8e87d7047f6bb7cc4d4d5cfecea65813fb4bfef5049b79")) + + assertTrue(runCatching { reader.read(root, emptyList()) }.exceptionOrNull() is ContentVerificationException) + } + + @Test + fun `a CAR with any block changed is refused whole`() { + val car = resource("subdir-with-two-single-block-files.car") + val tampered = car.copyOf().also { it[it.size - 2] = (it[it.size - 2] + 1).toByte() } // inside "hello world\n" + + assertTrue(runCatching { VerifiedBlocks.fromCar(tampered) }.exceptionOrNull() is ContentVerificationException) + } + + @Test + fun `a truncated CAR is refused`() { + val car = resource("subdir-with-two-single-block-files.car") + + assertTrue(runCatching { VerifiedBlocks.fromCar(car.copyOf(car.size - 3)) }.exceptionOrNull() is ContentVerificationException) + } + + @Test + fun `a file larger than the limit is not assembled`() { + val reader = UnixFsReader(VerifiedBlocks.fromCar(resource("dir-with-files.car")), maxFileSize = 1000) + val root = cid("bafybeihchr7vmgjaasntayyatmp5sv6xza57iy2h4xj7g46bpjij6yhrmy") + + assertTrue(runCatching { reader.read(root, listOf("multiblock.txt")) }.exceptionOrNull() is ContentVerificationException) + } + + @Test + fun `path segments that could escape are refused`() { + val reader = reader("subdir-with-two-single-block-files.car") + val root = cid("bafybeietjm63oynimmv5yyqay33nui4y4wx6u3peezwetxgiwvfmelutzu") + + listOf("..", ".", "", "subdir/hello.txt").forEach { segment -> + assertTrue(segment, runCatching { reader.read(root, listOf(segment)) }.exceptionOrNull() is ContentVerificationException) + } + } + + @Test + fun `murmur3 matches the shard prefix Kubo gave hello txt`() { + assertEquals(0xDF, (UnixFsReader.murmur3x64_64("hello.txt".toByteArray()) ushr 56).toInt()) + } + + // Guava's Murmur3_128 vector: x64_128 = 6c1b07bc7bbc4be3 47939ac4a93c437a, h1 written little-endian. + // 43 bytes, so both 16-byte blocks and both tail halves are exercised. + @Test + fun `murmur3 matches the reference vector over blocks and tail`() { + val h1 = UnixFsReader.murmur3x64_64("The quick brown fox jumps over the lazy dog".toByteArray()) + + assertEquals("e34bbc7bbc071b6c", java.lang.Long.toHexString(h1)) + } + + private fun reader(name: String) = UnixFsReader(VerifiedBlocks.fromCar(resource(name))) + + private fun text(entry: UnixFsReader.Entry?) = String((entry as UnixFsReader.Entry.File).bytes, Charsets.UTF_8) +} + +internal fun resource(name: String): ByteArray = UnixFsReaderTest::class.java.getResourceAsStream("/kurd-content/$name")!!.use { it.readBytes() } + +internal fun hex(value: String): ByteArray = ByteArray(value.length / 2) { value.substring(2 * it, 2 * it + 2).toInt(16).toByte() } + +/** Multibase base32 (`b…`) to a CID, for writing fixtures' CIDs as they are published. */ +internal fun cid(value: String): Cid { + require(value.startsWith("b")) + val alphabet = "abcdefghijklmnopqrstuvwxyz234567" + val out = java.io.ByteArrayOutputStream() + var buffer = 0 + var bits = 0 + for (char in value.substring(1)) { + buffer = (buffer shl 5) or alphabet.indexOf(char).also { require(it >= 0) } + bits += 5 + if (bits >= 8) { + out.write((buffer shr (bits - 8)) and 0xff) + bits -= 8 + } + } + return Cid.parse(out.toByteArray()) +} diff --git a/runtime/src/test/resources/kurd-content/README.md b/runtime/src/test/resources/kurd-content/README.md new file mode 100644 index 00000000..2d83d971 --- /dev/null +++ b/runtime/src/test/resources/kurd-content/README.md @@ -0,0 +1,4 @@ +CAR fixtures from [ipfs/gateway-conformance](https://github.com/ipfs/gateway-conformance) +at commit `eaca278518dc977db10bfec4acd79c92c4ee11ac` (`fixtures/trustless_gateway_car/` and +`fixtures/path_gateway_unixfs/`), produced by Kubo. Dual licensed MIT / Apache-2.0 by their authors. +Unmodified; used to check the wallet's CAR and UnixFS verifier against the reference implementation. diff --git a/runtime/src/test/resources/kurd-content/dir-with-files.car b/runtime/src/test/resources/kurd-content/dir-with-files.car new file mode 100644 index 00000000..d0accae1 Binary files /dev/null and b/runtime/src/test/resources/kurd-content/dir-with-files.car differ diff --git a/runtime/src/test/resources/kurd-content/file-3k-and-3-blocks-missing-block.car b/runtime/src/test/resources/kurd-content/file-3k-and-3-blocks-missing-block.car new file mode 100644 index 00000000..bb348733 Binary files /dev/null and b/runtime/src/test/resources/kurd-content/file-3k-and-3-blocks-missing-block.car differ diff --git a/runtime/src/test/resources/kurd-content/pbnode-field-orders.car b/runtime/src/test/resources/kurd-content/pbnode-field-orders.car new file mode 100644 index 00000000..76ad68c6 Binary files /dev/null and b/runtime/src/test/resources/kurd-content/pbnode-field-orders.car differ diff --git a/runtime/src/test/resources/kurd-content/single-layer-hamt-with-multi-block-files.car b/runtime/src/test/resources/kurd-content/single-layer-hamt-with-multi-block-files.car new file mode 100644 index 00000000..bc2ae755 Binary files /dev/null and b/runtime/src/test/resources/kurd-content/single-layer-hamt-with-multi-block-files.car differ diff --git a/runtime/src/test/resources/kurd-content/subdir-with-two-single-block-files.car b/runtime/src/test/resources/kurd-content/subdir-with-two-single-block-files.car new file mode 100644 index 00000000..7e54019f Binary files /dev/null and b/runtime/src/test/resources/kurd-content/subdir-with-two-single-block-files.car differ diff --git a/runtime/src/test/resources/kurd-ipns/README.md b/runtime/src/test/resources/kurd-ipns/README.md new file mode 100644 index 00000000..685e3dd1 --- /dev/null +++ b/runtime/src/test/resources/kurd-ipns/README.md @@ -0,0 +1,4 @@ +IPNS record fixtures from [ipfs/gateway-conformance](https://github.com/ipfs/gateway-conformance) +at commit `eaca278518dc977db10bfec4acd79c92c4ee11ac` (`fixtures/ipns_records/`), produced by Kubo's +record library. Dual licensed MIT / Apache-2.0 by their authors. Unmodified; each file is named by +the IPNS name of the key that signed it. diff --git a/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5diamp7qnnvs1p1gzmku3eijkeijs3418j23j077zrkok63xdm8c_v1-v2-broken-signature-v2.ipns-record b/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5diamp7qnnvs1p1gzmku3eijkeijs3418j23j077zrkok63xdm8c_v1-v2-broken-signature-v2.ipns-record new file mode 100644 index 00000000..0f278c86 Binary files /dev/null and b/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5diamp7qnnvs1p1gzmku3eijkeijs3418j23j077zrkok63xdm8c_v1-v2-broken-signature-v2.ipns-record differ diff --git a/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dilgf7gorsh9vcqqq4myo6jd4zmqkuy9pxyxi5fua3uf7axph4y_v1-v2-broken-signature-v1.ipns-record b/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dilgf7gorsh9vcqqq4myo6jd4zmqkuy9pxyxi5fua3uf7axph4y_v1-v2-broken-signature-v1.ipns-record new file mode 100644 index 00000000..cb914e98 Binary files /dev/null and b/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dilgf7gorsh9vcqqq4myo6jd4zmqkuy9pxyxi5fua3uf7axph4y_v1-v2-broken-signature-v1.ipns-record differ diff --git a/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dit2ku9mutlfgwyz8u730on38kd10m97m36bjt66my99hb6103f_v2.ipns-record b/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dit2ku9mutlfgwyz8u730on38kd10m97m36bjt66my99hb6103f_v2.ipns-record new file mode 100644 index 00000000..ddce7382 Binary files /dev/null and b/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dit2ku9mutlfgwyz8u730on38kd10m97m36bjt66my99hb6103f_v2.ipns-record differ diff --git a/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dlkw8pxuw9qmqayfdeh4kfebhmreauqdc6a7c3y7d5i9fi8mk9w_v1-v2.ipns-record b/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dlkw8pxuw9qmqayfdeh4kfebhmreauqdc6a7c3y7d5i9fi8mk9w_v1-v2.ipns-record new file mode 100644 index 00000000..6f44adc6 Binary files /dev/null and b/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dlkw8pxuw9qmqayfdeh4kfebhmreauqdc6a7c3y7d5i9fi8mk9w_v1-v2.ipns-record differ diff --git a/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dlmit2tuwdvnx4sbnyqgmvbxftl0eo3f33wwtb9gr7yozae9kpw_v1-v2-broken-v1-value.ipns-record b/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dlmit2tuwdvnx4sbnyqgmvbxftl0eo3f33wwtb9gr7yozae9kpw_v1-v2-broken-v1-value.ipns-record new file mode 100644 index 00000000..9b4953e9 Binary files /dev/null and b/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dlmit2tuwdvnx4sbnyqgmvbxftl0eo3f33wwtb9gr7yozae9kpw_v1-v2-broken-v1-value.ipns-record differ diff --git a/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dm4tm0wt8srkg9h9suud4wuiwjimndrkydqm81cqtlb5ak6p7ku_v1.ipns-record b/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dm4tm0wt8srkg9h9suud4wuiwjimndrkydqm81cqtlb5ak6p7ku_v1.ipns-record new file mode 100644 index 00000000..c6e2a0f5 Binary files /dev/null and b/runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dm4tm0wt8srkg9h9suud4wuiwjimndrkydqm81cqtlb5ak6p7ku_v1.ipns-record differ