Merge branch 'master' into unitdiff

This commit is contained in:
Ignotus Peverell
2018-10-25 14:20:41 -07:00
committed by GitHub
131 changed files with 1942 additions and 2372 deletions
+1 -1
View File
@@ -297,7 +297,7 @@ where
}
/// Factor by which the secondary proof of work difficulty will be adjusted
pub fn secondary_pow_scaling(height: u64, diff_data: &Vec<HeaderInfo>) -> u32 {
pub fn secondary_pow_scaling(height: u64, diff_data: &[HeaderInfo]) -> u32 {
// Get the secondary count across the window, in pct (100 * 60 * 2nd_pow_fraction)
let snd_count = 100 * diff_data.iter().filter(|n| n.is_secondary).count() as u64;
+59 -29
View File
@@ -20,7 +20,8 @@ use std::collections::HashSet;
use std::fmt;
use std::iter::FromIterator;
use std::mem;
use std::sync::{Arc, RwLock};
use std::sync::Arc;
use util::RwLock;
use consensus::{self, reward, REWARD};
use core::committed::{self, Committed};
@@ -35,7 +36,7 @@ use global;
use keychain::{self, BlindingFactor};
use pow::{Difficulty, Proof, ProofOfWork};
use ser::{self, PMMRable, Readable, Reader, Writeable, Writer};
use util::{secp, static_secp_instance, LOGGER};
use util::{secp, static_secp_instance};
/// Errors thrown by Block validation
#[derive(Debug, Clone, Eq, PartialEq, Fail)]
@@ -285,7 +286,7 @@ impl BlockHeader {
/// Total difficulty accumulated by the proof of work on this header
pub fn total_difficulty(&self) -> Difficulty {
self.pow.total_difficulty.clone()
self.pow.total_difficulty
}
/// The "overage" to use when verifying the kernel sums.
@@ -361,10 +362,7 @@ impl Readable for Block {
body.validate_read(true)
.map_err(|_| ser::Error::CorruptedData)?;
Ok(Block {
header: header,
body: body,
})
Ok(Block { header, body })
}
}
@@ -420,16 +418,40 @@ impl Block {
Ok(block)
}
/// Extract tx data from this block as a single aggregate tx.
pub fn aggregate_transaction(
&self,
prev_kernel_offset: BlindingFactor,
) -> Result<Option<Transaction>, Error> {
let inputs = self.inputs().iter().cloned().collect();
let outputs = self
.outputs()
.iter()
.filter(|x| !x.features.contains(OutputFeatures::COINBASE_OUTPUT))
.cloned()
.collect();
let kernels = self
.kernels()
.iter()
.filter(|x| !x.features.contains(KernelFeatures::COINBASE_KERNEL))
.cloned()
.collect::<Vec<_>>();
let tx = if kernels.is_empty() {
None
} else {
let tx = Transaction::new(inputs, outputs, kernels)
.with_offset(self.block_kernel_offset(prev_kernel_offset)?);
Some(tx)
};
Ok(tx)
}
/// Hydrate a block from a compact block.
/// Note: caller must validate the block themselves, we do not validate it
/// here.
pub fn hydrate_from(cb: CompactBlock, txs: Vec<Transaction>) -> Result<Block, Error> {
trace!(
LOGGER,
"block: hydrate_from: {}, {} txs",
cb.hash(),
txs.len(),
);
trace!("block: hydrate_from: {}, {} txs", cb.hash(), txs.len(),);
let header = cb.header.clone();
@@ -469,7 +491,7 @@ impl Block {
/// Build a new empty block from a specified header
pub fn with_header(header: BlockHeader) -> Block {
Block {
header: header,
header,
..Default::default()
}
}
@@ -596,6 +618,23 @@ impl Block {
Ok(())
}
fn block_kernel_offset(
&self,
prev_kernel_offset: BlindingFactor,
) -> Result<BlindingFactor, Error> {
let offset = if self.header.total_kernel_offset() == prev_kernel_offset {
// special case when the sum hasn't changed (typically an empty block),
// zero isn't a valid private key but it's a valid blinding factor
BlindingFactor::zero()
} else {
committed::sum_kernel_offsets(
vec![self.header.total_kernel_offset()],
vec![prev_kernel_offset],
)?
};
Ok(offset)
}
/// Validates all the elements in a block that can be checked without
/// additional data. Includes commitment sums and kernels, Merkle
/// trees, reward, etc.
@@ -603,7 +642,7 @@ impl Block {
&self,
prev_kernel_offset: &BlindingFactor,
verifier: Arc<RwLock<VerifierCache>>,
) -> Result<(Commitment), Error> {
) -> Result<Commitment, Error> {
self.body.validate(true, verifier)?;
self.verify_kernel_lock_heights()?;
@@ -611,19 +650,10 @@ impl Block {
// take the kernel offset for this block (block offset minus previous) and
// verify.body.outputs and kernel sums
let block_kernel_offset = if self.header.total_kernel_offset() == prev_kernel_offset.clone()
{
// special case when the sum hasn't changed (typically an empty block),
// zero isn't a valid private key but it's a valid blinding factor
BlindingFactor::zero()
} else {
committed::sum_kernel_offsets(
vec![self.header.total_kernel_offset()],
vec![prev_kernel_offset.clone()],
)?
};
let (_utxo_sum, kernel_sum) =
self.verify_kernel_sums(self.header.overage(), block_kernel_offset)?;
let (_utxo_sum, kernel_sum) = self.verify_kernel_sums(
self.header.overage(),
self.block_kernel_offset(*prev_kernel_offset)?,
)?;
Ok(kernel_sum)
}
@@ -648,7 +678,7 @@ impl Block {
{
let secp = static_secp_instance();
let secp = secp.lock().unwrap();
let secp = secp.lock();
let over_commit = secp.commit_value(reward(self.total_fees()))?;
let out_adjust_sum = secp.commit_sum(
+2 -2
View File
@@ -53,8 +53,8 @@ impl Default for BlockSums {
fn default() -> BlockSums {
let zero_commit = secp_static::commit_to_zero_value();
BlockSums {
utxo_sum: zero_commit.clone(),
kernel_sum: zero_commit.clone(),
utxo_sum: zero_commit,
kernel_sum: zero_commit,
}
}
}
+4 -4
View File
@@ -66,7 +66,7 @@ pub trait Committed {
// commit to zero built from the offset
let kernel_sum_plus_offset = {
let secp = static_secp_instance();
let secp = secp.lock().unwrap();
let secp = secp.lock();
let mut commits = vec![kernel_sum];
if *offset != BlindingFactor::zero() {
let key = offset.secret_key(&secp)?;
@@ -90,7 +90,7 @@ pub trait Committed {
if overage != 0 {
let over_commit = {
let secp = static_secp_instance();
let secp = secp.lock().unwrap();
let secp = secp.lock();
let overage_abs = overage.checked_abs().ok_or_else(|| Error::InvalidValue)? as u64;
secp.commit_value(overage_abs).unwrap()
};
@@ -144,7 +144,7 @@ pub fn sum_commits(
positive.retain(|x| *x != zero_commit);
negative.retain(|x| *x != zero_commit);
let secp = static_secp_instance();
let secp = secp.lock().unwrap();
let secp = secp.lock();
Ok(secp.commit_sum(positive, negative)?)
}
@@ -156,7 +156,7 @@ pub fn sum_kernel_offsets(
negative: Vec<BlindingFactor>,
) -> Result<BlindingFactor, Error> {
let secp = static_secp_instance();
let secp = secp.lock().unwrap();
let secp = secp.lock();
let positive = to_secrets(positive, &secp);
let negative = to_secrets(negative, &secp);
+4 -4
View File
@@ -86,7 +86,7 @@ impl MerkleProof {
pub fn from_hex(hex: &str) -> Result<MerkleProof, String> {
let bytes = util::from_hex(hex.to_string()).unwrap();
let res = ser::deserialize(&mut &bytes[..])
.map_err(|_| format!("failed to deserialize a Merkle Proof"))?;
.map_err(|_| "failed to deserialize a Merkle Proof".to_string())?;
Ok(res)
}
@@ -102,7 +102,7 @@ impl MerkleProof {
// calculate the peaks once as these are based on overall MMR size
// (and will not change)
let peaks_pos = pmmr::peaks(self.mmr_size);
proof.verify_consume(root, element, node_pos, peaks_pos)
proof.verify_consume(root, element, node_pos, &peaks_pos)
}
/// Consumes the Merkle proof while verifying it.
@@ -113,7 +113,7 @@ impl MerkleProof {
root: Hash,
element: &PMMRIndexHashable,
node_pos: u64,
peaks_pos: Vec<u64>,
peaks_pos: &[u64],
) -> Result<(), MerkleProofError> {
let node_hash = if node_pos > self.mmr_size {
element.hash_with_index(self.mmr_size)
@@ -123,7 +123,7 @@ impl MerkleProof {
// handle special case of only a single entry in the MMR
// (no siblings to hash together)
if self.path.len() == 0 {
if self.path.is_empty() {
if root == node_hash {
return Ok(());
} else {
+4 -4
View File
@@ -42,8 +42,8 @@ where
/// Build a new db backed MMR.
pub fn new(backend: &'a mut B) -> DBPMMR<T, B> {
DBPMMR {
backend,
last_pos: 0,
backend: backend,
_marker: marker::PhantomData,
}
}
@@ -52,8 +52,8 @@ where
/// last_pos with the provided db backend.
pub fn at(backend: &'a mut B, last_pos: u64) -> DBPMMR<T, B> {
DBPMMR {
last_pos: last_pos,
backend: backend,
backend,
last_pos,
_marker: marker::PhantomData,
}
}
@@ -98,7 +98,7 @@ where
/// Push a new element into the MMR. Computes new related peaks at
/// the same time if applicable.
pub fn push(&mut self, elmt: T) -> Result<u64, String> {
pub fn push(&mut self, elmt: &T) -> Result<u64, String> {
let elmt_pos = self.last_pos + 1;
let mut current_hash = elmt.hash_with_index(elmt_pos - 1);
+13 -14
View File
@@ -22,7 +22,6 @@ use core::merkle_proof::MerkleProof;
use core::pmmr::{Backend, ReadonlyPMMR};
use core::BlockHeader;
use ser::{PMMRIndexHashable, PMMRable};
use util::LOGGER;
/// 64 bits all ones: 0b11111111...1
const ALL_ONES: u64 = u64::MAX;
@@ -54,8 +53,8 @@ where
/// Build a new prunable Merkle Mountain Range using the provided backend.
pub fn new(backend: &'a mut B) -> PMMR<T, B> {
PMMR {
backend,
last_pos: 0,
backend: backend,
_marker: marker::PhantomData,
}
}
@@ -64,8 +63,8 @@ where
/// last_pos with the provided backend.
pub fn at(backend: &'a mut B, last_pos: u64) -> PMMR<T, B> {
PMMR {
last_pos: last_pos,
backend: backend,
backend,
last_pos,
_marker: marker::PhantomData,
}
}
@@ -91,7 +90,7 @@ where
let rhs = self.bag_the_rhs(peak_pos);
let mut res = peaks(self.last_pos)
.into_iter()
.filter(|x| x < &peak_pos)
.filter(|x| *x < peak_pos)
.filter_map(|x| self.backend.get_from_file(x))
.collect::<Vec<_>>();
res.reverse();
@@ -108,7 +107,7 @@ where
pub fn bag_the_rhs(&self, peak_pos: u64) -> Option<Hash> {
let rhs = peaks(self.last_pos)
.into_iter()
.filter(|x| x > &peak_pos)
.filter(|x| *x > peak_pos)
.filter_map(|x| self.backend.get_from_file(x))
.collect::<Vec<_>>();
@@ -137,7 +136,7 @@ where
/// Build a Merkle proof for the element at the given position.
pub fn merkle_proof(&self, pos: u64) -> Result<MerkleProof, String> {
debug!(LOGGER, "merkle_proof {}, last_pos {}", pos, self.last_pos);
debug!("merkle_proof {}, last_pos {}", pos, self.last_pos);
// check this pos is actually a leaf in the MMR
if !is_leaf(pos) {
@@ -146,7 +145,7 @@ where
// check we actually have a hash in the MMR at this pos
self.get_hash(pos)
.ok_or(format!("no element at pos {}", pos))?;
.ok_or_else(|| format!("no element at pos {}", pos))?;
let mmr_size = self.unpruned_size();
@@ -384,14 +383,14 @@ where
None => hashes.push_str(&format!("{:>8} ", "??")),
}
}
trace!(LOGGER, "{}", idx);
trace!(LOGGER, "{}", hashes);
trace!("{}", idx);
trace!("{}", hashes);
}
}
/// Prints PMMR statistics to the logs, used for debugging.
pub fn dump_stats(&self) {
debug!(LOGGER, "pmmr: unpruned - {}", self.unpruned_size());
debug!("pmmr: unpruned - {}", self.unpruned_size());
self.backend.dump_stats();
}
@@ -418,8 +417,8 @@ where
None => hashes.push_str(&format!("{:>8} ", " .")),
}
}
debug!(LOGGER, "{}", idx);
debug!(LOGGER, "{}", hashes);
debug!("{}", idx);
debug!("{}", hashes);
}
}
}
@@ -511,7 +510,7 @@ pub fn peak_map_height(mut pos: u64) -> (u64, u64) {
let mut peak_size = ALL_ONES >> pos.leading_zeros();
let mut bitmap = 0;
while peak_size != 0 {
bitmap = bitmap << 1;
bitmap <<= 1;
if pos >= peak_size {
pos -= peak_size;
bitmap |= 1;
+3 -3
View File
@@ -41,8 +41,8 @@ where
/// Build a new readonly PMMR.
pub fn new(backend: &'a B) -> ReadonlyPMMR<T, B> {
ReadonlyPMMR {
backend,
last_pos: 0,
backend: backend,
_marker: marker::PhantomData,
}
}
@@ -51,8 +51,8 @@ where
/// last_pos with the provided backend.
pub fn at(backend: &'a B, last_pos: u64) -> ReadonlyPMMR<T, B> {
ReadonlyPMMR {
last_pos: last_pos,
backend: backend,
backend,
last_pos,
_marker: marker::PhantomData,
}
}
+3 -3
View File
@@ -43,8 +43,8 @@ where
/// Build a new readonly PMMR.
pub fn new(backend: &'a B) -> RewindablePMMR<T, B> {
RewindablePMMR {
backend,
last_pos: 0,
backend: backend,
_marker: marker::PhantomData,
}
}
@@ -53,8 +53,8 @@ where
/// last_pos with the provided backend.
pub fn at(backend: &'a B, last_pos: u64) -> RewindablePMMR<T, B> {
RewindablePMMR {
last_pos: last_pos,
backend: backend,
backend,
last_pos,
_marker: marker::PhantomData,
}
}
+23 -25
View File
@@ -17,8 +17,9 @@
use std::cmp::max;
use std::cmp::Ordering;
use std::collections::HashSet;
use std::sync::{Arc, RwLock};
use std::sync::Arc;
use std::{error, fmt};
use util::RwLock;
use consensus::{self, VerifySortOrder};
use core::hash::Hashed;
@@ -176,7 +177,7 @@ impl Readable for TxKernel {
let features =
KernelFeatures::from_bits(reader.read_u8()?).ok_or(ser::Error::CorruptedData)?;
Ok(TxKernel {
features: features,
features,
fee: reader.read_u64()?,
lock_height: reader.read_u64()?,
excess: Commitment::read(reader)?,
@@ -197,7 +198,7 @@ impl TxKernel {
pub fn verify(&self) -> Result<(), secp::Error> {
let msg = Message::from_slice(&kernel_sig_msg(self.fee, self.lock_height))?;
let secp = static_secp_instance();
let secp = secp.lock().unwrap();
let secp = secp.lock();
let sig = &self.excess_sig;
// Verify aggsig directly in libsecp
let pubkey = &self.excess.to_pubkey(&secp)?;
@@ -229,13 +230,13 @@ impl TxKernel {
/// Builds a new tx kernel with the provided fee.
pub fn with_fee(self, fee: u64) -> TxKernel {
TxKernel { fee: fee, ..self }
TxKernel { fee, ..self }
}
/// Builds a new tx kernel with the provided lock_height.
pub fn with_lock_height(self, lock_height: u64) -> TxKernel {
TxKernel {
lock_height: lock_height,
lock_height,
..self
}
}
@@ -355,9 +356,9 @@ impl TransactionBody {
verify_sorted: bool,
) -> Result<TransactionBody, Error> {
let body = TransactionBody {
inputs: inputs,
outputs: outputs,
kernels: kernels,
inputs,
outputs,
kernels,
};
if verify_sorted {
@@ -435,7 +436,7 @@ impl TransactionBody {
/// Calculate transaction weight from transaction details
pub fn weight(input_len: usize, output_len: usize, kernel_len: usize) -> u32 {
let mut body_weight = -1 * (input_len as i32) + (4 * output_len as i32) + kernel_len as i32;
let mut body_weight = -(input_len as i32) + (4 * output_len as i32) + kernel_len as i32;
if body_weight < 1 {
body_weight = 1;
}
@@ -553,12 +554,12 @@ impl TransactionBody {
// Find all the outputs that have not had their rangeproofs verified.
let outputs = {
let mut verifier = verifier.write().unwrap();
let mut verifier = verifier.write();
verifier.filter_rangeproof_unverified(&self.outputs)
};
// Now batch verify all those unverified rangeproofs
if outputs.len() > 0 {
if !outputs.is_empty() {
let mut commits = vec![];
let mut proofs = vec![];
for x in &outputs {
@@ -570,7 +571,7 @@ impl TransactionBody {
// Find all the kernels that have not yet been verified.
let kernels = {
let mut verifier = verifier.write().unwrap();
let mut verifier = verifier.write();
verifier.filter_kernel_sig_unverified(&self.kernels)
};
@@ -583,7 +584,7 @@ impl TransactionBody {
// Cache the successful verification results for the new outputs and kernels.
{
let mut verifier = verifier.write().unwrap();
let mut verifier = verifier.write();
verifier.add_rangeproof_verified(outputs);
verifier.add_kernel_sig_verified(kernels);
}
@@ -686,10 +687,7 @@ impl Transaction {
/// Creates a new transaction using this transaction as a template
/// and with the specified offset.
pub fn with_offset(self, offset: BlindingFactor) -> Transaction {
Transaction {
offset: offset,
..self
}
Transaction { offset, ..self }
}
/// Builds a new transaction with the provided inputs added. Existing
@@ -911,7 +909,7 @@ pub fn deaggregate(mk_tx: Transaction, txs: Vec<Transaction>) -> Result<Transact
// now compute the total kernel offset
let total_kernel_offset = {
let secp = static_secp_instance();
let secp = secp.lock().unwrap();
let secp = secp.lock();
let mut positive_key = vec![mk_tx.offset]
.into_iter()
.filter(|x| *x != BlindingFactor::zero())
@@ -1071,7 +1069,7 @@ impl Readable for Output {
OutputFeatures::from_bits(reader.read_u8()?).ok_or(ser::Error::CorruptedData)?;
Ok(Output {
features: features,
features,
commit: Commitment::read(reader)?,
proof: RangeProof::read(reader)?,
})
@@ -1092,7 +1090,7 @@ impl Output {
/// Validates the range proof using the commitment
pub fn verify_proof(&self) -> Result<(), secp::Error> {
let secp = static_secp_instance();
let secp = secp.lock().unwrap();
let secp = secp.lock();
match secp.verify_bullet_proof(self.commit, self.proof, None) {
Ok(_) => Ok(()),
Err(e) => Err(e),
@@ -1105,7 +1103,7 @@ impl Output {
proofs: &Vec<RangeProof>,
) -> Result<(), secp::Error> {
let secp = static_secp_instance();
let secp = secp.lock().unwrap();
let secp = secp.lock();
match secp.verify_bullet_proof_multi(commits.clone(), proofs.clone(), None) {
Ok(_) => Ok(()),
Err(e) => Err(e),
@@ -1130,8 +1128,8 @@ impl OutputIdentifier {
/// Build a new output_identifier.
pub fn new(features: OutputFeatures, commit: &Commitment) -> OutputIdentifier {
OutputIdentifier {
features: features,
commit: commit.clone(),
features,
commit: *commit,
}
}
@@ -1151,9 +1149,9 @@ impl OutputIdentifier {
/// Converts this identifier to a full output, provided a RangeProof
pub fn into_output(self, proof: RangeProof) -> Output {
Output {
proof,
features: self.features,
commit: self.commit,
proof: proof,
}
}
@@ -1195,8 +1193,8 @@ impl Readable for OutputIdentifier {
let features =
OutputFeatures::from_bits(reader.read_u8()?).ok_or(ser::Error::CorruptedData)?;
Ok(OutputIdentifier {
features,
commit: Commitment::read(reader)?,
features: features,
})
}
}
+6 -12
View File
@@ -19,7 +19,6 @@ use lru_cache::LruCache;
use core::hash::{Hash, Hashed};
use core::{Output, TxKernel};
use util::LOGGER;
/// Verifier cache for caching expensive verification results.
/// Specifically the following -
@@ -28,10 +27,10 @@ use util::LOGGER;
pub trait VerifierCache: Sync + Send {
/// Takes a vec of tx kernels and returns those kernels
/// that have not yet been verified.
fn filter_kernel_sig_unverified(&mut self, kernels: &Vec<TxKernel>) -> Vec<TxKernel>;
fn filter_kernel_sig_unverified(&mut self, kernels: &[TxKernel]) -> Vec<TxKernel>;
/// Takes a vec of tx outputs and returns those outputs
/// that have not yet had their rangeproofs verified.
fn filter_rangeproof_unverified(&mut self, outputs: &Vec<Output>) -> Vec<Output>;
fn filter_rangeproof_unverified(&mut self, outputs: &[Output]) -> Vec<Output>;
/// Adds a vec of tx kernels to the cache (used in conjunction with the the filter above).
fn add_kernel_sig_verified(&mut self, kernels: Vec<TxKernel>);
/// Adds a vec of outputs to the cache (used in conjunction with the the filter above).
@@ -46,9 +45,6 @@ pub struct LruVerifierCache {
rangeproof_verification_cache: LruCache<Hash, bool>,
}
unsafe impl Sync for LruVerifierCache {}
unsafe impl Send for LruVerifierCache {}
impl LruVerifierCache {
/// TODO how big should these caches be?
/// They need to be *at least* large enough to cover a maxed out block.
@@ -61,7 +57,7 @@ impl LruVerifierCache {
}
impl VerifierCache for LruVerifierCache {
fn filter_kernel_sig_unverified(&mut self, kernels: &Vec<TxKernel>) -> Vec<TxKernel> {
fn filter_kernel_sig_unverified(&mut self, kernels: &[TxKernel]) -> Vec<TxKernel> {
let res = kernels
.into_iter()
.filter(|x| {
@@ -71,8 +67,7 @@ impl VerifierCache for LruVerifierCache {
.unwrap_or(&mut false)
}).cloned()
.collect::<Vec<_>>();
debug!(
LOGGER,
trace!(
"lru_verifier_cache: kernel sigs: {}, not cached (must verify): {}",
kernels.len(),
res.len()
@@ -80,7 +75,7 @@ impl VerifierCache for LruVerifierCache {
res
}
fn filter_rangeproof_unverified(&mut self, outputs: &Vec<Output>) -> Vec<Output> {
fn filter_rangeproof_unverified(&mut self, outputs: &[Output]) -> Vec<Output> {
let res = outputs
.into_iter()
.filter(|x| {
@@ -90,8 +85,7 @@ impl VerifierCache for LruVerifierCache {
.unwrap_or(&mut false)
}).cloned()
.collect::<Vec<_>>();
debug!(
LOGGER,
trace!(
"lru_verifier_cache: rangeproofs: {}, not cached (must verify): {}",
outputs.len(),
res.len()
+24 -16
View File
@@ -27,7 +27,7 @@ use pow::{self, CuckatooContext, EdgeType, PoWContext};
/// code wherever mining is needed. This should allow for
/// different sets of parameters for different purposes,
/// e.g. CI, User testing, production values
use std::sync::RwLock;
use util::RwLock;
/// Define these here, as they should be developer-set, not really tweakable
/// by users
@@ -70,13 +70,21 @@ pub const TESTNET3_INITIAL_DIFFICULTY: u64 = 30000;
/// we're sure this peer is a stuck node, and we will kick out such kind of stuck peers.
pub const STUCK_PEER_KICK_TIME: i64 = 2 * 3600 * 1000;
/// If a peer's last seen time is 2 weeks ago we will forget such kind of defunct peers.
const PEER_EXPIRATION_DAYS: i64 = 7 * 2;
/// Constant that expresses defunct peer timeout in seconds to be used in checks.
pub const PEER_EXPIRATION_REMOVE_TIME: i64 = PEER_EXPIRATION_DAYS * 24 * 3600;
/// Testnet 4 initial block difficulty
/// 1_000 times natural scale factor for cuckatoo29
pub const TESTNET4_INITIAL_DIFFICULTY: u64 = 1_000 * UNIT_DIFFICULTY;
/// Trigger compaction check on average every day for FAST_SYNC_NODE,
/// roll the dice on every block to decide,
/// all blocks lower than (BodyHead.height - CUT_THROUGH_HORIZON) will be removed.
/// Trigger compaction check on average every day for all nodes.
/// Randomized per node - roll the dice on every block to decide.
/// Will compact the txhashset to remove pruned data.
/// Will also remove old blocks and associated data from the database.
/// For a node configured as "archival_mode = true" only the txhashset will be compacted.
pub const COMPACTION_CHECK: u64 = DAY_HEIGHT;
/// Types of chain a server can run with, dictates the genesis block and
@@ -126,7 +134,7 @@ lazy_static!{
/// Set the mining mode
pub fn set_mining_mode(mode: ChainTypes) {
let mut param_ref = CHAIN_TYPE.write().unwrap();
let mut param_ref = CHAIN_TYPE.write();
*param_ref = mode;
}
@@ -150,7 +158,7 @@ pub fn pow_type() -> PoWContextTypes {
/// The minimum acceptable edge_bits
pub fn min_edge_bits() -> u8 {
let param_ref = CHAIN_TYPE.read().unwrap();
let param_ref = CHAIN_TYPE.read();
match *param_ref {
ChainTypes::AutomatedTesting => AUTOMATED_TESTING_MIN_EDGE_BITS,
ChainTypes::UserTesting => USER_TESTING_MIN_EDGE_BITS,
@@ -163,7 +171,7 @@ pub fn min_edge_bits() -> u8 {
/// while the min_edge_bits can be changed on a soft fork, changing
/// base_edge_bits is a hard fork.
pub fn base_edge_bits() -> u8 {
let param_ref = CHAIN_TYPE.read().unwrap();
let param_ref = CHAIN_TYPE.read();
match *param_ref {
ChainTypes::AutomatedTesting => AUTOMATED_TESTING_MIN_EDGE_BITS,
ChainTypes::UserTesting => USER_TESTING_MIN_EDGE_BITS,
@@ -174,7 +182,7 @@ pub fn base_edge_bits() -> u8 {
/// The proofsize
pub fn proofsize() -> usize {
let param_ref = CHAIN_TYPE.read().unwrap();
let param_ref = CHAIN_TYPE.read();
match *param_ref {
ChainTypes::AutomatedTesting => AUTOMATED_TESTING_PROOF_SIZE,
ChainTypes::UserTesting => USER_TESTING_PROOF_SIZE,
@@ -184,7 +192,7 @@ pub fn proofsize() -> usize {
/// Coinbase maturity for coinbases to be spent
pub fn coinbase_maturity() -> u64 {
let param_ref = CHAIN_TYPE.read().unwrap();
let param_ref = CHAIN_TYPE.read();
match *param_ref {
ChainTypes::AutomatedTesting => AUTOMATED_TESTING_COINBASE_MATURITY,
ChainTypes::UserTesting => USER_TESTING_COINBASE_MATURITY,
@@ -194,7 +202,7 @@ pub fn coinbase_maturity() -> u64 {
/// Initial mining difficulty
pub fn initial_block_difficulty() -> u64 {
let param_ref = CHAIN_TYPE.read().unwrap();
let param_ref = CHAIN_TYPE.read();
match *param_ref {
ChainTypes::AutomatedTesting => TESTING_INITIAL_DIFFICULTY,
ChainTypes::UserTesting => TESTING_INITIAL_DIFFICULTY,
@@ -207,7 +215,7 @@ pub fn initial_block_difficulty() -> u64 {
}
/// Initial mining secondary scale
pub fn initial_graph_weight() -> u32 {
let param_ref = CHAIN_TYPE.read().unwrap();
let param_ref = CHAIN_TYPE.read();
match *param_ref {
ChainTypes::AutomatedTesting => TESTING_INITIAL_GRAPH_WEIGHT,
ChainTypes::UserTesting => TESTING_INITIAL_GRAPH_WEIGHT,
@@ -221,7 +229,7 @@ pub fn initial_graph_weight() -> u32 {
/// Horizon at which we can cut-through and do full local pruning
pub fn cut_through_horizon() -> u32 {
let param_ref = CHAIN_TYPE.read().unwrap();
let param_ref = CHAIN_TYPE.read();
match *param_ref {
ChainTypes::AutomatedTesting => TESTING_CUT_THROUGH_HORIZON,
ChainTypes::UserTesting => TESTING_CUT_THROUGH_HORIZON,
@@ -231,19 +239,19 @@ pub fn cut_through_horizon() -> u32 {
/// Are we in automated testing mode?
pub fn is_automated_testing_mode() -> bool {
let param_ref = CHAIN_TYPE.read().unwrap();
let param_ref = CHAIN_TYPE.read();
ChainTypes::AutomatedTesting == *param_ref
}
/// Are we in user testing mode?
pub fn is_user_testing_mode() -> bool {
let param_ref = CHAIN_TYPE.read().unwrap();
let param_ref = CHAIN_TYPE.read();
ChainTypes::UserTesting == *param_ref
}
/// Are we in production mode (a live public network)?
pub fn is_production_mode() -> bool {
let param_ref = CHAIN_TYPE.read().unwrap();
let param_ref = CHAIN_TYPE.read();
ChainTypes::Testnet1 == *param_ref
|| ChainTypes::Testnet2 == *param_ref
|| ChainTypes::Testnet3 == *param_ref
@@ -256,7 +264,7 @@ pub fn is_production_mode() -> bool {
/// as the genesis block POW solution turns out to be the same for every new
/// block chain at the moment
pub fn get_genesis_nonce() -> u64 {
let param_ref = CHAIN_TYPE.read().unwrap();
let param_ref = CHAIN_TYPE.read();
match *param_ref {
// won't make a difference
ChainTypes::AutomatedTesting => 0,
+1 -1
View File
@@ -38,7 +38,7 @@ extern crate serde;
extern crate serde_derive;
extern crate siphasher;
#[macro_use]
extern crate slog;
extern crate log;
extern crate chrono;
extern crate failure;
#[macro_use]
+7 -7
View File
@@ -78,19 +78,19 @@ where
}
}
pub fn set_header_nonce(header: Vec<u8>, nonce: Option<u32>) -> Result<[u64; 4], Error> {
pub fn set_header_nonce(header: &[u8], nonce: Option<u32>) -> Result<[u64; 4], Error> {
if let Some(n) = nonce {
let len = header.len();
let mut header = header.clone();
let mut header = header.to_owned();
header.truncate(len - mem::size_of::<u32>());
header.write_u32::<LittleEndian>(n)?;
create_siphash_keys(header)
create_siphash_keys(&header)
} else {
create_siphash_keys(header)
create_siphash_keys(&header)
}
}
pub fn create_siphash_keys(header: Vec<u8>) -> Result<[u64; 4], Error> {
pub fn create_siphash_keys(header: &[u8]) -> Result<[u64; 4], Error> {
let h = blake2b(32, &[], &header);
let hb = h.as_bytes();
let mut rdr = Cursor::new(hb);
@@ -163,7 +163,7 @@ where
/// Reset the main keys used for siphash from the header and nonce
pub fn reset_header_nonce(&mut self, header: Vec<u8>, nonce: Option<u32>) -> Result<(), Error> {
self.siphash_keys = set_header_nonce(header, nonce)?;
self.siphash_keys = set_header_nonce(&header, nonce)?;
Ok(())
}
@@ -175,7 +175,7 @@ where
);
let mut masked = hash_u64 & self.edge_mask.to_u64().ok_or(ErrorKind::IntegerCast)?;
if shift {
masked = masked << 1;
masked <<= 1;
masked |= uorv;
}
Ok(T::from(masked).ok_or(ErrorKind::IntegerCast)?)
+6 -6
View File
@@ -54,14 +54,14 @@ where
pub fn new(max_edges: T, max_sols: u32, proof_size: usize) -> Result<Graph<T>, Error> {
let max_nodes = 2 * to_u64!(max_edges);
Ok(Graph {
max_edges: max_edges,
max_nodes: max_nodes,
max_edges,
max_nodes,
max_sols,
proof_size,
links: vec![],
adj_list: vec![],
visited: Bitmap::create(),
max_sols: max_sols,
solutions: vec![],
proof_size: proof_size,
nil: T::max_value(),
})
}
@@ -241,7 +241,7 @@ where
/// Simple implementation of algorithm
pub fn find_cycles_iter<'a, I>(&mut self, iter: I) -> Result<Vec<Proof>, Error>
pub fn find_cycles_iter<I>(&mut self, iter: I) -> Result<Vec<Proof>, Error>
where
I: Iterator<Item = u64>,
{
@@ -260,7 +260,7 @@ where
for s in &self.graph.solutions {
self.verify_impl(&s)?;
}
if self.graph.solutions.len() == 0 {
if self.graph.solutions.is_empty() {
Err(ErrorKind::NoSolution)?
} else {
Ok(self.graph.solutions.clone())
+4 -4
View File
@@ -77,7 +77,7 @@ where
let params = CuckooParams::new(edge_bits, proof_size)?;
let num_nodes = 2 * params.num_edges as usize;
Ok(CuckooContext {
params: params,
params,
graph: vec![T::zero(); num_nodes],
_max_sols: max_sols,
})
@@ -190,7 +190,7 @@ where
cycle.insert(Edge { u: us[0], v: vs[0] });
while nu != 0 {
// u's in even position; v's in odd
nu = nu - 1;
nu -= 1;
cycle.insert(Edge {
u: us[((nu + 1) & !1) as usize],
v: us[(nu | 1) as usize],
@@ -214,11 +214,11 @@ where
cycle.remove(&edge);
}
}
return if n == self.params.proof_size {
if n == self.params.proof_size {
Ok(sol)
} else {
Err(ErrorKind::NoCycle)?
};
}
}
/// Searches for a solution (simple implementation)
+1 -1
View File
@@ -85,7 +85,7 @@ impl From<ErrorKind> for Error {
impl From<Context<ErrorKind>> for Error {
fn from(inner: Context<ErrorKind>) -> Error {
Error { inner: inner }
Error { inner }
}
}
+1 -1
View File
@@ -37,7 +37,7 @@ impl Lean {
// edge bitmap, before trimming all of them are on
let mut edges = Bitmap::create_with_capacity(params.num_edges as u32);
edges.flip_inplace(0..params.num_edges.into());
edges.flip_inplace(0..params.num_edges);
Lean { params, edges }
}
+1 -1
View File
@@ -77,7 +77,7 @@ pub fn mine_genesis_block() -> Result<Block, Error> {
}
// total_difficulty on the genesis header *is* the difficulty of that block
let genesis_difficulty = gen.header.pow.total_difficulty.clone();
let genesis_difficulty = gen.header.pow.total_difficulty;
let sz = global::min_edge_bits();
let proof_size = global::proofsize();
+1 -1
View File
@@ -62,7 +62,7 @@ pub fn siphash24(v: &[u64; 4], nonce: u64) -> u64 {
round!();
round!();
return v0 ^ v1 ^ v2 ^ v3;
v0 ^ v1 ^ v2 ^ v3
}
#[cfg(test)]
-5
View File
@@ -80,11 +80,6 @@ impl Difficulty {
Difficulty { num: max(num, 1) }
}
/// Compute difficulty scaling factor for graph defined by 2 * 2^edge_bits * edge_bits bits
pub fn scale(edge_bits: u8) -> u64 {
(2 << (edge_bits - global::base_edge_bits()) as u64) * (edge_bits as u64)
}
/// Computes the difficulty from a hash. Divides the maximum target by the
/// provided hash and applies the Cuck(at)oo size adjustment factor (see
/// https://lists.launchpad.net/mimblewimble/msg00494.html).
+22 -31
View File
@@ -92,10 +92,7 @@ impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::IOErr(ref e, _) => e,
Error::UnexpectedData {
expected: _,
received: _,
} => "unexpected data",
Error::UnexpectedData { .. } => "unexpected data",
Error::CorruptedData => "corrupted data",
Error::TooLargeReadErr => "too large read",
Error::ConsensusError(_) => "consensus error (sort order)",
@@ -231,13 +228,13 @@ where
/// Deserializes a Readeable from any std::io::Read implementation.
pub fn deserialize<T: Readable>(source: &mut Read) -> Result<T, Error> {
let mut reader = BinReader { source: source };
let mut reader = BinReader { source };
T::read(&mut reader)
}
/// Serializes a Writeable into any std::io::Write implementation.
pub fn serialize<W: Writeable>(sink: &mut Write, thing: &W) -> Result<(), Error> {
let mut writer = BinWriter { sink: sink };
let mut writer = BinWriter { sink };
thing.write(&mut writer)
}
@@ -319,9 +316,7 @@ impl Readable for Commitment {
fn read(reader: &mut Reader) -> Result<Commitment, Error> {
let a = reader.read_fixed_bytes(PEDERSEN_COMMITMENT_SIZE)?;
let mut c = [0; PEDERSEN_COMMITMENT_SIZE];
for i in 0..PEDERSEN_COMMITMENT_SIZE {
c[i] = a[i];
}
c[..PEDERSEN_COMMITMENT_SIZE].clone_from_slice(&a[..PEDERSEN_COMMITMENT_SIZE]);
Ok(Commitment(c))
}
}
@@ -368,9 +363,7 @@ impl Readable for RangeProof {
fn read(reader: &mut Reader) -> Result<RangeProof, Error> {
let p = reader.read_limited_vec(MAX_PROOF_SIZE)?;
let mut a = [0; MAX_PROOF_SIZE];
for i in 0..p.len() {
a[i] = p[i];
}
a[..p.len()].clone_from_slice(&p[..]);
Ok(RangeProof {
proof: a,
plen: p.len(),
@@ -388,9 +381,7 @@ impl Readable for Signature {
fn read(reader: &mut Reader) -> Result<Signature, Error> {
let a = reader.read_fixed_bytes(AGG_SIGNATURE_SIZE)?;
let mut c = [0; AGG_SIGNATURE_SIZE];
for i in 0..AGG_SIGNATURE_SIZE {
c[i] = a[i];
}
c[..AGG_SIGNATURE_SIZE].clone_from_slice(&a[..AGG_SIGNATURE_SIZE]);
Ok(Signature::from_raw_data(&c).unwrap())
}
}
@@ -577,81 +568,81 @@ pub trait AsFixedBytes: Sized + AsRef<[u8]> {
impl<'a> AsFixedBytes for &'a [u8] {
fn len(&self) -> usize {
return 1;
1
}
}
impl AsFixedBytes for Vec<u8> {
fn len(&self) -> usize {
return self.len();
self.len()
}
}
impl AsFixedBytes for [u8; 1] {
fn len(&self) -> usize {
return 1;
1
}
}
impl AsFixedBytes for [u8; 2] {
fn len(&self) -> usize {
return 2;
2
}
}
impl AsFixedBytes for [u8; 4] {
fn len(&self) -> usize {
return 4;
4
}
}
impl AsFixedBytes for [u8; 6] {
fn len(&self) -> usize {
return 6;
6
}
}
impl AsFixedBytes for [u8; 8] {
fn len(&self) -> usize {
return 8;
8
}
}
impl AsFixedBytes for [u8; 20] {
fn len(&self) -> usize {
return 20;
20
}
}
impl AsFixedBytes for [u8; 32] {
fn len(&self) -> usize {
return 32;
32
}
}
impl AsFixedBytes for String {
fn len(&self) -> usize {
return self.len();
self.len()
}
}
impl AsFixedBytes for ::core::hash::Hash {
fn len(&self) -> usize {
return 32;
32
}
}
impl AsFixedBytes for ::util::secp::pedersen::RangeProof {
fn len(&self) -> usize {
return self.plen;
self.plen
}
}
impl AsFixedBytes for ::util::secp::Signature {
fn len(&self) -> usize {
return 64;
64
}
}
impl AsFixedBytes for ::util::secp::pedersen::Commitment {
fn len(&self) -> usize {
return PEDERSEN_COMMITMENT_SIZE;
PEDERSEN_COMMITMENT_SIZE
}
}
impl AsFixedBytes for BlindingFactor {
fn len(&self) -> usize {
return SECRET_KEY_SIZE;
SECRET_KEY_SIZE
}
}
impl AsFixedBytes for ::keychain::Identifier {
fn len(&self) -> usize {
return IDENTIFIER_SIZE;
IDENTIFIER_SIZE
}
}