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
1001
1002
1003
1004
1005
1006
1007
1008
1009
// SPDX-License-Identifier: Apache-2.0
use crate::{
    error::{AttributesError, ConversionsError, SharesError},
    views::threshold_meta,
    AttrId, AttrView, Builder, ConvView, DataView, Error, Multisig, ThresholdAttrView,
    ThresholdView, Views,
};
use multi_key::ThresholdDisclosure;
use blsful::{
    inner_types::{G1Projective, G2Projective, Scalar},
    vsss_rs::{IdentifierPrimeField, Share, ValueGroup},
    Bls12381G1Impl, Bls12381G2Impl, Signature, SignatureSchemes, SignatureShare,
};
use multi_codec::Codec;
use multi_trait::{EncodeInto, TryDecodeFrom};
use multi_util::{Varbytes, Varuint};
use std::{collections::BTreeMap, fmt};

/// the name used to identify these signatures in non-Multikey formats
pub const ALGORITHM_NAME_G1: &str = "bls12_381-g1@multisig";
/// the name used to identify these signatures in non-Multikey formats
pub const ALGORITHM_NAME_G1_SHARE: &str = "bls12_381-g1-share@multisig";
/// the name used to identify these signatures in non-Multikey formats
pub const ALGORITHM_NAME_G2: &str = "bls12_381-g2@multisig";
/// the name used to identify these signatures in non-Multikey formats
pub const ALGORITHM_NAME_G2_SHARE: &str = "bls12_381-g2-share@multisig";

/// The different signature scheme methods offered in the blsful BLS crate
#[repr(u8)]
#[derive(Clone, Copy, Default, Hash, Ord, PartialOrd, PartialEq, Eq)]
pub enum SchemeTypeId {
    /// Basic
    Basic,
    /// Message Augmentation
    MessageAugmentation,
    /// ProofOfPossession
    #[default]
    ProofOfPossession,
}

impl SchemeTypeId {
    /// Get the code for the attribute id
    pub fn code(&self) -> u8 {
        (*self).into()
    }

    /// Convert the attribute id to &str
    pub fn as_str(&self) -> &str {
        match self {
            Self::Basic => "basic",
            Self::MessageAugmentation => "message-augmentation",
            Self::ProofOfPossession => "proof-of-possession",
        }
    }
}

impl From<SchemeTypeId> for u8 {
    fn from(val: SchemeTypeId) -> Self {
        val as u8
    }
}

impl TryFrom<u8> for SchemeTypeId {
    type Error = Error;

    fn try_from(c: u8) -> Result<Self, Self::Error> {
        match c {
            0 => Ok(Self::Basic),
            1 => Ok(Self::MessageAugmentation),
            2 => Ok(Self::ProofOfPossession),
            _ => Err(SharesError::InvalidSchemeTypeId(c).into()),
        }
    }
}

impl From<SchemeTypeId> for SignatureSchemes {
    fn from(val: SchemeTypeId) -> Self {
        match val {
            SchemeTypeId::Basic => SignatureSchemes::Basic,
            SchemeTypeId::MessageAugmentation => SignatureSchemes::MessageAugmentation,
            SchemeTypeId::ProofOfPossession => SignatureSchemes::ProofOfPossession,
        }
    }
}

impl From<&SignatureSchemes> for SchemeTypeId {
    fn from(s: &SignatureSchemes) -> Self {
        match s {
            SignatureSchemes::Basic => SchemeTypeId::Basic,
            SignatureSchemes::MessageAugmentation => SchemeTypeId::MessageAugmentation,
            SignatureSchemes::ProofOfPossession => SchemeTypeId::ProofOfPossession,
        }
    }
}

impl<C> From<&Signature<C>> for SchemeTypeId
where
    C: blsful::BlsSignatureImpl,
{
    fn from(s: &Signature<C>) -> Self {
        match s {
            Signature::Basic(_) => SchemeTypeId::Basic,
            Signature::MessageAugmentation(_) => SchemeTypeId::MessageAugmentation,
            Signature::ProofOfPossession(_) => SchemeTypeId::ProofOfPossession,
        }
    }
}

impl<C> From<&SignatureShare<C>> for SchemeTypeId
where
    C: blsful::BlsSignatureImpl,
{
    fn from(s: &SignatureShare<C>) -> Self {
        match s {
            SignatureShare::Basic(_) => SchemeTypeId::Basic,
            SignatureShare::MessageAugmentation(_) => SchemeTypeId::MessageAugmentation,
            SignatureShare::ProofOfPossession(_) => SchemeTypeId::ProofOfPossession,
        }
    }
}

impl From<SchemeTypeId> for Vec<u8> {
    fn from(val: SchemeTypeId) -> Self {
        val.code().encode_into()
    }
}

impl<'a> TryFrom<&'a [u8]> for SchemeTypeId {
    type Error = Error;

    fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
        let (id, _) = Self::try_decode_from(bytes)?;
        Ok(id)
    }
}

impl<'a> TryDecodeFrom<'a> for SchemeTypeId {
    type Error = Error;

    fn try_decode_from(bytes: &'a [u8]) -> Result<(Self, &'a [u8]), Self::Error> {
        let (code, ptr) = u8::try_decode_from(bytes)?;
        Ok((Self::try_from(code)?, ptr))
    }
}

impl TryFrom<&str> for SchemeTypeId {
    type Error = Error;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        match s.to_ascii_lowercase().as_str() {
            "basic" => Ok(Self::Basic),
            "message-augmentation" => Ok(Self::MessageAugmentation),
            "proof-of-possession" => Ok(Self::ProofOfPossession),
            _ => Err(SharesError::InvalidShareTypeName(s.to_string()).into()),
        }
    }
}

impl fmt::Display for SchemeTypeId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// tuple of combined signature data
#[derive(Clone)]
pub struct SigCombined(
    /// signature scheme
    pub SchemeTypeId,
    /// signature bytes
    pub Vec<u8>,
);

impl From<SigCombined> for Vec<u8> {
    fn from(val: SigCombined) -> Self {
        let mut v = Vec::default();
        // add in the signature type id
        v.append(&mut val.0.into());
        // add in the signature bytes
        v.append(&mut Varbytes::new(val.1.clone()).into());
        v
    }
}

impl<'a> TryFrom<&'a [u8]> for SigCombined {
    type Error = Error;

    fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
        let (sig, _) = Self::try_decode_from(bytes)?;
        Ok(sig)
    }
}

impl<'a> TryDecodeFrom<'a> for SigCombined {
    type Error = Error;

    fn try_decode_from(bytes: &'a [u8]) -> Result<(Self, &'a [u8]), Self::Error> {
        // try to decode the signature type
        let (sig_type, ptr) = SchemeTypeId::try_decode_from(bytes)?;
        // try to decode the signature bytes
        let (sig_data, ptr) = Varbytes::try_decode_from(ptr)?;
        Ok((Self(sig_type, sig_data.to_inner()), ptr))
    }
}

/// tuple of signature share data with threshold attributes
#[derive(Clone)]
pub struct SigShare(
    /// identifier
    pub IdentifierPrimeField<Scalar>,
    /// threshold
    pub usize,
    /// limit
    pub usize,
    /// signature scheme
    pub SchemeTypeId,
    /// share bytes
    pub Vec<u8>,
);

impl From<SigShare> for Vec<u8> {
    fn from(val: SigShare) -> Self {
        let mut v = Vec::default();
        // add in the share identifier
        v.append(&mut val.0 .0.to_be_bytes().into());
        // add in the share threshold
        v.append(&mut Varuint(val.1).into());
        // add in the share limit
        v.append(&mut Varuint(val.2).into());
        // add in the share type id
        v.append(&mut val.3.into());
        // add in the share data
        v.append(&mut Varbytes::new(val.4.clone()).into());
        v
    }
}

impl<'a> TryFrom<&'a [u8]> for SigShare {
    type Error = Error;

    fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
        let (share, _) = Self::try_decode_from(bytes)?;
        Ok(share)
    }
}

impl<'a> TryDecodeFrom<'a> for SigShare {
    type Error = Error;

    fn try_decode_from(bytes: &'a [u8]) -> Result<(Self, &'a [u8]), Self::Error> {
        // try to decode the identifier
        let (id_bytes, ptr) = Varuint::<[u8; 32]>::try_decode_from(bytes)?;
        let id = Option::<Scalar>::from(Scalar::from_be_bytes(&id_bytes)).ok_or(
            Error::FailedConversion("Can't convert identifier to scalar".to_string()),
        )?;
        // try to decode the threshold
        let (threshold, ptr) = Varuint::<usize>::try_decode_from(ptr)?;
        // try to decode the limit
        let (limit, ptr) = Varuint::<usize>::try_decode_from(ptr)?;
        // try to decode the share type id
        let (share_type, ptr) = SchemeTypeId::try_decode_from(ptr)?;
        // try to decode the share data
        let (share_data, ptr) = Varbytes::try_decode_from(ptr)?;
        Ok((
            Self(
                IdentifierPrimeField(id),
                threshold.to_inner(),
                limit.to_inner(),
                share_type,
                share_data.to_inner(),
            ),
            ptr,
        ))
    }
}

#[derive(Clone, Default)]
pub(crate) struct ThresholdData(pub(crate) BTreeMap<IdentifierPrimeField<Scalar>, SigShare>);

impl From<ThresholdData> for Vec<u8> {
    fn from(val: ThresholdData) -> Self {
        let mut v = Vec::default();
        // add in the number of sig shares
        v.append(&mut Varuint(val.0.len()).into());
        // add in the sig shares
        val.0.iter().for_each(|(_, share)| {
            v.append(&mut share.clone().into());
        });
        v
    }
}

impl<'a> TryFrom<&'a [u8]> for ThresholdData {
    type Error = Error;

    fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
        let (tdata, _) = Self::try_decode_from(bytes)?;
        Ok(tdata)
    }
}

impl<'a> TryDecodeFrom<'a> for ThresholdData {
    type Error = Error;

    fn try_decode_from(bytes: &'a [u8]) -> Result<(Self, &'a [u8]), Self::Error> {
        // try to decode the number of shares
        let (num_shares, ptr) = Varuint::<usize>::try_decode_from(bytes)?;
        // decode the signature-specific attributes
        let (shares, ptr) = match *num_shares {
            0 => (BTreeMap::default(), ptr),
            _ => {
                let mut shares = BTreeMap::new();
                let mut p = ptr;
                for _ in 0..*num_shares {
                    let (share, ptr) = SigShare::try_decode_from(p)?;
                    shares.insert(share.0, share);
                    p = ptr;
                }
                (shares, p)
            }
        };

        Ok((Self(shares), ptr))
    }
}

pub(crate) struct View<'a> {
    ms: &'a Multisig,
}

impl<'a> TryFrom<&'a Multisig> for View<'a> {
    type Error = Error;

    fn try_from(ms: &'a Multisig) -> Result<Self, Self::Error> {
        Ok(Self { ms })
    }
}

impl<'a> AttrView for View<'a> {
    /// for Bls Multisigs, the payload encoding is stored using the
    /// SchemeTypeId::PayloadEncoding attribute id.
    fn payload_encoding(&self) -> Result<Codec, Error> {
        let v = self
            .ms
            .attributes
            .get(&AttrId::PayloadEncoding)
            .ok_or(AttributesError::MissingPayloadEncoding)?;
        let encoding = Codec::try_from(v.as_slice())?;
        Ok(encoding)
    }
    /// Bls signatures have three different schemes which is needed
    /// for verifying the signatures
    fn scheme(&self) -> Result<u8, Error> {
        let v = self
            .ms
            .attributes
            .get(&AttrId::Scheme)
            .ok_or(AttributesError::MissingScheme)?;
        let scheme = Varuint::<u8>::try_from(v.as_slice())?;
        Ok(*scheme)
    }
}

impl<'a> DataView for View<'a> {
    /// For Bls Multisig values, the sig data is stored using the
    /// SchemeTypeId::SigData attribute id.
    fn sig_bytes(&self) -> Result<Vec<u8>, Error> {
        let sig = self
            .ms
            .attributes
            .get(&AttrId::SigData)
            .ok_or(AttributesError::MissingSignature)?;
        Ok(sig.clone())
    }
}

impl<'a> ConvView for View<'a> {
    /// convert to SSH signature format
    fn to_ssh_signature(&self) -> Result<ssh_key::Signature, Error> {
        // get the signature data
        let dv = self.ms.data_view()?;
        let sig_bytes = dv.sig_bytes()?;

        // get the scheme
        let av = self.ms.attr_view()?;
        let scheme_type = SchemeTypeId::try_from(av.scheme()?)?;

        match self.ms.codec {
            Codec::Bls12381G1Msig => {
                // create the combined sig tuple
                let sig_data: Vec<u8> = SigCombined(scheme_type, sig_bytes).into();

                Ok(ssh_key::Signature::new(
                    ssh_key::Algorithm::Other(
                        ssh_key::AlgorithmName::new(ALGORITHM_NAME_G1)
                            .map_err(|e| ConversionsError::Ssh(e.into()))?,
                    ),
                    sig_data,
                )
                .map_err(|e| ConversionsError::Ssh(e.into()))?)
            }
            Codec::Bls12381G2Msig => {
                // create the combined sig tuple
                let sig_data: Vec<u8> = SigCombined(scheme_type, sig_bytes).into();

                Ok(ssh_key::Signature::new(
                    ssh_key::Algorithm::Other(
                        ssh_key::AlgorithmName::new(ALGORITHM_NAME_G2)
                            .map_err(|e| ConversionsError::Ssh(e.into()))?,
                    ),
                    sig_data,
                )
                .map_err(|e| ConversionsError::Ssh(e.into()))?)
            }
            Codec::Bls12381G1ShareMsig => {
                // get the threshold attributes
                let av = self.ms.threshold_attr_view()?;
                let threshold = av.threshold()?;
                let limit = av.limit()?;
                let identifier_bytes = av.identifier()?;
                if identifier_bytes.len() != 32 {
                    return Err(Error::FailedConversion(
                        "Insufficient identifier bytes".to_string(),
                    ));
                }
                let identifier_array = <[u8; 32]>::try_from(identifier_bytes)
                    .map_err(|_| Error::FailedConversion("Invalid bytes".to_string()))?;
                let id_scalar = Option::<Scalar>::from(Scalar::from_be_bytes(&identifier_array))
                    .ok_or(Error::FailedConversion(
                        "Invalid share identifier bytes".to_string(),
                    ))?;

                // create the sig share tuple
                let sig_data: Vec<u8> = SigShare(
                    IdentifierPrimeField(id_scalar),
                    threshold,
                    limit,
                    scheme_type,
                    sig_bytes,
                )
                .into();

                Ok(ssh_key::Signature::new(
                    ssh_key::Algorithm::Other(
                        ssh_key::AlgorithmName::new(ALGORITHM_NAME_G1_SHARE)
                            .map_err(|e| ConversionsError::Ssh(e.into()))?,
                    ),
                    sig_data,
                )
                .map_err(|e| ConversionsError::Ssh(e.into()))?)
            }
            Codec::Bls12381G2ShareMsig => {
                // get the threshold attributes
                let av = self.ms.threshold_attr_view()?;
                let threshold = av.threshold()?;
                let limit = av.limit()?;
                let identifier_bytes = av.identifier()?;
                if identifier_bytes.len() != 32 {
                    return Err(Error::FailedConversion(
                        "Insufficient identifier bytes".to_string(),
                    ));
                }
                let identifier_array = <[u8; 32]>::try_from(identifier_bytes)
                    .map_err(|_| Error::FailedConversion("Invalid bytes".to_string()))?;
                let id_scalar = Option::<Scalar>::from(Scalar::from_be_bytes(&identifier_array))
                    .ok_or(Error::FailedConversion(
                        "Invalid share identifier bytes".to_string(),
                    ))?;

                // create the sig share tuple
                let sig_data: Vec<u8> = SigShare(
                    IdentifierPrimeField(id_scalar),
                    threshold,
                    limit,
                    scheme_type,
                    sig_bytes,
                )
                .into();

                Ok(ssh_key::Signature::new(
                    ssh_key::Algorithm::Other(
                        ssh_key::AlgorithmName::new(ALGORITHM_NAME_G2_SHARE)
                            .map_err(|e| ConversionsError::Ssh(e.into()))?,
                    ),
                    sig_data,
                )
                .map_err(|e| ConversionsError::Ssh(e.into()))?)
            }
            _ => Err(Error::UnsupportedAlgorithm(self.ms.codec.to_string())),
        }
    }
}

impl<'a> ThresholdAttrView for View<'a> {
    /// get the threshold value for this multisig
    fn threshold(&self) -> Result<usize, Error> {
        let threshold = self
            .ms
            .attributes
            .get(&AttrId::Threshold)
            .ok_or(AttributesError::MissingThreshold)?;
        Ok(Varuint::<usize>::try_from(threshold.as_slice())?.to_inner())
    }
    /// get the limit value for this multisig
    fn limit(&self) -> Result<usize, Error> {
        let limit = self
            .ms
            .attributes
            .get(&AttrId::Limit)
            .ok_or(AttributesError::MissingLimit)?;
        Ok(Varuint::<usize>::try_from(limit.as_slice())?.to_inner())
    }
    /// get the share identifier
    fn identifier(&self) -> Result<&[u8], Error> {
        match self.ms.codec {
            Codec::Bls12381G1ShareMsig | Codec::Bls12381G2ShareMsig => {
                let identifier = self
                    .ms
                    .attributes
                    .get(&AttrId::ShareIdentifier)
                    .ok_or(AttributesError::MissingIdentifier)?;
                Ok(identifier.as_slice())
            }
            _ => Err(SharesError::NotASignatureShare.into()),
        }
    }
    /// get the threshold data
    fn threshold_data(&self) -> Result<&[u8], Error> {
        let v = self
            .ms
            .attributes
            .get(&AttrId::ThresholdData)
            .ok_or(AttributesError::MissingThresholdData)?;
        Ok(v.as_slice())
    }
}

/// trait for accumulating shares to rebuild a threshold signature
impl<'a> ThresholdView for View<'a> {
    /// get the signature shares
    fn shares(&self) -> Result<Vec<Multisig>, Error> {
        // get the codec for the new share multisigs
        let codec = match self.ms.codec {
            Codec::Bls12381G1Msig => Codec::Bls12381G1ShareMsig,
            Codec::Bls12381G2Msig => Codec::Bls12381G2ShareMsig,
            Codec::Bls12381G1ShareMsig | Codec::Bls12381G2ShareMsig => {
                return Err(SharesError::IsASignatureShare.into())
            }
            _ => return Err(Error::UnsupportedAlgorithm(self.ms.codec.to_string())),
        };

        // current Multisig threshold data
        let threshold_data = {
            let av = self.ms.threshold_attr_view()?;
            match av.threshold_data() {
                Ok(b) => ThresholdData::try_from(b).unwrap_or_default(),
                Err(_) => ThresholdData::default(),
            }
        };

        // build the vec for the shares
        let mut shares = Vec::with_capacity(threshold_data.0.len());

        // build multisigs out of each share
        threshold_data
            .0
            .values()
            .try_for_each(|share| -> Result<(), Error> {
                let encoding = {
                    let av = self.ms.attr_view()?;
                    av.payload_encoding()?
                };
                // build a multisig share out of the share, preserve the message
                // and the payload encoding value
                let share = Builder::new(codec)
                    .with_message_bytes(&self.ms.message.as_slice())
                    .with_identifier(&share.0 .0.to_be_bytes())
                    .with_threshold(share.1)
                    .with_limit(share.2)
                    .with_signature_bytes(&share.4)
                    .with_payload_encoding(encoding)
                    .with_scheme(share.3.into())
                    .try_build()?;
                // add it to the list of shares
                shares.push(share);
                Ok(())
            })?;

        Ok(shares)
    }
    /// add a new share and return the Multisig with the share added
    fn add_share(&self, share: &Multisig) -> Result<Multisig, Error> {
        // check the codec is correct for this function
        match self.ms.codec {
            Codec::Bls12381G1Msig | Codec::Bls12381G2Msig => {}
            Codec::Bls12381G1ShareMsig | Codec::Bls12381G2ShareMsig => {
                return Err(SharesError::IsASignatureShare.into())
            }
            _ => return Err(Error::UnsupportedAlgorithm(self.ms.codec.to_string())),
        };

        let (sdata, identifier, threshold, limit, encoding) = {
            // get the scheme
            let av = share.attr_view()?;
            let scheme_type = SchemeTypeId::try_from(av.scheme()?)?;
            // get the share's attributes
            let av = share.threshold_attr_view()?;
            let threshold = av.threshold()?;
            let limit = av.limit()?;
            let identifier_bytes = av.identifier()?;
            if identifier_bytes.len() != 32 {
                return Err(Error::FailedConversion(
                    "Insufficient number of identifier bytes".to_string(),
                ));
            }
            let identifier_array = <[u8; 32]>::try_from(identifier_bytes)
                .map_err(|_| Error::FailedConversion("Incorrect identifier bytes".to_string()))?;
            let identifier = IdentifierPrimeField(
                Option::<Scalar>::from(Scalar::from_be_bytes(&identifier_array)).ok_or(
                    Error::FailedConversion("Incorrect identifier bytes".to_string()),
                )?,
            );

            // get the share's signature data
            let dv = share.data_view()?;
            let sig_bytes = dv.sig_bytes()?;

            let encoding = {
                let av = self.ms.attr_view()?;
                av.payload_encoding().ok()
            };

            // create the sig share tuple
            (
                SigShare(identifier, threshold, limit, scheme_type, sig_bytes),
                identifier,
                threshold,
                limit,
                encoding,
            )
        };

        // update the threshold data
        let threshold_data: Vec<u8> = {
            let av = self.ms.threshold_attr_view()?;
            let mut tdata = match av.threshold_data() {
                Ok(b) => ThresholdData::try_from(b).unwrap_or_default(),
                Err(_) => ThresholdData::default(),
            };
            // insert the share data into the list of shares
            tdata.0.insert(identifier, sdata);
            tdata.into()
        };

        // get the payload encoding
        let encoding = {
            let av = self.ms.attr_view()?;
            // if this multisig doesn't have payload encoding set, set it to
            // the value from the first share added
            match av.payload_encoding() {
                Ok(encoding) => Some(encoding),
                Err(_) => encoding,
            }
        };

        // if this multisig doesn't already have the threshold/limit set then
        // set it to match the values from the first share added
        let av = share.threshold_attr_view()?;
        let threshold = av.threshold().unwrap_or(threshold);
        let limit = av.limit().unwrap_or(limit);

        let builder = Builder::new(self.ms.codec)
            .with_message_bytes(&self.ms.message.as_slice())
            .with_threshold(threshold)
            .with_limit(limit)
            .with_threshold_data(&threshold_data);

        if let Some(encoding) = encoding {
            builder.with_payload_encoding(encoding).try_build()
        } else {
            builder.try_build()
        }
    }
    /// reconstruct the signature from the shares
    fn combine(&self) -> Result<Multisig, Error> {
        // current Multisig threshold data
        let threshold_data = {
            let av = self.ms.threshold_attr_view()?;
            match av.threshold_data() {
                Ok(b) => ThresholdData::try_from(b).unwrap_or_default(),
                Err(_) => ThresholdData::default(),
            }
        };

        // check that we have enough shares to combine
        let num_shares = threshold_data.0.len();
        let av = self.ms.threshold_attr_view()?;
        if num_shares < av.threshold()? {
            return Err(SharesError::NotEnoughShares.into());
        }

        match self.ms.codec {
            Codec::Bls12381G1Msig => {
                let mut share_type_id: Option<SchemeTypeId> = None;
                let mut shares = Vec::default();
                threshold_data
                    .0
                    .iter()
                    .try_for_each(|(id, share)| -> Result<(), Error> {
                        let bytes: [u8; 48] = share.4.as_slice().try_into().map_err(|_| {
                            Error::FailedConversion("Invalid signature share bytes".to_string())
                        })?;
                        let inner = Option::from(G1Projective::from_compressed(&bytes)).ok_or(
                            Error::FailedConversion("Invalid signature share bytes".to_string()),
                        )?;
                        let vsss = Share::with_identifier_and_value(*id, ValueGroup(inner));
                        // check to make sure all shares are of the same type
                        if let Some(sti) = share_type_id {
                            if sti != share.3 {
                                return Err(SharesError::ShareTypeMismatch.into());
                            }
                        } else {
                            share_type_id = Some(share.3);
                        }
                        let s = match share.3 {
                            SchemeTypeId::Basic => SignatureShare::<Bls12381G1Impl>::Basic(vsss),
                            SchemeTypeId::MessageAugmentation => {
                                SignatureShare::<Bls12381G1Impl>::MessageAugmentation(vsss)
                            }
                            SchemeTypeId::ProofOfPossession => {
                                SignatureShare::<Bls12381G1Impl>::ProofOfPossession(vsss)
                            }
                        };
                        shares.push(s);
                        Ok(())
                    })?;

                let sig = Signature::from_shares(shares.as_slice())
                    .map_err(|e| SharesError::ShareCombineFailed(e.to_string()))?;
                let encoding = {
                    let av = self.ms.attr_view()?;
                    av.payload_encoding()?
                };
                Builder::new_from_bls_signature(&sig)?
                    .with_message_bytes(&self.ms.message.as_slice())
                    .with_payload_encoding(encoding)
                    .try_build()
            }
            Codec::Bls12381G2Msig => {
                let mut share_type_id: Option<SchemeTypeId> = None;
                let mut shares = Vec::default();
                threshold_data
                    .0
                    .iter()
                    .try_for_each(|(id, share)| -> Result<(), Error> {
                        let bytes: [u8; 96] = share.4.as_slice().try_into().map_err(|_| {
                            Error::FailedConversion("Invalid signature share bytes".to_string())
                        })?;
                        let inner = Option::from(G2Projective::from_compressed(&bytes)).ok_or(
                            Error::FailedConversion("Invalid signature share bytes".to_string()),
                        )?;
                        let vsss = Share::with_identifier_and_value(*id, ValueGroup(inner));
                        // check to make sure all shares are of the same type
                        if let Some(sti) = share_type_id {
                            if sti != share.3 {
                                return Err(SharesError::ShareTypeMismatch.into());
                            }
                        } else {
                            share_type_id = Some(share.3);
                        }
                        let s = match share.3 {
                            SchemeTypeId::Basic => SignatureShare::<Bls12381G2Impl>::Basic(vsss),
                            SchemeTypeId::MessageAugmentation => {
                                SignatureShare::<Bls12381G2Impl>::MessageAugmentation(vsss)
                            }
                            SchemeTypeId::ProofOfPossession => {
                                SignatureShare::<Bls12381G2Impl>::ProofOfPossession(vsss)
                            }
                        };
                        shares.push(s);
                        Ok(())
                    })?;

                let sig = Signature::from_shares(shares.as_slice())
                    .map_err(|e| SharesError::ShareCombineFailed(e.to_string()))?;
                let encoding = {
                    let av = self.ms.attr_view()?;
                    av.payload_encoding().ok()
                };
                let builder = Builder::new_from_bls_signature(&sig)?
                    .with_message_bytes(&self.ms.message.as_slice());

                if let Some(encoding) = encoding {
                    builder.with_payload_encoding(encoding).try_build()
                } else {
                    builder.try_build()
                }
            }
            _ => Err(Error::UnsupportedAlgorithm(self.ms.codec.to_string())),
        }
    }

    /// Get shares with a specific disclosure mode applied.
    fn shares_with_disclosure(
        &self,
        mode: ThresholdDisclosure,
        meta_key: Option<&multi_key::Multikey>,
    ) -> Result<Vec<Multisig>, Error> {
        let shares = self.shares()?;
        shares
            .iter()
            .map(|s| {
                s.disclosure_view()?
                    .to_disclosure(mode, meta_key, None)
            })
            .collect()
    }

    /// Add a share with a meta_key for decrypting threshold params.
    fn add_share_with_meta(
        &self,
        share: &Multisig,
        meta_key: Option<&multi_key::Multikey>,
    ) -> Result<Multisig, Error> {
        let (share_t, share_n) =
            threshold_meta::read_threshold_params(share, meta_key)?;

        let (sdata, identifier, encoding) = {
            let av = share.attr_view()?;
            let scheme_type = SchemeTypeId::try_from(av.scheme()?)?;
            let tav = share.threshold_attr_view()?;
            let identifier_bytes = tav.identifier()?;
            if identifier_bytes.len() != 32 {
                return Err(Error::FailedConversion(
                    "Insufficient number of identifier bytes".to_string(),
                ));
            }
            let identifier_array = <[u8; 32]>::try_from(identifier_bytes)
                .map_err(|_| Error::FailedConversion("Incorrect identifier bytes".to_string()))?;
            let identifier = IdentifierPrimeField(
                Option::<Scalar>::from(Scalar::from_be_bytes(&identifier_array)).ok_or(
                    Error::FailedConversion("Incorrect identifier bytes".to_string()),
                )?,
            );
            let dv = share.data_view()?;
            let sig_bytes = dv.sig_bytes()?;
            let encoding = {
                let av = self.ms.attr_view()?;
                av.payload_encoding().ok()
            };
            (
                SigShare(identifier, share_t, share_n, scheme_type, sig_bytes),
                identifier,
                encoding,
            )
        };

        let threshold_data: Vec<u8> = {
            let av = self.ms.threshold_attr_view()?;
            let mut tdata = match av.threshold_data() {
                Ok(b) => ThresholdData::try_from(b)
                    .map_err(|e| SharesError::InvalidThresholdData(e.to_string()))?,
                Err(_) => ThresholdData::default(),
            };
            if tdata.0.contains_key(&identifier) {
                return Err(SharesError::DuplicateShare.into());
            }
            tdata.0.insert(identifier, sdata);
            tdata.into()
        };

        let encoding = {
            let av = self.ms.attr_view()?;
            match av.payload_encoding() {
                Ok(encoding) => Some(encoding),
                Err(_) => encoding,
            }
        };

        let builder = Builder::new(self.ms.codec)
            .with_message_bytes(&self.ms.message.as_slice())
            .with_threshold(share_t)
            .with_limit(share_n)
            .with_threshold_data(&threshold_data);

        if let Some(encoding) = encoding {
            builder.with_payload_encoding(encoding).try_build()
        } else {
            builder.try_build()
        }
    }

    /// Combine with a meta_key for decrypting threshold params.
    fn combine_with_meta(
        &self,
        meta_key: Option<&multi_key::Multikey>,
    ) -> Result<Multisig, Error> {
        let (threshold, _limit) =
            threshold_meta::read_threshold_params(self.ms, meta_key)?;

        let threshold_data = {
            let av = self.ms.threshold_attr_view()?;
            match av.threshold_data() {
                Ok(b) => ThresholdData::try_from(b)
                    .map_err(|e| SharesError::InvalidThresholdData(e.to_string()))?,
                Err(_) => ThresholdData::default(),
            }
        };

        let num_shares = threshold_data.0.len();
        if num_shares < threshold {
            return Err(SharesError::NotEnoughShares.into());
        }

        match self.ms.codec {
            Codec::Bls12381G1Msig => {
                let mut share_type_id: Option<SchemeTypeId> = None;
                let mut shares = Vec::default();
                threshold_data
                    .0
                    .iter()
                    .try_for_each(|(id, share)| -> Result<(), Error> {
                        let bytes: [u8; 48] = share.4.as_slice().try_into().map_err(|_| {
                            Error::FailedConversion("Invalid signature share bytes".to_string())
                        })?;
                        let inner = Option::from(G1Projective::from_compressed(&bytes)).ok_or(
                            Error::FailedConversion("Invalid signature share bytes".to_string()),
                        )?;
                        let vsss = Share::with_identifier_and_value(*id, ValueGroup(inner));
                        if let Some(sti) = share_type_id {
                            if sti != share.3 {
                                return Err(SharesError::ShareTypeMismatch.into());
                            }
                        } else {
                            share_type_id = Some(share.3);
                        }
                        let s = match share.3 {
                            SchemeTypeId::Basic => SignatureShare::<Bls12381G1Impl>::Basic(vsss),
                            SchemeTypeId::MessageAugmentation => {
                                SignatureShare::<Bls12381G1Impl>::MessageAugmentation(vsss)
                            }
                            SchemeTypeId::ProofOfPossession => {
                                SignatureShare::<Bls12381G1Impl>::ProofOfPossession(vsss)
                            }
                        };
                        shares.push(s);
                        Ok(())
                    })?;

                let sig = Signature::from_shares(shares.as_slice())
                    .map_err(|e| SharesError::ShareCombineFailed(e.to_string()))?;
                let encoding = {
                    let av = self.ms.attr_view()?;
                    av.payload_encoding()?
                };
                Builder::new_from_bls_signature(&sig)?
                    .with_message_bytes(&self.ms.message.as_slice())
                    .with_payload_encoding(encoding)
                    .try_build()
            }
            Codec::Bls12381G2Msig => {
                let mut share_type_id: Option<SchemeTypeId> = None;
                let mut shares = Vec::default();
                threshold_data
                    .0
                    .iter()
                    .try_for_each(|(id, share)| -> Result<(), Error> {
                        let bytes: [u8; 96] = share.4.as_slice().try_into().map_err(|_| {
                            Error::FailedConversion("Invalid signature share bytes".to_string())
                        })?;
                        let inner = Option::from(G2Projective::from_compressed(&bytes)).ok_or(
                            Error::FailedConversion("Invalid signature share bytes".to_string()),
                        )?;
                        let vsss = Share::with_identifier_and_value(*id, ValueGroup(inner));
                        if let Some(sti) = share_type_id {
                            if sti != share.3 {
                                return Err(SharesError::ShareTypeMismatch.into());
                            }
                        } else {
                            share_type_id = Some(share.3);
                        }
                        let s = match share.3 {
                            SchemeTypeId::Basic => SignatureShare::<Bls12381G2Impl>::Basic(vsss),
                            SchemeTypeId::MessageAugmentation => {
                                SignatureShare::<Bls12381G2Impl>::MessageAugmentation(vsss)
                            }
                            SchemeTypeId::ProofOfPossession => {
                                SignatureShare::<Bls12381G2Impl>::ProofOfPossession(vsss)
                            }
                        };
                        shares.push(s);
                        Ok(())
                    })?;

                let sig = Signature::from_shares(shares.as_slice())
                    .map_err(|e| SharesError::ShareCombineFailed(e.to_string()))?;
                let encoding = {
                    let av = self.ms.attr_view()?;
                    av.payload_encoding()?
                };
                Builder::new_from_bls_signature(&sig)?
                    .with_message_bytes(&self.ms.message.as_slice())
                    .with_payload_encoding(encoding)
                    .try_build()
            }
            _ => Err(Error::UnsupportedAlgorithm(self.ms.codec.to_string())),
        }
    }
}