1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
// Copyright 2015-2020 Tetsy Technologies (UK) Ltd.
// This file is part of Tetsy Vapory.

// Tetsy Vapory 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.

// Tetsy Vapory 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 Tetsy Vapory.  If not, see <http://www.gnu.org/licenses/>.

//! Light client implementation. Stores data from light sync

use std::sync::{Weak, Arc};

use enjen::{Engine, EpochChange, Proof};
use verification::queue::{self, HeaderQueue};
use vapcore_spec::{Spec, SpecHardcodedSync};
use io::IoChannel;
use parking_lot::{Mutex, RwLock};
use vapory_types::{H256, U256};
use futures::{IntoFuture, Future};
use common_types::{
	BlockNumber,
	block_status::BlockStatus,
	blockchain_info::BlockChainInfo,
	client_types::ClientReport,
	encoded,
	engines::epoch::{Transition as EpochTransition, PendingTransition},
	errors::VapcoreError as Error,
	errors::VapcoreResult,
	header::Header,
	ids::BlockId,
	io_message::ClientIoMessage,
	verification::VerificationQueueInfo as BlockQueueInfo,
};
use tetsy_kvdb::KeyValueDB;
use tetsy_vm::EnvInfo;

use self::fetch::ChainDataFetcher;
use self::header_chain::{AncestryIter, HeaderChain, HardcodedSync};

use cache::Cache;

pub use self::service::Service;
use client_traits::ForceUpdateSealing;

mod header_chain;
mod service;

pub mod fetch;

/// Configuration for the light client.
#[derive(Debug, Clone)]
pub struct Config {
	/// Verification queue config.
	pub queue: queue::Config,
	/// Chain column in database.
	pub chain_column: u32,
	/// Should it do full verification of blocks?
	pub verify_full: bool,
	/// Should it check the seal of blocks?
	pub check_seal: bool,
	/// Disable hardcoded sync.
	pub no_hardcoded_sync: bool,
}

impl Default for Config {
	fn default() -> Config {
		Config {
			queue: Default::default(),
			chain_column: 0,
			verify_full: true,
			check_seal: true,
			no_hardcoded_sync: false,
		}
	}
}

/// Trait for interacting with the header chain abstractly.
pub trait LightChainClient: Send + Sync {
	/// Adds a new `LightChainNotify` listener.
	fn add_listener(&self, listener: Weak<dyn LightChainNotify>);

	/// Get chain info.
	fn chain_info(&self) -> BlockChainInfo;

	/// Queue header to be verified. Required that all headers queued have their
	/// parent queued prior.
	fn queue_header(&self, header: Header) -> VapcoreResult<H256>;

	/// Attempt to get a block hash by block id.
	fn block_hash(&self, id: BlockId) -> Option<H256>;

	/// Get block queue information.
	fn queue_info(&self) -> BlockQueueInfo;

	/// Attempt to get block header by block id.
	fn block_header(&self, id: BlockId) -> Option<encoded::Header>;

	/// Get the best block header.
	fn best_block_header(&self) -> encoded::Header;

	/// Get a block's chain score by ID.
	fn score(&self, id: BlockId) -> Option<U256>;

	/// Get an iterator over a block and its ancestry.
	fn ancestry_iter<'a>(&'a self, start: BlockId) -> Box<dyn Iterator<Item=encoded::Header> + 'a>;

	/// Get the signing chain ID.
	fn signing_chain_id(&self) -> Option<u64>;

	/// Get environment info for execution at a given block.
	/// Fails if that block's header is not stored.
	fn env_info(&self, id: BlockId) -> Option<EnvInfo>;

	/// Get a handle to the consensus engine.
	fn engine(&self) -> &Arc<dyn Engine>;

	/// Query whether a block is known.
	fn is_known(&self, hash: &H256) -> bool;

	/// Set the chain via a spec name.
	fn set_spec_name(&self, new_spec_name: String) -> Result<(), ()>;

	/// Clear the queue.
	fn clear_queue(&self);

	/// Flush the queue.
	fn flush_queue(&self);

	/// Get the `i`th CHT root.
	fn cht_root(&self, i: usize) -> Option<H256>;

	/// Get a report of import activity since the last call.
	fn report(&self) -> ClientReport;
}

/// An actor listening to light chain events.
pub trait LightChainNotify: Send + Sync {
	/// Notifies about imported headers.
	fn new_headers(&self, good: &[H256]);
}

/// Something which can be treated as a `LightChainClient`.
pub trait AsLightClient {
	/// The kind of light client this can be treated as.
	type Client: LightChainClient;

	/// Access the underlying light client.
	fn as_light_client(&self) -> &Self::Client;
}

impl<T: LightChainClient> AsLightClient for T {
	type Client = Self;

	fn as_light_client(&self) -> &Self { self }
}

/// Light client implementation.
pub struct Client<T> {
	queue: HeaderQueue<()>,
	engine: Arc<dyn Engine>,
	chain: HeaderChain,
	report: RwLock<ClientReport>,
	import_lock: Mutex<()>,
	db: Arc<dyn KeyValueDB>,
	listeners: RwLock<Vec<Weak<dyn LightChainNotify>>>,
	fetcher: T,
	verify_full: bool,
	/// A closure to call when we want to restart the client
	exit_handler: Mutex<Option<Box<dyn Fn(String) + 'static + Send>>>,
}

impl<T: ChainDataFetcher> Client<T> {
	/// Create a new `Client`.
	pub fn new(
		config: Config,
		db: Arc<dyn KeyValueDB>,
		chain_col: u32,
		spec: &Spec,
		fetcher: T,
		io_channel: IoChannel<ClientIoMessage<()>>,
		cache: Arc<Mutex<Cache>>
	) -> Result<Self, Error> {
		Ok(Self {
			queue: HeaderQueue::new(config.queue, spec.engine.clone(), io_channel, config.check_seal),
			engine: spec.engine.clone(),
			chain: {
				let hs_cfg = if config.no_hardcoded_sync { HardcodedSync::Deny } else { HardcodedSync::Allow };
				HeaderChain::new(db.clone(), chain_col, &spec, cache, hs_cfg)?
			},
			report: RwLock::new(ClientReport::default()),
			import_lock: Mutex::new(()),
			db,
			listeners: RwLock::new(vec![]),
			fetcher,
			verify_full: config.verify_full,
			exit_handler: Mutex::new(None),
		})
	}

	/// Generates the specifications for hardcoded sync. This is typically only called manually
	/// from time to time by a Tetsy developer in order to update the chain specifications.
	///
	/// Returns `None` if we are at the genesis block.
	pub fn read_hardcoded_sync(&self) -> Result<Option<SpecHardcodedSync>, Error> {
		self.chain.read_hardcoded_sync()
	}

	/// Adds a new `LightChainNotify` listener.
	pub fn add_listener(&self, listener: Weak<dyn LightChainNotify>) {
		self.listeners.write().push(listener);
	}

	/// Import a header to the queue for additional verification.
	pub fn import_header(&self, header: Header) -> VapcoreResult<H256> {
		self.queue.import(header).map_err(|(e, _)| e)
	}

	/// Inquire about the status of a given header.
	pub fn status(&self, hash: &H256) -> BlockStatus {
		match self.queue.status(hash) {
			queue::Status::Unknown => self.chain.status(hash),
			other => other.into(),
		}
	}

	/// Get the chain info.
	pub fn chain_info(&self) -> BlockChainInfo {
		let best_hdr = self.chain.best_header();
		let best_td = self.chain.best_block().total_difficulty;

		let first_block = self.chain.first_block();
		let genesis_hash = self.chain.genesis_hash();

		BlockChainInfo {
			total_difficulty: best_td,
			pending_total_difficulty: best_td + self.queue.total_difficulty(),
			genesis_hash,
			best_block_hash: best_hdr.hash(),
			best_block_number: best_hdr.number(),
			best_block_timestamp: best_hdr.timestamp(),
			ancient_block_hash: if first_block.is_some() { Some(genesis_hash) } else { None },
			ancient_block_number: if first_block.is_some() { Some(0) } else { None },
			first_block_hash: first_block.as_ref().map(|first| first.hash),
			first_block_number: first_block.as_ref().map(|first| first.number),
		}
	}

	/// Get the header queue info.
	pub fn queue_info(&self) -> BlockQueueInfo {
		self.queue.queue_info()
	}

	/// Attempt to get a block hash by block id.
	pub fn block_hash(&self, id: BlockId) -> Option<H256> {
		self.chain.block_hash(id)
	}

	/// Get a block header by Id.
	pub fn block_header(&self, id: BlockId) -> Option<encoded::Header> {
		self.chain.block_header(id)
	}

	/// Get the best block header.
	pub fn best_block_header(&self) -> encoded::Header {
		self.chain.best_header()
	}

	/// Get a block's chain score.
	pub fn score(&self, id: BlockId) -> Option<U256> {
		self.chain.score(id)
	}

	/// Get an iterator over a block and its ancestry.
	pub fn ancestry_iter(&self, start: BlockId) -> AncestryIter {
		self.chain.ancestry_iter(start)
	}

	/// Get the signing chain id.
	pub fn signing_chain_id(&self) -> Option<u64> {
		self.engine.signing_chain_id(&self.latest_env_info())
	}

	/// Flush the header queue.
	pub fn flush_queue(&self) {
		self.queue.flush()
	}

	/// Get the `i`th CHT root.
	pub fn cht_root(&self, i: usize) -> Option<H256> {
		self.chain.cht_root(i)
	}

	/// Import a set of pre-verified headers from the queue.
	pub fn import_verified(&self) {
		const MAX: usize = 256;

		let _lock = self.import_lock.lock();

		let mut bad = Vec::new();
		let mut good = Vec::new();
		for verified_header in self.queue.drain(MAX) {
			let (num, hash) = (verified_header.number(), verified_header.hash());
			trace!(target: "client", "importing block {}", num);

			if self.verify_full && !self.check_header(&mut bad, &verified_header) {
				continue
			}

			let write_proof_result = match self.check_epoch_signal(&verified_header) {
				Ok(Some(proof)) => self.write_pending_proof(&verified_header, proof),
				Ok(None) => Ok(()),
				Err(e) =>
					panic!("Unable to fetch epoch transition proof: {:?}", e),
			};

			if let Err(e) = write_proof_result {
				warn!(target: "client", "Error writing pending transition proof to DB: {:?} \
					The node may not be able to synchronize further.", e);
			}

			let epoch_proof = self.engine.is_epoch_end_light(
				&verified_header,
				&|h| self.chain.block_header(BlockId::Hash(h)).and_then(|hdr| hdr.decode().ok()),
				&|h| self.chain.pending_transition(h),
			);

			let mut tx = self.db.transaction();
			let pending = match self.chain.insert(&mut tx, &verified_header, epoch_proof) {
				Ok(pending) => {
					good.push(hash);
					self.report.write().blocks_imported += 1;
					pending
				}
				Err(e) => {
					debug!(target: "client", "Error importing header {:?}: {:?}", (num, hash), e);
					bad.push(hash);
					continue;
				}
			};

			self.db.write_buffered(tx);
			self.chain.apply_pending(pending);
		}

		if let Err(e) = self.db.flush() {
			panic!("Database flush failed: {}. Check disk health and space.", e);
		}

		self.queue.mark_as_bad(&bad);
		self.queue.mark_as_good(&good);

		self.notify(|listener| listener.new_headers(&good));
	}

	/// Get a report about blocks imported.
	pub fn report(&self) -> ClientReport {
		self.report.read().clone()
	}

	/// Get blockchain mem usage in bytes.
	pub fn chain_mem_used(&self) -> usize {
		use tetsy_util_mem::MallocSizeOfExt;

		self.chain.malloc_size_of()
	}

	/// Set a closure to call when the client wants to be restarted.
	///
	/// The parameter passed to the callback is the name of the new chain spec to use after
	/// the restart.
	pub fn set_exit_handler<F>(&self, f: F) where F: Fn(String) + 'static + Send {
		*self.exit_handler.lock() = Some(Box::new(f));
	}

	/// Get a handle to the verification engine.
	pub fn engine(&self) -> &Arc<dyn Engine> {
		&self.engine
	}

	/// Get the latest environment info.
	pub fn latest_env_info(&self) -> EnvInfo {
		self.env_info(BlockId::Latest)
			.expect("Best block header and recent hashes always stored; qed")
	}

	/// Get environment info for a given block.
	pub fn env_info(&self, id: BlockId) -> Option<EnvInfo> {
		let header = match self.block_header(id) {
			Some(hdr) => hdr,
			None => return None,
		};

		Some(EnvInfo {
			number: header.number(),
			author: header.author(),
			timestamp: header.timestamp(),
			difficulty: header.difficulty(),
			last_hashes: self.build_last_hashes(header.parent_hash()),
			gas_used: Default::default(),
			gas_limit: header.gas_limit(),
		})
	}

	fn build_last_hashes(&self, mut parent_hash: H256) -> Arc<Vec<H256>> {
		let mut v = Vec::with_capacity(256);
		for _ in 0..255 {
			v.push(parent_hash);
			match self.block_header(BlockId::Hash(parent_hash)) {
				Some(header) => parent_hash = header.hash(),
				None => break,
			}
		}

		Arc::new(v)
	}

	fn notify<F: Fn(&dyn LightChainNotify)>(&self, f: F) {
		for listener in &*self.listeners.read() {
			if let Some(listener) = listener.upgrade() {
				f(&*listener)
			}
		}
	}

	// return false if should skip, true otherwise. may push onto bad if
	// should skip.
	fn check_header(&self, bad: &mut Vec<H256>, verified_header: &Header) -> bool {
		let hash = verified_header.hash();
		let parent_header = match self.chain.block_header(BlockId::Hash(*verified_header.parent_hash())) {
			Some(header) => header,
			None => {
				trace!(target: "client", "No parent for block ({}, {})",
					verified_header.number(), hash);
				return false // skip import of block with missing parent.
			}
		};

		// Verify Block Family

		let verify_family_result = {
			parent_header.decode()
				.map_err(|dec_err| dec_err.into())
				.and_then(|decoded| {
					self.engine.verify_block_family(&verified_header, &decoded)
				})

		};
		if let Err(e) = verify_family_result {
			warn!(target: "client", "Stage 3 block verification failed for #{} ({})\nError: {:?}",
				verified_header.number(), verified_header.hash(), e);
			bad.push(hash);
			return false;
		};

		// "external" verification.
		let verify_external_result = self.engine.verify_block_external(&verified_header);
		if let Err(e) = verify_external_result {
			warn!(target: "client", "Stage 4 block verification failed for #{} ({})\nError: {:?}",
				verified_header.number(), verified_header.hash(), e);

			bad.push(hash);
			return false;
		};

		true
	}

	fn check_epoch_signal(&self, verified_header: &Header) -> Result<Option<Proof>, T::Error> {
		use common_types::engines::machine::{AuxiliaryRequest, AuxiliaryData};

		let mut block: Option<Vec<u8>> = None;
		let mut receipts: Option<Vec<_>> = None;

		loop {

			let is_signal = {
				let auxiliary = AuxiliaryData {
					bytes: block.as_ref().map(|x| &x[..]),
					receipts: receipts.as_ref().map(|x| &x[..]),
				};

				self.engine.signals_epoch_end(verified_header, auxiliary)
			};

			// check with any auxiliary data fetched so far
			match is_signal {
				EpochChange::No => return Ok(None),
				EpochChange::Yes(proof) => return Ok(Some(proof)),
				EpochChange::Unsure(unsure) => {
					let (b, r) = match unsure {
						AuxiliaryRequest::Body =>
							(Some(self.fetcher.block_body(verified_header)), None),
						AuxiliaryRequest::Receipts =>
							(None, Some(self.fetcher.block_receipts(verified_header))),
						AuxiliaryRequest::Both => (
							Some(self.fetcher.block_body(verified_header)),
							Some(self.fetcher.block_receipts(verified_header)),
						),
					};

					if let Some(b) = b {
						block = Some(b.into_future().wait()?.into_inner());
					}

					if let Some(r) = r {
						receipts = Some(r.into_future().wait()?);
					}
				}
			}
		}
	}

	// attempts to fetch the epoch proof from the network until successful.
	fn write_pending_proof(&self, header: &Header, proof: Proof) -> Result<(), T::Error> {
		let proof = match proof {
			Proof::Known(known) => known,
			Proof::WithState(state_dependent) => {
				self.fetcher.epoch_transition(
					header.hash(),
					self.engine.clone(),
					state_dependent
				).into_future().wait()?
			}
		};

		let mut batch = self.db.transaction();
		self.chain.insert_pending_transition(&mut batch, header.hash(), &PendingTransition {
			proof,
		});
		self.db.write_buffered(batch);
		Ok(())
	}
}


impl<T: ChainDataFetcher> LightChainClient for Client<T> {
	fn add_listener(&self, listener: Weak<dyn LightChainNotify>) {
		Client::add_listener(self, listener)
	}

	fn chain_info(&self) -> BlockChainInfo { Client::chain_info(self) }

	fn queue_info(&self) -> BlockQueueInfo {
		self.queue.queue_info()
	}

	fn queue_header(&self, header: Header) -> VapcoreResult<H256> {
		self.import_header(header)
	}

	fn block_hash(&self, id: BlockId) -> Option<H256> {
		Client::block_hash(self, id)
	}

	fn block_header(&self, id: BlockId) -> Option<encoded::Header> {
		Client::block_header(self, id)
	}

	fn best_block_header(&self) -> encoded::Header {
		Client::best_block_header(self)
	}

	fn score(&self, id: BlockId) -> Option<U256> {
		Client::score(self, id)
	}

	fn ancestry_iter<'a>(&'a self, start: BlockId) -> Box<dyn Iterator<Item=encoded::Header> + 'a> {
		Box::new(Client::ancestry_iter(self, start))
	}

	fn signing_chain_id(&self) -> Option<u64> {
		Client::signing_chain_id(self)
	}

	fn env_info(&self, id: BlockId) -> Option<EnvInfo> {
		Client::env_info(self, id)
	}

	fn engine(&self) -> &Arc<dyn Engine> {
		Client::engine(self)
	}

	fn set_spec_name(&self, new_spec_name: String) -> Result<(), ()> {
		trace!(target: "mode", "Client::set_spec_name({:?})", new_spec_name);
		if let Some(ref h) = *self.exit_handler.lock() {
			(*h)(new_spec_name);
			Ok(())
		} else {
			warn!("Not hypervised; cannot change chain.");
			Err(())
		}
	}

	fn is_known(&self, hash: &H256) -> bool {
		self.status(hash) == BlockStatus::InChain
	}

	fn clear_queue(&self) {
		self.queue.clear()
	}

	fn flush_queue(&self) {
		Client::flush_queue(self);
	}

	fn cht_root(&self, i: usize) -> Option<H256> {
		Client::cht_root(self, i)
	}

	fn report(&self) -> ClientReport {
		Client::report(self)
	}
}

impl<T: ChainDataFetcher> client_traits::ChainInfo for Client<T> {
	fn chain_info(&self) -> BlockChainInfo {
		Client::chain_info(self)
	}
}

impl<T: ChainDataFetcher> client_traits::EngineClient for Client<T> {
	fn update_sealing(&self, _force: ForceUpdateSealing) {}
	fn submit_seal(&self, _block_hash: H256, _seal: Vec<Vec<u8>>) { }
	fn broadcast_consensus_message(&self, _message: Vec<u8>) { }

	fn epoch_transition_for(&self, parent_hash: H256) -> Option<EpochTransition> {
		self.chain.epoch_transition_for(parent_hash).map(|(hdr, proof)| EpochTransition {
			block_hash: hdr.hash(),
			block_number: hdr.number(),
			proof,
		})
	}

	fn as_full_client(&self) -> Option<&dyn (client_traits::BlockChainClient)> {
		None
	}

	fn block_number(&self, id: BlockId) -> Option<BlockNumber> {
		self.block_header(id).map(|hdr| hdr.number())
	}

	fn block_header(&self, id: BlockId) -> Option<encoded::Header> {
		Client::block_header(self, id)
	}
}

impl<T> client_traits::Tick for Client<T> {}