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
use std::collections::BTreeSet;
use blsttc::{
Ciphertext, DecryptionShare, PublicKey, PublicKeySet, SecretKey, SecretKeySet, SecretKeyShare,
};
use bulletproofs::{BulletproofGens, PedersenGens, RangeProof};
use curve25519_dalek_ng::ristretto::CompressedRistretto;
use curve25519_dalek_ng::scalar::Scalar;
use merlin::Transcript;
use rand8::rngs::OsRng;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use tiny_keccak::{Hasher, Sha3};
use crate::{DbcContentHash, Error, Hash};
pub(crate) const RANGE_PROOF_BITS: usize = 64;
pub(crate) const RANGE_PROOF_PARTIES: usize = 1;
pub(crate) const MERLIN_TRANSCRIPT_LABEL: &[u8] = b"SN_DBC";
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
pub struct BlindedOwner(Hash);
const AMT_SIZE: usize = 8;
const BF_SIZE: usize = 32;
pub type Amount = u64;
impl BlindedOwner {
pub fn new(owner: &PublicKey, parents: &BTreeSet<DbcContentHash>) -> Self {
let mut sha3 = Sha3::v256();
for parent in parents.iter() {
sha3.update(parent);
}
sha3.update(&owner.to_bytes());
let mut hash = [0; 32];
sha3.finalize(&mut hash);
Self(Hash(hash))
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, Serialize, Deserialize)]
pub struct AmountSecrets {
pub amount: Amount,
pub blinding_factor: Scalar,
}
impl AmountSecrets {
pub fn to_bytes(&self) -> Vec<u8> {
let mut v: Vec<u8> = Default::default();
v.extend(&self.amount.to_le_bytes());
v.extend(&self.blinding_factor.to_bytes());
v
}
pub fn from_bytes(bytes: [u8; AMT_SIZE + BF_SIZE]) -> Self {
let amount = Amount::from_le_bytes({
let mut b = [0u8; AMT_SIZE];
b.copy_from_slice(&bytes[0..AMT_SIZE]);
b
});
let blinding_factor = Scalar::from_bytes_mod_order({
let mut b = [0u8; BF_SIZE];
b.copy_from_slice(&bytes[AMT_SIZE..]);
b
});
Self {
amount,
blinding_factor,
}
}
pub fn from_bytes_ref(bytes: &[u8]) -> Result<Self, Error> {
if bytes.len() != AMT_SIZE + BF_SIZE {
return Err(Error::AmountSecretsBytesInvalid);
}
let amount = Amount::from_le_bytes({
let mut b = [0u8; AMT_SIZE];
b.copy_from_slice(&bytes[0..AMT_SIZE]);
b
});
let blinding_factor = Scalar::from_bytes_mod_order({
let mut b = [0u8; BF_SIZE];
b.copy_from_slice(&bytes[AMT_SIZE..]);
b
});
Ok(Self {
amount,
blinding_factor,
})
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
pub struct DbcContent {
pub parents: BTreeSet<DbcContentHash>,
pub amount_secrets_cipher: Ciphertext,
pub commitment: CompressedRistretto,
pub range_proof_bytes: Vec<u8>,
pub owner: BlindedOwner,
}
impl DbcContent {
pub fn new(
parents: BTreeSet<DbcContentHash>,
amount: Amount,
owner_key: PublicKey,
blinding_factor: Scalar,
) -> Result<Self, Error> {
let owner = BlindedOwner::new(&owner_key, &parents);
let secret = amount;
let pc_gens = PedersenGens::default();
let bullet_gens = BulletproofGens::new(RANGE_PROOF_BITS, RANGE_PROOF_PARTIES);
let mut prover_ts = Transcript::new(MERLIN_TRANSCRIPT_LABEL);
let (proof, commitment) = RangeProof::prove_single(
&bullet_gens,
&pc_gens,
&mut prover_ts,
secret,
&blinding_factor,
RANGE_PROOF_BITS,
)?;
let amount_secrets = AmountSecrets {
amount,
blinding_factor,
};
let amount_secrets_cipher = owner_key.encrypt(amount_secrets.to_bytes().as_slice());
Ok(DbcContent {
parents,
amount_secrets_cipher,
owner,
commitment,
range_proof_bytes: proof.to_bytes(),
})
}
pub fn random_blinding_factor() -> Scalar {
let mut csprng: OsRng = OsRng::default();
Scalar::random(&mut csprng)
}
pub fn validate_unblinding(&self, owner_key: &PublicKey) -> Result<(), Error> {
let blinded = BlindedOwner::new(owner_key, &self.parents);
if blinded == self.owner {
Ok(())
} else {
Err(Error::FailedUnblinding)
}
}
pub fn hash(&self) -> DbcContentHash {
let mut sha3 = Sha3::v256();
for parent in self.parents.iter() {
sha3.update(parent);
}
sha3.update(&self.amount_secrets_cipher.to_bytes());
sha3.update(&self.owner.0);
let mut hash = [0; 32];
sha3.finalize(&mut hash);
Hash(hash)
}
pub fn amount_secret_by_secret_key(
&self,
secret_key: &SecretKey,
) -> Result<AmountSecrets, Error> {
let bytes_vec = secret_key
.decrypt(&self.amount_secrets_cipher)
.ok_or(Error::DecryptionBySecretKeyFailed)?;
AmountSecrets::from_bytes_ref(&bytes_vec)
}
pub fn amount_secrets_by_secret_key_set(
&self,
secret_key_set: &SecretKeySet,
) -> Result<AmountSecrets, Error> {
self.amount_secret_by_secret_key(&secret_key_set.secret_key())
}
pub fn amount_secrets_by_secret_key_shares(
&self,
public_key_set: &PublicKeySet,
secret_key_shares: &BTreeMap<usize, SecretKeyShare>,
) -> Result<AmountSecrets, Error> {
let mut decryption_shares: BTreeMap<usize, DecryptionShare> = Default::default();
for (idx, sec_share) in secret_key_shares.iter() {
let share = sec_share.decrypt_share_no_verify(&self.amount_secrets_cipher);
decryption_shares.insert(*idx, share);
}
self.amount_secrets_by_decryption_shares(public_key_set, &decryption_shares)
}
pub fn amount_secrets_by_decryption_shares(
&self,
public_key_set: &PublicKeySet,
decryption_shares: &BTreeMap<usize, DecryptionShare>,
) -> Result<AmountSecrets, Error> {
let bytes_vec = public_key_set.decrypt(decryption_shares, &self.amount_secrets_cipher)?;
AmountSecrets::from_bytes_ref(&bytes_vec)
}
pub fn verify_range_proof(&self) -> Result<(), Error> {
let bullet_gens = BulletproofGens::new(RANGE_PROOF_BITS, RANGE_PROOF_PARTIES);
let pc_gens = PedersenGens::default();
let mut verifier_ts = Transcript::new(MERLIN_TRANSCRIPT_LABEL);
let proof = RangeProof::from_bytes(&self.range_proof_bytes)?;
Ok(proof.verify_single(
&bullet_gens,
&pc_gens,
&mut verifier_ts,
&self.commitment,
RANGE_PROOF_BITS,
)?)
}
pub fn confirm_amount_matches_commitment(
&self,
public_key_set: &PublicKeySet,
decryption_shares: &BTreeMap<usize, DecryptionShare>,
) -> Result<bool, Error> {
let secrets =
self.amount_secrets_by_decryption_shares(public_key_set, decryption_shares)?;
Ok(self.confirm_provided_amount_matches_commitment(&secrets))
}
pub fn confirm_provided_amount_matches_commitment(&self, amount: &AmountSecrets) -> bool {
let commitment =
PedersenGens::default().commit(Scalar::from(amount.amount), amount.blinding_factor);
self.commitment == commitment.compress()
}
pub fn calc_blinding_factor(
is_last: bool,
inputs_bf_sum: Scalar,
outputs_bf_sum: Scalar,
) -> Scalar {
match is_last {
true => inputs_bf_sum - outputs_bf_sum,
false => DbcContent::random_blinding_factor(),
}
}
}