-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock.rs
More file actions
383 lines (348 loc) · 11.5 KB
/
block.rs
File metadata and controls
383 lines (348 loc) · 11.5 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
//! Contains [Block], [Ownership] and implementations
use crate::PROTO_VERSION;
use crate::{error::Error, Hash, Result, DEFAULT_GENESIS};
use openssl::pkey::{PKey, Private, Public};
use openssl::sha::Sha256;
use serde::de::{self, Visitor};
use serde::{ser::SerializeStruct, Deserialize, Deserializer, Serialize}; // TODO: #[cfg(feature = "serde")]
/// Single block within a larger blockchain, providing access to a block of data
///
/// # Using
///
/// You can, in high level terms, do the following directly to a block:
///
/// - Create a genesis block: [Block::default]
/// - Create a block containing data: [Block::new]
/// - Verify a block: [Block::verify]
///
/// # Example
///
/// ```rust
/// use onft::prelude::*;
///
/// fn main() -> onft::Result<()> {
/// let genesis_block = Block::default();
///
/// let data = "Hello, world!";
/// let new_block = Block::new(&genesis_block, data)?;
/// let verified = new_block.verify(&genesis_block)?;
///
/// if verified {
/// println!("Verified")
/// } else {
/// eprintln!("Not verified")
/// }
/// Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Block {
/// The hash of this block.
pub hash: Hash,
/// Ownership identifier, represents if we own it or not.
pub ownership: Ownership,
/// Signature which wraps data into a key to verify ownership.
pub signature: [u8; Hash::SIG_LEN],
/// Underlying data contained for this block.
pub data: BlockData,
}
impl<'a> Block {
/// Creates a new block from the previous block in a chain alongside the data
/// contained within this block.
///
/// # Example
///
/// ```rust
/// use onft::prelude::*;
///
/// fn main() -> onft::Result<()> {
/// let genesis_block = Block::default();
///
/// let data = "Hello, world!";
/// let block = Block::new(&genesis_block, data)?;
///
/// println!("Block:\n{:?}", block);
/// Ok(())
/// }
/// ```
pub fn new(previous_hash: impl Into<&'a Hash>, data: impl Into<Vec<u8>>) -> Result<Self> {
let data = BlockData::new(data.into())?;
let (hash, signature, pkey) = Hash::new(previous_hash, data.hash)?;
Ok(Self {
hash,
ownership: pkey.into(),
signature,
data,
})
}
/// Verifies this individual block based upon the known hash of the last block.
///
/// # Example
///
/// ```rust
/// use onft::prelude::*;
///
/// fn main() -> onft::Result<()> {
/// let genesis_block = Block::default();
///
/// let data = "Hello, world!";
/// let new_block = Block::new(&genesis_block, data)?;
/// let verified = new_block.verify(&genesis_block)?;
///
/// if verified {
/// println!("Verified")
/// } else {
/// eprintln!("Not verified")
/// }
/// Ok(())
/// }
/// ```
pub fn verify(&self, previous_hash: impl Into<&'a Hash>) -> Result<bool> {
let previous_hash = previous_hash.into();
let data_hash = self.data.hash;
match &self.ownership {
Ownership::Them(pkey) => {
self.hash
.verify(previous_hash, self.signature, data_hash, pkey)
}
Ownership::Us(pkey) => self
.hash
.verify(previous_hash, self.signature, data_hash, pkey),
Ownership::Genesis => Err(Error::GenesisIsNotKey),
}
}
}
impl Default for Block {
/// Creates default genesis block.
fn default() -> Self {
Self {
hash: Hash::default(),
ownership: Ownership::Genesis,
signature: [0; Hash::SIG_LEN],
data: BlockData::default(),
}
}
}
impl Serialize for Block {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut state = serializer.serialize_struct("Block", 4 + 1)?;
state.serialize_field("pver", &PROTO_VERSION)?; // custom protocol version
state.serialize_field("hash", &self.hash)?;
state.serialize_field("ownership", &self.ownership)?;
state.serialize_field("signature", &self.signature)?; // TODO: serde-big-array <https://github.com/est31/serde-big-array>
state.serialize_field("block_data", &self.data)?;
state.end()
}
}
// NOTE: see docs <https://serde.rs/deserialize-struct.html> for info
// TODO: #[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Block {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
enum Field {
ProtoVersion,
Hash,
Ownership,
Signature,
BlockData,
}
impl Field {
fn expected() -> &'static str {
"`pver` or `hash` or `ownership` or `block_data`"
}
}
impl<'de> Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str(Field::expected())
}
fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
where
E: de::Error,
{
match v {
"pver" => Ok(Field::ProtoVersion),
"hash" => Ok(Field::Hash),
"ownership" => Ok(Field::Ownership),
"signature" => Ok(Field::Signature),
"data" => Ok(Field::BlockData),
_ => Err(de::Error::unknown_field(v, FIELDS)),
}
}
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
struct BlockVisitor;
impl<'de> Visitor<'de> for BlockVisitor {
type Value = Block;
fn expecting(&self, _formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
todo!("block deserialization")
}
fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error>
where
A: de::SeqAccess<'de>,
{
// proto version check
let proto_version: u8 = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(0, &self))?;
if proto_version != PROTO_VERSION {
todo!("proto version error")
}
// bulk
let hash = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(1, &self))?;
let ownership = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(2, &self))?;
let signature = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(3, &self))?; // TODO: serde-big-array <https://github.com/est31/serde-big-array>
let data = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(4, &self))?;
Ok(Block {
hash,
ownership,
signature,
data,
})
}
}
const FIELDS: &[&str] = &["pver", "ownership", "signature", "data"];
deserializer.deserialize_struct("Block", FIELDS, BlockVisitor)
}
}
/// Data contained within a block along with it's hash to be used downstream
///
/// # Example
///
/// TODO: example
#[derive(Serialize, Deserialize)]
// #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockData {
/// Actual data in a byte vector.
pub inner: Vec<u8>,
/// Computed hash of data to use for constructing/verifying block hashes.
pub hash: [u8; 32],
}
impl BlockData {
/// Creates new instance from data, hashing automatically.
pub fn new(data: impl Into<Vec<u8>>) -> Result<Self> {
let mut hasher = Sha256::new();
let data = data.into();
hasher.update(data.as_slice());
Ok(Self {
inner: data,
hash: hasher.finish(),
})
}
}
impl Default for BlockData {
fn default() -> Self {
Self {
inner: vec![],
hash: DEFAULT_GENESIS,
}
}
}
impl From<BlockData> for Vec<u8> {
fn from(block_data: BlockData) -> Self {
block_data.inner
}
}
impl<'a> From<&'a BlockData> for &'a [u8] {
fn from(block_data: &'a BlockData) -> Self {
&block_data.inner[..]
}
}
impl From<BlockData> for [u8; 32] {
fn from(block_data: BlockData) -> Self {
block_data.hash
}
}
impl From<&BlockData> for [u8; 32] {
fn from(block_data: &BlockData) -> Self {
block_data.hash
}
}
// TODO: try_into
/// Contains ownership keys and information for a given block
#[derive(Deserialize, Debug, Clone)]
pub enum Ownership {
/// Special genesis ownership type as the genesis block is owned by nobody.
Genesis,
/// Owned by an external source as we have a general public key.
// TODO: #[cfg_attr(feature = "serde", serde(deserialize_with = "Ownership::from_public_raw"))]
#[serde(deserialize_with = "de_pkey_pub")]
Them(PKey<Public>),
/// Owned by us as we have a private key.
// TODO: #[cfg_attr(feature = "serde", serde(skip_deserializing))]
#[serde(skip_deserializing)]
Us(PKey<Private>),
}
impl Ownership {
/// Converts ownership to a public key, used primarily for serialization if enabled.
pub fn to_raw_public(&self) -> Result<Vec<u8>> {
match self {
Self::Genesis => Err(Error::GenesisIsNotKey),
Self::Them(pkey) => pkey.raw_public_key().map_err(Error::KeyPublic),
Self::Us(pkey) => pkey.raw_public_key().map_err(Error::KeyPublic),
}
}
}
impl From<PKey<Public>> for Ownership {
fn from(pkey: PKey<Public>) -> Self {
Self::Them(pkey)
}
}
impl From<PKey<Private>> for Ownership {
fn from(pkey: PKey<Private>) -> Self {
Self::Us(pkey)
}
}
// #[cfg(feature = "serde")]
impl Serialize for Ownership {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
const NAME: &str = "Ownership";
match self {
Ownership::Genesis => serializer.serialize_unit_variant(NAME, 0, "Genesis"),
_ => serializer.serialize_newtype_variant(
NAME,
1,
"Them",
&self
.to_raw_public()
.map_err(|err| serde::ser::Error::custom(&format!("{}", err)))?[..],
),
}
}
}
// TODO: finish
/// Produces serde-orientated data into a new pkey instance
// TODO: #[cfg(feature = "serde")]
fn de_pkey_pub<'de, D>(_data: D) -> std::result::Result<PKey<Public>, D::Error>
where
D: Deserializer<'de>,
{
// let pkey = PKey::public_key_from_raw_bytes(bytes.as_ref(), Id::ED25519)
// .map_err(Error::KeyPublic)?;
todo!()
}