openethereum/util/journaldb/src/archivedb.rs

468 lines
13 KiB
Rust
Raw Normal View History

// Copyright 2015-2017 Parity Technologies (UK) Ltd.
2016-03-11 13:50:39 +01:00
// This file is part of Parity.
// Parity 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
// (at your option) any later version.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
2016-04-06 10:07:24 +02:00
//! Disk-backed `HashDB` implementation.
2016-03-11 13:50:39 +01:00
2017-07-29 17:12:07 +02:00
use std::collections::HashMap;
2017-08-26 19:09:32 +02:00
use std::collections::hash_map::Entry;
2017-07-29 21:56:42 +02:00
use std::sync::Arc;
use rlp::{encode, decode};
2016-03-11 13:50:39 +01:00
use hashdb::*;
use super::memorydb::*;
use super::{DB_PREFIX_LEN, LATEST_ERA_KEY};
use traits::JournalDB;
use kvdb::{KeyValueDB, DBTransaction};
use ethereum_types::H256;
use error::{BaseDataError, UtilError};
use bytes::Bytes;
2016-03-11 13:50:39 +01:00
2016-04-06 10:07:24 +02:00
/// Implementation of the `HashDB` trait for a disk-backed database with a memory overlay
2016-03-11 13:50:39 +01:00
/// and latent-removal semantics.
///
2016-04-06 10:07:24 +02:00
/// Like `OverlayDB`, there is a memory overlay; `commit()` must be called in order to
/// write operations out to disk. Unlike `OverlayDB`, `remove()` operations do not take effect
/// immediately. As this is an "archive" database, nothing is ever removed. This means
/// that the states of any block the node has ever processed will be accessible.
2016-03-11 13:50:39 +01:00
pub struct ArchiveDB {
overlay: MemoryDB,
backing: Arc<KeyValueDB>,
latest_era: Option<u64>,
column: Option<u32>,
2016-03-11 13:50:39 +01:00
}
impl ArchiveDB {
/// Create a new instance from a key-value db.
[beta] Backports (#8624) * Trace precompiled contracts when the transfer value is not zero (#8486) * Trace precompiled contracts when the transfer value is not zero * Add tests for precompiled CALL tracing * Use byzantium test machine for the new test * Add notes in comments on why we don't trace all precompileds * Use is_transferred instead of transferred * Return error if RLP size of transaction exceeds the limit (#8473) * Return error if RLP size of transaction exceeds the limit * Review comments fixed * RLP check moved to verifier, corresponding pool test added * Don't block sync when importing old blocks (#8530) * Alter IO queueing. * Don't require IoMessages to be Clone * Ancient blocks imported via IoChannel. * Get rid of private transactions io message. * Get rid of deadlock and fix disconnected handler. * Revert to old disconnect condition. * Fix tests. * Fix deadlock. * Refactoring `ethcore-sync` - Fixing warp-sync barrier (#8543) * Start dividing sync chain : first supplier method * WIP - updated chain sync supplier * Finish refactoring the Chain Sync Supplier * Create Chain Sync Requester * Add Propagator for Chain Sync * Add the Chain Sync Handler * Move tests from mod -> handler * Move tests to propagator * Refactor SyncRequester arguments * Refactoring peer fork header handler * Fix wrong highest block number in snapshot sync * Small refactor... * Address PR grumbles * Retry failed CI job * Fix tests * PR Grumbles * Handle socket address parsing errors (#8545) Unpack errors and check for io::ErrorKind::InvalidInput and return our own AddressParse error. Remove the foreign link to std::net::AddrParseError and add an `impl From` for that error. Test parsing properly. * Fix packet count when talking with PAR2 peers (#8555) * Support diferent packet counts in different protocol versions. * Fix light timeouts and eclipse protection. * Fix devp2p tests. * Fix whisper-cli compilation. * Fix compilation. * Fix ethcore-sync tests. * Revert "Fix light timeouts and eclipse protection." This reverts commit 06285ea8c1d9d184d809f64b5507aece633da6cc. * Increase timeouts. * Add whisper CLI to the pipelines (#8578) * Add whisper CLI to the pipelines * Address todo, ref #8579 * Rename `whisper-cli binary` to `whisper` (#8579) * rename whisper-cli binary to whisper * fix tests * Remove manually added text to the errors (#8595) These messages were confusing for the users especially the help message. * Fix account list double 0x display (#8596) * Remove unused self import * Fix account list double 0x display * Fix BlockReward contract "arithmetic operation overflow" (#8611) * Fix BlockReward contract "arithmetic operation overflow" * Add docs on how execute_as_system works * Fix typo * Rlp decode returns Result (#8527) rlp::decode returns Result Make a best effort to handle decoding errors gracefully throughout the code, using `expect` where the value is guaranteed to be valid (and in other places where it makes sense). * Remove expect (#8536) * Remove expect and propagate rlp::DecoderErrors as TrieErrors * Decoding headers can fail (#8570) * rlp::decode returns Result * Fix journaldb to handle rlp::decode Result * Fix ethcore to work with rlp::decode returning Result * Light client handles rlp::decode returning Result * Fix tests in rlp_derive * Fix tests * Cleanup * cleanup * Allow panic rather than breaking out of iterator * Let decoding failures when reading from disk blow up * syntax * Fix the trivial grumbles * Fix failing tests * Make Account::from_rlp return Result * Syntx, sigh * Temp-fix for decoding failures * Header::decode returns Result Handle new return type throughout the code base. * Do not continue reading from the DB when a value could not be read * Fix tests * Handle header decoding in light_sync * Handling header decoding errors * Let the DecodeError bubble up unchanged * Remove redundant error conversion * fix compiler warning (#8590) * Attempt to fix intermittent test failures (#8584) Occasionally should_return_correct_nonces_when_dropped_because_of_limit fails, possibly because of multiple threads competing to finish. See CI logs here for an example: https://gitlab.parity.io/parity/parity/-/jobs/86738 * block_header can fail so return Result (#8581) * block_header can fail so return Result * Restore previous return type based on feedback * Fix failing doc tests running on non-code * Block::decode() returns Result (#8586) * Gitlab test script fixes (#8573) * Exclude /docs from modified files. * Ensure all references in the working tree are available * Remove duplicated line from test script
2018-05-15 07:41:30 +02:00
pub fn new(backing: Arc<KeyValueDB>, column: Option<u32>) -> ArchiveDB {
let latest_era = backing.get(column, &LATEST_ERA_KEY)
.expect("Low-level database error.")
.map(|val| decode::<u64>(&val).expect("decoding db value failed"));
2016-03-11 13:50:39 +01:00
ArchiveDB {
overlay: MemoryDB::new(),
[beta] Backports (#8624) * Trace precompiled contracts when the transfer value is not zero (#8486) * Trace precompiled contracts when the transfer value is not zero * Add tests for precompiled CALL tracing * Use byzantium test machine for the new test * Add notes in comments on why we don't trace all precompileds * Use is_transferred instead of transferred * Return error if RLP size of transaction exceeds the limit (#8473) * Return error if RLP size of transaction exceeds the limit * Review comments fixed * RLP check moved to verifier, corresponding pool test added * Don't block sync when importing old blocks (#8530) * Alter IO queueing. * Don't require IoMessages to be Clone * Ancient blocks imported via IoChannel. * Get rid of private transactions io message. * Get rid of deadlock and fix disconnected handler. * Revert to old disconnect condition. * Fix tests. * Fix deadlock. * Refactoring `ethcore-sync` - Fixing warp-sync barrier (#8543) * Start dividing sync chain : first supplier method * WIP - updated chain sync supplier * Finish refactoring the Chain Sync Supplier * Create Chain Sync Requester * Add Propagator for Chain Sync * Add the Chain Sync Handler * Move tests from mod -> handler * Move tests to propagator * Refactor SyncRequester arguments * Refactoring peer fork header handler * Fix wrong highest block number in snapshot sync * Small refactor... * Address PR grumbles * Retry failed CI job * Fix tests * PR Grumbles * Handle socket address parsing errors (#8545) Unpack errors and check for io::ErrorKind::InvalidInput and return our own AddressParse error. Remove the foreign link to std::net::AddrParseError and add an `impl From` for that error. Test parsing properly. * Fix packet count when talking with PAR2 peers (#8555) * Support diferent packet counts in different protocol versions. * Fix light timeouts and eclipse protection. * Fix devp2p tests. * Fix whisper-cli compilation. * Fix compilation. * Fix ethcore-sync tests. * Revert "Fix light timeouts and eclipse protection." This reverts commit 06285ea8c1d9d184d809f64b5507aece633da6cc. * Increase timeouts. * Add whisper CLI to the pipelines (#8578) * Add whisper CLI to the pipelines * Address todo, ref #8579 * Rename `whisper-cli binary` to `whisper` (#8579) * rename whisper-cli binary to whisper * fix tests * Remove manually added text to the errors (#8595) These messages were confusing for the users especially the help message. * Fix account list double 0x display (#8596) * Remove unused self import * Fix account list double 0x display * Fix BlockReward contract "arithmetic operation overflow" (#8611) * Fix BlockReward contract "arithmetic operation overflow" * Add docs on how execute_as_system works * Fix typo * Rlp decode returns Result (#8527) rlp::decode returns Result Make a best effort to handle decoding errors gracefully throughout the code, using `expect` where the value is guaranteed to be valid (and in other places where it makes sense). * Remove expect (#8536) * Remove expect and propagate rlp::DecoderErrors as TrieErrors * Decoding headers can fail (#8570) * rlp::decode returns Result * Fix journaldb to handle rlp::decode Result * Fix ethcore to work with rlp::decode returning Result * Light client handles rlp::decode returning Result * Fix tests in rlp_derive * Fix tests * Cleanup * cleanup * Allow panic rather than breaking out of iterator * Let decoding failures when reading from disk blow up * syntax * Fix the trivial grumbles * Fix failing tests * Make Account::from_rlp return Result * Syntx, sigh * Temp-fix for decoding failures * Header::decode returns Result Handle new return type throughout the code base. * Do not continue reading from the DB when a value could not be read * Fix tests * Handle header decoding in light_sync * Handling header decoding errors * Let the DecodeError bubble up unchanged * Remove redundant error conversion * fix compiler warning (#8590) * Attempt to fix intermittent test failures (#8584) Occasionally should_return_correct_nonces_when_dropped_because_of_limit fails, possibly because of multiple threads competing to finish. See CI logs here for an example: https://gitlab.parity.io/parity/parity/-/jobs/86738 * block_header can fail so return Result (#8581) * block_header can fail so return Result * Restore previous return type based on feedback * Fix failing doc tests running on non-code * Block::decode() returns Result (#8586) * Gitlab test script fixes (#8573) * Exclude /docs from modified files. * Ensure all references in the working tree are available * Remove duplicated line from test script
2018-05-15 07:41:30 +02:00
backing,
latest_era,
column,
2016-03-11 13:50:39 +01:00
}
}
2016-10-26 13:53:47 +02:00
fn payload(&self, key: &H256) -> Option<DBValue> {
self.backing.get(self.column, key).expect("Low-level database error. Some issue with your hard disk?")
2016-03-11 13:50:39 +01:00
}
}
impl HashDB for ArchiveDB {
fn keys(&self) -> HashMap<H256, i32> {
2017-08-26 19:09:32 +02:00
let mut ret: HashMap<H256, i32> = self.backing.iter(self.column)
.map(|(key, _)| (H256::from_slice(&*key), 1))
.collect();
2016-03-11 13:50:39 +01:00
for (key, refs) in self.overlay.keys() {
2017-08-26 19:09:32 +02:00
match ret.entry(key) {
Entry::Occupied(mut entry) => {
*entry.get_mut() += refs;
},
Entry::Vacant(entry) => {
2017-08-26 19:16:08 +02:00
entry.insert(refs);
2017-08-26 19:09:32 +02:00
}
}
2016-03-11 13:50:39 +01:00
}
ret
}
2016-10-26 13:53:47 +02:00
fn get(&self, key: &H256) -> Option<DBValue> {
2017-08-26 19:09:32 +02:00
if let Some((d, rc)) = self.overlay.raw(key) {
if rc > 0 {
return Some(d);
}
2016-03-11 13:50:39 +01:00
}
2016-10-26 13:53:47 +02:00
self.payload(key)
2016-03-11 13:50:39 +01:00
}
fn contains(&self, key: &H256) -> bool {
self.get(key).is_some()
2016-03-11 13:50:39 +01:00
}
fn insert(&mut self, value: &[u8]) -> H256 {
self.overlay.insert(value)
}
2016-10-26 13:53:47 +02:00
fn emplace(&mut self, key: H256, value: DBValue) {
2016-03-11 13:50:39 +01:00
self.overlay.emplace(key, value);
}
fn remove(&mut self, key: &H256) {
self.overlay.remove(key);
2016-03-11 13:50:39 +01:00
}
}
impl JournalDB for ArchiveDB {
2016-03-28 09:42:50 +02:00
fn boxed_clone(&self) -> Box<JournalDB> {
2016-03-11 13:50:39 +01:00
Box::new(ArchiveDB {
2016-03-27 14:35:27 +02:00
overlay: self.overlay.clone(),
2016-03-11 13:50:39 +01:00
backing: self.backing.clone(),
2016-03-13 19:22:42 +01:00
latest_era: self.latest_era,
column: self.column.clone(),
2016-03-11 13:50:39 +01:00
})
}
fn mem_used(&self) -> usize {
self.overlay.mem_used()
}
fn is_empty(&self) -> bool {
self.latest_era.is_none()
2016-03-11 13:50:39 +01:00
}
fn journal_under(&mut self, batch: &mut DBTransaction, now: u64, _id: &H256) -> Result<u32, UtilError> {
2016-03-11 13:50:39 +01:00
let mut inserts = 0usize;
let mut deletes = 0usize;
2016-06-27 09:16:34 +02:00
for i in self.overlay.drain() {
2016-03-11 13:50:39 +01:00
let (key, (value, rc)) = i;
if rc > 0 {
batch.put(self.column, &key, &value);
2016-03-11 13:50:39 +01:00
inserts += 1;
}
if rc < 0 {
assert!(rc == -1);
deletes += 1;
}
}
2016-06-27 09:16:34 +02:00
2016-03-13 19:22:42 +01:00
if self.latest_era.map_or(true, |e| now > e) {
batch.put(self.column, &LATEST_ERA_KEY, &encode(&now));
2016-03-13 19:22:42 +01:00
self.latest_era = Some(now);
}
2016-03-11 13:50:39 +01:00
Ok((inserts + deletes) as u32)
}
2016-03-11 19:15:56 +01:00
fn mark_canonical(&mut self, _batch: &mut DBTransaction, _end_era: u64, _canon_id: &H256) -> Result<u32, UtilError> {
// keep everything! it's an archive, after all.
Ok(0)
}
fn inject(&mut self, batch: &mut DBTransaction) -> Result<u32, UtilError> {
let mut inserts = 0usize;
let mut deletes = 0usize;
for i in self.overlay.drain() {
let (key, (value, rc)) = i;
if rc > 0 {
if self.backing.get(self.column, &key)?.is_some() {
return Err(BaseDataError::AlreadyExists(key).into());
}
batch.put(self.column, &key, &value);
inserts += 1;
}
if rc < 0 {
assert!(rc == -1);
if self.backing.get(self.column, &key)?.is_none() {
return Err(BaseDataError::NegativelyReferencedHash(key).into());
}
batch.delete(self.column, &key);
deletes += 1;
}
}
Ok((inserts + deletes) as u32)
}
2016-04-12 03:42:50 +02:00
fn latest_era(&self) -> Option<u64> { self.latest_era }
2016-04-12 00:51:14 +02:00
2016-03-11 19:15:56 +01:00
fn state(&self, id: &H256) -> Option<Bytes> {
2017-06-28 09:36:42 +02:00
self.backing.get_by_prefix(self.column, &id[0..DB_PREFIX_LEN]).map(|b| b.into_vec())
2016-03-11 19:15:56 +01:00
}
2016-06-03 12:10:10 +02:00
fn is_pruned(&self) -> bool { false }
fn backing(&self) -> &Arc<KeyValueDB> {
&self.backing
}
fn consolidate(&mut self, with: MemoryDB) {
self.overlay.consolidate(with);
}
2016-03-11 13:50:39 +01:00
}
#[cfg(test)]
mod tests {
2016-03-18 10:14:19 +01:00
use keccak::keccak;
2016-11-28 17:05:37 +01:00
use hashdb::{HashDB, DBValue};
2016-03-11 13:50:39 +01:00
use super::*;
2017-10-17 10:40:45 +02:00
use {kvdb_memorydb, JournalDB};
2016-03-11 13:50:39 +01:00
#[test]
fn insert_same_in_fork() {
// history is 1
let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None);
2016-03-11 13:50:39 +01:00
let x = jdb.insert(b"X");
jdb.commit_batch(1, &keccak(b"1"), None).unwrap();
jdb.commit_batch(2, &keccak(b"2"), None).unwrap();
jdb.commit_batch(3, &keccak(b"1002a"), Some((1, keccak(b"1")))).unwrap();
jdb.commit_batch(4, &keccak(b"1003a"), Some((2, keccak(b"2")))).unwrap();
2016-03-11 13:50:39 +01:00
jdb.remove(&x);
jdb.commit_batch(3, &keccak(b"1002b"), Some((1, keccak(b"1")))).unwrap();
2016-03-11 13:50:39 +01:00
let x = jdb.insert(b"X");
jdb.commit_batch(4, &keccak(b"1003b"), Some((2, keccak(b"2")))).unwrap();
2016-03-11 13:50:39 +01:00
jdb.commit_batch(5, &keccak(b"1004a"), Some((3, keccak(b"1002a")))).unwrap();
jdb.commit_batch(6, &keccak(b"1005a"), Some((4, keccak(b"1003a")))).unwrap();
2016-03-11 13:50:39 +01:00
assert!(jdb.contains(&x));
2016-03-11 13:50:39 +01:00
}
#[test]
fn long_history() {
// history is 3
let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None);
2016-03-11 13:50:39 +01:00
let h = jdb.insert(b"foo");
jdb.commit_batch(0, &keccak(b"0"), None).unwrap();
assert!(jdb.contains(&h));
2016-03-11 13:50:39 +01:00
jdb.remove(&h);
jdb.commit_batch(1, &keccak(b"1"), None).unwrap();
assert!(jdb.contains(&h));
jdb.commit_batch(2, &keccak(b"2"), None).unwrap();
assert!(jdb.contains(&h));
jdb.commit_batch(3, &keccak(b"3"), Some((0, keccak(b"0")))).unwrap();
assert!(jdb.contains(&h));
jdb.commit_batch(4, &keccak(b"4"), Some((1, keccak(b"1")))).unwrap();
assert!(jdb.contains(&h));
2016-03-11 13:50:39 +01:00
}
2017-06-09 18:23:25 +02:00
#[test]
#[should_panic]
fn multiple_owed_removal_not_allowed() {
let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None);
2017-06-09 18:23:25 +02:00
let h = jdb.insert(b"foo");
jdb.commit_batch(0, &keccak(b"0"), None).unwrap();
2017-06-09 18:23:25 +02:00
assert!(jdb.contains(&h));
jdb.remove(&h);
jdb.remove(&h);
// commit_batch would call journal_under(),
// and we don't allow multiple owned removals.
jdb.commit_batch(1, &keccak(b"1"), None).unwrap();
2017-06-09 18:23:25 +02:00
}
2016-03-11 13:50:39 +01:00
#[test]
fn complex() {
// history is 1
let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None);
2016-03-11 13:50:39 +01:00
let foo = jdb.insert(b"foo");
let bar = jdb.insert(b"bar");
jdb.commit_batch(0, &keccak(b"0"), None).unwrap();
assert!(jdb.contains(&foo));
assert!(jdb.contains(&bar));
2016-03-11 13:50:39 +01:00
jdb.remove(&foo);
jdb.remove(&bar);
let baz = jdb.insert(b"baz");
jdb.commit_batch(1, &keccak(b"1"), Some((0, keccak(b"0")))).unwrap();
assert!(jdb.contains(&foo));
assert!(jdb.contains(&bar));
assert!(jdb.contains(&baz));
2016-03-11 13:50:39 +01:00
let foo = jdb.insert(b"foo");
jdb.remove(&baz);
jdb.commit_batch(2, &keccak(b"2"), Some((1, keccak(b"1")))).unwrap();
assert!(jdb.contains(&foo));
assert!(jdb.contains(&baz));
2016-03-11 13:50:39 +01:00
jdb.remove(&foo);
jdb.commit_batch(3, &keccak(b"3"), Some((2, keccak(b"2")))).unwrap();
assert!(jdb.contains(&foo));
2016-03-11 13:50:39 +01:00
jdb.commit_batch(4, &keccak(b"4"), Some((3, keccak(b"3")))).unwrap();
2016-03-11 13:50:39 +01:00
}
#[test]
fn fork() {
// history is 1
let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None);
2016-03-11 13:50:39 +01:00
let foo = jdb.insert(b"foo");
let bar = jdb.insert(b"bar");
jdb.commit_batch(0, &keccak(b"0"), None).unwrap();
assert!(jdb.contains(&foo));
assert!(jdb.contains(&bar));
2016-03-11 13:50:39 +01:00
jdb.remove(&foo);
let baz = jdb.insert(b"baz");
jdb.commit_batch(1, &keccak(b"1a"), Some((0, keccak(b"0")))).unwrap();
2016-03-11 13:50:39 +01:00
jdb.remove(&bar);
jdb.commit_batch(1, &keccak(b"1b"), Some((0, keccak(b"0")))).unwrap();
2016-03-11 13:50:39 +01:00
assert!(jdb.contains(&foo));
assert!(jdb.contains(&bar));
assert!(jdb.contains(&baz));
2016-03-11 13:50:39 +01:00
jdb.commit_batch(2, &keccak(b"2b"), Some((1, keccak(b"1b")))).unwrap();
assert!(jdb.contains(&foo));
2016-03-11 13:50:39 +01:00
}
#[test]
fn overwrite() {
// history is 1
let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None);
2016-03-11 13:50:39 +01:00
let foo = jdb.insert(b"foo");
jdb.commit_batch(0, &keccak(b"0"), None).unwrap();
assert!(jdb.contains(&foo));
2016-03-11 13:50:39 +01:00
jdb.remove(&foo);
jdb.commit_batch(1, &keccak(b"1"), Some((0, keccak(b"0")))).unwrap();
2016-03-11 13:50:39 +01:00
jdb.insert(b"foo");
assert!(jdb.contains(&foo));
jdb.commit_batch(2, &keccak(b"2"), Some((1, keccak(b"1")))).unwrap();
assert!(jdb.contains(&foo));
jdb.commit_batch(3, &keccak(b"2"), Some((0, keccak(b"2")))).unwrap();
assert!(jdb.contains(&foo));
2016-03-11 13:50:39 +01:00
}
#[test]
fn fork_same_key() {
// history is 1
let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None);
jdb.commit_batch(0, &keccak(b"0"), None).unwrap();
2016-03-11 13:50:39 +01:00
let foo = jdb.insert(b"foo");
jdb.commit_batch(1, &keccak(b"1a"), Some((0, keccak(b"0")))).unwrap();
2016-03-11 13:50:39 +01:00
jdb.insert(b"foo");
jdb.commit_batch(1, &keccak(b"1b"), Some((0, keccak(b"0")))).unwrap();
assert!(jdb.contains(&foo));
2016-03-11 13:50:39 +01:00
jdb.commit_batch(2, &keccak(b"2a"), Some((1, keccak(b"1a")))).unwrap();
assert!(jdb.contains(&foo));
2016-03-11 13:50:39 +01:00
}
#[test]
fn reopen() {
let shared_db = Arc::new(kvdb_memorydb::create(0));
2016-03-11 13:50:39 +01:00
let bar = H256::random();
let foo = {
let mut jdb = ArchiveDB::new(shared_db.clone(), None);
2016-03-11 13:50:39 +01:00
// history is 1
let foo = jdb.insert(b"foo");
2016-10-26 13:53:47 +02:00
jdb.emplace(bar.clone(), DBValue::from_slice(b"bar"));
jdb.commit_batch(0, &keccak(b"0"), None).unwrap();
2016-03-11 13:50:39 +01:00
foo
};
{
let mut jdb = ArchiveDB::new(shared_db.clone(), None);
2016-03-11 13:50:39 +01:00
jdb.remove(&foo);
jdb.commit_batch(1, &keccak(b"1"), Some((0, keccak(b"0")))).unwrap();
2016-03-11 13:50:39 +01:00
}
{
let mut jdb = ArchiveDB::new(shared_db, None);
assert!(jdb.contains(&foo));
assert!(jdb.contains(&bar));
jdb.commit_batch(2, &keccak(b"2"), Some((1, keccak(b"1")))).unwrap();
2016-03-11 13:50:39 +01:00
}
}
#[test]
fn reopen_remove() {
let shared_db = Arc::new(kvdb_memorydb::create(0));
2016-03-11 13:50:39 +01:00
let foo = {
let mut jdb = ArchiveDB::new(shared_db.clone(), None);
2016-03-11 13:50:39 +01:00
// history is 1
let foo = jdb.insert(b"foo");
jdb.commit_batch(0, &keccak(b"0"), None).unwrap();
jdb.commit_batch(1, &keccak(b"1"), Some((0, keccak(b"0")))).unwrap();
2016-03-11 13:50:39 +01:00
// foo is ancient history.
jdb.insert(b"foo");
jdb.commit_batch(2, &keccak(b"2"), Some((1, keccak(b"1")))).unwrap();
2016-03-11 13:50:39 +01:00
foo
};
{
let mut jdb = ArchiveDB::new(shared_db, None);
2016-03-11 13:50:39 +01:00
jdb.remove(&foo);
jdb.commit_batch(3, &keccak(b"3"), Some((2, keccak(b"2")))).unwrap();
assert!(jdb.contains(&foo));
2016-03-11 13:50:39 +01:00
jdb.remove(&foo);
jdb.commit_batch(4, &keccak(b"4"), Some((3, keccak(b"3")))).unwrap();
jdb.commit_batch(5, &keccak(b"5"), Some((4, keccak(b"4")))).unwrap();
2016-03-11 13:50:39 +01:00
}
}
2016-03-18 10:14:19 +01:00
2016-03-11 13:50:39 +01:00
#[test]
fn reopen_fork() {
let shared_db = Arc::new(kvdb_memorydb::create(0));
let (foo, _, _) = {
let mut jdb = ArchiveDB::new(shared_db.clone(), None);
2016-03-11 13:50:39 +01:00
// history is 1
let foo = jdb.insert(b"foo");
let bar = jdb.insert(b"bar");
jdb.commit_batch(0, &keccak(b"0"), None).unwrap();
2016-03-11 13:50:39 +01:00
jdb.remove(&foo);
let baz = jdb.insert(b"baz");
jdb.commit_batch(1, &keccak(b"1a"), Some((0, keccak(b"0")))).unwrap();
2016-03-11 13:50:39 +01:00
jdb.remove(&bar);
jdb.commit_batch(1, &keccak(b"1b"), Some((0, keccak(b"0")))).unwrap();
2016-03-11 13:50:39 +01:00
(foo, bar, baz)
};
{
let mut jdb = ArchiveDB::new(shared_db, None);
jdb.commit_batch(2, &keccak(b"2b"), Some((1, keccak(b"1b")))).unwrap();
assert!(jdb.contains(&foo));
2016-03-11 13:50:39 +01:00
}
}
2016-03-11 19:15:56 +01:00
#[test]
fn returns_state() {
let shared_db = Arc::new(kvdb_memorydb::create(0));
2016-03-11 19:15:56 +01:00
let key = {
let mut jdb = ArchiveDB::new(shared_db.clone(), None);
2016-03-11 19:15:56 +01:00
let key = jdb.insert(b"foo");
jdb.commit_batch(0, &keccak(b"0"), None).unwrap();
2016-03-11 19:15:56 +01:00
key
};
{
let jdb = ArchiveDB::new(shared_db, None);
2016-03-11 19:15:56 +01:00
let state = jdb.state(&key);
assert!(state.is_some());
}
}
#[test]
fn inject() {
let mut jdb = ArchiveDB::new(Arc::new(kvdb_memorydb::create(0)), None);
let key = jdb.insert(b"dog");
jdb.inject_batch().unwrap();
2016-10-26 13:53:47 +02:00
assert_eq!(jdb.get(&key).unwrap(), DBValue::from_slice(b"dog"));
jdb.remove(&key);
jdb.inject_batch().unwrap();
assert!(jdb.get(&key).is_none());
}
2016-03-11 13:50:39 +01:00
}