Add domain to all signature funcitons, modify validate_proof_of_possession()

This commit is contained in:
Kirk Baird 2019-02-15 13:58:14 +11:00
parent 88c42bf3fb
commit 977f3edfb6
No known key found for this signature in database
GPG Key ID: BF864B7ED0BEA33F
19 changed files with 98 additions and 65 deletions

View File

@ -112,7 +112,7 @@ impl AttestationAggregator {
if !free_attestation if !free_attestation
.signature .signature
.verify(&signable_message, &validator_record.pubkey) .verify(&signable_message, spec.domain_attestation, &validator_record.pubkey)
{ {
return Ok(Outcome { return Ok(Outcome {
valid: false, valid: false,

View File

@ -25,23 +25,23 @@ impl LocalSigner {
} }
/// Sign some message. /// Sign some message.
fn bls_sign(&self, message: &[u8]) -> Option<Signature> { fn bls_sign(&self, message: &[u8], domain: u64) -> Option<Signature> {
Some(Signature::new(message, &self.keypair.sk)) Some(Signature::new(message, domain, &self.keypair.sk))
} }
} }
impl BlockProposerSigner for LocalSigner { impl BlockProposerSigner for LocalSigner {
fn sign_block_proposal(&self, message: &[u8]) -> Option<Signature> { fn sign_block_proposal(&self, message: &[u8], domain: u64) -> Option<Signature> {
self.bls_sign(message) self.bls_sign(message, domain)
} }
fn sign_randao_reveal(&self, message: &[u8]) -> Option<Signature> { fn sign_randao_reveal(&self, message: &[u8], domain: u64) -> Option<Signature> {
self.bls_sign(message) self.bls_sign(message, domain)
} }
} }
impl AttesterSigner for LocalSigner { impl AttesterSigner for LocalSigner {
fn sign_attestation_message(&self, message: &[u8]) -> Option<Signature> { fn sign_attestation_message(&self, message: &[u8], domain: u64) -> Option<Signature> {
self.bls_sign(message) self.bls_sign(message, domain)
} }
} }

View File

@ -10,6 +10,7 @@ pub use self::traits::{
}; };
const PHASE_0_CUSTODY_BIT: bool = false; const PHASE_0_CUSTODY_BIT: bool = false;
const DOMAIN_ATTESTATION: u64 = 1;
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum PollOutcome { pub enum PollOutcome {
@ -137,7 +138,7 @@ impl<T: SlotClock, U: BeaconNode, V: DutiesReader, W: Signer> Attester<T, U, V,
self.store_produce(attestation_data); self.store_produce(attestation_data);
self.signer self.signer
.sign_attestation_message(&attestation_data.signable_message(PHASE_0_CUSTODY_BIT)[..]) .sign_attestation_message(&attestation_data.signable_message(PHASE_0_CUSTODY_BIT)[..], DOMAIN_ATTESTATION)
} }
/// Returns `true` if signing some attestation_data is safe (non-slashable). /// Returns `true` if signing some attestation_data is safe (non-slashable).

View File

@ -25,7 +25,7 @@ impl LocalSigner {
} }
impl Signer for LocalSigner { impl Signer for LocalSigner {
fn sign_attestation_message(&self, message: &[u8]) -> Option<Signature> { fn sign_attestation_message(&self, message: &[u8], domain: u64) -> Option<Signature> {
Some(Signature::new(message, &self.keypair.sk)) Some(Signature::new(message, domain, &self.keypair.sk))
} }
} }

View File

@ -45,5 +45,5 @@ pub trait DutiesReader: Send + Sync {
/// Signs message using an internally-maintained private key. /// Signs message using an internally-maintained private key.
pub trait Signer { pub trait Signer {
fn sign_attestation_message(&self, message: &[u8]) -> Option<Signature>; fn sign_attestation_message(&self, message: &[u8], domain: u64) -> Option<Signature>;
} }

View File

@ -134,7 +134,7 @@ impl<T: SlotClock, U: BeaconNode, V: DutiesReader, W: Signer> BlockProducer<T, U
// TODO: add domain, etc to this message. Also ensure result matches `into_to_bytes32`. // TODO: add domain, etc to this message. Also ensure result matches `into_to_bytes32`.
let message = ssz_encode(&slot.epoch(self.spec.epoch_length)); let message = ssz_encode(&slot.epoch(self.spec.epoch_length));
match self.signer.sign_randao_reveal(&message) { match self.signer.sign_randao_reveal(&message, self.spec.domain_randao) {
None => return Ok(PollOutcome::SignerRejection(slot)), None => return Ok(PollOutcome::SignerRejection(slot)),
Some(signature) => signature, Some(signature) => signature,
} }
@ -168,7 +168,7 @@ impl<T: SlotClock, U: BeaconNode, V: DutiesReader, W: Signer> BlockProducer<T, U
match self match self
.signer .signer
.sign_block_proposal(&block.proposal_root(&self.spec)[..]) .sign_block_proposal(&block.proposal_root(&self.spec)[..], self.spec.domain_proposal)
{ {
None => None, None => None,
Some(signature) => { Some(signature) => {

View File

@ -25,11 +25,11 @@ impl LocalSigner {
} }
impl Signer for LocalSigner { impl Signer for LocalSigner {
fn sign_block_proposal(&self, message: &[u8]) -> Option<Signature> { fn sign_block_proposal(&self, message: &[u8], domain: u64) -> Option<Signature> {
Some(Signature::new(message, &self.keypair.sk)) Some(Signature::new(message, domain, &self.keypair.sk))
} }
fn sign_randao_reveal(&self, message: &[u8]) -> Option<Signature> { fn sign_randao_reveal(&self, message: &[u8], domain: u64) -> Option<Signature> {
Some(Signature::new(message, &self.keypair.sk)) Some(Signature::new(message, domain, &self.keypair.sk))
} }
} }

View File

@ -44,6 +44,6 @@ pub trait DutiesReader: Send + Sync {
/// Signs message using an internally-maintained private key. /// Signs message using an internally-maintained private key.
pub trait Signer { pub trait Signer {
fn sign_block_proposal(&self, message: &[u8]) -> Option<Signature>; fn sign_block_proposal(&self, message: &[u8], domain: u64) -> Option<Signature>;
fn sign_randao_reveal(&self, message: &[u8]) -> Option<Signature>; fn sign_randao_reveal(&self, message: &[u8], domain: u64) -> Option<Signature>;
} }

View File

@ -31,7 +31,8 @@ use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use types::{ use types::{
readers::BeaconBlockReader, readers::BeaconBlockReader,
slot_epoch_height::{Height, Slot}, slot_epoch::Slot,
slot_height::SlotHeight,
validator_registry::get_active_validator_indices, validator_registry::get_active_validator_indices,
BeaconBlock, Hash256, BeaconBlock, Hash256,
}; };
@ -77,7 +78,7 @@ pub struct OptimisedLMDGhost<T: ClientDB + Sized> {
block_store: Arc<BeaconBlockStore<T>>, block_store: Arc<BeaconBlockStore<T>>,
/// State storage access. /// State storage access.
state_store: Arc<BeaconStateStore<T>>, state_store: Arc<BeaconStateStore<T>>,
max_known_height: Height, max_known_height: SlotHeight,
} }
impl<T> OptimisedLMDGhost<T> impl<T> OptimisedLMDGhost<T>
@ -93,7 +94,7 @@ where
ancestors: vec![HashMap::new(); 16], ancestors: vec![HashMap::new(); 16],
latest_attestation_targets: HashMap::new(), latest_attestation_targets: HashMap::new(),
children: HashMap::new(), children: HashMap::new(),
max_known_height: Height::new(0), max_known_height: SlotHeight::new(0),
block_store, block_store,
state_store, state_store,
} }
@ -137,7 +138,7 @@ where
} }
/// Gets the ancestor at a given height `at_height` of a block specified by `block_hash`. /// Gets the ancestor at a given height `at_height` of a block specified by `block_hash`.
fn get_ancestor(&mut self, block_hash: Hash256, at_height: Height) -> Option<Hash256> { fn get_ancestor(&mut self, block_hash: Hash256, at_height: SlotHeight) -> Option<Hash256> {
// return None if we can't get the block from the db. // return None if we can't get the block from the db.
let block_height = { let block_height = {
let block_slot = self let block_slot = self
@ -186,7 +187,7 @@ where
fn get_clear_winner( fn get_clear_winner(
&mut self, &mut self,
latest_votes: &HashMap<Hash256, u64>, latest_votes: &HashMap<Hash256, u64>,
block_height: Height, block_height: SlotHeight,
) -> Option<Hash256> { ) -> Option<Hash256> {
// map of vote counts for every hash at this height // map of vote counts for every hash at this height
let mut current_votes: HashMap<Hash256, u64> = HashMap::new(); let mut current_votes: HashMap<Hash256, u64> = HashMap::new();

View File

@ -29,7 +29,7 @@ use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use types::{ use types::{
readers::{BeaconBlockReader, BeaconStateReader}, readers::{BeaconBlockReader, BeaconStateReader},
slot_epoch_height::Slot, slot_epoch::Slot,
validator_registry::get_active_validator_indices, validator_registry::get_active_validator_indices,
BeaconBlock, Hash256, BeaconBlock, Hash256,
}; };

View File

@ -374,14 +374,12 @@ fn validate_attestation_signature_optional(
Ok(()) Ok(())
} }
fn get_domain(_fork: &Fork, _epoch: Epoch, _domain_type: u64) -> u64 { fn get_domain(fork: &Fork, epoch: Epoch, domain_type: u64) -> u64 {
// TODO: stubbed out. fork.get_domain(epoch, domain_type)
0
} }
fn bls_verify(pubkey: &PublicKey, message: &[u8], signature: &Signature, _domain: u64) -> bool { fn bls_verify(pubkey: &PublicKey, message: &[u8], signature: &Signature, domain: u64) -> bool {
// TODO: add domain signature.verify(message, domain, pubkey)
signature.verify(message, pubkey)
} }
impl From<AttestationValidationError> for Error { impl From<AttestationValidationError> for Error {

View File

@ -25,11 +25,10 @@ impl Attestation {
&self, &self,
group_public_key: &AggregatePublicKey, group_public_key: &AggregatePublicKey,
custody_bit: bool, custody_bit: bool,
// TODO: use domain. domain: u64,
_domain: u64,
) -> bool { ) -> bool {
self.aggregate_signature self.aggregate_signature
.verify(&self.signable_message(custody_bit), group_public_key) .verify(&self.signable_message(custody_bit), domain, group_public_key)
} }
} }

View File

@ -1,10 +1,9 @@
use crate::test_utils::TestRandom; use crate::test_utils::TestRandom;
use crate::{ use crate::{
validator::StatusFlags, validator_registry::get_active_validator_indices, AttestationData, validator::StatusFlags, validator_registry::get_active_validator_indices, AttestationData,
Bitfield, ChainSpec, Crosslink, Deposit, Epoch, Eth1Data, Eth1DataVote, Fork, Hash256, Bitfield, ChainSpec, Crosslink, Deposit, DepositInput, Epoch, Eth1Data, Eth1DataVote, Fork, Hash256,
PendingAttestation, PublicKey, Signature, Slot, Validator, PendingAttestation, PublicKey, Signature, Slot, Validator,
}; };
use bls::verify_proof_of_possession;
use honey_badger_split::SplitExt; use honey_badger_split::SplitExt;
use rand::RngCore; use rand::RngCore;
use serde_derive::Serialize; use serde_derive::Serialize;
@ -587,6 +586,32 @@ impl BeaconState {
self.validator_registry_update_epoch = current_epoch; self.validator_registry_update_epoch = current_epoch;
} }
/// Confirm validator owns PublicKey
pub fn validate_proof_of_possession(
&self,
pubkey: PublicKey,
proof_of_possession: Signature,
withdrawal_credentials: Hash256,
spec: &ChainSpec
) -> bool {
let proof_of_possession_data = DepositInput {
pubkey: pubkey.clone(),
withdrawal_credentials,
proof_of_possession: proof_of_possession.clone(),
};
proof_of_possession.verify(
&proof_of_possession_data.hash_tree_root(),
self.fork.get_domain(
self.slot.epoch(spec.epoch_length),
spec.domain_deposit,
),
&pubkey,
)
}
/// Process a validator deposit, returning the validator index if the deposit is valid. /// Process a validator deposit, returning the validator index if the deposit is valid.
/// ///
/// Spec v0.2.0 /// Spec v0.2.0
@ -598,8 +623,7 @@ impl BeaconState {
withdrawal_credentials: Hash256, withdrawal_credentials: Hash256,
spec: &ChainSpec, spec: &ChainSpec,
) -> Result<usize, ()> { ) -> Result<usize, ()> {
// TODO: ensure verify proof-of-possession represents the spec accurately. if !self.validate_proof_of_possession(pubkey.clone(), proof_of_possession, withdrawal_credentials, &spec) {
if !verify_proof_of_possession(&proof_of_possession, &pubkey) {
return Err(()); return Err(());
} }

View File

@ -10,6 +10,22 @@ pub struct Fork {
pub epoch: Epoch, pub epoch: Epoch,
} }
impl Fork {
/// Return the fork version of the given ``epoch``.
pub fn get_fork_version(&self, epoch: Epoch) -> u64 {
if epoch < self.epoch {
return self.previous_version;
}
self.current_version
}
/// Get the domain number that represents the fork meta and signature domain.
pub fn get_domain(&self, epoch: Epoch, domain_type: u64) -> u64 {
let fork_version = self.get_fork_version(epoch);
fork_version * u64::pow(2,32) + domain_type
}
}
impl Encodable for Fork { impl Encodable for Fork {
fn ssz_append(&self, s: &mut SszStream) { fn ssz_append(&self, s: &mut SszStream) {
s.append(&self.previous_version); s.append(&self.previous_version);

View File

@ -8,6 +8,6 @@ impl<T: RngCore> TestRandom<T> for Signature {
let mut message = vec![0; 32]; let mut message = vec![0; 32];
rng.fill_bytes(&mut message); rng.fill_bytes(&mut message);
Signature::new(&message, &secret_key) Signature::new(&message, 0, &secret_key)
} }
} }

View File

@ -5,7 +5,7 @@ authors = ["Paul Hauner <paul@paulhauner.com>"]
edition = "2018" edition = "2018"
[dependencies] [dependencies]
bls-aggregates = { git = "https://github.com/sigp/signature-schemes", tag = "v0.3.0" } bls-aggregates = { git = "https://github.com/sigp/signature-schemes", tag = "0.4.1" }
hashing = { path = "../hashing" } hashing = { path = "../hashing" }
hex = "0.3" hex = "0.3"
serde = "1.0" serde = "1.0"

View File

@ -27,8 +27,8 @@ impl AggregateSignature {
/// ///
/// Only returns `true` if the set of keys in the `AggregatePublicKey` match the set of keys /// Only returns `true` if the set of keys in the `AggregatePublicKey` match the set of keys
/// that signed the `AggregateSignature`. /// that signed the `AggregateSignature`.
pub fn verify(&self, msg: &[u8], aggregate_public_key: &AggregatePublicKey) -> bool { pub fn verify(&self, msg: &[u8], domain: u64, aggregate_public_key: &AggregatePublicKey) -> bool {
self.0.verify(msg, aggregate_public_key) self.0.verify(msg, domain, aggregate_public_key)
} }
} }
@ -73,7 +73,7 @@ mod tests {
let keypair = Keypair::random(); let keypair = Keypair::random();
let mut original = AggregateSignature::new(); let mut original = AggregateSignature::new();
original.add(&Signature::new(&[42, 42], &keypair.sk)); original.add(&Signature::new(&[42, 42], 0, &keypair.sk));
let bytes = ssz_encode(&original); let bytes = ssz_encode(&original);
let (decoded, _) = AggregateSignature::ssz_decode(&bytes, 0).unwrap(); let (decoded, _) = AggregateSignature::ssz_decode(&bytes, 0).unwrap();

View File

@ -29,24 +29,18 @@ fn extend_if_needed(hash: &mut Vec<u8>) {
/// For some signature and public key, ensure that the signature message was the public key and it /// For some signature and public key, ensure that the signature message was the public key and it
/// was signed by the secret key that corresponds to that public key. /// was signed by the secret key that corresponds to that public key.
pub fn verify_proof_of_possession(sig: &Signature, pubkey: &PublicKey) -> bool {
let mut hash = hash(&ssz_encode(pubkey));
extend_if_needed(&mut hash);
sig.verify_hashed(&hash, &pubkey)
}
pub fn create_proof_of_possession(keypair: &Keypair) -> Signature { pub fn create_proof_of_possession(keypair: &Keypair) -> Signature {
let mut hash = hash(&ssz_encode(&keypair.pk)); Signature::new(&ssz_encode(&keypair.pk), 0, &keypair.sk)
extend_if_needed(&mut hash);
Signature::new_hashed(&hash, &keypair.sk)
} }
pub fn bls_verify_aggregate( pub fn bls_verify_aggregate(
pubkey: &AggregatePublicKey, pubkey: &AggregatePublicKey,
message: &[u8], message: &[u8],
signature: &AggregateSignature, signature: &AggregateSignature,
_domain: u64, domain: u64,
) -> bool { ) -> bool {
// TODO: add domain // TODO: add domain
signature.verify(message, pubkey) signature.verify(message, domain, pubkey)
} }

View File

@ -14,24 +14,24 @@ pub struct Signature(RawSignature);
impl Signature { impl Signature {
/// Instantiate a new Signature from a message and a SecretKey. /// Instantiate a new Signature from a message and a SecretKey.
pub fn new(msg: &[u8], sk: &SecretKey) -> Self { pub fn new(msg: &[u8], domain: u64, sk: &SecretKey) -> Self {
Signature(RawSignature::new(msg, sk.as_raw())) Signature(RawSignature::new(msg, domain, sk.as_raw()))
} }
/// Instantiate a new Signature from a message and a SecretKey, where the message has already /// Instantiate a new Signature from a message and a SecretKey, where the message has already
/// been hashed. /// been hashed.
pub fn new_hashed(msg_hashed: &[u8], sk: &SecretKey) -> Self { pub fn new_hashed(x_real_hashed: &[u8], x_imaginary_hashed: &[u8], sk: &SecretKey) -> Self {
Signature(RawSignature::new_hashed(msg_hashed, sk.as_raw())) Signature(RawSignature::new_hashed(x_real_hashed, x_imaginary_hashed, sk.as_raw()))
} }
/// Verify the Signature against a PublicKey. /// Verify the Signature against a PublicKey.
pub fn verify(&self, msg: &[u8], pk: &PublicKey) -> bool { pub fn verify(&self, msg: &[u8], domain: u64, pk: &PublicKey) -> bool {
self.0.verify(msg, pk.as_raw()) self.0.verify(msg, domain, pk.as_raw())
} }
/// Verify the Signature against a PublicKey, where the message has already been hashed. /// Verify the Signature against a PublicKey, where the message has already been hashed.
pub fn verify_hashed(&self, msg_hash: &[u8], pk: &PublicKey) -> bool { pub fn verify_hashed(&self, x_real_hashed: &[u8], x_imaginary_hashed: &[u8], pk: &PublicKey) -> bool {
self.0.verify_hashed(msg_hash, pk.as_raw()) self.0.verify_hashed(x_real_hashed, x_imaginary_hashed, pk.as_raw())
} }
/// Returns the underlying signature. /// Returns the underlying signature.
@ -41,7 +41,7 @@ impl Signature {
/// Returns a new empty signature. /// Returns a new empty signature.
pub fn empty_signature() -> Self { pub fn empty_signature() -> Self {
let empty: Vec<u8> = vec![0; 97]; let empty: Vec<u8> = vec![0; 96];
Signature(RawSignature::from_bytes(&empty).unwrap()) Signature(RawSignature::from_bytes(&empty).unwrap())
} }
} }
@ -85,7 +85,7 @@ mod tests {
pub fn test_ssz_round_trip() { pub fn test_ssz_round_trip() {
let keypair = Keypair::random(); let keypair = Keypair::random();
let original = Signature::new(&[42, 42], &keypair.sk); let original = Signature::new(&[42, 42], 0, &keypair.sk);
let bytes = ssz_encode(&original); let bytes = ssz_encode(&original);
let (decoded, _) = Signature::ssz_decode(&bytes, 0).unwrap(); let (decoded, _) = Signature::ssz_decode(&bytes, 0).unwrap();