zeroproof 0.2.6
Python SDK for ZeroProof AI verification API - Secure your agentic e-commerce ecosystem
License: MIT
Requires Python: >=3.8
Keywords: agent, ai, ecommerce, security, verification, zero-knowledge-proof, zeroproof, zkp

# ZeroProof Python SDK

[![PyPI version](https://badge.fury.io/py/zeroproof.svg)](https://badge.fury.io/py/zeroproof)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Python SDK for the ZeroProof AI verification API. Secure your agentic e-commerce ecosystem with zero-knowledge proofs.

## Installation

```bash
pip install zeroproof
```

## Quick Start

```python
from zeroproof import ZeroProof

# Initialize the client with your API key
client = ZeroProof(api_key="zkp_your_api_key_here")

# Create a verification challenge
challenge = client.create_challenge(
    agent_id="shopping-assistant-v1",
    action="add_to_cart",
    context={"item_id": "laptop-123", "price": 999.99}
)

print(f"Challenge ID: {challenge.challenge_id}")
print(f"Nonce: {challenge.nonce}")
print(f"Expires in: {challenge.expires_in} seconds")

# Verify the proof (in production, this would be generated by your agent)
result = client.verify_proof(
    challenge_id=challenge.challenge_id,
    proof="your_cryptographic_proof_here",
    agent_signature="optional_signature_here"
)

if result.verified:
    print(f"✅ Verification successful!")
    print(f"   Agent: {result.agent_id}")
    print(f"   Action: {result.action}")
    print(f"   Confidence: {result.confidence * 100}%")
    # Now execute the actual e-commerce action
else:
    print("❌ Verification failed")
```

## Features

- 🔐 **Zero-Knowledge Proof Verification**: Verify agent authenticity without revealing sensitive data
- 🔒 **Encrypted Messaging**: Secure agent-to-agent communication with AES-256-GCM
- 🚀 **Simple API**: Easy-to-use Python interface
- ⚡ **Fast**: Low-latency operations (< 100ms for encryption)
- 🛡️ **Secure**: End-to-end encryption with automatic key management

## Use Cases

### Encrypted Agent Communication

```python
from zeroproof import ZeroProof

client = ZeroProof(api_key="zkp_...")

# Agent 1 sends encrypted message
result = client.send_encrypted(
    to_agent_id="checkout-agent",
    message={
        "action": "process_order",
        "order_id": "ORD-12345",
        "amount": 299.99
    },
    ttl_minutes=60
)

print(f"Message ID: {result.message_id}")

# Agent 2 receives and decrypts
message = client.receive_encrypted(message_id=result.message_id)
print(f"Order: {message.message['order_id']}")
print(f"Amount: ${message.message['amount']}")
```

### E-Commerce Agent Authorization

```python
from zeroproof import ZeroProof

client = ZeroProof(api_key="zkp_...")

# Before allowing an agent to make a purchase
challenge = client.create_challenge(
    agent_id="checkout-agent-v2",
    action="initiate_purchase",
    context={
        "amount": 1499.99,
        "merchant": "TechStore",
        "items": ["laptop", "mouse", "keyboard"]
    }
)

# Agent generates proof
proof = your_agent.generate_proof(challenge)

# Verify before processing payment
result = client.verify_proof(challenge.challenge_id, proof)

if result.verified and result.confidence > 0.95:
    process_payment(1499.99)
else:
    log_security_incident(result)
```

### Refund Authorization

```python
# Verify agent before approving refund
challenge = client.create_challenge(
    agent_id="refund-processor",
    action="approve_refund",
    context={"order_id": "ORD-12345", "amount": 299.99}
)

result = client.verify_proof(challenge.challenge_id, proof)

if result.verified:
    approve_refund(order_id="ORD-12345")
```

### Inventory Management

```python
# Verify agent before updating inventory
challenge = client.create_challenge(
    agent_id="inventory-manager",
    action="update_stock",
    context={"product_id": "PROD-789", "quantity_change": -50}
)

result = client.verify_proof(challenge.challenge_id, proof)

if result.verified:
    update_inventory("PROD-789", quantity=-50)
```

### Multi-Agent Approval Workflows

```python
from zeroproof import ZeroProof

client = ZeroProof(api_key="zkp_...")

# Initiator creates approval workflow for a large purchase
workflow = client.create_approval_workflow(
    transaction_id="txn_12345",
    amount=5000.00,
    required_approvers=[
        {"agent_id": "budget_agent", "timeout_minutes": 30},
        {"agent_id": "compliance_agent", "timeout_minutes": 60}
    ],
    metadata={"vendor": "TechCorp", "category": "software"}
)

print(f"Workflow created: {workflow.workflow_id}")
print(f"Status: {workflow.status}")

# Budget agent receives notification and approves
budget_agent = ZeroProof(api_key="zkp_budget_key")
result = budget_agent.approve_workflow(
    workflow_id=workflow.workflow_id,
    decision="approved",
    reason="Within budget limits"
)

print(f"Budget agent approved. Status: {result.status}")
print(f"Pending approvers: {result.pending_approvers}")

# Compliance agent approves
compliance_agent = ZeroProof(api_key="zkp_compliance_key")
result = compliance_agent.approve_workflow(
    workflow_id=workflow.workflow_id,
    decision="approved",
    reason="Meets compliance requirements"
)

print(f"Compliance approved. Status: {result.status}")

# Check final status
status = client.get_workflow_status(workflow.workflow_id)
if status.status == "approved":
    print("✅ All approvals received - proceed with purchase")
    process_purchase(transaction_id="txn_12345")
```

## API Reference

### ZeroProof

The main client class for interacting with the API.

#### `__init__(api_key: str, base_url: Optional[str] = None)`

Initialize the ZeroProof client.

**Parameters:**
- `api_key` (str): Your ZeroProof API key (starts with 'zkp_')
- `base_url` (str, optional): Custom API base URL (defaults to production)

**Raises:**
- `ValueError`: If API key is invalid or missing

#### `create_challenge(agent_id: str, action: str, context: Optional[Dict] = None) -> Challenge`

Create a new verification challenge.

**Parameters:**
- `agent_id` (str): Unique identifier for the AI agent
- `action` (str): The action the agent wants to perform
- `context` (dict, optional): Additional context for the action

**Returns:**
- `Challenge`: Object containing challenge_id, nonce, expires_in, timestamp

**Raises:**
- `ZeroProofError`: If the request fails

#### `verify_proof(challenge_id: str, proof: str, agent_signature: Optional[str] = None) -> VerificationResult`

Verify a proof for a given challenge.

**Parameters:**
- `challenge_id` (str): The challenge ID from create_challenge()
- `proof` (str): The cryptographic proof data
- `agent_signature` (str, optional): Optional agent signature

**Returns:**
- `VerificationResult`: Object containing verification details

**Raises:**
- `ZeroProofError`: If verification fails

#### `get_status(session_id: str) -> Dict`

Get the status of a verification session.

**Parameters:**
- `session_id` (str): The session/challenge ID to check

**Returns:**
- `dict`: Session status details

**Raises:**
- `ZeroProofError`: If the request fails

### Approval Workflows

#### `create_approval_workflow(transaction_id: str, amount: float, required_approvers: list, metadata: Optional[Dict] = None) -> ApprovalWorkflow`

Create a multi-agent approval workflow.

**Parameters:**
- `transaction_id` (str): Unique transaction identifier
- `amount` (float): Transaction amount in USD
- `required_approvers` (list): List of approvers with agent_id and optional timeout_minutes
- `metadata` (dict, optional): Additional workflow context

**Returns:**
- `ApprovalWorkflow`: Created workflow information

**Raises:**
- `ZeroProofError`: If the request fails

**Example:**
```python
workflow = client.create_approval_workflow(
    transaction_id="txn_12345",
    amount=5000.00,
    required_approvers=[
        {"agent_id": "budget_agent", "timeout_minutes": 30},
        {"agent_id": "compliance_agent", "timeout_minutes": 60}
    ],
    metadata={"vendor": "TechCorp"}
)
```

#### `approve_workflow(workflow_id: str, decision: str, reason: Optional[str] = None) -> WorkflowStatus`

Approve or reject an approval workflow.

**Parameters:**
- `workflow_id` (str): The workflow ID to approve/reject
- `decision` (str): Either "approved" or "rejected"
- `reason` (str, optional): Optional reason for the decision

**Returns:**
- `WorkflowStatus`: Updated workflow status

**Raises:**
- `ZeroProofError`: If the request fails

**Example:**
```python
result = client.approve_workflow(
    workflow_id="wf_abc123",
    decision="approved",
    reason="Within budget limits"
)
```

#### `get_workflow_status(workflow_id: str) -> WorkflowStatus`

Get the status of an approval workflow.

**Parameters:**
- `workflow_id` (str): The workflow ID to check

**Returns:**
- `WorkflowStatus`: Current workflow status with approvals and pending approvers

**Raises:**
- `ZeroProofError`: If the request fails

**Example:**
```python
status = client.get_workflow_status(workflow_id="wf_abc123")
print(f"Status: {status.status}")
print(f"Approvals: {len(status.approvals)}/{len(status.required_approvers)}")
```

### Encrypted Messaging

#### `send_encrypted(to_agent_id: str, message: Any, ttl_minutes: int = 60) -> EncryptedMessage`

Send an encrypted message to another agent.

**Parameters:**
- `to_agent_id` (str): Target agent identifier
- `message` (Any): Message content (string, dict, or JSON-serializable data)
- `ttl_minutes` (int, optional): Time-to-live in minutes (default: 60, max: 1440)

**Returns:**
- `EncryptedMessage`: Object containing message_id, expires_at, status, ttl_minutes

**Example:**
```python
result = client.send_encrypted(
    to_agent_id="agent_456",
    message="Hello, secure world!",
    ttl_minutes=30
)
```

#### `receive_encrypted(message_id: str) -> DecryptedMessage`

Receive and decrypt an encrypted message.

**Parameters:**
- `message_id` (str): The message ID from send_encrypted()

**Returns:**
- `DecryptedMessage`: Object with decrypted message and metadata

**Raises:**
- `ZeroProofError`: If message not found, expired, or decryption fails

**Example:**
```python
message = client.receive_encrypted(message_id="msg_abc123...")
print(f"Content: {message.message}")
print(f"Read count: {message.read_count}")
```

### Data Classes

#### Challenge

Represents a verification challenge.

**Attributes:**
- `challenge_id` (str): Unique challenge identifier
- `nonce` (str): Random nonce for this challenge
- `expires_in` (int): Time until expiration in seconds
- `timestamp` (int): Challenge creation timestamp

#### VerificationResult

Represents the result of proof verification.

**Attributes:**
- `verified` (bool): Whether the proof was verified
- `agent_id` (str): The agent that was verified
- `action` (str): The action that was authorized
- `confidence` (float): Confidence score (0.0 to 1.0)
- `timestamp` (str): Verification timestamp
- `session_id` (str): Session identifier

#### EncryptedMessage

Represents an encrypted message response.

**Attributes:**
- `message_id` (str): Unique message identifier
- `expires_at` (str): Expiration timestamp (ISO 8601)
- `status` (str): Message status ("ready")
- `ttl_minutes` (int): Time-to-live in minutes

#### DecryptedMessage

Represents a decrypted message.

**Attributes:**
- `message_id` (str): Message identifier
- `from_agent_id` (str): Sender's API key (partial)
- `to_agent_id` (str): Recipient identifier
- `message` (Any): Decrypted message content
- `read_count` (int): Number of times message was read
- `created_at` (str): Creation timestamp
- `expires_at` (str): Expiration timestamp

#### ApprovalWorkflow

Represents a created approval workflow.

**Attributes:**
- `workflow_id` (str): Unique workflow identifier
- `status` (str): Workflow status (pending, approved, rejected, expired)
- `transaction_id` (str): Associated transaction ID
- `amount` (float): Transaction amount
- `required_approvers` (list): List of required approvers
- `created_at` (str): Creation timestamp
- `expires_at` (str): Expiration timestamp

#### WorkflowStatus

Represents the status of an approval workflow.

**Attributes:**
- `workflow_id` (str): Unique workflow identifier
- `status` (str): Current workflow status
- `transaction_id` (str): Associated transaction ID
- `amount` (float): Transaction amount
- `required_approvers` (list): List of required approvers
- `approvals` (list): List of WorkflowApproval objects
- `pending_approvers` (list): List of agent IDs still pending
- `created_at` (str): Creation timestamp
- `expires_at` (str): Expiration timestamp
- `updated_at` (str): Last update timestamp
- `metadata` (dict): Additional workflow context

#### WorkflowApproval

Represents a single approval within a workflow.

**Attributes:**
- `agent_id` (str): Approver's agent ID
- `decision` (str): "approved" or "rejected"
- `timestamp` (str): Approval timestamp
- `reason` (str, optional): Reason for decision

### Exceptions

#### ZeroProofError

Base exception for SDK errors.

**Attributes:**
- `message` (str): Error message
- `status_code` (int, optional): HTTP status code
- `response` (dict, optional): Full API response

## Context Manager Support

The SDK supports context managers for automatic resource cleanup:

```python
with ZeroProof(api_key="zkp_...") as client:
    challenge = client.create_challenge("agent-1", "purchase")
    result = client.verify_proof(challenge.challenge_id, proof)
# Session is automatically closed
```

## Error Handling

```python
from zeroproof import ZeroProof, ZeroProofError

client = ZeroProof(api_key="zkp_...")

try:
    challenge = client.create_challenge("agent", "action")
    result = client.verify_proof(challenge.challenge_id, "invalid_proof")
except ZeroProofError as e:
    print(f"Error: {e.message}")
    print(f"Status Code: {e.status_code}")
    print(f"Response: {e.response}")
```

### Handling Message Expiration

```python
try:
    message = client.receive_encrypted(message_id="msg_...")
except ZeroProofError as e:
    if e.status_code == 410:
        print("Message expired")
    elif e.status_code == 404:
        print("Message not found")
    else:
        print(f"Error: {e.message}")
```

## Configuration

### Custom API Endpoint

For testing or self-hosted deployments:

```python
client = ZeroProof(
    api_key="zkp_...",
    base_url="https://api.custom-domain.com/v1"
)
```

### Environment Variables

You can set your API key via environment variable:

```python
import os
from zeroproof import ZeroProof

api_key = os.getenv("ZEROPROOF_API_KEY")
client = ZeroProof(api_key=api_key)
```

## Requirements

- Python 3.8+
- requests >= 2.25.0

## Examples

See the [examples](examples/) directory for complete examples:

- `shopping_agent_demo.py` - ZKP verification demo
- `encrypted_messaging_demo.py` - Encrypted messaging demo with multiple scenarios

Run an example:

```bash
export ZEROPROOF_API_KEY="zkp_your_key_here"
python examples/encrypted_messaging_demo.py
```

## Getting an API Key

1. Sign up at [https://zeroproofai.com](https://zeroproofai.com)
2. Navigate to your dashboard
3. Generate a new API key
4. Copy the key (starts with `zkp_`)

## Development

### Installing for Development

```bash
git clone https://github.com/jacobweiss2305/zeroproof.git
cd zeroproof/python-sdk
pip install -e ".[dev]"
```

### Running Tests

```bash
pytest tests/
```

### Code Formatting

```bash
black zeroproof/
flake8 zeroproof/
mypy zeroproof/
```

## Support

- **Documentation**: [https://docs.zeroproofai.com](https://docs.zeroproofai.com)
- **Issues**: [GitHub Issues](https://github.com/jacobweiss2305/zeroproof/issues)
- **Email**: support@zeroproofai.com

## License

MIT License - see [LICENSE](LICENSE) file for details.

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## Changelog

### 0.3.0 (2025-01-06)

- ✨ Added Multi-Agent Approval Workflows
- 🔄 `create_approval_workflow()` - Create approval workflows with multiple approvers
- ✅ `approve_workflow()` - Approve or reject workflows
- 📊 `get_workflow_status()` - Query workflow status and approvals
- 🔔 Automatic encrypted notifications to approvers
- ⏰ Configurable timeout per approver (1-1440 minutes)
- 🎯 Automatic status transitions (pending → approved/rejected)
- 🔐 Authorization checks and access control

### 0.2.0 (2025-10-02)

- ✨ Added encrypted messaging service
- 🔒 AES-256-GCM encryption for agent-to-agent communication
- ⏰ TTL-based message expiration with auto-cleanup
- 📖 Multiple reads supported until expiration
- 📝 New example: encrypted_messaging_demo.py

### 0.1.0 (2025-01-10)

- Initial release
- Basic challenge/proof verification flow
- Context manager support
- Comprehensive error handling
- Full type hints