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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
use crate::mir::constant::Constant;
use crate::serialization::sigma_byte_reader::SigmaByteRead;
use crate::serialization::sigma_byte_writer::SigmaByteWrite;
use crate::serialization::SigmaParsingError;
use crate::serialization::SigmaSerializable;
use crate::serialization::SigmaSerializationError;
use crate::serialization::SigmaSerializeResult;
use derive_more::From;
use ergo_chain_types::Base16EncodedBytes;
use std::convert::TryInto;
use std::{collections::HashMap, convert::TryFrom};
use thiserror::Error;
#[derive(PartialEq, Eq, Debug, Clone, Copy, From)]
pub enum RegisterId {
MandatoryRegisterId(MandatoryRegisterId),
NonMandatoryRegisterId(NonMandatoryRegisterId),
}
impl RegisterId {
pub const R0: RegisterId = RegisterId::MandatoryRegisterId(MandatoryRegisterId::R0);
pub const R1: RegisterId = RegisterId::MandatoryRegisterId(MandatoryRegisterId::R1);
pub const R2: RegisterId = RegisterId::MandatoryRegisterId(MandatoryRegisterId::R2);
pub const R3: RegisterId = RegisterId::MandatoryRegisterId(MandatoryRegisterId::R3);
}
#[derive(Error, PartialEq, Eq, Debug, Clone)]
#[error("register id {0} is out of bounds (0 - 9)")]
pub struct RegisterIdOutOfBounds(pub i8);
impl TryFrom<i8> for RegisterId {
type Error = RegisterIdOutOfBounds;
fn try_from(value: i8) -> Result<Self, Self::Error> {
if value < 0 {
return Err(RegisterIdOutOfBounds(value));
}
let v = value as usize;
if v < NonMandatoryRegisterId::START_INDEX {
Ok(RegisterId::MandatoryRegisterId(value.try_into()?))
} else if v <= NonMandatoryRegisterId::END_INDEX {
Ok(RegisterId::NonMandatoryRegisterId(value.try_into()?))
} else {
Err(RegisterIdOutOfBounds(value))
}
}
}
impl TryFrom<u8> for RegisterId {
type Error = RegisterIdOutOfBounds;
fn try_from(value: u8) -> Result<Self, Self::Error> {
RegisterId::try_from(value as i8)
}
}
#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
#[cfg_attr(feature = "json", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "json", serde(into = "String", try_from = "String"))]
#[repr(u8)]
pub enum NonMandatoryRegisterId {
R4 = 4,
R5 = 5,
R6 = 6,
R7 = 7,
R8 = 8,
R9 = 9,
}
impl NonMandatoryRegisterId {
pub const START_INDEX: usize = 4;
pub const END_INDEX: usize = 9;
pub const NUM_REGS: usize = 6;
pub const REG_IDS: [NonMandatoryRegisterId; NonMandatoryRegisterId::NUM_REGS] = [
NonMandatoryRegisterId::R4,
NonMandatoryRegisterId::R5,
NonMandatoryRegisterId::R6,
NonMandatoryRegisterId::R7,
NonMandatoryRegisterId::R8,
NonMandatoryRegisterId::R9,
];
pub fn get_by_zero_index(i: usize) -> NonMandatoryRegisterId {
assert!(i < NonMandatoryRegisterId::NUM_REGS);
NonMandatoryRegisterId::REG_IDS[i]
}
}
impl From<NonMandatoryRegisterId> for String {
fn from(v: NonMandatoryRegisterId) -> Self {
format!("R{}", v as u8)
}
}
impl TryFrom<String> for NonMandatoryRegisterId {
type Error = NonMandatoryRegisterIdParsingError;
fn try_from(str: String) -> Result<Self, Self::Error> {
if str.len() == 2 && &str[..1] == "R" {
let index = str[1..2]
.parse::<usize>()
.map_err(|_| NonMandatoryRegisterIdParsingError())?;
if (NonMandatoryRegisterId::START_INDEX..=NonMandatoryRegisterId::END_INDEX)
.contains(&index)
{
Ok(NonMandatoryRegisterId::get_by_zero_index(
index - NonMandatoryRegisterId::START_INDEX,
))
} else {
Err(NonMandatoryRegisterIdParsingError())
}
} else {
Err(NonMandatoryRegisterIdParsingError())
}
}
}
impl TryFrom<i8> for NonMandatoryRegisterId {
type Error = RegisterIdOutOfBounds;
fn try_from(value: i8) -> Result<Self, Self::Error> {
let v_usize = value as usize;
if (NonMandatoryRegisterId::START_INDEX..=NonMandatoryRegisterId::END_INDEX)
.contains(&v_usize)
{
Ok(NonMandatoryRegisterId::get_by_zero_index(
v_usize - NonMandatoryRegisterId::START_INDEX,
))
} else {
Err(RegisterIdOutOfBounds(value))
}
}
}
#[derive(Error, PartialEq, Eq, Debug, Clone)]
#[error("failed to parse register id")]
pub struct NonMandatoryRegisterIdParsingError();
#[derive(PartialEq, Eq, Debug, Clone)]
#[cfg_attr(feature = "json", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "json",
serde(
into = "HashMap<NonMandatoryRegisterId, ergo_chain_types::Base16EncodedBytes>",
try_from = "HashMap<NonMandatoryRegisterId, crate::chain::json::ergo_box::ConstantHolder>"
)
)]
pub struct NonMandatoryRegisters(Vec<RegisterValue>);
impl NonMandatoryRegisters {
pub const MAX_SIZE: usize = NonMandatoryRegisterId::NUM_REGS;
pub fn empty() -> NonMandatoryRegisters {
NonMandatoryRegisters(vec![])
}
pub fn new(
regs: HashMap<NonMandatoryRegisterId, Constant>,
) -> Result<NonMandatoryRegisters, NonMandatoryRegistersError> {
NonMandatoryRegisters::try_from(
regs.into_iter()
.map(|(k, v)| (k, v.into()))
.collect::<HashMap<NonMandatoryRegisterId, RegisterValue>>(),
)
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn get(&self, reg_id: NonMandatoryRegisterId) -> Option<&RegisterValue> {
self.0.get(reg_id as usize)
}
pub fn get_constant(&self, reg_id: NonMandatoryRegisterId) -> Option<&Constant> {
self.0
.get(reg_id as usize - NonMandatoryRegisterId::START_INDEX)
.and_then(|rv| rv.as_option_constant())
}
}
#[derive(PartialEq, Eq, Debug, Clone, From)]
pub enum RegisterValue {
Parsed(Constant),
Unparseable(Vec<u8>),
}
impl RegisterValue {
pub fn as_option_constant(&self) -> Option<&Constant> {
match self {
RegisterValue::Parsed(c) => Some(c),
RegisterValue::Unparseable(_) => None,
}
}
#[allow(clippy::unwrap_used)] fn sigma_serialize_bytes(&self) -> Vec<u8> {
match self {
RegisterValue::Parsed(c) => c.sigma_serialize_bytes().unwrap(),
RegisterValue::Unparseable(bytes) => bytes.clone(),
}
}
}
impl TryFrom<Vec<RegisterValue>> for NonMandatoryRegisters {
type Error = NonMandatoryRegistersError;
fn try_from(values: Vec<RegisterValue>) -> Result<Self, Self::Error> {
if values.len() > NonMandatoryRegisters::MAX_SIZE {
Err(NonMandatoryRegistersError::InvalidSize(values.len()))
} else {
Ok(NonMandatoryRegisters(values))
}
}
}
impl TryFrom<Vec<Constant>> for NonMandatoryRegisters {
type Error = NonMandatoryRegistersError;
fn try_from(values: Vec<Constant>) -> Result<Self, Self::Error> {
NonMandatoryRegisters::try_from(
values
.into_iter()
.map(RegisterValue::Parsed)
.collect::<Vec<RegisterValue>>(),
)
}
}
impl SigmaSerializable for NonMandatoryRegisters {
fn sigma_serialize<W: SigmaByteWrite>(&self, w: &mut W) -> SigmaSerializeResult {
let regs_num = self.len();
w.put_u8(regs_num as u8)?;
for reg_value in self.0.iter() {
match reg_value {
RegisterValue::Parsed(c) => c.sigma_serialize(w)?,
RegisterValue::Unparseable(_) => {
return Err(SigmaSerializationError::NotSupported(
"unparseable register value cannot be serialized, because it cannot be parsed later"
))
}
};
}
Ok(())
}
fn sigma_parse<R: SigmaByteRead>(r: &mut R) -> Result<Self, SigmaParsingError> {
let regs_num = r.get_u8()?;
let mut additional_regs = Vec::with_capacity(regs_num as usize);
for _ in 0..regs_num {
let v = Constant::sigma_parse(r)?;
additional_regs.push(v);
}
Ok(additional_regs.try_into()?)
}
}
#[derive(Error, PartialEq, Eq, Clone, Debug)]
pub enum NonMandatoryRegistersError {
#[error("invalid non-mandatory registers size ({0})")]
InvalidSize(usize),
#[error("registers are not densely packed (register R{0} is missing)")]
NonDenselyPacked(u8),
}
impl From<NonMandatoryRegisters>
for HashMap<NonMandatoryRegisterId, ergo_chain_types::Base16EncodedBytes>
{
fn from(v: NonMandatoryRegisters) -> Self {
v.0.into_iter()
.enumerate()
.map(|(i, reg_value)| {
(
NonMandatoryRegisterId::get_by_zero_index(i),
#[allow(clippy::unwrap_used)]
Base16EncodedBytes::new(®_value.sigma_serialize_bytes()),
)
})
.collect()
}
}
impl From<NonMandatoryRegisters> for HashMap<NonMandatoryRegisterId, RegisterValue> {
fn from(v: NonMandatoryRegisters) -> Self {
v.0.into_iter()
.enumerate()
.map(|(i, reg_val)| (NonMandatoryRegisterId::get_by_zero_index(i), reg_val))
.collect()
}
}
impl TryFrom<HashMap<NonMandatoryRegisterId, RegisterValue>> for NonMandatoryRegisters {
type Error = NonMandatoryRegistersError;
fn try_from(
reg_map: HashMap<NonMandatoryRegisterId, RegisterValue>,
) -> Result<Self, Self::Error> {
let regs_num = reg_map.len();
if regs_num > NonMandatoryRegisters::MAX_SIZE {
Err(NonMandatoryRegistersError::InvalidSize(regs_num))
} else {
let mut res: Vec<RegisterValue> = vec![];
NonMandatoryRegisterId::REG_IDS
.iter()
.take(regs_num)
.try_for_each(|reg_id| match reg_map.get(reg_id) {
Some(v) => Ok(res.push(v.clone())),
None => Err(NonMandatoryRegistersError::NonDenselyPacked(*reg_id as u8)),
})?;
Ok(NonMandatoryRegisters(res))
}
}
}
#[cfg(feature = "json")]
impl TryFrom<HashMap<NonMandatoryRegisterId, crate::chain::json::ergo_box::ConstantHolder>>
for NonMandatoryRegisters
{
type Error = NonMandatoryRegistersError;
fn try_from(
value: HashMap<NonMandatoryRegisterId, crate::chain::json::ergo_box::ConstantHolder>,
) -> Result<Self, Self::Error> {
let cm: HashMap<NonMandatoryRegisterId, RegisterValue> =
value.into_iter().map(|(k, v)| (k, v.into())).collect();
NonMandatoryRegisters::try_from(cm)
}
}
impl From<NonMandatoryRegistersError> for SigmaParsingError {
fn from(error: NonMandatoryRegistersError) -> Self {
SigmaParsingError::Misc(error.to_string())
}
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum MandatoryRegisterId {
R0 = 0,
R1 = 1,
R2 = 2,
R3 = 3,
}
impl TryFrom<i8> for MandatoryRegisterId {
type Error = RegisterIdOutOfBounds;
fn try_from(value: i8) -> Result<Self, Self::Error> {
match value {
v if v == MandatoryRegisterId::R0 as i8 => Ok(MandatoryRegisterId::R0),
v if v == MandatoryRegisterId::R1 as i8 => Ok(MandatoryRegisterId::R1),
v if v == MandatoryRegisterId::R2 as i8 => Ok(MandatoryRegisterId::R2),
v if v == MandatoryRegisterId::R3 as i8 => Ok(MandatoryRegisterId::R3),
_ => Err(RegisterIdOutOfBounds(value)),
}
}
}
#[allow(clippy::unwrap_used)]
#[cfg(feature = "arbitrary")]
pub(crate) mod arbitrary {
use super::*;
use proptest::{arbitrary::Arbitrary, collection::vec, prelude::*};
#[derive(Default)]
pub struct ArbNonMandatoryRegistersParams {
pub allow_unparseable: bool,
}
impl Arbitrary for NonMandatoryRegisters {
type Parameters = ArbNonMandatoryRegistersParams;
type Strategy = BoxedStrategy<Self>;
fn arbitrary_with(params: Self::Parameters) -> Self::Strategy {
vec(
if params.allow_unparseable {
prop_oneof![
any::<Constant>().prop_map(RegisterValue::Parsed),
vec(any::<u8>(), 0..100).prop_map(RegisterValue::Unparseable)
]
.boxed()
} else {
any::<Constant>().prop_map(RegisterValue::Parsed).boxed()
},
0..=NonMandatoryRegisterId::NUM_REGS,
)
.prop_map(|reg_values| NonMandatoryRegisters::try_from(reg_values).unwrap())
.boxed()
}
}
}
#[allow(clippy::panic)]
#[allow(clippy::unwrap_used)]
#[allow(clippy::expect_used)]
#[cfg(test)]
mod tests {
use super::*;
use crate::serialization::sigma_serialize_roundtrip;
use proptest::prelude::*;
proptest! {
#[test]
fn hash_map_roundtrip(regs in any::<NonMandatoryRegisters>()) {
let hash_map: HashMap<NonMandatoryRegisterId, RegisterValue> = regs.clone().into();
let regs_from_map = NonMandatoryRegisters::try_from(hash_map);
prop_assert![regs_from_map.is_ok()];
prop_assert_eq![regs_from_map.unwrap(), regs];
}
#[test]
fn get(regs in any::<NonMandatoryRegisters>()) {
let hash_map: HashMap<NonMandatoryRegisterId, RegisterValue> = regs.clone().into();
hash_map.keys().try_for_each(|reg_id| {
prop_assert_eq![regs.get_constant(*reg_id), hash_map.get(reg_id).unwrap().as_option_constant()];
Ok(())
})?;
}
#[test]
fn reg_id_from_byte(reg_id_byte in 0i8..NonMandatoryRegisterId::END_INDEX as i8) {
assert!(RegisterId::try_from(reg_id_byte).is_ok());
}
#[test]
fn ser_roundtrip(regs in any::<NonMandatoryRegisters>()) {
prop_assert_eq![sigma_serialize_roundtrip(®s), regs];
}
}
#[test]
fn test_empty() {
assert!(NonMandatoryRegisters::empty().is_empty());
}
#[test]
fn test_non_densely_packed_error() {
let mut hash_map: HashMap<NonMandatoryRegisterId, RegisterValue> = HashMap::new();
let c: Constant = 1i32.into();
hash_map.insert(NonMandatoryRegisterId::R4, c.clone().into());
hash_map.insert(NonMandatoryRegisterId::R6, c.into());
assert!(NonMandatoryRegisters::try_from(hash_map).is_err());
}
}