Playground
codespan_test.gno
package wesh
import (
"strings"
"testing"
)
// A crafted URL path used to close this code span early and render its own
// markdown. md.InlineCode sizes the fence past any backtick run, so the payload
// comes back inside a double fence with the backtick intact.
func TestRenderPathCannotEscapeItsCodeSpan(t *testing.T) {
out := Render("a`b")
if !strings.Contains(out, "``a`b``") {
t.Fatalf("the fence did not outscan the caller's backtick: %q", out)
}
}
gnomod.toml
module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/wesh/v0" gno = "0.9" private = true [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 914348 max_deposit = "21000000ugnot"
render.gno
package wesh
import (
"chain/runtime"
"encoding/hex"
"strconv"
"strings"
"time"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/wesh/v0"
)
// Render serves the directory index at "" and one identity card at "<name>".
//
// The index deliberately does not compute a Berty link per row: base58 over a
// 70-byte payload is big-integer work, and it belongs on the page that a human
// actually asked for.
func Render(path string) string {
path = strings.Trim(path, "/")
if path == "" {
return renderIndex()
}
return renderIdentity(path)
}
func renderIndex() string {
var b strings.Builder
b.WriteString("# Wesh directory\n\n")
b.WriteString("Resolvable, self-signed [Wesh protocol](https://berty.tech/docs/protocol/) ")
b.WriteString("identities, on top of [`p/moul/x/wesh`](/p/moul/x/wesh/v0).\n\n")
b.WriteString("A Berty identity normally travels out of band as a QR code, cannot be ")
b.WriteString("looked up, cannot announce a seed rotation, and can never revoke a device. ")
b.WriteString("This realm addresses those three, and stores no secret of any kind.\n\n")
if byName.Size() == 0 {
b.WriteString("_No identity registered yet._\n")
return b.String()
}
b.WriteString("| name | owner | rev | mode | devices |\n")
b.WriteString("|---|---|---|---|---|\n")
byName.Iterate("", "", func(key string, value any) bool {
id := value.(*identity)
b.WriteString("| [" + id.name + "](/r/moul/x/wesh/v0:" + id.name + ") ")
b.WriteString("| `" + id.owner.String() + "` ")
b.WriteString("| " + strconv.Itoa(id.revision) + " ")
b.WriteString("| " + modeLabel(id) + " ")
b.WriteString("| " + strconv.Itoa(activeDevices(id)) + " active / " + strconv.Itoa(len(id.devices)) + " entries |\n")
return false
})
n := byName.Size()
if n == 1 {
b.WriteString("\n1 identity.\n")
} else {
b.WriteString("\n" + strconv.Itoa(n) + " identities.\n")
}
return b.String()
}
func renderIdentity(name string) string {
id := lookup(name)
if id == nil {
return "# Not found\n\nNo identity named " + md.InlineCode(name) + ". [Back to the directory](/r/moul/x/wesh/v0).\n"
}
var b strings.Builder
b.WriteString("# " + id.name + "\n\n")
if id.displayName != "" {
b.WriteString("_" + id.displayName + "_\n\n")
}
b.WriteString("| field | value |\n|---|---|\n")
b.WriteString("| owner | `" + id.owner.String() + "` |\n")
b.WriteString("| account key | `" + hex.EncodeToString(id.accountPK) + "` |\n")
b.WriteString("| mode | " + modeLabel(id) + " |\n")
b.WriteString("| revision | " + strconv.Itoa(id.revision) + " |\n")
b.WriteString("| registered | block " + strconv.FormatInt(id.history[0].height, 10) + " |\n")
b.WriteString("\n## Contact\n\n")
if id.committed {
b.WriteString("This identity publishes a **commitment**, `")
b.WriteString(hex.EncodeToString(id.payload))
b.WriteString("`, not its rendezvous seed.\n\n")
b.WriteString("The chain attests that this account key claimed that commitment from ")
b.WriteString("that gno address. The seed itself is shared out of band, and whoever ")
b.WriteString("receives it can check it here with `H(seed || salt)` before using it. ")
b.WriteString("The rendezvous point stays off chain.\n")
} else {
link, err := contactOf(id).WebLink()
if err != nil {
b.WriteString("_Contact is unrenderable: " + err.Error() + "_\n")
} else {
b.WriteString("Scan or open this in Berty to send a contact request:\n\n")
b.WriteString("```\n" + link + "\n```\n\n")
b.WriteString("| field | value |\n|---|---|\n")
b.WriteString("| rendezvous seed | `" + hex.EncodeToString(id.payload) + "` |\n")
now := time.Now().Unix()
period := wesh.RoundPeriod(now, wesh.DefaultRotationInterval)
point, _ := contactOf(id).RendezvousPointAt(now, wesh.DefaultRotationInterval)
b.WriteString("| rendezvous point, period " + strconv.FormatInt(period, 10) + " | `" + hex.EncodeToString(point) + "` |\n")
b.WriteString("\nThe point is `HMAC-SHA256(accountPK || seed, be64(period))`, derived ")
b.WriteString("exactly as weshnet derives it, and it rotates every 24h. Anyone can ")
b.WriteString("recompute it and check the DHT, so this entry is verifiable rather ")
b.WriteString("than merely asserted.\n")
}
}
b.WriteString("\n## Devices\n\n")
if len(id.devices) == 0 {
b.WriteString("No sigchain entry yet. Head is the genesis digest `")
b.WriteString(hex.EncodeToString(id.head) + "`.\n")
} else {
b.WriteString("Every entry below was signed by the account key and verified on chain, ")
b.WriteString("and chains to the digest of the one before it.\n\n")
b.WriteString("| seq | op | device | block | digest |\n|---|---|---|---|---|\n")
for _, e := range id.devices {
b.WriteString("| " + strconv.Itoa(e.seq) + " ")
b.WriteString("| " + e.op + " ")
b.WriteString("| `" + short(hex.EncodeToString(e.devicePK)) + "` ")
b.WriteString("| " + strconv.FormatInt(e.height, 10) + " ")
b.WriteString("| `" + short(hex.EncodeToString(e.digest)) + "` |\n")
}
b.WriteString("\nHead: `" + hex.EncodeToString(id.head) + "`\n")
}
if len(id.history) > 1 {
b.WriteString("\n## Rotation history\n\n")
b.WriteString("Weshnet has no way to announce that a seed was reset, so every link ")
b.WriteString("ever shared dies silently. These are the superseded values, kept so a ")
b.WriteString("stale link can be recognised as stale.\n\n")
b.WriteString("| rev | value | block |\n|---|---|---|\n")
for _, r := range id.history {
mark := ""
if r.revision == id.revision {
mark = " (current)"
}
b.WriteString("| " + strconv.Itoa(r.revision) + mark + " ")
b.WriteString("| `" + short(hex.EncodeToString(r.payload)) + "` ")
b.WriteString("| " + strconv.FormatInt(r.height, 10) + " |\n")
}
}
b.WriteString("\n[Back to the directory](/r/moul/x/wesh/v0) · chain `" + runtime.ChainID() + "`\n")
return b.String()
}
func modeLabel(id *identity) string {
if id.committed {
return "committed"
}
return "published"
}
// activeDevices counts the distinct devices whose latest sigchain entry is an
// add. A device can be added, revoked and added again, so only the last entry
// for each key decides.
func activeDevices(id *identity) int {
seen := []string{}
for _, e := range id.devices {
key := string(e.devicePK)
known := false
for _, s := range seen {
if s == key {
known = true
break
}
}
if !known {
seen = append(seen, key)
}
}
n := 0
for _, k := range seen {
if deviceIsActive(id, []byte(k)) {
n++
}
}
return n
}
// short abbreviates a long hex string for table cells.
func short(s string) string {
if len(s) <= 16 {
return s
}
return s[:8] + "…" + s[len(s)-8:]
}
render_example_test.gno
package wesh
import (
"encoding/hex"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/wesh/v0"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/testutils/v0"
)
// seedDemo puts the realm into a fixed state for the examples below.
//
// It writes the globals directly instead of going through the crossing API:
// realm globals persist for the whole test binary and examples run after every
// Test, so an example that did not reset would pin whatever the last test left
// behind. Heights are literals for the same reason.
func seedDemo() {
byName = avl.Tree{}
byOwner = avl.Tree{}
byAccount = avl.Tree{}
pk, _ := hex.DecodeString("2152f8d19b791d24453242e15f2eab6cb7cffa7b6a5ed30097960e069881db12")
seed1, _ := hex.DecodeString("abababababababababababababababababababababababababababababababab")
seed2, _ := hex.DecodeString("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
dev1, _ := hex.DecodeString("0707070707070707070707070707070707070707070707070707070707070707")
dev2, _ := hex.DecodeString("0909090909090909090909090909090909090909090909090909090909090909")
d1, _ := hex.DecodeString("bc51799b5d012dc7ce806b4c63474b1e2db515e7d1622ecd5900b23e1d6a9519")
d2, _ := hex.DecodeString("b0da03f83e5349e92bc524714862daa850750f756ca6fd47264333fbf2175c15")
d3, _ := hex.DecodeString("ef0c1d0614420c7d660f8416b18651206118e49e8f46ac0360bef61ae6b9100d")
alice := &identity{
name: "alice",
owner: testutils.TestAddress("alice"),
accountPK: pk,
payload: seed2,
revision: 2,
displayName: "Alice, support line",
history: []rotation{
{revision: 1, payload: seed1, height: 100},
{revision: 2, payload: seed2, height: 140},
},
devices: []deviceEntry{
{seq: 0, op: wesh.OpAdd, devicePK: dev1, digest: d1, height: 110},
{seq: 1, op: wesh.OpAdd, devicePK: dev2, digest: d2, height: 120},
{seq: 2, op: wesh.OpRevoke, devicePK: dev1, digest: d3, height: 130},
},
head: d3,
}
byName.Set(alice.name, alice)
byOwner.Set(alice.owner.String(), alice.name)
byAccount.Set(hex.EncodeToString(pk), alice.name)
}
// ExampleRender pins the directory index.
func ExampleRender() {
seedDemo()
print(Render(""))
// Output:
// # Wesh directory
//
// Resolvable, self-signed [Wesh protocol](https://berty.tech/docs/protocol/) identities, on top of [`p/moul/x/wesh`](/p/moul/x/wesh/v0).
//
// A Berty identity normally travels out of band as a QR code, cannot be looked up, cannot announce a seed rotation, and can never revoke a device. This realm addresses those three, and stores no secret of any kind.
//
// | name | owner | rev | mode | devices |
// |---|---|---|---|---|
// | [alice](/r/moul/x/wesh/v0:alice) | `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh` | 2 | published | 1 active / 3 entries |
//
// 1 identity.
}
// ExampleRender_identity pins one identity card: the Berty link, today's
// rendezvous point, the device sigchain and the rotation history.
func ExampleRender_identity() {
seedDemo()
print(Render("alice"))
// Output:
// # alice
//
// _Alice, support line_
//
// | field | value |
// |---|---|
// | owner | `g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh` |
// | account key | `2152f8d19b791d24453242e15f2eab6cb7cffa7b6a5ed30097960e069881db12` |
// | mode | published |
// | revision | 2 |
// | registered | block 100 |
//
// ## Contact
//
// Scan or open this in Berty to send a contact request:
//
// ```
// https://berty.tech/id#contact/oZBLGHCDNRB847rT1zHe1xnon58fpWTUsuNntmAo9TK42aKzt14A1V5W67QoN5YzMouuVcucUiBWjN9d2qzy6gUNM4Jio4M/name=Alice%2C+support+line
// ```
//
// | field | value |
// |---|---|
// | rendezvous seed | `eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee` |
// | rendezvous point, period 1234483200 | `08ab5591fbd91f0251a7efe4856fc736a02d1a2252139483ddc8ca85f4616e07` |
//
// The point is `HMAC-SHA256(accountPK || seed, be64(period))`, derived exactly as weshnet derives it, and it rotates every 24h. Anyone can recompute it and check the DHT, so this entry is verifiable rather than merely asserted.
//
// ## Devices
//
// Every entry below was signed by the account key and verified on chain, and chains to the digest of the one before it.
//
// | seq | op | device | block | digest |
// |---|---|---|---|---|
// | 0 | add | `07070707…07070707` | 110 | `bc51799b…1d6a9519` |
// | 1 | add | `09090909…09090909` | 120 | `b0da03f8…f2175c15` |
// | 2 | revoke | `07070707…07070707` | 130 | `ef0c1d06…e6b9100d` |
//
// Head: `ef0c1d0614420c7d660f8416b18651206118e49e8f46ac0360bef61ae6b9100d`
//
// ## Rotation history
//
// Weshnet has no way to announce that a seed was reset, so every link ever shared dies silently. These are the superseded values, kept so a stale link can be recognised as stale.
//
// | rev | value | block |
// |---|---|---|
// | 1 | `abababab…abababab` | 100 |
// | 2 (current) | `eeeeeeee…eeeeeeee` | 140 |
//
// [Back to the directory](/r/moul/x/wesh/v0) · chain `dev`
}
// ExampleRender_unknown pins the miss.
func ExampleRender_unknown() {
seedDemo()
print(Render("nobody"))
// Output:
// # Not found
//
// No identity named `nobody`. [Back to the directory](/r/moul/x/wesh/v0).
}
wesh.gno
// Package wesh is an on-chain directory and device sigchain for Wesh protocol
// (weshnet / Berty) identities.
//
// It exists to give weshnet the three things a peer-to-peer network cannot
// give itself, and which a chain is uniquely good at:
//
// 1. Resolution. A Berty identity travels out of band as a QR code or a
// https://berty.tech/id# link, and there is no way to look one up. Here a
// name resolves to a contact, and Render emits the real, scannable link.
// 2. Rotation with a paper trail. Resetting the public rendezvous seed
// silently kills every link ever shared; there is no revocation channel.
// Here every rotation is a numbered, timestamped, signed entry, and the
// superseded seeds stay visible, so a stale link resolves to a redirect
// instead of to nothing.
// 3. Device revocation. The Wesh protocol documentation states plainly that a
// device, once linked to an account, can never be revoked: the account
// metadata log is append-only and no authority can void an entry. This
// realm hosts the log that was missing: a hash-chained, account-signed
// roster whose every entry the chain verifies with ed25519 before
// accepting it.
//
// # What this realm does not do, and will not
//
// It never stores a secret. Group secrets, device chain keys, message keys and
// ciphertexts stay off chain, permanently. The library this realm is built on,
// [p/moul/x/wesh](/p/moul/x/wesh/v0), has no type that can hold one.
//
// It also does not pretend to enforce revocation inside weshnet. A revoked
// device's ratchets are already distributed and forward secrecy is a local
// property; no chain can reach into a group and forget them. What revocation
// buys here is that it becomes public, ordered, and attributable to the
// account key, which is strictly more than weshnet has today.
//
// # Publishing is a deliberate act
//
// A published rendezvous seed lets anyone derive the account's rotating
// rendezvous point and watch the DHT for it. That is the same exposure as
// printing your Berty QR code on a billboard, and it is the right trade only
// for an identity that wants to be found: a support line, a shop, a public
// channel.
//
// [RegisterCommitted] is the alternative. It publishes H(seed ‖ salt) instead,
// so the chain attests that a seed handed over out of band really belongs to
// the named account, without broadcasting where that account listens.
//
// # Authentication
//
// Every state-changing call carries an ed25519 signature made with the Wesh
// account private key over a canonical statement that names this chain, the
// caller's gno address, and a monotonic revision or sequence number. Without
// it, anyone could publish anyone else's account key next to a seed of their
// choosing and harvest the contact requests that followed.
package wesh
import (
"chain/runtime"
"encoding/hex"
"strings"
"time"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/wesh/v0"
"gno.land/p/nt/avl/v0"
)
const (
// MinNameLen and MaxNameLen bound a directory handle.
MinNameLen = 3
MaxNameLen = 32
// MaxDevices bounds one account's sigchain so iteration and Render stay
// affordable. weshnet accounts hold a handful of devices, not hundreds.
MaxDevices = 64
// MaxRotations bounds the retained rotation history. Older entries are
// dropped from the front: the point of the history is to let a stale link
// be recognised, not to keep a permanent archive.
MaxRotations = 32
)
// rotation is one seed (or commitment) an identity has published.
type rotation struct {
revision int
payload []byte
height int64
}
// deviceEntry is one verified sigchain statement.
type deviceEntry struct {
seq int
op string
devicePK []byte
digest []byte
height int64
}
// identity is a published Wesh identity bound to one gno address.
//
// payload holds the public rendezvous seed when committed is false, and
// H(seed ‖ salt) when it is true. head is the digest of the last accepted
// sigchain entry, which the next entry must chain to.
type identity struct {
name string
owner address
accountPK []byte
payload []byte
committed bool
revision int
displayName string
createdAt int64
updatedAt int64
history []rotation
devices []deviceEntry
head []byte
}
var (
// byName is the directory, keyed by handle so avl iteration is alphabetical.
byName avl.Tree
// byOwner maps a gno address to its handle: one identity per address.
byOwner avl.Tree
// byAccount maps a hex account key to its handle, so two handles can never
// claim the same Wesh account.
byAccount avl.Tree
)
// Register publishes an identity whose rendezvous seed is public.
//
// sigHex must be an ed25519 signature by the account private key over
// wesh.BindStatement(chainID, caller, accountPK, seed, 1). Revision 1 is fixed
// at registration so a signature captured from a later rotation cannot be
// replayed to re-register the name after it is released.
func Register(cur realm, name, accountPKHex, seedHex, displayName, sigHex string) {
if !cur.IsCurrent() {
panic("spoofed realm")
}
register(cur.Previous().Address(), name, accountPKHex, seedHex, displayName, sigHex, false)
}
// RegisterCommitted publishes an identity that keeps its rendezvous point off
// chain: commitmentHex is wesh.SeedCommitment(seed, salt), and the seed itself
// is shared out of band.
//
// The chain still attests the binding (this account key really did claim this
// commitment from this gno address), so a seed later disclosed privately can
// be checked against it. What it does not do is tell the world where the
// account listens.
func RegisterCommitted(cur realm, name, accountPKHex, commitmentHex, displayName, sigHex string) {
if !cur.IsCurrent() {
panic("spoofed realm")
}
register(cur.Previous().Address(), name, accountPKHex, commitmentHex, displayName, sigHex, true)
}
// register is shared by Register and RegisterCommitted. It takes the already
// resolved caller rather than a realm: a helper whose first parameter is
// `realm` would be a second crossing hop, and Previous() inside it would
// resolve to this realm rather than to the user who called in.
func register(caller address, name, accountPKHex, payloadHex, displayName, sigHex string, committed bool) {
name = normalizeName(name)
assertNameAvailable(name)
if byOwner.Has(caller.String()) {
panic("wesh: this address already owns an identity; release it first")
}
accountPK := mustAccountPK(accountPKHex)
if byAccount.Has(accountPKHex) {
panic("wesh: this account key is already published under another name")
}
payload := mustPayload(payloadHex, committed)
assertDisplayName(displayName)
if err := wesh.VerifyBind(runtime.ChainID(), caller.String(), accountPK, payload, 1, mustSig(sigHex)); err != nil {
panic("wesh: " + err.Error())
}
now := time.Now().Unix()
id := &identity{
name: name,
owner: caller,
accountPK: accountPK,
payload: payload,
committed: committed,
revision: 1,
displayName: displayName,
createdAt: now,
updatedAt: now,
history: []rotation{{revision: 1, payload: payload, height: runtime.ChainHeight()}},
head: wesh.GenesisDigest(),
}
byName.Set(name, id)
byOwner.Set(caller.String(), name)
byAccount.Set(accountPKHex, name)
}
// Rotate publishes a new seed (or commitment) for the caller's identity.
//
// This is the operation weshnet's ContactRequestResetReference has no
// counterpart for. There, resetting the seed silently invalidates every link
// ever shared. Here the new value is numbered and the old one stays in the
// history, so a holder of a stale link can see that it was superseded and when.
//
// The signature must be over revision+1, which is what stops a superseded
// binding being replayed to roll a rotation back.
func Rotate(cur realm, payloadHex, sigHex string) {
if !cur.IsCurrent() {
panic("spoofed realm")
}
id := mustOwnIdentity(cur.Previous().Address())
payload := mustPayload(payloadHex, id.committed)
if string(payload) == string(id.payload) {
panic("wesh: the new value is identical to the current one")
}
next := id.revision + 1
if err := wesh.VerifyBind(runtime.ChainID(), id.owner.String(), id.accountPK, payload, next, mustSig(sigHex)); err != nil {
panic("wesh: " + err.Error())
}
id.revision = next
id.payload = payload
id.updatedAt = time.Now().Unix()
id.history = append(id.history, rotation{revision: next, payload: payload, height: runtime.ChainHeight()})
if len(id.history) > MaxRotations {
id.history = id.history[len(id.history)-MaxRotations:]
}
}
// AppendDevice adds one entry to the caller's device sigchain.
//
// prevHex must be the digest of the current head (all zeros for the first
// entry), and the signature must cover the whole statement including the
// sequence number and that digest. Chaining every entry to its predecessor is
// what stops the log being reordered or having an entry quietly dropped: any
// gap changes every digest after it.
//
// op is "add" or "revoke". Adding a device that is already active, or revoking
// one that is not, is refused: an append-only log is only useful if its entries
// are meaningful.
func AppendDevice(cur realm, prevHex, op, devicePKHex, sigHex string) {
if !cur.IsCurrent() {
panic("spoofed realm")
}
id := mustOwnIdentity(cur.Previous().Address())
if len(id.devices) >= MaxDevices {
panic("wesh: device sigchain is full")
}
prev, err := wesh.DecodeCommitment(prevHex)
if err != nil {
panic("wesh: previous digest: " + err.Error())
}
if string(prev) != string(id.head) {
panic("wesh: previous digest does not match the sigchain head " + hex.EncodeToString(id.head))
}
devicePK, err := wesh.DecodeDevicePK(devicePKHex)
if err != nil {
panic("wesh: device key: " + err.Error())
}
active := deviceIsActive(id, devicePK)
switch op {
case wesh.OpAdd:
if active {
panic("wesh: device is already active")
}
case wesh.OpRevoke:
if !active {
panic("wesh: device is not active, nothing to revoke")
}
default:
panic("wesh: operation must be add or revoke")
}
seq := len(id.devices)
digest, err := wesh.VerifyDevice(runtime.ChainID(), id.accountPK, seq, prev, op, devicePK, mustSig(sigHex))
if err != nil {
panic("wesh: " + err.Error())
}
id.devices = append(id.devices, deviceEntry{
seq: seq,
op: op,
devicePK: devicePK,
digest: digest,
height: runtime.ChainHeight(),
})
id.head = digest
id.updatedAt = time.Now().Unix()
}
// SetDisplayName updates the identity's free-form label.
//
// It carries no signature because it authenticates nothing: the display name
// is app metadata, and berty's own link format keeps it outside the signed
// payload for the same reason. Only the owning address may change it.
func SetDisplayName(cur realm, displayName string) {
if !cur.IsCurrent() {
panic("spoofed realm")
}
assertDisplayName(displayName)
id := mustOwnIdentity(cur.Previous().Address())
id.displayName = displayName
id.updatedAt = time.Now().Unix()
}
// Release removes the caller's identity and frees its name and account key.
//
// The sigchain goes with it. That is the honest behaviour: a directory entry
// is a live claim, not an archive, and keeping a dangling roster for a name
// somebody else can now take would be worse than keeping nothing.
func Release(cur realm) {
if !cur.IsCurrent() {
panic("spoofed realm")
}
caller := cur.Previous().Address()
id := mustOwnIdentity(caller)
byName.Remove(id.name)
byOwner.Remove(caller.String())
byAccount.Remove(hex.EncodeToString(id.accountPK))
}
// --- read-only API, for gnoweb and for other realms ---
// Resolve returns the account key and current payload of a name, both hex, and
// whether the payload is a commitment rather than a seed. ok is false when the
// name is not registered.
func Resolve(name string) (accountPKHex, payloadHex string, committed, ok bool) {
id := lookup(name)
if id == nil {
return "", "", false, false
}
return hex.EncodeToString(id.accountPK), hex.EncodeToString(id.payload), id.committed, true
}
// Link returns the shareable Berty web link for a name, or "" when the name is
// unknown or its rendezvous point is committed rather than published.
func Link(name string) string {
id := lookup(name)
if id == nil || id.committed {
return ""
}
link, err := contactOf(id).WebLink()
if err != nil {
return ""
}
return link
}
// RendezvousPointAt returns the hex rendezvous point the named account
// announces on during the rotation period containing unixSec, or "" when the
// name is unknown or committed.
//
// This is what makes a directory entry checkable rather than merely claimed:
// anyone can compare it against the DHT without trusting this realm.
func RendezvousPointAt(name string, unixSec int64) string {
id := lookup(name)
if id == nil || id.committed {
return ""
}
point, err := contactOf(id).RendezvousPointAt(unixSec, wesh.DefaultRotationInterval)
if err != nil {
return ""
}
return hex.EncodeToString(point)
}
// DeviceStatus reports "active", "revoked" or "unknown" for a device under a
// name. "unknown" also covers an unregistered name: a caller must not be able
// to tell those apart by status alone.
func DeviceStatus(name, devicePKHex string) string {
id := lookup(name)
if id == nil {
return "unknown"
}
devicePK, err := wesh.DecodeDevicePK(devicePKHex)
if err != nil {
return "unknown"
}
if !deviceSeen(id, devicePK) {
return "unknown"
}
if deviceIsActive(id, devicePK) {
return "active"
}
return "revoked"
}
// SigchainHead returns the hex digest the next sigchain entry must chain to,
// or "" when the name is unknown. A client builds its next statement from this.
func SigchainHead(name string) string {
id := lookup(name)
if id == nil {
return ""
}
return hex.EncodeToString(id.head)
}
// NameOf returns the handle owned by an address, or "".
func NameOf(owner address) string {
v := byOwner.Get(owner.String())
if v == nil {
return ""
}
return v.(string)
}
// Count returns the number of registered identities.
func Count() int { return byName.Size() }
// --- helpers ---
func lookup(name string) *identity {
v := byName.Get(normalizeName(name))
if v == nil {
return nil
}
return v.(*identity)
}
func contactOf(id *identity) wesh.Contact {
return wesh.Contact{
AccountPK: id.accountPK,
Seed: id.payload,
DisplayName: id.displayName,
}
}
func deviceIsActive(id *identity, devicePK []byte) bool {
active := false
for _, e := range id.devices {
if string(e.devicePK) != string(devicePK) {
continue
}
active = e.op == wesh.OpAdd
}
return active
}
func deviceSeen(id *identity, devicePK []byte) bool {
for _, e := range id.devices {
if string(e.devicePK) == string(devicePK) {
return true
}
}
return false
}
func mustOwnIdentity(caller address) *identity {
v := byOwner.Get(caller.String())
if v == nil {
panic("wesh: no identity registered for this address")
}
return lookup(v.(string))
}
func mustAccountPK(s string) []byte {
pk, err := wesh.DecodeAccountPK(s)
if err != nil {
panic("wesh: account key: " + err.Error())
}
return pk
}
func mustPayload(s string, committed bool) []byte {
if committed {
c, err := wesh.DecodeCommitment(s)
if err != nil {
panic("wesh: commitment: " + err.Error())
}
return c
}
seed, err := wesh.DecodeSeed(s)
if err != nil {
panic("wesh: seed: " + err.Error())
}
return seed
}
func mustSig(s string) []byte {
sig, err := hex.DecodeString(s)
if err != nil || len(sig) != 64 {
panic("wesh: signature must be 64 hex-encoded bytes")
}
return sig
}
func assertDisplayName(s string) {
if len(s) > wesh.MaxDisplayNameLen {
panic("wesh: display name is too long")
}
}
func assertNameAvailable(name string) {
if len(name) < MinNameLen || len(name) > MaxNameLen {
panic("wesh: name must be between 3 and 32 characters")
}
for i := 0; i < len(name); i++ {
c := name[i]
ok := (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_'
if !ok {
panic("wesh: name may only contain a-z, 0-9, '-' and '_'")
}
}
if byName.Has(name) {
panic("wesh: name is already taken")
}
}
// normalizeName lowercases a handle so lookups are case-insensitive and two
// handles cannot differ only by case.
func normalizeName(name string) string {
return strings.ToLower(strings.TrimSpace(name))
}
wesh_test.gno
package wesh
import (
"testing"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/wesh/v0"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// Signature fixtures. Each was produced with Go's crypto/ed25519 over the exact
// statement wesh.BindStatement / wesh.DeviceStatement builds, for chain-id
// "dev" (what the test VM reports) and the address named in the constant.
// Regenerating them means re-signing: that is the point, since the whole
// scheme rests on the chain being unable to accept anything unsigned.
const (
// alice, g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh
aliceAccountPKHex = "2152f8d19b791d24453242e15f2eab6cb7cffa7b6a5ed30097960e069881db12"
aliceSeed1Hex = "abababababababababababababababababababababababababababababababab"
aliceSeed2Hex = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
aliceCommitHex = "c9744f547763321102debcf355a5652208604d53dba6c77e978ee8077ceb472a"
aliceBind1Sig = "1279475fc9f7423d13e3eeea96a1714754f74c77abbb5859ba899bd3f820f59d" +
"2b0a16f2f6c436cdafd8e20b0d709a5e247a5bbbf4b34df38c1405aba3645905"
aliceBind2Sig = "e915b181109936b1ef77ea8e31e512b56ac63a7e690c382e3613df3ef50472ba" +
"23233442d789c22ad9401cb882f57be737a67e24db207a9856186eda61fdc108"
aliceBind3Sig = "d04f8733f564ee45f141fb71ecb049078a23215b29a14dafeed6c1ced91511ec" +
"47b8c3de120f0d23c534c7387e3273e86b50787280ff38a7f1bd31c23ab35f03"
aliceCommitBindSig = "d467d806145c228ff7b784658f06f8f05e7fa19354ae0bad3a69b40a1a4cf518" +
"ecb3a679674705017c6dfa1bf0bac3e1ec67a4f417c18a80faf77062b8c1e100"
// signed by alice's key but naming bob's gno address
aliceBindForBobSig = "7bac691e9da577c6474af269b690a7415f07c4a8e4df486deccf824b41061735" +
"01cd22af6f1b9654603a866a3a46942ec020714226b01105700eab84cfc08700"
// bob, g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu
bobAccountPKHex = "332ebe8d27cb7323b3a401c1c13b5dd64bccc0e10ecda1c2b5d11a03779a85e5"
bobBind1Sig = "69653e1bef41150eed026b355d5ee9837455e3432003ca19102075078305fdbe" +
"b440eedb421056a0e62a182a406cb3394c1225de768dcd114f9d0b9b3501b90f"
// alice's device sigchain: add dev1, add dev2, revoke dev1
dev1Hex = "0707070707070707070707070707070707070707070707070707070707070707"
dev2Hex = "0909090909090909090909090909090909090909090909090909090909090909"
devAdd1Sig = "259abde508b8880dd1f53b236d93b08aa1c7511c4308c2b16da2520d5f553a50" +
"67c24876299b6c3e4d9fb88e043dec1978f8d9328f7ac13d80bfdab536893507"
devAdd1Digest = "bc51799b5d012dc7ce806b4c63474b1e2db515e7d1622ecd5900b23e1d6a9519"
devAdd2Sig = "4799b276bf9b713d84855670198a86de8d38bc2644349a554fe0d4dab5fbea9b" +
"7e90aecfe9b7da74345e61f5016361e92e7c0959fe09665a1f20f604015bea00"
devAdd2Digest = "b0da03f83e5349e92bc524714862daa850750f756ca6fd47264333fbf2175c15"
devRevoke1Sig = "47433475efd00ed87769e7bb748a5af9be77cde56817ea9a1ddd9288533e2bf9" +
"b783d85a025a632466ce8dcf637047c932c9d1a15131187213e1ae354e22df02"
devRevoke1Digest = "ef0c1d0614420c7d660f8416b18651206118e49e8f46ac0360bef61ae6b9100d"
// signed for sequence 5 while the head is still at sequence 1
devWrongSeqSig = "c65d9c48c441bf36dcf01c8c0e46fe73a9f7f8d8edffb07bd05f9ca4a8f875bc" +
"6de7ebe30c1d5ae785fde8bfe7b48705605a6c247a62def9b03d37fb62f6f809"
genesisDigestHex = "0000000000000000000000000000000000000000000000000000000000000000"
)
// reset clears realm globals: gno subtests do not roll them back.
func reset() {
byName = avl.Tree{}
byOwner = avl.Tree{}
byAccount = avl.Tree{}
}
// Two gno-specific rules shape every test below, and both cost a red run to
// learn:
//
// - testing.SetRealm is scoped to the frame that calls it, so it has to be
// called in the test body, not in a setUpAlice() helper.
// - a helper whose first parameter is `realm` is itself a crossing function,
// so routing a call through one makes THIS realm the Previous() the
// callee sees, not the user. Crossing calls stay inline.
//
// Together they mean the two setup lines are repeated rather than factored.
func aliceAddr() address { return testutils.TestAddress("alice") }
func bobAddr() address { return testutils.TestAddress("bob") }
func TestRegister(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
Register(cross(cur), "alice", aliceAccountPKHex, aliceSeed1Hex, "Alice", aliceBind1Sig)
uassert.Equal(t, 1, Count())
pk, payload, committed, ok := Resolve("alice")
uassert.True(t, ok, "the name resolves")
uassert.Equal(t, aliceAccountPKHex, pk)
uassert.Equal(t, aliceSeed1Hex, payload)
uassert.False(t, committed, "the seed is published, not committed")
uassert.Equal(t, "alice", NameOf(aliceAddr()))
}
// TestRegisterEmitsARealBertyLink is the payoff: the realm hands back a link a
// Berty client can actually open.
func TestRegisterEmitsARealBertyLink(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
Register(cross(cur), "alice", aliceAccountPKHex, aliceSeed1Hex, "Alice", aliceBind1Sig)
uassert.Equal(t,
"https://berty.tech/id#contact/oZBLFpzghxrATkepWvDPNX9pHYqi6BWgP45xGWhqxcwmqN2bnMMbU7UcwUuTaCcDyUvMjmWRMDWcP96bXAndcjNiAZ1Vz9X/name=Alice",
Link("alice"))
// and the rendezvous point anyone can check against the DHT
uassert.Equal(t,
"aad2926c39dacabaabbbde48522d043557c8945b6a2dc7b08499c112c72587da",
RendezvousPointAt("alice", 1789171200))
}
func TestRegisterIsCaseInsensitive(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
Register(cross(cur), " ALICE ", aliceAccountPKHex, aliceSeed1Hex, "", aliceBind1Sig)
_, _, _, ok := Resolve("Alice")
uassert.True(t, ok, "lookup is case-insensitive")
uassert.Equal(t, "alice", NameOf(aliceAddr()), "the handle is stored lowercased")
}
// TestRegisterRejectsAnUnsignedClaim is the attack the binding signature
// exists to stop: bob publishing alice's account key next to a seed he
// controls, and harvesting the contact requests that follow.
func TestRegisterRejectsAnotherAccountsKey(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(bobAddr()))
uassert.AbortsContains(t, cur, "signature does not verify", func() {
Register(cross(cur), "notalice", aliceAccountPKHex, aliceSeed1Hex, "", aliceBind1Sig)
}, "alice's signature does not authorise bob's address")
}
// TestRegisterRejectsAReplayedBinding: the statement names the gno address, so
// a signature harvested from alice's transaction is useless to anyone else.
func TestRegisterRejectsAReplayedBinding(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
uassert.AbortsContains(t, cur, "signature does not verify", func() {
// this signature names bob's address, alice is calling
Register(cross(cur), "alice", aliceAccountPKHex, aliceSeed1Hex, "", aliceBindForBobSig)
})
}
func TestRegisterRejectsDuplicates(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
Register(cross(cur), "alice", aliceAccountPKHex, aliceSeed1Hex, "Alice", aliceBind1Sig)
testing.SetRealm(testing.NewUserRealm(bobAddr()))
uassert.AbortsContains(t, cur, "name is already taken", func() {
Register(cross(cur), "alice", bobAccountPKHex, aliceSeed1Hex, "", bobBind1Sig)
})
uassert.AbortsContains(t, cur, "already published under another name", func() {
Register(cross(cur), "alice2", aliceAccountPKHex, aliceSeed1Hex, "", aliceBind1Sig)
}, "one Wesh account, one directory entry")
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
uassert.AbortsContains(t, cur, "already owns an identity", func() {
Register(cross(cur), "alice2", aliceAccountPKHex, aliceSeed1Hex, "", aliceBind1Sig)
})
}
func TestRegisterValidatesInput(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
uassert.AbortsContains(t, cur, "between 3 and 32", func() {
Register(cross(cur), "ab", aliceAccountPKHex, aliceSeed1Hex, "", aliceBind1Sig)
})
uassert.AbortsContains(t, cur, "a-z, 0-9", func() {
Register(cross(cur), "al!ce", aliceAccountPKHex, aliceSeed1Hex, "", aliceBind1Sig)
})
uassert.AbortsContains(t, cur, "account key", func() {
Register(cross(cur), "alice", "abcd", aliceSeed1Hex, "", aliceBind1Sig)
})
uassert.AbortsContains(t, cur, "seed", func() {
Register(cross(cur), "alice", aliceAccountPKHex, "abcd", "", aliceBind1Sig)
})
uassert.AbortsContains(t, cur, "signature must be 64", func() {
Register(cross(cur), "alice", aliceAccountPKHex, aliceSeed1Hex, "", "00")
})
}
func TestRegisterCommitted(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
RegisterCommitted(cross(cur), "alice", aliceAccountPKHex, aliceCommitHex, "", aliceCommitBindSig)
_, payload, committed, ok := Resolve("alice")
uassert.True(t, ok)
uassert.True(t, committed)
uassert.Equal(t, aliceCommitHex, payload)
uassert.Equal(t, "", Link("alice"), "a committed identity publishes no link")
uassert.Equal(t, "", RendezvousPointAt("alice", 1789171200),
"a committed identity does not disclose its rendezvous point")
}
// TestCommitmentOpensWithTheOutOfBandSeed: the chain attests the binding, and
// the seed handed over privately checks against it.
func TestCommitmentOpensWithTheOutOfBandSeed(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
RegisterCommitted(cross(cur), "alice", aliceAccountPKHex, aliceCommitHex, "", aliceCommitBindSig)
_, payload, _, _ := Resolve("alice")
commitment, err := wesh.DecodeCommitment(payload)
uassert.NoError(t, err)
seed, err := wesh.DecodeSeed(aliceSeed1Hex)
uassert.NoError(t, err)
uassert.True(t, wesh.OpenCommitment(commitment, seed, []byte("a-16-byte-salt!!")),
"the seed shared out of band matches what the chain attested")
uassert.False(t, wesh.OpenCommitment(commitment, seed, []byte("wrong-salt!!!!!!")))
}
func TestRotate(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
Register(cross(cur), "alice", aliceAccountPKHex, aliceSeed1Hex, "Alice", aliceBind1Sig)
Rotate(cross(cur), aliceSeed2Hex, aliceBind2Sig)
_, payload, _, _ := Resolve("alice")
uassert.Equal(t, aliceSeed2Hex, payload)
id := lookup("alice")
uassert.Equal(t, 2, id.revision)
uassert.Equal(t, 2, len(id.history), "the superseded seed is kept so a stale link is recognisable")
uassert.Equal(t, aliceSeed1Hex, hexOf(id.history[0].payload))
}
// TestRotateRejectsAReplayedRevision is what a monotonic revision buys: an old
// binding cannot be replayed to roll a rotation back.
func TestRotateRejectsAReplayedRevision(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
Register(cross(cur), "alice", aliceAccountPKHex, aliceSeed1Hex, "Alice", aliceBind1Sig)
Rotate(cross(cur), aliceSeed2Hex, aliceBind2Sig)
uassert.AbortsContains(t, cur, "signature does not verify", func() {
Rotate(cross(cur), aliceSeed1Hex, aliceBind1Sig)
}, "the revision-1 signature is dead once revision 2 exists")
// the correctly-signed revision 3 does go back to the first seed
Rotate(cross(cur), aliceSeed1Hex, aliceBind3Sig)
uassert.Equal(t, 3, lookup("alice").revision)
}
func TestRotateRejectsANoOp(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
Register(cross(cur), "alice", aliceAccountPKHex, aliceSeed1Hex, "Alice", aliceBind1Sig)
uassert.AbortsContains(t, cur, "identical to the current one", func() {
Rotate(cross(cur), aliceSeed1Hex, aliceBind2Sig)
})
}
func TestRotateRequiresAnIdentity(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(bobAddr()))
uassert.AbortsContains(t, cur, "no identity registered", func() {
Rotate(cross(cur), aliceSeed2Hex, aliceBind2Sig)
})
}
// TestDeviceSigchain walks the sequence weshnet itself cannot express:
// add a device, add a second, then revoke the first.
func TestDeviceSigchain(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
Register(cross(cur), "alice", aliceAccountPKHex, aliceSeed1Hex, "Alice", aliceBind1Sig)
uassert.Equal(t, genesisDigestHex, SigchainHead("alice"), "an empty chain starts at the genesis digest")
uassert.Equal(t, "unknown", DeviceStatus("alice", dev1Hex))
AppendDevice(cross(cur), genesisDigestHex, wesh.OpAdd, dev1Hex, devAdd1Sig)
uassert.Equal(t, devAdd1Digest, SigchainHead("alice"))
uassert.Equal(t, "active", DeviceStatus("alice", dev1Hex))
AppendDevice(cross(cur), devAdd1Digest, wesh.OpAdd, dev2Hex, devAdd2Sig)
uassert.Equal(t, devAdd2Digest, SigchainHead("alice"))
AppendDevice(cross(cur), devAdd2Digest, wesh.OpRevoke, dev1Hex, devRevoke1Sig)
uassert.Equal(t, devRevoke1Digest, SigchainHead("alice"))
uassert.Equal(t, "revoked", DeviceStatus("alice", dev1Hex), "revocation is public, ordered and attributable")
uassert.Equal(t, "active", DeviceStatus("alice", dev2Hex))
uassert.Equal(t, 1, activeDevices(lookup("alice")))
}
// TestDeviceSigchainRejectsAForkedChain: every entry chains to the digest of
// the one before it, so the log cannot be reordered or have an entry dropped.
func TestDeviceSigchainRejectsAForkedChain(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
Register(cross(cur), "alice", aliceAccountPKHex, aliceSeed1Hex, "Alice", aliceBind1Sig)
AppendDevice(cross(cur), genesisDigestHex, wesh.OpAdd, dev1Hex, devAdd1Sig)
uassert.AbortsContains(t, cur, "does not match the sigchain head", func() {
AppendDevice(cross(cur), genesisDigestHex, wesh.OpAdd, dev2Hex, devAdd2Sig)
}, "the second entry must chain to the first")
uassert.AbortsContains(t, cur, "signature does not verify", func() {
AppendDevice(cross(cur), devAdd1Digest, wesh.OpAdd, dev2Hex, devWrongSeqSig)
}, "a signature made for another sequence number is not accepted at this one")
}
func TestDeviceSigchainRejectsMeaninglessOps(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
Register(cross(cur), "alice", aliceAccountPKHex, aliceSeed1Hex, "Alice", aliceBind1Sig)
AppendDevice(cross(cur), genesisDigestHex, wesh.OpAdd, dev1Hex, devAdd1Sig)
uassert.AbortsContains(t, cur, "already active", func() {
AppendDevice(cross(cur), devAdd1Digest, wesh.OpAdd, dev1Hex, devAdd1Sig)
})
uassert.AbortsContains(t, cur, "not active, nothing to revoke", func() {
AppendDevice(cross(cur), devAdd1Digest, wesh.OpRevoke, dev2Hex, devAdd2Sig)
})
uassert.AbortsContains(t, cur, "add or revoke", func() {
AppendDevice(cross(cur), devAdd1Digest, "delete", dev2Hex, devAdd2Sig)
})
uassert.AbortsContains(t, cur, "device key", func() {
AppendDevice(cross(cur), devAdd1Digest, wesh.OpAdd, "abcd", devAdd2Sig)
})
}
func TestSetDisplayName(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
Register(cross(cur), "alice", aliceAccountPKHex, aliceSeed1Hex, "Alice", aliceBind1Sig)
SetDisplayName(cross(cur), "Alice, support line")
uassert.Equal(t, "Alice, support line", lookup("alice").displayName)
testing.SetRealm(testing.NewUserRealm(bobAddr()))
uassert.AbortsContains(t, cur, "no identity registered", func() {
SetDisplayName(cross(cur), "hijacked")
})
}
func TestRelease(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(aliceAddr()))
Register(cross(cur), "alice", aliceAccountPKHex, aliceSeed1Hex, "Alice", aliceBind1Sig)
Release(cross(cur))
uassert.Equal(t, 0, Count())
_, _, _, ok := Resolve("alice")
uassert.False(t, ok)
uassert.Equal(t, "", NameOf(aliceAddr()))
// the name and the account key are both free again
testing.SetRealm(testing.NewUserRealm(bobAddr()))
Register(cross(cur), "alice", bobAccountPKHex, aliceSeed1Hex, "", bobBind1Sig)
uassert.Equal(t, 1, Count())
}
func TestReadersOnUnknownNames(cur realm, t *testing.T) {
reset()
uassert.Equal(t, "", Link("nope"))
uassert.Equal(t, "", RendezvousPointAt("nope", 0))
uassert.Equal(t, "", SigchainHead("nope"))
uassert.Equal(t, "unknown", DeviceStatus("nope", dev1Hex))
uassert.Equal(t, "unknown", DeviceStatus("nope", "not-hex"))
_, _, _, ok := Resolve("nope")
uassert.False(t, ok)
}
func hexOf(b []byte) string {
const digits = "0123456789abcdef"
out := make([]byte, 0, len(b)*2)
for _, c := range b {
out = append(out, digits[c>>4], digits[c&0x0f])
}
return string(out)
}