tap-node 0.7.0

Transaction Authorization Protocol (TAP) node implementation for routing and processing messages
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
477
478
479
480
481
482
483
484
# TAP Node Event System Documentation

## Overview

The TAP Node event system provides a comprehensive event-driven architecture for monitoring and reacting to various activities within the node. It implements a publish-subscribe pattern with support for both callback-based and channel-based subscriptions.

## Event Types

The TAP Node defines the following event categories and types:

### 1. Message Events

#### `PlainMessageReceived` (Deprecated)
- **Description**: Legacy event for backward compatibility
- **Data**: 
  - `message`: The received message as a JSON Value
- **Note**: Use `MessageReceived` instead for new implementations
- **Use Cases**:
  - Monitoring and logging received messages
  - Triggering follow-up actions based on message content
  - Auditing message flow through the system

#### `PlainMessageSent`
- **Description**: Triggered when a message is sent from one agent to another
- **Data**:
  - `message`: The sent message as a JSON Value
  - `from`: The DID of the sending agent
  - `to`: The DID of the receiving agent
- **Use Cases**:
  - Tracking message delivery
  - Analyzing communication patterns
  - Generating message delivery receipts

### 2. Agent Lifecycle Events

#### `AgentRegistered`
- **Description**: Triggered when a new agent is registered with the node
- **Data**:
  - `did`: The DID of the registered agent
- **Use Cases**:
  - Tracking agent lifecycle
  - Initializing resources for new agents
  - Notifying other components of new agent availability

#### `AgentUnregistered`
- **Description**: Triggered when an agent is removed from the node
- **Data**:
  - `did`: The DID of the unregistered agent
- **Use Cases**:
  - Cleanup of resources associated with the agent
  - Notifying other components of agent removal
  - Updating routing tables

### 3. Resolution Events

#### `DidResolved`
- **Description**: Triggered when the node attempts to resolve a DID
- **Data**:
  - `did`: The DID that was resolved
  - `success`: Whether the resolution was successful
- **Use Cases**:
  - Monitoring resolution failures
  - Caching resolution results
  - Diagnostics and debugging

### 4. Raw Message Events

#### `AgentPlainMessage`
- **Description**: Contains raw binary message data intended for a specific agent
- **Data**:
  - `did`: The DID of the target agent
  - `message`: The raw binary message data (Vec<u8>)
- **Use Cases**:
  - Direct message delivery to agents
  - Integration with transport-specific mechanisms
  - Binary protocol support

### 5. Message Validation Events

#### `MessageRejected`
- **Description**: Triggered when a message fails validation checks
- **Data**:
  - `message_id`: The ID of the rejected message
  - `reason`: The reason for rejection
  - `from`: The DID of the sender
  - `to`: The DID of the intended recipient
- **Use Cases**:
  - Monitoring validation failures
  - Alerting on suspicious activity
  - Debugging message flow issues

#### `MessageAccepted`
- **Description**: Triggered when a message passes all validation checks
- **Data**:
  - `message_id`: The ID of the accepted message
  - `message_type`: The type of the message
  - `from`: The DID of the sender
  - `to`: The DID of the recipient
- **Use Cases**:
  - Tracking successful message flow
  - Updating message status in database
  - Triggering downstream processing

### 6. Reply Events

#### `ReplyReceived`
- **Description**: Triggered when a reply is received for a previously sent message
- **Data**:
  - `original_message_id`: The ID of the original message
  - `reply_message`: The reply message
  - `original_message`: The original message being replied to
- **Use Cases**:
  - Correlating request/response pairs
  - Tracking conversation flow
  - Implementing timeout handling

### 7. Transaction State Events

#### `TransactionStateChanged`
- **Description**: Triggered when a transaction transitions from one state to another
- **Data**:
  - `transaction_id`: The ID of the transaction
  - `old_state`: The previous state
  - `new_state`: The new state
  - `agent_did`: The DID of the agent that triggered the change (optional)
- **Use Cases**:
  - Monitoring transaction lifecycle
  - Triggering state-specific actions
  - Auditing state transitions

### 8. Enhanced Message Events

#### `MessageReceived`
- **Description**: Triggered when a message is received from a specific source
- **Data**:
  - `message`: The received PlainMessage object
  - `source`: The source identifier (e.g., "https", "internal", "websocket")
- **Use Cases**:
  - Source-aware message processing
  - Transport-specific handling
  - Security auditing by source

#### `MessageSent`
- **Description**: Triggered when a message is sent to a specific destination
- **Data**:
  - `message`: The sent PlainMessage object
  - `destination`: The destination identifier
- **Use Cases**:
  - Destination-aware delivery tracking
  - Transport selection
  - Delivery confirmation

### 9. Transaction Management Events

#### `TransactionCreated`
- **Description**: Triggered when a new transaction is created in the system
- **Data**:
  - `transaction`: The complete transaction data from storage
  - `agent_did`: The DID of the agent that created the transaction
- **Use Cases**:
  - Customer data extraction
  - Compliance reporting
  - Transaction monitoring

### 10. Customer Management Events

#### `CustomerUpdated`
- **Description**: Triggered when customer information is created or updated
- **Data**:
  - `customer_id`: The unique customer identifier
  - `agent_did`: The DID of the agent that owns the customer
  - `update_type`: The type of update ("created", "updated", "verified")
- **Use Cases**:
  - Customer lifecycle tracking
  - KYC/AML monitoring
  - Data synchronization

=======
>>>>>>> origin/main
## Event Handlers

### 1. EventLogger

**Purpose**: Provides comprehensive logging of all node events to various destinations.

**Configuration**:
```rust
EventLoggerConfig {
    destination: LogDestination::File {
        path: "./logs/tap-node.log".to_string(),
        max_size: Some(10 * 1024 * 1024), // 10 MB
        rotate: true,
    },
    structured: true,  // JSON format
    log_level: log::Level::Info,
}
```

**Destination Options**:
- `Console`: Logs to standard output
- `File`: Logs to a file with optional rotation
- `Custom`: Custom logging function

**Features**:
- Plain text or structured JSON output
- Automatic file rotation
- Configurable log levels
- Thread-safe operation

### 2. MessageStatusHandler

**Purpose**: Updates message status in the database based on validation results.

**Database Integration**:
- Updates the `messages` table
- Sets status to "accepted" or "rejected"
- Handles database errors gracefully

**Subscribed Events**:
- `MessageAccepted` → Updates status to "accepted"
- `MessageRejected` → Updates status to "rejected"

### 3. TransactionStateHandler

**Purpose**: Maintains transaction state consistency in the database.

**Database Integration**:
- Updates the `transactions` table
- Maps event states to database statuses:
  - "pending" → pending
  - "confirmed" → confirmed
  - "failed" → failed
  - "cancelled" → cancelled
  - "reverted" → reverted

**Subscribed Events**:
- `TransactionStateChanged`

### 4. TransactionAuditHandler

**Purpose**: Provides detailed audit logging for compliance and debugging.

**Features**:
- Logs all transaction state transitions
- Includes agent DIDs when available
- Provides human-readable audit trail
- Helps with debugging transaction flows

**Subscribed Events**:
- `TransactionStateChanged`
- `MessageAccepted`
- `MessageRejected`
- `ReplyReceived`

### 5. TrustPingResponseHandler

**Purpose**: Handles automatic Trust Ping response delivery.

**Operation**:
1. Monitors `PlainMessageSent` events
2. Filters for Trust Ping response messages
3. Serializes and sends responses via configured sender
4. Logs delivery success/failure

**Integration**:
- Works with `TrustPingProcessor` for automatic responses
- Supports various message senders (HTTP, WebSocket)

### 6. CustomerEventHandler

**Purpose**: Automatically extracts and manages customer data from TAP messages.

**Features**:
- Extracts party information from Transfer messages
- Updates customer records from UpdateParty messages
- Manages relationships from ConfirmRelationship messages
- Generates IVMS101-compatible data structures
- **Automatically registered for each agent** when the agent is registered with the node

**Subscribed Events**:
- `MessageReceived` → Processes incoming Transfer, UpdateParty, and ConfirmRelationship messages
- `MessageSent` → Processes outgoing messages for customer data
- `TransactionCreated` → Extracts customer data from new transactions

**Database Integration**:
- Creates/updates customer records
- Manages customer relationships
- Stores IVMS101 compliance data
- Maintains customer metadata
- Uses agent-specific storage for data isolation

**Operation**:
1. Automatically created when an agent is registered with `node.register_agent()`
2. Monitors message events for relevant TAP message types
3. Extracts party information (originator, beneficiary, agents)
4. Creates or updates customer records with extracted data
5. Establishes relationships between customers and agents
6. Stores compliance-relevant information for reporting in agent-specific database

**Automatic Registration**:
The CustomerEventHandler is now automatically registered for each agent during the agent registration process. This ensures that:
- Each agent has its own customer data handler
- Customer data is properly isolated in agent-specific databases
- No manual configuration is needed for customer data extraction

=======
>>>>>>> origin/main
## Event Processing Workflows

### Trust Ping Workflow

```
1. Incoming Trust Ping → TrustPingProcessor
2. Generate response → Publish PlainMessageSent event
3. TrustPingResponseHandler catches event
4. Response sent via configured sender
```

<<<<<<< HEAD
### Customer Data Extraction Workflow

```
1. Transfer/Payment message received → MessageReceived event
2. CustomerEventHandler processes message
3. Extract party information (originator, beneficiary)
4. Create/update customer records
5. CustomerUpdated event published
6. Relationships established between parties
```

=======
>>>>>>> origin/main
### Message Validation Workflow

```
1. Message received → ValidationProcessor
2. Validation passes → MessageAccepted event
   OR
   Validation fails → MessageRejected event
3. MessageStatusHandler updates database
```

### Transaction State Machine Workflow

```
1. Transfer/Payment received → Create transaction
2. TransactionCreated event published
3. CustomerEventHandler extracts customer data
4. Authorize received → TransactionStateChanged event
5. All agents authorized → Generate Settle message
6. TransactionStateHandler updates database
7. TransactionAuditHandler logs transition
```

## Subscription Models

### 1. Callback-based Subscriptions

Implement the `EventSubscriber` trait:

```rust
#[async_trait]
impl EventSubscriber for MyHandler {
    async fn handle_event(&self, event: NodeEvent) {
        match event {
            NodeEvent::MessageReceived { message } => {
                // Handle received message
            },
            _ => {}
        }
    }
}

// Subscribe
event_bus.subscribe(Arc::new(MyHandler)).await;
```

### 2. Channel-based Subscriptions

Use broadcast channels for async processing:

```rust
let mut receiver = event_bus.subscribe_channel();

tokio::spawn(async move {
    while let Ok(event) = receiver.recv().await {
        // Process event
    }
});
```

## Best Practices

### 1. Handler Design
- Keep handlers lightweight and non-blocking
- Spawn separate tasks for long-running operations
- Handle errors gracefully without panicking
- Use appropriate logging levels
- Consider data privacy when logging customer information

### 2. Event Publishing
- Use the provided convenience methods on EventBus
- Include all relevant data in events
- Consider event ordering implications
- Avoid publishing events from within handlers (prevent loops)
- Use specific event types (MessageReceived vs PlainMessageReceived) for clarity

### 3. Performance Considerations
- The event bus uses a broadcast channel with capacity 100
- Slow subscribers can cause backpressure
- Consider using channel-based subscriptions for heavy processing
- Monitor event processing latency

### 4. Error Handling
- Handlers should not panic on errors
- Log errors appropriately
- Consider retry logic for transient failures
- Maintain system stability despite handler failures

## Configuration Example

```rust
use tap_node::{NodeConfig, TapNode};
use tap_node::event::logger::{EventLogger, EventLoggerConfig, LogDestination};

// Configure node with event logging
let config = NodeConfig {
    event_logger: Some(EventLoggerConfig {
        destination: LogDestination::File {
            path: "./logs/tap-node.log".to_string(),
            max_size: Some(10 * 1024 * 1024),
            rotate: true,
        },
        structured: true,
        log_level: log::Level::Info,
    }),
    ..Default::default()
};

// Create node - event handlers are automatically set up
let mut node = TapNode::new(config);
node.init_storage().await?;
<<<<<<< HEAD

// Note: CustomerEventHandler is now automatically registered for each agent
// when the agent is registered with the node, so manual registration is no longer needed
=======
>>>>>>> origin/main
```

## Extending the Event System

To add new event types:

1. Add variant to `NodeEvent` enum
2. Add publishing method to `EventBus`
3. Update existing handlers if needed
4. Document the new event type
<<<<<<< HEAD
5. Consider backward compatibility with legacy events
=======
>>>>>>> origin/main

To add new handlers:

1. Implement `EventSubscriber` trait
2. Subscribe to the event bus
3. Handle relevant events
4. Add error handling and logging
<<<<<<< HEAD
5. Test with various event scenarios
6. Consider performance impact for high-frequency events

## Event Type Migration Guide

The TAP Node event system has evolved to provide more specific and feature-rich events:

- `PlainMessageReceived` → `MessageReceived` (includes source information)
- `PlainMessageSent` → `MessageSent` (includes destination information)

Legacy events are maintained for backward compatibility but new implementations should use the enhanced event types for better tracking and monitoring capabilities.
=======
5. Test with various event scenarios
>>>>>>> origin/main