forked from ElementsProject/rust-elements
-
Notifications
You must be signed in to change notification settings - Fork 0
/
confidential.rs
1446 lines (1282 loc) · 45.3 KB
/
confidential.rs
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Rust Elements Library
// Written in 2018 by
// Andrew Poelstra <apoelstra@blockstream.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//
//! # Confidential Commitments
//!
//! Structures representing Pedersen commitments of various types
//!
use crate::hashes::{sha256d, Hash, hex};
use secp256k1_zkp::{self, CommitmentSecrets, Generator, PedersenCommitment,
PublicKey, Secp256k1, SecretKey, Signing, Tweak, ZERO_TWEAK,
compute_adaptive_blinding_factor,
rand::{CryptoRng, Rng, RngCore}
};
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::{fmt, io, ops::{AddAssign, Neg}, str};
use crate::encode::{self, Decodable, Encodable};
use crate::issuance::AssetId;
/// A CT commitment to an amount
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Value {
/// No value
Null,
/// Value is explicitly encoded
Explicit(u64),
/// Value is committed
Confidential(PedersenCommitment),
}
impl Value {
/// Create value commitment.
pub fn new_confidential<C: Signing>(
secp: &Secp256k1<C>,
value: u64,
asset: Generator,
bf: ValueBlindingFactor,
) -> Self {
Value::Confidential(PedersenCommitment::new(secp, value, bf.0, asset))
}
/// Create value commitment from assetID, asset blinding factor,
/// value and value blinding factor
pub fn new_confidential_from_assetid<C: Signing>(
secp: &Secp256k1<C>,
value: u64,
asset: AssetId,
v_bf: ValueBlindingFactor,
a_bf: AssetBlindingFactor,
) -> Self {
let generator = Generator::new_blinded(secp, asset.into_tag(), a_bf.0);
let comm = PedersenCommitment::new(secp, value, v_bf.0, generator);
Value::Confidential(comm)
}
/// Serialized length, in bytes
pub fn encoded_length(&self) -> usize {
match *self {
Value::Null => 1,
Value::Explicit(..) => 9,
Value::Confidential(..) => 33,
}
}
/// Create from commitment.
pub fn from_commitment(bytes: &[u8]) -> Result<Self, encode::Error> {
Ok(Value::Confidential(PedersenCommitment::from_slice(bytes)?))
}
/// Check if the object is null.
pub fn is_null(&self) -> bool {
match self {
Value::Null => true,
_ => false
}
}
/// Check if the object is explicit.
pub fn is_explicit(&self) -> bool {
match self {
Value::Explicit(_) => true,
_ => false
}
}
/// Check if the object is confidential.
pub fn is_confidential(&self) -> bool {
match self {
Value::Confidential(_) => true,
_ => false
}
}
/// Returns the explicit inner value.
/// Returns [None] if [is_explicit] returns false.
pub fn explicit(&self) -> Option<u64> {
match *self {
Value::Explicit(i) => Some(i),
_ => None,
}
}
/// Returns the confidential commitment in case of a confidential value.
/// Returns [None] if [is_confidential] returns false.
pub fn commitment(&self) -> Option<PedersenCommitment> {
match *self {
Value::Confidential(i) => Some(i),
_ => None,
}
}
}
impl From<PedersenCommitment> for Value {
fn from(from: PedersenCommitment) -> Self {
Value::Confidential(from)
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Value::Null => f.write_str("null"),
Value::Explicit(n) => write!(f, "{}", n),
Value::Confidential(commitment) => write!(f, "{:02x}", commitment),
}
}
}
impl Default for Value {
fn default() -> Self {
Value::Null
}
}
impl Encodable for Value {
fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {
match *self {
Value::Null => 0u8.consensus_encode(s),
Value::Explicit(n) => {
1u8.consensus_encode(&mut s)?;
Ok(1 + u64::swap_bytes(n).consensus_encode(&mut s)?)
}
Value::Confidential(commitment) => commitment.consensus_encode(&mut s),
}
}
}
impl Encodable for PedersenCommitment {
fn consensus_encode<W: io::Write>(&self, mut e: W) -> Result<usize, encode::Error> {
e.write_all(&self.serialize())?;
Ok(33)
}
}
impl Decodable for Value {
fn consensus_decode<D: io::Read>(mut d: D) -> Result<Value, encode::Error> {
let prefix = u8::consensus_decode(&mut d)?;
match prefix {
0 => Ok(Value::Null),
1 => {
let explicit = u64::swap_bytes(Decodable::consensus_decode(&mut d)?);
Ok(Value::Explicit(explicit))
}
p if p == 0x08 || p == 0x09 => {
let mut comm = [0u8; 33];
comm[0] = p;
d.read_exact(&mut comm[1..])?;
Ok(Value::Confidential(PedersenCommitment::from_slice(&comm)?))
}
p => Err(encode::Error::InvalidConfidentialPrefix(p)),
}
}
}
impl Decodable for PedersenCommitment {
fn consensus_decode<D: io::Read>(d: D) -> Result<Self, encode::Error> {
let bytes = <[u8; 33]>::consensus_decode(d)?;
Ok(PedersenCommitment::from_slice(&bytes)?)
}
}
#[cfg(feature = "serde")]
impl Serialize for Value {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeSeq;
let seq_len = match *self {
Value::Null => 1,
Value::Explicit(_) | Value::Confidential(_) => 2
};
let mut seq = s.serialize_seq(Some(seq_len))?;
match *self {
Value::Null => seq.serialize_element(&0u8)?,
Value::Explicit(n) => {
seq.serialize_element(&1u8)?;
seq.serialize_element(&u64::swap_bytes(n))?;
}
Value::Confidential(commitment) => {
seq.serialize_element(&2u8)?;
seq.serialize_element(&commitment)?;
}
}
seq.end()
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Value {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
use serde::de::{Error, SeqAccess, Visitor};
struct CommitVisitor;
impl<'de> Visitor<'de> for CommitVisitor {
type Value = Value;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a committed value")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {
let prefix = access.next_element::<u8>()?;
match prefix {
Some(0) => Ok(Value::Null),
Some(1) => {
match access.next_element()? {
Some(x) => Ok(Value::Explicit(u64::swap_bytes(x))),
None => Err(A::Error::custom("missing explicit value")),
}
}
Some(2) => {
match access.next_element()? {
Some(x) => Ok(Value::Confidential(x)),
None => Err(A::Error::custom("missing pedersen commitment")),
}
}
_ => Err(A::Error::custom("wrong or missing prefix")),
}
}
}
d.deserialize_seq(CommitVisitor)
}
}
/// A CT commitment to an asset
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Asset {
/// No value
Null,
/// Asset entropy is explicitly encoded
Explicit(AssetId),
/// Asset is committed
Confidential(Generator),
}
impl Asset {
/// Create asset commitment.
pub fn new_confidential<C: Signing>(
secp: &Secp256k1<C>,
asset: AssetId,
bf: AssetBlindingFactor,
) -> Self {
Asset::Confidential(Generator::new_blinded(
secp,
asset.into_tag(),
bf.into_inner(),
))
}
/// Serialized length, in bytes
pub fn encoded_length(&self) -> usize {
match *self {
Asset::Null => 1,
Asset::Explicit(..) => 33,
Asset::Confidential(..) => 33,
}
}
/// Create from commitment.
pub fn from_commitment(bytes: &[u8]) -> Result<Self, encode::Error> {
Ok(Asset::Confidential(Generator::from_slice(bytes)?))
}
/// Check if the object is null.
pub fn is_null(&self) -> bool {
match *self {
Asset::Null => true,
_ => false
}
}
/// Check if the object is explicit.
pub fn is_explicit(&self) -> bool {
match *self {
Asset::Explicit(_) => true,
_ => false
}
}
/// Check if the object is confidential.
pub fn is_confidential(&self) -> bool {
match *self {
Asset::Confidential(_) => true,
_ => false
}
}
/// Returns the explicit inner value.
/// Returns [None] if [is_explicit] returns false.
pub fn explicit(&self) -> Option<AssetId> {
match *self {
Asset::Explicit(i) => Some(i),
_ => None,
}
}
/// Returns the confidential commitment in case of a confidential value.
/// Returns [None] if [is_confidential] returns false.
pub fn commitment(&self) -> Option<Generator> {
match *self {
Asset::Confidential(i) => Some(i),
_ => None,
}
}
/// Internally used function for getting the generator from asset
/// Used in the amount verification check
/// Returns [`None`] is the asset is [`Asset::Null`]
/// Converts a explicit asset into a generator and returns the confidential
/// generator as is.
pub fn into_asset_gen<C: secp256k1_zkp::Signing> (
self,
secp: &Secp256k1<C>,
) -> Option<Generator> {
match self {
// Only error is Null error which is dealt with later
// when we have more context information about it.
Asset::Null => return None,
Asset::Explicit(x) => {
Some(Generator::new_unblinded(secp, x.into_tag()))
}
Asset::Confidential(gen) => Some(gen),
}
}
}
impl From<Generator> for Asset {
fn from(from: Generator) -> Self {
Asset::Confidential(from)
}
}
impl fmt::Display for Asset {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Asset::Null => f.write_str("null"),
Asset::Explicit(n) => write!(f, "{}", n),
Asset::Confidential(generator) => write!(f, "{:02x}", generator),
}
}
}
impl Default for Asset {
fn default() -> Self {
Asset::Null
}
}
impl Encodable for Asset {
fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {
match *self {
Asset::Null => 0u8.consensus_encode(s),
Asset::Explicit(n) => {
1u8.consensus_encode(&mut s)?;
Ok(1 + n.consensus_encode(&mut s)?)
}
Asset::Confidential(generator) => generator.consensus_encode(&mut s)
}
}
}
impl Encodable for Generator {
fn consensus_encode<W: io::Write>(&self, mut e: W) -> Result<usize, encode::Error> {
e.write_all(&self.serialize())?;
Ok(33)
}
}
impl Decodable for Asset {
fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, encode::Error> {
let prefix = u8::consensus_decode(&mut d)?;
match prefix {
0 => Ok(Asset::Null),
1 => {
let explicit = Decodable::consensus_decode(&mut d)?;
Ok(Asset::Explicit(explicit))
}
p if p == 0x0a || p == 0x0b => {
let mut comm = [0u8; 33];
comm[0] = p;
d.read_exact(&mut comm[1..])?;
Ok(Asset::Confidential(Generator::from_slice(&comm[..])?))
}
p => Err(encode::Error::InvalidConfidentialPrefix(p)),
}
}
}
impl Decodable for Generator {
fn consensus_decode<D: io::Read>(d: D) -> Result<Self, encode::Error> {
let bytes = <[u8; 33]>::consensus_decode(d)?;
Ok(Generator::from_slice(&bytes)?)
}
}
#[cfg(feature = "serde")]
impl Serialize for Asset {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeSeq;
let seq_len = match *self {
Asset::Null => 1,
Asset::Explicit(_) | Asset::Confidential(_) => 2
};
let mut seq = s.serialize_seq(Some(seq_len))?;
match *self {
Asset::Null => seq.serialize_element(&0u8)?,
Asset::Explicit(n) => {
seq.serialize_element(&1u8)?;
seq.serialize_element(&n)?;
}
Asset::Confidential(commitment) => {
seq.serialize_element(&2u8)?;
seq.serialize_element(&commitment)?;
}
}
seq.end()
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Asset {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
use serde::de::{Error, SeqAccess, Visitor};
struct CommitVisitor;
impl<'de> Visitor<'de> for CommitVisitor {
type Value = Asset;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a committed value")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Asset, A::Error> {
let prefix = access.next_element::<u8>()?;
match prefix {
Some(0) => Ok(Asset::Null),
Some(1) => {
match access.next_element()? {
Some(x) => Ok(Asset::Explicit(x)),
None => Err(A::Error::custom("missing explicit asset")),
}
}
Some(2) => {
match access.next_element()? {
Some(x) => Ok(Asset::Confidential(x)),
None => Err(A::Error::custom("missing generator")),
}
}
_ => Err(A::Error::custom("wrong or missing prefix")),
}
}
}
d.deserialize_seq(CommitVisitor)
}
}
/// A CT commitment to an output nonce (i.e. a public key)
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum Nonce {
/// No value
Null,
/// There should be no such thing as an "explicit nonce", but Elements will deserialize
/// such a thing (and insists that its size be 32 bytes). So we stick a 32-byte type here
/// that implements all the traits we need.
Explicit([u8; 32]),
/// Nonce is committed
Confidential(PublicKey),
}
impl Nonce {
/// Create nonce commitment.
pub fn new_confidential<R: RngCore + CryptoRng, C: Signing>(
rng: &mut R,
secp: &Secp256k1<C>,
receiver_blinding_pk: &PublicKey,
) -> (Self, SecretKey) {
let sender_sk = SecretKey::new(rng);
let sender_pk = PublicKey::from_secret_key(&secp, &sender_sk);
let shared_secret = Self::make_shared_secret(receiver_blinding_pk, &sender_sk);
(Nonce::Confidential(sender_pk), shared_secret)
}
/// Calculate the shared secret.
pub fn shared_secret(&self, receiver_blinding_sk: &SecretKey) -> Option<SecretKey> {
match self {
Nonce::Confidential(sender_pk) => {
Some(Self::make_shared_secret(&sender_pk, receiver_blinding_sk))
}
_ => None,
}
}
/// Create the shared secret.
fn make_shared_secret(pk: &PublicKey, sk: &SecretKey) -> SecretKey {
let xy = secp256k1_zkp::ecdh::shared_secret_point(pk, sk);
let shared_secret = {
// Yes, what follows is the compressed representation of a Bitcoin public key.
// However, this is more by accident then by design, see here: https://github.com/rust-bitcoin/rust-secp256k1/pull/255#issuecomment-744146282
let mut dh_secret = [0u8; 33];
dh_secret[0] = if xy.last().unwrap() % 2 == 0 {
0x02
} else {
0x03
};
dh_secret[1..].copy_from_slice(&xy[0..32]);
sha256d::Hash::hash(&dh_secret).into_inner()
};
SecretKey::from_slice(&shared_secret.as_ref()[..32]).expect("always has exactly 32 bytes")
}
/// Serialized length, in bytes
pub fn encoded_length(&self) -> usize {
match *self {
Nonce::Null => 1,
Nonce::Explicit(..) => 33,
Nonce::Confidential(..) => 33,
}
}
/// Create from commitment.
pub fn from_commitment(bytes: &[u8]) -> Result<Self, encode::Error> {
Ok(Nonce::Confidential(
PublicKey::from_slice(bytes).map_err(secp256k1_zkp::Error::Upstream)?,
))
}
/// Check if the object is null.
pub fn is_null(&self) -> bool {
match *self {
Nonce::Null => true,
_ => false
}
}
/// Check if the object is explicit.
pub fn is_explicit(&self) -> bool {
match *self {
Nonce::Explicit(_) => true,
_ => false
}
}
/// Check if the object is confidential.
pub fn is_confidential(&self) -> bool {
match *self {
Nonce::Confidential(_) => true,
_ => false
}
}
/// Returns the explicit inner value.
/// Returns [None] if [is_explicit] returns false.
pub fn explicit(&self) -> Option<[u8; 32]> {
match *self {
Nonce::Explicit(i) => Some(i),
_ => None,
}
}
/// Returns the confidential commitment in case of a confidential value.
/// Returns [None] if [is_confidential] returns false.
pub fn commitment(&self) -> Option<PublicKey> {
match *self {
Nonce::Confidential(i) => Some(i),
_ => None,
}
}
}
impl From<PublicKey> for Nonce {
fn from(from: PublicKey) -> Self {
Nonce::Confidential(from)
}
}
impl fmt::Display for Nonce {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Nonce::Null => f.write_str("null"),
Nonce::Explicit(n) => {
for b in n.iter() {
write!(f, "{:02x}", b)?;
}
Ok(())
}
Nonce::Confidential(pk) => write!(f, "{:02x}", pk),
}
}
}
impl Default for Nonce {
fn default() -> Self {
Nonce::Null
}
}
impl Encodable for Nonce {
fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {
match *self {
Nonce::Null => 0u8.consensus_encode(s),
Nonce::Explicit(n) => {
1u8.consensus_encode(&mut s)?;
Ok(1 + n.consensus_encode(&mut s)?)
}
Nonce::Confidential(commitment) => commitment.consensus_encode(&mut s),
}
}
}
impl Encodable for PublicKey {
fn consensus_encode<W: io::Write>(&self, mut e: W) -> Result<usize, encode::Error> {
e.write_all(&self.serialize())?;
Ok(33)
}
}
impl Decodable for Nonce {
fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, encode::Error> {
let prefix = u8::consensus_decode(&mut d)?;
match prefix {
0 => Ok(Nonce::Null),
1 => {
let explicit = Decodable::consensus_decode(&mut d)?;
Ok(Nonce::Explicit(explicit))
}
p if p == 0x02 || p == 0x03 => {
let mut comm = [0u8; 33];
comm[0] = p;
d.read_exact(&mut comm[1..])?;
Ok(Nonce::Confidential(PublicKey::from_slice(&comm)?))
}
p => Err(encode::Error::InvalidConfidentialPrefix(p)),
}
}
}
impl Decodable for PublicKey {
fn consensus_decode<D: io::Read>(d: D) -> Result<Self, encode::Error> {
let bytes = <[u8; 33]>::consensus_decode(d)?;
Ok(PublicKey::from_slice(&bytes)?)
}
}
#[cfg(feature = "serde")]
impl Serialize for Nonce {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeSeq;
let seq_len = match *self {
Nonce::Null => 1,
Nonce::Explicit(_) | Nonce::Confidential(_) => 2
};
let mut seq = s.serialize_seq(Some(seq_len))?;
match *self {
Nonce::Null => seq.serialize_element(&0u8)?,
Nonce::Explicit(n) => {
seq.serialize_element(&1u8)?;
seq.serialize_element(&n)?;
}
Nonce::Confidential(commitment) => {
seq.serialize_element(&2u8)?;
seq.serialize_element(&commitment)?;
}
}
seq.end()
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Nonce {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
use serde::de::{Error, SeqAccess, Visitor};
struct CommitVisitor;
impl<'de> Visitor<'de> for CommitVisitor {
type Value = Nonce;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a committed value")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Nonce, A::Error> {
let prefix = access.next_element::<u8>()?;
match prefix {
Some(0) => Ok(Nonce::Null),
Some(1) => {
match access.next_element()? {
Some(x) => Ok(Nonce::Explicit(x)),
None => Err(A::Error::custom("missing explicit nonce")),
}
}
Some(2) => {
match access.next_element()? {
Some(x) => Ok(Nonce::Confidential(x)),
None => Err(A::Error::custom("missing nonce")),
}
}
_ => Err(A::Error::custom("wrong or missing prefix"))
}
}
}
d.deserialize_seq(CommitVisitor)
}
}
/// Blinding factor used for asset commitments.
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
pub struct AssetBlindingFactor(pub(crate) Tweak);
impl AssetBlindingFactor {
/// Generate random asset blinding factor.
pub fn new<R: Rng>(rng: &mut R) -> Self {
AssetBlindingFactor(Tweak::new(rng))
}
/// Create from bytes.
pub fn from_slice(bytes: &[u8]) -> Result<Self, secp256k1_zkp::Error> {
Ok(AssetBlindingFactor(Tweak::from_slice(bytes)?))
}
/// Returns the inner value.
pub fn into_inner(self) -> Tweak {
self.0
}
/// Get a unblinded/zero AssetBlinding factor
pub fn zero() -> Self {
AssetBlindingFactor(ZERO_TWEAK)
}
}
impl hex::FromHex for AssetBlindingFactor {
fn from_byte_iter<I>(iter: I) -> Result<Self, hex::Error>
where I: Iterator<Item=Result<u8, hex::Error>> +
ExactSizeIterator +
DoubleEndedIterator
{
let slice = <[u8; 32]>::from_byte_iter(iter.rev())?;
// Incorrect Return Error
// See: https://github.com/rust-bitcoin/bitcoin_hashes/issues/124
let inner = Tweak::from_inner(slice)
.map_err(|_e| hex::Error::InvalidChar(0))?;
Ok(AssetBlindingFactor(inner))
}
}
impl fmt::Display for AssetBlindingFactor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
hex::format_hex_reverse(self.0.as_ref(), f)
}
}
impl fmt::LowerHex for AssetBlindingFactor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
hex::format_hex_reverse(self.0.as_ref(), f)
}
}
impl str::FromStr for AssetBlindingFactor {
type Err = encode::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(hex::FromHex::from_hex(s)?)
}
}
#[cfg(feature = "serde")]
impl Serialize for AssetBlindingFactor {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
if s.is_human_readable() {
s.collect_str(&self)
} else {
s.serialize_bytes(&self.0[..])
}
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for AssetBlindingFactor {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<AssetBlindingFactor, D::Error> {
use bitcoin::hashes::hex::FromHex;
if d.is_human_readable() {
struct HexVisitor;
impl<'de> ::serde::de::Visitor<'de> for HexVisitor {
type Value = AssetBlindingFactor;
fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
formatter.write_str("an ASCII hex string")
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
{
if let Ok(hex) = ::std::str::from_utf8(v) {
AssetBlindingFactor::from_hex(hex).map_err(E::custom)
} else {
return Err(E::invalid_value(::serde::de::Unexpected::Bytes(v), &self));
}
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
{
AssetBlindingFactor::from_hex(v).map_err(E::custom)
}
}
d.deserialize_str(HexVisitor)
} else {
struct BytesVisitor;
impl<'de> ::serde::de::Visitor<'de> for BytesVisitor {
type Value = AssetBlindingFactor;
fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
formatter.write_str("a bytestring")
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
{
if v.len() != 32 {
Err(E::invalid_length(v.len(), &stringify!($len)))
} else {
let mut ret = [0; 32];
ret.copy_from_slice(v);
let inner = Tweak::from_inner(ret).map_err(E::custom)?;
Ok(AssetBlindingFactor(inner))
}
}
}
d.deserialize_bytes(BytesVisitor)
}
}
}
/// Blinding factor used for value commitments.
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
pub struct ValueBlindingFactor(pub(crate) Tweak);
impl ValueBlindingFactor {
/// Generate random value blinding factor.
pub fn new<R: Rng>(rng: &mut R) -> Self {
ValueBlindingFactor(Tweak::new(rng))
}
/// Create the value blinding factor of the last output of a transaction.
pub fn last<C: Signing>(
secp: &Secp256k1<C>,
value: u64,
abf: AssetBlindingFactor,
inputs: &[(u64, AssetBlindingFactor, ValueBlindingFactor)],
outputs: &[(u64, AssetBlindingFactor, ValueBlindingFactor)],
) -> Self {
let set_a = inputs
.iter()
.map(|(value, abf, vbf)| CommitmentSecrets {
value: *value,
value_blinding_factor: vbf.0,
generator_blinding_factor: abf.into_inner(),
})
.collect::<Vec<_>>();
let set_b = outputs
.iter()
.map(|(value, abf, vbf)| CommitmentSecrets {
value: *value,
value_blinding_factor: vbf.0,
generator_blinding_factor: abf.into_inner(),
})
.collect::<Vec<_>>();
ValueBlindingFactor(compute_adaptive_blinding_factor(
secp, value, abf.0, &set_a, &set_b,
))
}
/// Create from bytes.
pub fn from_slice(bytes: &[u8]) -> Result<Self, secp256k1_zkp::Error> {
Ok(ValueBlindingFactor(Tweak::from_slice(bytes)?))
}
/// Returns the inner value.
pub fn into_inner(self) -> Tweak {
self.0
}
/// Get a unblinded/zero AssetBlinding factor
pub fn zero() -> Self {
ValueBlindingFactor(ZERO_TWEAK)
}
}
impl AddAssign for ValueBlindingFactor {
fn add_assign(&mut self, other: Self) {
if self.0.as_ref() == &[0u8; 32] {
*self = other;
} else if other.0.as_ref() == &[0u8; 32] {
// nothing to do
} else {
// Since libsecp does not expose low level APIs
// for scalar arethematic, we need to abuse secret key
// operations for this
let sk2 = SecretKey::from_slice(self.into_inner().as_ref()).expect("Valid key");
let sk = SecretKey::from_slice(other.into_inner().as_ref()).expect("Valid key");
// The only reason that secret key addition can fail
// is when the keys add up to zero since we have already checked
// keys are in valid secret keys
match sk.add_tweak(&sk2.into()) {
Ok(sk_tweaked) => *self = ValueBlindingFactor::from_slice(sk_tweaked.as_ref()).expect("Valid Tweak"),
Err(_) => *self = Self::zero(),
}
}
}
}
impl Neg for ValueBlindingFactor {
type Output = Self;
fn neg(self) -> Self::Output {
if self.0.as_ref() == &[0u8; 32] {
self
} else {
let sk = SecretKey::from_slice(self.into_inner().as_ref()).expect("Valid key").negate();
ValueBlindingFactor::from_slice(sk.as_ref()).expect("Valid Tweak")
}
}
}
impl hex::FromHex for ValueBlindingFactor {
fn from_byte_iter<I>(iter: I) -> Result<Self, hex::Error>
where I: Iterator<Item=Result<u8, hex::Error>> +
ExactSizeIterator +
DoubleEndedIterator
{
let slice = <[u8; 32]>::from_byte_iter(iter.rev())?;
// Incorrect Return Error
// See: https://github.com/rust-bitcoin/bitcoin_hashes/issues/124
let inner = Tweak::from_inner(slice)
.map_err(|_e| hex::Error::InvalidChar(0))?;
Ok(ValueBlindingFactor(inner))
}
}
impl fmt::Display for ValueBlindingFactor {