Skip to content

fix: Luhn check digit for card numbers and a new card type on every call - #105

Merged
bxcodec merged 3 commits into
go-faker:mainfrom
simonkundrik:fix/credit-card-numbers
Nov 26, 2026
Merged

bxcodec merged 3 commits into
go-faker:mainfrom
simonkundrik:fix/credit-card-numbers

Conversation

@simonkundrik

Copy link
Copy Markdown
Contributor

CCNumber() and the cc_number tag only made a prefix and random digits, so about 9 in 10 numbers fail the Luhn check that a shop or a form runs on a card number, and CCType() returned the same type on every call after the first (#24).

Why

  • ccnumber took a prefix of the card type and filled the rest with random digits, with no check digit. The last digit is random, so exactly 1 in 10 numbers passes (60,236 of 600,000 in a copy of the rule; in the new test on master 5,375 of 6,000 fail).
  • cctype kept the first type it picked in the package variable cacheCreditCard and never reset it, so CCType() is one value for the rest of the program and every struct you fill gets the same card type. The variable is there so the cc_type and the cc_number of one struct are the same card, which is worth keeping.
  • cctype also made its list of types by ranging over the creditCards map, which Go reads in a random order, so the same seed (SetRandomSource) could pick another first type.
  • Two goroutines that call it for the first time write the variable at once (also mentioned in Cached cctype results in non-random data #24).

What changed

  • creditCardNumber ends a number with the Luhn check digit (luhnCheckDigit). Lengths and prefixes are as before, so it has one random digit less.
  • CCType() and CCNumber() pick a card type from the sorted keys of creditCards on every call, so a seed gives the same sequence. The methods of GetPayment() do the same outside of a struct.
  • Inside a struct the cc_type and cc_number fields still get one card, in either order. getFakedValueForStruct starts a card for each struct and puts the outer one back when it is done, so the elements of a slice get different cards, and a struct inside a struct has a card of its own. The variable is behind a mutex.
  • The sample output in the comments of the examples is not tested, I left it as it is.

Fixes #24

How it was tested
  • New tests in payment_test.go. luhnCheckDigit: the six card numbers that the payment providers publish for tests, and every prefix of 4 and of 5 digits (exactly one check digit passes and it is the one returned). The numbers of CCNumber() pass the Luhn check, CCType() gives all six types in 600 calls and the same ones for the same seed, and a struct (in either field order) and the elements of a slice get a number that fits the type of their own card (length, prefix, check digit). Six of the tests fail on master.
  • 60,000 numbers from filled structs all pass isLuhnNumber of validator.js, and isCreditCard accepts them with the provider of their type, except the Diners Club ones that start with 39 (3,382 of 10,111): its pattern for that brand does not know the prefix, I left the prefixes alone.
  • go test ./..., go vet and gofmt pass. I could not run -race or golangci-lint here (no C compiler and no linter installed), CI does.

CCNumber and the cc_number tag made a prefix and random digits, so only
1 number in 10 passed the Luhn check that a shop or a form runs on a card
number. The last digit is the check digit now.

cctype kept the first card type it picked in a package variable and never
let it go, so CCType returned the same type on every call (go-faker#24) and every
struct got the same one. It also read the creditCards map in its random
order, so the same seed could pick another first type. Now every call picks
a type from the keys in a fixed order, and a struct gets a card of its own:
its cc_type and cc_number fields still agree, the next struct gets another.
The variable is behind a mutex, so parallel FakeData calls do not write it
at the same time.

Fixes go-faker#24
@bxcodec

bxcodec commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Hey,
I stress test this (thx to AI), here is my test

package faker

import (
	"sync"
	"sync/atomic"
	"testing"
)

func TestZZConcurrentMismatch(t *testing.T) {
	type C struct {
		T string `faker:"cc_type"`
		N string `faker:"cc_number"`
	}
	var bad, total atomic.Int64
	var wg sync.WaitGroup
	for range 8 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for range 5000 {
				var c C
				_ = FakeData(&c)
				total.Add(1)
				if !cardNumberMatches(c.N, c.T) {
					bad.Add(1)
				}
			}
		}()
	}
	wg.Wait()
	if bad.Load() > 0 {
		t.Errorf("cc_type and cc_number mismatched in %d of %d structs", bad.Load(), total.Load())
	}
}

It fails on concurrent, the data is not matched.

Comment thread payment.go Outdated
defer cacheCreditCardMu.Unlock()

outer := cacheCreditCard
cacheCreditCard = ""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the issue is here this is on package-level but reset here while another goroutine's struct is still using it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe the solution is to keep the card per FakeData call instead of a package global?

getFakedValueForStruct (

faker/faker.go

Line 586 in eb9c7e5

func getFakedValueForStruct(item any, t reflect.Type, opts *options.Options) (reflect.Value, error) {
) already passes opts down, so maybe it can live there. Then no mutex needed.

…ariable

The card of a struct was kept in a package variable behind a mutex. The
mutex kept the writes from racing, but not the pairing: a goroutine that
started another struct put the variable back to empty while this struct
was half filled, so its cc_number got another card than its cc_type. With
8 goroutines that happened in 29,809 of 40,000 structs.

getFakedValueForStruct keeps the card in a variable of its own now, one per
struct, picked by the first of its cc_type and cc_number fields. A struct
inside a struct has a card of its own, and a struct that is filled at the
same time in another goroutine does not share it. There is no package state
and no mutex left.
@simonkundrik

Copy link
Copy Markdown
Contributor Author

Thanks, you're right: the mutex stopped the writes from racing, but not the pairing. I ran your test on my commit and it failed in 29,809 of 40,000 structs. I pushed a new commit: the card is a variable of getFakedValueForStruct now, so there's no package state and no mutex. I kept it per struct and not per FakeData call, so the elements of one slice still get different cards. Your test passes, and mine checks the pairing now (it only looked for races before).

@bxcodec

bxcodec commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Thanks, this is better now

One thing I found: since setFieldWithTag fills cc_type/cc_number directly, a custom provider is ignored inside structs now. E.g.

faker.RemoveProvider("cc_type")
faker.AddProvider("cc_type", func(v reflect.Value) (any, error) { return "MY-CARD", nil })

On master, a struct field with faker:"cc_type" gets "MY-CARD", on this branch, it gets a random type. Not common, but it fails silently. Can you help to make it use the struct card only when the built-in provider is still there? And please include a test for it.

…struct

A struct filled its cc_type and cc_number fields from the card of the
struct without asking the registry, so a provider that a caller put in
place of the built-in one (RemoveProvider, then AddProvider) was ignored
there, and a removed provider did not give the unsupported tag error.

mapperTag marks the providers that the package registers itself. The
fields of a struct get the card of the struct only while the provider of
their tag is still that one. A provider of the caller fills the field like
it does for every other tag, and with no provider left the tag is an error
again.
@simonkundrik

Copy link
Copy Markdown
Contributor Author

Good catch, thanks. I pushed a new commit: the card of the struct is used for cc_type and cc_number only while the provider of the tag is still the built-in one. mapperTag marks the providers that the package registers itself, and RemoveProvider + AddProvider replaces the mark with yours, so your function fills the field like on master, for string and *string fields. A tag with no provider left is an error again (Tag unsupported: cc_type), also like on master. The other tag keeps the card of the struct.

New test TestCreditCardCustomProviderInAStruct: your example for cc_type, for cc_number, for both, and for a removed provider, with the built-ins put back when each case ends. It fails on the previous commit in all four cases, and go test ./..., go vet and gofmt pass here (no -race or golangci-lint on this machine, CI has them).

One thing to know: if a caller registers the built-in function itself (AddProvider("cc_type", faker.GetPayment().CreditCardType)), it counts as a provider of the caller and is called like any other, so its card is not the card of the struct.

@bxcodec bxcodec left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@bxcodec
bxcodec merged commit aa17435 into go-faker:main Nov 26, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cached cctype results in non-random data

2 participants