1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use std::collections::HashSet;

use ed25519::{Keypair, PublicKey as EdPublicKey, Signature as EdSignature, Signer, Verifier};
use tiny_keccak::{Hasher, Sha3};

use crate::{Error, Hash, Result};

#[derive(Debug, Clone, Copy)]
pub struct PublicKey(pub(crate) EdPublicKey);

#[derive(Debug, Clone, Copy)]
pub struct Signature(pub(crate) EdSignature);

impl PartialEq for PublicKey {
    fn eq(&self, other: &Self) -> bool {
        self.0.to_bytes() == other.0.to_bytes()
    }
}

impl Eq for PublicKey {}

impl std::hash::Hash for PublicKey {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.to_bytes().hash(state)
    }
}

impl PartialEq for Signature {
    fn eq(&self, other: &Self) -> bool {
        self.0.to_bytes() == other.0.to_bytes()
    }
}

impl Eq for Signature {}

impl std::hash::Hash for Signature {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.to_bytes().hash(state)
    }
}

impl PublicKey {
    pub fn hash(&self) -> Hash {
        let mut sha3 = Sha3::v256();

        sha3.update(&self.ed().to_bytes());

        let mut hash = [0; 32];
        sha3.finalize(&mut hash);
        hash
    }

    pub fn ed(&self) -> EdPublicKey {
        self.0
    }
}

impl Signature {
    pub fn ed(&self) -> EdSignature {
        self.0
    }
}

pub fn ed25519_keypair() -> Keypair {
    Keypair::generate(&mut rand::thread_rng())
}

#[derive(Default)]
pub struct KeyCache(HashSet<PublicKey>);

impl KeyCache {
    pub fn verify(&self, msg: &Hash, key: &PublicKey, sig: &Signature) -> Result<()> {
        self.verify_known_key(key)?;
        key.0.verify(msg, &sig.0)?;
        Ok(())
    }

    pub fn verify_known_key(&self, key: &PublicKey) -> Result<()> {
        if self.0.contains(key) {
            Ok(())
        } else {
            Err(Error::UnrecognisedAuthority)
        }
    }

    pub fn add_known_key(&mut self, key: PublicKey) {
        self.0.insert(key);
    }
}

impl From<Vec<PublicKey>> for KeyCache {
    fn from(keys: Vec<PublicKey>) -> Self {
        Self(keys.into_iter().collect())
    }
}

#[derive(Debug, Clone)]
pub struct ChainNode {
    mint_key: PublicKey,
    prev_mint_sig: Signature,
}

pub struct KeyManager {
    keypair: Keypair,
    genesis: PublicKey,
    chain: Vec<ChainNode>,
    cache: KeyCache,
}

impl KeyManager {
    pub fn new(keypair: Keypair, genesis: PublicKey) -> Self {
        let mut cache = KeyCache::default();
        cache.add_known_key(genesis);
        Self {
            keypair,
            genesis,
            chain: Vec::default(),
            cache,
        }
    }

    pub fn generate(genesis: PublicKey) -> Self {
        Self::new(ed25519_keypair(), genesis)
    }

    pub fn new_genesis() -> Self {
        let keypair = ed25519_keypair();
        let genesis = PublicKey(keypair.public);
        Self::new(keypair, genesis)
    }

    pub fn key_cache(&self) -> &KeyCache {
        &self.cache
    }

    pub fn public_key(&self) -> PublicKey {
        PublicKey(self.keypair.public)
    }

    pub fn sign(&self, msg_hash: &Hash) -> Signature {
        Signature(self.keypair.sign(msg_hash))
    }

    pub fn verify(&self, msg_hash: &Hash, key: &PublicKey, signature: &Signature) -> Result<()> {
        self.cache.verify_known_key(key)?;
        key.ed().verify(msg_hash, &signature.ed())?;
        Ok(())
    }

    pub fn prove_authority(&self) -> &[ChainNode] {
        &self.chain
    }

    pub fn process_chain(&mut self, chain: &[ChainNode]) -> Result<()> {
        let adjacent_pairs = std::iter::once(&self.genesis)
            .chain(chain.iter().map(|n| &n.mint_key))
            .zip(chain.iter());

        for (prev_mint_key, successor_mint) in adjacent_pairs {
            prev_mint_key.ed().verify(
                &successor_mint.mint_key.hash(),
                &successor_mint.prev_mint_sig.ed(),
            )?;
            self.cache.add_known_key(successor_mint.mint_key);
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use quickcheck_macros::quickcheck;

    #[test]
    fn test_empty_chain_processing() {
        let mut genesis_key_mgr = KeyManager::new_genesis();
        assert!(genesis_key_mgr.process_chain(&[]).is_ok());
    }

    #[quickcheck]
    #[ignore]
    fn prop_processing_chain_makes_chain_keys_known() {
        todo!();
    }
}