rings-core 0.10.0

Chord DHT implementation with ICE
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
#![warn(missing_docs)]
//! Understanding Abstract Account and Session keypair in Rings Network
//!
//! Rings network offers a unique mechanism to bolster security and abstract the user's keypair through a feature known as session keypair.
//! The fundamental concept behind session keypair is signing a generated keypair with a time period {ts, ttl} by user without access its private key in this program.
//! This can be conceptualized as a contract stating, "I delegate to a keypair for the time period {ts, ttl}".
//!
//! In our terminology:
//! - `I` is [Account].
//! - `keypair` is [SessionSk].
//! - The time period {ts, ttl} is in `SessionSk.session` field.
//!
//! The following is an example to build a [SessionSk] in Rust and use it to sign a message.
//! It is not necessary to construct a secret_key in Rust.
//! User may manually set account_type, account_entity, and session_sig, instead of provide secret key.
//! ```
//! use rings_core::dht::Did;
//! use rings_core::session::SessionSkBuilder;
//!
//! // We are generate an ethereum account for example.
//! // It's convenient because secp256k1 is also used in session_sk.
//! let user_secret_key = rings_core::ecc::SecretKey::random();
//! let user_secret_key_did: Did = user_secret_key.address().into();
//!
//! // The account type is "secp256k1".
//! // The account entity is its address, also known as Did in rings network.
//! let account_type = "secp256k1".to_string();
//! let account_entity = user_secret_key_did.to_string();
//!
//! let builder = SessionSkBuilder::new(account_entity, account_type);
//! let unsigned_proof = builder.unsigned_proof();
//!
//! // Sign the unsigned proof with user's secret key.
//! let session_sig = user_secret_key.sign(&unsigned_proof).to_vec();
//! let builder = builder.set_session_sig(session_sig);
//!
//! let session_sk = builder.build().unwrap();
//!
//! // Check session_sk is valid. (The verify_self is already called in build().)
//! assert_eq!(session_sk.account_did(), user_secret_key_did);
//! assert!(session_sk.session().verify_self().is_ok());
//!
//! // Sign a message with session_sk.
//! let msg = "hello world".as_bytes();
//! let msg_sig = session_sk.sign(msg).unwrap();
//! let msg_session = session_sk.session();
//!
//! // Verify the message with session.
//! assert_eq!(msg_session.account_did(), user_secret_key_did);
//! assert!(msg_session.verify(msg, msg_sig).is_ok());
//! ```
//!
//! [SessionSkBuilder], [SessionSk] is exported to wasm envirement.
//! To build a [SessionSk] in javascript:
//! ```js
//!    // prepare auth & send to metamask for sign
//!    let sessionBuilder = SessionSkBuilder.new(account, 'eip191')
//!    let unsignedSession = sessionBuilder.unsigned_proof()
//!    const { signed } = await sendMessage(
//!      'sign-message',
//!      {
//!        auth: unsignedSession,
//!      },
//!      'popup'
//!    )
//!    const signature = new Uint8Array(hexToBytes(signed))
//!    sessionBuilder = sessionBuilder.set_session_sig(signature)
//!    let sessionSk: SessionSk = sessionBuilder.build()
//! ```

//!
//! See [SessionSk] and [SessionSkBuilder] for details.

use std::str::FromStr;

use rings_derive::wasm_export;
use serde::Deserialize;
use serde::Serialize;

use crate::consts::DEFAULT_SESSION_TTL_MS;
use crate::dht::Did;
use crate::ecc::keccak256;
use crate::ecc::keys::AccountVerifier;
use crate::ecc::keys::SignatureAlgorithm;
use crate::ecc::keys::VerificationPublicKey;
use crate::ecc::signers;
use crate::ecc::PublicKey;
use crate::ecc::SecretKey;
use crate::error::Error;
use crate::error::Result;
use crate::utils;

fn pack_session(session_id: Did, ts_ms: u128, ttl_ms: u64) -> String {
    format!("{session_id}\n{ts_ms}\n{ttl_ms}")
}

/// SessionSkBuilder is used to build a [SessionSk].
///
/// Firstly, you need to provide the account's entity and type to [SessionSkBuilder::new] method.
/// Then you can call `pack_session` to get the session dump for signing.
/// After signing, you can call `sig` to set the signature back to builder.
/// Finally, you can call `build` to get the [SessionSk].
#[wasm_export]
pub struct SessionSkBuilder {
    sk: SecretKey,
    /// Account of session.
    account_entity: String,
    /// Account of session.
    account_type: String,
    /// Session's lifetime
    ttl_ms: u64,
    /// Timestamp when session created
    ts_ms: u128,
    /// Signature of session
    sig: Vec<u8>,
}

/// SessionSk holds the [Session] and its session private key.
/// To prove that the message was sent by the [Account] of [Session],
/// we need to attach session and the signature signed by sk to the payload.
///
/// SessionSk provide a `session` method to clone the session.
/// SessionSk also provide `sign` method to sign a message.
///
/// To verify the session, use `verify_self()` method of [Session].
/// To verify a message, use `verify(msg, sig)` method of [Session].
#[wasm_export]
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct SessionSk {
    /// Session
    session: Session,
    /// The private key of session. Used for signing and decrypting.
    sk: SecretKey,
}

/// Session is used to verify the message.
/// It's serializable and can be attached to the message payload.
///
/// To verify the session is provided by the account, use session.verify_self().
/// To verify the message, use session.verify(msg, sig).
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]
pub struct Session {
    /// Did of session, this is hash of sessionPk
    session_id: Did,
    /// Account of session
    account: Account,
    /// Session's lifetime
    ttl_ms: u64,
    /// Timestamp when session created
    ts_ms: u128,
    /// Signature to verify that the session was signed by the account.
    sig: Vec<u8>,
}

/// We will support as many protocols/algorithms as possible.
/// Currently, it comprises Secp256k1, EIP191, BIP137, Ed25519, and BLS12-381.
/// We welcome any issues and PRs for additional implementations.
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]
pub enum Account {
    /// ecdsa
    Secp256k1(Did),
    /// ref: <https://eips.ethereum.org/EIPS/eip-191>
    Secp256r1(PublicKey<33>),
    /// ref: <https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API>
    EIP191(Did),
    /// bitcoin bip137 ref: <https://github.com/bitcoin/bips/blob/master/bip-0137.mediawiki>
    BIP137(Did),
    /// ed25519
    Ed25519(PublicKey<33>),
    /// bls12-381
    Bls12381(PublicKey<48>),
}

impl TryFrom<(String, String)> for Account {
    type Error = Error;

    fn try_from((account_entity, account_type): (String, String)) -> Result<Self> {
        match AccountVerifier::from_account_parts(&account_entity, &account_type)? {
            AccountVerifier::Recoverable {
                algorithm: SignatureAlgorithm::Secp256k1,
                did,
            } => Ok(Account::Secp256k1(did)),
            AccountVerifier::Recoverable {
                algorithm: SignatureAlgorithm::Eip191,
                did,
            } => Ok(Account::EIP191(did)),
            AccountVerifier::Recoverable {
                algorithm: SignatureAlgorithm::Bip137,
                did,
            } => Ok(Account::BIP137(did)),
            AccountVerifier::PublicKey(VerificationPublicKey::Secp256r1(pk)) => {
                Ok(Account::Secp256r1(pk))
            }
            AccountVerifier::PublicKey(VerificationPublicKey::Ed25519(pk)) => {
                Ok(Account::Ed25519(pk))
            }
            AccountVerifier::PublicKey(VerificationPublicKey::Bls12381(pk)) => {
                Ok(Account::Bls12381(pk))
            }
            _ => Err(Error::UnknownAccount),
        }
    }
}

impl Account {
    fn account_verifier(&self) -> AccountVerifier {
        match self {
            Self::Secp256k1(did) => AccountVerifier::Recoverable {
                algorithm: SignatureAlgorithm::Secp256k1,
                did: *did,
            },
            Self::EIP191(did) => AccountVerifier::Recoverable {
                algorithm: SignatureAlgorithm::Eip191,
                did: *did,
            },
            Self::BIP137(did) => AccountVerifier::Recoverable {
                algorithm: SignatureAlgorithm::Bip137,
                did: *did,
            },
            Self::Secp256r1(pk) => {
                AccountVerifier::PublicKey(VerificationPublicKey::Secp256r1(*pk))
            }
            Self::Ed25519(pk) => AccountVerifier::PublicKey(VerificationPublicKey::Ed25519(*pk)),
            Self::Bls12381(pk) => AccountVerifier::PublicKey(VerificationPublicKey::Bls12381(*pk)),
        }
    }
}

// A SessionSk can be converted to a string using JSON and then encoded with base58.
// To load the SessionSk from a string, use `SessionSk::from_str`.
impl FromStr for SessionSk {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        let s = base58_monero::decode_check(s).map_err(|_| Error::Decode)?;
        let session_sk: SessionSk = serde_json::from_slice(&s).map_err(Error::Deserialize)?;
        Ok(session_sk)
    }
}

#[wasm_export]
impl SessionSkBuilder {
    /// Create a new SessionSkBuilder.
    /// The "account_type" is lower case of [Account] variant.
    /// The "account_entity" refers to the entity that is encapsulated by the [Account] variant, in string format.
    pub fn new(account_entity: String, account_type: String) -> SessionSkBuilder {
        let sk = SecretKey::random();
        Self {
            sk,
            account_entity,
            account_type,
            ttl_ms: DEFAULT_SESSION_TTL_MS,
            ts_ms: utils::get_epoch_ms(),
            sig: vec![],
        }
    }

    /// This is a helper method to let user know if the account params is valid.
    pub fn validate_account(&self) -> bool {
        Account::try_from((self.account_entity.clone(), self.account_type.clone()))
            .map_err(|e| {
                tracing::warn!("validate_account error: {:?}", e);
                e
            })
            .is_ok()
    }

    /// Construct unsigned_info string for signing.
    pub fn unsigned_proof(&self) -> String {
        pack_session(self.sk.address().into(), self.ts_ms, self.ttl_ms)
    }

    /// Set the signature of session that signed by account.
    pub fn set_session_sig(mut self, sig: Vec<u8>) -> Self {
        self.sig = sig;
        self
    }

    /// Set the lifetime of session.
    pub fn set_ttl(mut self, ttl_ms: u64) -> Self {
        self.ttl_ms = ttl_ms;
        self
    }

    /// Build the [SessionSk].
    pub fn build(self) -> Result<SessionSk> {
        let account = Account::try_from((self.account_entity, self.account_type))?;
        let session = Session {
            session_id: self.sk.address().into(),
            account,
            ttl_ms: self.ttl_ms,
            ts_ms: self.ts_ms,
            sig: self.sig,
        };

        session.verify_self()?;

        Ok(SessionSk {
            session,
            sk: self.sk,
        })
    }
}

impl Session {
    /// Pack the session into a string for verification or public key recovery.
    pub fn pack(&self) -> Vec<u8> {
        pack_session(self.session_id, self.ts_ms, self.ttl_ms)
            .as_bytes()
            .to_vec()
    }

    /// Check session is expired or not.
    pub fn is_expired(&self) -> bool {
        let now = utils::get_epoch_ms();
        now > self.ts_ms + self.ttl_ms as u128
    }

    /// Verify session.
    pub fn verify_self(&self) -> Result<()> {
        if self.is_expired() {
            return Err(Error::SessionExpired);
        }

        let auth_bytes = self.pack();

        if !self
            .account
            .account_verifier()
            .verify(&auth_bytes, &self.sig)
        {
            return Err(Error::VerifySignatureFailed);
        }

        Ok(())
    }

    /// Verify message.
    pub fn verify(&self, msg: &[u8], sig: impl AsRef<[u8]>) -> Result<()> {
        self.verify_self()?;
        if !signers::secp256k1::verify(msg, &self.session_id, sig) {
            return Err(Error::VerifySignatureFailed);
        }
        Ok(())
    }

    /// Get legacy secp256k1-compatible account public key.
    ///
    /// Use `account_verification_pubkey` for typed account verification keys.
    pub fn account_pubkey(&self) -> Result<PublicKey<33>> {
        match self.account_verification_pubkey()? {
            VerificationPublicKey::Secp256k1(pk)
            | VerificationPublicKey::Eip191(pk)
            | VerificationPublicKey::Bip137(pk) => Ok(pk),
            VerificationPublicKey::Secp256r1(_)
            | VerificationPublicKey::Ed25519(_)
            | VerificationPublicKey::Bls12381(_) => Err(Error::UnknownAccount),
        }
    }

    /// Get typed account verification public key from session proof.
    pub fn account_verification_pubkey(&self) -> Result<VerificationPublicKey> {
        self.account
            .account_verifier()
            .verification_key_from_signature(&self.pack(), &self.sig)
    }

    /// Get typed account verifier.
    pub fn account_verifier(&self) -> AccountVerifier {
        self.account.account_verifier()
    }

    /// Get account did.
    pub fn account_did(&self) -> Did {
        self.account.account_verifier().did()
    }
}

impl SessionSk {
    /// Generate Session with private key. Only use it for unittest.
    /// To protect your private key, please use [SessionSkBuilder] to generate session.
    pub fn new_with_seckey(key: &SecretKey) -> Result<Self> {
        let account_entity = Did::from(key.address()).to_string();
        let account_type = "secp256k1".to_string();

        let mut builder = SessionSkBuilder::new(account_entity, account_type);

        let sig = key.sign(&builder.unsigned_proof());
        builder = builder.set_session_sig(sig.to_vec());

        builder.build()
    }

    /// Get session from SessionSk.
    pub fn session(&self) -> Session {
        self.session.clone()
    }

    /// Sign message with session.
    pub fn sign(&self, msg: &[u8]) -> Result<Vec<u8>> {
        let key = self.sk;
        let h = keccak256(msg);
        Ok(signers::secp256k1::sign(key, &h).to_vec())
    }

    /// Get account did from session.
    pub fn account_did(&self) -> Did {
        self.session.account_did()
    }

    /// Get typed account verifier from session.
    pub fn account_verifier(&self) -> AccountVerifier {
        self.session.account_verifier()
    }

    /// Dump session_sk to string, allowing user to save it in a config file.
    /// It can be restored using `SessionSk::from_str`.
    pub fn dump(&self) -> Result<String> {
        let s = serde_json::to_string(&self).map_err(|_| Error::SerializeError)?;
        base58_monero::encode_check(s.as_bytes()).map_err(|_| Error::Encode)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::ecc::keys::SigningSecretKey;

    #[test]
    pub fn test_session_verify() {
        let key = SecretKey::random();
        let sm = SessionSk::new_with_seckey(&key).unwrap();
        let session = sm.session();
        assert!(session.verify_self().is_ok());
    }

    #[test]
    pub fn test_account_pubkey() {
        let key = SecretKey::random();
        let sm = SessionSk::new_with_seckey(&key).unwrap();
        let session = sm.session();
        let pubkey = session.account_pubkey().unwrap();
        assert_eq!(key.pubkey(), pubkey);
    }

    #[test]
    pub fn test_session_verify_secp256r1_account_key() {
        let account_entity = "17a6afd392fcbe4ac9270a599a9c5732c4f838ce35ea2234d389d8f0c367f3f5dcab906352e27289002c7f2c96039ddce7c1b5aad8b87ba94984d4c8b4f95702";
        let account_key = VerificationPublicKey::Secp256r1(
            PublicKey::<33>::from_hex_string(account_entity).unwrap(),
        );
        let signing_key =
            SecretKey::try_from("2544acda37415a476d42312969926dc48e529867036cec71922d4177ea9c1038")
                .unwrap();
        let mut builder =
            SessionSkBuilder::new(account_entity.to_string(), "secp256r1".to_string());
        let proof = builder.unsigned_proof();
        let sig =
            signers::secp256r1::sign(signing_key, &signers::secp256r1::hash(proof.as_bytes()))
                .unwrap();
        builder = builder.set_session_sig(sig.to_vec());

        let session = builder.build().unwrap().session();
        assert_eq!(session.account_verification_pubkey().unwrap(), account_key);
        assert_eq!(session.account_did(), account_key.did());
        assert!(session.verify_self().is_ok());
        assert!(session.account_pubkey().is_err());
    }

    #[test]
    pub fn test_session_rejects_invalid_secp256r1_account_key() {
        let mut invalid_key = None;
        for i in 0u8..=u8::MAX {
            let mut key = [0u8; 33];
            key[0] = 2;
            key[32] = i;
            let public_key = PublicKey(key);
            let verifying_key = public_key.ct_try_into_secp256r1_pubkey();
            if !bool::from(verifying_key.is_some()) || verifying_key.unwrap().is_err() {
                invalid_key = Some(key);
                break;
            }
        }
        let account_entity = hex::encode(invalid_key.expect("at least one invalid P-256 x"));
        let builder = SessionSkBuilder::new(account_entity, "secp256r1".to_string())
            .set_session_sig(vec![0u8; 64]);

        assert!(!builder.validate_account());
        assert!(builder.build().is_err());
    }

    #[test]
    pub fn test_session_verify_bls12381_account_key() {
        let signing_key = SigningSecretKey::random_bls12381().unwrap();
        let account_key = signing_key.public_key().unwrap();
        let VerificationPublicKey::Bls12381(raw_account_key) = account_key else {
            unreachable!("random_bls12381 returns a BLS verification key");
        };
        let account_entity = base58_monero::encode_check(&raw_account_key.0).unwrap();
        let mut builder = SessionSkBuilder::new(account_entity, "bls12-381".to_string());
        let proof = builder.unsigned_proof();
        builder = builder.set_session_sig(signing_key.sign_raw(proof.as_bytes()).unwrap());

        let session = builder.build().unwrap().session();
        assert_eq!(
            session.account_verification_pubkey().unwrap(),
            VerificationPublicKey::Bls12381(raw_account_key)
        );
        assert_eq!(session.account_did(), account_key.did());
        assert!(session.verify_self().is_ok());
        assert!(session.account_pubkey().is_err());
    }

    #[test]
    pub fn test_session_verify_ed25519_account_key() {
        let signing_key = SigningSecretKey::random_ed25519();
        let account_key = signing_key.public_key().unwrap();
        let VerificationPublicKey::Ed25519(raw_account_key) = account_key else {
            unreachable!("random_ed25519 returns an Ed25519 verification key");
        };
        let account_entity = raw_account_key.to_base58_string().unwrap();
        let mut builder = SessionSkBuilder::new(account_entity, "ed25519".to_string());
        let proof = builder.unsigned_proof();
        builder = builder.set_session_sig(signing_key.sign_raw(proof.as_bytes()).unwrap());

        let session = builder.build().unwrap().session();
        assert_eq!(
            session.account_verification_pubkey().unwrap(),
            VerificationPublicKey::Ed25519(raw_account_key)
        );
        assert_eq!(session.account_did(), account_key.did());
        assert!(session.verify_self().is_ok());
        assert!(session.account_pubkey().is_err());
    }

    #[test]
    pub fn test_dump_restore() {
        let key = SecretKey::random();
        let sm = SessionSk::new_with_seckey(&key).unwrap();
        let dump = sm.dump().unwrap();
        let sm2 = SessionSk::from_str(&dump).unwrap();
        assert_eq!(sm, sm2);
    }
}