Playground
blog.gno
// Package blog is a multi-author on-chain blog realm for gno.land.
//
// Any caller can Publish a post; posts are stored persistently and rendered
// newest-first. Each post records its author (the calling address) and the
// block height at which it was published.
package blog
import (
"strconv"
"strings"
"chain"
"chain/runtime"
"gno.land/p/nym-moultest123/kit/store/v0"
"gno.land/p/nym-moultest123/kit/ui/v0"
"gno.land/p/nym-moultest123/md/v0"
)
// selfPath is this realm's own page. A root-relative link resolves against
// the domain, not the realm, so every link back into it names it in full.
const selfPath = "/r/nym-moultest123/x/daily/blog/v1"
// Post is a single blog entry. It carries no id field: the id belongs to the
// store, which hands it back on lookup and iteration.
type Post struct {
Title string
Body string
Author address
Height int64
}
// posts holds every published post. The store keys by seqid, so iteration is
// in publication order for any number of posts; v0 kept its own nextID plus a
// key() that zero-padded to width 12 and stopped ordering past it.
var posts = store.Named("post")
// Publish creates a new post authored by the caller and returns its id.
// It is a state-mutating exported function, so it takes `cur realm`.
func Publish(cur realm, title string, body string) int {
if !cur.IsCurrent() {
panic("blog: spoofed realm")
}
title = strings.TrimSpace(title)
body = strings.TrimSpace(body)
if title == "" {
panic("blog: title must not be empty")
}
if body == "" {
panic("blog: body must not be empty")
}
author := cur.Previous().Address()
id := posts.Add(&Post{
Title: title,
Body: body,
Author: author,
Height: runtime.ChainHeight(),
})
chain.Emit(
"PostPublished",
"id", id.String(),
"author", author.String(),
)
return int(id)
}
// PostCount returns the number of published posts.
func PostCount() int {
return posts.Len()
}
// Render lists all posts newest-first at the root, or a single post's full
// text at path "/<id>". Render is NOT a crossing function.
func Render(path string) string {
path = strings.TrimSpace(path)
if path == "" || path == "/" {
return renderList()
}
idStr := strings.TrimPrefix(path, "/")
id, ok := store.ParseID(idStr)
if !ok {
return "# Not found\n\nInvalid post path: " + md.InlineCode(path) + "\n\n[← back](" + selfPath + ")\n"
}
v, ok := posts.Get(id)
if !ok {
return "# Not found\n\nNo post with id " + idStr + ".\n\n[← back](" + selfPath + ")\n"
}
return renderPost(v.(*Post))
}
func renderList() string {
var b strings.Builder
b.WriteString("# 📝 Blog\n\n")
if posts.Len() == 0 {
b.WriteString("_No posts yet. Be the first to `Publish`._\n")
return b.String()
}
b.WriteString(strconv.Itoa(posts.Len()) + " post(s), newest first.\n\n")
// Ids ascend with publication, so reverse iteration is newest-first.
posts.EachReverse(func(id store.ID, v any) {
p := v.(*Post)
b.WriteString("## [")
b.WriteString(ui.Inline(p.Title))
b.WriteString("](" + selfPath + ":/")
b.WriteString(id.String())
b.WriteString(")\n\n")
b.WriteString("by `")
b.WriteString(p.Author.String())
b.WriteString("` · height ")
b.WriteString(strconv.FormatInt(p.Height, 10))
b.WriteString("\n\n")
b.WriteString(ui.Excerpt(strings.TrimSpace(p.Body), 140))
b.WriteString("\n\n---\n\n")
})
return b.String()
}
func renderPost(p *Post) string {
var b strings.Builder
b.WriteString("# ")
b.WriteString(ui.Inline(p.Title))
b.WriteString("\n\n")
b.WriteString("by `")
b.WriteString(p.Author.String())
b.WriteString("` · height ")
b.WriteString(strconv.FormatInt(p.Height, 10))
b.WriteString("\n\n")
// Anyone may publish, so the body is the caller's text, not this realm's
// markdown: each line is escaped, and a blank line still breaks a paragraph.
for i, line := range strings.Split(p.Body, "\n") {
if i > 0 {
b.WriteString(" \n")
}
b.WriteString(ui.Inline(line))
}
b.WriteString("\n\n---\n\n[← back to all posts](" + selfPath + ")\n")
return b.String()
}
blog_test.gno
package blog
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
func TestPublishAndRender(cur realm, t *testing.T) {
alice := testutils.TestAddress("alice")
bob := testutils.TestAddress("bob")
testing.SetRealm(testing.NewUserRealm(alice))
// Ids start at 1 in v1: the store never assigns 0, so the zero id stays
// usable as "absent". v0 handed out 0 for the first post.
id0 := Publish(cross(cur), "First Post", "Hello from alice.")
uassert.Equal(t, 1, id0)
testing.SetRealm(testing.NewUserRealm(bob))
id1 := Publish(cross(cur), "Second Post", "A longer body\nwith a newline from bob.")
uassert.Equal(t, 2, id1)
uassert.Equal(t, 2, PostCount())
// Root render lists both, newest (bob's) first.
list := Render("")
uassert.True(t, strings.Contains(list, "First Post"), "list has first post")
uassert.True(t, strings.Contains(list, "Second Post"), "list has second post")
uassert.True(t, strings.Index(list, "Second Post") < strings.Index(list, "First Post"),
"newest post appears first")
uassert.True(t, strings.Contains(list, alice.String()), "list shows alice author")
// Single-post render shows full body + back link.
single := Render("/2")
uassert.True(t, strings.Contains(single, "newline from bob"), "full body shown")
uassert.True(t, strings.Contains(single, "← back"), "back link present")
// Unknown id.
uassert.True(t, strings.Contains(Render("/99"), "Not found"), "missing post handled")
// Id 0 is never assigned, so the path is rejected rather than looked up.
uassert.True(t, strings.Contains(Render("/0"), "Invalid post path"), "id 0 is not a post")
uassert.True(t, strings.Contains(Render("/abc"), "Invalid post path"), "a non-numeric path is rejected")
}
func TestPublishEmptyTitleAborts(cur realm, t *testing.T) {
carol := testutils.TestAddress("carol")
testing.SetRealm(testing.NewUserRealm(carol))
uassert.AbortsWithMessage(t, cur, "blog: title must not be empty", func() {
Publish(cross(cur), " ", "some body")
})
uassert.AbortsWithMessage(t, cur, "blog: body must not be empty", func() {
Publish(cross(cur), "a title", "")
})
}
gnomod.toml
module = "gno.land/r/nym-moultest123/x/daily/blog/v1" gno = "0.9" private = true [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186413 max_deposit = "6000000ugnot"
zz_escape_test.gno
package blog
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nym-moultest123/md/v0"
"gno.land/p/nt/uassert/v0"
)
// Anyone may publish, so a title or a body is the caller's text and must not
// become live markdown on the realm's own pages.
func TestTitleAndBodyAreEscaped(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("escaper")))
id := Publish(cross(cur), "[claim](https://evil.example)", "line one\n[claim](https://evil.example)")
uassert.False(t, strings.Contains(Render(""), "[claim](https://evil.example)"), Render(""))
page := Render("/" + itoaTest(id))
uassert.False(t, strings.Contains(page, "[claim](https://evil.example)"), page)
}
// A path that names nothing is echoed back on the not-found page. It is the
// visitor's text, so a backtick in it must not close a code span and let a
// link through.
func TestNotFoundPathIsEscaped(t *testing.T) {
out := Render("/x` [claim](https://evil.example) `")
// Still there, but inside a span md.InlineCode widened past its backticks.
uassert.True(t, strings.Contains(out, md.InlineCode("/x` [claim](https://evil.example) `")), out)
}
zz_links_test.gno
package blog
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// Every link the realm renders names its own absolute path. A dead link here
// once read /r/REPLACE_ADDR/blog, and a test that only checked "a back link
// exists" passed against it.
func TestLinksNameThisRealm(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("linker")))
id := Publish(cross(cur), "Linked", "body")
idx := Render("")
uassert.True(t, strings.Contains(idx, "](/r/nym-moultest123/x/daily/blog/v1:/"), idx)
page := Render("/" + itoaTest(id))
uassert.True(t, strings.Contains(page, "(/r/nym-moultest123/x/daily/blog/v1)"), page)
}
func itoaTest(n int) string {
if n == 0 {
return "0"
}
s := ""
for n > 0 {
s = string(rune(byte(n%10)+byte(48))) + s
n /= 10
}
return s
}