dcp-ai 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dcp_ai/__init__.py ADDED
@@ -0,0 +1,69 @@
1
+ """
2
+ dcp-ai: Python SDK for the Digital Citizenship Protocol for AI Agents.
3
+
4
+ Provides models, cryptographic signing/verification, schema validation,
5
+ Merkle tree operations, and a builder for DCP Citizenship Bundles.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from dcp_ai.models import (
13
+ ResponsiblePrincipalRecord,
14
+ AgentPassport,
15
+ Intent,
16
+ IntentTarget,
17
+ PolicyDecision,
18
+ AuditEntry,
19
+ AuditEvidence,
20
+ CitizenshipBundle,
21
+ SignedBundle,
22
+ BundleSignature,
23
+ SignerInfo,
24
+ RevocationRecord,
25
+ HumanConfirmation,
26
+ )
27
+ from dcp_ai.crypto import generate_keypair, sign_object, verify_object, canonicalize
28
+ from dcp_ai.merkle import hash_object, merkle_root_for_audit_entries, intent_hash, prev_hash_for_entry
29
+ from dcp_ai.verify import verify_signed_bundle
30
+ from dcp_ai.bundle import BundleBuilder, sign_bundle
31
+
32
+ import dcp_ai.v2 as v2
33
+
34
+ __version__ = "1.0.0"
35
+
36
+
37
+ def detect_dcp_version(artifact: dict[str, Any]) -> str | None:
38
+ """Detect the DCP protocol version from an artifact dict.
39
+
40
+ Checks dcp_version, dcp_bundle_version, and bundle.dcp_bundle_version fields.
41
+ Returns "1.0", "2.0", or None if unrecognised.
42
+ """
43
+ version = artifact.get("dcp_version")
44
+ if version in ("1.0", "2.0"):
45
+ return version
46
+
47
+ bundle_version = artifact.get("dcp_bundle_version")
48
+ if bundle_version == "2.0":
49
+ return "2.0"
50
+
51
+ nested_version = artifact.get("bundle", {}).get("dcp_bundle_version")
52
+ if nested_version == "2.0":
53
+ return "2.0"
54
+
55
+ return None
56
+
57
+
58
+ __all__ = [
59
+ "ResponsiblePrincipalRecord", "AgentPassport", "Intent", "IntentTarget",
60
+ "PolicyDecision", "AuditEntry", "AuditEvidence",
61
+ "CitizenshipBundle", "SignedBundle", "BundleSignature", "SignerInfo",
62
+ "RevocationRecord", "HumanConfirmation",
63
+ "generate_keypair", "sign_object", "verify_object", "canonicalize",
64
+ "hash_object", "merkle_root_for_audit_entries", "intent_hash", "prev_hash_for_entry",
65
+ "verify_signed_bundle",
66
+ "BundleBuilder", "sign_bundle",
67
+ "v2",
68
+ "detect_dcp_version",
69
+ ]
dcp_ai/bundle.py ADDED
@@ -0,0 +1,146 @@
1
+ """
2
+ Builder pattern for constructing and signing DCP Citizenship Bundles.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import hashlib
8
+ from datetime import datetime, timezone
9
+ from typing import Any
10
+
11
+ from dcp_ai.crypto import canonicalize, sign_object, public_key_from_secret
12
+ from dcp_ai.merkle import hash_object, intent_hash, merkle_root_for_audit_entries
13
+ from dcp_ai.models import (
14
+ CitizenshipBundle,
15
+ ResponsiblePrincipalRecord,
16
+ AgentPassport,
17
+ Intent,
18
+ PolicyDecision,
19
+ AuditEntry,
20
+ AuditEvidence,
21
+ )
22
+
23
+
24
+ class BundleBuilder:
25
+ """Fluent builder for DCP Citizenship Bundles."""
26
+
27
+ def __init__(self) -> None:
28
+ self._rpr: ResponsiblePrincipalRecord | None = None
29
+ self._passport: AgentPassport | None = None
30
+ self._intent: Intent | None = None
31
+ self._policy: PolicyDecision | None = None
32
+ self._audit_entries: list[AuditEntry] = []
33
+
34
+ def responsible_principal_record(self, rpr: ResponsiblePrincipalRecord) -> BundleBuilder:
35
+ self._rpr = rpr
36
+ return self
37
+
38
+ def agent_passport(self, passport: AgentPassport) -> BundleBuilder:
39
+ self._passport = passport
40
+ return self
41
+
42
+ def intent(self, intent: Intent) -> BundleBuilder:
43
+ self._intent = intent
44
+ return self
45
+
46
+ def policy_decision(self, policy: PolicyDecision) -> BundleBuilder:
47
+ self._policy = policy
48
+ return self
49
+
50
+ def add_audit_entry(self, entry: AuditEntry) -> BundleBuilder:
51
+ self._audit_entries.append(entry)
52
+ return self
53
+
54
+ def create_audit_entry(
55
+ self,
56
+ *,
57
+ audit_id: str,
58
+ timestamp: str,
59
+ agent_id: str,
60
+ human_id: str,
61
+ intent_id: str,
62
+ policy_decision: str,
63
+ outcome: str,
64
+ evidence: AuditEvidence | None = None,
65
+ ) -> BundleBuilder:
66
+ """Create a new audit entry with correct intent_hash and prev_hash chaining."""
67
+ if not self._intent:
68
+ raise ValueError("Intent must be set before creating audit entries")
69
+
70
+ i_hash = intent_hash(self._intent.model_dump())
71
+ prev_hash = (
72
+ "GENESIS"
73
+ if not self._audit_entries
74
+ else hash_object(self._audit_entries[-1].model_dump())
75
+ )
76
+
77
+ entry = AuditEntry(
78
+ audit_id=audit_id,
79
+ prev_hash=prev_hash,
80
+ timestamp=timestamp,
81
+ agent_id=agent_id,
82
+ human_id=human_id,
83
+ intent_id=intent_id,
84
+ intent_hash=i_hash,
85
+ policy_decision=policy_decision, # type: ignore
86
+ outcome=outcome,
87
+ evidence=evidence or AuditEvidence(),
88
+ )
89
+ self._audit_entries.append(entry)
90
+ return self
91
+
92
+ def build(self) -> CitizenshipBundle:
93
+ """Build the Citizenship Bundle. Raises ValueError if any required artifact is missing."""
94
+ if not self._rpr:
95
+ raise ValueError("Missing responsible_principal_record")
96
+ if not self._passport:
97
+ raise ValueError("Missing agent_passport")
98
+ if not self._intent:
99
+ raise ValueError("Missing intent")
100
+ if not self._policy:
101
+ raise ValueError("Missing policy_decision")
102
+ if not self._audit_entries:
103
+ raise ValueError("At least one audit entry is required")
104
+
105
+ return CitizenshipBundle(
106
+ responsible_principal_record=self._rpr,
107
+ agent_passport=self._passport,
108
+ intent=self._intent,
109
+ policy_decision=self._policy,
110
+ audit_entries=self._audit_entries,
111
+ )
112
+
113
+
114
+ def sign_bundle(
115
+ bundle: CitizenshipBundle,
116
+ secret_key_b64: str,
117
+ signer_type: str = "human",
118
+ signer_id: str | None = None,
119
+ ) -> dict[str, Any]:
120
+ """Sign a Citizenship Bundle and produce a Signed Bundle dict."""
121
+ bundle_dict = bundle.model_dump()
122
+ public_key_b64 = public_key_from_secret(secret_key_b64)
123
+
124
+ bundle_hash_hex = hashlib.sha256(
125
+ canonicalize(bundle_dict).encode("utf-8")
126
+ ).hexdigest()
127
+
128
+ merkle_hex = merkle_root_for_audit_entries(bundle_dict.get("audit_entries", []))
129
+
130
+ sig_b64 = sign_object(bundle_dict, secret_key_b64)
131
+
132
+ return {
133
+ "bundle": bundle_dict,
134
+ "signature": {
135
+ "alg": "ed25519",
136
+ "created_at": datetime.now(timezone.utc).isoformat(),
137
+ "signer": {
138
+ "type": signer_type,
139
+ "id": signer_id or bundle.responsible_principal_record.human_id,
140
+ "public_key_b64": public_key_b64,
141
+ },
142
+ "bundle_hash": f"sha256:{bundle_hash_hex}",
143
+ "merkle_root": f"sha256:{merkle_hex}" if merkle_hex else None,
144
+ "sig_b64": sig_b64,
145
+ },
146
+ }
dcp_ai/cli.py ADDED
@@ -0,0 +1,120 @@
1
+ """
2
+ DCP CLI — Command-line interface for the Digital Citizenship Protocol.
3
+ Built with Typer.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ import typer
13
+
14
+ app = typer.Typer(name="dcp", help="Digital Citizenship Protocol CLI")
15
+
16
+
17
+ @app.command()
18
+ def version() -> None:
19
+ """Show the DCP SDK version."""
20
+ from dcp_ai import __version__
21
+ typer.echo(f"dcp-ai {__version__}")
22
+
23
+
24
+ @app.command()
25
+ def keygen(out_dir: str = "keys") -> None:
26
+ """Generate a new Ed25519 keypair."""
27
+ from dcp_ai.crypto import generate_keypair
28
+
29
+ out = Path(out_dir)
30
+ out.mkdir(parents=True, exist_ok=True)
31
+ kp = generate_keypair()
32
+ (out / "public_key.txt").write_text(kp["public_key_b64"] + "\n")
33
+ (out / "secret_key.txt").write_text(kp["secret_key_b64"] + "\n")
34
+ typer.echo(f"Keypair written to {out_dir}/")
35
+
36
+
37
+ @app.command()
38
+ def validate(schema_name: str, json_path: str) -> None:
39
+ """Validate a JSON file against a DCP schema."""
40
+ from dcp_ai.schema import validate_schema
41
+
42
+ data = json.loads(Path(json_path).read_text())
43
+ result = validate_schema(schema_name, data)
44
+ if result["valid"]:
45
+ typer.echo(f"VALID ({schema_name})")
46
+ else:
47
+ for e in result.get("errors", []):
48
+ typer.echo(f" - {e}", err=True)
49
+ raise typer.Exit(1)
50
+
51
+
52
+ @app.command()
53
+ def validate_bundle(bundle_path: str) -> None:
54
+ """Validate a Citizenship Bundle JSON file."""
55
+ from dcp_ai.schema import validate_bundle as _validate_bundle
56
+
57
+ bundle = json.loads(Path(bundle_path).read_text())
58
+ result = _validate_bundle(bundle)
59
+ if result["valid"]:
60
+ typer.echo("BUNDLE VALID (DCP-01/02/03)")
61
+ else:
62
+ for e in result.get("errors", []):
63
+ typer.echo(f" - {e}", err=True)
64
+ raise typer.Exit(1)
65
+
66
+
67
+ @app.command()
68
+ def verify(signed_path: str, public_key_path: str | None = None) -> None:
69
+ """Verify a signed bundle."""
70
+ from dcp_ai.verify import verify_signed_bundle
71
+
72
+ signed_bundle = json.loads(Path(signed_path).read_text())
73
+ pk_b64 = Path(public_key_path).read_text().strip() if public_key_path else None
74
+ result = verify_signed_bundle(signed_bundle, pk_b64)
75
+ if result["verified"]:
76
+ typer.echo("SIGNATURE VALID")
77
+ typer.echo("BUNDLE INTEGRITY VALID")
78
+ typer.echo("VERIFIED (SCHEMA + SIGNATURE)")
79
+ else:
80
+ for e in result.get("errors", []):
81
+ typer.echo(e, err=True)
82
+ raise typer.Exit(1)
83
+
84
+
85
+ @app.command()
86
+ def bundle_hash(bundle_path: str) -> None:
87
+ """Compute the SHA-256 hash of a bundle."""
88
+ import hashlib
89
+ from dcp_ai.crypto import canonicalize
90
+
91
+ bundle = json.loads(Path(bundle_path).read_text())
92
+ hex_hash = hashlib.sha256(canonicalize(bundle).encode("utf-8")).hexdigest()
93
+ typer.echo(f"sha256:{hex_hash}")
94
+
95
+
96
+ @app.command()
97
+ def merkle_root(bundle_path: str) -> None:
98
+ """Compute the Merkle root of audit_entries in a bundle."""
99
+ from dcp_ai.merkle import merkle_root_for_audit_entries
100
+
101
+ bundle = json.loads(Path(bundle_path).read_text())
102
+ entries = bundle.get("audit_entries", [])
103
+ if not entries:
104
+ typer.echo("audit_entries must be a non-empty array", err=True)
105
+ raise typer.Exit(2)
106
+ root = merkle_root_for_audit_entries(entries)
107
+ typer.echo(f"sha256:{root}" if root else "null")
108
+
109
+
110
+ @app.command()
111
+ def intent_hash_cmd(intent_path: str) -> None:
112
+ """Compute the intent_hash for an Intent JSON file."""
113
+ from dcp_ai.merkle import intent_hash
114
+
115
+ intent = json.loads(Path(intent_path).read_text())
116
+ typer.echo(intent_hash(intent))
117
+
118
+
119
+ if __name__ == "__main__":
120
+ app()
dcp_ai/crypto.py ADDED
@@ -0,0 +1,69 @@
1
+ """
2
+ Ed25519 signing and verification for DCP bundles.
3
+ Uses PyNaCl for cryptographic operations.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from typing import Any
10
+
11
+ import nacl.signing
12
+ import nacl.encoding
13
+
14
+
15
+ def canonicalize(obj: Any) -> str:
16
+ """Canonical JSON serialization (deterministic key ordering, no whitespace)."""
17
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
18
+
19
+
20
+ def generate_keypair() -> dict[str, str]:
21
+ """Generate a new Ed25519 keypair. Returns dict with public_key_b64 and secret_key_b64."""
22
+ signing_key = nacl.signing.SigningKey.generate()
23
+ verify_key = signing_key.verify_key
24
+ import base64
25
+ sk_bytes = signing_key.encode() + verify_key.encode()
26
+ return {
27
+ "public_key_b64": verify_key.encode(encoder=nacl.encoding.Base64Encoder).decode("ascii"),
28
+ "secret_key_b64": base64.b64encode(sk_bytes).decode("ascii"),
29
+ }
30
+
31
+
32
+ def _to_b64(data: bytes) -> str:
33
+ import base64
34
+ return base64.b64encode(data).decode("ascii")
35
+
36
+
37
+ def _from_b64(s: str) -> bytes:
38
+ import base64
39
+ return base64.b64decode(s)
40
+
41
+
42
+ def sign_object(obj: Any, secret_key_b64: str) -> str:
43
+ """Sign a JSON object with Ed25519 (detached). Returns base64 signature."""
44
+ msg = canonicalize(obj).encode("utf-8")
45
+ sk_bytes = _from_b64(secret_key_b64)
46
+ signing_key = nacl.signing.SigningKey(sk_bytes[:32])
47
+ signed = signing_key.sign(msg)
48
+ # Detached signature is the first 64 bytes
49
+ return _to_b64(signed.signature)
50
+
51
+
52
+ def verify_object(obj: Any, signature_b64: str, public_key_b64: str) -> bool:
53
+ """Verify an Ed25519 detached signature on a JSON object."""
54
+ msg = canonicalize(obj).encode("utf-8")
55
+ sig = _from_b64(signature_b64)
56
+ pk_bytes = _from_b64(public_key_b64)
57
+ verify_key = nacl.signing.VerifyKey(pk_bytes)
58
+ try:
59
+ verify_key.verify(msg, sig)
60
+ return True
61
+ except nacl.exceptions.BadSignatureError:
62
+ return False
63
+
64
+
65
+ def public_key_from_secret(secret_key_b64: str) -> str:
66
+ """Derive the public key from a secret key (base64)."""
67
+ sk_bytes = _from_b64(secret_key_b64)
68
+ signing_key = nacl.signing.SigningKey(sk_bytes[:32])
69
+ return _to_b64(signing_key.verify_key.encode())
dcp_ai/merkle.py ADDED
@@ -0,0 +1,53 @@
1
+ """
2
+ SHA-256 hashing and Merkle tree operations for DCP.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import hashlib
8
+ from typing import Any
9
+
10
+ from dcp_ai.crypto import canonicalize
11
+
12
+
13
+ def _sha256_hex(data: bytes) -> str:
14
+ return hashlib.sha256(data).hexdigest()
15
+
16
+
17
+ def hash_object(obj: Any) -> str:
18
+ """Compute the SHA-256 hash of a canonicalized JSON object."""
19
+ canon = canonicalize(obj)
20
+ return _sha256_hex(canon.encode("utf-8"))
21
+
22
+
23
+ def merkle_root_from_hex_leaves(leaves: list[str]) -> str | None:
24
+ """Compute Merkle root from an array of hex leaf hashes."""
25
+ if not leaves:
26
+ return None
27
+ layer = list(leaves)
28
+ while len(layer) > 1:
29
+ if len(layer) % 2 == 1:
30
+ layer.append(layer[-1])
31
+ next_layer: list[str] = []
32
+ for i in range(0, len(layer), 2):
33
+ left = bytes.fromhex(layer[i])
34
+ right = bytes.fromhex(layer[i + 1])
35
+ next_layer.append(_sha256_hex(left + right))
36
+ layer = next_layer
37
+ return layer[0]
38
+
39
+
40
+ def merkle_root_for_audit_entries(audit_entries: list[Any]) -> str | None:
41
+ """Compute Merkle root for an array of audit entries."""
42
+ leaves = [hash_object(entry) for entry in audit_entries]
43
+ return merkle_root_from_hex_leaves(leaves)
44
+
45
+
46
+ def intent_hash(intent: Any) -> str:
47
+ """Compute intent_hash for an Intent object (DCP-02)."""
48
+ return hash_object(intent)
49
+
50
+
51
+ def prev_hash_for_entry(prev_entry: Any) -> str:
52
+ """Compute prev_hash for audit entry chaining (DCP-03)."""
53
+ return hash_object(prev_entry)
dcp_ai/models.py ADDED
@@ -0,0 +1,153 @@
1
+ """
2
+ Pydantic v2 models for all DCP v1 artifacts.
3
+ Generated from the DCP JSON Schemas.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Any, Literal, Optional
9
+ from pydantic import BaseModel, Field
10
+
11
+
12
+ # ── DCP-01: Identity & Human Binding ──
13
+
14
+ class ResponsiblePrincipalRecord(BaseModel):
15
+ dcp_version: str = "1.0"
16
+ human_id: str
17
+ legal_name: str
18
+ entity_type: Literal["natural_person", "organization"]
19
+ jurisdiction: str
20
+ liability_mode: Literal["owner_responsible"]
21
+ override_rights: bool
22
+ issued_at: str
23
+ expires_at: Optional[str] = None
24
+ contact: Optional[str] = None
25
+ signature: str
26
+
27
+
28
+ class AgentPassport(BaseModel):
29
+ dcp_version: str = "1.0"
30
+ agent_id: str
31
+ public_key: str
32
+ principal_binding_reference: str
33
+ capabilities: Optional[list[str]] = None
34
+ risk_tier: Optional[Literal["low", "medium", "high"]] = None
35
+ created_at: str
36
+ status: Literal["active", "revoked", "suspended"]
37
+ signature: str
38
+
39
+
40
+ # ── DCP-02: Intent Declaration & Policy Gating ──
41
+
42
+ class IntentTarget(BaseModel):
43
+ channel: Literal["web", "api", "email", "calendar", "payments", "crm", "filesystem", "runtime"]
44
+ to: Optional[str] = None
45
+ domain: Optional[str] = None
46
+ url: Optional[str] = None
47
+
48
+ model_config = {"extra": "allow"}
49
+
50
+
51
+ class Intent(BaseModel):
52
+ dcp_version: str = "1.0"
53
+ intent_id: str
54
+ agent_id: str
55
+ human_id: str
56
+ timestamp: str
57
+ action_type: Literal[
58
+ "browse", "api_call", "send_email", "create_calendar_event",
59
+ "initiate_payment", "update_crm", "write_file", "execute_code"
60
+ ]
61
+ target: IntentTarget
62
+ data_classes: list[str]
63
+ estimated_impact: Literal["low", "medium", "high"]
64
+ requires_consent: Optional[bool] = None
65
+
66
+
67
+ class RequiredConfirmation(BaseModel):
68
+ type: Literal["human_approve"]
69
+ fields: Optional[list[str]] = None
70
+
71
+
72
+ class PolicyDecision(BaseModel):
73
+ dcp_version: str = "1.0"
74
+ intent_id: str
75
+ decision: Literal["approve", "escalate", "block"]
76
+ risk_score: float = Field(ge=0, le=1)
77
+ reasons: list[str]
78
+ required_confirmation: Optional[RequiredConfirmation] = None
79
+
80
+
81
+ # ── DCP-03: Audit Chain & Transparency ──
82
+
83
+ class AuditEvidence(BaseModel):
84
+ tool: Optional[str] = None
85
+ result_ref: Optional[str] = None
86
+
87
+ model_config = {"extra": "allow"}
88
+
89
+
90
+ class AuditEntry(BaseModel):
91
+ dcp_version: str = "1.0"
92
+ audit_id: str
93
+ prev_hash: str
94
+ timestamp: str
95
+ agent_id: str
96
+ human_id: str
97
+ intent_id: str
98
+ intent_hash: str
99
+ policy_decision: Literal["approved", "escalated", "blocked"]
100
+ outcome: str
101
+ evidence: AuditEvidence
102
+
103
+
104
+ # ── Bundle Types ──
105
+
106
+ class CitizenshipBundle(BaseModel):
107
+ responsible_principal_record: ResponsiblePrincipalRecord
108
+ agent_passport: AgentPassport
109
+ intent: Intent
110
+ policy_decision: PolicyDecision
111
+ audit_entries: list[AuditEntry]
112
+
113
+
114
+ class SignerInfo(BaseModel):
115
+ type: Literal["human", "organization"]
116
+ id: str
117
+ public_key_b64: str
118
+
119
+
120
+ class BundleSignature(BaseModel):
121
+ alg: Literal["ed25519"] = "ed25519"
122
+ created_at: str
123
+ signer: SignerInfo
124
+ bundle_hash: str
125
+ merkle_root: Optional[str] = None
126
+ sig_b64: str
127
+
128
+
129
+ class SignedBundle(BaseModel):
130
+ bundle: CitizenshipBundle
131
+ signature: BundleSignature
132
+
133
+
134
+ # ── Revocation ──
135
+
136
+ class RevocationRecord(BaseModel):
137
+ dcp_version: str = "1.0"
138
+ agent_id: str
139
+ human_id: str
140
+ timestamp: str
141
+ reason: str
142
+ signature: str
143
+
144
+
145
+ # ── Human Confirmation ──
146
+
147
+ class HumanConfirmation(BaseModel):
148
+ dcp_version: str = "1.0"
149
+ intent_id: str
150
+ human_id: str
151
+ timestamp: str
152
+ decision: Literal["approve", "deny"]
153
+ signature: str
@@ -0,0 +1,19 @@
1
+ """
2
+ Concrete cryptographic provider implementations for DCP.
3
+ """
4
+
5
+ from dcp_ai.providers.ed25519_provider import Ed25519Provider
6
+
7
+ __all__ = ["Ed25519Provider"]
8
+
9
+ try:
10
+ from dcp_ai.providers.ml_dsa_65_provider import MlDsa65Provider
11
+ __all__.append("MlDsa65Provider")
12
+ except ImportError:
13
+ pass
14
+
15
+ try:
16
+ from dcp_ai.providers.slh_dsa_192f_provider import SlhDsa192fProvider
17
+ __all__.append("SlhDsa192fProvider")
18
+ except ImportError:
19
+ pass
@@ -0,0 +1,48 @@
1
+ """
2
+ Ed25519 signature provider using PyNaCl.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import base64
8
+
9
+ import nacl.encoding
10
+ import nacl.exceptions
11
+ import nacl.signing
12
+
13
+ from dcp_ai.v2.crypto_provider import CryptoProvider, derive_kid
14
+
15
+
16
+ class Ed25519Provider(CryptoProvider):
17
+ alg = "ed25519"
18
+ key_size = 32
19
+ sig_size = 64
20
+ is_constant_time = True
21
+
22
+ async def generate_keypair(self) -> dict[str, str]:
23
+ signing_key = nacl.signing.SigningKey.generate()
24
+ verify_key = signing_key.verify_key
25
+ pk_bytes = verify_key.encode()
26
+ kid = derive_kid(self.alg, pk_bytes)
27
+ return {
28
+ "kid": kid,
29
+ "public_key_b64": base64.b64encode(pk_bytes).decode("ascii"),
30
+ "secret_key_b64": base64.b64encode(
31
+ signing_key.encode() + pk_bytes
32
+ ).decode("ascii"),
33
+ }
34
+
35
+ async def sign(self, message: bytes, secret_key_b64: str) -> bytes:
36
+ sk_bytes = base64.b64decode(secret_key_b64)
37
+ signing_key = nacl.signing.SigningKey(sk_bytes[:32])
38
+ signed = signing_key.sign(message)
39
+ return signed.signature
40
+
41
+ async def verify(self, message: bytes, signature: bytes, public_key_b64: str) -> bool:
42
+ pk_bytes = base64.b64decode(public_key_b64)
43
+ verify_key = nacl.signing.VerifyKey(pk_bytes)
44
+ try:
45
+ verify_key.verify(message, signature)
46
+ return True
47
+ except nacl.exceptions.BadSignatureError:
48
+ return False