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
//! Symbolica is a blazing fast computer algebra system.
//!
//! It can be used to perform mathematical operations,
//! such as symbolic differentiation, integration, simplification,
//! pattern matching and solving equations.
//!
//! For example:
//!
//! ```
//! use symbolica::{atom::Atom, state::State};
//!
//! fn main() {
//!     let input = Atom::parse("x^2*log(2*x + y) + exp(3*x)").unwrap();
//!     let a = input.derivative(State::get_symbol("x"));
//!     println!("d({})/dx = {}:", input, a);
//! }
//! ```
//!
//! Check out the [guide](https://symbolica.io/docs/get_started.html) for more information, examples,
//! and additional documentation.

use std::{
    collections::HashMap,
    env,
    io::{Read, Write},
    net::{TcpListener, TcpStream},
    process::abort,
    thread::ThreadId,
    time::{Duration, SystemTime},
};

use colored::Colorize;
use once_cell::sync::OnceCell;
use tinyjson::JsonValue;

mod api;
pub mod atom;
pub mod coefficient;
mod collect;
pub mod combinatorics;
mod derivative;
pub mod domains;
pub mod evaluate;
mod expand;
pub mod id;
mod normalize;
pub mod numerical_integration;
pub mod parser;
pub mod poly;
pub mod printer;
mod solve;
pub mod state;
pub mod streaming;
pub mod tensors;
pub mod transformer;
pub mod utils;

#[cfg(feature = "faster_alloc")]
#[global_allocator]
static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;

static LICENSE_KEY: OnceCell<String> = OnceCell::new();
static LICENSE_MANAGER: OnceCell<LicenseManager> = OnceCell::new();

#[allow(dead_code)]
pub struct LicenseManager {
    lock: Option<TcpListener>,
    core_limit: Option<usize>,
    pid: u32,
    thread_id: ThreadId,
    has_license: bool,
}

const MULTIPLE_INSTANCE_WARNING: &str = "┌───────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Cannot start new unlicensed Symbolica instance since there is already another one running on the machine. │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────┘"
;

const NETWORK_ERROR: &str = "┌────────────────────────────────────────────────┐
│ Could not connect to Symbolica license server. │
│                                                │
│ Please check your network configuration.       │
└────────────────────────────────────────────────┘";

const ACTIVATION_ERROR: &str = "┌──────────────────────────────────────────┐
│ Could not activate the Symbolica license │
└──────────────────────────────────────────┘";

const MISSING_LICENSE_ERROR: &str = "┌───────────────────────────────┐
│ Symbolica license key missing │
└───────────────────────────────┘";

impl Default for LicenseManager {
    fn default() -> Self {
        Self::new()
    }
}

impl LicenseManager {
    pub fn new() -> LicenseManager {
        let pid = std::process::id();
        let thread_id = std::thread::current().id();

        match Self::check_license_key() {
            Ok(()) => {
                return LicenseManager {
                    lock: None,
                    core_limit: None,
                    pid,
                    thread_id,
                    has_license: true,
                };
            }
            Err(e) => {
                eprintln!("{}", e);
            }
        }

        println!(
            "┌────────────────────────────────────────────────────────┐
│ You are running an unlicensed Symbolica instance.      │
│                                                        │
│ This mode is only allowed for non-professional use and │
│ is limited to one instance and core.                   │
│                                                        │
│ {} can easily acquire a free license to unlock  │
│ all cores and to remove this banner:                   │
│                                                        │
│   from symbolica import *                              │
│   request_hobbyist_license('YOUR_NAME', 'YOUR_EMAIL')  │
│                                                        │
│ {} users must obtain an appropriate license, │
│ or can get a free 30-day trial license:                │
│                                                        │
│   from symbolica import *                              │
│   request_trial_license('NAME', 'EMAIL', 'EMPLOYER')   │
│                                                        │
│ See https://symbolica.io/docs/get_started.html#license │
└────────────────────────────────────────────────────────┘",
            "Hobbyists".bold(),
            "Professional".bold(),
        );

        match TcpListener::bind("127.0.0.1:12011") {
            Ok(o) => {
                rayon::ThreadPoolBuilder::new()
                    .num_threads(1)
                    .build_global()
                    .unwrap();

                drop(o);

                std::thread::spawn(|| loop {
                    match TcpListener::bind("127.0.0.1:12011") {
                        Ok(_) => {
                            std::thread::sleep(Duration::from_secs(1));
                        }
                        Err(_) => {
                            println!("{}", MULTIPLE_INSTANCE_WARNING);
                            abort();
                        }
                    }
                });

                LicenseManager {
                    lock: None,
                    core_limit: Some(1),
                    pid,
                    thread_id,
                    has_license: false,
                }
            }
            Err(_) => {
                println!("{}", MULTIPLE_INSTANCE_WARNING);
                abort();
            }
        }
    }

    fn check_license_key() -> Result<(), String> {
        let key = LICENSE_KEY
            .get()
            .cloned()
            .or(env::var("SYMBOLICA_LICENSE").ok());

        let Some(key) = key else {
            return Err(MISSING_LICENSE_ERROR.to_owned());
        };

        if key.contains('@') {
            let mut a = key.split('@');
            let f1 = a.next().unwrap();
            let f2 = a.next().unwrap();
            let f3 = a.next().ok_or_else(|| ACTIVATION_ERROR.to_owned())?;

            let mut h: u32 = 5381;
            for b in f2.as_bytes() {
                h = h.wrapping_mul(33).wrapping_add(*b as u32);
            }
            for b in f3.as_bytes() {
                h = h.wrapping_mul(33).wrapping_add(*b as u32);
            }

            if f1 != h.to_string() {
                Err(ACTIVATION_ERROR.to_owned())?;
            }

            let t = SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap()
                .as_secs();

            let t2 = f2.parse::<u64>().map_err(|_| ACTIVATION_ERROR.to_owned())?;

            if t < t2 || t - t2 > 24 * 60 * 60 {
                Err("┌───────────────────────────────────────────┐
│ The offline Symbolica license has expired │
└───────────────────────────────────────────┘"
                    .to_owned())?;
            }

            return Ok(());
        }

        let Ok(mut stream) = TcpStream::connect("symbolica.io:12012") else {
            return Err(NETWORK_ERROR.to_owned());
        };

        let mut m: HashMap<String, JsonValue> = HashMap::default();
        m.insert(
            "version".to_owned(),
            env!("CARGO_PKG_VERSION").to_owned().into(),
        );
        m.insert("license".to_owned(), key.into());
        let mut v = JsonValue::from(m).stringify().unwrap();
        v.push('\n');

        stream
            .write_all(v.as_bytes())
            .map_err(|e| format!("{}\nError: {}", NETWORK_ERROR, e))?;

        let mut buf = Vec::new();
        stream
            .read_to_end(&mut buf)
            .map_err(|e| format!("{}\nError: {}", NETWORK_ERROR, e))?;
        let read_str =
            std::str::from_utf8(&buf).map_err(|e| format!("{}\nError: {}", NETWORK_ERROR, e))?;

        if read_str == "{\"status\":\"ok\"}\n" {
            Ok(())
        } else if read_str.is_empty() {
            Err("┌──────────────────────────────────────────┐
│ Could not activate the Symbolica license │
└──────────────────────────────────────────┘"
                .to_owned())
        } else {
            let message: JsonValue = read_str[..read_str.len() - 1]
                .parse()
                .map_err(|e| format!("{}\nError: {}", NETWORK_ERROR, e))?;
            let message_parsed: &HashMap<_, _> = message
                .get()
                .ok_or_else(|| format!("{}\nError: Empty response", NETWORK_ERROR))?;
            let status: &String = message_parsed
                .get("status")
                .unwrap()
                .get()
                .ok_or_else(|| format!("{}\nError: missing status", NETWORK_ERROR))?;
            Err(format!(
                "┌──────────────────────────────────────────┐
│ Could not activate the Symbolica license │
└──────────────────────────────────────────┘
Error: {}",
                status,
            ))
        }
    }

    fn check(&self) {
        if self.has_license {
            return;
        }

        let pid = std::process::id();
        let thread_id = std::thread::current().id();

        if self.pid != pid || self.thread_id != thread_id {
            println!("{}", MULTIPLE_INSTANCE_WARNING);
            abort();
        }
    }

    /// Set the license key. Can only be called before calling any other Symbolica functions.
    pub fn set_license_key(key: &str) -> Result<(), String> {
        if LICENSE_KEY.get_or_init(|| key.to_owned()) != key {
            Err("Different license key cannot be set in same session")?;
        }

        Self::check_license_key()
    }

    /// Returns `true` iff this instance has a valid license key set.
    pub fn is_licensed() -> bool {
        Self::check_license_key().is_ok()
    }

    /// Get the current Symbolica version.
    pub fn get_version() -> &'static str {
        env!("SYMBOLICA_VERSION")
    }

    /// Request a key for **non-professional** use for the user `name`, that will be sent to the e-mail address
    /// `email`.
    pub fn request_hobbyist_license(name: &str, email: &str) -> Result<(), String> {
        if let Ok(mut stream) = TcpStream::connect("symbolica.io:12012") {
            let mut m: HashMap<String, JsonValue> = HashMap::default();
            m.insert("name".to_owned(), name.to_owned().into());
            m.insert("email".to_owned(), email.to_owned().into());
            m.insert("type".to_owned(), "hobbyist".to_owned().into());
            let mut v = JsonValue::from(m).stringify().unwrap();
            v.push('\n');

            stream.write_all(v.as_bytes()).unwrap();

            let mut buf = Vec::new();
            stream.read_to_end(&mut buf).unwrap();
            let read_str = std::str::from_utf8(&buf).unwrap();

            if read_str == "{\"status\":\"email sent\"}\n" {
                Ok(())
            } else if read_str.is_empty() {
                Err("Empty response".to_owned())
            } else {
                let message: JsonValue = read_str[..read_str.len() - 1].parse().unwrap();
                let message_parsed: &HashMap<_, _> = message.get().unwrap();
                let status: &String = message_parsed.get("status").unwrap().get().unwrap();
                Err(status.clone())
            }
        } else {
            Err("Could not connect to the license server".to_owned())
        }
    }

    /// Request a key for a trial license for the user `name` working at `company`, that will be sent to the e-mail address
    /// `email`.
    pub fn request_trial_license(name: &str, email: &str, company: &str) -> Result<(), String> {
        if let Ok(mut stream) = TcpStream::connect("symbolica.io:12012") {
            let mut m: HashMap<String, JsonValue> = HashMap::default();
            m.insert("name".to_owned(), name.to_owned().into());
            m.insert("email".to_owned(), email.to_owned().into());
            m.insert("company".to_owned(), company.to_owned().into());
            m.insert("type".to_owned(), "trial".to_owned().into());
            let mut v = JsonValue::from(m).stringify().unwrap();
            v.push('\n');

            stream.write_all(v.as_bytes()).unwrap();

            let mut buf = Vec::new();
            stream.read_to_end(&mut buf).unwrap();
            let read_str = std::str::from_utf8(&buf).unwrap();

            if read_str == "{\"status\":\"email sent\"}\n" {
                Ok(())
            } else if read_str.is_empty() {
                Err("Empty response".to_owned())
            } else {
                let message: JsonValue = read_str[..read_str.len() - 1].parse().unwrap();
                let message_parsed: &HashMap<_, _> = message.get().unwrap();
                let status: &String = message_parsed.get("status").unwrap().get().unwrap();
                Err(status.clone())
            }
        } else {
            Err("Could not connect to the license server".to_owned())
        }
    }

    /// Request a sublicense key for the user `name` working at `company` that has the site-wide license `super_license`.
    /// The key will be sent to the e-mail address `email`.
    pub fn request_sublicense(
        name: &str,
        email: &str,
        company: &str,
        super_license: &str,
    ) -> Result<(), String> {
        if let Ok(mut stream) = TcpStream::connect("symbolica.io:12012") {
            let mut m: HashMap<String, JsonValue> = HashMap::default();
            m.insert("name".to_owned(), name.to_owned().into());
            m.insert("email".to_owned(), email.to_owned().into());
            m.insert("company".to_owned(), company.to_owned().into());
            m.insert("type".to_owned(), "sublicense".to_owned().into());
            m.insert("super_license".to_owned(), super_license.to_owned().into());
            let mut v = JsonValue::from(m).stringify().unwrap();
            v.push('\n');

            stream.write_all(v.as_bytes()).unwrap();

            let mut buf = Vec::new();
            stream.read_to_end(&mut buf).unwrap();
            let read_str = std::str::from_utf8(&buf).unwrap();

            if read_str == "{\"status\":\"email sent\"}\n" {
                Ok(())
            } else if read_str.is_empty() {
                Err("Empty response".to_owned())
            } else {
                let message: JsonValue = read_str[..read_str.len() - 1].parse().unwrap();
                let message_parsed: &HashMap<_, _> = message.get().unwrap();
                let status: &String = message_parsed.get("status").unwrap().get().unwrap();
                Err(status.clone())
            }
        } else {
            Err("Could not connect to the license server".to_owned())
        }
    }

    /// Get a license key for offline use, generated from a licensed Symbolica session. The key will remain valid for 24 hours.
    pub fn get_offline_license_key() -> Result<String, String> {
        if Self::check_license_key().is_err() {
            Err("Cannot request offline license from an unlicensed session".to_owned())?;
        }
        let key = LICENSE_KEY
            .get()
            .cloned()
            .or(env::var("SYMBOLICA_LICENSE").ok());

        let Some(key) = key else {
            return Err(ACTIVATION_ERROR.to_owned());
        };

        if !key.contains('@') {
            let t = SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap()
                .as_secs()
                .to_string();

            let mut h: u32 = 5381;
            for b in t.as_bytes() {
                h = h.wrapping_mul(33).wrapping_add(*b as u32);
            }
            for b in key.as_bytes() {
                h = h.wrapping_mul(33).wrapping_add(*b as u32);
            }

            Ok(format!("{}@{}@{}", h, t, key))
        } else {
            Err("Cannot request offline license key from an offline session".to_owned())
        }
    }
}