Allocate: deduplicate by pubkey, GetByPubKey: return latest

Allocate now checks if pubkey already has an identity and returns it. Prevents duplicate identities for same pubkey (was causing random number assignment on cert auth). GetByPubKey returns identity with highest CreatedAt for deterministic behavior.
This commit is contained in:
Niko Marmeladkov 2026-07-01 15:41:00 +03:00
parent 8726dcc01e
commit 48143cdbf5

View file

@ -44,6 +44,10 @@ func NewManager(engine *store.Engine, masterKey [32]byte, prefix string, cooldow
}
func (m *Manager) Allocate(pubKey [32]byte) (*Identity, error) {
if existing, err := m.GetByPubKey(pubKey); err == nil {
return existing, nil
}
var number string
for attempts := 0; attempts < 100; attempts++ {
number = GenerateNumber(m.prefix)
@ -141,11 +145,12 @@ func (m *Manager) Exists(number string) bool {
func (m *Manager) GetByPubKey(pubKey [32]byte) (*Identity, error) {
var found *Identity
var latest int64
err := m.store.Iterate(func(keyHash uint64, payload []byte) bool {
ident := m.unmarshalIdentity(payload)
if ident != nil && ident.PubKey == pubKey {
if ident != nil && ident.PubKey == pubKey && ident.CreatedAt > latest {
found = ident
return false
latest = ident.CreatedAt
}
return true
}, m.masterKey)