├── .gitignore ├── Cargo.toml ├── src ├── lib.rs ├── journaldb │ ├── mod.rs │ ├── algorithm.rs │ ├── traits.rs │ └── archivedb.rs ├── error.rs ├── hashdb.rs └── memorydb.rs ├── .github └── workflows │ └── test.yml ├── rustfmt.toml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | 4 | Cargo.lock 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "codechain-db" 3 | version = "0.2.0" 4 | authors = ["CodeChain Team ", "Parity Technologies "] 5 | description = "Databases that CodeChain uses" 6 | license = "AGPL-3.0" 7 | edition = "2018" 8 | 9 | [dependencies] 10 | codechain-crypto = { git = "https://github.com/CodeChain-io/rust-codechain-crypto.git", version = "0.3", tag = "v0.3.0" } 11 | kvdb = "0.1" 12 | plain_hasher = "0.2" 13 | primitives = { git = "https://github.com/CodeChain-io/rust-codechain-primitives.git", version = "0.5.0", tag = "v0.5.1" } 14 | rlp = { git = "https://github.com/CodeChain-io/rlp.git", version = "0.5", tag = "v0.5.0" } 15 | 16 | [dev-dependencies] 17 | kvdb-memorydb = "0.1" 18 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Kodebox, Inc. 2 | // This file is part of CodeChain. 3 | // 4 | // This is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | mod error; 18 | mod hashdb; 19 | mod journaldb; 20 | mod memorydb; 21 | 22 | pub use crate::error::DatabaseError; 23 | pub use crate::hashdb::{AsHashDB, DBValue, HashDB}; 24 | pub use crate::journaldb::{new_journaldb, Algorithm, JournalDB}; 25 | pub use crate::memorydb::MemoryDB; 26 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: test 4 | 5 | jobs: 6 | clippy: 7 | name: Actions - clippy 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v1 11 | with: 12 | fetch-depth: 1 13 | - uses: actions-rs/toolchain@v1 14 | with: 15 | toolchain: nightly-2020-07-27 16 | components: clippy 17 | profile: minimal 18 | override: true 19 | - run: cargo fetch --verbose 20 | - run: cargo clippy --all --all-targets -- -D warnings 21 | 22 | rustfmt: 23 | name: Actions - rustfmt 24 | runs-on: ubuntu-latest 25 | steps: 26 | - uses: actions/checkout@v1 27 | with: 28 | fetch-depth: 1 29 | - uses: actions-rs/toolchain@v1 30 | with: 31 | toolchain: nightly-2020-07-27 32 | components: rustfmt 33 | profile: minimal 34 | override: true 35 | - run: cargo fmt -- --check 36 | 37 | unit-test: 38 | name: Actions - unit test 39 | runs-on: ${{ matrix.os }} 40 | strategy: 41 | matrix: 42 | os: [macOS-latest, ubuntu-latest] 43 | steps: 44 | - uses: actions/checkout@v1 45 | with: 46 | fetch-depth: 1 47 | - uses: actions-rs/toolchain@v1 48 | with: 49 | toolchain: 1.45.2 50 | profile: minimal 51 | override: true 52 | - run: cargo fetch --verbose 53 | - run: cargo build 54 | - run: cargo test --verbose --all 55 | env: 56 | RUST_BACKTRACE: 1 57 | -------------------------------------------------------------------------------- /src/journaldb/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Kodebox, Inc. 2 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 3 | // This file is part of CodeChain. 4 | // 5 | // This is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | //! `JournalDB` interface and implementation. 19 | 20 | mod algorithm; 21 | mod archivedb; 22 | mod traits; 23 | 24 | pub use self::algorithm::Algorithm; 25 | pub use self::traits::JournalDB; 26 | use std::sync::Arc; 27 | 28 | /// Create a new `JournalDB` trait object over a generic key-value database. 29 | pub fn new_journaldb(backing: Arc, algorithm: Algorithm, col: Option) -> Box { 30 | match algorithm { 31 | Algorithm::Archive => Box::new(archivedb::ArchiveDB::new(backing, col)), 32 | } 33 | } 34 | 35 | // all keys must be at least 12 bytes 36 | const DB_PREFIX_LEN: usize = ::kvdb::PREFIX_LEN; 37 | const LATEST_ERA_KEY: [u8; ::kvdb::PREFIX_LEN] = [b'l', b'a', b's', b't', 0, 0, 0, 0, 0, 0, 0, 0]; 38 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Kodebox, Inc. 2 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 3 | // This file is part of CodeChain. 4 | // 5 | // This is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this. If not, see . 17 | 18 | use primitives::H256; 19 | use std::{fmt, io}; 20 | 21 | #[derive(Debug)] 22 | /// Error in database subsystem. 23 | pub enum DatabaseError { 24 | Io(io::Error), 25 | /// An entry was removed more times than inserted. 26 | NegativelyReferencedHash(H256), 27 | /// A committed value was inserted more than once. 28 | AlreadyExists(H256), 29 | } 30 | 31 | impl fmt::Display for DatabaseError { 32 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 33 | match *self { 34 | DatabaseError::NegativelyReferencedHash(hash) => { 35 | write!(f, "Entry {} removed from database more times than it was added.", hash) 36 | } 37 | DatabaseError::AlreadyExists(hash) => write!(f, "Committed key already exists in database: {}", hash), 38 | DatabaseError::Io(ref err) => err.fmt(f), 39 | } 40 | } 41 | } 42 | 43 | impl From for DatabaseError { 44 | fn from(err: io::Error) -> Self { 45 | DatabaseError::Io(err) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | indent_style = "Block" 2 | use_small_heuristics = "Off" # "Default" 3 | binop_separator = "Front" 4 | # combine_control_expr = true 5 | comment_width = 120 # 80 6 | condense_wildcard_suffixes = true # false 7 | control_brace_style = "AlwaysSameLine" 8 | # disable_all_formatting = false 9 | error_on_line_overflow = false # true 10 | # error_on_unformatted = false 11 | fn_args_layout = "Tall" 12 | brace_style = "PreferSameLine" # "SameLineWhere" 13 | empty_item_single_line = true 14 | enum_discrim_align_threshold = 0 15 | fn_single_line = false 16 | # where_single_line = false 17 | force_explicit_abi = true 18 | format_strings = false 19 | format_macro_matchers = false 20 | format_macro_bodies = true 21 | hard_tabs = false 22 | imports_indent = "Block" # "Visual" 23 | imports_layout = "Mixed" 24 | merge_imports = false 25 | match_block_trailing_comma = false 26 | max_width = 120 # 100 27 | merge_derives = true 28 | # force_multiline_blocks = false 29 | newline_style = "Unix" 30 | normalize_comments = false 31 | remove_nested_parens = true 32 | reorder_imports = true 33 | reorder_modules = true 34 | # reorder_impl_items = false 35 | # report_todo = "Never" 36 | # report_fixme = "Never" 37 | space_after_colon = true 38 | space_before_colon = false 39 | struct_field_align_threshold = 0 40 | spaces_around_ranges = false 41 | ## struct_lit_single_line = true 42 | tab_spaces = 4 43 | trailing_comma = "Vertical" 44 | trailing_semicolon = false # true 45 | # type_punctuation_density = "Wide" 46 | use_field_init_shorthand = true # false 47 | use_try_shorthand = true # false 48 | # format_code_in_doc_comments = false 49 | wrap_comments = false 50 | match_arm_blocks = true 51 | overflow_delimited_expr = true 52 | blank_lines_upper_bound = 2 # 1 53 | blank_lines_lower_bound = 0 54 | # required_version 55 | hide_parse_errors = false 56 | color = "Always" # "Auto" 57 | unstable_features = false 58 | # license_template_path 59 | # ignore 60 | edition = "2018" 61 | # version 62 | normalize_doc_attributes = true # false 63 | inline_attribute_width = 0 64 | -------------------------------------------------------------------------------- /src/hashdb.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Kodebox, Inc. 2 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 3 | // This file is part of CodeChain. 4 | // 5 | // This is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | //! Database of byte-slices keyed to their blake2b hash. 19 | use primitives::H256; 20 | use std::collections::HashMap; 21 | 22 | /// `HashDB` value type. 23 | pub type DBValue = Vec; 24 | 25 | /// Trait modelling datastore keyed by a 32-byte blake2b hash. 26 | pub trait HashDB: AsHashDB + Send + Sync { 27 | /// Get the keys in the database together with number of underlying references. 28 | fn keys(&self) -> HashMap; 29 | 30 | /// Look up a given hash into the bytes that hash to it, returning None if the 31 | /// hash is not known. 32 | fn get(&self, key: &H256) -> Option; 33 | 34 | /// Check for the existence of a hash-key. 35 | fn contains(&self, key: &H256) -> bool; 36 | 37 | /// Insert a datum item into the DB and return the datum's hash for a later lookup. Insertions 38 | /// are counted and the equivalent number of `remove()`s must be performed before the data 39 | /// is considered dead. 40 | fn insert(&mut self, value: &[u8]) -> H256; 41 | 42 | /// Remove a datum previously inserted. Insertions can be "owed" such that the same number of `insert()`s may 43 | /// happen without the data being eventually being inserted into the DB. It can be "owed" more than once. 44 | fn remove(&mut self, key: &H256); 45 | 46 | /// check if the db has no commits 47 | fn is_empty(&self) -> bool; 48 | } 49 | 50 | /// Upcast trait. 51 | pub trait AsHashDB { 52 | /// Perform upcast to HashDB for anything that derives from HashDB. 53 | fn as_hashdb(&self) -> &dyn HashDB; 54 | /// Perform mutable upcast to HashDB for anything that derives from HashDB. 55 | fn as_hashdb_mut(&mut self) -> &mut dyn HashDB; 56 | } 57 | 58 | impl AsHashDB for T { 59 | fn as_hashdb(&self) -> &dyn HashDB { 60 | self 61 | } 62 | fn as_hashdb_mut(&mut self) -> &mut dyn HashDB { 63 | self 64 | } 65 | } 66 | 67 | impl<'a> AsHashDB for &'a mut dyn HashDB { 68 | fn as_hashdb(&self) -> &dyn HashDB { 69 | &**self 70 | } 71 | 72 | fn as_hashdb_mut(&mut self) -> &mut dyn HashDB { 73 | &mut **self 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/journaldb/algorithm.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Kodebox, Inc. 2 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 3 | // This file is part of CodeChain. 4 | // 5 | // This is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | use std::{fmt, str}; 19 | 20 | /// Journal database operating strategy. 21 | #[derive(Debug, PartialEq, Clone, Copy)] 22 | pub enum Algorithm { 23 | /// Keep all keys forever. 24 | Archive, 25 | } 26 | 27 | impl Default for Algorithm { 28 | fn default() -> Algorithm { 29 | Algorithm::Archive 30 | } 31 | } 32 | 33 | impl str::FromStr for Algorithm { 34 | type Err = String; 35 | 36 | fn from_str(s: &str) -> Result { 37 | match s { 38 | "archive" => Ok(Algorithm::Archive), 39 | e => Err(format!("Invalid algorithm: {}", e)), 40 | } 41 | } 42 | } 43 | 44 | impl Algorithm { 45 | /// Returns true if pruning strategy is stable 46 | pub fn is_stable(self) -> bool { 47 | match self { 48 | Algorithm::Archive => true, 49 | } 50 | } 51 | 52 | /// Returns all algorithm types. 53 | pub fn all_types() -> Vec { 54 | vec![Algorithm::Archive] 55 | } 56 | } 57 | 58 | impl fmt::Display for Algorithm { 59 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 60 | match self { 61 | Algorithm::Archive => write!(f, "archive"), 62 | } 63 | } 64 | } 65 | 66 | #[cfg(test)] 67 | mod tests { 68 | use super::Algorithm; 69 | 70 | #[test] 71 | fn journal_algorithm_parsing() { 72 | assert_eq!(Algorithm::Archive, "archive".parse().unwrap()); 73 | } 74 | 75 | #[test] 76 | fn journal_algorithm_printing() { 77 | assert_eq!(Algorithm::Archive.to_string(), "archive".to_string()); 78 | } 79 | 80 | #[test] 81 | fn journal_algorithm_is_stable() { 82 | assert!(Algorithm::Archive.is_stable()); 83 | } 84 | 85 | #[test] 86 | fn journal_algorithm_default() { 87 | assert_eq!(Algorithm::default(), Algorithm::Archive); 88 | } 89 | 90 | #[test] 91 | fn journal_algorithm_all_types() { 92 | // compiling should fail if some cases are not covered 93 | let mut archive = 0; 94 | 95 | for a in &Algorithm::all_types() { 96 | match *a { 97 | Algorithm::Archive => archive += 1, 98 | } 99 | } 100 | 101 | assert_eq!(archive, 1); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/journaldb/traits.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Kodebox, Inc. 2 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 3 | // This file is part of CodeChain. 4 | // 5 | // This is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | //! Disk-backed `HashDB` implementation. 19 | 20 | use crate::hashdb::HashDB; 21 | use crate::memorydb::MemoryDB; 22 | use crate::DatabaseError; 23 | use kvdb::{DBTransaction, KeyValueDB}; 24 | use primitives::{Bytes, H256}; 25 | use std::sync::Arc; 26 | 27 | /// A `HashDB` which can manage a short-term journal potentially containing many forks of mutually 28 | /// exclusive actions. 29 | pub trait JournalDB: HashDB { 30 | /// Return a copy of ourself, in a box. 31 | fn boxed_clone(&self) -> Box; 32 | 33 | /// Returns the size of journalled state in memory. 34 | /// This function has a considerable speed requirement -- 35 | /// it must be fast enough to call several times per block imported. 36 | fn journal_size(&self) -> usize { 37 | 0 38 | } 39 | 40 | /// Get the earliest era in the DB. None if there isn't yet any data in there. 41 | fn earliest_era(&self) -> Option { 42 | None 43 | } 44 | 45 | /// Get the latest era in the DB. None if there isn't yet any data in there. 46 | fn latest_era(&self) -> Option; 47 | 48 | /// Journal recent database operations as being associated with a given era and id. 49 | // TODO: give the overlay to this function so journaldbs don't manage the overlays themselves. 50 | fn journal_under(&mut self, batch: &mut DBTransaction, now: u64, id: &H256) -> Result; 51 | 52 | /// Mark a given block as canonical, indicating that competing blocks' states may be pruned out. 53 | fn mark_canonical(&mut self, batch: &mut DBTransaction, era: u64, id: &H256) -> Result; 54 | 55 | /// Commit all queued insert and delete operations without affecting any journalling -- this requires that all insertions 56 | /// and deletions are indeed canonical and will likely lead to an invalid database if that assumption is violated. 57 | /// 58 | /// Any keys or values inserted or deleted must be completely independent of those affected 59 | /// by any previous `commit` operations. Essentially, this means that `inject` can be used 60 | /// either to restore a state to a fresh database, or to insert data which may only be journalled 61 | /// from this point onwards. 62 | fn inject(&mut self, batch: &mut DBTransaction) -> Result; 63 | 64 | /// State data query 65 | fn state(&self, _id: &H256) -> Option; 66 | 67 | /// Whether this database is pruned. 68 | fn is_pruned(&self) -> bool { 69 | true 70 | } 71 | 72 | /// Get backing database. 73 | fn backing(&self) -> &Arc; 74 | 75 | /// Clear internal structures. This should called after changes have been written 76 | /// to the backing storage. 77 | fn flush(&self) {} 78 | 79 | /// Consolidate all the insertions and deletions in the given memory overlay. 80 | fn consolidate(&mut self, overlay: MemoryDB); 81 | 82 | /// Commit all changes in a single batch 83 | #[cfg(test)] 84 | fn commit_batch(&mut self, now: u64, id: &H256, end: Option<(u64, H256)>) -> Result { 85 | let mut batch = self.backing().transaction(); 86 | let mut ops = self.journal_under(&mut batch, now, id)?; 87 | 88 | if let Some((end_era, canon_id)) = end { 89 | ops += self.mark_canonical(&mut batch, end_era, &canon_id)?; 90 | } 91 | 92 | let result = self.backing().write(batch).map(|_| ops).map_err(Into::into); 93 | self.flush(); 94 | result 95 | } 96 | 97 | /// Inject all changes in a single batch. 98 | #[cfg(test)] 99 | fn inject_batch(&mut self) -> Result { 100 | let mut batch = self.backing().transaction(); 101 | let res = self.inject(&mut batch)?; 102 | self.backing().write(batch).map(|_| res).map_err(Into::into) 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/memorydb.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Kodebox, Inc. 2 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 3 | // This file is part of CodeChain. 4 | // 5 | // This is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | //! Reference-counted memory-based `HashDB` implementation. 19 | 20 | use super::{DBValue, HashDB}; 21 | use codechain_crypto::{blake256, BLAKE_NULL_RLP}; 22 | use plain_hasher::PlainHasher; 23 | use primitives::H256; 24 | use rlp::NULL_RLP; 25 | use std::collections::hash_map::Entry; 26 | use std::collections::HashMap; 27 | use std::hash; 28 | use std::mem; 29 | 30 | type H256FastMap = HashMap>; 31 | 32 | /// Reference-counted memory-based `HashDB` implementation. 33 | /// 34 | /// Use `new()` to create a new database. Insert items with `insert()`, remove items 35 | /// with `remove()`, check for existence with `contains()` and lookup a hash to derive 36 | /// the data with `get()`. Clear with `clear()` and purge the portions of the data 37 | /// that have no references with `purge()`. 38 | /// 39 | /// # Example 40 | /// ```rust 41 | /// use codechain_db::*; 42 | /// 43 | /// let mut m = MemoryDB::new(); 44 | /// let d = "Hello world!".as_bytes(); 45 | /// 46 | /// let k = m.insert(d); 47 | /// assert!(m.contains(&k)); 48 | /// assert_eq!(m.get(&k).unwrap(), d); 49 | /// 50 | /// m.insert(d); 51 | /// assert!(m.contains(&k)); 52 | /// 53 | /// m.remove(&k); 54 | /// assert!(m.contains(&k)); 55 | /// 56 | /// m.remove(&k); 57 | /// assert!(!m.contains(&k)); 58 | /// 59 | /// m.remove(&k); 60 | /// assert!(!m.contains(&k)); 61 | /// 62 | /// m.insert(d); 63 | /// assert!(!m.contains(&k)); 64 | 65 | /// m.insert(d); 66 | /// assert!(m.contains(&k)); 67 | /// assert_eq!(m.get(&k).unwrap(), d); 68 | /// 69 | /// m.remove(&k); 70 | /// assert!(!m.contains(&k)); 71 | /// ``` 72 | #[derive(Default, Clone, PartialEq)] 73 | pub struct MemoryDB { 74 | data: H256FastMap<(DBValue, i32)>, 75 | } 76 | 77 | impl MemoryDB { 78 | /// Create a new instance of the memory DB. 79 | pub fn new() -> MemoryDB { 80 | Default::default() 81 | } 82 | 83 | /// Clear all data from the database. 84 | /// 85 | /// # Examples 86 | /// ```rust 87 | /// use codechain_db::*; 88 | /// 89 | /// let mut m = MemoryDB::new(); 90 | /// let hello_bytes = "Hello world!".as_bytes(); 91 | /// let hash = m.insert(hello_bytes); 92 | /// assert!(m.contains(&hash)); 93 | /// m.clear(); 94 | /// assert!(!m.contains(&hash)); 95 | /// ``` 96 | pub fn clear(&mut self) { 97 | self.data.clear(); 98 | } 99 | 100 | /// Purge all zero-referenced data from the database. 101 | pub fn purge(&mut self) { 102 | self.data.retain(|_, &mut (_, rc)| rc != 0); 103 | } 104 | 105 | /// Return the internal map of hashes to data, clearing the current state. 106 | pub fn drain(&mut self) -> H256FastMap<(DBValue, i32)> { 107 | mem::take(&mut self.data) 108 | } 109 | 110 | /// Grab the raw information associated with a key. Returns None if the key 111 | /// doesn't exist. 112 | /// 113 | /// Even when Some is returned, the data is only guaranteed to be useful 114 | /// when the refs > 0. 115 | pub fn raw(&self, key: &H256) -> Option<(DBValue, i32)> { 116 | if key == &BLAKE_NULL_RLP { 117 | return Some((NULL_RLP.to_vec(), 1)) 118 | } 119 | self.data.get(key).cloned() 120 | } 121 | 122 | /// Remove an element and delete it from storage if reference count reaches zero. 123 | /// If the value was purged, return the old value. 124 | pub fn remove_and_purge(&mut self, key: &H256) -> Option { 125 | if key == &BLAKE_NULL_RLP { 126 | return None 127 | } 128 | match self.data.entry(*key) { 129 | Entry::Occupied(mut entry) => { 130 | if entry.get().1 == 1 { 131 | Some(entry.remove().0) 132 | } else { 133 | entry.get_mut().1 -= 1; 134 | None 135 | } 136 | } 137 | Entry::Vacant(entry) => { 138 | entry.insert((DBValue::new(), -1)); 139 | None 140 | } 141 | } 142 | } 143 | 144 | /// Consolidate all the entries of `other` into `self`. 145 | pub fn consolidate(&mut self, mut other: Self) { 146 | for (key, (value, rc)) in other.drain() { 147 | let (old_value, old_rc) = self.data.entry(key).or_default(); 148 | if *old_rc <= 0 { 149 | *old_value = value; 150 | } 151 | *old_rc += rc; 152 | if *old_rc < -1 { 153 | *old_rc = -1; 154 | } 155 | } 156 | } 157 | } 158 | 159 | impl HashDB for MemoryDB { 160 | fn keys(&self) -> HashMap { 161 | self.data 162 | .iter() 163 | .filter_map(|(k, v)| { 164 | if v.1 != 0 { 165 | Some((*k, v.1)) 166 | } else { 167 | None 168 | } 169 | }) 170 | .collect() 171 | } 172 | 173 | fn get(&self, key: &H256) -> Option { 174 | if key == &BLAKE_NULL_RLP { 175 | return Some(NULL_RLP.to_vec()) 176 | } 177 | 178 | match self.data.get(key) { 179 | Some(&(ref d, rc)) if rc > 0 => Some(d.clone()), 180 | _ => None, 181 | } 182 | } 183 | 184 | fn contains(&self, key: &H256) -> bool { 185 | if key == &BLAKE_NULL_RLP { 186 | return true 187 | } 188 | 189 | matches!(self.data.get(key), Some(&(_, x)) if x > 0) 190 | } 191 | 192 | fn insert(&mut self, value: &[u8]) -> H256 { 193 | if *value == NULL_RLP { 194 | return BLAKE_NULL_RLP 195 | } 196 | let key = blake256(value); 197 | let (old_value, rc) = self.data.entry(key).or_default(); 198 | if *rc <= 0 { 199 | *old_value = value.to_vec(); 200 | } 201 | *rc += 1; 202 | key 203 | } 204 | 205 | fn remove(&mut self, key: &H256) { 206 | if key == &BLAKE_NULL_RLP { 207 | return 208 | } 209 | let (_, rc) = self.data.entry(*key).or_default(); 210 | *rc -= 1; 211 | } 212 | 213 | fn is_empty(&self) -> bool { 214 | self.data.is_empty() 215 | } 216 | } 217 | 218 | #[cfg(test)] 219 | mod tests { 220 | use super::*; 221 | 222 | #[test] 223 | fn memorydb_remove_and_purge() { 224 | let hello_bytes = b"Hello world!"; 225 | let hello_key = blake256(hello_bytes); 226 | 227 | let mut m = MemoryDB::new(); 228 | m.remove(&hello_key); 229 | assert_eq!(m.raw(&hello_key).unwrap().1, -1); 230 | m.purge(); 231 | assert_eq!(m.raw(&hello_key).unwrap().1, -1); 232 | m.insert(hello_bytes); 233 | assert_eq!(m.raw(&hello_key).unwrap().1, 0); 234 | m.purge(); 235 | assert_eq!(m.raw(&hello_key), None); 236 | 237 | let mut m = MemoryDB::new(); 238 | assert!(m.remove_and_purge(&hello_key).is_none()); 239 | assert_eq!(m.raw(&hello_key).unwrap().1, -1); 240 | m.insert(hello_bytes); 241 | m.insert(hello_bytes); 242 | assert_eq!(m.raw(&hello_key).unwrap().1, 1); 243 | assert_eq!(&*m.remove_and_purge(&hello_key).unwrap(), hello_bytes); 244 | assert_eq!(m.raw(&hello_key), None); 245 | assert!(m.remove_and_purge(&hello_key).is_none()); 246 | } 247 | 248 | #[test] 249 | fn consolidate() { 250 | let mut main = MemoryDB::new(); 251 | let mut other = MemoryDB::new(); 252 | let remove_key = other.insert(b"doggo"); 253 | main.remove(&remove_key); 254 | 255 | let insert_key = other.insert(b"arf"); 256 | main.insert(b"arf"); 257 | 258 | let negative_remove_key = other.insert(b"negative"); 259 | other.remove(&negative_remove_key); // ref cnt: 0 260 | other.remove(&negative_remove_key); // ref cnt: -1 261 | main.remove(&negative_remove_key); // ref cnt: -1 262 | 263 | main.consolidate(other); 264 | 265 | let overlay = main.drain(); 266 | 267 | assert_eq!(overlay[&remove_key], (b"doggo".to_vec(), 0)); 268 | assert_eq!(overlay[&insert_key], (b"arf".to_vec(), 2)); 269 | assert_eq!(overlay[&negative_remove_key], (b"negative".to_vec(), -1)); 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /src/journaldb/archivedb.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 Kodebox, Inc. 2 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 3 | // This file is part of CodeChain. 4 | // 5 | // This is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | //! Disk-backed `HashDB` implementation. 19 | 20 | use super::traits::JournalDB; 21 | use super::{DB_PREFIX_LEN, LATEST_ERA_KEY}; 22 | use crate::hashdb::*; 23 | use crate::memorydb::*; 24 | use crate::DatabaseError; 25 | use kvdb::{DBTransaction, KeyValueDB}; 26 | use primitives::{Bytes, H256}; 27 | use rlp::{decode, encode}; 28 | use std::collections::HashMap; 29 | use std::sync::Arc; 30 | 31 | /// Implementation of the `HashDB` trait for a disk-backed database with a memory overlay 32 | /// and latent-removal semantics. 33 | /// 34 | /// Like `OverlayDB`, there is a memory overlay; `commit()` must be called in order to 35 | /// write operations out to disk. Unlike `OverlayDB`, `remove()` operations do not take effect 36 | /// immediately. As this is an "archive" database, nothing is ever removed. This means 37 | /// that the states of any block the node has ever processed will be accessible. 38 | pub struct ArchiveDB { 39 | overlay: MemoryDB, 40 | backing: Arc, 41 | latest_era: Option, 42 | column: Option, 43 | } 44 | 45 | impl ArchiveDB { 46 | /// Create a new instance from a key-value db. 47 | pub fn new(backing: Arc, col: Option) -> ArchiveDB { 48 | let latest_era = backing 49 | .get(col, &LATEST_ERA_KEY) 50 | .expect("Low-level database error.") 51 | .map(|val| decode::(&val).unwrap()); 52 | ArchiveDB { 53 | overlay: MemoryDB::new(), 54 | backing, 55 | latest_era, 56 | column: col, 57 | } 58 | } 59 | 60 | fn payload(&self, key: &H256) -> Option { 61 | self.backing 62 | .get(self.column, key.as_bytes()) 63 | .expect("Low-level database error. Some issue with your hard disk?") 64 | .map(|data| data.to_vec()) 65 | } 66 | } 67 | 68 | impl HashDB for ArchiveDB { 69 | fn keys(&self) -> HashMap { 70 | let mut ret: HashMap = 71 | self.backing.iter(self.column).map(|(key, _)| (H256::from_slice(&*key), 1)).collect(); 72 | 73 | for (key, refs) in self.overlay.keys() { 74 | let rc = ret.entry(key).or_default(); 75 | *rc += refs; 76 | assert!(*rc >= -1, "rc should be equal to or greater than -1, but {}", rc); 77 | } 78 | ret 79 | } 80 | 81 | fn get(&self, key: &H256) -> Option { 82 | if let Some((d, rc)) = self.overlay.raw(key) { 83 | if rc > 0 { 84 | return Some(d) 85 | } 86 | } 87 | self.payload(key) 88 | } 89 | 90 | fn contains(&self, key: &H256) -> bool { 91 | self.get(key).is_some() 92 | } 93 | 94 | fn insert(&mut self, value: &[u8]) -> H256 { 95 | self.overlay.insert(value) 96 | } 97 | 98 | fn remove(&mut self, key: &H256) { 99 | self.overlay.remove(key); 100 | } 101 | 102 | fn is_empty(&self) -> bool { 103 | self.latest_era.is_none() 104 | } 105 | } 106 | 107 | impl JournalDB for ArchiveDB { 108 | fn boxed_clone(&self) -> Box { 109 | Box::new(ArchiveDB { 110 | overlay: self.overlay.clone(), 111 | backing: self.backing.clone(), 112 | latest_era: self.latest_era, 113 | column: self.column, 114 | }) 115 | } 116 | 117 | fn latest_era(&self) -> Option { 118 | self.latest_era 119 | } 120 | 121 | fn journal_under(&mut self, batch: &mut DBTransaction, now: u64, _id: &H256) -> Result { 122 | let mut inserts = 0usize; 123 | let mut deletes = 0usize; 124 | 125 | for i in self.overlay.drain() { 126 | let (key, (value, rc)) = i; 127 | if rc > 0 { 128 | batch.put(self.column, key.as_bytes(), &value); 129 | inserts += 1; 130 | } 131 | if rc < 0 { 132 | assert_eq!(-1, rc); 133 | deletes += 1; 134 | } 135 | } 136 | 137 | if self.latest_era.map_or(true, |e| now > e) { 138 | batch.put(self.column, &LATEST_ERA_KEY, &encode(&now)); 139 | self.latest_era = Some(now); 140 | } 141 | Ok((inserts + deletes) as u32) 142 | } 143 | 144 | fn mark_canonical( 145 | &mut self, 146 | _batch: &mut DBTransaction, 147 | _end_era: u64, 148 | _canon_id: &H256, 149 | ) -> Result { 150 | // keep everything! it's an archive, after all. 151 | Ok(0) 152 | } 153 | 154 | fn inject(&mut self, batch: &mut DBTransaction) -> Result { 155 | let mut inserts = 0usize; 156 | let mut deletes = 0usize; 157 | 158 | for i in self.overlay.drain() { 159 | let (key, (value, rc)) = i; 160 | if rc > 0 { 161 | if self.backing.get(self.column, key.as_bytes())?.is_some() { 162 | return Err(DatabaseError::AlreadyExists(key)) 163 | } 164 | batch.put(self.column, key.as_bytes(), &value); 165 | inserts += 1; 166 | } 167 | if rc < 0 { 168 | assert_eq!(-1, rc); 169 | if self.backing.get(self.column, key.as_bytes())?.is_none() { 170 | return Err(DatabaseError::NegativelyReferencedHash(key)) 171 | } 172 | batch.delete(self.column, key.as_bytes()); 173 | deletes += 1; 174 | } 175 | } 176 | 177 | Ok((inserts + deletes) as u32) 178 | } 179 | 180 | fn state(&self, id: &H256) -> Option { 181 | self.backing.get_by_prefix(self.column, &id[0..DB_PREFIX_LEN]).map(<[u8]>::into_vec) 182 | } 183 | 184 | fn is_pruned(&self) -> bool { 185 | false 186 | } 187 | 188 | fn backing(&self) -> &Arc { 189 | &self.backing 190 | } 191 | 192 | fn consolidate(&mut self, with: MemoryDB) { 193 | self.overlay.consolidate(with); 194 | } 195 | } 196 | 197 | #[cfg(test)] 198 | mod tests { 199 | use super::*; 200 | use crate::JournalDB; 201 | use codechain_crypto::blake256; 202 | 203 | #[test] 204 | fn insert_same_in_fork() { 205 | // history is 1 206 | let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None); 207 | 208 | let x = jdb.insert(b"X"); 209 | jdb.commit_batch(1, &blake256(b"1"), None).unwrap(); 210 | jdb.commit_batch(2, &blake256(b"2"), None).unwrap(); 211 | jdb.commit_batch(3, &blake256(b"1002a"), Some((1, blake256(b"1")))).unwrap(); 212 | jdb.commit_batch(4, &blake256(b"1003a"), Some((2, blake256(b"2")))).unwrap(); 213 | 214 | jdb.remove(&x); 215 | jdb.commit_batch(3, &blake256(b"1002b"), Some((1, blake256(b"1")))).unwrap(); 216 | let x = jdb.insert(b"X"); 217 | jdb.commit_batch(4, &blake256(b"1003b"), Some((2, blake256(b"2")))).unwrap(); 218 | 219 | jdb.commit_batch(5, &blake256(b"1004a"), Some((3, blake256(b"1002a")))).unwrap(); 220 | jdb.commit_batch(6, &blake256(b"1005a"), Some((4, blake256(b"1003a")))).unwrap(); 221 | 222 | assert!(jdb.contains(&x)); 223 | } 224 | 225 | #[test] 226 | fn long_history() { 227 | // history is 3 228 | let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None); 229 | let h = jdb.insert(b"foo"); 230 | jdb.commit_batch(0, &blake256(b"0"), None).unwrap(); 231 | assert!(jdb.contains(&h)); 232 | jdb.remove(&h); 233 | jdb.commit_batch(1, &blake256(b"1"), None).unwrap(); 234 | assert!(jdb.contains(&h)); 235 | jdb.commit_batch(2, &blake256(b"2"), None).unwrap(); 236 | assert!(jdb.contains(&h)); 237 | jdb.commit_batch(3, &blake256(b"3"), Some((0, blake256(b"0")))).unwrap(); 238 | assert!(jdb.contains(&h)); 239 | jdb.commit_batch(4, &blake256(b"4"), Some((1, blake256(b"1")))).unwrap(); 240 | assert!(jdb.contains(&h)); 241 | } 242 | 243 | #[test] 244 | #[should_panic] 245 | fn multiple_owed_removal_not_allowed() { 246 | let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None); 247 | let h = jdb.insert(b"foo"); 248 | jdb.commit_batch(0, &blake256(b"0"), None).unwrap(); 249 | assert!(jdb.contains(&h)); 250 | jdb.remove(&h); 251 | jdb.remove(&h); 252 | // commit_batch would call journal_under(), 253 | // and we don't allow multiple owned removals. 254 | jdb.commit_batch(1, &blake256(b"1"), None).unwrap(); 255 | } 256 | 257 | #[test] 258 | fn complex() { 259 | // history is 1 260 | let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None); 261 | 262 | let foo_hash = jdb.insert(b"foo"); 263 | let bar_hash = jdb.insert(b"bar"); 264 | jdb.commit_batch(0, &blake256(b"0"), None).unwrap(); 265 | assert!(jdb.contains(&foo_hash)); 266 | assert!(jdb.contains(&bar_hash)); 267 | 268 | jdb.remove(&foo_hash); 269 | jdb.remove(&bar_hash); 270 | let baz_hash = jdb.insert(b"baz"); 271 | jdb.commit_batch(1, &blake256(b"1"), Some((0, blake256(b"0")))).unwrap(); 272 | assert!(jdb.contains(&foo_hash)); 273 | assert!(jdb.contains(&bar_hash)); 274 | assert!(jdb.contains(&baz_hash)); 275 | 276 | let foo_hash = jdb.insert(b"foo"); 277 | jdb.remove(&baz_hash); 278 | jdb.commit_batch(2, &blake256(b"2"), Some((1, blake256(b"1")))).unwrap(); 279 | assert!(jdb.contains(&foo_hash)); 280 | assert!(jdb.contains(&baz_hash)); 281 | 282 | jdb.remove(&foo_hash); 283 | jdb.commit_batch(3, &blake256(b"3"), Some((2, blake256(b"2")))).unwrap(); 284 | assert!(jdb.contains(&foo_hash)); 285 | 286 | jdb.commit_batch(4, &blake256(b"4"), Some((3, blake256(b"3")))).unwrap(); 287 | } 288 | 289 | #[test] 290 | fn fork() { 291 | // history is 1 292 | let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None); 293 | 294 | let foo_hash = jdb.insert(b"foo"); 295 | let bar_hash = jdb.insert(b"bar"); 296 | jdb.commit_batch(0, &blake256(b"0"), None).unwrap(); 297 | assert!(jdb.contains(&foo_hash)); 298 | assert!(jdb.contains(&bar_hash)); 299 | 300 | jdb.remove(&foo_hash); 301 | let baz_hash = jdb.insert(b"baz"); 302 | jdb.commit_batch(1, &blake256(b"1a"), Some((0, blake256(b"0")))).unwrap(); 303 | 304 | jdb.remove(&bar_hash); 305 | jdb.commit_batch(1, &blake256(b"1b"), Some((0, blake256(b"0")))).unwrap(); 306 | 307 | assert!(jdb.contains(&foo_hash)); 308 | assert!(jdb.contains(&bar_hash)); 309 | assert!(jdb.contains(&baz_hash)); 310 | 311 | jdb.commit_batch(2, &blake256(b"2b"), Some((1, blake256(b"1b")))).unwrap(); 312 | assert!(jdb.contains(&foo_hash)); 313 | } 314 | 315 | #[test] 316 | fn overwrite() { 317 | // history is 1 318 | let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None); 319 | 320 | let foo_hash = jdb.insert(b"foo"); 321 | jdb.commit_batch(0, &blake256(b"0"), None).unwrap(); 322 | assert!(jdb.contains(&foo_hash)); 323 | 324 | jdb.remove(&foo_hash); 325 | jdb.commit_batch(1, &blake256(b"1"), Some((0, blake256(b"0")))).unwrap(); 326 | jdb.insert(b"foo"); 327 | assert!(jdb.contains(&foo_hash)); 328 | jdb.commit_batch(2, &blake256(b"2"), Some((1, blake256(b"1")))).unwrap(); 329 | assert!(jdb.contains(&foo_hash)); 330 | jdb.commit_batch(3, &blake256(b"2"), Some((0, blake256(b"2")))).unwrap(); 331 | assert!(jdb.contains(&foo_hash)); 332 | } 333 | 334 | #[test] 335 | fn fork_same_key() { 336 | // history is 1 337 | let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None); 338 | jdb.commit_batch(0, &blake256(b"0"), None).unwrap(); 339 | 340 | let foo_hash = jdb.insert(b"foo"); 341 | jdb.commit_batch(1, &blake256(b"1a"), Some((0, blake256(b"0")))).unwrap(); 342 | 343 | jdb.insert(b"foo"); 344 | jdb.commit_batch(1, &blake256(b"1b"), Some((0, blake256(b"0")))).unwrap(); 345 | assert!(jdb.contains(&foo_hash)); 346 | 347 | jdb.commit_batch(2, &blake256(b"2a"), Some((1, blake256(b"1a")))).unwrap(); 348 | assert!(jdb.contains(&foo_hash)); 349 | } 350 | 351 | #[test] 352 | fn reopen() { 353 | let shared_db = Arc::new(kvdb_memorydb::create(0)); 354 | 355 | let (foo_hash, bar_hash) = { 356 | let mut jdb = ArchiveDB::new(shared_db.clone(), None); 357 | // history is 1 358 | let foo_hash = jdb.insert(b"foo"); 359 | let bar_hash = jdb.insert(b"bar"); 360 | jdb.commit_batch(0, &blake256(b"0"), None).unwrap(); 361 | (foo_hash, bar_hash) 362 | }; 363 | 364 | { 365 | let mut jdb = ArchiveDB::new(shared_db.clone(), None); 366 | jdb.remove(&foo_hash); 367 | jdb.commit_batch(1, &blake256(b"1"), Some((0, blake256(b"0")))).unwrap(); 368 | } 369 | 370 | { 371 | let mut jdb = ArchiveDB::new(shared_db, None); 372 | assert!(jdb.contains(&foo_hash)); 373 | assert!(jdb.contains(&bar_hash)); 374 | jdb.commit_batch(2, &blake256(b"2"), Some((1, blake256(b"1")))).unwrap(); 375 | } 376 | } 377 | 378 | #[test] 379 | fn reopen_remove() { 380 | let shared_db = Arc::new(kvdb_memorydb::create(0)); 381 | 382 | let foo_hash = { 383 | let mut jdb = ArchiveDB::new(shared_db.clone(), None); 384 | // history is 1 385 | let foo_hash = jdb.insert(b"foo"); 386 | jdb.commit_batch(0, &blake256(b"0"), None).unwrap(); 387 | jdb.commit_batch(1, &blake256(b"1"), Some((0, blake256(b"0")))).unwrap(); 388 | 389 | // foo is ancient history. 390 | 391 | jdb.insert(b"foo"); 392 | jdb.commit_batch(2, &blake256(b"2"), Some((1, blake256(b"1")))).unwrap(); 393 | foo_hash 394 | }; 395 | 396 | { 397 | let mut jdb = ArchiveDB::new(shared_db, None); 398 | jdb.remove(&foo_hash); 399 | jdb.commit_batch(3, &blake256(b"3"), Some((2, blake256(b"2")))).unwrap(); 400 | assert!(jdb.contains(&foo_hash)); 401 | jdb.remove(&foo_hash); 402 | jdb.commit_batch(4, &blake256(b"4"), Some((3, blake256(b"3")))).unwrap(); 403 | jdb.commit_batch(5, &blake256(b"5"), Some((4, blake256(b"4")))).unwrap(); 404 | } 405 | } 406 | 407 | #[test] 408 | fn reopen_fork() { 409 | let shared_db = Arc::new(kvdb_memorydb::create(0)); 410 | let (foo_hash, ..) = { 411 | let mut jdb = ArchiveDB::new(shared_db.clone(), None); 412 | // history is 1 413 | let foo_hash = jdb.insert(b"foo"); 414 | let bar_hash = jdb.insert(b"bar"); 415 | jdb.commit_batch(0, &blake256(b"0"), None).unwrap(); 416 | jdb.remove(&foo_hash); 417 | let baz_hash = jdb.insert(b"baz"); 418 | jdb.commit_batch(1, &blake256(b"1a"), Some((0, blake256(b"0")))).unwrap(); 419 | 420 | jdb.remove(&bar_hash); 421 | jdb.commit_batch(1, &blake256(b"1b"), Some((0, blake256(b"0")))).unwrap(); 422 | (foo_hash, bar_hash, baz_hash) 423 | }; 424 | 425 | { 426 | let mut jdb = ArchiveDB::new(shared_db, None); 427 | jdb.commit_batch(2, &blake256(b"2b"), Some((1, blake256(b"1b")))).unwrap(); 428 | assert!(jdb.contains(&foo_hash)); 429 | } 430 | } 431 | 432 | #[test] 433 | fn return_state() { 434 | let shared_db = Arc::new(kvdb_memorydb::create(0)); 435 | 436 | let key = { 437 | let mut jdb = ArchiveDB::new(shared_db.clone(), None); 438 | let key = jdb.insert(b"foo"); 439 | jdb.commit_batch(0, &blake256(b"0"), None).unwrap(); 440 | key 441 | }; 442 | 443 | { 444 | let jdb = ArchiveDB::new(shared_db, None); 445 | let state = jdb.state(&key); 446 | assert_eq!(Some("foo".to_string().into_bytes()), state); 447 | } 448 | } 449 | 450 | #[test] 451 | fn inject() { 452 | let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None); 453 | let key = jdb.insert(b"dog"); 454 | jdb.inject_batch().unwrap(); 455 | 456 | assert_eq!(jdb.get(&key).unwrap(), b"dog".to_vec()); 457 | jdb.remove(&key); 458 | jdb.inject_batch().unwrap(); 459 | 460 | assert_eq!(None, jdb.get(&key)); 461 | } 462 | } 463 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------