agentic-payments 0.1.0

Autonomous multi-agent Ed25519 signature verification with Byzantine fault tolerance
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
# AP2 (Agent Payments Protocol) Implementation

## Overview

The Agent Payments Protocol (AP2) provides a standardized, secure framework for agent-to-agent payment authorization and verification using W3C Verifiable Credentials with Ed25519 signatures.

## Architecture

### Core Components

```
┌─────────────────────────────────────────────────────────────┐
│                     AP2 Protocol Layer                      │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐    │
│  │ Verifiable   │  │   Mandates   │  │     DID      │    │
│  │ Credentials  │  │ Management   │  │  Management  │    │
│  └──────────────┘  └──────────────┘  └──────────────┘    │
│         │                  │                  │            │
│         └──────────────────┴──────────────────┘            │
│                         │                                   │
│                ┌────────▼────────┐                         │
│                │  Verification   │                         │
│                │   Workflow      │                         │
│                └─────────────────┘                         │
└─────────────────────────────────────────────────────────────┘
         │                                         │
         ▼                                         ▼
┌─────────────────┐                    ┌──────────────────┐
│ Ed25519 Crypto  │                    │ Multi-Agent      │
│   (dalek)       │                    │  Consensus       │
└─────────────────┘                    └──────────────────┘
```

## Modules

### 1. Verifiable Credentials (`credentials.rs`)

W3C Verifiable Credentials implementation with Ed25519 signatures.

**Key Types:**
- `VerifiableCredential` - Main credential structure
- `CredentialSubject` - Subject claims
- `Proof` - Cryptographic proof with Ed25519 signature
- `VerificationMethod` - Public key information
- `CredentialBuilder` - Fluent API for credential creation

**Features:**
- Ed25519 signature creation and verification
- Expiration handling
- Canonical JSON serialization
- Base64URL encoding for signatures
- Multi-context support (W3C VC + AP2)

**Example:**
```rust
use agentic_payments::ap2::*;
use ed25519_dalek::SigningKey;

let signing_key = SigningKey::generate(&mut rand::rngs::OsRng);
let issuer = "did:ap2:issuer".to_string();

let credential = CredentialBuilder::new(issuer, "did:ap2:subject".to_string())
    .add_claim("role".to_string(), serde_json::json!("payment-agent"))
    .add_type("PaymentCredential".to_string())
    .with_expiration(Utc::now() + Duration::days(30))
    .build(signing_key.as_bytes())?;
```

### 2. Mandates (`mandates.rs`)

Three types of mandates for payment authorization:

#### Intent Mandate
User authorization for agent actions with permissions and constraints.

```rust
let mut mandate = IntentMandate::new(
    "did:ap2:user".to_string(),
    "did:ap2:agent".to_string(),
    "Purchase items on behalf of user".to_string(),
);

mandate.add_permission(Permission {
    action: "purchase".to_string(),
    resource: "electronics".to_string(),
    conditions: vec!["max_amount:10000".to_string()],
});

mandate.add_constraint(
    "daily_limit".to_string(),
    serde_json::json!(50000),
);
```

#### Cart Mandate
Explicit purchase authorization with itemized cart and calculations.

```rust
let items = vec![
    CartItem::new("item1".to_string(), "Product A".to_string(), 2, 2500),
    CartItem::new("item2".to_string(), "Product B".to_string(), 1, 5000),
];

let cart_mandate = CartMandate::new(
    "did:ap2:user".to_string(),
    items,
    10000,
    "USD".to_string(),
)
.with_merchant("did:ap2:merchant".to_string())
.with_tax(800)
.with_shipping(500);

assert!(cart_mandate.verify_total());
```

#### Payment Mandate
Payment network signaling for actual transaction execution.

```rust
let mut payment_mandate = PaymentMandate::new(
    "did:ap2:payer".to_string(),
    "did:ap2:payee".to_string(),
    10000,
    "USD".to_string(),
    "credit_card".to_string(),
)
.with_payment_method(PaymentMethod::CreditCard {
    last_four: "4242".to_string(),
})
.with_payment_network("stripe".to_string())
.link_cart_mandate(cart_id);

payment_mandate.activate();
```

### 3. DID Management (`did.rs`)

Decentralized Identifier (DID) creation, resolution, and management.

**Key Types:**
- `DidDocument` - W3C DID Document
- `DidManager` - DID creation and lifecycle management
- `DidResolver` - DID resolution with caching
- `ServiceEndpoint` - Service endpoint definitions
- `DidUrlParser` - DID URL parsing

**Features:**
- DID document creation with verification methods
- Service endpoint management
- DID resolution and caching
- Multiple verification method support
- Controller chain management

**Example:**
```rust
let mut manager = DidManager::new();

// Create DID
let public_key = signing_key.verifying_key().to_bytes().to_vec();
let did = manager.create_did("agent-001", public_key)?;

// Add service endpoint
let service = ServiceEndpoint {
    id: format!("{}#payment", did),
    service_type: "PaymentService".to_string(),
    service_endpoint: "https://payment.example.com".to_string(),
    description: Some("Payment processing".to_string()),
};

manager.add_service_to_did(&did, service)?;

// Resolve DID
let did_doc = manager.get_did_document(&did)?;
```

### 4. Verification Workflow (`verification.rs`)

Multi-agent consensus verification for credentials.

**Key Types:**
- `VerificationWorkflow` - Main verification orchestrator
- `ConsensusVerification` - Consensus algorithm implementation
- `VerifierNode` - Verifier agent representation
- `VerificationResult` - Detailed verification results
- `VerificationPolicy` - Verification rules and policies

**Features:**
- Multi-agent consensus with configurable threshold
- Weighted voting with reputation system
- Parallel verification execution
- Verifier node registry
- Reputation management
- Multiple policy levels (strict, standard, permissive)

**Example:**
```rust
let workflow = VerificationWorkflow::new();

// Register verifiers
for i in 0..5 {
    let verifier = VerifierNode::new(
        format!("verifier-{}", i),
        format!("did:ap2:verifier-{}", i),
        format!("https://verifier-{}.example.com", i),
    )
    .with_weight(1.0)
    .with_reputation(0.95);

    workflow.register_verifier(verifier).await;
}

// Verify with consensus
let result = workflow.verify_with_all_verifiers(
    &credential,
    &did_resolver,
).await?;

println!("Consensus: {}/{} approved", result.approval_count, result.verifier_count);
```

## Complete Payment Flow

### Step-by-Step Authorization Chain

```rust
use agentic_payments::ap2::*;

#[tokio::main]
async fn main() -> Result<()> {
    let mut protocol = Ap2Protocol::new();

    // 1. Register participants
    let user_key = SigningKey::generate(&mut rand::rngs::OsRng);
    let merchant_key = SigningKey::generate(&mut rand::rngs::OsRng);

    let user = protocol.register_agent(
        "user",
        user_key.verifying_key().to_bytes().to_vec(),
    )?;

    let merchant = protocol.register_agent(
        "merchant",
        merchant_key.verifying_key().to_bytes().to_vec(),
    )?;

    // 2. Create Intent Mandate (user authorization)
    let intent = protocol.create_intent_mandate(
        &user,
        &merchant.did,
        "Purchase items from merchant",
        user_key.as_bytes(),
    )?;

    // 3. Create Cart Mandate (explicit purchase)
    let items = vec![
        CartItem::new("item1".to_string(), "Product".to_string(), 1, 5000),
    ];

    let cart = protocol.create_cart_mandate(
        &user,
        items,
        5000,
        "USD",
        user_key.as_bytes(),
    )?;

    // 4. Create Payment Mandate (payment signal)
    let payment = protocol.create_payment_mandate(
        &user,
        &merchant.did,
        5000,
        "USD",
        "credit_card",
        user_key.as_bytes(),
    )?;

    // 5. Create authorization chain
    let authorization = PaymentAuthorization::new(intent, cart, payment);

    // 6. Verify chain
    assert!(authorization.verify_chain(protocol.did_resolver())?);

    // 7. Verify with consensus
    let verifiers = create_verifier_nodes(&mut protocol, 5);
    let result = protocol.verify_payment_authorization(
        &authorization,
        verifiers,
    ).await?;

    assert!(result.verified);
    println!("Payment authorized: {}/{} consensus",
        result.approval_count, result.verifier_count);

    Ok(())
}
```

## Security Features

### 1. Ed25519 Signatures
- Fast verification (~64 microseconds)
- Small signatures (64 bytes)
- Strong security (128-bit security level)
- Deterministic signing

### 2. Cryptographic Verification
- SHA-256 hashing for canonical representation
- Base64URL encoding for web-safe transport
- Signature verification before any processing
- Expiration checks

### 3. Multi-Agent Consensus
- Byzantine fault tolerance
- Configurable consensus threshold (default: 2/3)
- Weighted voting with reputation
- Parallel verification for performance
- Minimum verifier requirements

### 4. Authorization Chain
- Three-tier mandate system
- Complete chain verification
- Expiration handling at each level
- Revocation support

## Performance Characteristics

### Verification Speed
- Single credential verification: ~500μs
- Multi-agent consensus (5 nodes): ~2ms
- DID resolution (cached): ~100μs
- Complete authorization chain: ~5ms

### Scalability
- Supports 100+ verifier nodes
- Parallel verification execution
- Efficient caching for DID resolution
- Async/await for non-blocking operations

### Resource Usage
- Minimal memory footprint
- No heavy dependencies
- Efficient serialization with serde
- Zero-copy operations where possible

## Testing

### Unit Tests
Run unit tests for individual modules:
```bash
cargo test --package agentic-payments --lib ap2
```

### Integration Tests
Run complete payment flow tests:
```bash
cargo test --package agentic-payments --test ap2_integration_test
```

### Examples
Run example scenarios:
```bash
# Complete payment flow
cargo run --example ap2_payment_flow

# Mandate management
cargo run --example ap2_mandate_management
```

## API Reference

### Main Types

#### `Ap2Protocol`
Main protocol handler for AP2 operations.

Methods:
- `new()` - Create new protocol instance
- `register_agent(id, public_key)` - Register agent identity
- `create_intent_mandate(...)` - Create intent mandate
- `create_cart_mandate(...)` - Create cart mandate
- `create_payment_mandate(...)` - Create payment mandate
- `verify_payment_authorization(...)` - Verify with consensus
- `resolve_did(did)` - Resolve DID to document

#### `VerifiableCredential`
W3C Verifiable Credential with Ed25519 proof.

Methods:
- `new(issuer, subject, private_key)` - Create credential
- `verify(did_resolver)` - Verify signature
- `is_expired()` - Check expiration
- `get_claim(key)` - Get claim value

#### `PaymentAuthorization`
Complete authorization chain for payments.

Methods:
- `new(intent, cart, payment)` - Create authorization
- `verify_chain(did_resolver)` - Verify complete chain
- `is_valid()` - Check if still valid

### Error Types

```rust
pub enum Ap2Error {
    InvalidCredential(String),
    SignatureVerificationFailed(String),
    DidResolutionFailed(String),
    MandateValidationFailed(String),
    ConsensusVerificationFailed(String),
    Expired,
    InsufficientAuthorization(String),
    SerializationError(String),
    CryptographicError(String),
}
```

## Standards Compliance

### W3C Verifiable Credentials
- Context: `https://www.w3.org/2018/credentials/v1`
- Proof type: `Ed25519Signature2020`
- Compliant JSON-LD structure

### W3C Decentralized Identifiers (DID)
- DID method: `did:ap2:`
- Verification method support
- Service endpoint definitions
- Controller relationships

### Ed25519 Signatures
- RFC 8032 compliant
- dalek-cryptography implementation
- Deterministic signing

## Future Enhancements

1. **Additional Signature Schemes**
   - ECDSA support
   - BLS signatures for aggregation
   - Post-quantum signatures

2. **Advanced Features**
   - Revocation lists
   - Delegation chains
   - Time-based restrictions
   - Geographic constraints

3. **Integrations**
   - Payment gateway bridges
   - Blockchain anchoring
   - Hardware security module (HSM) support
   - WASM compilation

4. **Performance**
   - Batch verification
   - Signature aggregation
   - Enhanced caching
   - Distributed consensus

## License

MIT OR Apache-2.0

## Contributing

See the main repository CONTRIBUTING.md for guidelines.

## Support

For issues and questions:
- GitHub Issues: https://github.com/agentic-catalog/agentic-payments/issues
- Documentation: https://docs.agentic-catalog.io/ap2