Update types to new tree_hash crate

This commit is contained in:
Paul Hauner 2019-04-16 14:14:38 +10:00
parent 3eaa06d758
commit b8c4c3308a
No known key found for this signature in database
GPG Key ID: D362883A9218FCC6
70 changed files with 284 additions and 234 deletions

View File

@ -7,9 +7,9 @@ use db::stores::{BeaconBlockStore, BeaconStateStore};
use db::{DiskDB, MemoryDB};
use fork_choice::BitwiseLMDGhost;
use slot_clock::SystemTimeSlotClock;
use ssz::TreeHash;
use std::path::PathBuf;
use std::sync::Arc;
use tree_hash::TreeHash;
use types::test_utils::TestingBeaconStateBuilder;
use types::{BeaconBlock, ChainSpec, Hash256};
@ -32,7 +32,7 @@ pub fn initialise_beacon_chain(
let (genesis_state, _keypairs) = state_builder.build();
let mut genesis_block = BeaconBlock::empty(&spec);
genesis_block.state_root = Hash256::from_slice(&genesis_state.hash_tree_root());
genesis_block.state_root = Hash256::from_slice(&genesis_state.tree_hash_root());
// Slot clock
let slot_clock = SystemTimeSlotClock::new(
@ -73,7 +73,7 @@ pub fn initialise_test_beacon_chain(
let (genesis_state, _keypairs) = state_builder.build();
let mut genesis_block = BeaconBlock::empty(spec);
genesis_block.state_root = Hash256::from_slice(&genesis_state.hash_tree_root());
genesis_block.state_root = Hash256::from_slice(&genesis_state.tree_hash_root());
// Slot clock
let slot_clock = SystemTimeSlotClock::new(

View File

@ -5,8 +5,8 @@ use db::{
};
use fork_choice::BitwiseLMDGhost;
use slot_clock::TestingSlotClock;
use ssz::TreeHash;
use std::sync::Arc;
use tree_hash::TreeHash;
use types::test_utils::TestingBeaconStateBuilder;
use types::*;
@ -27,7 +27,7 @@ impl TestingBeaconChainBuilder {
let (genesis_state, _keypairs) = self.state_builder.build();
let mut genesis_block = BeaconBlock::empty(&spec);
genesis_block.state_root = Hash256::from_slice(&genesis_state.hash_tree_root());
genesis_block.state_root = Hash256::from_slice(&genesis_state.tree_hash_root());
// Create the Beacon Chain
BeaconChain::from_genesis(

View File

@ -9,8 +9,8 @@ use fork_choice::BitwiseLMDGhost;
use log::debug;
use rayon::prelude::*;
use slot_clock::TestingSlotClock;
use ssz::TreeHash;
use std::sync::Arc;
use tree_hash::TreeHash;
use types::{test_utils::TestingBeaconStateBuilder, *};
type TestingBeaconChain = BeaconChain<MemoryDB, TestingSlotClock, BitwiseLMDGhost<MemoryDB>>;
@ -54,7 +54,7 @@ impl BeaconChainHarness {
let (mut genesis_state, keypairs) = state_builder.build();
let mut genesis_block = BeaconBlock::empty(&spec);
genesis_block.state_root = Hash256::from_slice(&genesis_state.hash_tree_root());
genesis_block.state_root = Hash256::from_slice(&genesis_state.tree_hash_root());
genesis_state
.build_epoch_cache(RelativeEpoch::Previous, &spec)
@ -163,7 +163,7 @@ impl BeaconChainHarness {
data: data.clone(),
custody_bit: false,
}
.hash_tree_root();
.tree_hash_root();
let domain = self.spec.get_domain(
state.slot.epoch(self.spec.slots_per_epoch),
Domain::Attestation,

View File

@ -4,7 +4,7 @@
use crate::beacon_chain_harness::BeaconChainHarness;
use beacon_chain::CheckPoint;
use log::{info, warn};
use ssz::SignedRoot;
use tree_hash::SignedRoot;
use types::*;
use types::test_utils::*;

View File

@ -2,9 +2,9 @@ use crate::beacon_chain::BeaconChain;
use eth2_libp2p::rpc::methods::*;
use eth2_libp2p::PeerId;
use slog::{debug, error};
use ssz::TreeHash;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tree_hash::TreeHash;
use types::{BeaconBlock, BeaconBlockBody, BeaconBlockHeader, Hash256, Slot};
/// Provides a queue for fully and partially built `BeaconBlock`s.
@ -15,7 +15,7 @@ use types::{BeaconBlock, BeaconBlockBody, BeaconBlockHeader, Hash256, Slot};
///
/// - When we receive a `BeaconBlockBody`, the only way we can find it's matching
/// `BeaconBlockHeader` is to find a header such that `header.beacon_block_body ==
/// hash_tree_root(body)`. Therefore, if we used a `HashMap` we would need to use the root of
/// tree_hash_root(body)`. Therefore, if we used a `HashMap` we would need to use the root of
/// `BeaconBlockBody` as the key.
/// - It is possible for multiple distinct blocks to have identical `BeaconBlockBodies`. Therefore
/// we cannot use a `HashMap` keyed by the root of `BeaconBlockBody`.
@ -166,7 +166,7 @@ impl ImportQueue {
let mut required_bodies: Vec<Hash256> = vec![];
for header in headers {
let block_root = Hash256::from_slice(&header.hash_tree_root()[..]);
let block_root = Hash256::from_slice(&header.tree_hash_root()[..]);
if self.chain_has_not_seen_block(&block_root) {
self.insert_header(block_root, header, sender.clone());
@ -230,7 +230,7 @@ impl ImportQueue {
///
/// If the body already existed, the `inserted` time is set to `now`.
fn insert_body(&mut self, body: BeaconBlockBody, sender: PeerId) {
let body_root = Hash256::from_slice(&body.hash_tree_root()[..]);
let body_root = Hash256::from_slice(&body.tree_hash_root()[..]);
self.partials.iter_mut().for_each(|mut p| {
if let Some(header) = &mut p.header {
@ -250,7 +250,7 @@ impl ImportQueue {
///
/// If the partial already existed, the `inserted` time is set to `now`.
fn insert_full_block(&mut self, block: BeaconBlock, sender: PeerId) {
let block_root = Hash256::from_slice(&block.hash_tree_root()[..]);
let block_root = Hash256::from_slice(&block.tree_hash_root()[..]);
let partial = PartialBeaconBlock {
slot: block.slot,

View File

@ -5,10 +5,10 @@ use eth2_libp2p::rpc::methods::*;
use eth2_libp2p::rpc::{RPCRequest, RPCResponse, RequestId};
use eth2_libp2p::PeerId;
use slog::{debug, error, info, o, warn};
use ssz::TreeHash;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tree_hash::TreeHash;
use types::{Attestation, BeaconBlock, Epoch, Hash256, Slot};
/// The number of slots that we can import blocks ahead of us, before going into full Sync mode.
@ -565,7 +565,7 @@ impl SimpleSync {
return false;
}
let block_root = Hash256::from_slice(&block.hash_tree_root());
let block_root = Hash256::from_slice(&block.tree_hash_root());
// Ignore any block that the chain already knows about.
if self.chain_has_seen_block(&block_root) {

View File

@ -2,8 +2,8 @@ pub mod test_utils;
mod traits;
use slot_clock::SlotClock;
use ssz::TreeHash;
use std::sync::Arc;
use tree_hash::TreeHash;
use types::{AttestationData, AttestationDataAndCustodyBit, FreeAttestation, Signature, Slot};
pub use self::traits::{
@ -141,7 +141,8 @@ impl<T: SlotClock, U: BeaconNode, V: DutiesReader, W: Signer> Attester<T, U, V,
data: attestation_data.clone(),
custody_bit: PHASE_0_CUSTODY_BIT,
}
.hash_tree_root();
.tree_hash_root
| update();
self.signer
.sign_attestation_message(&message[..], DOMAIN_ATTESTATION)

View File

@ -139,7 +139,7 @@ impl<T: SlotClock, U: BeaconNode, V: DutiesReader, W: Signer> BlockProducer<T, U
let randao_reveal = {
// TODO: add domain, etc to this message. Also ensure result matches `into_to_bytes32`.
let message = slot.epoch(self.spec.slots_per_epoch).hash_tree_root();
let message = slot.epoch(self.spec.slots_per_epoch).tree_hash_root();
match self.signer.sign_randao_reveal(
&message,

View File

@ -1,6 +1,5 @@
use criterion::Criterion;
use criterion::{black_box, Benchmark};
use ssz::TreeHash;
use state_processing::{
per_block_processing,
per_block_processing::{
@ -9,6 +8,7 @@ use state_processing::{
verify_block_signature,
},
};
use tree_hash::TreeHash;
use types::*;
/// Run the detailed benchmarking suite on the given `BeaconState`.
@ -263,7 +263,7 @@ pub fn bench_block_processing(
c.bench(
&format!("{}/block_processing", desc),
Benchmark::new("tree_hash_block", move |b| {
b.iter(|| black_box(block.hash_tree_root()))
b.iter(|| black_box(block.tree_hash_root()))
})
.sample_size(10),
);

View File

@ -1,6 +1,5 @@
use criterion::Criterion;
use criterion::{black_box, Benchmark};
use ssz::TreeHash;
use state_processing::{
per_epoch_processing,
per_epoch_processing::{
@ -9,6 +8,7 @@ use state_processing::{
update_active_tree_index_roots, update_latest_slashed_balances,
},
};
use tree_hash::TreeHash;
use types::test_utils::TestingBeaconStateBuilder;
use types::*;
@ -256,7 +256,7 @@ fn bench_epoch_processing(c: &mut Criterion, state: &BeaconState, spec: &ChainSp
c.bench(
&format!("{}/epoch_processing", desc),
Benchmark::new("tree_hash_state", move |b| {
b.iter(|| black_box(state_clone.hash_tree_root()))
b.iter(|| black_box(state_clone.tree_hash_root()))
})
.sample_size(SMALL_BENCHING_SAMPLE_SIZE),
);

View File

@ -1,5 +1,5 @@
use super::per_block_processing::{errors::BlockProcessingError, process_deposits};
use ssz::TreeHash;
use tree_hash::TreeHash;
use types::*;
pub enum GenesisError {
@ -36,7 +36,7 @@ pub fn get_genesis_state(
let active_validator_indices = state
.get_cached_active_validator_indices(RelativeEpoch::Current, spec)?
.to_vec();
let genesis_active_index_root = Hash256::from_slice(&active_validator_indices.hash_tree_root());
let genesis_active_index_root = Hash256::from_slice(&active_validator_indices.tree_hash_root());
state.fill_active_index_roots_with(genesis_active_index_root, spec);
// Generate the current shuffling seed.

View File

@ -162,7 +162,7 @@ pub fn process_randao(
// Verify the RANDAO is a valid signature of the proposer.
verify!(
block.body.randao_reveal.verify(
&state.current_epoch(spec).hash_tree_root()[..],
&state.current_epoch(spec).tree_hash_root()[..],
spec.get_domain(
block.slot.epoch(spec.slots_per_epoch),
Domain::Randao,

View File

@ -1,6 +1,6 @@
use super::errors::{AttestationInvalid as Invalid, AttestationValidationError as Error};
use crate::common::verify_bitfield_length;
use ssz::TreeHash;
use tree_hash::TreeHash;
use types::*;
/// Indicates if an `Attestation` is valid to be included in a block in the current epoch of the
@ -270,14 +270,14 @@ fn verify_attestation_signature(
data: a.data.clone(),
custody_bit: false,
}
.hash_tree_root();
.tree_hash_root();
// Message when custody bitfield is `true`
let message_1 = AttestationDataAndCustodyBit {
data: a.data.clone(),
custody_bit: true,
}
.hash_tree_root();
.tree_hash_root();
let mut messages = vec![];
let mut keys = vec![];

View File

@ -1,5 +1,5 @@
use super::errors::{ExitInvalid as Invalid, ExitValidationError as Error};
use ssz::SignedRoot;
use tree_hash::SignedRoot;
use types::*;
/// Indicates if an `Exit` is valid to be included in a block in the current epoch of the given

View File

@ -1,5 +1,5 @@
use super::errors::{ProposerSlashingInvalid as Invalid, ProposerSlashingValidationError as Error};
use ssz::SignedRoot;
use tree_hash::SignedRoot;
use types::*;
/// Indicates if a `ProposerSlashing` is valid to be included in a block in the current epoch of the given

View File

@ -2,7 +2,7 @@ use super::errors::{
SlashableAttestationInvalid as Invalid, SlashableAttestationValidationError as Error,
};
use crate::common::verify_bitfield_length;
use ssz::TreeHash;
use tree_hash::TreeHash;
use types::*;
/// Indicates if a `SlashableAttestation` is valid to be included in a block in the current epoch of the given
@ -77,12 +77,12 @@ pub fn verify_slashable_attestation(
data: slashable_attestation.data.clone(),
custody_bit: false,
}
.hash_tree_root();
.tree_hash_root();
let message_1 = AttestationDataAndCustodyBit {
data: slashable_attestation.data.clone(),
custody_bit: true,
}
.hash_tree_root();
.tree_hash_root();
let mut messages = vec![];
let mut keys = vec![];

View File

@ -1,6 +1,6 @@
use super::errors::{TransferInvalid as Invalid, TransferValidationError as Error};
use bls::get_withdrawal_credentials;
use ssz::SignedRoot;
use tree_hash::SignedRoot;
use types::*;
/// Indicates if a `Transfer` is valid to be included in a block in the current epoch of the given

View File

@ -3,8 +3,8 @@ use errors::EpochProcessingError as Error;
use process_ejections::process_ejections;
use process_exit_queue::process_exit_queue;
use process_slashings::process_slashings;
use ssz::TreeHash;
use std::collections::HashMap;
use tree_hash::TreeHash;
use types::*;
use update_registry_and_shuffling_data::update_registry_and_shuffling_data;
use validator_statuses::{TotalBalances, ValidatorStatuses};
@ -236,7 +236,7 @@ pub fn finish_epoch_update(state: &mut BeaconState, spec: &ChainSpec) -> Result<
let active_index_root = Hash256::from_slice(
&state
.get_active_validator_indices(next_epoch + spec.activation_exit_delay)
.hash_tree_root()[..],
.tree_hash_root()[..],
);
state.set_active_index_root(next_epoch, active_index_root, spec)?;
@ -261,7 +261,7 @@ pub fn finish_epoch_update(state: &mut BeaconState, spec: &ChainSpec) -> Result<
let historical_batch: HistoricalBatch = state.historical_batch();
state
.historical_roots
.push(Hash256::from_slice(&historical_batch.hash_tree_root()[..]));
.push(Hash256::from_slice(&historical_batch.tree_hash_root()[..]));
}
state.previous_epoch_attestations = state.current_epoch_attestations.clone();

View File

@ -1,5 +1,5 @@
use crate::*;
use ssz::TreeHash;
use tree_hash::TreeHash;
use types::*;
#[derive(Debug, PartialEq)]
@ -32,7 +32,7 @@ fn cache_state(
latest_block_header: &BeaconBlockHeader,
spec: &ChainSpec,
) -> Result<(), Error> {
let previous_slot_state_root = Hash256::from_slice(&state.hash_tree_root()[..]);
let previous_slot_state_root = Hash256::from_slice(&state.tree_hash_root()[..]);
// Note: increment the state slot here to allow use of our `state_root` and `block_root`
// getter/setter functions.
@ -46,7 +46,7 @@ fn cache_state(
state.latest_block_header.state_root = previous_slot_state_root
}
let latest_block_root = Hash256::from_slice(&latest_block_header.hash_tree_root()[..]);
let latest_block_root = Hash256::from_slice(&latest_block_header.tree_hash_root()[..]);
state.set_block_root(previous_slot, latest_block_root, spec)?;
// Set the state slot back to what it should be.

View File

@ -26,6 +26,8 @@ ssz = { path = "../utils/ssz" }
ssz_derive = { path = "../utils/ssz_derive" }
swap_or_not_shuffle = { path = "../utils/swap_or_not_shuffle" }
test_random_derive = { path = "../utils/test_random_derive" }
tree_hash = { path = "../utils/tree_hash" }
tree_hash_derive = { path = "../utils/tree_hash_derive" }
libp2p = { git = "https://github.com/SigP/rust-libp2p", rev = "b3c32d9a821ae6cc89079499cc6e8a6bab0bffc3" }
[dev-dependencies]

View File

@ -2,9 +2,10 @@ use super::{AggregateSignature, AttestationData, Bitfield};
use crate::test_utils::TestRandom;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz::TreeHash;
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash::TreeHash;
use tree_hash_derive::{SignedRoot, TreeHash};
/// Details an attestation that can be slashable.
///

View File

@ -2,9 +2,10 @@ use crate::test_utils::TestRandom;
use crate::{Crosslink, Epoch, Hash256, Slot};
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz::TreeHash;
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash::TreeHash;
use tree_hash_derive::{SignedRoot, TreeHash};
/// The data upon which an attestation is based.
///

View File

@ -2,7 +2,8 @@ use super::AttestationData;
use crate::test_utils::TestRandom;
use rand::RngCore;
use serde_derive::Serialize;
use ssz_derive::{Decode, Encode, TreeHash};
use ssz_derive::{Decode, Encode};
use tree_hash_derive::TreeHash;
/// Used for pairing an attestation with a proof-of-custody.
///

View File

@ -1,8 +1,9 @@
use crate::{test_utils::TestRandom, SlashableAttestation};
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash_derive::TreeHash;
/// Two conflicting attestations.
///

View File

@ -3,9 +3,10 @@ use crate::*;
use bls::Signature;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz::TreeHash;
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash::TreeHash;
use tree_hash_derive::{SignedRoot, TreeHash};
/// A block of the `BeaconChain`.
///
@ -57,11 +58,11 @@ impl BeaconBlock {
}
}
/// Returns the `hash_tree_root` of the block.
/// Returns the `tree_hash_root | update` of the block.
///
/// Spec v0.5.0
pub fn canonical_root(&self) -> Hash256 {
Hash256::from_slice(&self.hash_tree_root()[..])
Hash256::from_slice(&self.tree_hash_root()[..])
}
/// Returns a full `BeaconBlockHeader` of this block.
@ -77,7 +78,7 @@ impl BeaconBlock {
slot: self.slot,
previous_block_root: self.previous_block_root,
state_root: self.state_root,
block_body_root: Hash256::from_slice(&self.body.hash_tree_root()[..]),
block_body_root: Hash256::from_slice(&self.body.tree_hash_root()[..]),
signature: self.signature.clone(),
}
}

View File

@ -2,8 +2,9 @@ use crate::test_utils::TestRandom;
use crate::*;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash_derive::TreeHash;
/// The body of a `BeaconChain` block, containing operations.
///

View File

@ -3,9 +3,10 @@ use crate::*;
use bls::Signature;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz::TreeHash;
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash::TreeHash;
use tree_hash_derive::{SignedRoot, TreeHash};
/// A header of a `BeaconBlock`.
///
@ -32,11 +33,11 @@ pub struct BeaconBlockHeader {
}
impl BeaconBlockHeader {
/// Returns the `hash_tree_root` of the header.
/// Returns the `tree_hash_root` of the header.
///
/// Spec v0.5.0
pub fn canonical_root(&self) -> Hash256 {
Hash256::from_slice(&self.hash_tree_root()[..])
Hash256::from_slice(&self.tree_hash_root()[..])
}
/// Given a `body`, consumes `self` and returns a complete `BeaconBlock`.

View File

@ -5,9 +5,11 @@ use int_to_bytes::int_to_bytes32;
use pubkey_cache::PubkeyCache;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz::{hash, ssz_encode, TreeHash};
use ssz_derive::{Decode, Encode, TreeHash};
use ssz::{hash, ssz_encode};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash::TreeHash;
use tree_hash_derive::TreeHash;
mod epoch_cache;
mod pubkey_cache;
@ -186,11 +188,11 @@ impl BeaconState {
}
}
/// Returns the `hash_tree_root` of the state.
/// Returns the `tree_hash_root` of the state.
///
/// Spec v0.5.0
pub fn canonical_root(&self) -> Hash256 {
Hash256::from_slice(&self.hash_tree_root()[..])
Hash256::from_slice(&self.tree_hash_root()[..])
}
pub fn historical_batch(&self) -> HistoricalBatch {

View File

@ -2,8 +2,9 @@ use crate::test_utils::TestRandom;
use crate::{Epoch, Hash256};
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash_derive::TreeHash;
/// Specifies the block hash for a shard at an epoch.
///

View File

@ -1,6 +1,7 @@
use crate::*;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode, TreeHash};
use ssz_derive::{Decode, Encode};
use tree_hash_derive::TreeHash;
#[derive(Default, Clone, Debug, PartialEq, Serialize, Deserialize, Decode, Encode, TreeHash)]
pub struct CrosslinkCommittee {

View File

@ -2,8 +2,9 @@ use super::{DepositData, Hash256};
use crate::test_utils::TestRandom;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash_derive::TreeHash;
/// A deposit to potentially become a beacon chain validator.
///

View File

@ -2,8 +2,9 @@ use super::DepositInput;
use crate::test_utils::TestRandom;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash_derive::TreeHash;
/// Data generated by the deposit contract.
///

View File

@ -3,9 +3,10 @@ use crate::*;
use bls::{PublicKey, Signature};
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz::{SignedRoot, TreeHash};
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash::{SignedRoot, TreeHash};
use tree_hash_derive::{SignedRoot, TreeHash};
/// The data supplied by the user to the deposit contract.
///

View File

@ -2,8 +2,9 @@ use super::Hash256;
use crate::test_utils::TestRandom;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash_derive::TreeHash;
/// Contains data obtained from the Eth1 chain.
///

View File

@ -2,8 +2,9 @@ use super::Eth1Data;
use crate::test_utils::TestRandom;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash_derive::TreeHash;
/// A summation of votes for some `Eth1Data`.
///

View File

@ -5,8 +5,9 @@ use crate::{
use int_to_bytes::int_to_bytes4;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash_derive::TreeHash;
/// Specifies a fork of the `BeaconChain`, to prevent replay attacks.
///

View File

@ -2,8 +2,9 @@ use crate::test_utils::TestRandom;
use crate::Hash256;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash_derive::TreeHash;
/// Historical block and state roots.
///

View File

@ -2,8 +2,9 @@ use crate::test_utils::TestRandom;
use crate::{Attestation, AttestationData, Bitfield, Slot};
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash_derive::TreeHash;
/// An attestation that has been included in the state but not yet fully processed.
///

View File

@ -2,8 +2,9 @@ use super::BeaconBlockHeader;
use crate::test_utils::TestRandom;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash_derive::TreeHash;
/// Two conflicting proposals from the same proposer (validator).
///

View File

@ -1,9 +1,10 @@
use crate::{test_utils::TestRandom, AggregateSignature, AttestationData, Bitfield, ChainSpec};
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz::TreeHash;
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash::TreeHash;
use tree_hash_derive::{SignedRoot, TreeHash};
/// Details an attestation that can be slashable.
///

View File

@ -14,7 +14,7 @@ use crate::test_utils::TestRandom;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use slog;
use ssz::{hash, ssz_encode, Decodable, DecodeError, Encodable, SszStream, TreeHash};
use ssz::{ssz_encode, Decodable, DecodeError, Encodable, SszStream};
use std::cmp::{Ord, Ordering};
use std::fmt;
use std::hash::{Hash, Hasher};

View File

@ -206,11 +206,21 @@ macro_rules! impl_ssz {
}
}
impl TreeHash for $type {
fn hash_tree_root(&self) -> Vec<u8> {
let mut result: Vec<u8> = vec![];
result.append(&mut self.0.hash_tree_root());
hash(&result)
impl tree_hash::TreeHash for $type {
fn tree_hash_type() -> tree_hash::TreeHashType {
tree_hash::TreeHashType::Basic
}
fn tree_hash_packed_encoding(&self) -> Vec<u8> {
ssz_encode(self)
}
fn tree_hash_packing_factor() -> usize {
32 / 8
}
fn tree_hash_root(&self) -> Vec<u8> {
int_to_bytes::int_to_bytes32(self.0)
}
}

View File

@ -2,7 +2,7 @@ use crate::slot_epoch::{Epoch, Slot};
use crate::test_utils::TestRandom;
use rand::RngCore;
use serde_derive::Serialize;
use ssz::{hash, ssz_encode, Decodable, DecodeError, Encodable, SszStream, TreeHash};
use ssz::{ssz_encode, Decodable, DecodeError, Encodable, SszStream};
use std::cmp::{Ord, Ordering};
use std::fmt;
use std::hash::{Hash, Hasher};

View File

@ -17,14 +17,14 @@ macro_rules! ssz_tests {
}
#[test]
pub fn test_hash_tree_root() {
pub fn test_tree_hash_root() {
use crate::test_utils::{SeedableRng, TestRandom, XorShiftRng};
use ssz::TreeHash;
use tree_hash::TreeHash;
let mut rng = XorShiftRng::from_seed([42; 16]);
let original = $type::random_for_test(&mut rng);
let result = original.hash_tree_root();
let result = original.tree_hash_root();
assert_eq!(result.len(), 32);
// TODO: Add further tests

View File

@ -1,6 +1,6 @@
use crate::test_utils::TestingAttestationDataBuilder;
use crate::*;
use ssz::TreeHash;
use tree_hash::TreeHash;
/// Builds an attestation to be used for testing purposes.
///
@ -74,7 +74,7 @@ impl TestingAttestationBuilder {
data: self.attestation.data.clone(),
custody_bit: false,
}
.hash_tree_root();
.tree_hash_root();
let domain = spec.get_domain(
self.attestation.data.slot.epoch(spec.slots_per_epoch),

View File

@ -1,5 +1,5 @@
use crate::*;
use ssz::TreeHash;
use tree_hash::TreeHash;
/// Builds an `AttesterSlashing`.
///
@ -66,7 +66,7 @@ impl TestingAttesterSlashingBuilder {
data: attestation.data.clone(),
custody_bit: false,
};
let message = attestation_data_and_custody_bit.hash_tree_root();
let message = attestation_data_and_custody_bit.tree_hash_root();
for (i, validator_index) in validator_indices.iter().enumerate() {
attestation.custody_bitfield.set(i, false);

View File

@ -6,7 +6,7 @@ use crate::{
*,
};
use rayon::prelude::*;
use ssz::{SignedRoot, TreeHash};
use tree_hash::{SignedRoot, TreeHash};
/// Builds a beacon block to be used for testing purposes.
///
@ -43,7 +43,7 @@ impl TestingBeaconBlockBuilder {
/// Modifying the block's slot after signing may invalidate the signature.
pub fn set_randao_reveal(&mut self, sk: &SecretKey, fork: &Fork, spec: &ChainSpec) {
let epoch = self.block.slot.epoch(spec.slots_per_epoch);
let message = epoch.hash_tree_root();
let message = epoch.tree_hash_root();
let domain = spec.get_domain(epoch, Domain::Randao, fork);
self.block.body.randao_reveal = Signature::new(&message, domain, sk);
}

View File

@ -1,5 +1,5 @@
use crate::*;
use ssz::SignedRoot;
use tree_hash::SignedRoot;
/// Builds a `ProposerSlashing`.
///

View File

@ -1,5 +1,5 @@
use crate::*;
use ssz::SignedRoot;
use tree_hash::SignedRoot;
/// Builds a transfer to be used for testing purposes.
///

View File

@ -1,5 +1,5 @@
use crate::*;
use ssz::SignedRoot;
use tree_hash::SignedRoot;
/// Builds an exit to be used for testing purposes.
///

View File

@ -4,9 +4,10 @@ use bls::{PublicKey, Signature};
use derivative::Derivative;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz::TreeHash;
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash::TreeHash;
use tree_hash_derive::{SignedRoot, TreeHash};
/// The data submitted to the deposit contract.
///

View File

@ -1,8 +1,9 @@
use crate::{test_utils::TestRandom, Epoch, Hash256, PublicKey};
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash_derive::TreeHash;
/// Information about a `BeaconChain` validator.
///

View File

@ -2,9 +2,10 @@ use crate::{test_utils::TestRandom, Epoch};
use bls::Signature;
use rand::RngCore;
use serde_derive::{Deserialize, Serialize};
use ssz::TreeHash;
use ssz_derive::{Decode, Encode, SignedRoot, TreeHash};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash::TreeHash;
use tree_hash_derive::{SignedRoot, TreeHash};
/// An exit voluntarily submitted a validator who wishes to withdraw.
///

View File

@ -12,3 +12,4 @@ serde = "1.0"
serde_derive = "1.0"
serde_hex = { path = "../serde_hex" }
ssz = { path = "../ssz" }
tree_hash = { path = "../tree_hash" }

View File

@ -166,7 +166,7 @@ impl<'de> Deserialize<'de> for AggregateSignature {
}
impl TreeHash for AggregateSignature {
fn hash_tree_root(&self) -> Vec<u8> {
fn tree_hash_root(&self) -> Vec<u8> {
hash(&self.as_bytes())
}
}

View File

@ -2,7 +2,8 @@ use super::{fake_signature::FakeSignature, AggregatePublicKey, BLS_AGG_SIG_BYTE_
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::{encode as hex_encode, PrefixedHexVisitor};
use ssz::{hash, ssz_encode, Decodable, DecodeError, Encodable, SszStream, TreeHash};
use ssz::{ssz_encode, Decodable, DecodeError, Encodable, SszStream};
use tree_hash::impl_tree_hash_for_ssz_bytes;
/// A BLS aggregate signature.
///
@ -98,11 +99,7 @@ impl<'de> Deserialize<'de> for FakeAggregateSignature {
}
}
impl TreeHash for FakeAggregateSignature {
fn hash_tree_root(&self) -> Vec<u8> {
hash(&self.bytes)
}
}
impl_tree_hash_for_ssz_bytes!(FakeAggregateSignature);
#[cfg(test)]
mod tests {

View File

@ -3,7 +3,8 @@ use hex::encode as hex_encode;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::HexVisitor;
use ssz::{hash, ssz_encode, Decodable, DecodeError, Encodable, SszStream, TreeHash};
use ssz::{ssz_encode, Decodable, DecodeError, Encodable, SszStream};
use tree_hash::impl_tree_hash_for_ssz_bytes;
/// A single BLS signature.
///
@ -73,11 +74,7 @@ impl Decodable for FakeSignature {
}
}
impl TreeHash for FakeSignature {
fn hash_tree_root(&self) -> Vec<u8> {
hash(&self.bytes)
}
}
impl_tree_hash_for_ssz_bytes!(FakeSignature);
impl Serialize for FakeSignature {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>

View File

@ -3,10 +3,11 @@ use bls_aggregates::PublicKey as RawPublicKey;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::{encode as hex_encode, HexVisitor};
use ssz::{decode, hash, ssz_encode, Decodable, DecodeError, Encodable, SszStream, TreeHash};
use ssz::{decode, ssz_encode, Decodable, DecodeError, Encodable, SszStream};
use std::default;
use std::fmt;
use std::hash::{Hash, Hasher};
use tree_hash::impl_tree_hash_for_ssz_bytes;
/// A single BLS signature.
///
@ -104,11 +105,7 @@ impl<'de> Deserialize<'de> for PublicKey {
}
}
impl TreeHash for PublicKey {
fn hash_tree_root(&self) -> Vec<u8> {
hash(&self.0.as_bytes())
}
}
impl_tree_hash_for_ssz_bytes!(PublicKey);
impl PartialEq for PublicKey {
fn eq(&self, other: &PublicKey) -> bool {

View File

@ -4,7 +4,8 @@ use hex::encode as hex_encode;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::HexVisitor;
use ssz::{decode, ssz_encode, Decodable, DecodeError, Encodable, SszStream, TreeHash};
use ssz::{decode, ssz_encode, Decodable, DecodeError, Encodable, SszStream};
use tree_hash::impl_tree_hash_for_ssz_bytes;
/// A single BLS signature.
///
@ -69,11 +70,7 @@ impl<'de> Deserialize<'de> for SecretKey {
}
}
impl TreeHash for SecretKey {
fn hash_tree_root(&self) -> Vec<u8> {
self.0.as_bytes().clone()
}
}
impl_tree_hash_for_ssz_bytes!(SecretKey);
#[cfg(test)]
mod tests {

View File

@ -115,7 +115,7 @@ impl Decodable for Signature {
}
impl TreeHash for Signature {
fn hash_tree_root(&self) -> Vec<u8> {
fn tree_hash_root(&self) -> Vec<u8> {
hash(&self.as_bytes())
}
}

View File

@ -10,3 +10,4 @@ ssz = { path = "../ssz" }
bit-vec = "0.5.0"
serde = "1.0"
serde_derive = "1.0"
tree_hash = { path = "../tree_hash" }

View File

@ -9,6 +9,7 @@ use serde_hex::{encode, PrefixedHexVisitor};
use ssz::{Decodable, Encodable};
use std::cmp;
use std::default;
use tree_hash::impl_tree_hash_for_ssz_bytes;
/// A BooleanBitfield represents a set of booleans compactly stored as a vector of bits.
/// The BooleanBitfield is given a fixed size during construction. Reads outside of the current size return an out-of-bounds error. Writes outside of the current size expand the size of the set.
@ -256,11 +257,7 @@ impl<'de> Deserialize<'de> for BooleanBitfield {
}
}
impl ssz::TreeHash for BooleanBitfield {
fn hash_tree_root(&self) -> Vec<u8> {
self.to_bytes().hash_tree_root()
}
}
impl_tree_hash_for_ssz_bytes!(BooleanBitfield);
#[cfg(test)]
mod tests {

View File

@ -1,94 +0,0 @@
use ssz::{SignedRoot, TreeHash};
use ssz_derive::{SignedRoot, TreeHash};
#[derive(TreeHash, SignedRoot)]
struct CryptoKitties {
best_kitty: u64,
worst_kitty: u8,
kitties: Vec<u32>,
}
impl CryptoKitties {
fn new() -> Self {
CryptoKitties {
best_kitty: 9999,
worst_kitty: 1,
kitties: vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43],
}
}
fn hash(&self) -> Vec<u8> {
let mut list: Vec<Vec<u8>> = Vec::new();
list.push(self.best_kitty.hash_tree_root());
list.push(self.worst_kitty.hash_tree_root());
list.push(self.kitties.hash_tree_root());
ssz::merkle_hash(&mut list)
}
}
#[test]
fn test_cryptokitties_hash() {
let kitties = CryptoKitties::new();
let expected_hash = vec![
201, 9, 139, 14, 24, 247, 21, 55, 132, 211, 51, 125, 183, 186, 177, 33, 147, 210, 42, 108,
174, 162, 221, 227, 157, 179, 15, 7, 97, 239, 82, 220,
];
assert_eq!(kitties.hash(), expected_hash);
}
#[test]
fn test_simple_tree_hash_derive() {
let kitties = CryptoKitties::new();
assert_eq!(kitties.hash_tree_root(), kitties.hash());
}
#[test]
fn test_simple_signed_root_derive() {
let kitties = CryptoKitties::new();
assert_eq!(kitties.signed_root(), kitties.hash());
}
#[derive(TreeHash, SignedRoot)]
struct Casper {
friendly: bool,
#[tree_hash(skip_hashing)]
friends: Vec<u32>,
#[signed_root(skip_hashing)]
dead: bool,
}
impl Casper {
fn new() -> Self {
Casper {
friendly: true,
friends: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
dead: true,
}
}
fn expected_signed_hash(&self) -> Vec<u8> {
let mut list = Vec::new();
list.push(self.friendly.hash_tree_root());
list.push(self.friends.hash_tree_root());
ssz::merkle_hash(&mut list)
}
fn expected_tree_hash(&self) -> Vec<u8> {
let mut list = Vec::new();
list.push(self.friendly.hash_tree_root());
list.push(self.dead.hash_tree_root());
ssz::merkle_hash(&mut list)
}
}
#[test]
fn test_annotated_tree_hash_derive() {
let casper = Casper::new();
assert_eq!(casper.hash_tree_root(), casper.expected_tree_hash());
}
#[test]
fn test_annotated_signed_root_derive() {
let casper = Casper::new();
assert_eq!(casper.signed_root(), casper.expected_signed_hash());
}

View File

@ -25,9 +25,14 @@ pub fn efficient_merkleize(bytes: &[u8]) -> Vec<u8> {
let nodes = num_nodes(leaves);
let internal_nodes = nodes - leaves;
let num_bytes = internal_nodes * HASHSIZE + bytes.len();
let num_bytes = std::cmp::max(internal_nodes, 1) * HASHSIZE + bytes.len();
let mut o: Vec<u8> = vec![0; internal_nodes * HASHSIZE];
if o.len() < HASHSIZE {
o.resize(HASHSIZE, 0);
}
o.append(&mut bytes.to_vec());
assert_eq!(o.len(), num_bytes);

View File

@ -30,6 +30,24 @@ impl_for_bitsize!(u64, 64);
impl_for_bitsize!(usize, 64);
impl_for_bitsize!(bool, 8);
impl TreeHash for [u8; 4] {
fn tree_hash_type() -> TreeHashType {
TreeHashType::List
}
fn tree_hash_packed_encoding(&self) -> Vec<u8> {
panic!("bytesN should never be packed.")
}
fn tree_hash_packing_factor() -> usize {
panic!("bytesN should never be packed.")
}
fn tree_hash_root(&self) -> Vec<u8> {
merkle_root(&ssz::ssz_encode(self))
}
}
impl TreeHash for H256 {
fn tree_hash_type() -> TreeHashType {
TreeHashType::Basic
@ -95,3 +113,20 @@ where
hash(&root_and_len)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn bool() {
let mut true_bytes: Vec<u8> = vec![1];
true_bytes.append(&mut vec![0; 31]);
let false_bytes: Vec<u8> = vec![0; 32];
assert_eq!(true.tree_hash_root(), true_bytes);
assert_eq!(false.tree_hash_root(), false_bytes);
}
}

View File

@ -31,12 +31,10 @@ fn get_hashable_named_field_idents<'a>(struct_data: &'a syn::DataStruct) -> Vec<
///
/// The field attribute is: `#[tree_hash(skip_hashing)]`
fn should_skip_hashing(field: &syn::Field) -> bool {
for attr in &field.attrs {
if attr.tts.to_string() == "( skip_hashing )" {
return true;
}
}
false
field
.attrs
.iter()
.any(|attr| attr.into_token_stream().to_string() == "# [ tree_hash ( skip_hashing ) ]")
}
/// Implements `tree_hash::CachedTreeHashSubTree` for some `struct`.

View File

@ -98,3 +98,85 @@ fn signed_root() {
assert_eq!(unsigned.tree_hash_root(), signed.signed_root());
}
#[derive(TreeHash, SignedRoot)]
struct CryptoKitties {
best_kitty: u64,
worst_kitty: u8,
kitties: Vec<u32>,
}
impl CryptoKitties {
fn new() -> Self {
CryptoKitties {
best_kitty: 9999,
worst_kitty: 1,
kitties: vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43],
}
}
fn hash(&self) -> Vec<u8> {
let mut leaves = vec![];
leaves.append(&mut self.best_kitty.tree_hash_root());
leaves.append(&mut self.worst_kitty.tree_hash_root());
leaves.append(&mut self.kitties.tree_hash_root());
tree_hash::merkle_root(&leaves)
}
}
#[test]
fn test_simple_tree_hash_derive() {
let kitties = CryptoKitties::new();
assert_eq!(kitties.tree_hash_root(), kitties.hash());
}
#[test]
fn test_simple_signed_root_derive() {
let kitties = CryptoKitties::new();
assert_eq!(kitties.signed_root(), kitties.hash());
}
#[derive(TreeHash, SignedRoot)]
struct Casper {
friendly: bool,
#[tree_hash(skip_hashing)]
friends: Vec<u32>,
#[signed_root(skip_hashing)]
dead: bool,
}
impl Casper {
fn new() -> Self {
Casper {
friendly: true,
friends: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
dead: true,
}
}
fn expected_signed_hash(&self) -> Vec<u8> {
let mut list = Vec::new();
list.append(&mut self.friendly.tree_hash_root());
list.append(&mut self.friends.tree_hash_root());
tree_hash::merkle_root(&list)
}
fn expected_tree_hash(&self) -> Vec<u8> {
let mut list = Vec::new();
list.append(&mut self.friendly.tree_hash_root());
list.append(&mut self.dead.tree_hash_root());
tree_hash::merkle_root(&list)
}
}
#[test]
fn test_annotated_tree_hash_derive() {
let casper = Casper::new();
assert_eq!(casper.tree_hash_root(), casper.expected_tree_hash());
}
#[test]
fn test_annotated_signed_root_derive() {
let casper = Casper::new();
assert_eq!(casper.signed_root(), casper.expected_signed_hash());
}

View File

@ -8,7 +8,7 @@ use super::block_producer::{BeaconNodeError, PublishOutcome, ValidatorEvent};
use crate::signer::Signer;
use beacon_node_attestation::BeaconNodeAttestation;
use slog::{error, info, warn};
use ssz::TreeHash;
use tree_hash::TreeHash;
use types::{
AggregateSignature, Attestation, AttestationData, AttestationDataAndCustodyBit,
AttestationDuty, Bitfield,
@ -123,7 +123,7 @@ impl<'a, B: BeaconNodeAttestation, S: Signer> AttestationProducer<'a, B, S> {
data: attestation.clone(),
custody_bit: false,
}
.hash_tree_root();
.tree_hash_root();
let sig = self.signer.sign_message(&message, domain)?;

View File

@ -86,7 +86,7 @@ impl<'a, B: BeaconNodeBlock, S: Signer> BlockProducer<'a, B, S> {
pub fn produce_block(&mut self) -> Result<ValidatorEvent, Error> {
let epoch = self.slot.epoch(self.spec.slots_per_epoch);
let message = epoch.hash_tree_root();
let message = epoch.tree_hash_root();
let randao_reveal = match self.signer.sign_message(
&message,
self.spec.get_domain(epoch, Domain::Randao, &self.fork),