From 425079281c5f9992286e3b12a1fe4e4ac4546b48 Mon Sep 17 00:00:00 2001 From: SatoshiQaziMuhammed Date: Fri, 6 Nov 2026 00:25:15 +0400 Subject: [PATCH] Resolve and serve .kurd sites from verified content, never via DNS (#37) * Resolve .kurd names on chain and keep them away from DNS and search The Navnisan pallet is live on Zagros People. The wallet now reads a name's record and every ancestor's at one finalized block, checks that each record sits under the parent its name implies, and judges validity the way the pallet does (expiry, 30-day grace for leases, a subname valid only under the registration it was set against). Records are decoded by hand, so a lookup does not depend on the chain's runtime being loaded; the decoder is tested against records read from the live chain, and namehash against the vectors the pallet pins. Names are read through the light client, which proves each value. The chain's own connection is RPC first, so it is not used for names. When the light client cannot answer, two RPC nodes on different hosts must return the same records; an answer reached that way is marked unverified, and an official, institutional, reserved or zone name is then refused rather than opened. The light client tracked its users with one set, so the RPC fallback releasing a chain would stop it under any other reader. Each holder now keeps its own lease. A .kurd host never reaches system DNS or the search engine: the search box offers no web address or search for it, and the DApp browser answers every request to such a host itself, including loadUrl and resources a page embeds. The DuckDuckGo query is now URL-encoded. * Verify .kurd site content block by block A name's content is an IPFS CID on chain; mirrors serve it as a CAR. Every block in the CAR is checked against its CID while it is read, and one block that does not match refuses the whole CAR, so a mirror can withhold content but cannot change it. Files are then assembled only by following CIDs taken from blocks already checked, starting from the CID the chain gave rather than the roots the CAR claims. Supported: CIDv1 and CIDv0, dag-pb and raw, sha2-256 and inlined identity blocks; UnixFS files of any chunking, plain directories and HAMT-sharded directories (murmur3-x64-64, as Kubo builds them). An ipns contenthash, a symlink, an escaping path segment or a file over 32 MiB is refused. Tested against CARs Kubo produced, taken unchanged from ipfs/gateway-conformance (MIT / Apache-2.0), including a 238-shard HAMT, a CAR with a missing block and nodes with their fields in either order; murmur3 also against Guava's reference vector. * Serve .kurd sites from verified content under their own origin The DApp browser now answers https://.kurd itself: the name is resolved on chain, its content root fetched from IPFS trustless gateways as a CAR for the requested path, verified block by block, and only then served. The page's origin is the full name, so cookies, storage and permissions belong to that name alone, and every response carries a policy the wallet writes: nothing loads or connects outside the name, no workers, no framing. Gateways are tried in order and one that fails, withholds or changes a block is skipped. A gateway saying "not found" is believed only once the parent directory, verified, shows the name is absent. A directory is served through its index.html. The gateway list is the signed kurd/gateways.json from the config repository when it can be read, otherwise the gateways measured reachable from Turkiye; entries can only be https origins. Bad paths (dot segments, encoded slashes, malformed escapes, non-UTF-8) are refused before any lookup. A refused, missing or unavailable name, ipns content and feeds get their own status; a name's resolution is reused for a minute so one page does not resolve it once per resource. * Give the runtime component the app's HTTP client for .kurd content The site server fetches CARs over the shared client, so gateway requests use the same DNS-over-HTTPS-first resolver as the rest of the app. * Hear the DApp bridge only from the top frame of the page shown The polkadot-js and MetaMask bridges were exposed with addJavascriptInterface, which every frame of a page can call. A third-party frame inside an authorised DApp -- an ad, an embed -- could ask for the account list or a signature, and the request was shown in the DApp's name, because authorisation follows the page the tab shows. The bridges now use a web message listener: the WebView reports each message's origin and frame, and only a message from the top frame whose origin is the page shown is heard. On a WebView too old to report them, the bridge stays off instead of trusting the page. The bridge is also added before the tab's first load, since it reaches only documents loaded after it. * Let .kurd pages reach the chain through the wallet's connection A .kurd page may only connect to its own name, so it cannot open a node connection of its own. The provider half of the polkadot-js extension API (pub(rpc.listProviders, startProvider, send, subscribe, subscribeConnected)) now answers it over the wallet's connection to Pezkuwi and Zagros relay, Asset Hub and People, which falls back to the light client. Offered only when the tab shows a .kurd page, judged by the WebView's page rather than the message. Only calls that read state, estimate fees or submit an extrinsic the user already signed pass; key, peer and offchain methods do not. A subscription ends when the tab leaves the page's origin. Calls are answered off the request queue so a slow node does not hold up the page, and params are forwarded as the page wrote them rather than reparsed (a block number must not become 123.0). * Offer a typed .kurd name in DApp search as the name itself Typing a valid .kurd name now shows it under its own heading, with the shield and "resolved on chain, never sent to a search engine", and opens https:/// in the browser. An invalid one is offered nowhere: not as a web address, not as a search. * Let runtime unit tests log a warning with its cause The test stand-in for android.util.Log had no w(tag, msg, throwable), so any code under test that logged a failure that way stopped with NoSuchMethodError instead of carrying on: the .kurd fetcher logs each gateway it skips. * Show what was verified about a .kurd page, and stop at what was not The address bar of a .kurd page carries a badge in place of the padlock: Official for a name Parliament gave, Registered for a bought one, Not verified for one the reader chose to open on two RPC nodes' word. Tapping it shows the block the name was proven at, the owner (a state institution or an account), the content CID, and a button to clear the site's storage, cookies and permissions. A page that did not open is replaced by a notice instead of a blank page: an official name that cannot be verified now (retry, never open), a name read through RPC nodes only (go back, or open anyway), an unregistered name, a name without a site, and content no mirror could deliver verifiably. Behind it the site server keeps each name's page state, set only by the page's own document, and holds back a name read through RPC nodes until the reader chooses to open it. Texts in Kurmanji, English and Turkish. * Warn before opening a .kurd name that imitates an official one Zone names are institutional by construction, and the commonest imitation folds the zone into the label: serok-gov.kurd or serokgov.kurd for serok.gov.kurd. When a typed name has such a candidate and the candidate resolves, proven, as an official name, search asks first: go to the official name, or open the typed one anyway. The check runs only for names with a candidate and gives up after a few seconds; the opened page still shows by its badge whether it is official. * Say on the signing screen what kind of .kurd name asks A signature requested from a .kurd page now names the page by its .kurd name with its kind: Official, Bought (not official) or Not verified. For a name that is not official, the reader is told to check the full name, since the state did not give it; for one opened without proof, to sign only when sure whose site it is. * Judge a DApp request by the page that sent it, not the page shown by then Bridge requests are handled one at a time, after they arrive. A page could send a request and navigate at once, and its request was then authorised, and named on the signing screen, as the next page's: a .kurd page could have its signature request shown as Official by moving to an official name. Every request now carries the origin the WebView reported for its message (the polkadot-js url the page writes is no longer read). A request whose origin is not the page shown when it is handled is refused, and the signing screen is built from the asking origin's own .kurd state, refusing as well if the tab has moved on. * Serve .kurd feeds from their publisher's newest signed release A feed name (a site that changes many times a day) carries its publisher's key and an anchor: the newest release the chain was told of. The wallet asks the gateways for the publisher's IPNS record, verifies each against the key the chain gives (never the key in the record or its name), refuses expired ones, V1-only ones and ones whose legacy fields contradict the signed data, and serves the newest release at or past the anchor. When none is confirmed, it serves the anchor itself and the browser says that a newer version could not be found; the release the chain already names is always served from the chain's root. Verification is tested against records Kubo signed, taken unchanged from ipfs/gateway-conformance (MIT / Apache-2.0). --- common/src/main/res/values-ku/strings.xml | 43 ++++ common/src/main/res/values-tr/strings.xml | 43 ++++ common/src/main/res/values/strings.xml | 43 ++++ .../presentation/view/DAppView.kt | 6 + feature-dapp-impl/build.gradle | 1 + .../di/DAppFeatureDependencies.kt | 6 + .../di/modules/BrowserTabsModule.kt | 6 +- .../di/modules/web3/PolkadotJsModule.kt | 5 +- .../domain/search/DappSearchGroup.kt | 2 +- .../domain/search/DappSearchResult.kt | 7 + .../domain/search/SearchDappInteractor.kt | 12 +- .../browser/main/DAppBrowserFragment.kt | 130 ++++++++++- .../browser/main/DAppBrowserViewModel.kt | 86 ++++++- .../browser/main/di/DAppBrowserModule.kt | 17 +- .../browser/main/kurd/KurdDetailsSheet.kt | 73 ++++++ .../browser/main/kurd/KurdPageUi.kt | 79 +++++++ .../browser/main/view/AddressBarView.kt | 38 ++++ .../search/DAppSearchViewModel.kt | 43 +++- .../presentation/search/DappSearchFragment.kt | 4 + .../presentation/search/KurdLookalikeSheet.kt | 44 ++++ .../presentation/search/SearchDappAdapter.kt | 6 +- .../search/di/DAppSearchModule.kt | 9 +- .../search/model/DappSearchModel.kt | 1 + .../utils/tabs/models/BrowserTabSession.kt | 16 +- .../feature_dapp_impl/web3/Web3Transport.kt | 3 + .../metamask/states/DefaultMetamaskState.kt | 7 +- .../metamask/transport/MetamaskInjector.kt | 2 +- .../metamask/transport/MetamaskTransport.kt | 14 +- .../transport/MetamaskTransportRequest.kt | 19 +- .../web3/polkadotJs/PolkadotJsTransport.kt | 24 +- .../polkadotJs/PolkadotJsTransportRequest.kt | 99 ++++++++ .../web3/polkadotJs/rpc/ChainRegistryRpc.kt | 29 +++ .../polkadotJs/rpc/PolkadotJsRpcBridge.kt | 114 ++++++++++ .../web3/polkadotJs/rpc/RpcCall.kt | 23 ++ .../states/DefaultPolkadotJsState.kt | 45 +++- .../states/PolkadotJsStateFactory.kt | 6 +- .../web3/states/BaseState.kt | 10 + .../web3/states/Web3ExtensionStateMachine.kt | 4 +- .../web3/webview/Web3WebViewClient.kt | 46 +++- .../web3/webview/WebViewScriptInjector.kt | 18 +- .../webview/WebViewWeb3JavaScriptInterface.kt | 52 ++++- .../web3/webview/WebViewWeb3Transport.kt | 5 +- .../main/res/layout/fragment_dapp_browser.xml | 41 ++++ .../main/res/layout/sheet_kurd_details.xml | 91 ++++++++ .../main/res/layout/sheet_kurd_lookalike.xml | 68 ++++++ .../src/main/res/layout/view_address_bar.xml | 14 ++ .../src/main/res/layout/view_kurd_notice.xml | 74 ++++++ .../res/raw/javascript_interface_bridge.js | 2 +- .../domain/search/SearchDappInteractorTest.kt | 46 ++++ .../browser/main/kurd/KurdPageUiTest.kt | 87 +++++++ .../web3/polkadotJs/PolkadotJsBridgeTest.kt | 3 +- .../polkadotJs/rpc/PolkadotJsRpcBridgeTest.kt | 105 +++++++++ .../web3/polkadotJs/rpc/RpcCallParsingTest.kt | 28 +++ .../WebViewWeb3JavaScriptInterfaceTest.kt | 38 ++++ .../model/signPayload/ExternalSignPayload.kt | 16 +- .../signExtrinsic/ExternalSignFragment.kt | 21 +- .../fragment_confirm_sign_extrinsic.xml | 10 + runtime/build.gradle | 1 + .../nova/runtime/di/ChainRegistryModule.kt | 38 ++++ .../nova/runtime/di/RuntimeApi.kt | 6 + .../nova/runtime/di/RuntimeDependencies.kt | 3 + .../connection/ChainConnection.kt | 4 +- .../connection/light/LightClientLeases.kt | 30 +++ .../connection/light/LightClients.kt | 34 +-- .../nova/runtime/names/KurdLookalikes.kt | 29 +++ .../nova/runtime/names/KurdName.kt | 91 ++++++++ .../nova/runtime/names/KurdNameResolver.kt | 164 ++++++++++++++ .../nova/runtime/names/KurdResolution.kt | 41 ++++ .../nova/runtime/names/NameLookup.kt | 129 +++++++++++ .../nova/runtime/names/NameRecord.kt | 134 +++++++++++ .../nova/runtime/names/content/Cid.kt | 159 +++++++++++++ .../nova/runtime/names/content/IpnsRecord.kt | 213 ++++++++++++++++++ .../names/content/KurdContentFetcher.kt | 151 +++++++++++++ .../runtime/names/content/KurdFeedResolver.kt | 74 ++++++ .../runtime/names/content/KurdSiteServer.kt | 189 ++++++++++++++++ .../runtime/names/content/OkHttpCarSource.kt | 44 ++++ .../nova/runtime/names/content/UnixFs.kt | 106 +++++++++ .../runtime/names/content/UnixFsReader.kt | 197 ++++++++++++++++ .../runtime/names/content/VerifiedBlocks.kt | 67 ++++++ runtime/src/test/java/android/util/Log.java | 5 + .../connection/light/LightClientLeasesTest.kt | 47 ++++ .../nova/runtime/names/KurdLookalikesTest.kt | 30 +++ .../nova/runtime/names/KurdNameTest.kt | 87 +++++++ .../runtime/names/KurdResolutionJudgeTest.kt | 52 +++++ .../nova/runtime/names/NameFixtures.kt | 26 +++ .../nova/runtime/names/NameLookupTest.kt | 141 ++++++++++++ .../nova/runtime/names/NameRecordTest.kt | 60 +++++ .../nova/runtime/names/content/CidTest.kt | 59 +++++ .../runtime/names/content/IpnsRecordTest.kt | 66 ++++++ .../names/content/KurdContentFetcherTest.kt | 78 +++++++ .../names/content/KurdFeedResolverTest.kt | 139 ++++++++++++ .../names/content/KurdSiteServerTest.kt | 158 +++++++++++++ .../runtime/names/content/UnixFsReaderTest.kt | 139 ++++++++++++ .../src/test/resources/kurd-content/README.md | 4 + .../resources/kurd-content/dir-with-files.car | Bin 0 -> 1939 bytes .../file-3k-and-3-blocks-missing-block.car | Bin 0 -> 2380 bytes .../kurd-content/pbnode-field-orders.car | Bin 0 -> 678 bytes ...ngle-layer-hamt-with-multi-block-files.car | Bin 0 -> 84273 bytes .../subdir-with-two-single-block-files.car | Bin 0 -> 416 bytes .../src/test/resources/kurd-ipns/README.md | 4 + ...dm8c_v1-v2-broken-signature-v2.ipns-record | Bin 0 -> 334 bytes ...ph4y_v1-v2-broken-signature-v1.ipns-record | Bin 0 -> 334 bytes ...8kd10m97m36bjt66my99hb6103f_v2.ipns-record | Bin 0 -> 188 bytes ...eauqdc6a7c3y7d5i9fi8mk9w_v1-v2.ipns-record | Bin 0 -> 326 bytes ...ozae9kpw_v1-v2-broken-v1-value.ipns-record | Bin 0 -> 377 bytes ...wjimndrkydqm81cqtlb5ak6p7ku_v1.ipns-record | Bin 0 -> 144 bytes 106 files changed, 4786 insertions(+), 97 deletions(-) create mode 100644 feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/kurd/KurdDetailsSheet.kt create mode 100644 feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/kurd/KurdPageUi.kt create mode 100644 feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/presentation/search/KurdLookalikeSheet.kt create mode 100644 feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/ChainRegistryRpc.kt create mode 100644 feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/PolkadotJsRpcBridge.kt create mode 100644 feature-dapp-impl/src/main/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/RpcCall.kt create mode 100644 feature-dapp-impl/src/main/res/layout/sheet_kurd_details.xml create mode 100644 feature-dapp-impl/src/main/res/layout/sheet_kurd_lookalike.xml create mode 100644 feature-dapp-impl/src/main/res/layout/view_kurd_notice.xml create mode 100644 feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/domain/search/SearchDappInteractorTest.kt create mode 100644 feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/presentation/browser/main/kurd/KurdPageUiTest.kt create mode 100644 feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/PolkadotJsRpcBridgeTest.kt create mode 100644 feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/polkadotJs/rpc/RpcCallParsingTest.kt create mode 100644 feature-dapp-impl/src/test/java/io/novafoundation/nova/feature_dapp_impl/web3/webview/WebViewWeb3JavaScriptInterfaceTest.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/multiNetwork/connection/light/LightClientLeases.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdLookalikes.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdName.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdNameResolver.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/KurdResolution.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/NameLookup.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/NameRecord.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/content/Cid.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/content/IpnsRecord.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/content/KurdContentFetcher.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/content/KurdFeedResolver.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/content/KurdSiteServer.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/content/OkHttpCarSource.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/content/UnixFs.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/content/UnixFsReader.kt create mode 100644 runtime/src/main/java/io/novafoundation/nova/runtime/names/content/VerifiedBlocks.kt create mode 100644 runtime/src/test/java/io/novafoundation/nova/runtime/multiNetwork/connection/light/LightClientLeasesTest.kt create mode 100644 runtime/src/test/java/io/novafoundation/nova/runtime/names/KurdLookalikesTest.kt create mode 100644 runtime/src/test/java/io/novafoundation/nova/runtime/names/KurdNameTest.kt create mode 100644 runtime/src/test/java/io/novafoundation/nova/runtime/names/KurdResolutionJudgeTest.kt create mode 100644 runtime/src/test/java/io/novafoundation/nova/runtime/names/NameFixtures.kt create mode 100644 runtime/src/test/java/io/novafoundation/nova/runtime/names/NameLookupTest.kt create mode 100644 runtime/src/test/java/io/novafoundation/nova/runtime/names/NameRecordTest.kt create mode 100644 runtime/src/test/java/io/novafoundation/nova/runtime/names/content/CidTest.kt create mode 100644 runtime/src/test/java/io/novafoundation/nova/runtime/names/content/IpnsRecordTest.kt create mode 100644 runtime/src/test/java/io/novafoundation/nova/runtime/names/content/KurdContentFetcherTest.kt create mode 100644 runtime/src/test/java/io/novafoundation/nova/runtime/names/content/KurdFeedResolverTest.kt create mode 100644 runtime/src/test/java/io/novafoundation/nova/runtime/names/content/KurdSiteServerTest.kt create mode 100644 runtime/src/test/java/io/novafoundation/nova/runtime/names/content/UnixFsReaderTest.kt create mode 100644 runtime/src/test/resources/kurd-content/README.md create mode 100644 runtime/src/test/resources/kurd-content/dir-with-files.car create mode 100644 runtime/src/test/resources/kurd-content/file-3k-and-3-blocks-missing-block.car create mode 100644 runtime/src/test/resources/kurd-content/pbnode-field-orders.car create mode 100644 runtime/src/test/resources/kurd-content/single-layer-hamt-with-multi-block-files.car create mode 100644 runtime/src/test/resources/kurd-content/subdir-with-two-single-block-files.car create mode 100644 runtime/src/test/resources/kurd-ipns/README.md create mode 100644 runtime/src/test/resources/kurd-ipns/k51qzi5uqu5diamp7qnnvs1p1gzmku3eijkeijs3418j23j077zrkok63xdm8c_v1-v2-broken-signature-v2.ipns-record create mode 100644 runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dilgf7gorsh9vcqqq4myo6jd4zmqkuy9pxyxi5fua3uf7axph4y_v1-v2-broken-signature-v1.ipns-record create mode 100644 runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dit2ku9mutlfgwyz8u730on38kd10m97m36bjt66my99hb6103f_v2.ipns-record create mode 100644 runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dlkw8pxuw9qmqayfdeh4kfebhmreauqdc6a7c3y7d5i9fi8mk9w_v1-v2.ipns-record create mode 100644 runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dlmit2tuwdvnx4sbnyqgmvbxftl0eo3f33wwtb9gr7yozae9kpw_v1-v2-broken-v1-value.ipns-record create mode 100644 runtime/src/test/resources/kurd-ipns/k51qzi5uqu5dm4tm0wt8srkg9h9suud4wuiwjimndrkydqm81cqtlb5ak6p7ku_v1.ipns-record 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 0000000000000000000000000000000000000000..d0accae1597921dc5f64832b872382a3af23c2bb GIT binary patch literal 1939 zcma)7ZERFU6m8cgwreeBsi95LPOKVJ*Vkeb6=`Uot;MuhqG=@>iL>)&w^L@`yw1mh z7;UMVnwTgW6-k4N@J9`ipy7u_BK}cHiUB2jXt2RlH1Qh~h!F73zTKAo+9sRqX6AmJ zd(OGD_rFJ#ltynp(YW@ulF~4N&a@8q*P^oVW>PXHSq(dYcw>jlZ&aE9-8q>Av1Oa&WTo=Fcy_ zaCF;_*LHO!Dh4R$GM7}DSPGqB^e;NzZTon)H+875p}hLQ^P+9>9eZMB)&JFB866~d zZ`zWm5|$g5;*zY-WuC8y$I46F=QCff9l~MA8NmklYsv<`$3pIV1gm(nt5FPeRAYlw z+>dX|v0oJNoe_uI*T24cPg`qKr@!{{sn5i^C#J`D?mO}Gp~sgW8}D2G@WMn%%}6Yf z55ClJxNK@k?3wiG6?^%DOP};L-22fVy=TwAdDGdh_D_ea=LCOuf%Wswo$Uv%oUR+b zr~TSvwZHqTHtc)gmzLeXj=a^oV@`1Qx^GtAxbla(#jj3&`OhsAXI?&4cX3SoRQdIy zjW3EnJC{bmjS=R(Z~s_%_>JCY_m@|yw(WnlHe7cuc6{rF?>in_bo9uQsplX#7GGE% zs~IgvBeB^}Y*);YS#0DUsi;6K)K(y0a;cDJ24O)>5)m0_N(?ntA?&k|fi;5+qMR8I zJ!Aud0vRACLaKa54GQ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xNsu%$nx4ajoS41nZ;BI!t=X%N;Fkc-1vyC|pJE-lI_s;UN)~8;^k|%7vxZ zw{fbPJ}{(30xy%}n0~a>S}awamRKisHHhU(FWSdO-5j14 z1GHRfAJ(}DboWpjh}|MlGBO$j;U9qNMKcSRKBK+}StcHVV4l4GQd@9wAmV)S_9P@1 zwpryIu^sPGfg(yaln!GQChAua4vQ`DJh2wT-zkPNb<`E&YQF3p>{FIVUX8Ni4ed^e z;c~GvFX>taA!Jtu{`=cZ-Hq~!gSXt5c*%2==`&L3zMZJjfTM?yki2_yx_PdhkqqL% ze3RdqB)MV?LvoF*3D-&3Cl#abLPV=AA%6i_wZbh7j7Bu5ccTHtFwT0>vEI6VR>Ba@ ztfKL?k=^Z>m3E*bX=#C3M)=2>ZuK{DSbW?*LI@L=cFm>?lDTx$_E1v4G(u=OV^dm^ zGx5_!FAoZ=r`jYHd3Bm+FD2@#A`nHcb!)#e`fdorX8I)s^y95~1rucgTUuMgFWXJj z)p}*k&ev|^NDeO^jXC+TnIwD7mvi?QQ1`x{3|5XE`Q$j?RTw!*B{4Nvz8k)Z502J{Y9(hYOfzqpcqye?*7IjK qMp0)WRFW96iLi{zI9P+_X}uI$h!4x%eA2aEJQ< literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..76ad68c623fab4c75a8ab26f7cd34b96a7648f76 GIT binary patch literal 678 zcmdnWxG1$KKfk27<%U*-Dg$GIkivy^Voy?A1wOvy5YH1gI8+E3d?8xp{5_(?WQns9XJNG)jiJ{lw3d77yMGsDBHSftP zSZ$gxqx9I5TSbn%l^J&Hv*&Gp_VYhnq35P<)yvPe8758JVA6S2k+CRkYeRq5(|j$Hl^8wGyfyd=HlPhs+UlM794i(a^W z+sB-dnv;{y6-$htxR^K?g^amWh%r`(6Kt?vNkxeS8`yM00YR3@ASX33f*emM__$O# kScPO77;pm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mr;@4V)=E7l!aURjwI z*0^anJ(CnV6%X$lQs+sj7Vbr7+MiALteM>H$f0cAEJe0GF!$NTiUiH^@z0a?r}|o* zJ80)tbMf4<=S#{Ny7U3)J&D}WPf`XZjfaX4l9J`2f0qGT&Jk7C)Guoy^=kM{+;NQA zgOkl#1Yf8QEqkVEyW(Q??3&R#U&@EJ9-5wEqpmq^yplWV13ei~W@-tHQ;V_2K-4h( ztF$^9j{~kwtR$#L^Z`jdpGaVkQcQy1=Gq$&SEvp){#Sj3_8D%nw>h-etd5%|Ii#lk zFe!@N#bb!KbU0Es+dhUR)`JkrZY2>HoZP!pPl&Wf|b7pUmW2#d7fkQpZ)tw y66$}9U44e0Pf+7PP{ip+=^Hh^|7sFrx literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..7e54019fc6222946fdbef90c73b1a7829d457f8a GIT binary patch literal 416 zcmcColvsKsE}XQ)U5GOyH76$@tceHYCTC)-0_#yoEGWpyOinBT29thSUW#63K~9QZa$*se S0muwOHbcxP&o9bJ;Q|2bFR(xW literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..0f278c868ba26c92efacfaf040f198372fc1b057 GIT binary patch literal 334 zcmdG|ef_EiKH*%`Fsi=za8K-t7|2`{7T-&*Z4SoSC*KQnW9i!Qks_LHHmR)a!81eGy?0GCjE(f|Me literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..cb914e98935285d36324920ed73cf82a2f3bf39a GIT binary patch literal 334 zcmdG|ef_EiKH*&CL|z&CDxH%*jkqC@v{YOOs$wk~T6lGS)S)&^0s(F*LF=G`BJ^ z)-$s-F)%fX(qJ%XSn%=CMiVCoqoaLU>++`c72KF_xNyNnKZ%D%w)3t@otPav#XYft zuY5~)Hs@-)ja$BnBxHvMS4S*elkTixbTwsWZ%Zw^%vN@)WXu#yyR4d44`?LDVZge5%_$R15*`JS&+&A01K#iGXMYp literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..ddce7382d79027426e6c02ea1bdabfd5078e8468 GIT binary patch literal 188 zcmZ>A$SRu=5vMKA&Us}@ok+LDMuqFSTTDgYuK6_K{ori3Ku+HTpM&2J0OO znRQR?%c*A5FGu8b{{P#!i)$&PSH;rgkPshf1_s8(5-|Y`sbPsZrKu4r`k4i3#rjE! zY1xH|DJA9UndRkX#wEE0sf8J-RXHhnrd8>g8NsQArKx$zsSFuFU70DFC6y7Zq9KFs-}ipe6I< z-fhKtq3<)8&OJ-L=6a9qNXV-9=h;F^xlj1bc2wmyeR4&1spZk7PW6ZRIPOeYviDR2 z^AA1=1|?}DLnC8d0}EY4lMq8AD?@WD17kfiOA`ZAqbLmqgN6kk4{bDYa_|b=k>cFx z{ra+^8`B#dGj%?n3jtkexxY-q5{~@pUNm7{?GxX!)j>y!=UdhlI!^b?a$I29Ae3d{Udom+9wXifbFFBPV1E?i4C9|Y5 P0-u|6V5&kY3sM;X9A9~{ literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..9b4953e9440c39508eb798c0d477b730c1918a43 GIT binary patch literal 377 zcmd-w)6XnOE7ng+Ov^4zOwTFJEvu@?G|I`(H7QI_t;|VHO)9NOG%hJgO{z-It~4&l z&nnJHPc9U4@XO7%eJ|>F$M=6C4|BsZXQK#ni^GwZ>Nf0H(eiTgZH~Fi*z*nfJEy7? z$gYT7?E7T(r>SM4vxS^)eHU?7tW4vRU{I1aGBh&QHL%b%Gzl>@vNANcGBDONvotX< zHHy+;Flbot@z6#SCkL;2r?=LpIlTMd=vlLIZNQEB?$4i!F@+`X`^J)>-?r`LejBYH zSFF5trLK{ZR=dV~=tp2OYn=NhwrgQ*)wR;wS-d7OE=>*z@sVa=U|cK_6TpxfmY7qT z8exa*^^B78^whG7+}xr>pcl*2jg5Iw0W>c&C9|Y50-uj^V5&kY3sM;X1?i5@ literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..c6e2a0f5c5a7482bb42367715f262e5f85044b37 GIT binary patch literal 144 zcmV;B0B`>aBrj=jW^*rMVPaAk35WqNF6ZZ&#mX%aw3oqH(c zT>wh5G^qr9f#GHkR1G}+apD(BEi>AoF4(LlER1|>po#OObsy8PYkTL*I#d`GdbIAB yYOV&%>sSXE03sVQF)}kPFgPtSG*mG%Ix#moFf%STIW#aeGFm7AFo2-(!m%{xT{cJn literal 0 HcmV?d00001