gxt 4.1.0

Minimal, encrypted, signed and copy-pasteable tokens for manual data exchange between games
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
//! # GXT (Game Exchange Token)
//!
//! Minimal, encrypted, signed and copy-pasteable tokens for manual data exchange between games.
//!
//! For details check out [`spec.md`](https://github.com/hardliner66/gxt/blob/main/spec.md).
//!
//! **Note:**
//! This is intended to be used as a base for mods to exchange data in a secure way.
//! The protocol only handles the data exchange part. It is on the integrator to ensure
//! that the the correct actions take place inside the game. For trades, it is recommended
//! to remove the offered items from the inventory of the player when the trade is created
//! in order to avoid people offering items and then giving them away before the trade is completed.
//!
//! Its also recommended to save the game state after a trade is created in order to avoid save scumming.
//! You should also store the ID of a trade so that it can be verified that a message was in response to
//! that ID. When responding to a message, make sure you set the parent field to the ID of the message you're
//! responding to. Otherwise there is no way to verify the message chain.
//!
//! You might also want to store some lightweight meta data for the trade request. For instance the
//! identifiers of the items that were taken away. This way they can be given back when the other player
//! cancels a trade. The trade result defined in the advisory module contains data from the original request
//! that can be used to give items back or to award the items from the fulfillment.

#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![allow(clippy::similar_names)]

use std::{fmt, str::FromStr};

use chacha20poly1305::aead::{Aead, KeyInit};
use chacha20poly1305::{Key, XChaCha20Poly1305, XNonce};
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use rand::RngCore;
use rand::rngs::OsRng;
use serde::Deserialize;
use serde::{Serialize, de::DeserializeOwned};
use serde_cbor::Value as CborValue;
use thiserror::Error;
use x25519_dalek::{PublicKey as XPublicKey, StaticSecret as XSecret};

pub use serde_json::{Value as JsonValue, from_value, json, to_value};

/// Helper function to deserialize strings into json values
pub fn value_from_str(s: &str) -> Result<JsonValue, serde_json::Error> {
    serde_json::from_str(s)
}

/// Helper function to serialize json values into strings
pub fn value_to_string(value: &JsonValue) -> Result<String, serde_json::Error> {
    serde_json::to_string(value)
}

/// Helper function to serialize arbitrary values, that implement the `Serialize` trait, into strings
pub fn to_json<T: Serialize>(value: &T) -> Result<String, serde_json::Error> {
    serde_json::to_string(value)
}

/// Helper function to serialize arbitrary values, that implement the `Serialize` trait, into strings
/// and format it nicely
pub fn to_json_pretty<T: Serialize>(value: &T) -> Result<String, serde_json::Error> {
    serde_json::to_string_pretty(value)
}

/// Helper function to deserialize a string into an arbitrary value, that implement the `Serialize` trait
pub fn from_json<T: DeserializeOwned>(s: &str) -> Result<T, serde_json::Error> {
    serde_json::from_str(s)
}

/// The advisory module contains simple structures that can be used as a base for implementing trades.
///
/// If you need need more features or different shapes of data, feel free to use your own instead.
///
/// **Important:**
/// These data structures might not be compatible with those defined for other languages.
/// Normally, this should not be a problem because a mod is normally only written in one language,
/// but if you have a use-case with more than one language, you need to keep this in mind.
pub mod advisory;

const PREFIX: &str = "gx";
const SIGNATURE_DOMAIN: &[u8] = b"GXT";
const VERSION: u8 = 4;

type Bytes32 = [u8; 32];
type Bytes64 = [u8; 64];

#[derive(Error, Debug)]
/// Errors that can occur while encoding, decoding, compressing,
/// or verifying GXT tokens.
pub enum GxtError {
    #[error("bad prefix")]
    /// The message must start with the prefix "gxt:"
    BadPrefix,
    #[error("decode error: {0}")]
    /// Base58 decoding failed
    Decode(#[from] bs58::decode::Error),
    /// Compression or decompression failed
    #[error("decompress error: {0}")]
    Compression(#[from] std::io::Error),
    /// Encryption or decryption failed
    #[error("encrypt error: {0}")]
    Encryption(String),
    /// CBOR serialization failed
    #[error("cbor error: {0}")]
    Cbor(#[from] serde_cbor::Error),
    /// JSON serialization failed
    #[error("json error: {0}")]
    Json(#[from] serde_json::Error),
    /// The signature is wrong
    #[error("invalid signature")]
    BadSig,
    /// The id is wrong
    #[error("invalid id")]
    BadId,
    /// A hex value contains invalid characters
    #[error("bad hex")]
    BadHex(#[from] hex::FromHexError),
    /// A hex has the wrong size
    #[error("invalid hex size. expected {expected} got {got}")]
    InvalidHexSize {
        /// The expected hex size
        expected: usize,
        /// The hex size we got
        got: usize,
    },
    /// The specified key can not decrypt this message
    #[error("access denied")]
    AccessDenied,
    /// The structure message is invalid
    #[error("invalid record")]
    Invalid,
    /// Received an unknown payload kind
    #[error("unknown payload kind")]
    UnknownPayloadKind,
}

/// What kind of payload was sent
#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, Eq)]
pub enum PayloadKind {
    /// ID card
    Id,
    /// Message
    Msg,
    /// A key packaged into a gxt token
    Key,
}

impl FromStr for PayloadKind {
    type Err = GxtError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim() {
            "i" => Ok(PayloadKind::Id),
            "m" => Ok(PayloadKind::Msg),
            "k" => Ok(PayloadKind::Key),
            _ => Err(GxtError::UnknownPayloadKind),
        }
    }
}

impl fmt::Display for PayloadKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Id => write!(f, "id"),
            Self::Msg => write!(f, "msg"),
            Self::Key => write!(f, "key"),
        }
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
/// Parsed, verified GXT record.
///
/// Represents a decoded token after signature verification and/or decryption.
#[serde(bound(serialize = "P: Serialize", deserialize = "P: Deserialize<'de>"))]
pub struct Envelope<P> {
    /// Version
    pub version: u8,
    /// Verification Key
    pub verification_key: String,
    /// Public Key
    pub encryption_key: String,
    /// Payload Kind
    pub kind: PayloadKind,
    /// Opaque Payload
    pub payload: P,
    /// Id of the Parent Message
    pub parent: Option<String>,
    /// Id of this Message
    pub id: String,
    /// Signature of this Message
    pub signature: String,
}

impl<P: Serialize + DeserializeOwned> fmt::Display for Envelope<P> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "valid           : true")?;
        writeln!(f, "version         : {}", self.version)?;
        writeln!(
            f,
            "parent          : {}",
            self.parent.as_ref().map_or_else(
                || "-".to_string(),
                |parent| format!("{} ({})", parent, &parent[..8])

            )
        )?;
        writeln!(f, "id              : {} ({})", self.id, &self.id[..8])?;
        writeln!(
            f,
            "verification key: {} ({})",
            self.verification_key,
            &self.verification_key[..8]
        )?;
        writeln!(
            f,
            "encryption key  : {} ({})",
            self.encryption_key,
            &self.encryption_key[..8]
        )?;
        writeln!(f, "kind            : {}", self.kind)?;
        writeln!(f, "payload:")?;
        writeln!(
            f,
            "{}",
            serde_json::to_string_pretty(&self.payload).map_err(|_| fmt::Error)?
        )?;
        Ok(())
    }
}

/// The kind of key
pub enum KeyKind {
    /// Plain text, no gxt token around it
    Raw,
    /// Gxt encoded
    Gxt,
}

/// Creates a private key for a peer.
pub fn make_key() -> String {
    let key = SigningKey::generate(&mut OsRng);
    let key_json = serde_json::to_value(&key).expect("Should never happen.");
    make(
        &key,
        PayloadKind::Key,
        serde_cbor::value::to_value(&key_json).expect("Should never happen."),
        None,
    )
    .expect("Should never happen.")
}

/// Creates an ID card containing the necessary data for
/// the encrypted communication and some opaque meta data.
///
/// # Errors
/// - returns a corresponding [`GxtError`], depending on what went wrong.
pub fn make_id_card<M: Serialize + DeserializeOwned>(
    key: &str,
    meta: M,
) -> Result<String, GxtError> {
    let key = parse_key(key.trim())?;
    make(
        &key,
        PayloadKind::Id,
        serde_cbor::value::to_value(meta)?,
        None,
    )
}

/// Verify the signature of a message and return a parsed [`Envelope`].
///
/// # Errors
/// - returns a corresponding [`GxtError`], depending on what went wrong.
pub fn verify_message<P: Serialize + DeserializeOwned>(msg: &str) -> Result<Envelope<P>, GxtError> {
    let msg = msg.trim();
    let (kind, msg) = get_kind(msg)?;
    let raw = decode_message(msg)?;
    let envelope_cbor: CborValue = serde_cbor::from_slice(&raw)?;

    let arr = match envelope_cbor {
        CborValue::Array(a) if a.len() == 7 => a,
        _ => return Err(GxtError::Invalid),
    };

    let mut values = arr.into_iter();

    let version = match values.next() {
        Some(CborValue::Integer(i)) if i == VERSION.into() => VERSION,
        _ => return Err(GxtError::Invalid),
    };
    let verification_key_bytes = match values.next() {
        Some(CborValue::Text(t)) => parse_hex::<32>(&t)?,
        _ => return Err(GxtError::Invalid),
    };
    let encryption_key = match values.next() {
        Some(CborValue::Text(t)) => parse_hex::<32>(&t)?,
        _ => return Err(GxtError::Invalid),
    };
    let payload = match values.next() {
        Some(payload) => payload.clone(),
        _ => return Err(GxtError::Invalid),
    };
    let parent = match values.next() {
        Some(CborValue::Text(t)) if !t.is_empty() => Some(parse_hex::<32>(&t)?),
        Some(CborValue::Text(_)) => None,
        _ => return Err(GxtError::Invalid),
    };
    let id = match values.next() {
        Some(CborValue::Text(t)) => parse_hex::<32>(&t)?,
        _ => return Err(GxtError::Invalid),
    };
    let signature_bytes = match values.next() {
        Some(CborValue::Text(t)) => parse_hex::<64>(&t)?,
        _ => return Err(GxtError::Invalid),
    };

    let canonical =
        get_canonical_representation(&verification_key_bytes, &encryption_key, payload.clone())?;
    let expect = blake3::hash(&canonical);
    if id != *expect.as_bytes() {
        return Err(GxtError::BadId);
    }

    let verification_key =
        VerifyingKey::from_bytes(&verification_key_bytes).map_err(|_| GxtError::Invalid)?;
    let signature = Signature::from_bytes(&signature_bytes);
    verification_key
        .verify_strict(&preimage(&canonical), &signature)
        .map_err(|_| GxtError::BadSig)?;

    Ok(Envelope {
        version,
        verification_key: hex::encode(verification_key_bytes),
        encryption_key: hex::encode(encryption_key),
        parent: parent.map(hex::encode),
        kind,
        payload: serde_cbor::value::from_value(payload)?,
        id: hex::encode(id),
        signature: hex::encode(signature_bytes),
    })
}

/// Create an **encrypted** message for the owner of the
/// ID card that was passed in.
///
/// # Errors
/// - returns a corresponding [`GxtError`], depending on what went wrong.
pub fn encrypt_message<P: Serialize + DeserializeOwned>(
    key: &str,
    id_card: &str,
    payload: &P,
    parent: Option<String>,
) -> Result<String, GxtError> {
    let id_card = verify_message::<CborValue>(id_card.trim())?;
    let their_encryption_key = parse_hex::<32>(&id_card.encryption_key)?;
    let key = parse_key(key.trim())?;
    let (my_secret_key, _my_encryption_key) = derive_enc_from_signing(&key);
    let encryption_key = enc_derive_key_from_pairs(&my_secret_key, &their_encryption_key);
    let cipher = XChaCha20Poly1305::new(&encryption_key);
    let mut nonce_bytes = [0u8; 24];
    OsRng.fill_bytes(&mut nonce_bytes);
    let nonce = XNonce::from_slice(&nonce_bytes);
    let plaintext = serde_cbor::to_vec(&payload)?;
    let cipher_text = cipher
        .encrypt(nonce, plaintext.as_ref())
        .map_err(|e| GxtError::Encryption(e.to_string()))?;

    let mut message = std::collections::BTreeMap::new();
    message.insert(
        CborValue::Text("to".into()),
        CborValue::Text(hex::encode(their_encryption_key)),
    );
    let mut encrypted_message = std::collections::BTreeMap::new();
    encrypted_message.insert(
        CborValue::Text("alg".into()),
        CborValue::Text("xchacha20poly1305".into()),
    );
    encrypted_message.insert(
        CborValue::Text("n24".into()),
        CborValue::Text(hex::encode(nonce_bytes)),
    );
    encrypted_message.insert(
        CborValue::Text("ct".into()),
        CborValue::Text(hex::encode(&cipher_text)),
    );
    message.insert(
        CborValue::Text("enc".into()),
        CborValue::Map(encrypted_message),
    );
    let payload = CborValue::Map(message);
    make(
        &key,
        PayloadKind::Msg,
        payload,
        parent.map(|parent| parse_hex::<32>(&parent)).transpose()?,
    )
}

/// Verify the signature of a message, decrypt its payload and return a parsed [`Envelope`].
///
/// # Errors
/// - returns a corresponding [`GxtError`], depending on what went wrong.
pub fn decrypt_message<P: Serialize + DeserializeOwned>(
    message: &str,
    key: &str,
) -> Result<Envelope<P>, GxtError> {
    let mut envelope = verify_message::<CborValue>(message.trim())?;

    let key = parse_key(key)?;
    let CborValue::Map(map) = &envelope.payload else {
        return Err(GxtError::Invalid);
    };
    let to = match map.get(&CborValue::Text("to".into())) {
        Some(CborValue::Text(t)) => parse_hex::<32>(t)?,
        _ => return Err(GxtError::Invalid),
    };
    let Some(CborValue::Map(encm)) = map.get(&CborValue::Text("enc".into())) else {
        return Err(GxtError::Invalid);
    };
    let nonce = match encm.get(&CborValue::Text("n24".into())) {
        Some(CborValue::Text(t)) => parse_hex::<24>(t)?,
        _ => return Err(GxtError::Invalid),
    };
    let cipher_text = match encm.get(&CborValue::Text("ct".into())) {
        Some(CborValue::Text(t)) => hex::decode(t)?,
        _ => return Err(GxtError::Invalid),
    };

    let (my_secret_key, my_encryption_key) = derive_enc_from_signing(&key);
    if to != my_encryption_key {
        return Err(GxtError::AccessDenied);
    }

    let key = enc_derive_key_from_pairs(&my_secret_key, &parse_hex(&envelope.encryption_key)?);
    let cipher = XChaCha20Poly1305::new(&key);
    let nonce = XNonce::from_slice(&nonce);
    let plaintext = cipher
        .decrypt(nonce, cipher_text.as_ref())
        .map_err(|e| GxtError::Encryption(e.to_string()))?;
    envelope.payload = serde_cbor::from_slice(&plaintext)?;

    Ok(Envelope {
        version: envelope.version,
        verification_key: envelope.verification_key,
        encryption_key: envelope.encryption_key,
        kind: envelope.kind,
        payload: serde_cbor::value::from_value(envelope.payload)?,
        parent: envelope.parent,
        id: envelope.id,
        signature: envelope.signature,
    })
}

#[allow(clippy::too_many_arguments)]
fn cbor_array(
    verification_key: &Bytes32,
    encryption_key: &Bytes32,
    payload: CborValue,
    parent: Option<Bytes32>,
    id: Option<&Bytes32>,
    signature: Option<&Bytes64>,
) -> Result<Vec<u8>, GxtError> {
    let envelope_values = CborValue::Array(vec![
        CborValue::Integer(VERSION.into()),
        CborValue::Text(hex::encode(verification_key)),
        CborValue::Text(hex::encode(encryption_key)),
        payload,
        CborValue::Text(parent.map(hex::encode).unwrap_or_default()),
        CborValue::Text(id.map(hex::encode).unwrap_or_default()),
        CborValue::Text(signature.map(hex::encode).unwrap_or_default()),
    ]);
    Ok(serde_cbor::to_vec(&envelope_values)?)
}

fn get_canonical_representation(
    verification_key: &Bytes32,
    encryption_key: &Bytes32,
    payload: CborValue,
) -> Result<Vec<u8>, GxtError> {
    cbor_array(verification_key, encryption_key, payload, None, None, None)
}

fn preimage(canonical: &[u8]) -> Vec<u8> {
    let mut v = Vec::with_capacity(SIGNATURE_DOMAIN.len() + canonical.len());
    v.extend_from_slice(SIGNATURE_DOMAIN);
    v.extend_from_slice(canonical);
    v
}

fn make(
    key: &SigningKey,
    kind: PayloadKind,
    payload: CborValue,
    parent: Option<Bytes32>,
) -> Result<String, GxtError> {
    let verification_key = key.verifying_key().to_bytes();
    let (_, encryption_key) = derive_enc_from_signing(key);
    let canonical =
        get_canonical_representation(&verification_key, &encryption_key, payload.clone())?;

    let id = blake3::hash(&canonical);
    let signature = key.sign(&preimage(&canonical));

    encode_message(
        &verification_key,
        &encryption_key,
        kind,
        payload,
        parent,
        id.as_bytes(),
        &signature.to_bytes(),
    )
}

fn make_prefix(kind: PayloadKind) -> String {
    format!(
        "{PREFIX}{}:",
        match kind {
            PayloadKind::Id => "i",
            PayloadKind::Msg => "m",
            PayloadKind::Key => "k",
        }
    )
}

#[allow(clippy::too_many_arguments)]
fn encode_message(
    verification_key: &Bytes32,
    encryption_key: &Bytes32,
    kind: PayloadKind,
    payload: CborValue,
    parent: Option<Bytes32>,
    id: &Bytes32,
    signature: &Bytes64,
) -> Result<String, GxtError> {
    let envelope_cbor = cbor_array(
        verification_key,
        encryption_key,
        payload,
        parent,
        Some(id),
        Some(signature),
    )?;
    let compressed_message = zstd::encode_all(&envelope_cbor[..], 3)?;
    Ok(format!(
        "{}{}",
        make_prefix(kind),
        bs58::encode(compressed_message).into_string()
    ))
}

fn get_kind(message: &str) -> Result<(PayloadKind, &str), GxtError> {
    let rest = message.strip_prefix(PREFIX).ok_or(GxtError::BadPrefix)?;
    let (left, right) = rest.split_once(':').ok_or(GxtError::BadPrefix)?;
    Ok((PayloadKind::from_str(left)?, right))
}

fn decode_message(message: &str) -> Result<Vec<u8>, GxtError> {
    let compressed_message = bs58::decode(message).into_vec()?;
    let raw = zstd::decode_all(&compressed_message[..])?;
    Ok(raw)
}

fn parse_hex<const SIZE: usize>(hex_string: &str) -> Result<[u8; SIZE], GxtError> {
    let unsized_hex = hex::decode(hex_string)?;

    let got = unsized_hex.len();
    let hex: [u8; SIZE] = unsized_hex
        .try_into()
        .map_err(|_| GxtError::InvalidHexSize {
            expected: SIZE,
            got,
        })?;
    Ok(hex)
}

fn parse_key(key: &str) -> Result<SigningKey, GxtError> {
    if key.starts_with(PREFIX) {
        let token = verify_message::<JsonValue>(key.trim())?;
        Ok(from_value(token.payload)?)
    } else {
        Ok(SigningKey::from_bytes(&parse_hex::<32>(key)?))
    }
}

fn derive_enc_from_signing(key: &SigningKey) -> (Bytes32, Bytes32) {
    let seed = key.to_bytes();
    let derived_key = blake3::derive_key("GXT-ENC-X25519-FROM-ED25519", &seed);
    let secret_key = XSecret::from(derived_key);
    let encryption_key = XPublicKey::from(&secret_key);
    (secret_key.to_bytes(), encryption_key.to_bytes())
}

fn enc_derive_key_from_pairs(my_secret_key: &Bytes32, their_encryption_key: &Bytes32) -> Key {
    let key = XSecret::from(*my_secret_key);
    let verification_key = XPublicKey::from(*their_encryption_key);
    let shared = key.diffie_hellman(&verification_key);
    let derived_key = blake3::derive_key("GXT-ENC-XCHACHA20POLY1305", shared.as_bytes());
    Key::from_slice(&derived_key).to_owned()
}