Playground
gnomod.toml
module = "gno.land/p/nym-moultest123/x/wesh/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186410 max_deposit = "19000000ugnot"
hmac.gno
package wesh
import "crypto/sha256"
// blockSize is SHA-256's internal block size, the padding width HMAC uses.
const blockSize = 64
// HMACSHA256 computes HMAC-SHA256 as specified in RFC 2104.
//
// gno's standard library exposes sha256.Sum256 but no streaming hash.Hash and
// no crypto/hmac, so the construction is spelled out here:
//
// HMAC(K, m) = H((K' ⊕ opad) ‖ H((K' ⊕ ipad) ‖ m))
//
// with K' the key hashed down when longer than the block size, then
// zero-padded up to it. This is the primitive weshnet's rendezvous point
// derivation is built on, so it has to agree byte-for-byte; see
// [RendezvousPoint].
func HMACSHA256(key, msg []byte) []byte {
k := key
if len(k) > blockSize {
sum := sha256.Sum256(k)
k = sum[:]
}
ipad := make([]byte, blockSize)
opad := make([]byte, blockSize)
copy(ipad, k)
copy(opad, k)
for i := 0; i < blockSize; i++ {
ipad[i] ^= 0x36
opad[i] ^= 0x5c
}
inner := sha256.Sum256(append(ipad, msg...))
outer := sha256.Sum256(append(opad, inner[:]...))
return outer[:]
}
hmac_test.gno
package wesh
import (
"encoding/hex"
"testing"
"gno.land/p/nt/uassert/v0"
)
// TestHMACSHA256RFC4231 checks the HMAC construction against the published
// RFC 4231 vectors. Case 6 matters most: its key is longer than the block
// size, which is the branch that hashes the key down first and the one most
// easily got wrong.
func TestHMACSHA256RFC4231(t *testing.T) {
cases := []struct {
name string
key []byte
data []byte
want string
}{
{
"rfc4231 case 1",
repeat(0x0b, 20),
[]byte("Hi There"),
"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7",
},
{
"rfc4231 case 2",
[]byte("Jefe"),
[]byte("what do ya want for nothing?"),
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843",
},
{
"rfc4231 case 6 (key longer than the block size)",
repeat(0xaa, 131),
[]byte("Test Using Larger Than Block-Size Key - Hash Key First"),
"60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54",
},
}
for _, tc := range cases {
got := hex.EncodeToString(HMACSHA256(tc.key, tc.data))
uassert.Equal(t, tc.want, got, tc.name)
}
}
// repeat returns n copies of b.
func repeat(b byte, n int) []byte {
out := make([]byte, n)
for i := range out {
out[i] = b
}
return out
}
link.gno
package wesh
import (
"encoding/binary"
"errors"
"net/url"
"strings"
"gno.land/p/nym-moultest123/x/daily/b58/v0"
)
// WebLinkPrefix is the prefix of a shareable Berty web link. The fragment
// marker is part of it on purpose: everything after '#' stays in the browser
// and is never sent to berty.tech, so the web host never learns the identity
// being shared.
const WebLinkPrefix = "https://berty.tech/id#"
// contactKind is the human-readable link kind for a contact invite,
// berty's BertyLink_ContactInviteV1Kind.
const contactKind = "contact"
// Protobuf field numbers, from berty's api/messengertypes/messengertypes.proto
// and weshnet's api/protocol/protocoltypes.proto. They are wire-format
// constants: changing one silently produces a link no Berty client can read.
const (
fieldBertyLinkBertyID = 2 // BertyLink.berty_id
fieldBertyIDSeed = 1 // BertyID.public_rendezvous_seed
fieldBertyIDAccountPK = 2 // BertyID.account_pk
)
var (
ErrNotAWebLink = errors.New("wesh: not a berty web link")
ErrNotAContactLink = errors.New("wesh: link is not a contact invite")
ErrBadLinkPayload = errors.New("wesh: link payload is not a valid contact")
)
// Blob returns the protobuf-encoded machine payload of a contact invite link:
// a BertyLink carrying only a BertyID with the rendezvous seed and account key.
//
// The kind and the display name are deliberately absent. berty's MarshalLink
// puts the kind in the human-readable path segment and the display name in the
// query string, so a blob that carried them would not match a link produced by
// a real Berty client. The encoding here is verified against berty's own
// golden test vector; see link_test.gno.
func (c Contact) Blob() ([]byte, error) {
if err := c.Validate(); err != nil {
return nil, err
}
id := appendBytesField(nil, fieldBertyIDSeed, c.Seed)
id = appendBytesField(id, fieldBertyIDAccountPK, c.AccountPK)
return appendBytesField(nil, fieldBertyLinkBertyID, id), nil
}
// WebLink returns the shareable https://berty.tech/id# link for the contact.
// Scanning or opening it in Berty starts a contact request.
func (c Contact) WebLink() (string, error) {
blob, err := c.Blob()
if err != nil {
return "", err
}
link := WebLinkPrefix + contactKind + "/" + b58.Encode(blob)
if c.DisplayName != "" {
link += "/name=" + url.QueryEscape(c.DisplayName)
}
return link, nil
}
// ParseWebLink decodes a Berty contact web link back into a [Contact].
//
// It accepts links with or without a trailing query segment, and ignores query
// keys other than "name", matching berty's own UnmarshalLink leniency.
func ParseWebLink(link string) (Contact, error) {
var c Contact
if !strings.HasPrefix(link, WebLinkPrefix) {
return c, ErrNotAWebLink
}
parts := strings.Split(strings.TrimPrefix(link, WebLinkPrefix), "/")
if len(parts) < 2 {
return c, ErrNotAWebLink
}
if parts[0] != contactKind {
return c, ErrNotAContactLink
}
if !b58.IsValid(parts[1]) {
return c, ErrBadLinkPayload
}
inner, ok := lookupBytesField(b58.Decode(parts[1]), fieldBertyLinkBertyID)
if !ok {
return c, ErrBadLinkPayload
}
seed, ok := lookupBytesField(inner, fieldBertyIDSeed)
if !ok {
return c, ErrBadLinkPayload
}
pk, ok := lookupBytesField(inner, fieldBertyIDAccountPK)
if !ok {
return c, ErrBadLinkPayload
}
c.AccountPK = pk
c.Seed = seed
if len(parts) > 2 {
c.DisplayName = queryName(parts[2])
}
if err := c.Validate(); err != nil {
return Contact{}, err
}
return c, nil
}
// queryName pulls the "name" key out of an encoded query segment, returning ""
// when it is absent or malformed. A bad display name must never fail a link
// that is otherwise valid: the name is decoration, the keys are the payload.
func queryName(q string) string {
for _, pair := range strings.Split(q, "&") {
if !strings.HasPrefix(pair, "name=") {
continue
}
name, err := url.QueryUnescape(strings.TrimPrefix(pair, "name="))
if err != nil || len(name) > MaxDisplayNameLen {
return ""
}
return name
}
return ""
}
// appendBytesField appends a length-delimited (wire type 2) protobuf field.
// An empty value encodes to nothing, which is what proto3 does for a zero
// bytes field, and is why an invalid contact can never produce a short-but-
// plausible blob: Validate has already rejected it.
func appendBytesField(dst []byte, num int, val []byte) []byte {
if len(val) == 0 {
return dst
}
dst = append(dst, byte(num<<3|2))
dst = binary.AppendUvarint(dst, uint64(len(val)))
return append(dst, val...)
}
// lookupBytesField scans a protobuf message for the first length-delimited
// field with the given number, skipping every other field whatever its wire
// type. Unknown fields are skipped rather than rejected so a link produced by
// a newer Berty client still parses.
func lookupBytesField(buf []byte, num int) ([]byte, bool) {
i := 0
for i < len(buf) {
tag, n := binary.Uvarint(buf[i:])
if n <= 0 {
return nil, false
}
i += n
fieldNum := int(tag >> 3)
wireType := int(tag & 0x7)
switch wireType {
case 0: // varint
_, n := binary.Uvarint(buf[i:])
if n <= 0 {
return nil, false
}
i += n
case 1: // 64-bit
if i+8 > len(buf) {
return nil, false
}
i += 8
case 2: // length-delimited
l, n := binary.Uvarint(buf[i:])
if n <= 0 {
return nil, false
}
i += n
end := i + int(l)
if end < i || end > len(buf) {
return nil, false
}
if fieldNum == num {
return buf[i:end], true
}
i = end
case 5: // 32-bit
if i+4 > len(buf) {
return nil, false
}
i += 4
default:
return nil, false
}
}
return nil, false
}
link_test.gno
package wesh
import (
"encoding/hex"
"testing"
"gno.land/p/nym-moultest123/x/daily/b58/v0"
"gno.land/p/nt/uassert/v0"
)
// bertyGoldenBlob is the base58 payload from berty's own links_test.go
// ("simple-contact"), produced by MarshalLink from
// PublicRendezvousSeed = 16 x 0x01 and AccountPk = 16 x 0x02.
//
// It is the ground truth for this package's wire format. The keys are 16 bytes
// because that test predates the length rule, so the vector is checked against
// the raw encoder rather than through Contact.Blob, which would (correctly)
// reject them.
const bertyGoldenBlob = "3geQXHmsW9rxRfQFJdu8CEuPtWkfTWgJH13NzAoGatcnh4brusu3"
func TestBlobEncodingMatchesBertyGoldenVector(t *testing.T) {
id := appendBytesField(nil, fieldBertyIDSeed, repeat(0x01, 16))
id = appendBytesField(id, fieldBertyIDAccountPK, repeat(0x02, 16))
blob := appendBytesField(nil, fieldBertyLinkBertyID, id)
uassert.Equal(t,
"12240a1001010101010101010101010101010101121002020202020202020202020202020202",
hex.EncodeToString(blob),
"protobuf wire bytes")
uassert.Equal(t, bertyGoldenBlob, b58.Encode(blob), "base58 payload berty produces")
}
// TestWebLink pins the full link for a real 32-byte identity.
func TestWebLink(t *testing.T) {
c := Contact{
AccountPK: mustHex(t, testAccountPKHex),
Seed: mustHex(t, testSeedHex),
}
link, err := c.WebLink()
uassert.NoError(t, err)
uassert.Equal(t,
"https://berty.tech/id#contact/oZBLFpzghxrATkepWvDPNX9pHYqi6BWgP45xGWhqxcwmqN2bnMMbU7UcwUuTaCcDyUvMjmWRMDWcP96bXAndcjNiAZ1Vz9X",
link)
}
// TestWebLinkDisplayNameEscaping matches berty's url.Values encoding: space
// becomes '+', and everything outside the unreserved set is percent-escaped.
func TestWebLinkDisplayNameEscaping(t *testing.T) {
c := Contact{
AccountPK: mustHex(t, testAccountPKHex),
Seed: mustHex(t, testSeedHex),
DisplayName: "Hello World!",
}
link, err := c.WebLink()
uassert.NoError(t, err)
uassert.True(t, endsWith(link, "/name=Hello+World%21"), "display name is query-escaped: "+link)
}
func TestWebLinkRoundTrip(t *testing.T) {
cases := []struct {
name string
in Contact
}{
{"no display name", Contact{AccountPK: repeat(0x11, 32), Seed: repeat(0x22, 32)}},
{"with a display name", Contact{AccountPK: repeat(0x11, 32), Seed: repeat(0x22, 32), DisplayName: "gno support"}},
{"name needing escapes", Contact{AccountPK: repeat(0x11, 32), Seed: repeat(0x22, 32), DisplayName: "a/b c&d=e"}},
{"leading zero bytes", Contact{AccountPK: repeat(0x00, 32), Seed: repeat(0x00, 32)}},
}
for _, tc := range cases {
link, err := tc.in.WebLink()
uassert.NoError(t, err, tc.name)
got, err := ParseWebLink(link)
uassert.NoError(t, err, tc.name)
uassert.Equal(t, hex.EncodeToString(tc.in.AccountPK), hex.EncodeToString(got.AccountPK), tc.name+": account key")
uassert.Equal(t, hex.EncodeToString(tc.in.Seed), hex.EncodeToString(got.Seed), tc.name+": seed")
uassert.Equal(t, tc.in.DisplayName, got.DisplayName, tc.name+": display name")
}
}
func TestParseWebLinkRejects(t *testing.T) {
valid, err := Contact{AccountPK: repeat(0x11, 32), Seed: repeat(0x22, 32)}.WebLink()
uassert.NoError(t, err)
cases := []struct {
name string
in string
want error
}{
{"not a berty link", "https://example.com/id#contact/abc", ErrNotAWebLink},
{"no payload segment", WebLinkPrefix + "contact", ErrNotAWebLink},
{"a group link, not a contact", WebLinkPrefix + "group/" + b58.Encode([]byte{1, 2, 3}), ErrNotAContactLink},
{"payload is not base58", WebLinkPrefix + "contact/not-base58-0OIl", ErrBadLinkPayload},
{"payload is not a BertyLink", WebLinkPrefix + "contact/" + b58.Encode([]byte{0xff, 0xff}), ErrBadLinkPayload},
{"berty's own 16-byte golden vector is too short now", WebLinkPrefix + "contact/" + bertyGoldenBlob, ErrBadSeedLen},
{"truncated payload", valid[:len(valid)-8], ErrBadLinkPayload},
}
for _, tc := range cases {
_, err := ParseWebLink(tc.in)
uassert.ErrorIs(t, err, tc.want, tc.name)
}
}
// TestParseWebLinkIgnoresUnknownQueryKeys matches berty's UnmarshalLink, which
// accepts a link carrying query keys it does not know.
func TestParseWebLinkIgnoresUnknownQueryKeys(t *testing.T) {
link, err := Contact{AccountPK: repeat(0x11, 32), Seed: repeat(0x22, 32)}.WebLink()
uassert.NoError(t, err)
got, err := ParseWebLink(link + "/foo=bar&name=Alice")
uassert.NoError(t, err)
uassert.Equal(t, "Alice", got.DisplayName)
}
// TestLookupBytesFieldSkipsOtherWireTypes covers the decoder's skip paths: a
// varint, a 64-bit and a 32-bit field ahead of the one being looked up.
func TestLookupBytesFieldSkipsOtherWireTypes(t *testing.T) {
buf := []byte{0x08, 0x96, 0x01} // field 1, varint 150
buf = append(buf, 0x11) // field 2, 64-bit
buf = append(buf, repeat(0xaa, 8)...)
buf = append(buf, 0x1d) // field 3, 32-bit
buf = append(buf, repeat(0xbb, 4)...)
buf = appendBytesField(buf, 4, []byte("found"))
got, ok := lookupBytesField(buf, 4)
uassert.True(t, ok, "the length-delimited field is reachable past the others")
uassert.Equal(t, "found", string(got))
_, ok = lookupBytesField(buf, 9)
uassert.False(t, ok, "an absent field is reported missing, not guessed")
}
func TestBlobRejectsAnInvalidContact(t *testing.T) {
_, err := Contact{AccountPK: repeat(1, 31), Seed: repeat(2, 32)}.Blob()
uassert.ErrorIs(t, err, ErrBadAccountPKLen)
}
func endsWith(s, suffix string) bool {
return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
}
rendezvous.gno
package wesh
import "encoding/binary"
// DefaultRotationInterval is weshnet's rendezvous rotation period, in seconds
// (rendezvous.DefaultRotationInterval = 24h). The rendezvous point an account
// announces on changes once per interval, so an observer who learns one point
// does not learn every future one.
const DefaultRotationInterval int64 = 86400
// RoundPeriod returns the start of the rotation period containing unixSec.
// Mirrors weshnet's rendezvous.RoundTimePeriod.
func RoundPeriod(unixSec, interval int64) int64 {
if interval < 0 {
interval = -interval
}
if interval == 0 {
panic("wesh: rotation interval must not be zero")
}
return (unixSec / interval) * interval
}
// NextPeriod returns the start of the period after the one containing unixSec.
// Mirrors weshnet's rendezvous.NextTimePeriod.
func NextPeriod(unixSec, interval int64) int64 {
if interval < 0 {
interval = -interval
}
return RoundPeriod(unixSec, interval) + interval
}
// RendezvousPoint derives the rotating DHT topic an account announces on
// during the period starting at periodStart.
//
// It reproduces weshnet's rendezvous.GenerateRendezvousPointForPeriod exactly:
//
// HMAC-SHA256(key = topic ‖ seed, msg = big-endian uint64(periodStart))
//
// For contact requests, weshnet passes the account public key as the topic and
// the public rendezvous seed as the seed (see swiper.WatchTopic in
// contact_request_manager.go), which is what [Contact.RendezvousPointAt] does.
//
// Deriving this on chain is what makes a published identity checkable: anyone
// can confirm that the seed in the directory really is the one the account is
// announcing under, without trusting the directory.
func RendezvousPoint(topic, seed []byte, periodStart int64) []byte {
key := make([]byte, 0, len(topic)+len(seed))
key = append(key, topic...)
key = append(key, seed...)
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, uint64(periodStart))
return HMACSHA256(key, buf)
}
// RendezvousPointAt returns the contact's rendezvous point for the rotation
// period containing unixSec.
func (c Contact) RendezvousPointAt(unixSec, interval int64) ([]byte, error) {
if err := c.Validate(); err != nil {
return nil, err
}
return RendezvousPoint(c.AccountPK, c.Seed, RoundPeriod(unixSec, interval)), nil
}
rendezvous_test.gno
package wesh
import (
"encoding/hex"
"testing"
"gno.land/p/nt/uassert/v0"
)
// Reference vectors produced by running weshnet's own algorithm
// (rendezvous.GenerateRendezvousPointForPeriod) against these inputs:
// topic = accountPK, seed = seed, interval = 24h.
const (
testAccountPKHex = "2152f8d19b791d24453242e15f2eab6cb7cffa7b6a5ed30097960e069881db12"
testSeedHex = "abababababababababababababababababababababababababababababababab"
)
func TestRoundPeriod(t *testing.T) {
cases := []struct {
name string
unixSec int64
interval int64
want int64
}{
{"epoch", 0, DefaultRotationInterval, 0},
{"exactly on a boundary", 1789171200, DefaultRotationInterval, 1789171200},
{"one second before the next", 1789257599, DefaultRotationInterval, 1789171200},
{"one second after a boundary", 1789171201, DefaultRotationInterval, 1789171200},
{"a negative interval is taken as positive", 1789257599, -DefaultRotationInterval, 1789171200},
{"an hourly interval", 1789174800 + 59, 3600, 1789174800},
}
for _, tc := range cases {
uassert.Equal(t, tc.want, RoundPeriod(tc.unixSec, tc.interval), tc.name)
}
}
func TestNextPeriod(t *testing.T) {
uassert.Equal(t, int64(1789257600), NextPeriod(1789171200, DefaultRotationInterval))
uassert.Equal(t, int64(1789257600), NextPeriod(1789257599, DefaultRotationInterval))
}
// TestRendezvousPointMatchesWeshnet pins the derivation against vectors
// computed with weshnet's implementation. A divergence here means a gno-derived
// rendezvous point would not match the one the account actually announces on,
// which makes a published identity unverifiable.
func TestRendezvousPointMatchesWeshnet(t *testing.T) {
pk := mustHex(t, testAccountPKHex)
seed := mustHex(t, testSeedHex)
cases := []struct {
name string
periodStart int64
want string
}{
{
"period 0",
0,
"04500fdede2a684f4e61cd67968b46ecdbf10d45604041bb7e0350572b8cc9cc",
},
{
"period starting 1789171200",
1789171200,
"aad2926c39dacabaabbbde48522d043557c8945b6a2dc7b08499c112c72587da",
},
}
for _, tc := range cases {
got := hex.EncodeToString(RendezvousPoint(pk, seed, tc.periodStart))
uassert.Equal(t, tc.want, got, tc.name)
}
}
// TestRendezvousPointAtIsStableWithinAPeriod is the property that makes
// rotation useful: every instant inside one interval maps to the same point,
// and the next interval maps somewhere unrelated.
func TestRendezvousPointAtIsStableWithinAPeriod(t *testing.T) {
c := Contact{AccountPK: mustHex(t, testAccountPKHex), Seed: mustHex(t, testSeedHex)}
start, err := c.RendezvousPointAt(1789171200, DefaultRotationInterval)
uassert.NoError(t, err)
end, err := c.RendezvousPointAt(1789257599, DefaultRotationInterval)
uassert.NoError(t, err)
next, err := c.RendezvousPointAt(1789257600, DefaultRotationInterval)
uassert.NoError(t, err)
uassert.Equal(t, hex.EncodeToString(start), hex.EncodeToString(end),
"the point is stable for the whole period")
uassert.False(t, hex.EncodeToString(start) == hex.EncodeToString(next),
"the point rotates at the period boundary")
}
func TestRendezvousPointAtRejectsAnInvalidContact(t *testing.T) {
_, err := Contact{AccountPK: repeat(1, 32), Seed: repeat(2, 31)}.RendezvousPointAt(0, DefaultRotationInterval)
uassert.ErrorIs(t, err, ErrBadSeedLen)
}
func mustHex(t *testing.T, s string) []byte {
t.Helper()
b, err := hex.DecodeString(s)
if err != nil {
t.Fatalf("bad hex fixture: %v", err)
}
return b
}
statement.gno
package wesh
import (
"crypto/ed25519"
"crypto/sha256"
"encoding/hex"
"errors"
"strconv"
"strings"
)
// Statement kinds. A signature is only ever valid for the kind it was made
// under, so a binding signature can never be replayed as a device statement.
const (
kindBind = "gno.wesh/v0:bind"
kindDevice = "gno.wesh/v0:device"
)
// Device sigchain operations.
const (
OpAdd = "add"
OpRevoke = "revoke"
)
var (
ErrBadOp = errors.New("wesh: operation must be add or revoke")
ErrBadSignature = errors.New("wesh: signature does not verify under the account key")
ErrBadSeq = errors.New("wesh: sequence number must not be negative")
ErrBadPrevLen = errors.New("wesh: previous digest must be 32 bytes")
)
// DigestLen is the length of a statement digest (SHA-256).
const DigestLen = 32
// ValidOp reports whether op is a known sigchain operation.
func ValidOp(op string) bool { return op == OpAdd || op == OpRevoke }
// BindStatement returns the canonical text an account signs, with its Wesh
// account private key, to claim a directory entry.
//
// The signature is what makes a directory entry meaningful. Without it anyone
// could publish anyone else's account key next to a seed of their choosing and
// harvest the contact requests that followed. With it, a directory entry is a
// statement by the account itself, verifiable by anyone, replayable nowhere:
//
// - the kind prefix stops a signature made for one purpose being reused for
// another;
// - chainID stops a binding signed for a testnet being replayed on mainnet;
// - gnoAddr binds the Wesh identity to exactly one gno account, so a leaked
// signature cannot be used to claim the identity from a different address;
// - revision is monotonic, so an old, superseded binding cannot be replayed
// to roll a rotation back.
//
// payload is the seed for a publicly published identity, or the seed
// commitment from [SeedCommitment] for one that keeps its rendezvous point off
// chain. The two are indistinguishable on the wire, which is deliberate: an
// observer cannot tell a committed identity from a published one without the
// realm's own mode flag.
//
// Fields are newline-framed and hex-encoded, never concatenated raw: with
// plain concatenation a different split of the same bytes would produce the
// same statement.
func BindStatement(chainID, gnoAddr string, accountPK, payload []byte, revision int) string {
var b strings.Builder
b.WriteString(kindBind)
b.WriteString("\n")
b.WriteString(chainID)
b.WriteString("\n")
b.WriteString(gnoAddr)
b.WriteString("\n")
b.WriteString(hex.EncodeToString(accountPK))
b.WriteString("\n")
b.WriteString(hex.EncodeToString(payload))
b.WriteString("\n")
b.WriteString(strconv.Itoa(revision))
return b.String()
}
// DeviceStatement returns the canonical text an account signs to append one
// entry to its device sigchain.
//
// This is the piece the Wesh protocol has no answer for. Its own documentation
// says a device, once linked, can never be revoked: the account metadata log is
// append-only and no authority can mark an entry void. A chain cannot undo
// that (the ratchets are already out there and forward secrecy is a local
// property), but it can host the record that was missing, so a revocation
// becomes publicly visible, ordered, and attributable to the account key.
//
// prev is the digest of the preceding statement, or [GenesisDigest] for seq 0.
// Chaining each entry to its predecessor means the log cannot be reordered or
// have an entry quietly dropped: any gap changes every digest after it.
func DeviceStatement(chainID string, accountPK []byte, seq int, prev []byte, op string, devicePK []byte) string {
var b strings.Builder
b.WriteString(kindDevice)
b.WriteString("\n")
b.WriteString(chainID)
b.WriteString("\n")
b.WriteString(hex.EncodeToString(accountPK))
b.WriteString("\n")
b.WriteString(strconv.Itoa(seq))
b.WriteString("\n")
b.WriteString(hex.EncodeToString(prev))
b.WriteString("\n")
b.WriteString(op)
b.WriteString("\n")
b.WriteString(hex.EncodeToString(devicePK))
return b.String()
}
// StatementDigest returns SHA-256 of a canonical statement. It is the value
// the next sigchain entry chains to.
func StatementDigest(statement string) []byte {
sum := sha256.Sum256([]byte(statement))
return sum[:]
}
// GenesisDigest is the all-zero digest that the first sigchain entry chains to.
func GenesisDigest() []byte { return make([]byte, DigestLen) }
// VerifyBind checks a binding signature against the account key.
func VerifyBind(chainID, gnoAddr string, accountPK, payload []byte, revision int, sig []byte) error {
if len(accountPK) != AccountPKLen {
return ErrBadAccountPKLen
}
stmt := BindStatement(chainID, gnoAddr, accountPK, payload, revision)
if !ed25519.Verify(accountPK, []byte(stmt), sig) {
return ErrBadSignature
}
return nil
}
// VerifyDevice checks a sigchain entry's shape and its signature, and returns
// the digest the next entry must chain to.
func VerifyDevice(chainID string, accountPK []byte, seq int, prev []byte, op string, devicePK, sig []byte) ([]byte, error) {
if len(accountPK) != AccountPKLen {
return nil, ErrBadAccountPKLen
}
if len(devicePK) != DevicePKLen {
return nil, ErrBadDevicePKLen
}
if seq < 0 {
return nil, ErrBadSeq
}
if len(prev) != DigestLen {
return nil, ErrBadPrevLen
}
if !ValidOp(op) {
return nil, ErrBadOp
}
stmt := DeviceStatement(chainID, accountPK, seq, prev, op, devicePK)
if !ed25519.Verify(accountPK, []byte(stmt), sig) {
return nil, ErrBadSignature
}
return StatementDigest(stmt), nil
}
statement_test.gno
package wesh
import (
"encoding/hex"
"testing"
"gno.land/p/nt/uassert/v0"
)
// Fixtures. The signatures were produced with Go's crypto/ed25519 over the
// exact statement text this package builds, using the account key whose seed
// is 32 x 0x42, the same key as testAccountPKHex.
const (
testChainID = "gnoland-1"
testGnoAddr = "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"
testDev1Hex = "0707070707070707070707070707070707070707070707070707070707070707"
testDev2Hex = "0909090909090909090909090909090909090909090909090909090909090909"
bindRev1Sig = "4cd53e6096994d2801de1b16cfd1b2d2aa34ff35b265c53fa176cfb18c949be7" +
"0078161fe2afaf503cf808b2f52a321e15a625f56b1b2d0aaaf8c460f6d64702"
dev0Sig = "19d0bd2517ca6308b089196528e6c27359117b80e1972c71c25434a6f260d62a" +
"703a28c2f973d89056e7c691b4f879d38e1b016745508b357d217eb54c984305"
dev0Digest = "003570bf50d50213f9f3e9c76a8271435a8f2e4b7c24010a8e8383dedd0ed2a6"
dev1Sig = "c26b338045373f7504a0d251c2126e31ff3330f08463672a82467daf4dedca51" +
"1da4681715a6c3afe4115622cfcca9ec3f44d5a35f9973c3b9856cc06859810c"
dev1Digest = "35a8219e60f6cd375e1378879de8921f9d554f054cd8a70ea2d3914b20b77bbb"
)
func TestBindStatementIsCanonical(t *testing.T) {
got := BindStatement(testChainID, testGnoAddr, mustHex(t, testAccountPKHex), mustHex(t, testSeedHex), 1)
want := "gno.wesh/v0:bind\n" + testChainID + "\n" + testGnoAddr + "\n" +
testAccountPKHex + "\n" + testSeedHex + "\n1"
uassert.Equal(t, want, got)
}
func TestVerifyBind(t *testing.T) {
pk := mustHex(t, testAccountPKHex)
seed := mustHex(t, testSeedHex)
sig := mustHex(t, bindRev1Sig)
uassert.NoError(t, VerifyBind(testChainID, testGnoAddr, pk, seed, 1, sig),
"a signature made by the account key verifies")
}
// TestVerifyBindRejectsEveryTamperedField is the heart of the scheme: each
// field is in the signed text precisely so that changing it invalidates the
// signature. One case per field, so a regression names the field it broke.
func TestVerifyBindRejectsEveryTamperedField(t *testing.T) {
pk := mustHex(t, testAccountPKHex)
seed := mustHex(t, testSeedHex)
sig := mustHex(t, bindRev1Sig)
cases := []struct {
name string
chainID string
addr string
payload []byte
rev int
}{
{"replayed on another chain", "test7", testGnoAddr, seed, 1},
{"claimed from another gno address", testChainID, "g1manfred47kzduec920z88wfr64ylksmdcedlf5", seed, 1},
{"a different seed swapped in", testChainID, testGnoAddr, repeat(0xEE, 32), 1},
{"an older revision replayed", testChainID, testGnoAddr, seed, 0},
{"a newer revision forged", testChainID, testGnoAddr, seed, 2},
}
for _, tc := range cases {
err := VerifyBind(tc.chainID, tc.addr, pk, tc.payload, tc.rev, sig)
uassert.ErrorIs(t, err, ErrBadSignature, tc.name)
}
}
func TestVerifyBindRejectsAnotherAccountsKey(t *testing.T) {
err := VerifyBind(testChainID, testGnoAddr, repeat(0x33, 32), mustHex(t, testSeedHex), 1, mustHex(t, bindRev1Sig))
uassert.ErrorIs(t, err, ErrBadSignature)
err = VerifyBind(testChainID, testGnoAddr, repeat(0x33, 31), mustHex(t, testSeedHex), 1, mustHex(t, bindRev1Sig))
uassert.ErrorIs(t, err, ErrBadAccountPKLen)
}
func TestGenesisDigest(t *testing.T) {
uassert.Equal(t, DigestLen, len(GenesisDigest()))
uassert.Equal(t,
"0000000000000000000000000000000000000000000000000000000000000000",
hex.EncodeToString(GenesisDigest()))
}
// TestVerifyDeviceChain walks a three-entry sigchain: add, add, revoke. Each
// entry chains to the digest of the previous one, which is what stops an entry
// being reordered or silently dropped.
func TestVerifyDeviceChain(t *testing.T) {
pk := mustHex(t, testAccountPKHex)
d0, err := VerifyDevice(testChainID, pk, 0, GenesisDigest(), OpAdd, mustHex(t, testDev1Hex), mustHex(t, dev0Sig))
uassert.NoError(t, err, "first entry")
uassert.Equal(t, dev0Digest, hex.EncodeToString(d0), "digest the next entry must chain to")
d1, err := VerifyDevice(testChainID, pk, 1, d0, OpAdd, mustHex(t, testDev2Hex), mustHex(t, dev1Sig))
uassert.NoError(t, err, "second entry")
uassert.Equal(t, dev1Digest, hex.EncodeToString(d1))
}
func TestVerifyDeviceRejectsABrokenChain(t *testing.T) {
pk := mustHex(t, testAccountPKHex)
dev1 := mustHex(t, testDev1Hex)
dev2 := mustHex(t, testDev2Hex)
cases := []struct {
name string
seq int
prev []byte
op string
device []byte
sig string
wantErr error
}{
{"wrong previous digest", 1, GenesisDigest(), OpAdd, dev2, dev1Sig, ErrBadSignature},
{"wrong sequence number", 2, mustHexRaw(dev0Digest), OpAdd, dev2, dev1Sig, ErrBadSignature},
{"operation flipped to revoke", 0, GenesisDigest(), OpRevoke, dev1, dev0Sig, ErrBadSignature},
{"a different device substituted", 0, GenesisDigest(), OpAdd, dev2, dev0Sig, ErrBadSignature},
{"unknown operation", 0, GenesisDigest(), "delete", dev1, dev0Sig, ErrBadOp},
{"negative sequence", -1, GenesisDigest(), OpAdd, dev1, dev0Sig, ErrBadSeq},
{"short previous digest", 0, repeat(0, 31), OpAdd, dev1, dev0Sig, ErrBadPrevLen},
{"short device key", 0, GenesisDigest(), OpAdd, repeat(7, 31), dev0Sig, ErrBadDevicePKLen},
}
for _, tc := range cases {
_, err := VerifyDevice(testChainID, pk, tc.seq, tc.prev, tc.op, tc.device, mustHexRaw(tc.sig))
uassert.ErrorIs(t, err, tc.wantErr, tc.name)
}
}
func TestValidOp(t *testing.T) {
uassert.True(t, ValidOp(OpAdd))
uassert.True(t, ValidOp(OpRevoke))
uassert.False(t, ValidOp("Add"), "operations are case-sensitive")
uassert.False(t, ValidOp(""))
}
func mustHexRaw(s string) []byte {
b, err := hex.DecodeString(s)
if err != nil {
panic("bad hex fixture: " + s)
}
return b
}
wesh.gno
// Package wesh implements the publishable, non-secret half of the Wesh
// protocol (weshnet, the network layer behind Berty) as a pure gno library.
//
// # What this is, and what it deliberately is not
//
// Wesh is an off-grid, peer-to-peer, end-to-end-encrypted messaging protocol.
// A public blockchain is the opposite of that in almost every dimension:
// globally replicated, permanent, publicly readable and totally ordered. So
// "put Wesh on chain" is the wrong goal, and this package does not pursue it.
//
// What a chain *is* good at is the one thing Wesh has no answer for: an
// authenticated, ordered, publicly auditable record that no single party owns.
// Wesh has three gaps of exactly that shape:
//
// 1. A Berty identity travels out of band, as a QR code or a
// https://berty.tech/id# link. There is no way to look one up, and the
// web prefix is a single host that can be blocked or spoofed.
// 2. Resetting the public rendezvous seed (ContactRequestResetReference)
// silently invalidates every link ever shared. There is no revocation
// channel, so a business card keeps pointing at a dead rendezvous point.
// 3. A device, once linked to an account, can never be revoked. The Wesh
// protocol documentation states this outright. The account metadata log is
// append-only and there is no authority that can mark an entry void.
//
// This package carries the pieces needed to address those on chain, and
// nothing else. Everything here is public by construction:
//
// - [Contact], the publishable identity, weshnet's ShareableContact
// (account public key + public rendezvous seed + display name).
// - The Berty link codec, byte-compatible with berty's own MarshalLink.
// - [RendezvousPoint], the rotating DHT address derivation.
// - The canonical statements an account signs to bind itself to a gno
// address, rotate its seed, and append to a device sigchain.
//
// # What must never reach a chain
//
// Group secrets (weshnet's Group.secret, Group.link_key), device chain keys,
// message keys, ciphertexts. Publishing a group secret hands the group to
// everyone; publishing ciphertext is permanent, expensive, and leaks the
// social graph through access patterns. This package has no type that can
// hold one, which is the point: there is no struct field here for a secret to
// accidentally land in.
//
// # The privacy trade-off, stated plainly
//
// Publishing a rendezvous seed is equivalent to printing your Berty QR code on
// a billboard. Anyone can then derive today's rendezvous point with
// [RendezvousPoint] and watch the DHT for who shows up. That is a real
// deanonymization surface, and it is why publication must be an explicit,
// opt-in act for an identity that *wants* to be found: a support line, a shop,
// a DAO's public channel.
//
// For an identity that does not want that, [SeedCommitment] publishes
// H(seed ‖ salt) instead. The chain then proves that a seed handed over out of
// band really does belong to the named account, without broadcasting the
// rendezvous point to the world.
//
// Live realm using this library: [r/moul/x/wesh](/r/nym-moultest123/x/wesh/v0).
package wesh
import (
"crypto/sha256"
"encoding/hex"
"errors"
)
const (
// SeedLen is the length of a public rendezvous seed. Matches weshnet's
// protocoltypes.RendezvousSeedLength.
SeedLen = 32
// AccountPKLen is the length of an account public key. weshnet validates
// it with libp2p's UnmarshalEd25519PublicKey, which accepts raw 32-byte
// ed25519 public keys only.
AccountPKLen = 32
// DevicePKLen is the length of a device public key: also a raw ed25519
// public key.
DevicePKLen = 32
// MaxDisplayNameLen bounds the display name so a link stays scannable and
// gas stays predictable. Not a protocol constant.
MaxDisplayNameLen = 64
)
var (
ErrBadSeedLen = errors.New("wesh: public rendezvous seed must be 32 bytes")
ErrBadAccountPKLen = errors.New("wesh: account public key must be a raw 32-byte ed25519 key")
ErrBadDevicePKLen = errors.New("wesh: device public key must be a raw 32-byte ed25519 key")
ErrDisplayNameTooLong = errors.New("wesh: display name exceeds MaxDisplayNameLen")
ErrBadCommitmentLen = errors.New("wesh: seed commitment must be 32 bytes")
ErrBadHex = errors.New("wesh: value is not valid hex")
)
// Contact is the publishable identity of a Wesh account: weshnet's
// ShareableContact. It is everything a stranger needs to send a contact
// request, and it contains no secret.
//
// AccountPK is the raw ed25519 account public key. Seed is the public
// rendezvous seed; together they derive the rotating rendezvous point the
// account announces on, see [RendezvousPoint]. DisplayName is free-form app
// metadata and is not authenticated by anything.
type Contact struct {
AccountPK []byte
Seed []byte
DisplayName string
}
// Validate applies weshnet's own ShareableContact.CheckFormat rules: the seed
// must be exactly SeedLen bytes, and the account key must be a raw ed25519
// public key. It deliberately does not verify that AccountPK is a valid curve
// point; that costs a scalar multiplication and the chain gets the same
// guarantee for free the first time it verifies a signature under the key.
func (c Contact) Validate() error {
if len(c.Seed) != SeedLen {
return ErrBadSeedLen
}
if len(c.AccountPK) != AccountPKLen {
return ErrBadAccountPKLen
}
if len(c.DisplayName) > MaxDisplayNameLen {
return ErrDisplayNameTooLong
}
return nil
}
// SeedCommitment returns H(seed ‖ salt), the value published instead of the
// seed itself when an account wants the chain to attest the binding without
// broadcasting its rendezvous point.
//
// The salt is not optional: a seed is 32 bytes of entropy, but a commitment
// with no salt is a deterministic function of the seed, so two accounts that
// (impossibly, but still) shared a seed would be linkable, and a seed later
// disclosed out of band retroactively confirms every past commitment. The salt
// keeps disclosure a deliberate act.
func SeedCommitment(seed, salt []byte) ([]byte, error) {
if len(seed) != SeedLen {
return nil, ErrBadSeedLen
}
buf := make([]byte, 0, len(seed)+len(salt))
buf = append(buf, seed...)
buf = append(buf, salt...)
sum := sha256.Sum256(buf)
return sum[:], nil
}
// OpenCommitment reports whether commitment is H(seed ‖ salt).
//
// The comparison is constant-time over the digest: a short-circuiting compare
// leaks, through gas, how many leading bytes of a guess were right.
func OpenCommitment(commitment, seed, salt []byte) bool {
want, err := SeedCommitment(seed, salt)
if err != nil {
return false
}
return constantTimeEqual(commitment, want)
}
// constantTimeEqual compares two byte slices without an early return.
func constantTimeEqual(a, b []byte) bool {
if len(a) != len(b) {
return false
}
var diff byte
for i := 0; i < len(a); i++ {
diff |= a[i] ^ b[i]
}
return diff == 0
}
// Every key this package handles is 32 bytes, so a single length-checking
// helper cannot say which one was wrong. These four wrappers exist so the
// error a realm surfaces names the field the caller actually got wrong.
// DecodeAccountPK parses a hex-encoded account public key.
func DecodeAccountPK(s string) ([]byte, error) {
return decodeFixed(s, AccountPKLen, ErrBadAccountPKLen)
}
// DecodeSeed parses a hex-encoded public rendezvous seed.
func DecodeSeed(s string) ([]byte, error) {
return decodeFixed(s, SeedLen, ErrBadSeedLen)
}
// DecodeDevicePK parses a hex-encoded device public key.
func DecodeDevicePK(s string) ([]byte, error) {
return decodeFixed(s, DevicePKLen, ErrBadDevicePKLen)
}
// DecodeCommitment parses a hex-encoded seed commitment.
func DecodeCommitment(s string) ([]byte, error) {
return decodeFixed(s, DigestLen, ErrBadCommitmentLen)
}
// decodeFixed parses hex and enforces an exact byte length. Realms take keys
// as hex strings because that is what a transaction argument can carry; this
// is the single place the length rule is applied.
func decodeFixed(s string, want int, badLen error) ([]byte, error) {
b, err := hex.DecodeString(s)
if err != nil {
return nil, ErrBadHex
}
if len(b) != want {
return nil, badLen
}
return b, nil
}
wesh_test.gno
package wesh
import (
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestContactValidate(t *testing.T) {
cases := []struct {
name string
in Contact
want error
}{
{"well-formed", Contact{AccountPK: repeat(1, 32), Seed: repeat(2, 32)}, nil},
{"with a display name", Contact{AccountPK: repeat(1, 32), Seed: repeat(2, 32), DisplayName: "gno"}, nil},
{"seed too short", Contact{AccountPK: repeat(1, 32), Seed: repeat(2, 31)}, ErrBadSeedLen},
{"seed too long", Contact{AccountPK: repeat(1, 32), Seed: repeat(2, 33)}, ErrBadSeedLen},
{"no seed", Contact{AccountPK: repeat(1, 32)}, ErrBadSeedLen},
{"account key too short", Contact{AccountPK: repeat(1, 31), Seed: repeat(2, 32)}, ErrBadAccountPKLen},
{"no account key", Contact{Seed: repeat(2, 32)}, ErrBadAccountPKLen},
{
"display name too long",
Contact{AccountPK: repeat(1, 32), Seed: repeat(2, 32), DisplayName: string(make([]byte, MaxDisplayNameLen+1))},
ErrDisplayNameTooLong,
},
}
for _, tc := range cases {
err := tc.in.Validate()
if tc.want == nil {
uassert.NoError(t, err, tc.name)
continue
}
uassert.ErrorIs(t, err, tc.want, tc.name)
}
}
func TestSeedCommitment(t *testing.T) {
seed := mustHex(t, testSeedHex)
salt := []byte("a-16-byte-salt!!")
c, err := SeedCommitment(seed, salt)
uassert.NoError(t, err)
uassert.Equal(t, DigestLen, len(c))
again, err := SeedCommitment(seed, salt)
uassert.NoError(t, err)
uassert.Equal(t, string(c), string(again), "the commitment is deterministic")
uassert.True(t, OpenCommitment(c, seed, salt), "the correct opening verifies")
uassert.False(t, OpenCommitment(c, seed, []byte("another-salt!!!!")), "a wrong salt does not open it")
uassert.False(t, OpenCommitment(c, repeat(0xEE, 32), salt), "a wrong seed does not open it")
uassert.False(t, OpenCommitment(c[:31], seed, salt), "a truncated commitment does not open it")
}
func TestSeedCommitmentRejectsABadSeed(t *testing.T) {
_, err := SeedCommitment(repeat(1, 31), []byte("salt"))
uassert.ErrorIs(t, err, ErrBadSeedLen)
}
// TestSeedCommitmentIsSaltSeparated guards the length-extension style
// ambiguity: without distinct inputs, (seed, "ab") and (seed+"a", "b") would
// collide. The seed is fixed-length, which resolves it, and this pins that.
func TestSeedCommitmentDependsOnTheSplit(t *testing.T) {
seed := repeat(0xAA, 32)
a, _ := SeedCommitment(seed, []byte("ab"))
b, _ := SeedCommitment(seed, []byte("abc"))
uassert.False(t, string(a) == string(b))
}
func TestDecodeHelpers(t *testing.T) {
cases := []struct {
name string
fn func(string) ([]byte, error)
in string
err error
}{
{"account key", DecodeAccountPK, testAccountPKHex, nil},
{"seed", DecodeSeed, testSeedHex, nil},
{"device key", DecodeDevicePK, testSeedHex, nil},
{"commitment", DecodeCommitment, testSeedHex, nil},
{"account key, not hex", DecodeAccountPK, "zzzz", ErrBadHex},
{"account key, odd length", DecodeAccountPK, "abc", ErrBadHex},
{"account key, wrong length", DecodeAccountPK, "abcd", ErrBadAccountPKLen},
{"seed, wrong length", DecodeSeed, "abcd", ErrBadSeedLen},
{"device key, wrong length", DecodeDevicePK, "abcd", ErrBadDevicePKLen},
{"commitment, wrong length", DecodeCommitment, "abcd", ErrBadCommitmentLen},
}
for _, tc := range cases {
got, err := tc.fn(tc.in)
if tc.err == nil {
uassert.NoError(t, err, tc.name)
uassert.Equal(t, 32, len(got), tc.name)
continue
}
uassert.ErrorIs(t, err, tc.err, tc.name)
}
}