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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.

// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Parity Ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Parity Ethereum.  If not, see <http://www.gnu.org/licenses/>.

use super::{
    Bytes, Cipher, CipherSer, CipherSerParams, Kdf, KdfSer, KdfSerParams, H256,
};
use serde::{
    de::{Error, MapAccess, Visitor},
    ser::SerializeStruct,
    Deserialize, Deserializer, Serialize, Serializer,
};
use serde_json;
use std::{fmt, str};

pub type CipherText = Bytes;

#[derive(Debug, PartialEq)]
pub struct Crypto {
    pub cipher: Cipher,
    pub ciphertext: CipherText,
    pub kdf: Kdf,
    pub mac: H256,
}

impl str::FromStr for Crypto {
    type Err = serde_json::error::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> { serde_json::from_str(s) }
}

impl From<Crypto> for String {
    fn from(c: Crypto) -> Self {
        serde_json::to_string(&c).expect(
            "Serialization cannot fail, because all crypto keys are strings",
        )
    }
}

enum CryptoField {
    Cipher,
    CipherParams,
    CipherText,
    Kdf,
    KdfParams,
    Mac,
    Version,
}

impl<'a> Deserialize<'a> for CryptoField {
    fn deserialize<D>(deserializer: D) -> Result<CryptoField, D::Error>
    where D: Deserializer<'a> {
        deserializer.deserialize_any(CryptoFieldVisitor)
    }
}

struct CryptoFieldVisitor;

impl<'a> Visitor<'a> for CryptoFieldVisitor {
    type Value = CryptoField;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "a valid crypto struct description")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where E: Error {
        match value {
            "cipher" => Ok(CryptoField::Cipher),
            "cipherparams" => Ok(CryptoField::CipherParams),
            "ciphertext" => Ok(CryptoField::CipherText),
            "kdf" => Ok(CryptoField::Kdf),
            "kdfparams" => Ok(CryptoField::KdfParams),
            "mac" => Ok(CryptoField::Mac),
            "version" => Ok(CryptoField::Version),
            _ => Err(Error::custom(format!("Unknown field: '{}'", value))),
        }
    }
}

impl<'a> Deserialize<'a> for Crypto {
    fn deserialize<D>(deserializer: D) -> Result<Crypto, D::Error>
    where D: Deserializer<'a> {
        static FIELDS: &[&str] =
            &["id", "version", "crypto", "Crypto", "address"];
        deserializer.deserialize_struct("Crypto", FIELDS, CryptoVisitor)
    }
}

struct CryptoVisitor;

impl<'a> Visitor<'a> for CryptoVisitor {
    type Value = Crypto;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "a valid vault crypto object")
    }

    fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
    where V: MapAccess<'a> {
        let mut cipher = None;
        let mut cipherparams = None;
        let mut ciphertext = None;
        let mut kdf = None;
        let mut kdfparams = None;
        let mut mac = None;

        loop {
            match visitor.next_key()? {
                Some(CryptoField::Cipher) => {
                    cipher = Some(visitor.next_value()?);
                }
                Some(CryptoField::CipherParams) => {
                    cipherparams = Some(visitor.next_value()?);
                }
                Some(CryptoField::CipherText) => {
                    ciphertext = Some(visitor.next_value()?);
                }
                Some(CryptoField::Kdf) => {
                    kdf = Some(visitor.next_value()?);
                }
                Some(CryptoField::KdfParams) => {
                    kdfparams = Some(visitor.next_value()?);
                }
                Some(CryptoField::Mac) => {
                    mac = Some(visitor.next_value()?);
                }
                // skip not required version field (it appears in pyethereum
                // generated keystores)
                Some(CryptoField::Version) => {
                    visitor.next_value().unwrap_or(())
                }
                None => {
                    break;
                }
            }
        }

        let cipher = match (cipher, cipherparams) {
            (
                Some(CipherSer::Aes128Ctr),
                Some(CipherSerParams::Aes128Ctr(params)),
            ) => Cipher::Aes128Ctr(params),
            (None, _) => return Err(V::Error::missing_field("cipher")),
            (Some(_), None) => {
                return Err(V::Error::missing_field("cipherparams"))
            }
        };

        let ciphertext = match ciphertext {
            Some(ciphertext) => ciphertext,
            None => return Err(V::Error::missing_field("ciphertext")),
        };

        let kdf = match (kdf, kdfparams) {
            (Some(KdfSer::Pbkdf2), Some(KdfSerParams::Pbkdf2(params))) => {
                Kdf::Pbkdf2(params)
            }
            (Some(KdfSer::Scrypt), Some(KdfSerParams::Scrypt(params))) => {
                Kdf::Scrypt(params)
            }
            (Some(_), Some(_)) => {
                return Err(V::Error::custom("Invalid cipherparams"))
            }
            (None, _) => return Err(V::Error::missing_field("kdf")),
            (Some(_), None) => {
                return Err(V::Error::missing_field("kdfparams"))
            }
        };

        let mac = match mac {
            Some(mac) => mac,
            None => return Err(V::Error::missing_field("mac")),
        };

        let result = Crypto {
            cipher,
            ciphertext,
            kdf,
            mac,
        };

        Ok(result)
    }
}

impl Serialize for Crypto {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where S: Serializer {
        let mut crypto = serializer.serialize_struct("Crypto", 6)?;
        match self.cipher {
            Cipher::Aes128Ctr(ref params) => {
                crypto.serialize_field("cipher", &CipherSer::Aes128Ctr)?;
                crypto.serialize_field("cipherparams", params)?;
            }
        }
        crypto.serialize_field("ciphertext", &self.ciphertext)?;
        match self.kdf {
            Kdf::Pbkdf2(ref params) => {
                crypto.serialize_field("kdf", &KdfSer::Pbkdf2)?;
                crypto.serialize_field("kdfparams", params)?;
            }
            Kdf::Scrypt(ref params) => {
                crypto.serialize_field("kdf", &KdfSer::Scrypt)?;
                crypto.serialize_field("kdfparams", params)?;
            }
        }

        crypto.serialize_field("mac", &self.mac)?;
        crypto.end()
    }
}