Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

example_test.gno

package wiki

import "strings"

// ExampleRender shows what an article looks like once the library has
// rewritten its wikilinks and hoisted its categories into the footer.
//
// It prints only the structural lines: the header carries a timestamp and the
// footer a byte count, and neither is stable across the package's other tests.
// The full output is pinned by TestRenderRoutes and by the library's own
// render tests.
func ExampleRender() {
	for _, line := range strings.Split(Render("Tendermint2"), "\n") {
		switch {
		case strings.HasPrefix(line, "# "),
			strings.HasPrefix(line, "**Categories:**"),
			strings.HasPrefix(line, "Tendermint2 is"):
			print(line + "\n")
		}
	}
	// Output:
	// # Tendermint2
	// Tendermint2 is the consensus engine under [Gno land](/r/moul/x/wiki/v0:Gno_land).
	// **Categories:** [Chains](/r/moul/x/wiki/v0:Category:Chains)
}

gnomod.toml

module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/wiki/v0"
gno = "0.9"
private = true

[addpkg]
  creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv"
  height = 914348
  max_deposit = "13000000ugnot"

wiki.gno

// Package wiki is an open, on-chain encyclopedia: anyone can create and edit
// a page, every edit is a signed revision, and the whole history is public.
//
// It is a thin realm over gno.land/p/moul/x/wiki/v0. The library owns content
// (titles, revisions, wikilinks, categories, diffs, rendering); this realm
// owns authority (who may edit what) and the chain wiring (block height, block
// time, the calling address, transaction links).
//
// The split matters for reading the code: there is no policy in the library
// and no content logic here.
package wiki

import (
	"strings"
	"time"

	"chain/runtime"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/addrset/v1"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/realmpath/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/txlink/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/wiki/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/ownable/v0"
	"gno.land/p/nt/ufmt/v0"
)

// basePath is this realm's render path. It is a constant rather than a lookup
// so link building stays a pure string operation, and it is asserted against
// the real path by TestBasePathMatchesTheRealm.
const basePath = "/r/moul/x/wiki/v0"

// steward is the address that starts out able to protect, move, blank and
// purge pages. Ownable makes it transferable, so the wiki can be handed to a
// DAO realm without redeploying.
const steward address = "g1manfred47kzduec920z88wfr64ylksmdcedlf5" // @moul

var (
	site    *wiki.Wiki
	Ownable *ownable.Ownable

	// editors may write to semi-protected pages; banned may write nowhere.
	editors addrset.Set
	banned  addrset.Set

	// cooldown is the minimum number of blocks between two writes by the same
	// address, 0 to disable.
	//
	// The storage deposit makes ADDING bytes cost the adder, but it does not
	// make removing them cost anything: the chain refunds released storage to
	// the caller of the transaction that frees it, at the realm's blended
	// deposit rate, not to whoever originally paid (processStorageDeposit in
	// gno.land/pkg/sdk/vm/keeper.go). So replacing a long article with a short
	// one can pay the editor who does it. Blank and Purge are steward-gated
	// for that reason, and this cooldown plus the ban list and the protection
	// levels are what is left for ordinary edits. See #140 Q2.
	cooldown  int64
	lastEdit  avl.Tree // address -> the height of that address's last edit
	editCount int
)

func init() {
	Ownable = ownable.NewWithAddress(steward)
	site = wiki.New(wiki.DefaultRetention, wiki.DefaultMaxBody)
	seed()
}

// Edit creates or updates a page and returns the new revision id.
func Edit(cur realm, title, body, summary string) int {
	caller := cur.Previous().Address()
	assertMayEdit(caller, title)
	rev, err := site.Edit(caller, time.Now(), runtime.ChainHeight(), title, body, summary, false)
	if err != nil {
		panic(err)
	}
	noteEdit(caller)
	return int(rev.ID)
}

// Revert restores an earlier revision of a page as a new revision.
func Revert(cur realm, title string, rev int, summary string) int {
	caller := cur.Previous().Address()
	assertMayEdit(caller, title)
	r, err := site.Revert(caller, time.Now(), runtime.ChainHeight(), title, uint64(rev), summary)
	if err != nil {
		panic(err)
	}
	noteEdit(caller)
	return int(r.ID)
}

// Comment appends a message to a page's discussion and returns its id. Pass
// replyTo = 0 for a new thread, or the id of a top-level message to reply to.
//
// Commenting deliberately ignores the page's protection level: locking an
// article is how a steward stops an edit war, and the discussion is where that
// war is supposed to move. A banned address still cannot comment, and the
// cooldown still applies.
func Comment(cur realm, title, body string, replyTo int) int {
	caller := cur.Previous().Address()
	assertNotBanned(caller)
	c, err := site.Comment(caller, time.Now(), runtime.ChainHeight(), title, body, uint64(replyTo))
	if err != nil {
		panic(err)
	}
	noteEdit(caller)
	return int(c.ID)
}

// HideComment clears one message's body and returns the bytes released. The
// message stays in the thread, marked as removed.
func HideComment(cur realm, title string, id int) int {
	Ownable.AssertOwnedBy(cur.Previous().Address())
	n, err := site.HideComment(title, uint64(id))
	if err != nil {
		panic(err)
	}
	return n
}

// Protect sets a page's edit gate: "open", "semi" or "locked".
func Protect(cur realm, title, level string) {
	Ownable.AssertOwnedBy(cur.Previous().Address())
	if err := site.SetProtection(cur.Previous().Address(), time.Now(), runtime.ChainHeight(), title, level); err != nil {
		panic(err)
	}
}

// Move renames a page, keeping its history and leaving a redirect behind.
func Move(cur realm, from, to, reason string) {
	Ownable.AssertOwnedBy(cur.Previous().Address())
	if err := site.Move(cur.Previous().Address(), time.Now(), runtime.ChainHeight(), from, to, reason); err != nil {
		panic(err)
	}
}

// Blank replaces a page's content with a tombstone revision. The history stays.
func Blank(cur realm, title, reason string) {
	Ownable.AssertOwnedBy(cur.Previous().Address())
	if _, err := site.Blank(cur.Previous().Address(), time.Now(), runtime.ChainHeight(), title, reason); err != nil {
		panic(err)
	}
}

// Purge drops every body this realm still holds for a page and returns the
// number of bytes released. Use it for content that must stop being served
// from realm state; it cannot remove the transactions that wrote it.
func Purge(cur realm, title string) int {
	Ownable.AssertOwnedBy(cur.Previous().Address())
	n, err := site.Purge(title)
	if err != nil {
		panic(err)
	}
	return n
}

// AddEditor lets an address write to semi-protected pages.
func AddEditor(cur realm, addr address) {
	Ownable.AssertOwnedBy(cur.Previous().Address())
	editors.Add(addr)
}

// RemoveEditor revokes semi-protected write access.
func RemoveEditor(cur realm, addr address) {
	Ownable.AssertOwnedBy(cur.Previous().Address())
	editors.Remove(addr)
}

// Ban stops an address from editing anything.
func Ban(cur realm, addr address) {
	Ownable.AssertOwnedBy(cur.Previous().Address())
	banned.Add(addr)
}

// Unban lifts a ban.
func Unban(cur realm, addr address) {
	Ownable.AssertOwnedBy(cur.Previous().Address())
	banned.Remove(addr)
}

// SetCooldown sets the minimum number of blocks between two edits by the same
// address; 0 disables it.
func SetCooldown(cur realm, blocks int) {
	Ownable.AssertOwnedBy(cur.Previous().Address())
	if blocks < 0 {
		panic("cooldown must not be negative")
	}
	cooldown = int64(blocks)
}

// assertNotBanned is the floor every write shares: the ban list and the
// per-address cooldown.
func assertNotBanned(caller address) {
	if banned.Has(caller) {
		panic("this address is banned from editing")
	}
	if cooldown > 0 {
		if v := lastEdit.Get(caller.String()); v != nil {
			if wait := cooldown - (runtime.ChainHeight() - v.(int64)); wait > 0 {
				panic(ufmt.Sprintf("edit cooldown: wait %d more blocks", wait))
			}
		}
	}
}

// assertMayEdit is the whole authority model of this wiki, in one function.
func assertMayEdit(caller address, title string) {
	assertNotBanned(caller)

	p, err := site.Page(title)
	if err != nil {
		return // a page that does not exist yet is open to anyone
	}
	switch p.Protection {
	case wiki.Locked:
		Ownable.AssertOwnedBy(caller)
	case wiki.SemiProtected:
		if !editors.Has(caller) && !Ownable.OwnedBy(caller) {
			panic("this page is semi-protected: ask a steward for edit access")
		}
	}
}

func noteEdit(caller address) {
	lastEdit.Set(caller.String(), runtime.ChainHeight())
	editCount++
}

// ctx is the render context handed to the library on every read.
func ctx() wiki.Ctx {
	return wiki.Ctx{Base: basePath, Exists: site.Exists}
}

// Render is the whole read surface of the wiki.
//
// Routes:
//
//	                          the front page
//	Title                     an article
//	Title/history[?offset=]   its revisions, newest first
//	Title/raw                 the current source, with its hash
//	Title/rev/<id>            one stored revision
//	Title/diff?from=&to=      a line diff between two revisions
//	Title/talk[?offset=]      the page's discussion
//	Category:Name             a category page and its members
//	Special:AllPages[?ns=]    the page index for a namespace
//	Special:Categories        every category with at least one member
//	Special:RecentChanges     the change feed
//	Special:Backlinks?page=   what links to a page
//	Special:Stats             size and storage cost
func Render(path string) string {
	req := realmpath.Parse(path)
	c := ctx()

	first := req.PathPart(0)
	if first == "" {
		return wiki.RenderIndex(c, site, 20)
	}

	t, err := wiki.ParseTitle(first)
	if err != nil {
		return "400: " + err.Error()
	}
	if t.NS == wiki.NSSpecial {
		return renderSpecial(c, t.Name, req)
	}

	p, perr := site.PageByTitle(t)

	// A category renders its members even with no description page of its
	// own: membership is an index, not a page, so "the page does not exist"
	// would hide every member.
	if t.NS == wiki.NSCategory && req.PathPart(1) == "" {
		if perr != nil {
			p = nil
		}
		return wiki.RenderCategory(c, site, t, p, txlink.Call)
	}
	if perr != nil {
		return wiki.RenderMissing(c, site, t, txlink.Call)
	}

	switch req.PathPart(1) {
	case "":
		// Follow a redirect only for a bare read, so history and source
		// always address the page that was asked for.
		if dest, _, rerr := site.Resolve(first); rerr == nil {
			p = dest
		}
		return wiki.RenderArticle(c, site, p, txlink.Call)

	case "history":
		offset := intParam(req.Query.Get("offset"), 0)
		return wiki.RenderHistory(c, p, offset, 20, txlink.Call)

	case "raw":
		if p.Head() == nil {
			return "404: no revision"
		}
		return wiki.RenderRaw(c, p, p.Head())

	case "rev":
		r := p.Revision(uint64(intParam(req.PathPart(2), 0)))
		if r == nil {
			return "404: no such revision"
		}
		return wiki.RenderRevision(c, p, r)

	case "talk":
		offset := intParam(req.Query.Get("offset"), 0)
		return wiki.RenderTalk(c, site, p, offset, 20, txlink.Call)

	case "diff":
		from := p.Revision(uint64(intParam(req.Query.Get("from"), 0)))
		to := p.Revision(uint64(intParam(req.Query.Get("to"), 0)))
		if from == nil || to == nil {
			return "404: no such revision"
		}
		return wiki.RenderDiff(c, p, from, to)
	}
	return "404: unknown route"
}

func renderSpecial(c wiki.Ctx, name string, req *realmpath.Request) string {
	switch strings.ToLower(name) {
	case "allpages":
		ns := wiki.Namespace(intParam(req.Query.Get("ns"), 0))
		offset := intParam(req.Query.Get("offset"), 0)
		return wiki.RenderAllPages(c, site, ns, offset, 50)
	case "categories":
		return wiki.RenderCategories(c, site)
	case "recentchanges":
		return wiki.RenderRecent(c, site, 50)
	case "backlinks":
		t, err := wiki.ParseTitle(req.Query.Get("page"))
		if err != nil {
			return "400: " + err.Error()
		}
		return wiki.RenderBacklinks(c, site, t)
	case "stats":
		return wiki.RenderStats(c, site) + md.BulletList([]string{
			ufmt.Sprintf("edits since deploy: %d", editCount),
			ufmt.Sprintf("editors on the semi-protected list: %d", editors.Size()),
			ufmt.Sprintf("banned addresses: %d", banned.Size()),
			ufmt.Sprintf("edit cooldown: %d blocks", cooldown),
			ufmt.Sprintf("max comment length: %d bytes", wiki.MaxCommentLen),
			"steward: `" + Ownable.Owner().String() + "`",
		})
	}
	return "404: unknown special page"
}

// intParam parses a decimal parameter, falling back to def. It never panics:
// Render is reached from a URL, and a malformed query must render a page, not
// abort the query.
func intParam(s string, def int) int {
	if s == "" {
		return def
	}
	n := 0
	for i := 0; i < len(s); i++ {
		if s[i] < '0' || s[i] > '9' {
			return def
		}
		n = n*10 + int(s[i]-'0')
	}
	return n
}

// seed writes the pages the wiki starts with, so a fresh deploy renders
// something a reader can follow instead of an empty index.
func seed() {
	pages := []struct{ title, body, summary string }{
		{
			"Gno land",
			"gno.land is a smart-contract platform that runs [[Gno]], a deterministic " +
				"interpretation of Go, on top of [[Tendermint2]].\n\n" +
				"Realms keep their state as live objects rather than as a key-value blob, " +
				"which is what lets this wiki store its articles in the contract itself.\n\n" +
				"[[Category:Chains]]\n",
			"seed",
		},
		{
			"Gno",
			"Gno is the language realms are written in: Go's syntax and semantics, minus " +
				"the sources of non-determinism a chain cannot tolerate.\n\n" +
				"See [[Gno land]].\n\n[[Category:Languages]]\n",
			"seed",
		},
		{
			"Tendermint2",
			"Tendermint2 is the consensus engine under [[Gno land]].\n\n[[Category:Chains]]\n",
			"seed",
		},
		{
			"Help:Editing",
			"Anyone may create or edit a page by calling `Edit(title, body, summary)`.\n\n" +
				"The body is markdown with two additions:\n\n" +
				"- `[[Target]]` or `[[Target|label]]` links to another page. A link to a " +
				"page that does not exist yet is marked, and creating that page turns every " +
				"such link live.\n" +
				"- `[[Category:Name]]` puts the page in a category instead of rendering inline.\n\n" +
				"A page whose first line is `#REDIRECT [[Target]]` redirects.\n\n" +
				"Every page has a discussion thread at `<Title>/talk`, written with " +
				"`Comment(title, body, replyTo)`. It stays open even when the article " +
				"itself is locked, because that is where a disagreement should go.\n\n" +
				"Your transaction locks a storage deposit for the bytes you add, and releases " +
				"it when they are removed, so the wiki charges the author of a page rather " +
				"than its readers.\n\n[[Category:Help]]\n",
			"seed",
		},
	}
	now := time.Now()
	h := runtime.ChainHeight()
	for _, p := range pages {
		if _, err := site.Edit(steward, now, h, p.title, p.body, p.summary, false); err != nil {
			panic(err)
		}
	}
}

wiki_test.gno

package wiki

import (
	"strings"
	"testing"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/wiki/v0"
	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

var (
	alice = testutils.TestAddress("alice")
	bob   = testutils.TestAddress("bob")
	// carol edits only in TestCooldown: the cooldown is keyed by address and
	// by block height, and gno's testing.SkipHeights is relative, so a test
	// that reused an address another test already edited with would see a
	// zero-height delta and trip the cooldown before it meant to.
	carol = testutils.TestAddress("carol")
)

// TestBasePathMatchesTheRealm pins the constant used to build every link
// against the realm's own path. A wrong basePath produces a page whose links
// all 404, and nothing else would catch it.
func TestBasePathMatchesTheRealm(t *testing.T) {
	uassert.True(t, strings.HasSuffix(basePath, "/r/moul/x/wiki/v0"), basePath)
	out := Render("Gno_land")
	uassert.True(t, strings.Contains(out, "("+basePath+":Tendermint2)"), out)
}

func TestRenderRoutes(t *testing.T) {
	cases := []struct {
		path string
		want string
	}{
		{"", "# Wiki"},
		{"Gno_land", "# Gno land"},
		{"gno_land", "# Gno land"},                      // titles normalize
		{"Gno_land/history", "# History of Gno land"},   //
		{"Gno_land/raw", "# Source of Gno land"},        //
		{"Gno_land/rev/1", "revision 1"},                //
		{"Nonexistent_page", "does not exist yet"},      //
		{"Special:AllPages", "# All pages"},             //
		{"Special:allpages", "# All pages"},             // case-insensitive
		{"Special:Categories", "# Categories"},          //
		{"Special:RecentChanges", "# Recent changes"},   //
		{"Special:Stats", "# Wiki stats"},               //
		{"Special:Backlinks?page=Gno", "Pages that link to Gno"},
		{"Special:Nope", "404"},
		{"Gno_land/nope", "404"},
		{"Gno_land/rev/999", "404"},
		{"Category:Chains", "Pages in this category"},
		{"Gno_land/talk", "# Discussion: Gno land"},
	}
	for _, c := range cases {
		out := Render(c.path)
		uassert.True(t, strings.Contains(out, c.want),
			"Render("+c.path+") should contain "+c.want+", got: "+first80(out))
	}
}

func TestRenderIsTotal(t *testing.T) {
	// Render is reached from a URL, so malformed input must produce a page,
	// never an abort that makes the realm unreadable.
	for _, path := range []string{"Gno|land", "Special:Backlinks?page=", "Gno_land/diff?from=x&to=y", "//"} {
		uassert.NotEmpty(t, Render(path), path)
	}
}

func TestEditAndRevert(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(alice))
	rev := Edit(cross(cur), "Alice page", "First body.\n", "create")
	uassert.True(t, rev > 0)

	testing.SetRealm(testing.NewUserRealm(bob))
	Edit(cross(cur), "Alice page", "Vandalized.\n", "oops")
	uassert.True(t, strings.Contains(Render("Alice_page"), "Vandalized."))

	testing.SetRealm(testing.NewUserRealm(alice))
	Revert(cross(cur), "Alice page", rev, "rv")
	out := Render("Alice_page")
	uassert.True(t, strings.Contains(out, "First body."))
	// The vandalism is still in the history: that is the point of a wiki.
	uassert.True(t, strings.Contains(Render("Alice_page/history"), "oops"))
}

func TestEditRejectsAnEmptyBody(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "empty title", func() {
		Edit(cross(cur), "", "body\n", "")
	})
	uassert.AbortsContains(t, cur, "empty body", func() {
		Edit(cross(cur), "Some page", "", "")
	})
}

func TestBannedAddressCannotEdit(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(steward))
	Ban(cross(cur), bob)

	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "banned", func() {
		Edit(cross(cur), "Ban test", "body\n", "")
	})

	testing.SetRealm(testing.NewUserRealm(steward))
	Unban(cross(cur), bob)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.True(t, Edit(cross(cur), "Ban test", "body\n", "") > 0)
}

func TestProtectionLevels(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(alice))
	Edit(cross(cur), "Protected page", "body\n", "")

	testing.SetRealm(testing.NewUserRealm(steward))
	Protect(cross(cur), "Protected page", "semi")

	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "semi-protected", func() {
		Edit(cross(cur), "Protected page", "sneaky\n", "")
	})

	testing.SetRealm(testing.NewUserRealm(steward))
	AddEditor(cross(cur), alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.True(t, Edit(cross(cur), "Protected page", "allowed\n", "") > 0)

	testing.SetRealm(testing.NewUserRealm(steward))
	Protect(cross(cur), "Protected page", "locked")
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "caller is not owner", func() {
		Edit(cross(cur), "Protected page", "still sneaky\n", "")
	})
}

func TestStewardOnlyFunctionsRejectOthers(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(alice))
	Edit(cross(cur), "Steward test", "body\n", "")

	for _, call := range []struct {
		name string
		fn   func()
	}{
		{"Protect", func() { Protect(cross(cur), "Steward test", "locked") }},
		{"Move", func() { Move(cross(cur), "Steward test", "Elsewhere", "") }},
		{"Blank", func() { Blank(cross(cur), "Steward test", "") }},
		{"Purge", func() { Purge(cross(cur), "Steward test") }},
		{"Ban", func() { Ban(cross(cur), bob) }},
		{"SetCooldown", func() { SetCooldown(cross(cur), 5) }},
	} {
		testing.SetRealm(testing.NewUserRealm(alice))
		uassert.AbortsContains(t, cur, "caller is not owner", call.fn, call.name)
	}
}

func TestCooldown(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(steward))
	SetCooldown(cross(cur), 5)

	testing.SetRealm(testing.NewUserRealm(carol))
	Edit(cross(cur), "Cooldown page", "one\n", "")
	uassert.AbortsContains(t, cur, "cooldown", func() {
		Edit(cross(cur), "Cooldown page", "two\n", "")
	})

	testing.SkipHeights(6)
	testing.SetRealm(testing.NewUserRealm(carol))
	uassert.True(t, Edit(cross(cur), "Cooldown page", "two\n", "") > 0)

	testing.SetRealm(testing.NewUserRealm(steward))
	SetCooldown(cross(cur), 0)
}

func TestBlankAndPurgeReleaseBytes(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(alice))
	Edit(cross(cur), "Purge page", "a body worth some bytes\n", "")

	testing.SetRealm(testing.NewUserRealm(steward))
	Blank(cross(cur), "Purge page", "policy")
	uassert.True(t, strings.Contains(Render("Purge_page"), "was blanked"))

	testing.SetRealm(testing.NewUserRealm(steward))
	released := Purge(cross(cur), "Purge page")
	uassert.True(t, released > 0, "purging a page with a retained body must release bytes")
	uassert.True(t, strings.Contains(Render("Purge_page/history"), "body evicted"))
}

func TestMoveLeavesARedirect(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(alice))
	Edit(cross(cur), "Before move", "the body\n", "")

	testing.SetRealm(testing.NewUserRealm(steward))
	Move(cross(cur), "Before move", "After move", "rename")

	uassert.True(t, strings.Contains(Render("After_move"), "the body"))
	// Reading the old title follows the redirect; its history does not.
	uassert.True(t, strings.Contains(Render("Before_move"), "the body"))
	uassert.True(t, strings.Contains(Render("Before_move/raw"), "#REDIRECT"))
}

// TestSeedIsLinkedTogether checks the deployed starting state renders as a
// connected wiki rather than four orphans.
func TestSeedIsLinkedTogether(t *testing.T) {
	uassert.True(t, strings.Contains(Render("Gno_land"), "("+basePath+":Gno)"))
	uassert.True(t, strings.Contains(Render("Special:Backlinks?page=Gno_land"), "[Gno]"))
	uassert.True(t, strings.Contains(Render("Category:Chains"), "[Gno land]"))
}

// TestParseTitleIsTheSameOneTheLibraryUses guards against the realm and the
// library disagreeing about what a title is, which would make a page
// creatable but unreachable.
func TestParseTitleIsTheSameOneTheLibraryUses(t *testing.T) {
	tt := wiki.MustParseTitle("Gno land")
	uassert.Equal(t, "Gno_land", tt.Slug())
	uassert.True(t, strings.Contains(Render(tt.Slug()), "# Gno land"))
}

func first80(s string) string {
	if len(s) > 80 {
		return s[:80]
	}
	return s
}

func TestCommentOnALockedPage(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(alice))
	Edit(cross(cur), "Locked talk", "body\n", "")

	testing.SetRealm(testing.NewUserRealm(steward))
	Protect(cross(cur), "Locked talk", "locked")

	// Locking an article is how a steward stops an edit war; the discussion
	// is where that war is supposed to move, so it stays open.
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "caller is not owner", func() {
		Edit(cross(cur), "Locked talk", "sneaky\n", "")
	})
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Comment(cross(cur), "Locked talk", "I disagree, and here is why.\n", 0)
	uassert.True(t, id > 0)
	uassert.True(t, strings.Contains(Render("Locked_talk/talk"), "I disagree"))
}

func TestCommentRepliesAndModeration(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(alice))
	Edit(cross(cur), "Talk target", "body\n", "")
	root := Comment(cross(cur), "Talk target", "First.\n", 0)

	testing.SetRealm(testing.NewUserRealm(bob))
	Comment(cross(cur), "Talk target", "Replying.\n", root)

	out := Render("Talk_target/talk")
	uassert.True(t, strings.Contains(out, "First."))
	uassert.True(t, strings.Contains(out, "Replying."))

	testing.SetRealm(testing.NewUserRealm(steward))
	released := HideComment(cross(cur), "Talk target", root)
	uassert.True(t, released > 0, "hiding a message releases its bytes")
	out = Render("Talk_target/talk")
	uassert.True(t, strings.Contains(out, "removed by a steward"))
	uassert.False(t, strings.Contains(out, "First."))
}

func TestBannedAddressCannotComment(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(alice))
	Edit(cross(cur), "Ban talk", "body\n", "")

	testing.SetRealm(testing.NewUserRealm(steward))
	Ban(cross(cur), bob)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "banned", func() {
		Comment(cross(cur), "Ban talk", "spam\n", 0)
	})
	testing.SetRealm(testing.NewUserRealm(steward))
	Unban(cross(cur), bob)
}

func TestHideCommentIsStewardOnly(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(alice))
	Edit(cross(cur), "Mod talk", "body\n", "")
	id := Comment(cross(cur), "Mod talk", "hello\n", 0)

	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "caller is not owner", func() {
		HideComment(cross(cur), "Mod talk", id)
	})
}