entviz

package module
v0.15.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 20, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

README

entviz-go

CI Release Go Reference Spec License

Go implementation of entviz (spec v15) — visualize high-entropy values as comparable SVG diagrams.

Part of the entviz family

entviz is defined by a language-independent specification, with conformant implementations in Python (reference), Rust, TypeScript/JS + React, Java, and Go — all passing the same shared conformance corpus. See the directory of implementations, browse the spec & docs site, or try it live in the browser.

Status: certified against the v15 conformance corpus ✅

A full, self-contained implementation that passes the shared conformance corpus at Tier A (render model) + Tier B (canonical raster) for every render vector, rejects every error vector, and satisfies every invariant pair (54/54). What's here:

  • core.go — the deterministic shared core: alphabets, tokenization + 24-bit quant extension, the SHA-512 fingerprint, ftok median/quartile selection, the Oklab color rules + weighted-RGB edge selection, and grid selection.
  • entropy.go — the format-specific parsers (hex, UUID, Ethereum w/ EIP-55, ULID, base58 / bech32 / base32 chains, CESR, LEI, snowflake, SWHID / gitoid semantic-prefix fold, IPFS CID, SSH, …) + the disproof-based alphabet detection and large-input (head / fingerprint-middle / tail) tokenization.
  • keccak.go — vendored Keccak-256 for EIP-55 checksum validation.
  • pipeline.go — the SVG renderer: geometry, 24-box surround, fingerprint-edge cells, ellipse overlay, color bar + markers, blank-cell map, quartile marks, labels, borders — emitting the normative data-* profile.
  • cmd/entviz-conformance — the conformance CLI (the stdin→stdout contract in the entviz repo's compliance/README.md).

The module depends only on the Go standard library.

How to consume

go get github.com/dhh1128/entviz-go
package main

import (
	"fmt"
	"os"

	entviz "github.com/dhh1128/entviz-go"
)

func main() {
	// Render(entropy, targetAR, fontSizePt, note) -> (svg, error).
	// note is *string; pass nil for no note.
	svg, err := entviz.Render("a1b2c3d4e5f6a7b8", 1.0, 12.0, nil)
	if err != nil {
		fmt.Fprintln(os.Stderr, "render rejected:", err)
		os.Exit(1)
	}
	fmt.Print(svg)
}

Render rejects out-of-range parameters (font size must be 6–30 pt, aspect ratio 0.01–100), notes that are not printable ASCII (U+0020–U+007E) or longer than 10 characters, and Ethereum addresses whose EIP-55 mixed-case checksum is invalid (the error names the first mismatched-case position).

Characterize returns the structured entropy characterization — the same eight fields entviz emits as data-* attributes on the rendered SVG:

ch, err := entviz.Characterize("550e8400-e29b-41d4-a716-446655440000")
// ch.Scheme -> *"uuid", ch.Role -> *"identifier", ch.SizeBits -> 128
// ch.QualifiersJSON() / ch.PartsJSON() give the compact-JSON forms.

For embedding entviz across all five languages, see the Developer Integration Guide.

Build + test

gofmt -l .                                  # must print nothing
go vet ./...
go test ./... -race -cover                  # unit tests + corpus invariants
go build ./...

Conformance against the golden corpus (requires a checkout of the entviz reference repo as a sibling ../entviz and a Python venv with lxml):

go build -o /tmp/entviz-go-conformance ./cmd/entviz-conformance

# from a checkout of the entviz reference repo (sibling ../entviz):
PYTHONPATH=src:. python -m compliance.runner \
  --impl-cmd '/tmp/entviz-go-conformance' --tiers AB
# -> 54/54 vectors passed

Spec compliance & versioning

The module version encodes the entviz spec level it is compliant with:

0.<spec-major>.x — e.g. 0.10.x ⇒ compliant with entviz spec v10 (the same convention the Python reference and entviz-rs use, where spec v10 ↔ 0.10.0).

A spec bump (v10 → v11) is a minor release here (0.10.x0.11.0); a patch is a module-only change within a spec version. The canonical spec level is the SpecVersion constant in core.go; the per-impl stamp emitted as data-entviz-lib is LibVersion.

CI surfaces spec drift: the conformance job checks out the public entviz reference, compares its SPEC_VERSION to this module's, and runs the Tier-A conformance suite. When the reference spec is ahead of this module it warns loudly (without blocking unrelated PRs); when the versions match (or this module is ahead) conformance is a hard gate.

Releasing

Go has no central package registry to push to — pkg.go.dev indexes the module straight from a pushed Git tag — so a "release" here is creating the version tag and the GitHub release.

Releases are human-run (agents must not push tags). From a clean, in-sync main, bump the LibVersion constant in core.go, commit, then tag and push:

git tag v0.10.0
git push origin v0.10.0

The tag triggers .github/workflows/release.yml, which re-runs the full gate set (gofmt + vet + go test -race + Tier-A conformance), verifies the tag matches LibVersion, and creates the GitHub release. pkg.go.dev then indexes the new tag automatically.

Sister projects

  • entviz — the Python reference implementation and the canonical spec (docs/spec.md), plus the gallery and the shared conformance corpus this module is certified against.
  • entviz-rs — the certified Rust port (this module mirrors it line for line).
  • entviz-js — the certified TypeScript/JavaScript port.

License

Apache License 2.0. See also NOTICE.

Documentation

Overview

Package entviz renders high-entropy values as comparable SVG fingerprints. It is a Go port of the certified reference implementation; see https://github.com/dhh1128/entviz for the spec.

The deterministic shared core lives here: alphabets, tokenization + 24-bit quant extension, the SHA-512 fingerprint, ftok median/quartile selection, the Oklab color rules + weighted-RGB edge selection, and grid selection. The format-specific parsers live in entropy.go and the SVG renderer in pipeline.go.

Index

Constants

View Source
const LibVersion = "0.15.1"

LibVersion is this Go module's own version stamp. It is per-impl and is not compared by the conformance checker (only data-entviz-version is).

View Source
const (
	MARGIN = 1.0
)
View Source
const SpecVersion = "v15"

SpecVersion is the entviz spec level this library implements.

Variables

View Source
var (
	HEX = Alphabet{
		Name:        "hex",
		Chars:       "0123456789ABCDEF",
		BitsPerChar: 4,
	}
	BASE64URL = Alphabet{
		Name:        "base64url",
		Chars:       "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
		BitsPerChar: 6,
	}
	BASE58 = Alphabet{
		Name:        "base58",
		Chars:       "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",
		BitsPerChar: 6,
	}
	BASE64 = Alphabet{
		Name:        "base64",
		Chars:       "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
		BitsPerChar: 6,
	}
	BASE32 = Alphabet{
		Name:        "base32",
		Chars:       "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
		BitsPerChar: 5,
	}
	BECH32 = Alphabet{
		Name:        "bech32",
		Chars:       "qpzry9x8gf2tvdw0s3jn54khce6mua7l",
		BitsPerChar: 5,
	}
	CROCKFORD32 = Alphabet{
		Name:        "crockford32",
		Chars:       "0123456789ABCDEFGHJKMNPQRSTVWXYZ",
		BitsPerChar: 5,
	}
	BASE36 = Alphabet{
		Name:        "base36",
		Chars:       "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",
		BitsPerChar: 6,
	}
	DECIMAL = Alphabet{
		Name:        "decimal",
		Chars:       "0123456789",
		BitsPerChar: 4,
	}
)

Canonical alphabet constants used across the core and parsers.

View Source
var MiddleDomainTag = []byte("entviz/fingerprint-middle/v6\x00")

MiddleDomainTag is the frozen domain-separation constant for the second digest. The trailing NUL is included; the v6 here is the *construction* version (frozen), NOT the spec version — see the spec's large-input section.

View Source
var PossibleEdgeColors = [5]string{"#ffffff", "#e7be00", "#ff3f2f", "#2f3fbf", "#000000"}

PossibleEdgeColors is the fixed palette; indices 0-3 are background candidates, black (index 4) is always an edge color.

Functions

func ClosestPaletteColor

func ClosestPaletteColor(target string, palette []string) string

ClosestPaletteColor returns the palette entry with minimum weighted distance.

func ComputeFingerprint

func ComputeFingerprint(core string) [64]byte

ComputeFingerprint returns the SHA-512 digest of the core text bytes.

func NucleusColors

func NucleusColors(quant uint32) (string, string)

NucleusColors returns (bgHex, fgHex). Red is the low byte of the quant.

func OklabLightness

func OklabLightness(r, g, b uint8) float64

OklabLightness returns the Oklab L of an sRGB color.

func Render

func Render(entropyText string, targetAR, fontSizePt float64, note *string) (string, error)

Render renders entropy as an entviz SVG string.

func SecondDigest

func SecondDigest(core string) [64]byte

SecondDigest returns SHA-512(MiddleDomainTag ‖ core). Computed for every input: it drives the two color-bar markers (and the middle cells on large inputs).

func WeightedRGBDistance

func WeightedRGBDistance(c1, c2 string) float64

WeightedRGBDistance is the spec's cheap CIELAB ΔE stand-in for edge selection.

Types

type Alphabet

type Alphabet struct {
	Name        string
	Chars       string
	BitsPerChar uint
}

Alphabet describes a character set and its tokenization density.

type Characterization added in v0.15.1

type Characterization struct {
	Encoding    string
	Scheme      *string
	Role        *string
	Qualifiers  *OrderedMap
	SizeBasis   string
	SizeBits    int
	Parts       []Part
	EntropyType string
}

Characterization is the 8-field structured entropy characterization. Scheme and Role use pointers so a nil pointer serializes to the empty string (data-scheme/data-role) and JSON null semantics; every other field is always present.

func Characterize added in v0.15.1

func Characterize(entropy string) (*Characterization, error)

Characterize characterizes an entropy string into the structured model. Never errors for an in-range input: an unrecognized input falls back to the UTF-8 -> base64url path (scheme=nil, role=nil, size_basis="utf8", size measured over the ORIGINAL input bytes). A hard parse rejection (EIP-55) is surfaced via the error, matching Parse.

func (*Characterization) PartsJSON added in v0.15.1

func (c *Characterization) PartsJSON() string

PartsJSON returns the compact JSON array for data-parts, no spaces: [{"text":"...","bind":"core"}]. Insertion order matches reading order.

func (*Characterization) QualifiersJSON added in v0.15.1

func (c *Characterization) QualifiersJSON() string

QualifiersJSON returns the compact JSON object for data-qualifiers, keys in insertion order, no spaces: {"algorithm":"Blake3-256"}. Empty map -> {}.

func (*Characterization) RenderLabel added in v0.15.1

func (c *Characterization) RenderLabel(truncated bool, suffix, note string, lineChars int) (string, string)

RenderLabel projects the characterization into the (top, bottom) label strips. Pure function of the eight fields plus presentation facts the fields don't carry: whether the input was >512-bit truncated, the bound suffix checksum, the out-of-band user note, and the monospace lineChars budget the grid leaves for the top strip (used only to truncate the elastic prefix slot; lineChars < 0 = do not truncate).

top = [+hash ]PRIMARY[, MOD]...[, SIZE][, PREFIX] (", " joined, no trailing ':'). bottom = ...<suffix> then " (<note>)", "" when neither present.

func (*Characterization) RoleAttr added in v0.15.1

func (c *Characterization) RoleAttr() string

func (*Characterization) SchemeAttr added in v0.15.1

func (c *Characterization) SchemeAttr() string

SchemeAttr / RoleAttr return the empty string for a nil scheme/role.

type ChecksumError added in v0.15.1

type ChecksumError struct {
	Kind    string // e.g. "Bitcoin legacy", "bech32", "Bitcoin Cash", "LEI"
	Address string
}

ChecksumError is a hard rejection: a structure that clearly matches a scheme (right prefix / length / reserved bytes) but whose bound checksum — surfaced in the label — does not verify. Covers base58check (BTC/LTC legacy), bech32 (BTC segwit, LTC, generic cosmos), CashAddr (BCH), and LEI MOD 97-10. A bound checksum is shown, so it must be verified; a mismatch rejects rather than rendering an invalid address. Mirrors Base58CheckError / Bech32ChecksumError / LEIChecksumError in src/entviz/entropy.py.

func (*ChecksumError) Error added in v0.15.1

func (e *ChecksumError) Error() string

type Eip55Error

type Eip55Error struct {
	Position int
}

Eip55Error is a hard rejection: an EIP-55 mixed-case checksum mismatch. The Position is the 0-based index (within the 40-hex body) of the first digit whose case disagrees with the canonical case.

func (*Eip55Error) Error

func (e *Eip55Error) Error() string

type Grid

type Grid struct {
	Cols       int
	Rows       int
	TokenCount int
}

Grid is the chosen layout.

func ChooseGrid

func ChooseGrid(tokenCount int, targetAR float64) Grid

ChooseGrid selects the layout whose aspect ratio is closest to (but not below) the target, with at least 2 columns and 2 rows.

type OrderedMap added in v0.15.1

type OrderedMap struct {
	// contains filtered or unexported fields
}

OrderedMap is a small string->value map that preserves insertion order, so the emitted data-qualifiers JSON matches the reference insertion order. Values are either string or int (the CID version qualifier is numeric).

func (*OrderedMap) Get added in v0.15.1

func (m *OrderedMap) Get(k string) any

Get returns the value for a key.

func (*OrderedMap) Keys added in v0.15.1

func (m *OrderedMap) Keys() []string

Keys returns the insertion-ordered keys.

type Parsed

type Parsed struct {
	TypeName       string
	Alphabet       Alphabet
	Prefix         *string
	Core           string
	Suffix         *string
	PrefixSemantic bool
}

Parsed is a recognized entropy classification.

func Parse

func Parse(entropy string) (*Parsed, error)

Parse classifies the (already-trimmed) entropy string. It returns:

  • (parsed, nil) on a recognized type or disproof-detected alphabet,
  • (nil, nil) when nothing matches (caller re-encodes to base64url),
  • (nil, err) on a hard rejection (EIP-55 checksum failure).

type Part added in v0.15.1

type Part struct {
	Text string
	Bind string
}

Part is one ordered [{text, bind}] entry; bind in {none, fold, core}.

type RenderError

type RenderError struct {
	Kind     string // "note" | "input-too-long" | "font-size" | "aspect-ratio" | "no-tokens" | "eip55"
	Message  string
	Position int // for eip55
}

RenderError represents a render rejection. Kind discriminates the reason.

func (*RenderError) Error

func (e *RenderError) Error() string

type Token

type Token struct {
	Text  string
	Index int
	Quant uint32
}

Token is one rendered chunk of entropy (or one ftok of a fingerprint).

func MedianToken

func MedianToken(tokens []Token) (Token, bool)

MedianToken returns the lower-middle token of the ASCII text-sorted list.

func QuartileTokens

func QuartileTokens(tokens []Token) []*Token

QuartileTokens returns the first token of each of the four mirror-sorted quartiles; a slot is absent (ok=false) when it would fall in padding.

func Tokenize

func Tokenize(text string, alphabet Alphabet) []Token

Tokenize splits text into 24-bit tokens under the given alphabet, extending short trailing chunks to a full 24-bit quant by the bit-repeat rule.

func TokenizeEntropy

func TokenizeEntropy(core string, alphabet Alphabet) ([]Token, bool)

TokenizeEntropy tokenizes entropy with head/middle/tail large-input handling. It returns (tokens, truncated).

func TokenizeFingerprint

func TokenizeFingerprint(digest [64]byte) []Token

TokenizeFingerprint serializes the 64-byte digest to base64url and splits it into the 22 ftoks the spec guarantees.

type VisualStyle

type VisualStyle struct {
	BgColor    string
	EdgeColors []string
}

VisualStyle is the entviz background plus the 4-entry edge palette.

func SelectVisualStyle

func SelectVisualStyle(medianFtok Token) VisualStyle

SelectVisualStyle picks the background from the median ftok's low 2 bits and forms the edge palette from the remaining four colors.

Directories

Path Synopsis
cmd
entviz-conformance command
Command entviz-conformance is the conformance CLI: read one vector's JSON on stdin, write the entviz SVG to stdout (exit 0), or exit non-zero to reject (the contract in the entviz repo's compliance/README.md).
Command entviz-conformance is the conformance CLI: read one vector's JSON on stdin, write the entviz SVG to stdout (exit 0), or exit non-zero to reject (the contract in the entviz repo's compliance/README.md).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL