Playground
gnomod.toml
module = "gno.land/p/nym-moultest123/x/daily/luhn/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186405 max_deposit = "5000000ugnot"
luhn.gno
// Package luhn implements the Luhn mod-10 checksum (Hans Peter Luhn, 1954) as
// a pure, reusable package: the check used by credit-card numbers, IMEIs and
// many national ID schemes to catch typos and single-digit transpositions.
//
// It is a *checksum*, not a security primitive: it detects every single-digit
// error and almost every adjacent transposition, but it is trivial to forge and
// says nothing about whether an identifier actually exists. Never use it to
// authorize anything on-chain.
//
// No clocks, no randomness, no chain imports — same input, same output.
//
// A live demo of this package is at
// [r/moul/x/daily/luhndemo](/r/nym-moultest123/x/daily/luhndemo/v0).
package luhn
import (
"strings"
)
// MaxLen bounds an input so validation gas stays predictable.
const MaxLen = 64
// Valid reports whether s carries a correct Luhn check digit.
//
// Spaces and hyphens are ignored, so "4539 1488 0343 6467" and
// "4539-1488-0343-6467" both work. Any other non-digit makes it false, as does
// an empty/1-digit input or one longer than MaxLen. A string of all zeros is
// technically Luhn-valid and is accepted — reject it in the caller if your
// domain needs to.
func Valid(s string) bool {
digits, ok := clean(s)
if !ok || len(digits) < 2 {
return false
}
return sum(digits)%10 == 0
}
// CheckDigit returns the digit that must be appended to payload to make the
// whole string Luhn-valid, and whether the payload was usable.
func CheckDigit(payload string) (int, bool) {
digits, ok := clean(payload)
if !ok || len(digits) == 0 {
return 0, false
}
// The check digit sits in the "doubled" position of the final number, so
// compute the sum as if a 0 had already been appended.
total := sum(append(digits, 0))
return (10 - total%10) % 10, true
}
// Append returns payload with its Luhn check digit appended (digits only,
// separators stripped), and whether the payload was usable.
func Append(payload string) (string, bool) {
d, ok := CheckDigit(payload)
if !ok {
return "", false
}
digits, _ := clean(payload)
var b strings.Builder
for _, x := range digits {
b.WriteByte(byte('0' + x))
}
b.WriteByte(byte('0' + d))
return b.String(), true
}
// clean turns s into its digit values, ignoring spaces and hyphens. ok is false
// if any other character appears or the input exceeds MaxLen.
func clean(s string) ([]int, bool) {
if len(s) > MaxLen {
return nil, false
}
digits := make([]int, 0, len(s))
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c >= '0' && c <= '9':
digits = append(digits, int(c-'0'))
case c == ' ' || c == '-':
// separator: ignore
default:
return nil, false
}
}
return digits, true
}
// sum computes the Luhn total: walking right to left, every second digit is
// doubled, and a double of 10 or more has 9 subtracted (equivalent to adding
// its two decimal digits).
func sum(digits []int) int {
total := 0
double := false
for i := len(digits) - 1; i >= 0; i-- {
d := digits[i]
if double {
d *= 2
if d > 9 {
d -= 9
}
}
total += d
double = !double
}
return total
}
luhn_test.gno
package luhn
import (
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestValid(t *testing.T) {
cases := []struct {
name string
in string
want bool
}{
{"known-good test card", "4539148803436467", true},
{"spaces ignored", "4539 1488 0343 6467", true},
{"hyphens ignored", "4539-1488-0343-6467", true},
{"single digit flipped", "4539148803436468", false},
{"adjacent transposition", "4539148803436647", false},
{"classic 79927398713", "79927398713", true},
{"classic off by one", "79927398710", false},
{"all zeros is valid", "00", true},
{"letters rejected", "4539abc8803436467", false},
{"empty rejected", "", false},
{"one digit rejected", "7", false},
{"separators only rejected", " - ", false},
{"over MaxLen rejected", strings.Repeat("0", MaxLen+1), false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
uassert.Equal(t, c.want, Valid(c.in))
})
}
}
func TestCheckDigit(t *testing.T) {
cases := []struct {
payload string
want int
}{
{"7992739871", 3},
{"453914880343646", 7},
{"0", 0},
}
for _, c := range cases {
got, ok := CheckDigit(c.payload)
uassert.True(t, ok)
uassert.Equal(t, c.want, got)
}
}
func TestCheckDigitRejectsBadInput(t *testing.T) {
for _, in := range []string{"", "abc", " - "} {
_, ok := CheckDigit(in)
uassert.False(t, ok)
}
}
// Append must produce something Valid accepts — the round-trip property.
func TestAppendRoundTrip(t *testing.T) {
payloads := []string{"7992739871", "453914880343646", "1", "123456789012345"}
for _, p := range payloads {
got, ok := Append(p)
uassert.True(t, ok)
uassert.True(t, Valid(got))
uassert.Equal(t, len(p)+1, len(got))
}
}
// Append strips separators, so a spaced payload yields the same digits.
func TestAppendStripsSeparators(t *testing.T) {
a, ok := Append("4539 1488 0343 646")
uassert.True(t, ok)
b, ok2 := Append("453914880343646")
uassert.True(t, ok2)
uassert.Equal(t, b, a)
uassert.Equal(t, "4539148803436467", a)
}
// Every single-digit change to a valid number must be caught: that is the
// guarantee Luhn actually makes.
func TestDetectsEverySingleDigitError(t *testing.T) {
const base = "4539148803436467"
uassert.True(t, Valid(base))
for i := 0; i < len(base); i++ {
for d := byte('0'); d <= '9'; d++ {
if d == base[i] {
continue
}
mutated := base[:i] + string(d) + base[i+1:]
uassert.False(t, Valid(mutated))
}
}
}