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 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
/* * This file is part of ids_service * * ids_service is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * ids_service is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ids_service. If not, see <http://www.gnu.org/licenses/> */ //! Library that allows generating unique ids. It tried to keep cache filled using background threads //! to fill it. //! If the cache is empty (the number of requests is too high) an id is calculated on the fly. //! This will slow down obtaining the id but there is no error when the cache is empty. //! To generate unique ids the library uses an array of bytes with values from a random number generator //! and a timestamp as nanoseconds since January 1, 1970 UTC and finally create an hash from both data's. //! The size of random block is equal to the size of hash sha512 = 64 bytes. //! The size of data block to calculate an unique id using sha512 equal 64 bytes random + 8 bytes timestamp. //! //! The hash algorithm can be one from crypto::sha3::Sha3Mode //! The id can be: //! * Vec<u8> //! * String encoded hexadecimal lower case //! * String as Base64 //! * String as Base32 //! //! # Quick Start //! ``` //! extern crate ids_service; //! //! use crate::ids_service::crypto_hash::{Encode,IdsService}; //! //! fn main() { //! //! /* //! * Create an ids service with: //! * Cache size = 10'000 //! * hash algo. = sha512 //! * A pool of 20 threads //! */ //! let mut ids = IdsService::default(); //! ids.start(); //! println!("Get an id: {}", ids.get_id().as_hex()); //! println!("Get another id: {}", ids.get_id().as_base64()); //! println!("Current numbers of items in cache: {}", ids.get_cache_len()); //! //! } //! ``` //! //! ``` //! extern crate ids_service; //! //! use crate::ids_service::crypto_hash::*; //! //! fn main() { //! //! println!("Create an id sha512 without the service: {}", create_id_as_sha512()); //! println!("Create an id sha256 without the service: {}", create_id_as_sha256()); //! //! } //! ``` //! The lib use simplelog see for configuration: //! [crates.io Rust Package Registry SimpleLog ](https://crates.io/crates/simplelog). extern crate chrono; extern crate crypto; extern crate data_encoding; extern crate log; extern crate rand; extern crate simplelog; /// Module using crypto. hash pub mod crypto_hash { use chrono::prelude::*; use crypto::digest::Digest; use crypto::sha3::Sha3; use crypto::sha3::Sha3Mode; use data_encoding::{BASE64, HEXLOWER,BASE32,BASE64URL}; use log::*; use rand::prelude::*; use std::collections::VecDeque; use std::sync::{mpsc, Arc, Mutex}; use std::thread; const NUMBER_OF_FILL_THREAD: usize = 20; /// Struct for internal use of IdsService pub struct IdsService { ids_cache: Arc<Mutex<VecDeque<Vec<u8>>>>, cache_size: usize, rand_length: usize, mode: Sha3Mode, sender: Option<mpsc::Sender<usize>>, thread_counter: Arc<Mutex<i32>>, number_of_threads: usize, } /// /// Allow to create an instance using default parameters: /// * hash algorithm : Sha3_512 /// * cache size: 10'000 items /// * number of threads: 20 impl Default for IdsService { fn default() -> Self { let mode = Sha3Mode::Sha3_512; let cache_size = 10000 as usize; IdsService { ids_cache: Arc::new(Mutex::new(VecDeque::with_capacity(cache_size))), rand_length: mode.digest_length(), cache_size, mode, sender: None, thread_counter: Arc::new(Mutex::new(0i32)), number_of_threads : NUMBER_OF_FILL_THREAD, } } } /// Trait to define possible encoding output. pub trait Encode : Sized { fn as_hex(&self)-> String { unimplemented!() } fn as_base64(&self)-> String { unimplemented!() } fn as_base64_url(&self)-> String { unimplemented!() } fn as_base32(&self)-> String { unimplemented!() } } /// Implementation for Vec<u8> impl Encode for Vec<u8> { fn as_hex(&self)-> String { HEXLOWER.encode(self) } fn as_base64(&self)-> String { BASE64.encode(self) } fn as_base64_url(&self)-> String { BASE64URL.encode(self) } fn as_base32(&self)-> String { BASE32.encode(self) } } /// Implementation Iterator /// # Example /// ``` /// /// extern crate ids_service; /// /// use crate::ids_service::crypto_hash::{Encode,IdsService}; /// /// fn main() { /// /// /* /// * Create an ids service with: /// * Cache size = 10'000 /// * hash algo. = sha512 /// * A pool of 20 threads /// */ /// let mut ids = IdsService::default(); /// ids.start(); /// for id in ids.take(10) { /// println!("Get an id: {}", id.as_base64()); /// } /// /// } /// ``` impl Iterator for IdsService { type Item = Vec<u8>; fn next(&mut self) -> Option<Self::Item> { Some(self.get_id()) } } /// Main implementation during creation a thread to fill in cache is started /// # Examples /// /// ``` /// extern crate ids_service; /// extern crate simplelog; /// extern crate crypto; /// /// use crate::ids_service::crypto_hash::{Encode,IdsService}; /// use crate::simplelog::*; /// use crypto::sha3::Sha3Mode; /// use std::time::Duration; /// use std::thread; /// use log::*; /// /// fn main() { /// /// let _ = SimpleLogger::init(LevelFilter::Info, Config::default()); /// /// /* /// * Create an ids service with: /// * Cache size = 10'000 /// * hash algo. = Keccak256 /// * A pool of 100 threads /// */ /// let mut ids = IdsService::new(10000, Sha3Mode::Keccak256,Some(100 as usize)); /// ids.start(); /// /// //Wait the cache is filled /// loop{ /// thread::sleep(Duration::from_millis(100)); /// if !ids.is_filled(){ /// break; /// } /// } /// info!("Current numbers of items in cache: {}", ids.get_cache_len()); /// info!("Get an id: {}", ids.get_id().as_hex()); /// info!("Get another id: {}", ids.get_id().as_base64()); /// info!("Current numbers of items in cache: {}", ids.get_cache_len()); /// /// } /// ``` impl IdsService { pub fn new(cache_size: usize, mode: Sha3Mode, number_of_threads : Option<usize>) -> IdsService { let rand_length = length_for(mode); let threads = match number_of_threads{ Some (n) => n, None => NUMBER_OF_FILL_THREAD, }; IdsService { ids_cache: Arc::new(Mutex::new(VecDeque::with_capacity(cache_size))), rand_length, cache_size, mode, sender: None, thread_counter: Arc::new(Mutex::new(0i32)), number_of_threads : threads, } } /// /// Purpose: Start caching threads pub fn start(&mut self) { if self.sender.is_none() { // Channel to send number of items to create let cmd_chn: (mpsc::Sender<usize>, mpsc::Receiver<usize>) = mpsc::channel(); self.sender = Some(cmd_chn.0.clone()); // Copy values to move it into thread let mode = self.mode; let rand_length = self.rand_length; let ids_cache_clone = self.ids_cache.clone(); let thread_counter_clone = self.thread_counter.clone(); // Thread to proceed event from cmd_chn thread::spawn(move || { trace!("Start wait for events"); let receiver = cmd_chn.1; for number in receiver.iter() { let ids_cache_clone_clone = ids_cache_clone.clone(); let thread_counter_clone_clone = thread_counter_clone.clone(); trace!("Refill in with a size of {}", number); // Thread to create [number] items thread::spawn(move || { // Increase thread counter *thread_counter_clone_clone.lock().unwrap() += 1; for _ in 0..number { let mut id: Vec<u8> = vec![0u8;length_for(mode)]; create_id(mode, rand_length, id.as_mut()); ids_cache_clone_clone.lock().unwrap().push_back(id); } // Decrease thread counter *thread_counter_clone_clone.lock().unwrap() -= 1; }); } }); } self.do_fill_in(); } // Purpose: // Calculate size of slices to be sent to fill in thread fn do_fill_in(&mut self) { trace!("do_fill_in"); let cache_size = self.cache_size; let len = self.ids_cache.lock().unwrap().len(); let thread_counter = self.thread_counter.lock().unwrap().clone(); trace!("do_fill_in thread_counter={}",thread_counter); let mut number = 0; if len > cache_size { // With high numbers of get_id calls, when cache is empty it may have fill in messages // before previous messages have been take by threads. // Sometime the size of cache is bigger to the request size. // In that case we don't need to fill in number = 0 debug!("Real cache size = {} , Requested cache size = {}, thread_counter = {}",len , cache_size, thread_counter); } else { number = cache_size - len; } let block_size = number / self.number_of_threads; let mut remainder = number; if block_size!=0 { remainder = number % block_size; } if number >= block_size && thread_counter < 1 && self.sender.is_some() { for _ in 0..self.number_of_threads { trace!("Send event with size of: {}", block_size); self.sender .clone() .expect("Expect a sender") .send(block_size) .expect( format!("Expect to send a message with a size of: {}", block_size) .as_str(), ); } trace!("Send event with remaind size of: {}", remainder); self.sender .clone() .expect("Expect a sender") .send(remainder) .expect( format!("Expect to send a message with a size of: {}", remainder).as_str(), ); } } // Create an id based on function create_id fn create_id(&mut self, out: &mut Vec<u8>) { if out.len() < length_for(self.mode) { warn!("Create an id with vec param out not initialized. out len = {}, out expected len {}",out.len(),length_for(self.mode)); out.clear(); for _ in 0..length_for(self.mode) { out.push(0u8); } } create_id(self.mode, self.rand_length, out); } /// /// Get an id. It may never failed even if cache is empty. /// If cache is empty it create on fly and id. /// # Examples /// ``` /// extern crate ids_service; /// /// use crate::ids_service::crypto_hash::{Encode,IdsService}; /// /// fn main() { /// /// let mut ids = IdsService::default(); /// ids.start(); /// println!("Get an id: {}", ids.get_id().as_hex()); /// } /// ``` pub fn get_id(&mut self) -> Vec<u8> { let id = self.ids_cache.lock().unwrap().pop_front(); match id { Some(i) => { self.do_fill_in(); i }, None => { info!("The ids_cache is empty, create on fly an id"); self.do_fill_in(); let mut id :Vec<u8> = vec![0u8;length_for(self.mode)]; self.create_id(id.as_mut()); id } } } /// Get the internal cache size. pub fn get_cache_len(&mut self) -> usize { self.ids_cache.lock().unwrap().len() } /// Set an cache size. /// If the new size is bigger it start a refill /// If the new size is smaller it don't remove already created item. /// It will wait to refill the cache to be smaller to the new size. /// # Examples /// /// ``` /// extern crate ids_service; /// extern crate simplelog; /// extern crate crypto; /// /// use crate::ids_service::crypto_hash::{Encode,IdsService}; /// use crate::simplelog::*; /// use crypto::sha3::Sha3Mode; /// use std::time::Duration; /// use std::thread; /// use log::*; /// /// fn main() { /// /// let _ = SimpleLogger::init(LevelFilter::Info, Config::default()); /// /// let mut ids3 = IdsService::default(); /// ids3.start(); /// /// //Wait the cache is filled /// loop{ /// thread::sleep(Duration::from_millis(100)); /// if !ids3.is_filled(){ /// break; /// } /// } /// info!("Current numbers of items in cache ids3: {}", ids3.get_cache_len()); /// /// ids3.set_cache_size(20000); /// /// //Wait the cache is filled /// loop{ /// thread::sleep(Duration::from_millis(100)); /// if !ids3.is_filled(){ /// break; /// } /// } /// /// info!("Current numbers of items in cache ids3: {}", ids3.get_cache_len()); /// /// } /// ``` pub fn set_cache_size(&mut self, new_size: usize) { self.cache_size = new_size; self.do_fill_in(); } /// /// True if the cash is filled and the number of fill in thread equal 0 pub fn is_filled(&mut self) -> bool { let thread_counter = self.thread_counter.lock().unwrap().clone(); let len = self.ids_cache.lock().unwrap().len(); len < self.cache_size && thread_counter >0 } } // Function that create an ID fn create_id(mode: Sha3Mode, rand_length: usize, out: &mut Vec<u8>) { let ts = Utc::now().timestamp_nanos(); //Note add 8 due to timestamp first block let mut rand_data = vec![0u8; rand_length + 8]; rand_data.extend(ts.to_ne_bytes().iter()); for _i in 0..rand_length { rand_data.push(thread_rng().gen()); } let mut hasher = Sha3::new(mode); hasher.input(rand_data.as_slice()); hasher.result(out.as_mut()); } /// Single function to create an id without IdsService /// It use sha512 hash algorithm and it encode output as hexadecimal lower case /// # example: /// ``` /// extern crate ids_service; /// /// use crate::ids_service::crypto_hash::*; /// /// fn main() { /// /// println!("Create an id sha512 without the service: {}", create_id_as_sha512()); /// /// } /// ``` pub fn create_id_as_sha512() -> String { let mut id = vec![0u8; Sha3Mode::Sha3_512.digest_length()]; create_id(Sha3Mode::Sha3_512,Sha3Mode::Sha3_512.digest_length(),id.as_mut()); HEXLOWER.encode(id.as_slice()) } /// Single function to create an id without IdsService /// It use sha256 hash algorithm and it encode output as hexadecimal lower case /// # example: /// ``` /// extern crate ids_service; /// /// use crate::ids_service::crypto_hash::*; /// /// fn main() { /// /// println!("Create an id sha256 without the service: {}", create_id_as_sha256()); /// /// } /// ``` pub fn create_id_as_sha256() -> String { let mut id = vec![0u8; Sha3Mode::Sha3_256.digest_length()]; create_id(Sha3Mode::Sha3_256,Sha3Mode::Sha3_256.digest_length(),id.as_mut()); HEXLOWER.encode(id.as_slice()) } // Get length fo ShaMode due to Sha3Mode::Shake256 and Sha3Mode::Shake128 that return 0 fn length_for(mode : Sha3Mode) -> usize { let length = match mode.digest_length() { 0 => 64 as usize, _ => mode.digest_length(), }; length } /// /// Tests /// #[cfg(test)] mod tests { use crate::crypto_hash::*; use crate::crypto_hash::Encode; use crypto::sha3::Sha3Mode; use simplelog::*; use std::thread; use std::time::Duration; use std::collections::HashSet; #[test] fn test_start() { let _ = SimpleLogger::init(LevelFilter::Info, Config::default()); let mut service = IdsService::new(10067, Sha3Mode::Sha3_512,None); service.start(); loop{ thread::sleep(Duration::from_millis(500)); if !service.is_filled(){ break; } } assert_eq!(service.get_cache_len(),10067); } #[test] fn test_create_id_512() { let _ = SimpleLogger::init(LevelFilter::Info, Config::default()); let id1 = create_id_as_sha512(); let id2 = create_id_as_sha512(); assert!(!id1.eq(&id2)); } #[test] fn test_create_id_256() { let _ = SimpleLogger::init(LevelFilter::Info, Config::default()); let id1 = create_id_as_sha256(); let id2 = create_id_as_sha256(); assert!(!id1.eq(&id2)); } #[test] fn test_get_id() { let _ = SimpleLogger::init(LevelFilter::Info, Config::default()); let mut ids01 = IdsService::default(); ids01.start(); let r1= ids01.get_id(); debug!("r1: {:?}",r1); assert_eq!(r1.len(),Sha3Mode::Sha3_512.digest_length()); let r2= ids01.get_id(); debug!("r2: {:?}",r2); assert_eq!(r2.len(),Sha3Mode::Sha3_512.digest_length()); assert!(!r1.eq(&r2)); } #[test] fn test_get_id_all() { let _ = SimpleLogger::init(LevelFilter::Info, Config::default()); let do_test = |m : Sha3Mode| { debug!("mode: {:?}",m); let mut ids01 = IdsService::new(1000,m,None); ids01.start(); loop{ thread::sleep(Duration::from_millis(500)); if !ids01.is_filled(){ break; } } let r1= ids01.get_id(); debug!("r1: {:?}",r1); assert!(r1.len()>0); let r2= ids01.get_id(); debug!("r2: {:?}",r2); assert!(r2.len()>0); assert!(!r1.eq(&r2)); }; do_test(Sha3Mode::Keccak224); do_test(Sha3Mode::Keccak256); do_test(Sha3Mode::Keccak384); do_test(Sha3Mode::Keccak512); do_test(Sha3Mode::Sha3_224); do_test(Sha3Mode::Sha3_256); do_test(Sha3Mode::Sha3_384); do_test(Sha3Mode::Sha3_512); do_test(Sha3Mode::Shake128); do_test(Sha3Mode::Shake256); } #[test] fn test_get_id_as_hex() { let _ = SimpleLogger::init(LevelFilter::Info, Config::default()); let mut ids01 = IdsService::default(); ids01.start(); let result= ids01.get_id().as_hex(); debug!("Id {} / len {}",result,result.len()); assert_eq!(result.len(),128); } #[test] fn test_get_id_as_base64() { let _ = SimpleLogger::init(LevelFilter::Info, Config::default()); let mut ids01 = IdsService::default(); ids01.start(); let result= ids01.get_id().as_base64(); debug!("Id {} / len {}",result,result.len()); assert_eq!(result.len(),88); } #[test] fn test_get_id_as_base64_url() { let _ = SimpleLogger::init(LevelFilter::Info, Config::default()); let mut ids01 = IdsService::default(); ids01.start(); let result= ids01.get_id().as_base64_url(); debug!("Id {} / len {}",result,result.len()); assert_eq!(result.len(),88); } #[test] fn test_get_id_as_base32() { let _ = SimpleLogger::init(LevelFilter::Info, Config::default()); let mut ids01 = IdsService::default(); ids01.start(); let result= ids01.get_id().as_base32(); debug!("Id {} / len {}",result,result.len()); assert_eq!(result.len(),104); } #[test] fn test_iterator() { let _ = SimpleLogger::init(LevelFilter::Warn, Config::default()); let mut ids01 = IdsService::new(10000, Sha3Mode::Sha3_512,Some(100 as usize)); ids01.start(); loop{ thread::sleep(Duration::from_millis(500)); if !ids01.is_filled(){ break; } } let number = 10000; let mut ids = HashSet::with_capacity(number); for _ in 0..number { ids.insert(ids01.get_id().as_hex()); } assert_eq!(ids.len(),number); ids.clear(); for x in ids01.take(number) { ids.insert(x.as_hex()); } assert_eq!(ids.len(),number); } } }