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
use crate::keys::{PublicKey, SecretKey};
use digest::Digest;
use std::{ops::Mul, prelude::v1::Vec};
use thiserror::Error;
pub const MAX_SIGNATURES: usize = 32768;
#[derive(Clone, Debug, Error, PartialEq, Eq)]
pub enum MuSigError {
#[error("The number of public nonces must match the number of public keys in the joint key")]
MismatchedNonces,
#[error("The number of partial signatures must match the number of public keys in the joint key")]
MismatchedSignatures,
#[error("The aggregate signature did not verify")]
InvalidAggregateSignature,
#[error("A partial signature did not validate: {0}")]
InvalidPartialSignature(usize),
#[error("The participant list must be sorted before making this call")]
NotSorted,
#[error("The participant key is not in the list")]
ParticipantNotFound,
#[error("An attempt was made to perform an invalid MuSig state transition")]
InvalidStateTransition,
#[error("An attempt was made to add a duplicate public key to a MuSig signature")]
DuplicatePubKey,
#[error("There are too many parties in the MuSig signature")]
TooManyParticipants,
#[error("There are too few parties in the MuSig signature")]
NotEnoughParticipants,
#[error("A nonce hash is missing")]
MissingHash,
#[error("The message to be signed can only be set once")]
MessageAlreadySet,
#[error("The message to be signed MUST be set before the final nonce is added to the MuSig ceremony")]
MissingMessage,
#[error("The message to sign is invalid. have you hashed it?")]
InvalidMessage,
#[error("MuSig requires a hash function with a 32 byte digest")]
IncompatibleHashFunction,
}
pub struct JointKey<P, K>
where
K: SecretKey,
P: PublicKey<K = K>,
{
pub_keys: Vec<P>,
musig_scalars: Vec<K>,
common: K,
joint_pub_key: P,
}
pub struct JointKeyBuilder<P, K>
where
K: SecretKey,
P: PublicKey<K = K>,
{
num_signers: usize,
pub_keys: Vec<P>,
}
impl<K, P> JointKeyBuilder<P, K>
where
K: SecretKey + Mul<P, Output = P>,
P: PublicKey<K = K>,
{
pub fn new(n: usize) -> Result<JointKeyBuilder<P, K>, MuSigError> {
if n > MAX_SIGNATURES {
return Err(MuSigError::TooManyParticipants);
}
if n == 0 {
return Err(MuSigError::NotEnoughParticipants);
}
Ok(JointKeyBuilder {
pub_keys: Vec::with_capacity(n),
num_signers: n,
})
}
pub fn num_signers(&self) -> usize {
self.num_signers
}
pub fn add_key(&mut self, pub_key: P) -> Result<usize, MuSigError> {
if self.key_exists(&pub_key) {
return Err(MuSigError::DuplicatePubKey);
}
let n = self.pub_keys.len();
if n >= self.num_signers {
return Err(MuSigError::TooManyParticipants);
}
self.pub_keys.push(pub_key);
Ok(self.pub_keys.len())
}
pub fn key_exists(&self, key: &P) -> bool {
self.pub_keys.iter().any(|v| v == key)
}
pub fn is_full(&self) -> bool {
self.pub_keys.len() == self.num_signers
}
pub fn add_keys<T: IntoIterator<Item = P>>(&mut self, keys: T) -> Result<usize, MuSigError> {
for k in keys {
self.add_key(k)?;
}
Ok(self.pub_keys.len())
}
pub fn build<D: Digest>(mut self) -> Result<JointKey<P, K>, MuSigError> {
if !self.is_full() {
return Err(MuSigError::NotEnoughParticipants);
}
self.sort_keys();
let common = self.calculate_common::<D>();
let musig_scalars = self.calculate_musig_scalars::<D>(&common);
let joint_pub_key = JointKeyBuilder::calculate_joint_key::<D>(&musig_scalars, &self.pub_keys);
Ok(JointKey {
pub_keys: self.pub_keys,
musig_scalars,
joint_pub_key,
common,
})
}
fn calculate_common<D: Digest>(&self) -> K {
let mut common = D::new();
for k in self.pub_keys.iter() {
common = common.chain(k.as_bytes());
}
K::from_bytes(&common.result())
.expect("Could not calculate Scalar from hash value. Your crypto/hash combination might be inconsistent")
}
fn calculate_partial_key<D: Digest>(common: &[u8], pubkey: &P) -> K {
let k = D::new().chain(common).chain(pubkey.as_bytes()).result();
K::from_bytes(&k)
.expect("Could not calculate Scalar from hash value. Your crypto/hash combination might be inconsistent")
}
fn sort_keys(&mut self) {
self.pub_keys.sort_unstable();
}
fn calculate_musig_scalars<D: Digest>(&self, common: &K) -> Vec<K> {
self.pub_keys
.iter()
.map(|p| JointKeyBuilder::calculate_partial_key::<D>(common.as_bytes(), p))
.collect()
}
fn calculate_joint_key<D: Digest>(scalars: &[K], pub_keys: &[P]) -> P {
P::batch_mul(scalars, pub_keys)
}
}
impl<P, K> JointKey<P, K>
where
K: SecretKey,
P: PublicKey<K = K>,
{
pub fn index_of(&self, pubkey: &P) -> Result<usize, MuSigError> {
match self.pub_keys.binary_search(pubkey) {
Ok(i) => Ok(i),
Err(_) => Err(MuSigError::ParticipantNotFound),
}
}
#[inline]
pub fn size(&self) -> usize {
self.pub_keys.len()
}
#[inline]
pub fn get_pub_keys(&self, index: usize) -> &P {
&self.pub_keys[index]
}
#[inline]
pub fn get_musig_scalar(&self, index: usize) -> &K {
&self.musig_scalars[index]
}
#[inline]
pub fn get_common(&self) -> &K {
&self.common
}
#[inline]
pub fn get_joint_pubkey(&self) -> &P {
&self.joint_pub_key
}
}