mirror of
https://github.com/pezkuwichain/pezkuwi-wallet-android.git
synced 2026-11-26 20:40:01 +00:00
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://<name>.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://<name>/ 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).
This commit is contained in:
1 parent
cf74df7cf4
commit
425079281c
106 files changed
+4786
-97
No files matched your search
@@ -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;
|
||||
|
||||
+47
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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<String>(), candidates("dks.kurd"))
|
||||
assertEquals(emptyList<String>(), candidates("serok.gov.kurd"))
|
||||
assertEquals(emptyList<String>(), candidates("gov.kurd"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a guess that would not be a valid name is dropped`() {
|
||||
// five labels are too deep
|
||||
assertEquals(emptyList<String>(), candidates("a.b.c.d-gov.kurd"))
|
||||
}
|
||||
|
||||
private fun candidates(name: String): List<String> = KurdName.parse(name)?.let { KurdLookalikes.candidates(it).map(KurdName::name) } ?: emptyList()
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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,
|
||||
)
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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<String, ByteArray>()
|
||||
val blocksRead = mutableSetOf<String>()
|
||||
|
||||
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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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()))
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+78
@@ -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<String>()
|
||||
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())
|
||||
}
|
||||
}
|
||||
+139
@@ -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<String>()
|
||||
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<String, ByteArray>): 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<String, ByteArray>): ByteArray {
|
||||
return entries.fold(cborHead(5, entries.size.toLong())) { acc, (key, value) -> acc + cborHead(3, key.length.toLong()) + key.toByteArray() + value }
|
||||
}
|
||||
}
|
||||
+158
@@ -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<String>(), 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()
|
||||
}
|
||||
+139
@@ -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())
|
||||
}
|
||||
@@ -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.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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.
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Reference in new issue
Block a user