1use std::hash::{Hash, Hasher};
5use std::str::FromStr;
6
7use af_sui_types::Address as SuiAddress;
8pub use enum_dispatch::enum_dispatch;
9use fastcrypto::encoding::{Base64, Encoding};
10use fastcrypto::error::FastCryptoError;
11use fastcrypto::hash::HashFunction as _;
12use fastcrypto::traits::ToFromBytes;
13use once_cell::sync::OnceCell;
14use serde::{Deserialize, Serialize};
15use serde_with::serde_as;
16
17use crate::crypto::{
18 CompressedSignature,
19 DefaultHash,
20 Error,
21 PublicKey,
22 Signature,
23 SignatureScheme,
24};
25
26pub type WeightUnit = u8;
27pub type ThresholdUnit = u16;
28pub type BitmapUnit = u16;
29pub const MAX_SIGNER_IN_MULTISIG: usize = 10;
30pub const MAX_BITMAP_VALUE: BitmapUnit = 0b1111111111;
31
32#[derive(Deserialize, Debug)]
38pub struct MultiSigSigner {
39 pub multisig_pk: MultiSigPublicKey,
40 pub signers: Vec<usize>,
42}
43
44#[serde_as]
50#[derive(Debug, Serialize, Deserialize, Clone)]
51pub struct MultiSig {
52 sigs: Vec<CompressedSignature>,
54 bitmap: BitmapUnit,
56 multisig_pk: MultiSigPublicKey,
58 #[serde(skip)]
60 bytes: OnceCell<Vec<u8>>,
61}
62
63impl MultiSig {
64 pub fn combine(
69 full_sigs: Vec<Signature>,
70 multisig_pk: MultiSigPublicKey,
71 ) -> Result<Self, Error> {
72 multisig_pk
73 .validate()
74 .map_err(|_| Error::InvalidSignature {
75 error: "Invalid multisig public key".to_string(),
76 })?;
77
78 if full_sigs.len() > multisig_pk.pk_map.len() || full_sigs.is_empty() {
79 return Err(Error::InvalidSignature {
80 error: "Invalid number of signatures".to_string(),
81 });
82 }
83 let mut bitmap = 0;
84 let mut sigs = Vec::with_capacity(full_sigs.len());
85 for s in full_sigs {
86 let pk = s.to_public_key()?;
87 let index = multisig_pk
88 .get_index(&pk)
89 .ok_or_else(|| Error::IncorrectSigner {
90 error: format!("pk does not exist: {pk:?}"),
91 })?;
92 if bitmap & (1 << index) != 0 {
93 return Err(Error::InvalidSignature {
94 error: "Duplicate public key".to_string(),
95 });
96 }
97 bitmap |= 1 << index;
98 sigs.push(s.to_compressed()?);
99 }
100
101 Ok(Self {
102 sigs,
103 bitmap,
104 multisig_pk,
105 bytes: OnceCell::new(),
106 })
107 }
108
109 pub fn init_and_validate(&self) -> Result<Self, FastCryptoError> {
110 if self.sigs.len() > self.multisig_pk.pk_map.len()
111 || self.sigs.is_empty()
112 || self.bitmap > MAX_BITMAP_VALUE
113 {
114 return Err(FastCryptoError::InvalidInput);
115 }
116 self.multisig_pk.validate()?;
117 Ok(self.to_owned())
118 }
119
120 pub const fn get_pk(&self) -> &MultiSigPublicKey {
121 &self.multisig_pk
122 }
123
124 #[expect(
125 clippy::missing_const_for_fn,
126 reason = "Not changing the public API right now"
127 )]
128 pub fn get_sigs(&self) -> &[CompressedSignature] {
129 &self.sigs
130 }
131
132 pub fn get_indices(&self) -> Result<Vec<u8>, Error> {
133 as_indices(self.bitmap)
134 }
135}
136
137impl PartialEq for MultiSig {
139 fn eq(&self, other: &Self) -> bool {
140 self.sigs == other.sigs
141 && self.bitmap == other.bitmap
142 && self.multisig_pk == other.multisig_pk
143 }
144}
145
146impl Eq for MultiSig {}
148
149impl Hash for MultiSig {
151 fn hash<H: Hasher>(&self, state: &mut H) {
152 self.as_ref().hash(state);
153 }
154}
155
156pub fn as_indices(bitmap: u16) -> Result<Vec<u8>, Error> {
159 if bitmap > MAX_BITMAP_VALUE {
160 return Err(Error::InvalidSignature {
161 error: "Invalid bitmap".to_string(),
162 });
163 }
164 let mut res = Vec::new();
165 for i in 0..10 {
166 if bitmap & (1 << i) != 0 {
167 res.push(i as u8);
168 }
169 }
170 Ok(res)
171}
172
173impl ToFromBytes for MultiSig {
174 fn from_bytes(bytes: &[u8]) -> Result<Self, FastCryptoError> {
175 if bytes.first().ok_or(FastCryptoError::InvalidInput)? != &SignatureScheme::MultiSig.flag()
177 {
178 return Err(FastCryptoError::InvalidInput);
179 }
180 let multisig: Self =
181 bcs::from_bytes(&bytes[1..]).map_err(|_| FastCryptoError::InvalidSignature)?;
182 multisig.init_and_validate()
183 }
184}
185
186impl FromStr for MultiSig {
187 type Err = Error;
188
189 fn from_str(s: &str) -> Result<Self, Self::Err> {
190 let bytes = Base64::decode(s).map_err(|_| Error::InvalidSignature {
191 error: "Invalid base64 string".to_string(),
192 })?;
193 let sig = Self::from_bytes(&bytes).map_err(|_| Error::InvalidSignature {
194 error: "Invalid multisig bytes".to_string(),
195 })?;
196 Ok(sig)
197 }
198}
199
200impl AsRef<[u8]> for MultiSig {
204 fn as_ref(&self) -> &[u8] {
205 self.bytes
206 .get_or_try_init::<_, eyre::Report>(|| {
207 let as_bytes = bcs::to_bytes(self).expect("BCS serialization should not fail");
208 let mut bytes = Vec::with_capacity(1 + as_bytes.len());
209 bytes.push(SignatureScheme::MultiSig.flag());
210 bytes.extend_from_slice(as_bytes.as_slice());
211 Ok(bytes)
212 })
213 .expect("OnceCell invariant violated")
214 }
215}
216
217impl From<MultiSig> for af_sui_types::UserSignature {
218 fn from(value: MultiSig) -> Self {
219 Self::from_bytes(value.as_bytes()).expect("Compatible")
220 }
221}
222
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
229pub struct MultiSigPublicKey {
230 pk_map: Vec<(PublicKey, WeightUnit)>,
232 threshold: ThresholdUnit,
234}
235
236impl MultiSigPublicKey {
237 #[expect(
239 clippy::missing_const_for_fn,
240 reason = "Don't want to risk breaking the API if this uses a non-const init in the future"
241 )]
242 pub fn insecure_new(pk_map: Vec<(PublicKey, WeightUnit)>, threshold: ThresholdUnit) -> Self {
243 Self { pk_map, threshold }
244 }
245
246 pub fn new(
247 pks: Vec<PublicKey>,
248 weights: Vec<WeightUnit>,
249 threshold: ThresholdUnit,
250 ) -> Result<Self, Error> {
251 if pks.is_empty()
252 || weights.is_empty()
253 || threshold == 0
254 || pks.len() != weights.len()
255 || pks.len() > MAX_SIGNER_IN_MULTISIG
256 || weights.iter().any(|w| *w == 0)
257 || weights
258 .iter()
259 .map(|w| *w as ThresholdUnit)
260 .sum::<ThresholdUnit>()
261 < threshold
262 || pks
263 .iter()
264 .enumerate()
265 .any(|(i, pk)| pks.iter().skip(i + 1).any(|other_pk| *pk == *other_pk))
266 {
267 return Err(Error::InvalidSignature {
268 error: "Invalid multisig public key construction".to_string(),
269 });
270 }
271
272 Ok(Self {
273 pk_map: pks.into_iter().zip(weights).collect(),
274 threshold,
275 })
276 }
277
278 pub fn get_index(&self, pk: &PublicKey) -> Option<u8> {
279 self.pk_map.iter().position(|x| &x.0 == pk).map(|x| x as u8)
280 }
281
282 pub const fn threshold(&self) -> &ThresholdUnit {
283 &self.threshold
284 }
285
286 pub const fn pubkeys(&self) -> &Vec<(PublicKey, WeightUnit)> {
287 &self.pk_map
288 }
289
290 pub fn validate(&self) -> Result<Self, FastCryptoError> {
291 let pk_map = self.pubkeys();
292 if self.threshold == 0
293 || pk_map.is_empty()
294 || pk_map.len() > MAX_SIGNER_IN_MULTISIG
295 || pk_map.iter().any(|(_pk, weight)| *weight == 0)
296 || pk_map
297 .iter()
298 .map(|(_pk, weight)| *weight as ThresholdUnit)
299 .sum::<ThresholdUnit>()
300 < self.threshold
301 || pk_map.iter().enumerate().any(|(i, (pk, _weight))| {
302 pk_map
303 .iter()
304 .skip(i + 1)
305 .any(|(other_pk, _weight)| *pk == *other_pk)
306 })
307 {
308 return Err(FastCryptoError::InvalidInput);
309 }
310 Ok(self.to_owned())
311 }
312}
313
314impl From<&MultiSigPublicKey> for SuiAddress {
315 fn from(multisig_pk: &MultiSigPublicKey) -> Self {
324 let mut hasher = DefaultHash::default();
325 hasher.update([SignatureScheme::MultiSig.flag()]);
326 hasher.update(multisig_pk.threshold().to_le_bytes());
327 multisig_pk.pubkeys().iter().for_each(|(pk, w)| {
328 hasher.update([pk.flag()]);
329 hasher.update(pk.as_ref());
330 hasher.update(w.to_le_bytes());
331 });
332 Self::new(hasher.finalize().digest)
333 }
334}