1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use std::sync::{Arc, RwLock, Mutex, MutexGuard};
use std::marker::PhantomData;
use super::Error;
use crate::traits::{Operation, ImportOperation, Block, BlockExecutor, Backend, AsExternalities, Auxiliary};

/// A shared backend that also allows atomic import operation.
pub struct SharedBackend<B: Block, A: Auxiliary<B>, Ba: Backend<B, A>> {
	backend: Arc<RwLock<Ba>>,
	import_lock: Arc<Mutex<()>>,
	_marker: PhantomData<(B, A)>,
}

impl<B: Block, A: Auxiliary<B>, Ba> SharedBackend<B, A, Ba> where
	Ba: Backend<B, A>
{
	/// Create a new shared backend.
	pub fn new(backend: Ba) -> Self {
		Self {
			backend: Arc::new(RwLock::new(backend)),
			import_lock: Arc::new(Mutex::new(())),
			_marker: PhantomData,
		}
	}

	/// Get the genesis hash of the chain.
	pub fn genesis(&self) -> B::Identifier {
		self.backend.read().expect("backend lock is poisoned")
			.genesis()
	}

	/// Get the head of the chain.
	pub fn head(&self) -> B::Identifier {
		self.backend.read().expect("backend lock is poisoned")
			.head()
	}

	/// Check whether a hash is contained in the chain.
	pub fn contains(
		&self,
		hash: &B::Identifier,
	) -> Result<bool, Ba::Error> {
		self.backend.read().expect("backend lock is poisoned")
			.contains(hash)
	}

	/// Check whether a block is canonical.
	pub fn is_canon(
		&self,
		hash: &B::Identifier
	) -> Result<bool, Ba::Error> {
		self.backend.read().expect("backend lock is poisoned")
			.is_canon(hash)
	}

	/// Look up a canonical block via its depth.
	pub fn lookup_canon_depth(
		&self,
		depth: usize,
	) -> Result<Option<B::Identifier>, Ba::Error> {
		self.backend.read().expect("backend lock is poisoned")
			.lookup_canon_depth(depth)
	}

	/// Get the auxiliary value by key.
	pub fn auxiliary(
		&self,
		key: &A::Key
	) -> Result<Option<A>, Ba::Error> {
		self.backend.read().expect("backend lock is poisoned")
			.auxiliary(key)
	}

	/// Get the depth of a block.
	pub fn depth_at(
		&self,
		hash: &B::Identifier,
	) -> Result<usize, Ba::Error> {
		self.backend.read().expect("backend lock is poisoned")
			.depth_at(hash)
	}

	/// Get children of a block.
	pub fn children_at(
		&self,
		hash: &B::Identifier,
	) -> Result<Vec<B::Identifier>, Ba::Error> {
		self.backend.read().expect("backend lock is poisoned")
			.children_at(hash)
	}

	/// Get the state object of a block.
	pub fn state_at(
		&self,
		hash: &B::Identifier,
	) -> Result<Ba::State, Ba::Error> {
		self.backend.read().expect("backend lock is poisoned")
			.state_at(hash)
	}

	/// Get the object of a block.
	pub fn block_at(
		&self,
		hash: &B::Identifier,
	) -> Result<B, Ba::Error> {
		self.backend.read().expect("backend lock is poisoned")
			.block_at(hash)
	}

	/// Begin an import operation, returns an importer.
	pub fn begin_import<'a, 'executor, E: BlockExecutor<Block=B>>(
		&'a self,
		executor: &'executor E
	) -> Importer<'a, 'executor, E, A, Ba> where
		Ba::State: AsExternalities<E::Externalities>
	{
		Importer {
			executor,
			backend: self,
			pending: Default::default(),
			_guard: self.import_lock.lock().expect("Import mutex is poisoned"),
		}
	}
}

impl<B: Block, A: Auxiliary<B>, Ba: Backend<B, A>> Clone for SharedBackend<B, A, Ba> {
	fn clone(&self) -> Self {
		SharedBackend {
			backend: self.backend.clone(),
			import_lock: self.import_lock.clone(),
			_marker: PhantomData,
		}
	}
}

/// Block importer.
pub struct Importer<'a, 'executor, E: BlockExecutor, A: Auxiliary<E::Block>, Ba: Backend<E::Block, A>> {
	executor: &'executor E,
	backend: &'a SharedBackend<E::Block, A, Ba>,
	pending: Operation<E::Block, Ba::State, A>,
	_guard: MutexGuard<'a, ()>,
}

impl<'a, 'executor, E: BlockExecutor, A: Auxiliary<E::Block>, Ba: Backend<E::Block, A>> Importer<'a, 'executor, E, A, Ba> where
	Ba::State: AsExternalities<E::Externalities>,
{
	/// Get the associated backend of the importer.
	pub fn backend(&self) -> &'a SharedBackend<E::Block, A, Ba> {
		self.backend
	}

	/// Import a new block.
	pub fn import_block(&mut self, block: E::Block) -> Result<(), Error> {
		let mut state = self.backend
			.state_at(&block.parent_id().ok_or(Error::IsGenesis)?)
			.map_err(|e| Error::Backend(Box::new(e)))?;
		self.executor.execute_block(&block, state.as_externalities())
			.map_err(|e| Error::Executor(Box::new(e)))?;

		let operation = ImportOperation { block, state };
		self.import_raw(operation);

		Ok(())
	}

	/// Import a raw block.
	pub fn import_raw(&mut self, operation: ImportOperation<E::Block, Ba::State>) {
		self.pending.import_block.push(operation);
	}

	/// Set head to given hash.
	pub fn set_head(&mut self, head: <E::Block as Block>::Identifier) {
		self.pending.set_head = Some(head);
	}

	/// Insert auxiliary value.
	pub fn insert_auxiliary(&mut self, aux: A) {
		self.pending.insert_auxiliaries.push(aux);
	}

	/// Remove auxiliary value.
	pub fn remove_auxiliary(&mut self, aux_key: A::Key) {
		self.pending.remove_auxiliaries.push(aux_key);
	}

	/// Commit operation and drop import lock.
	pub fn commit(self) -> Result<(), Ba::Error> {
		self.backend.backend.write().expect("backend lock is poisoned")
			.commit(self.pending)
	}
}