package identity import ( "crypto/ed25519" "encoding/json" "errors" "os" "path/filepath" "time" ) // Device is what a running node holds: its own key plus the certificate that // ties it to an identity. The identity key itself is never stored. type Device struct { Key *Identity Cert *Cert } // Enroll creates a new device key and certifies it with the identity key. func Enroll(root *Identity, now time.Time, validFor time.Duration) (*Device, error) { key, err := Generate() if err != nil { return nil, err } cert, err := IssueCert(root, key.PublicKeyHex(), now, now.Add(validFor)) if err != nil { return nil, err } return &Device{Key: key, Cert: cert}, nil } const ( deviceKeyFile = "device.key" deviceCertFile = "device.cert" ) // Save writes the device key (refusing to overwrite) and certificate into dir. func (d *Device) Save(dir string) error { if err := d.Key.Save(filepath.Join(dir, deviceKeyFile)); err != nil { return err } return d.SaveCert(dir) } // SaveCert (over)writes only the certificate, e.g. after renewal. func (d *Device) SaveCert(dir string) error { data, err := json.Marshal(d.Cert) if err != nil { return err } path := filepath.Join(dir, deviceCertFile) tmp := path + ".tmp" if err := os.WriteFile(tmp, data, 0o644); err != nil { return err } return os.Rename(tmp, path) } // LoadDevice reads a device saved by Save and checks that key and // certificate belong together. func LoadDevice(dir string) (*Device, error) { key, err := Load(filepath.Join(dir, deviceKeyFile)) if err != nil { return nil, err } data, err := os.ReadFile(filepath.Join(dir, deviceCertFile)) if err != nil { return nil, err } var cert Cert if err := json.Unmarshal(data, &cert); err != nil { return nil, err } if err := cert.Check(); err != nil { return nil, err } if cert.Device != key.PublicKeyHex() { return nil, errors.New("identity: certificate does not match device key") } return &Device{Key: key, Cert: &cert}, nil } // PrivateKey exposes the raw key so the p2p layer can use it as the node's // libp2p identity. Handle with care. func (i *Identity) PrivateKey() ed25519.PrivateKey { return i.priv }