tap-msg 0.7.0

Core message processing library for the Transaction Authorization Protocol
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
//! Enum for all TAP message types
//!
//! This module provides an enum that encompasses all TAP message types
//! and functionality to convert from PlainMessage to the appropriate TAP message.

use crate::didcomm::PlainMessage;
use crate::error::{Error, Result};
use crate::message::{
    AddAgents, AuthorizationRequired, Authorize, BasicMessage, Cancel, Capture,
    ConfirmRelationship, Connect, DIDCommPresentation, ErrorBody, Lock, OutOfBand, Payment,
    Presentation, Quote, Reject, RemoveAgent, ReplaceAgent, RequestPresentation, Revert, Rfq,
    Settle, Transfer, TrustPing, TrustPingResponse, UpdateParty, UpdatePolicies,
};
use serde::{Deserialize, Serialize};

/// Enum encompassing all TAP message types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
#[allow(clippy::large_enum_variant)]
pub enum TapMessage {
    /// Add agents message (TAIP-5)
    AddAgents(AddAgents),
    /// Authorize message (TAIP-8)
    Authorize(Authorize),
    /// Authorization required message (TAIP-2)
    AuthorizationRequired(AuthorizationRequired),
    /// Basic message (DIDComm 2.0)
    BasicMessage(BasicMessage),
    /// Cancel message (TAIP-11)
    Cancel(Cancel),
    /// Capture message (TAIP-17)
    Capture(Capture),
    /// Confirm relationship message (TAIP-14)
    ConfirmRelationship(ConfirmRelationship),
    /// Connect message (TAIP-2)
    Connect(Connect),
    /// DIDComm presentation message
    DIDCommPresentation(DIDCommPresentation),
    /// Error message
    Error(ErrorBody),
    /// Lock message (TAIP-17). Formerly known as Escrow; the `Escrow` type
    /// alias still resolves to `Lock`.
    Lock(Lock),
    /// RFQ message (TAIP-18). Formerly known as Exchange; the `Exchange` type
    /// alias still resolves to `Rfq`.
    Rfq(Rfq),
    /// Out of band message (TAIP-2)
    OutOfBand(OutOfBand),
    /// Payment message (TAIP-14)
    Payment(Payment),
    /// Quote message (TAIP-18)
    Quote(Quote),
    /// Presentation message (TAIP-6)
    Presentation(Presentation),
    /// Reject message (TAIP-10)
    Reject(Reject),
    /// Remove agent message (TAIP-5)
    RemoveAgent(RemoveAgent),
    /// Replace agent message (TAIP-5)
    ReplaceAgent(ReplaceAgent),
    /// Request presentation message (TAIP-6)
    RequestPresentation(RequestPresentation),
    /// Revert message (TAIP-12)
    Revert(Revert),
    /// Settle message (TAIP-9)
    Settle(Settle),
    /// Transfer message (TAIP-3)
    Transfer(Transfer),
    /// Trust Ping message (DIDComm 2.0)
    TrustPing(TrustPing),
    /// Trust Ping Response message (DIDComm 2.0)
    TrustPingResponse(TrustPingResponse),
    /// Update party message (TAIP-4)
    UpdateParty(UpdateParty),
    /// Update policies message (TAIP-7)
    UpdatePolicies(UpdatePolicies),
}

impl TapMessage {
    /// Convert a PlainMessage into the appropriate TapMessage variant
    /// based on the message type field
    pub fn from_plain_message(plain_msg: &PlainMessage) -> Result<Self> {
        // Extract the type from either the type_ field or from the body's @type field
        let message_type =
            if !plain_msg.type_.is_empty() && plain_msg.type_ != "application/didcomm-plain+json" {
                &plain_msg.type_
            } else if let Some(body_obj) = plain_msg.body.as_object() {
                if let Some(type_val) = body_obj.get("@type") {
                    type_val.as_str().unwrap_or("")
                } else {
                    ""
                }
            } else {
                ""
            };

        if message_type.is_empty() {
            return Err(Error::Validation(
                "Message type not found in PlainMessage".to_string(),
            ));
        }

        // Parse the message body based on the type
        match message_type {
            "https://tap.rsvp/schema/1.0#AddAgents" => {
                let msg: AddAgents =
                    serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                        Error::SerializationError(format!("Failed to parse AddAgents: {}", e))
                    })?;
                Ok(TapMessage::AddAgents(msg))
            }
            "https://tap.rsvp/schema/1.0#Authorize" => {
                let msg: Authorize =
                    serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                        Error::SerializationError(format!("Failed to parse Authorize: {}", e))
                    })?;
                Ok(TapMessage::Authorize(msg))
            }
            "https://tap.rsvp/schema/1.0#AuthorizationRequired" => {
                let msg: AuthorizationRequired = serde_json::from_value(plain_msg.body.clone())
                    .map_err(|e| {
                        Error::SerializationError(format!(
                            "Failed to parse AuthorizationRequired: {}",
                            e
                        ))
                    })?;
                Ok(TapMessage::AuthorizationRequired(msg))
            }
            "https://didcomm.org/basicmessage/2.0/message" => {
                let msg: BasicMessage =
                    serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                        Error::SerializationError(format!("Failed to parse BasicMessage: {}", e))
                    })?;
                Ok(TapMessage::BasicMessage(msg))
            }
            "https://tap.rsvp/schema/1.0#Cancel" => {
                let msg: Cancel = serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                    Error::SerializationError(format!("Failed to parse Cancel: {}", e))
                })?;
                Ok(TapMessage::Cancel(msg))
            }
            "https://tap.rsvp/schema/1.0#Capture" => {
                let msg: Capture = serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                    Error::SerializationError(format!("Failed to parse Capture: {}", e))
                })?;
                Ok(TapMessage::Capture(msg))
            }
            "https://tap.rsvp/schema/1.0#ConfirmRelationship" => {
                let msg: ConfirmRelationship = serde_json::from_value(plain_msg.body.clone())
                    .map_err(|e| {
                        Error::SerializationError(format!(
                            "Failed to parse ConfirmRelationship: {}",
                            e
                        ))
                    })?;
                Ok(TapMessage::ConfirmRelationship(msg))
            }
            "https://tap.rsvp/schema/1.0#Connect" => {
                let msg: Connect = serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                    Error::SerializationError(format!("Failed to parse Connect: {}", e))
                })?;
                Ok(TapMessage::Connect(msg))
            }
            "https://didcomm.org/present-proof/3.0/presentation" => {
                let msg: DIDCommPresentation = serde_json::from_value(plain_msg.body.clone())
                    .map_err(|e| {
                        Error::SerializationError(format!(
                            "Failed to parse DIDCommPresentation: {}",
                            e
                        ))
                    })?;
                Ok(TapMessage::DIDCommPresentation(msg))
            }
            "https://tap.rsvp/schema/1.0#Error" => {
                let msg: ErrorBody =
                    serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                        Error::SerializationError(format!("Failed to parse Error: {}", e))
                    })?;
                Ok(TapMessage::Error(msg))
            }
            // Both the new `#Lock` URI and the legacy `#Escrow` URI dispatch to
            // `TapMessage::Lock` — `Escrow` is a type alias for `Lock`.
            "https://tap.rsvp/schema/1.0#Lock" | "https://tap.rsvp/schema/1.0#Escrow" => {
                let msg: Lock = serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                    Error::SerializationError(format!("Failed to parse Lock: {}", e))
                })?;
                Ok(TapMessage::Lock(msg))
            }
            // Both the new `#RFQ` URI and the legacy `#Exchange` URI dispatch to
            // `TapMessage::Rfq` — `Exchange` is a type alias for `Rfq`.
            "https://tap.rsvp/schema/1.0#RFQ" | "https://tap.rsvp/schema/1.0#Exchange" => {
                let msg: Rfq = serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                    Error::SerializationError(format!("Failed to parse RFQ: {}", e))
                })?;
                Ok(TapMessage::Rfq(msg))
            }
            "https://tap.rsvp/schema/1.0#OutOfBand" => {
                let msg: OutOfBand =
                    serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                        Error::SerializationError(format!("Failed to parse OutOfBand: {}", e))
                    })?;
                Ok(TapMessage::OutOfBand(msg))
            }
            "https://tap.rsvp/schema/1.0#Payment" => {
                let msg: Payment = serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                    Error::SerializationError(format!("Failed to parse Payment: {}", e))
                })?;
                Ok(TapMessage::Payment(msg))
            }
            "https://tap.rsvp/schema/1.0#Quote" => {
                let msg: Quote = serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                    Error::SerializationError(format!("Failed to parse Quote: {}", e))
                })?;
                Ok(TapMessage::Quote(msg))
            }
            "https://tap.rsvp/schema/1.0#Presentation" => {
                let msg: Presentation =
                    serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                        Error::SerializationError(format!("Failed to parse Presentation: {}", e))
                    })?;
                Ok(TapMessage::Presentation(msg))
            }
            "https://tap.rsvp/schema/1.0#Reject" => {
                let msg: Reject = serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                    Error::SerializationError(format!("Failed to parse Reject: {}", e))
                })?;
                Ok(TapMessage::Reject(msg))
            }
            "https://tap.rsvp/schema/1.0#RemoveAgent" => {
                let msg: RemoveAgent =
                    serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                        Error::SerializationError(format!("Failed to parse RemoveAgent: {}", e))
                    })?;
                Ok(TapMessage::RemoveAgent(msg))
            }
            "https://tap.rsvp/schema/1.0#ReplaceAgent" => {
                let msg: ReplaceAgent =
                    serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                        Error::SerializationError(format!("Failed to parse ReplaceAgent: {}", e))
                    })?;
                Ok(TapMessage::ReplaceAgent(msg))
            }
            "https://tap.rsvp/schema/1.0#RequestPresentation" => {
                let msg: RequestPresentation = serde_json::from_value(plain_msg.body.clone())
                    .map_err(|e| {
                        Error::SerializationError(format!(
                            "Failed to parse RequestPresentation: {}",
                            e
                        ))
                    })?;
                Ok(TapMessage::RequestPresentation(msg))
            }
            "https://tap.rsvp/schema/1.0#Revert" => {
                let msg: Revert = serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                    Error::SerializationError(format!("Failed to parse Revert: {}", e))
                })?;
                Ok(TapMessage::Revert(msg))
            }
            "https://tap.rsvp/schema/1.0#Settle" => {
                let msg: Settle = serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                    Error::SerializationError(format!("Failed to parse Settle: {}", e))
                })?;
                Ok(TapMessage::Settle(msg))
            }
            "https://tap.rsvp/schema/1.0#Transfer" => {
                let msg: Transfer =
                    serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                        Error::SerializationError(format!("Failed to parse Transfer: {}", e))
                    })?;
                Ok(TapMessage::Transfer(msg))
            }
            "https://tap.rsvp/schema/1.0#UpdateParty" => {
                let msg: UpdateParty =
                    serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                        Error::SerializationError(format!("Failed to parse UpdateParty: {}", e))
                    })?;
                Ok(TapMessage::UpdateParty(msg))
            }
            "https://tap.rsvp/schema/1.0#UpdatePolicies" => {
                let msg: UpdatePolicies =
                    serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                        Error::SerializationError(format!("Failed to parse UpdatePolicies: {}", e))
                    })?;
                Ok(TapMessage::UpdatePolicies(msg))
            }
            "https://didcomm.org/trust-ping/2.0/ping" => {
                let msg: TrustPing =
                    serde_json::from_value(plain_msg.body.clone()).map_err(|e| {
                        Error::SerializationError(format!("Failed to parse TrustPing: {}", e))
                    })?;
                Ok(TapMessage::TrustPing(msg))
            }
            "https://didcomm.org/trust-ping/2.0/ping-response" => {
                let msg: TrustPingResponse = serde_json::from_value(plain_msg.body.clone())
                    .map_err(|e| {
                        Error::SerializationError(format!(
                            "Failed to parse TrustPingResponse: {}",
                            e
                        ))
                    })?;
                Ok(TapMessage::TrustPingResponse(msg))
            }
            _ => Err(Error::Validation(format!(
                "Unknown message type: {}",
                message_type
            ))),
        }
    }

    /// Get the message type string for this TapMessage
    pub fn message_type(&self) -> &'static str {
        match self {
            TapMessage::AddAgents(_) => "https://tap.rsvp/schema/1.0#AddAgents",
            TapMessage::Authorize(_) => "https://tap.rsvp/schema/1.0#Authorize",
            TapMessage::AuthorizationRequired(_) => {
                "https://tap.rsvp/schema/1.0#AuthorizationRequired"
            }
            TapMessage::BasicMessage(_) => "https://didcomm.org/basicmessage/2.0/message",
            TapMessage::Cancel(_) => "https://tap.rsvp/schema/1.0#Cancel",
            TapMessage::Capture(_) => "https://tap.rsvp/schema/1.0#Capture",
            TapMessage::ConfirmRelationship(_) => "https://tap.rsvp/schema/1.0#ConfirmRelationship",
            TapMessage::Connect(_) => "https://tap.rsvp/schema/1.0#Connect",
            TapMessage::DIDCommPresentation(_) => {
                "https://didcomm.org/present-proof/3.0/presentation"
            }
            TapMessage::Error(_) => "https://tap.rsvp/schema/1.0#Error",
            TapMessage::Lock(_) => "https://tap.rsvp/schema/1.0#Lock",
            TapMessage::Rfq(_) => "https://tap.rsvp/schema/1.0#RFQ",
            TapMessage::OutOfBand(_) => "https://tap.rsvp/schema/1.0#OutOfBand",
            TapMessage::Payment(_) => "https://tap.rsvp/schema/1.0#Payment",
            TapMessage::Quote(_) => "https://tap.rsvp/schema/1.0#Quote",
            TapMessage::Presentation(_) => "https://tap.rsvp/schema/1.0#Presentation",
            TapMessage::Reject(_) => "https://tap.rsvp/schema/1.0#Reject",
            TapMessage::RemoveAgent(_) => "https://tap.rsvp/schema/1.0#RemoveAgent",
            TapMessage::ReplaceAgent(_) => "https://tap.rsvp/schema/1.0#ReplaceAgent",
            TapMessage::RequestPresentation(_) => "https://tap.rsvp/schema/1.0#RequestPresentation",
            TapMessage::Revert(_) => "https://tap.rsvp/schema/1.0#Revert",
            TapMessage::Settle(_) => "https://tap.rsvp/schema/1.0#Settle",
            TapMessage::Transfer(_) => "https://tap.rsvp/schema/1.0#Transfer",
            TapMessage::TrustPing(_) => "https://didcomm.org/trust-ping/2.0/ping",
            TapMessage::TrustPingResponse(_) => "https://didcomm.org/trust-ping/2.0/ping-response",
            TapMessage::UpdateParty(_) => "https://tap.rsvp/schema/1.0#UpdateParty",
            TapMessage::UpdatePolicies(_) => "https://tap.rsvp/schema/1.0#UpdatePolicies",
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_parse_transfer_body() {
        let body = json!({
            "@type": "https://tap.rsvp/schema/1.0#Transfer",
            "transaction_id": "test-tx-123",
            "asset": "eip155:1/slip44:60",
            "originator": {
                "@id": "did:example:alice"
            },
            "amount": "100",
            "agents": [],
            "metadata": {}
        });

        match serde_json::from_value::<Transfer>(body.clone()) {
            Ok(transfer) => {
                println!("Successfully parsed Transfer: {:?}", transfer);
                assert_eq!(transfer.amount, "100");
            }
            Err(e) => {
                panic!("Failed to parse Transfer: {}", e);
            }
        }
    }

    #[test]
    fn test_from_plain_message_transfer() {
        let plain_msg = PlainMessage {
            id: "test-123".to_string(),
            typ: "application/didcomm-plain+json".to_string(),
            type_: "https://tap.rsvp/schema/1.0#Transfer".to_string(),
            body: json!({
                "@type": "https://tap.rsvp/schema/1.0#Transfer",
                "transaction_id": "test-tx-456",
                "asset": "eip155:1/slip44:60",
                "originator": {
                    "@id": "did:example:alice"
                },
                "amount": "100",
                "agents": [],
                "metadata": {}
            }),
            from: "did:example:alice".to_string(),
            to: vec!["did:example:bob".to_string()],
            thid: None,
            pthid: None,
            created_time: Some(1234567890),
            expires_time: None,
            from_prior: None,
            attachments: None,
            extra_headers: Default::default(),
        };

        let tap_msg = TapMessage::from_plain_message(&plain_msg).unwrap();

        match tap_msg {
            TapMessage::Transfer(transfer) => {
                assert_eq!(transfer.amount, "100");
                assert_eq!(
                    transfer.originator.as_ref().unwrap().id,
                    "did:example:alice"
                );
            }
            _ => panic!("Expected Transfer message"),
        }
    }

    #[test]
    fn test_message_type() {
        let transfer = Transfer {
            asset: "eip155:1/slip44:60".parse().unwrap(),
            originator: Some(crate::message::Party::new("did:example:alice")),
            beneficiary: None,
            amount: "100".to_string(),
            agents: vec![],
            memo: None,
            settlement_id: None,
            expiry: None,
            transaction_value: None,
            connection_id: None,
            transaction_id: Some("tx-123".to_string()),
            metadata: Default::default(),
        };

        let tap_msg = TapMessage::Transfer(transfer);
        assert_eq!(
            tap_msg.message_type(),
            "https://tap.rsvp/schema/1.0#Transfer"
        );
    }
}