openethereum/src/overlaydb.rs

296 lines
9.0 KiB
Rust
Raw Normal View History

2015-11-28 03:09:36 +01:00
//! Disk-backed HashDB implementation.
use error::*;
2015-11-28 03:09:36 +01:00
use hash::*;
use bytes::*;
2015-11-28 19:03:50 +01:00
use rlp::*;
2015-11-28 03:09:36 +01:00
use hashdb::*;
use memorydb::*;
use std::ops::*;
use std::sync::*;
2015-11-28 22:54:12 +01:00
use std::env;
2015-11-28 03:09:36 +01:00
use rocksdb::{DB, Writable};
#[derive(Clone)]
2015-11-28 23:49:07 +01:00
/// Implementation of the HashDB trait for a disk-backed database with a memory overlay.
///
/// The operations `insert()` and `kill()` take place on the memory overlay; batches of
/// such operations may be flushed to the disk-backed DB with `commit()` or discarded with
/// `revert()`.
///
/// `lookup()` and `exists()` maintain normal behaviour - all `insert()` and `kill()`
/// queries have an immediate effect in terms of these functions.
2015-11-28 03:09:36 +01:00
pub struct OverlayDB {
overlay: MemoryDB,
backing: Arc<DB>,
2015-11-28 03:09:36 +01:00
}
impl OverlayDB {
/// Create a new instance of OverlayDB given a `backing` database.
2015-11-28 19:28:59 +01:00
pub fn new(backing: DB) -> OverlayDB {
OverlayDB{ overlay: MemoryDB::new(), backing: Arc::new(backing) }
2015-11-28 03:09:36 +01:00
}
2015-11-28 22:54:12 +01:00
/// Create a new instance of OverlayDB with an anonymous temporary database.
pub fn new_temp() -> OverlayDB {
let mut dir = env::temp_dir();
dir.push(H32::random().hex());
Self::new(DB::open_default(dir.to_str().unwrap()).unwrap())
}
2015-11-28 23:49:07 +01:00
/// Commit all memory operations to the backing database.
///
/// Returns either an error or the number of items changed in the backing database.
///
/// Will return an error if the number of `kill()`s ever exceeds the number of
/// `insert()`s for any key. This will leave the database in an undeterminate
/// state. Don't ever let it happen.
///
/// # Example
/// ```
/// extern crate ethcore_util;
/// use ethcore_util::hashdb::*;
/// use ethcore_util::overlaydb::*;
/// fn main() {
/// let mut m = OverlayDB::new_temp();
/// let key = m.insert(b"foo"); // insert item.
/// assert!(m.exists(&key)); // key exists (in memory).
/// assert_eq!(m.commit().unwrap(), 1); // 1 item changed.
/// assert!(m.exists(&key)); // key still exists (in backing).
/// m.kill(&key); // delete item.
/// assert!(!m.exists(&key)); // key "doesn't exist" (though still does in backing).
/// m.kill(&key); // oh dear... more kills than inserts for the key...
/// //m.commit().unwrap(); // this commit/unwrap would cause a panic.
/// m.revert(); // revert both kills.
/// assert!(m.exists(&key)); // key now still exists.
/// }
/// ```
2015-11-28 19:28:59 +01:00
pub fn commit(&mut self) -> Result<u32, EthcoreError> {
let mut ret = 0u32;
for i in self.overlay.drain().into_iter() {
let (key, (value, rc)) = i;
if rc != 0 {
2015-11-28 19:28:59 +01:00
match self.payload(&key) {
Some(x) => {
let (back_value, back_rc) = x;
2015-11-28 19:28:59 +01:00
let total_rc: i32 = back_rc as i32 + rc;
if total_rc < 0 {
return Err(From::from(BaseDataError::NegativelyReferencedHash));
}
2015-11-28 19:28:59 +01:00
self.put_payload(&key, (back_value, total_rc as u32));
}
None => {
2015-11-28 19:28:59 +01:00
if rc < 0 {
return Err(From::from(BaseDataError::NegativelyReferencedHash));
}
self.put_payload(&key, (value, rc as u32));
}
};
ret += 1;
}
}
Ok(ret)
2015-11-28 03:09:36 +01:00
}
2015-11-28 23:54:58 +01:00
/// Revert all operations on this object (i.e. `insert()`s and `kill()`s) since the
2015-11-28 23:49:07 +01:00
/// last `commit()`.
2015-11-28 23:54:58 +01:00
///
/// # Example
/// ```
/// extern crate ethcore_util;
/// use ethcore_util::hashdb::*;
/// use ethcore_util::overlaydb::*;
/// fn main() {
/// let mut m = OverlayDB::new_temp();
/// let foo = m.insert(b"foo"); // insert foo.
/// m.commit().unwrap(); // commit - new operations begin here...
/// let bar = m.insert(b"bar"); // insert bar.
/// m.kill(&foo); // kill foo.
/// assert!(!m.exists(&foo)); // foo is gone.
/// assert!(m.exists(&bar)); // bar is here.
/// m.revert(); // revert the last two operations.
/// assert!(m.exists(&foo)); // foo is here.
/// assert!(!m.exists(&bar)); // bar is gone.
/// }
/// ```
2015-11-28 22:54:12 +01:00
pub fn revert(&mut self) { self.overlay.clear(); }
2015-11-28 03:09:36 +01:00
/// Get the refs and value of the given key.
2015-11-28 19:28:59 +01:00
fn payload(&self, key: &H256) -> Option<(Bytes, u32)> {
self.backing.get(&key.bytes())
2015-11-28 19:03:50 +01:00
.expect("Low-level database error. Some issue with your hard disk?")
.map(|d| {
2015-11-28 19:28:59 +01:00
let r = Rlp::new(d.deref());
2015-11-29 09:28:48 +01:00
(Bytes::decode(&r.at(1)), u32::decode(&r.at(0)))
2015-11-28 19:03:50 +01:00
})
2015-11-28 03:09:36 +01:00
}
/// Get the refs and value of the given key.
2015-11-28 19:28:59 +01:00
fn put_payload(&self, key: &H256, payload: (Bytes, u32)) {
2015-11-28 19:03:50 +01:00
let mut s = RlpStream::new_list(2);
2015-11-28 19:28:59 +01:00
s.append(&payload.1);
s.append(&payload.0);
self.backing.put(&key.bytes(), &s.out()).expect("Low-level database error. Some issue with your hard disk?");
}
2015-11-28 03:09:36 +01:00
}
impl HashDB for OverlayDB {
2015-11-29 15:50:33 +01:00
fn lookup(&self, key: &H256) -> Option<&[u8]> {
// return ok if positive; if negative, check backing - might be enough references there to make
2015-11-28 03:09:36 +01:00
// it positive again.
let k = self.overlay.raw(key);
2015-11-28 03:09:36 +01:00
match k {
2015-11-29 15:50:33 +01:00
Some(&(ref d, rc)) if rc > 0 => Some(d),
2015-11-28 03:09:36 +01:00
_ => {
let memrc = k.map(|&(_, rc)| rc).unwrap_or(0);
match self.payload(key) {
Some(x) => {
let (d, rc) = x;
2015-11-28 19:28:59 +01:00
if rc as i32 + memrc > 0 {
2015-11-29 15:50:33 +01:00
Some(&self.overlay.denote(key, d).0)
}
else {
None
}
}
// Replace above match arm with this once https://github.com/rust-lang/rust/issues/15287 is done.
//Some((d, rc)) if rc + memrc > 0 => Some(d),
2015-11-28 03:09:36 +01:00
_ => None,
}
}
}
}
fn exists(&self, key: &H256) -> bool {
// return ok if positive; if negative, check backing - might be enough references there to make
// it positive again.
let k = self.overlay.raw(key);
match k {
2015-11-28 19:28:59 +01:00
Some(&(_, rc)) if rc > 0 => true,
_ => {
let memrc = k.map(|&(_, rc)| rc).unwrap_or(0);
match self.payload(key) {
Some(x) => {
2015-11-28 19:28:59 +01:00
let (_, rc) = x;
if rc as i32 + memrc > 0 {
true
}
else {
false
}
}
// Replace above match arm with this once https://github.com/rust-lang/rust/issues/15287 is done.
//Some((d, rc)) if rc + memrc > 0 => true,
_ => false,
}
}
}
2015-11-28 03:09:36 +01:00
}
fn insert(&mut self, value: &[u8]) -> H256 { self.overlay.insert(value) }
2015-11-30 02:57:02 +01:00
fn emplace(&mut self, key: H256, value: Bytes) { self.overlay.emplace(key, value); }
fn kill(&mut self, key: &H256) { self.overlay.kill(key); }
2015-11-28 03:09:36 +01:00
}
2015-11-28 22:54:12 +01:00
#[test]
fn overlaydb_overlay_insert_and_kill() {
let mut trie = OverlayDB::new_temp();
let h = trie.insert(b"hello world");
2015-11-29 15:50:33 +01:00
assert_eq!(trie.lookup(&h).unwrap(), b"hello world");
2015-11-28 22:54:12 +01:00
trie.kill(&h);
assert_eq!(trie.lookup(&h), None);
}
#[test]
fn overlaydb_backing_insert_revert() {
let mut trie = OverlayDB::new_temp();
let h = trie.insert(b"hello world");
2015-11-29 15:50:33 +01:00
assert_eq!(trie.lookup(&h).unwrap(), b"hello world");
2015-11-28 22:54:12 +01:00
trie.commit().unwrap();
2015-11-29 15:50:33 +01:00
assert_eq!(trie.lookup(&h).unwrap(), b"hello world");
2015-11-28 22:54:12 +01:00
trie.revert();
2015-11-29 15:50:33 +01:00
assert_eq!(trie.lookup(&h).unwrap(), b"hello world");
2015-11-28 22:54:12 +01:00
}
#[test]
fn overlaydb_backing_kill() {
let mut trie = OverlayDB::new_temp();
let h = trie.insert(b"hello world");
trie.commit().unwrap();
trie.kill(&h);
assert_eq!(trie.lookup(&h), None);
trie.commit().unwrap();
assert_eq!(trie.lookup(&h), None);
trie.revert();
assert_eq!(trie.lookup(&h), None);
}
#[test]
fn overlaydb_backing_kill_revert() {
let mut trie = OverlayDB::new_temp();
let h = trie.insert(b"hello world");
trie.commit().unwrap();
trie.kill(&h);
assert_eq!(trie.lookup(&h), None);
trie.revert();
2015-11-29 15:50:33 +01:00
assert_eq!(trie.lookup(&h).unwrap(), b"hello world");
2015-11-28 22:54:12 +01:00
}
#[test]
fn overlaydb_negative() {
let mut trie = OverlayDB::new_temp();
let h = trie.insert(b"hello world");
trie.commit().unwrap();
trie.kill(&h);
trie.kill(&h); //bad - sends us into negative refs.
assert_eq!(trie.lookup(&h), None);
assert!(trie.commit().is_err());
}
#[test]
fn overlaydb_complex() {
let mut trie = OverlayDB::new_temp();
let hfoo = trie.insert(b"foo");
2015-11-29 15:50:33 +01:00
assert_eq!(trie.lookup(&hfoo).unwrap(), b"foo");
2015-11-28 22:54:12 +01:00
let hbar = trie.insert(b"bar");
2015-11-29 15:50:33 +01:00
assert_eq!(trie.lookup(&hbar).unwrap(), b"bar");
2015-11-28 22:54:12 +01:00
trie.commit().unwrap();
2015-11-29 15:50:33 +01:00
assert_eq!(trie.lookup(&hfoo).unwrap(), b"foo");
assert_eq!(trie.lookup(&hbar).unwrap(), b"bar");
2015-11-28 22:54:12 +01:00
trie.insert(b"foo"); // two refs
2015-11-29 15:50:33 +01:00
assert_eq!(trie.lookup(&hfoo).unwrap(), b"foo");
2015-11-28 22:54:12 +01:00
trie.commit().unwrap();
2015-11-29 15:50:33 +01:00
assert_eq!(trie.lookup(&hfoo).unwrap(), b"foo");
assert_eq!(trie.lookup(&hbar).unwrap(), b"bar");
2015-11-28 22:54:12 +01:00
trie.kill(&hbar); // zero refs - delete
assert_eq!(trie.lookup(&hbar), None);
trie.kill(&hfoo); // one ref - keep
2015-11-29 15:50:33 +01:00
assert_eq!(trie.lookup(&hfoo).unwrap(), b"foo");
2015-11-28 22:54:12 +01:00
trie.commit().unwrap();
2015-11-29 15:50:33 +01:00
assert_eq!(trie.lookup(&hfoo).unwrap(), b"foo");
2015-11-28 22:54:12 +01:00
trie.kill(&hfoo); // zero ref - would delete, but...
assert_eq!(trie.lookup(&hfoo), None);
trie.insert(b"foo"); // one ref - keep after all.
2015-11-29 15:50:33 +01:00
assert_eq!(trie.lookup(&hfoo).unwrap(), b"foo");
2015-11-28 22:54:12 +01:00
trie.commit().unwrap();
2015-11-29 15:50:33 +01:00
assert_eq!(trie.lookup(&hfoo).unwrap(), b"foo");
2015-11-28 22:54:12 +01:00
trie.kill(&hfoo); // zero ref - delete
assert_eq!(trie.lookup(&hfoo), None);
trie.commit().unwrap(); //
assert_eq!(trie.lookup(&hfoo), None);
}
2015-11-28 03:09:36 +01:00
#[test]
fn playpen() {
2015-11-28 22:54:12 +01:00
use std::fs;
{
let db: DB = DB::open_default("/tmp/test").unwrap();
db.put(b"test", b"test2").unwrap();
match db.get(b"test") {
Ok(Some(value)) => println!("Got value {:?}", value.deref()),
Ok(None) => println!("No value for that key"),
Err(..) => println!("Gah"),
}
db.delete(b"test").unwrap();
2015-11-28 03:09:36 +01:00
}
2015-11-28 22:54:12 +01:00
fs::remove_dir_all("/tmp/test").unwrap();
2015-11-29 09:16:15 +01:00
}