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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
use crate::anon_creds::{
ACConfidentialRevealProof, ACIssuerPublicKey, AttributeCiphertext, AttributeDecKey,
AttributeEncKey,
};
use crate::keys::{KeyPair, KeyType, MultiSig, PublicKey};
use crate::xfr::{
asset_mixer::AssetMixProof,
asset_record::AssetRecordType,
asset_tracer::{RecordDataCiphertext, RecordDataDecKey, RecordDataEncKey},
};
use bulletproofs::RangeProof;
use digest::Digest;
use noah_algebra::{
ed25519::{Ed25519Point, Ed25519Scalar},
prelude::*,
ristretto::{
CompressedEdwardsY, CompressedRistretto, PedersenCommitmentRistretto, RistrettoScalar,
},
secp256k1::{SECP256K1Scalar, SECP256K1G1},
traits::PedersenCommitment,
};
use noah_crypto::basic::{
chaum_pedersen::ChaumPedersenProofX,
elgamal::elgamal_key_gen,
hybrid_encryption::{NoahHybridCiphertext, XPublicKey, XSecretKey},
pedersen_elgamal::PedersenElGamalEqProof,
};
use sha2::Sha512;
pub const ASSET_TYPE_LENGTH: usize = 32;
#[derive(
Deserialize, Serialize, Clone, Copy, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord,
)]
pub struct AssetType(pub [u8; ASSET_TYPE_LENGTH]);
impl AssetType {
pub fn from_identical_byte(byte: u8) -> Self {
Self([byte; ASSET_TYPE_LENGTH])
}
pub fn as_scalar<S: Scalar>(&self) -> S {
const MIN_SCALAR_LENGTH: usize = 32;
const ASSET_TYPE_NOAH_REPR_LENGTH: usize = 30;
let mut hash = sha2::Sha256::default();
hash.update(&self.0);
let array = hash.finalize();
let mut noah_repr = [0u8; MIN_SCALAR_LENGTH];
noah_repr[0..ASSET_TYPE_NOAH_REPR_LENGTH]
.copy_from_slice(&array[0..ASSET_TYPE_NOAH_REPR_LENGTH]);
if MIN_SCALAR_LENGTH == S::bytes_len() {
return S::from_bytes(&noah_repr).unwrap(); }
let mut v = vec![0u8; S::bytes_len()];
v[0..ASSET_TYPE_NOAH_REPR_LENGTH].copy_from_slice(&noah_repr);
S::from_bytes(&v).unwrap()
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct XfrNote {
pub body: XfrBody,
pub multisig: MultiSig,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct XfrBody {
pub inputs: Vec<BlindAssetRecord>,
pub outputs: Vec<BlindAssetRecord>,
pub proofs: XfrProofs,
pub asset_tracing_memos: Vec<Vec<TracerMemo>>, pub owners_memos: Vec<Option<OwnerMemo>>, }
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct BlindAssetRecord {
pub amount: XfrAmount,
pub asset_type: XfrAssetType,
pub public_key: PublicKey,
}
impl BlindAssetRecord {
pub fn get_record_type(&self) -> AssetRecordType {
AssetRecordType::from_flags(
matches!(self.amount, XfrAmount::Confidential(_)),
matches!(self.asset_type, XfrAssetType::Confidential(_)),
)
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum XfrAmount {
Confidential((CompressedRistretto, CompressedRistretto)), #[serde(with = "serde_str")]
NonConfidential(u64),
}
impl XfrAmount {
pub fn is_confidential(&self) -> bool {
matches!(self, XfrAmount::Confidential(_))
}
pub fn get_amount(&self) -> Option<u64> {
match self {
XfrAmount::NonConfidential(x) => Some(*x),
_ => None,
}
}
pub fn get_commitments(&self) -> Option<(CompressedRistretto, CompressedRistretto)> {
match self {
XfrAmount::Confidential(x) => Some(*x),
_ => None,
}
}
pub fn from_blinds(
pc_gens: &PedersenCommitmentRistretto,
amount: u64,
blind_lo: &RistrettoScalar,
blind_hi: &RistrettoScalar,
) -> Self {
let (amount_lo, amount_hi) = u64_to_u32_pair(amount);
let comm_lo = pc_gens
.commit(RistrettoScalar::from(amount_lo), *blind_lo)
.compress();
let comm_hi = pc_gens
.commit(RistrettoScalar::from(amount_hi), *blind_hi)
.compress();
XfrAmount::Confidential((comm_lo, comm_hi))
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum XfrAssetType {
Confidential(CompressedRistretto),
NonConfidential(AssetType),
}
impl XfrAssetType {
pub fn is_confidential(&self) -> bool {
matches!(self, XfrAssetType::Confidential(_))
}
pub fn get_asset_type(&self) -> Option<AssetType> {
match self {
XfrAssetType::NonConfidential(x) => Some(*x),
_ => None,
}
}
pub fn get_commitment(&self) -> Option<CompressedRistretto> {
match self {
XfrAssetType::Confidential(x) => Some(*x),
_ => None,
}
}
pub fn from_blind(
pc_gens: &PedersenCommitmentRistretto,
asset_type: &AssetType,
blind: &RistrettoScalar,
) -> Self {
let comm_type = pc_gens.commit(asset_type.as_scalar(), *blind).compress();
XfrAssetType::Confidential(comm_type)
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct AssetTracerEncKeys {
pub record_data_enc_key: RecordDataEncKey,
pub attrs_enc_key: AttributeEncKey,
pub lock_info_enc_key: XPublicKey,
}
#[derive(Deserialize, Eq, PartialEq, Serialize)]
pub struct AssetTracerDecKeys {
pub record_data_dec_key: RecordDataDecKey,
pub attrs_dec_key: AttributeDecKey,
pub lock_info_dec_key: XSecretKey,
}
#[derive(Deserialize, Eq, PartialEq, Serialize)]
pub struct AssetTracerKeyPair {
pub enc_key: AssetTracerEncKeys,
pub dec_key: AssetTracerDecKeys,
}
impl AssetTracerKeyPair {
pub fn generate<R: CryptoRng + RngCore>(prng: &mut R) -> Self {
let (record_data_dec_key, record_data_enc_key) = elgamal_key_gen(prng);
let (attrs_dec_key, attrs_enc_key) = elgamal_key_gen(prng);
let lock_info_dec_key = XSecretKey::new(prng);
let lock_info_enc_key = XPublicKey::from(&lock_info_dec_key);
AssetTracerKeyPair {
enc_key: AssetTracerEncKeys {
record_data_enc_key,
attrs_enc_key,
lock_info_enc_key,
},
dec_key: AssetTracerDecKeys {
record_data_dec_key,
attrs_dec_key,
lock_info_dec_key,
},
}
}
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct TracingPolicies(pub Vec<TracingPolicy>);
impl TracingPolicies {
pub fn new() -> Self {
TracingPolicies(vec![])
}
pub fn from_policy(policy: TracingPolicy) -> Self {
TracingPolicies(vec![policy])
}
pub fn add(&mut self, policy: TracingPolicy) {
self.0.push(policy);
}
pub fn get_policy(&self, index: usize) -> Option<&TracingPolicy> {
self.0.get(index)
}
pub fn get_policies(&self) -> &[TracingPolicy] {
self.0.as_slice()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct TracingPolicy {
pub enc_keys: AssetTracerEncKeys,
pub asset_tracing: bool,
pub identity_tracing: Option<IdentityRevealPolicy>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct IdentityRevealPolicy {
pub cred_issuer_pub_key: ACIssuerPublicKey,
pub reveal_map: Vec<bool>, }
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct TracerMemo {
pub enc_key: AssetTracerEncKeys,
pub lock_amount: Option<(RecordDataCiphertext, RecordDataCiphertext)>,
pub lock_asset_type: Option<RecordDataCiphertext>,
pub lock_attributes: Vec<AttributeCiphertext>,
pub lock_info: NoahHybridCiphertext,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct OwnerMemo {
pub key_type: KeyType,
pub blind_share_bytes: Vec<u8>,
pub lock_bytes: Vec<u8>,
}
impl OwnerMemo {
pub fn from_amount<R: CryptoRng + RngCore>(
prng: &mut R,
amount: u64,
pub_key: &PublicKey,
) -> Result<(Self, (RistrettoScalar, RistrettoScalar))> {
let (key_type, r, blind_share_bytes) = pub_key.random_scalar_with_compressed_point(prng);
let shared_point =
OwnerMemo::derive_shared_point(&key_type, &r, &pub_key.as_compressed_point()?)?;
let amount_blinds = OwnerMemo::calc_amount_blinds(&shared_point);
let lock_bytes = pub_key.hybrid_encrypt(prng, &amount.to_be_bytes())?;
Ok((
OwnerMemo {
key_type,
blind_share_bytes,
lock_bytes,
},
amount_blinds,
))
}
pub fn from_asset_type<R: CryptoRng + RngCore>(
prng: &mut R,
asset_type: &AssetType,
pub_key: &PublicKey,
) -> Result<(Self, RistrettoScalar)> {
let (key_type, r, blind_share_bytes) = pub_key.random_scalar_with_compressed_point(prng);
let shared_point =
OwnerMemo::derive_shared_point(&key_type, &r, &pub_key.as_compressed_point()?)?;
let asset_type_blind = OwnerMemo::calc_asset_type_blind(&shared_point);
let lock_bytes = pub_key.hybrid_encrypt(prng, &asset_type.0)?;
Ok((
OwnerMemo {
key_type,
blind_share_bytes,
lock_bytes,
},
asset_type_blind,
))
}
pub fn from_amount_and_asset_type<R: CryptoRng + RngCore>(
prng: &mut R,
amount: u64,
asset_type: &AssetType,
pub_key: &PublicKey,
) -> Result<(Self, (RistrettoScalar, RistrettoScalar), RistrettoScalar)> {
let (key_type, r, blind_share_bytes) = pub_key.random_scalar_with_compressed_point(prng);
let shared_point =
OwnerMemo::derive_shared_point(&key_type, &r, &pub_key.as_compressed_point()?)?;
let amount_blinds = OwnerMemo::calc_amount_blinds(&shared_point);
let asset_type_blind = OwnerMemo::calc_asset_type_blind(&shared_point);
let mut amount_asset_type_plaintext = vec![];
amount_asset_type_plaintext.extend_from_slice(&amount.to_be_bytes()[..]);
amount_asset_type_plaintext.extend_from_slice(&asset_type.0[..]);
let lock_bytes = pub_key.hybrid_encrypt(prng, &amount_asset_type_plaintext)?;
Ok((
OwnerMemo {
key_type,
blind_share_bytes,
lock_bytes,
},
amount_blinds,
asset_type_blind,
))
}
pub fn decrypt_amount(&self, keypair: &KeyPair) -> Result<u64> {
let decrypted_bytes = self.decrypt(&keypair)?;
if decrypted_bytes.len() != 8 {
return Err(eg!(NoahError::InconsistentStructureError));
}
let mut amt_be_bytes: [u8; 8] = Default::default();
amt_be_bytes.copy_from_slice(&decrypted_bytes[..]);
Ok(u64::from_be_bytes(amt_be_bytes))
}
pub fn decrypt_asset_type(&self, keypair: &KeyPair) -> Result<AssetType> {
let decrypted_bytes = self.decrypt(&keypair)?;
if decrypted_bytes.len() != ASSET_TYPE_LENGTH {
return Err(eg!(NoahError::InconsistentStructureError));
}
let mut asset_type_bytes: [u8; ASSET_TYPE_LENGTH] = Default::default();
asset_type_bytes.copy_from_slice(&decrypted_bytes[..]);
Ok(AssetType(asset_type_bytes))
}
pub fn decrypt_amount_and_asset_type(&self, keypair: &KeyPair) -> Result<(u64, AssetType)> {
let decrypted_bytes = self.decrypt(&keypair)?;
if decrypted_bytes.len() != ASSET_TYPE_LENGTH + 8 {
return Err(eg!(NoahError::InconsistentStructureError));
}
let mut amt_be_bytes: [u8; 8] = Default::default();
amt_be_bytes.copy_from_slice(&decrypted_bytes[..8]);
let mut asset_type_bytes: [u8; ASSET_TYPE_LENGTH] = Default::default();
asset_type_bytes.copy_from_slice(&decrypted_bytes[8..]);
Ok((
u64::from_be_bytes(amt_be_bytes),
AssetType(asset_type_bytes),
))
}
pub fn derive_amount_blinds(
&self,
keypair: &KeyPair,
) -> Result<(RistrettoScalar, RistrettoScalar)> {
let (key_type, s) = keypair.sec_key.as_scalar_bytes()?;
let shared_point = OwnerMemo::derive_shared_point(&key_type, &s, &self.blind_share_bytes)?;
Ok(OwnerMemo::calc_amount_blinds(&shared_point))
}
pub fn derive_asset_type_blind(&self, keypair: &KeyPair) -> Result<RistrettoScalar> {
let (key_type, s) = keypair.sec_key.as_scalar_bytes()?;
let shared_point = OwnerMemo::derive_shared_point(&key_type, &s, &self.blind_share_bytes)?;
Ok(OwnerMemo::calc_asset_type_blind(&shared_point))
}
}
impl OwnerMemo {
fn decrypt(&self, keypair: &KeyPair) -> Result<Vec<u8>> {
keypair.hybrid_decrypt(&self.lock_bytes)
}
fn calc_amount_blinds(shared_point: &[u8]) -> (RistrettoScalar, RistrettoScalar) {
(
OwnerMemo::hash_to_scalar(&shared_point, b"amount_low"),
OwnerMemo::hash_to_scalar(&shared_point, b"amount_high"),
)
}
fn calc_asset_type_blind(shared_point: &[u8]) -> RistrettoScalar {
OwnerMemo::hash_to_scalar(&shared_point, b"asset_type")
}
fn derive_shared_point(key_type: &KeyType, s: &[u8], p: &[u8]) -> Result<Vec<u8>> {
match key_type {
KeyType::Ed25519 => {
let scalar = Ed25519Scalar::from_bytes(s)?;
let point = Ed25519Point::from_compressed_bytes(p)?;
let shared_point = point.mul(&scalar);
Ok(shared_point.to_compressed_bytes())
}
KeyType::Secp256k1 => {
let scalar = SECP256K1Scalar::from_bytes(s)?;
let point = SECP256K1G1::from_compressed_bytes(p)?;
let shared_point = point.mul(&scalar);
Ok(shared_point.to_compressed_bytes())
}
KeyType::EthAddress => Err(eg!("Address not supported")),
}
}
fn hash_to_scalar(point: &[u8], aux: &'static [u8]) -> RistrettoScalar {
let mut hasher = Sha512::new();
hasher.update(point);
hasher.update(aux);
RistrettoScalar::from_hash(hasher)
}
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone)]
pub struct OpenAssetRecord {
pub blind_asset_record: BlindAssetRecord,
#[serde(with = "serde_str")]
pub amount: u64,
pub amount_blinds: (RistrettoScalar, RistrettoScalar), pub asset_type: AssetType,
pub type_blind: RistrettoScalar, }
impl OpenAssetRecord {
pub fn get_record_type(&self) -> AssetRecordType {
self.blind_asset_record.get_record_type()
}
pub fn get_asset_type(&self) -> &AssetType {
&self.asset_type
}
pub fn get_amount(&self) -> &u64 {
&self.amount
}
pub fn get_pub_key(&self) -> &PublicKey {
&self.blind_asset_record.public_key
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AssetRecord {
pub open_asset_record: OpenAssetRecord,
pub tracing_policies: TracingPolicies,
pub identity_proofs: Vec<Option<ACConfidentialRevealProof>>,
pub asset_tracers_memos: Vec<TracerMemo>,
pub owner_memo: Option<OwnerMemo>,
}
#[derive(Deserialize, Serialize)]
pub struct AssetRecordTemplate {
#[serde(with = "serde_str")]
pub amount: u64,
pub asset_type: AssetType,
pub public_key: PublicKey,
pub asset_record_type: AssetRecordType,
pub asset_tracing_policies: TracingPolicies,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum AssetTypeAndAmountProof {
AssetMix(AssetMixProof),
ConfAmount(XfrRangeProof), ConfAsset(Box<ChaumPedersenProofX>),
ConfAll(Box<(XfrRangeProof, ChaumPedersenProofX)>),
NoProof,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct XfrProofs {
pub asset_type_and_amount_proof: AssetTypeAndAmountProof,
pub asset_tracing_proof: AssetTracingProofs,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct XfrRangeProof {
#[serde(with = "noah_obj_serde")]
pub range_proof: RangeProof,
pub xfr_diff_commitment_low: CompressedRistretto,
pub xfr_diff_commitment_high: CompressedRistretto,
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct AssetTracingProofs {
pub asset_type_and_amount_proofs: Vec<PedersenElGamalEqProof>, pub inputs_identity_proofs: Vec<Vec<Option<ACConfidentialRevealProof>>>, pub outputs_identity_proofs: Vec<Vec<Option<ACConfidentialRevealProof>>>, }
impl PartialEq for XfrRangeProof {
fn eq(&self, other: &XfrRangeProof) -> bool {
self.range_proof.to_bytes() == other.range_proof.to_bytes()
&& self.xfr_diff_commitment_low == other.xfr_diff_commitment_low
&& self.xfr_diff_commitment_high == other.xfr_diff_commitment_high
}
}
impl Eq for XfrRangeProof {}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum CompatibleKeyType {
Old,
New(KeyType),
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum CompatibleBlindShare {
Old(CompressedEdwardsY),
New(Vec<u8>),
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum CompatibleLock {
Old(NoahHybridCiphertext),
New(Vec<u8>),
}
use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
impl<'de> Deserialize<'de> for OwnerMemo {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
enum Field {
KeyType,
BlindShare,
BlindShareBytes,
Lock,
LockBytes,
}
impl<'de> Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> std::result::Result<Field, 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("`blind_share` or `lock` or `key_type`")
}
fn visit_str<E>(self, value: &str) -> std::result::Result<Field, E>
where
E: de::Error,
{
match value {
"key_type" => Ok(Field::KeyType),
"blind_share" => Ok(Field::BlindShare),
"blind_share_bytes" => Ok(Field::BlindShareBytes),
"lock" => Ok(Field::Lock),
"lock_bytes" => Ok(Field::LockBytes),
_ => Err(de::Error::unknown_field(value, FIELDS)),
}
}
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
struct OwnerMemoVisitor;
impl<'de> Visitor<'de> for OwnerMemoVisitor {
type Value = OwnerMemo;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("struct OwnerMemo")
}
fn visit_seq<V>(self, mut seq: V) -> std::result::Result<OwnerMemo, V::Error>
where
V: SeqAccess<'de>,
{
let com_key_type = seq
.next_element::<CompatibleKeyType>()?
.ok_or_else(|| de::Error::invalid_length(0, &self))?;
let key_type = match com_key_type {
CompatibleKeyType::Old => KeyType::Ed25519,
CompatibleKeyType::New(k) => k,
};
let com_blind_share = seq
.next_element::<CompatibleBlindShare>()?
.ok_or_else(|| de::Error::invalid_length(1, &self))?;
let blind_share_bytes = match com_blind_share {
CompatibleBlindShare::Old(k) => k.0.to_bytes().to_vec(),
CompatibleBlindShare::New(k) => k,
};
let com_lock = seq
.next_element::<CompatibleLock>()?
.ok_or_else(|| de::Error::invalid_length(2, &self))?;
let lock_bytes = match com_lock {
CompatibleLock::Old(k) => k.noah_to_bytes(),
CompatibleLock::New(k) => k,
};
Ok(OwnerMemo {
key_type,
blind_share_bytes,
lock_bytes,
})
}
fn visit_map<V>(self, mut map: V) -> std::result::Result<OwnerMemo, V::Error>
where
V: MapAccess<'de>,
{
let mut key_type = None;
let mut blind_share_bytes = None;
let mut lock_bytes = None;
while let Some(key) = map.next_key()? {
match key {
Field::KeyType => {
if key_type.is_some() {
return Err(de::Error::duplicate_field("key_type"));
}
key_type = Some(map.next_value()?);
}
Field::BlindShare => {
if blind_share_bytes.is_some() {
return Err(de::Error::duplicate_field("blind_share"));
}
let tmp = map.next_value::<CompressedEdwardsY>()?;
blind_share_bytes = Some(tmp.0.to_bytes().to_vec());
}
Field::BlindShareBytes => {
if blind_share_bytes.is_some() {
return Err(de::Error::duplicate_field("blind_share"));
}
blind_share_bytes = Some(map.next_value()?);
}
Field::Lock => {
if lock_bytes.is_some() {
return Err(de::Error::duplicate_field("lock"));
}
let tmp = map.next_value::<NoahHybridCiphertext>()?;
lock_bytes = Some(tmp.noah_to_bytes());
}
Field::LockBytes => {
if lock_bytes.is_some() {
return Err(de::Error::duplicate_field("lock"));
}
lock_bytes = Some(map.next_value()?);
}
}
}
let key_type = key_type.unwrap_or(KeyType::Ed25519);
let blind_share_bytes =
blind_share_bytes.ok_or_else(|| de::Error::missing_field("blind_share"))?;
let lock_bytes = lock_bytes.ok_or_else(|| de::Error::missing_field("lock"))?;
Ok(OwnerMemo {
key_type,
blind_share_bytes,
lock_bytes,
})
}
}
const FIELDS: &'static [&'static str] = &[
"key_type",
"blind_share",
"blind_share_bytes",
"lock",
"lock_bytes",
];
deserializer.deserialize_struct("OwnerMemo", FIELDS, OwnerMemoVisitor)
}
}