package identity import ( "encoding/hex" "errors" "time" "git.stinnesbeck.com/nils/allmende/internal/jcs" "git.stinnesbeck.com/nils/allmende/internal/pow" ) const ( RevocationVersion = 1 revocationContext = "allmende-revocation-v1\n" ) // Revocation voids a device: every signature made by Device is rejected from // now on. Nodes keep it until the device's certificate would have expired // anyway (CertExpiresAt). It carries proof-of-work so nobody can flood the // network with revocations for throwaway identities. type Revocation struct { Version int `json:"v"` Author string `json:"author"` Device string `json:"device"` RevokedAt int64 `json:"revoked_at"` CertExpiresAt int64 `json:"cert_expires_at"` PoW uint64 `json:"pow"` Sig string `json:"sig,omitempty"` } func (r *Revocation) signingBytes() ([]byte, error) { cp := *r cp.Sig = "" b, err := jcs.Marshal(&cp) if err != nil { return nil, err } return append([]byte(revocationContext), b...), nil } // Revoke signs a revocation of the device named in cert, mining the // proof-of-work to the given difficulty. func Revoke(root *Identity, cert *Cert, at time.Time, difficulty int) (*Revocation, error) { if root.PublicKeyHex() != cert.Author { return nil, errors.New("identity: cert does not belong to this identity") } r := &Revocation{ Version: RevocationVersion, Author: cert.Author, Device: cert.Device, RevokedAt: at.Unix(), CertExpiresAt: cert.ExpiresAt, } for ; ; r.PoW++ { b, err := r.signingBytes() if err != nil { return nil, err } if pow.LeadingZeroBits(b) >= difficulty { r.Sig = hex.EncodeToString(root.Sign(b)) return r, nil } } } // Check verifies structure, signature and proof-of-work. func (r *Revocation) Check(difficulty int) error { if r.Version != RevocationVersion { return errors.New("identity: unsupported revocation version") } if !isHex(r.Author, 64) || !isHex(r.Device, 64) { return errors.New("identity: revocation keys must be 64 hex characters") } if r.PoW > 1<<53-1 { return errors.New("identity: number out of range") } sig, err := hex.DecodeString(r.Sig) if err != nil || len(sig) != 64 { return errors.New("identity: malformed revocation signature") } b, err := r.signingBytes() if err != nil { return err } if !Verify(r.Author, b, sig) { return errors.New("identity: bad revocation signature") } if pow.LeadingZeroBits(b) < difficulty { return errors.New("identity: insufficient proof-of-work") } return nil } // Bytes returns the canonical encoding including the signature. func (r *Revocation) Bytes() ([]byte, error) { return jcs.Marshal(r) }