2018-04-13 16:42:25 +03:00
|
|
|
// Copyright 2018 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.
|
|
|
|
|
|
|
|
//! Build a block to mine: gathers transactions from the pool, assembles
|
|
|
|
//! them into a block and returns it.
|
|
|
|
|
2018-12-08 02:59:40 +03:00
|
|
|
use crate::util::RwLock;
|
2018-08-16 00:14:48 +03:00
|
|
|
use chrono::prelude::{DateTime, NaiveDateTime, Utc};
|
2018-09-25 01:15:55 +03:00
|
|
|
use rand::{thread_rng, Rng};
|
2018-10-20 03:13:07 +03:00
|
|
|
use std::sync::Arc;
|
2018-05-16 02:21:33 +03:00
|
|
|
use std::thread;
|
2018-04-13 16:42:25 +03:00
|
|
|
use std::time::Duration;
|
|
|
|
|
2018-12-08 02:59:40 +03:00
|
|
|
use crate::chain;
|
|
|
|
use crate::common::types::Error;
|
|
|
|
use crate::core::core::verifier_cache::VerifierCache;
|
|
|
|
use crate::core::{consensus, core, ser};
|
|
|
|
use crate::keychain::{ExtKeychain, Identifier, Keychain};
|
|
|
|
use crate::pool;
|
|
|
|
use crate::util;
|
|
|
|
use crate::wallet::{self, BlockFees};
|
2018-04-13 16:42:25 +03:00
|
|
|
|
|
|
|
// Ensure a block suitable for mining is built and returned
|
|
|
|
// If a wallet listener URL is not provided the reward will be "burnt"
|
|
|
|
// Warning: This call does not return until/unless a new block can be built
|
|
|
|
pub fn get_block(
|
|
|
|
chain: &Arc<chain::Chain>,
|
2018-08-28 00:22:48 +03:00
|
|
|
tx_pool: &Arc<RwLock<pool::TransactionPool>>,
|
2018-12-08 02:59:40 +03:00
|
|
|
verifier_cache: Arc<RwLock<dyn VerifierCache>>,
|
2018-04-13 16:42:25 +03:00
|
|
|
key_id: Option<Identifier>,
|
|
|
|
wallet_listener_url: Option<String>,
|
|
|
|
) -> (core::Block, BlockFees) {
|
2018-04-25 18:48:19 +03:00
|
|
|
let wallet_retry_interval = 5;
|
2018-04-13 16:42:25 +03:00
|
|
|
// get the latest chain state and build a block on top of it
|
2018-08-30 17:44:34 +03:00
|
|
|
let mut result = build_block(
|
|
|
|
chain,
|
|
|
|
tx_pool,
|
|
|
|
verifier_cache.clone(),
|
|
|
|
key_id.clone(),
|
|
|
|
wallet_listener_url.clone(),
|
|
|
|
);
|
2018-04-13 16:42:25 +03:00
|
|
|
while let Err(e) = result {
|
|
|
|
match e {
|
2018-07-01 01:36:38 +03:00
|
|
|
self::Error::Chain(c) => match c.kind() {
|
|
|
|
chain::ErrorKind::DuplicateCommitment(_) => {
|
|
|
|
debug!(
|
|
|
|
"Duplicate commit for potential coinbase detected. Trying next derivation."
|
|
|
|
);
|
|
|
|
}
|
|
|
|
_ => {
|
2018-10-21 23:30:56 +03:00
|
|
|
error!("Chain Error: {}", c);
|
2018-07-01 01:36:38 +03:00
|
|
|
}
|
|
|
|
},
|
2018-04-25 18:48:19 +03:00
|
|
|
self::Error::Wallet(_) => {
|
|
|
|
error!(
|
2018-06-11 18:39:04 +03:00
|
|
|
"Error building new block: Can't connect to wallet listener at {:?}; will retry",
|
2018-04-25 18:48:19 +03:00
|
|
|
wallet_listener_url.as_ref().unwrap()
|
|
|
|
);
|
|
|
|
thread::sleep(Duration::from_secs(wallet_retry_interval));
|
|
|
|
}
|
2018-04-13 16:42:25 +03:00
|
|
|
ae => {
|
2018-10-21 23:30:56 +03:00
|
|
|
warn!("Error building new block: {:?}. Retrying.", ae);
|
2018-04-13 16:42:25 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
thread::sleep(Duration::from_millis(100));
|
2018-08-30 17:44:34 +03:00
|
|
|
result = build_block(
|
|
|
|
chain,
|
|
|
|
tx_pool,
|
|
|
|
verifier_cache.clone(),
|
|
|
|
key_id.clone(),
|
|
|
|
wallet_listener_url.clone(),
|
|
|
|
);
|
2018-04-13 16:42:25 +03:00
|
|
|
}
|
|
|
|
return result.unwrap();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Builds a new block with the chain head as previous and eligible
|
|
|
|
/// transactions from the pool.
|
|
|
|
fn build_block(
|
|
|
|
chain: &Arc<chain::Chain>,
|
2018-08-28 00:22:48 +03:00
|
|
|
tx_pool: &Arc<RwLock<pool::TransactionPool>>,
|
2018-12-08 02:59:40 +03:00
|
|
|
verifier_cache: Arc<RwLock<dyn VerifierCache>>,
|
2018-04-13 16:42:25 +03:00
|
|
|
key_id: Option<Identifier>,
|
|
|
|
wallet_listener_url: Option<String>,
|
|
|
|
) -> Result<(core::Block, BlockFees), Error> {
|
2018-05-07 16:21:41 +03:00
|
|
|
let head = chain.head_header()?;
|
|
|
|
|
2018-10-17 12:06:38 +03:00
|
|
|
// prepare the block header timestamp
|
2018-07-30 11:33:28 +03:00
|
|
|
let mut now_sec = Utc::now().timestamp();
|
|
|
|
let head_sec = head.timestamp.timestamp();
|
2018-04-13 16:42:25 +03:00
|
|
|
if now_sec <= head_sec {
|
|
|
|
now_sec = head_sec + 1;
|
|
|
|
}
|
|
|
|
|
2018-10-06 23:06:02 +03:00
|
|
|
// Determine the difficulty our block should be at.
|
|
|
|
// Note: do not keep the difficulty_iter in scope (it has an active batch).
|
2018-10-23 00:34:23 +03:00
|
|
|
let difficulty = consensus::next_difficulty(head.height + 1, chain.difficulty_iter());
|
2018-04-13 16:42:25 +03:00
|
|
|
|
|
|
|
// extract current transaction from the pool
|
2018-10-25 17:00:39 +03:00
|
|
|
let txs = tx_pool.read().prepare_mineable_transactions()?;
|
2018-05-16 02:21:33 +03:00
|
|
|
|
2018-04-13 16:42:25 +03:00
|
|
|
// build the coinbase and the block itself
|
|
|
|
let fees = txs.iter().map(|tx| tx.fee()).sum();
|
|
|
|
let height = head.height + 1;
|
|
|
|
let block_fees = BlockFees {
|
|
|
|
fees,
|
|
|
|
key_id,
|
|
|
|
height,
|
|
|
|
};
|
|
|
|
|
|
|
|
let (output, kernel, block_fees) = get_coinbase(wallet_listener_url, block_fees)?;
|
2018-12-07 02:38:15 +03:00
|
|
|
let mut b = core::Block::from_reward(&head, txs, output, kernel, difficulty.difficulty)?;
|
2018-04-13 16:42:25 +03:00
|
|
|
|
|
|
|
// making sure we're not spending time mining a useless block
|
2018-10-13 03:57:08 +03:00
|
|
|
b.validate(&head.total_kernel_offset, verifier_cache)?;
|
2018-04-13 16:42:25 +03:00
|
|
|
|
2018-09-25 01:15:55 +03:00
|
|
|
b.header.pow.nonce = thread_rng().gen();
|
2018-10-19 22:39:54 +03:00
|
|
|
b.header.pow.secondary_scaling = difficulty.secondary_scaling;
|
2018-10-13 23:57:01 +03:00
|
|
|
b.header.timestamp = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(now_sec, 0), Utc);
|
2018-04-13 16:42:25 +03:00
|
|
|
|
2018-09-11 01:36:57 +03:00
|
|
|
let b_difficulty = (b.header.total_difficulty() - head.total_difficulty()).to_num();
|
2018-04-13 16:42:25 +03:00
|
|
|
debug!(
|
|
|
|
"Built new block with {} inputs and {} outputs, network difficulty: {}, cumulative difficulty {}",
|
2018-08-16 00:14:48 +03:00
|
|
|
b.inputs().len(),
|
|
|
|
b.outputs().len(),
|
2018-04-13 16:42:25 +03:00
|
|
|
b_difficulty,
|
2018-09-11 01:36:57 +03:00
|
|
|
b.header.total_difficulty().to_num(),
|
2018-04-13 16:42:25 +03:00
|
|
|
);
|
|
|
|
|
2018-08-20 16:48:05 +03:00
|
|
|
// Now set txhashset roots and sizes on the header of the block being built.
|
2018-11-01 12:51:32 +03:00
|
|
|
let roots_result = chain.set_txhashset_roots(&mut b);
|
2018-04-13 16:42:25 +03:00
|
|
|
|
|
|
|
match roots_result {
|
|
|
|
Ok(_) => Ok((b, block_fees)),
|
|
|
|
|
|
|
|
// If it's a duplicate commitment, it's likely trying to use
|
|
|
|
// a key that's already been derived but not in the wallet
|
|
|
|
// for some reason, allow caller to retry
|
|
|
|
Err(e) => {
|
2018-07-01 01:36:38 +03:00
|
|
|
match e.kind() {
|
|
|
|
chain::ErrorKind::DuplicateCommitment(e) => Err(Error::Chain(
|
|
|
|
chain::ErrorKind::DuplicateCommitment(e).into(),
|
|
|
|
)),
|
|
|
|
|
|
|
|
//Some other issue, possibly duplicate kernel
|
|
|
|
_ => {
|
2018-10-21 23:30:56 +03:00
|
|
|
error!("Error setting txhashset root to build a block: {:?}", e);
|
2018-07-01 01:36:38 +03:00
|
|
|
Err(Error::Chain(
|
|
|
|
chain::ErrorKind::Other(format!("{:?}", e)).into(),
|
|
|
|
))
|
|
|
|
}
|
|
|
|
}
|
2018-04-13 16:42:25 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
///
|
|
|
|
/// Probably only want to do this when testing.
|
|
|
|
///
|
|
|
|
fn burn_reward(block_fees: BlockFees) -> Result<(core::Output, core::TxKernel, BlockFees), Error> {
|
2018-10-21 23:30:56 +03:00
|
|
|
warn!("Burning block fees: {:?}", block_fees);
|
2018-12-18 18:44:55 +03:00
|
|
|
let keychain = ExtKeychain::from_random_seed().unwrap();
|
2018-10-10 12:11:01 +03:00
|
|
|
let key_id = ExtKeychain::derive_key_id(1, 1, 0, 0, 0);
|
2018-04-13 16:42:25 +03:00
|
|
|
let (out, kernel) =
|
2018-12-08 02:59:40 +03:00
|
|
|
crate::core::libtx::reward::output(&keychain, &key_id, block_fees.fees, block_fees.height)
|
|
|
|
.unwrap();
|
2018-04-13 16:42:25 +03:00
|
|
|
Ok((out, kernel, block_fees))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Connect to the wallet listener and get coinbase.
|
|
|
|
// Warning: If a wallet listener URL is not provided the reward will be "burnt"
|
|
|
|
fn get_coinbase(
|
|
|
|
wallet_listener_url: Option<String>,
|
|
|
|
block_fees: BlockFees,
|
|
|
|
) -> Result<(core::Output, core::TxKernel, BlockFees), Error> {
|
|
|
|
match wallet_listener_url {
|
|
|
|
None => {
|
|
|
|
// Burn it
|
|
|
|
return burn_reward(block_fees);
|
|
|
|
}
|
|
|
|
Some(wallet_listener_url) => {
|
2018-06-07 17:04:21 +03:00
|
|
|
let res = wallet::create_coinbase(&wallet_listener_url, &block_fees)?;
|
2018-04-13 16:42:25 +03:00
|
|
|
let out_bin = util::from_hex(res.output).unwrap();
|
|
|
|
let kern_bin = util::from_hex(res.kernel).unwrap();
|
|
|
|
let key_id_bin = util::from_hex(res.key_id).unwrap();
|
|
|
|
let output = ser::deserialize(&mut &out_bin[..]).unwrap();
|
|
|
|
let kernel = ser::deserialize(&mut &kern_bin[..]).unwrap();
|
|
|
|
let key_id = ser::deserialize(&mut &key_id_bin[..]).unwrap();
|
|
|
|
let block_fees = BlockFees {
|
|
|
|
key_id: Some(key_id),
|
|
|
|
..block_fees
|
|
|
|
};
|
|
|
|
|
2018-10-21 23:30:56 +03:00
|
|
|
debug!("get_coinbase: {:?}", block_fees);
|
2018-04-13 16:42:25 +03:00
|
|
|
return Ok((output, kernel, block_fees));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|