google_wallet/
firebase_wallet.rs

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
use base64::{engine::general_purpose, Engine};
use dioxus_oauth::prelude::FirebaseService;
use gloo_storage::{errors::StorageError, LocalStorage, Storage};
use ring::{
    rand::SystemRandom,
    signature::{Ed25519KeyPair, KeyPair, Signature},
};
use simple_asn1::{
    oid, to_der,
    ASN1Block::{BitString, ObjectIdentifier, Sequence},
};

pub const IDENTITY_KEY: &str = "identity";

#[derive(Debug, Clone)]
pub struct FirebaseWallet {
    pub principal: Option<String>,
    pub firebase: FirebaseService,
    pub private_key: Option<String>,
    pub public_key: Option<Vec<u8>>,
    pub pkcs8: Option<Vec<u8>>,

    pub email: Option<String>,
    pub name: Option<String>,
    pub photo_url: Option<String>,
}

impl FirebaseWallet {
    pub fn new(
        api_key: String,
        auth_domain: String,
        project_id: String,
        storage_bucket: String,
        messaging_sender_id: String,
        app_id: String,
        measurement_id: String,
    ) -> Self {
        let firebase = FirebaseService::new(
            api_key,
            auth_domain,
            project_id,
            storage_bucket,
            messaging_sender_id,
            app_id,
            measurement_id,
        );

        Self {
            firebase,
            principal: None,
            private_key: None,
            public_key: None,
            pkcs8: None,

            email: None,
            name: None,
            photo_url: None,
        }
    }

    pub fn get_login(&self) -> bool {
        self.principal.is_some()
    }

    pub fn get_principal(&self) -> String {
        let public_key = self.public_key.clone().unwrap_or_default();

        let id_ed25519 = oid!(1, 3, 101, 112);
        let algorithm = Sequence(0, vec![ObjectIdentifier(0, id_ed25519)]);
        let subject_public_key = BitString(0, public_key.len() * 8, public_key);
        let subject_public_key_info = Sequence(0, vec![algorithm, subject_public_key]);
        let der_public_key = to_der(&subject_public_key_info).unwrap();
        let wallet_address = candid::Principal::self_authenticating(der_public_key);
        wallet_address.to_text()
    }

    pub fn get_user_info(&self) -> Option<(String, String, String)> {
        if self.email.is_none() || self.name.is_none() || self.photo_url.is_none() {
            return None;
        }

        Some((
            self.email.clone().unwrap(),
            self.name.clone().unwrap(),
            self.photo_url.clone().unwrap(),
        ))
    }

    pub fn try_setup_from_storage(&mut self) -> Option<String> {
        if self.get_login() {
            return self.principal.clone();
        }

        tracing::debug!("try_setup_from_storage");
        let key: Result<String, StorageError> = LocalStorage::get(IDENTITY_KEY);
        tracing::debug!("key from storage: {key:?}");

        if let Ok(private_key) = key {
            tracing::debug!("private_key: {private_key}");
            self.try_setup_from_private_key(private_key)
        } else {
            None
        }
    }

    pub async fn request_wallet_with_google(&mut self) -> Result<WalletEvent, String> {
        use crate::drive_api::DriveApi;

        let cred = self
            .firebase
            .sign_in_with_popup(vec![
                "https://www.googleapis.com/auth/drive.appdata".to_string()
            ])
            .await;
        tracing::debug!("cred: {cred:?}");
        let cli = DriveApi::new(cred.access_token);
        let data = match cli.list_files().await {
            Ok(v) => v,
            Err(e) => {
                tracing::error!("failed to get file {e}");
                return Err(format!("{e:?}"));
            }
        };
        tracing::debug!("data: {data:?}");

        let (evt, pkcs8) = match data
            .iter()
            .find(|x| x.name == option_env!("ENV").unwrap_or("local").to_string())
        {
            Some(v) => match cli.get_file(&v.id).await {
                Ok(v) => {
                    tracing::debug!("file content: {v}");

                    (WalletEvent::Login, v)
                    // self.try_setup_from_private_key(v);

                    // return Ok(WalletEvent::Login);
                }
                Err(e) => {
                    tracing::warn!("failed to get file {e}");

                    return Err("failed to get file".to_string());
                }
            },
            None => {
                tracing::warn!("file not found");
                let rng = SystemRandom::new();

                let key_pair = Ed25519KeyPair::generate_pkcs8(&rng).unwrap();
                let private_key = general_purpose::STANDARD.encode(key_pair.as_ref());

                if let Err(e) = cli.upload_file(&private_key).await {
                    tracing::error!("failed to upload file {e}");
                    return Err("failed to upload file".to_string());
                };

                (WalletEvent::Signup, private_key)
            }
        };

        self.try_setup_from_private_key(pkcs8);
        self.name = Some(cred.display_name);
        self.email = Some(cred.email);
        self.photo_url = Some(cred.photo_url);

        Ok(evt)
    }

    pub fn sign(&self, msg: &str) -> Option<Signature> {
        tracing::debug!("sign: {msg}");
        let key_pair = self.get_identity()?;

        Some(key_pair.sign(msg.as_bytes()))
    }

    pub fn public_key(&self) -> Option<Vec<u8>> {
        let key_pair = self.get_identity()?;

        Some(key_pair.public_key().as_ref().to_vec())
    }

    pub fn try_setup_from_private_key(&mut self, private_key: String) -> Option<String> {
        match general_purpose::STANDARD.decode(&private_key) {
            Ok(key) => {
                tracing::debug!("key setup");
                self.private_key = Some(private_key.clone());
                if let Some(key_pair) = self.init_or_get_identity(Some(key.as_ref())) {
                    self.public_key = Some(key_pair.public_key().as_ref().to_vec());
                    self.principal = Some(self.get_principal());
                    tracing::debug!("wallet initialized");
                }
            }
            Err(e) => {
                tracing::error!("Decode Error: {e}");

                return None;
            }
        };

        use gloo_storage::Storage;
        let _ = gloo_storage::LocalStorage::set(IDENTITY_KEY, private_key);

        Some(self.get_principal())
    }

    pub fn init_or_get_identity(&mut self, pkcs8: Option<&[u8]>) -> Option<Ed25519KeyPair> {
        if self.pkcs8.is_none() && pkcs8.is_some() {
            self.pkcs8 = Some(pkcs8.unwrap().to_vec());
        }

        self.get_identity()
    }

    pub fn get_identity(&self) -> Option<Ed25519KeyPair> {
        if let Some(pkcs8) = &self.pkcs8 {
            let key = ring::signature::Ed25519KeyPair::from_pkcs8(pkcs8)
                .expect("Could not read the key pair.");
            Some(key)
        } else {
            None
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum WalletEvent {
    Login,
    Signup,
    Logout,
}