2016-10-22 21:35:48 +03:00
|
|
|
// Copyright 2016 The Grin Developers
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2016-10-21 03:06:12 +03:00
|
|
|
//! Implementation of the chain block acceptance (or refusal) pipeline.
|
|
|
|
|
2016-12-19 02:51:54 +03:00
|
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
|
2016-10-21 03:06:12 +03:00
|
|
|
use secp;
|
2016-11-27 23:31:15 +03:00
|
|
|
use time;
|
2016-10-21 03:06:12 +03:00
|
|
|
|
2016-11-16 04:29:42 +03:00
|
|
|
use core::consensus;
|
2016-12-27 02:39:31 +03:00
|
|
|
use core::core::hash::{Hash, Hashed};
|
|
|
|
use core::core::target::Difficulty;
|
2016-11-16 04:29:42 +03:00
|
|
|
use core::core::{BlockHeader, Block, Proof};
|
2016-10-21 03:06:12 +03:00
|
|
|
use core::pow;
|
|
|
|
use types;
|
2016-12-21 04:35:04 +03:00
|
|
|
use types::{Tip, ChainStore, ChainAdapter, NoopAdapter};
|
2016-10-21 03:06:12 +03:00
|
|
|
use store;
|
|
|
|
|
|
|
|
bitflags! {
|
|
|
|
/// Options for block validation
|
|
|
|
pub flags Options: u32 {
|
2016-11-27 23:31:15 +03:00
|
|
|
const NONE = 0b00000001,
|
2016-10-21 03:06:12 +03:00
|
|
|
/// Runs with the easier version of the Proof of Work, mostly to make testing easier.
|
2016-11-27 23:31:15 +03:00
|
|
|
const EASY_POW = 0b00000010,
|
2016-10-21 03:06:12 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Contextual information required to process a new block and either reject or
|
|
|
|
/// accept it.
|
2016-12-19 02:51:54 +03:00
|
|
|
pub struct BlockContext {
|
2016-10-21 03:06:12 +03:00
|
|
|
opts: Options,
|
2016-12-19 02:51:54 +03:00
|
|
|
store: Arc<ChainStore>,
|
2016-12-21 04:35:04 +03:00
|
|
|
adapter: Arc<ChainAdapter>,
|
2016-10-21 03:06:12 +03:00
|
|
|
head: Tip,
|
|
|
|
tip: Option<Tip>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum Error {
|
|
|
|
/// The block doesn't fit anywhere in our chain
|
|
|
|
Unfit(String),
|
2016-12-27 02:39:31 +03:00
|
|
|
/// Difficulty is too low either compared to ours or the block PoW hash
|
|
|
|
DifficultyTooLow,
|
|
|
|
/// Addition of difficulties on all previous block is wrong
|
|
|
|
WrongTotalDifficulty,
|
2016-12-21 04:35:04 +03:00
|
|
|
/// Size of the Cuckoo graph in block header doesn't match PoW requirements
|
|
|
|
WrongCuckooSize,
|
2016-10-21 03:06:12 +03:00
|
|
|
/// The proof of work is invalid
|
|
|
|
InvalidPow,
|
|
|
|
/// The block doesn't sum correctly or a tx signature is invalid
|
|
|
|
InvalidBlockProof(secp::Error),
|
2016-11-17 04:03:23 +03:00
|
|
|
/// Block time is too old
|
|
|
|
InvalidBlockTime,
|
|
|
|
/// Internal issue when trying to save or load data from store
|
2016-10-21 03:06:12 +03:00
|
|
|
StoreErr(types::Error),
|
|
|
|
}
|
|
|
|
|
2016-12-21 04:35:04 +03:00
|
|
|
/// Runs the block processing pipeline, including validation and finding a
|
|
|
|
/// place for the new block in the chain. Returns the new
|
|
|
|
/// chain head if updated.
|
|
|
|
pub fn process_block(b: &Block,
|
|
|
|
store: Arc<ChainStore>,
|
|
|
|
adapter: Arc<ChainAdapter>,
|
|
|
|
opts: Options)
|
|
|
|
-> Result<Option<Tip>, Error> {
|
2016-10-21 03:06:12 +03:00
|
|
|
// TODO should just take a promise for a block with a full header so we don't
|
|
|
|
// spend resources reading the full block when its header is invalid
|
|
|
|
|
2016-11-17 04:03:23 +03:00
|
|
|
let head = try!(store.head().map_err(&Error::StoreErr));
|
2016-12-21 04:35:04 +03:00
|
|
|
|
2016-10-21 03:06:12 +03:00
|
|
|
let mut ctx = BlockContext {
|
|
|
|
opts: opts,
|
|
|
|
store: store,
|
2016-12-21 04:35:04 +03:00
|
|
|
adapter: adapter,
|
2016-10-21 03:06:12 +03:00
|
|
|
head: head,
|
|
|
|
tip: None,
|
|
|
|
};
|
|
|
|
|
2016-12-21 04:35:04 +03:00
|
|
|
info!("Starting validation pipeline for block {} at {}.",
|
|
|
|
b.hash(),
|
|
|
|
b.header.height);
|
|
|
|
try!(check_known(b.hash(), &mut ctx));
|
2016-11-16 04:29:42 +03:00
|
|
|
try!(validate_header(&b, &mut ctx));
|
|
|
|
try!(set_tip(&b.header, &mut ctx));
|
|
|
|
try!(validate_block(b, &mut ctx));
|
2016-12-21 04:35:04 +03:00
|
|
|
info!("Block at {} with hash {} is valid, going to save and append.",
|
|
|
|
b.header.height,
|
|
|
|
b.hash());
|
2016-11-16 04:29:42 +03:00
|
|
|
try!(add_block(b, &mut ctx));
|
2016-12-21 04:35:04 +03:00
|
|
|
// TODO a global lock should be set before that step or even earlier
|
2016-11-16 04:29:42 +03:00
|
|
|
try!(update_tips(&mut ctx));
|
2016-12-21 04:35:04 +03:00
|
|
|
|
|
|
|
// TODO make sure we always return the head, and not a fork that just got longer
|
|
|
|
Ok(ctx.tip)
|
2016-10-21 03:06:12 +03:00
|
|
|
}
|
|
|
|
|
2016-12-21 04:35:04 +03:00
|
|
|
/// Quick in-memory check to fast-reject any block we've already handled
|
|
|
|
/// recently. Keeps duplicates from the network in check.
|
|
|
|
fn check_known(bh: Hash, ctx: &mut BlockContext) -> Result<(), Error> {
|
|
|
|
if bh == ctx.head.last_block_h || bh == ctx.head.prev_block_h {
|
|
|
|
return Err(Error::Unfit("already known".to_string()));
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
2016-10-21 03:06:12 +03:00
|
|
|
|
|
|
|
/// First level of black validation that only needs to act on the block header
|
|
|
|
/// to make it as cheap as possible. The different validations are also
|
|
|
|
/// arranged by order of cost to have as little DoS surface as possible.
|
2016-11-27 23:31:15 +03:00
|
|
|
/// TODO require only the block header (with length information)
|
2016-11-16 04:29:42 +03:00
|
|
|
fn validate_header(b: &Block, ctx: &mut BlockContext) -> Result<(), Error> {
|
2016-10-21 03:06:12 +03:00
|
|
|
let header = &b.header;
|
|
|
|
if header.height > ctx.head.height + 1 {
|
|
|
|
// TODO actually handle orphans and add them to a size-limited set
|
2016-11-16 04:29:42 +03:00
|
|
|
return Err(Error::Unfit("orphan".to_string()));
|
2016-10-21 03:06:12 +03:00
|
|
|
}
|
|
|
|
|
2016-11-17 04:03:23 +03:00
|
|
|
let prev = try!(ctx.store.get_block_header(&header.previous).map_err(&Error::StoreErr));
|
|
|
|
|
|
|
|
if header.timestamp <= prev.timestamp {
|
2016-11-30 05:45:39 +03:00
|
|
|
// prevent time warp attacks and some timestamp manipulations by forcing strict
|
|
|
|
// time progression
|
2016-11-17 04:03:23 +03:00
|
|
|
return Err(Error::InvalidBlockTime);
|
|
|
|
}
|
2016-11-30 05:45:39 +03:00
|
|
|
if header.timestamp >
|
|
|
|
time::now() + time::Duration::seconds(12 * (consensus::BLOCK_TIME_SEC as i64)) {
|
2016-12-01 03:26:04 +03:00
|
|
|
// refuse blocks more than 12 blocks intervals in future (as in bitcoin)
|
2016-11-30 05:45:39 +03:00
|
|
|
// TODO add warning in p2p code if local time is too different from peers
|
2016-11-27 23:31:15 +03:00
|
|
|
return Err(Error::InvalidBlockTime);
|
2016-11-30 05:45:39 +03:00
|
|
|
}
|
2016-11-17 04:03:23 +03:00
|
|
|
|
2016-12-27 02:39:31 +03:00
|
|
|
if b.header.total_difficulty !=
|
|
|
|
prev.total_difficulty.clone() + Difficulty::from_hash(&prev.hash()) {
|
|
|
|
return Err(Error::WrongTotalDifficulty);
|
|
|
|
}
|
|
|
|
|
2016-12-21 04:35:04 +03:00
|
|
|
// verify the proof of work and related parameters
|
2016-12-27 02:39:31 +03:00
|
|
|
let (difficulty, cuckoo_sz) = consensus::next_target(header.timestamp.to_timespec().sec,
|
|
|
|
prev.timestamp.to_timespec().sec,
|
|
|
|
prev.difficulty,
|
|
|
|
prev.cuckoo_len);
|
|
|
|
if header.difficulty < difficulty {
|
|
|
|
return Err(Error::DifficultyTooLow);
|
2016-11-17 04:03:23 +03:00
|
|
|
}
|
2016-12-21 04:35:04 +03:00
|
|
|
if header.cuckoo_len != cuckoo_sz && !ctx.opts.intersects(EASY_POW) {
|
|
|
|
return Err(Error::WrongCuckooSize);
|
|
|
|
}
|
2016-10-21 03:06:12 +03:00
|
|
|
|
|
|
|
if ctx.opts.intersects(EASY_POW) {
|
2016-12-27 02:39:31 +03:00
|
|
|
if !pow::verify_size(b, 16) {
|
2016-11-16 04:29:42 +03:00
|
|
|
return Err(Error::InvalidPow);
|
2016-10-21 03:06:12 +03:00
|
|
|
}
|
2016-12-21 04:35:04 +03:00
|
|
|
} else if !pow::verify(b) {
|
2016-11-16 04:29:42 +03:00
|
|
|
return Err(Error::InvalidPow);
|
2016-10-21 03:06:12 +03:00
|
|
|
}
|
2016-11-17 04:03:23 +03:00
|
|
|
|
2016-11-16 04:29:42 +03:00
|
|
|
Ok(())
|
2016-10-21 03:06:12 +03:00
|
|
|
}
|
|
|
|
|
2016-11-16 04:29:42 +03:00
|
|
|
fn set_tip(h: &BlockHeader, ctx: &mut BlockContext) -> Result<(), Error> {
|
2016-12-21 04:35:04 +03:00
|
|
|
// TODO actually support more than one branch
|
|
|
|
if h.previous != ctx.head.last_block_h {
|
|
|
|
return Err(Error::Unfit("Just don't know where to put it right now".to_string()));
|
|
|
|
}
|
|
|
|
// TODO validate block header height
|
2016-10-21 03:06:12 +03:00
|
|
|
ctx.tip = Some(ctx.head.clone());
|
2016-11-16 04:29:42 +03:00
|
|
|
Ok(())
|
2016-10-21 03:06:12 +03:00
|
|
|
}
|
|
|
|
|
2016-11-16 04:29:42 +03:00
|
|
|
fn validate_block(b: &Block, ctx: &mut BlockContext) -> Result<(), Error> {
|
2016-10-21 03:06:12 +03:00
|
|
|
// TODO check tx merkle tree
|
|
|
|
let curve = secp::Secp256k1::with_caps(secp::ContextFlag::Commit);
|
2016-11-16 04:29:42 +03:00
|
|
|
try!(b.verify(&curve).map_err(&Error::InvalidBlockProof));
|
|
|
|
Ok(())
|
2016-10-21 03:06:12 +03:00
|
|
|
}
|
|
|
|
|
2016-11-16 04:29:42 +03:00
|
|
|
fn add_block(b: &Block, ctx: &mut BlockContext) -> Result<(), Error> {
|
2016-12-21 04:35:04 +03:00
|
|
|
// save the block and appends it to the selected tip
|
2016-10-21 03:06:12 +03:00
|
|
|
ctx.tip = ctx.tip.as_ref().map(|t| t.append(b.hash()));
|
2016-12-21 04:35:04 +03:00
|
|
|
ctx.store.save_block(b).map_err(&Error::StoreErr);
|
|
|
|
|
|
|
|
// broadcast the block
|
|
|
|
let adapter = ctx.adapter.clone();
|
|
|
|
adapter.block_accepted(b);
|
|
|
|
Ok(())
|
2016-10-21 03:06:12 +03:00
|
|
|
}
|
|
|
|
|
2016-11-16 04:29:42 +03:00
|
|
|
fn update_tips(ctx: &mut BlockContext) -> Result<(), Error> {
|
2016-12-21 04:35:04 +03:00
|
|
|
let tip = ctx.tip.as_ref().unwrap();
|
|
|
|
ctx.store.save_head(tip).map_err(&Error::StoreErr)
|
2016-10-21 03:06:12 +03:00
|
|
|
}
|