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
use crate::{
    conversion::{adjust_with_num, b64_to_num},
    derivation_code::DerivationCode,
    error::Error,
    primitives::codes::self_signing::SelfSigning,
};
use core::str::FromStr;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Index {
    BothSame(u16),
    Dual(u16, u16),
    BigDual(u16, u16),
    CurrentOnly(u16),
    BigCurrentOnly(u16),
}
impl Index {
    pub fn current(&self) -> u16 {
        match self {
            Index::BothSame(i)
            | Index::Dual(i, _)
            | Index::BigDual(i, _)
            | Index::CurrentOnly(i)
            | Index::BigCurrentOnly(i) => *i,
        }
    }
    pub fn prev_next(&self) -> Option<u16> {
        match self {
            Index::BothSame(i) | Index::Dual(_, i) | Index::BigDual(_, i) => Some(*i),
            _ => None,
        }
    }
}
/// Attached Signature Derivation Codes
///
/// A self signing prefix derivation outputs a signature as its derivative (2.3.5)
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct AttachedSignatureCode {
    pub index: Index,
    pub code: SelfSigning,
}

impl AttachedSignatureCode {
    pub fn new(code: SelfSigning, index: Index) -> Self {
        Self { index, code }
    }

    pub fn new_from_ints(code: SelfSigning, current: u16, prev_next: Option<u16>) -> Self {
        let index = match prev_next {
            Some(i) => {
                if i == current {
                    Index::BothSame(i)
                } else {
                    Index::BigDual(current, i)
                }
            }
            None => Index::CurrentOnly(current),
        };
        Self { code, index }
    }
}

impl DerivationCode for AttachedSignatureCode {
    fn soft_size(&self) -> usize {
        match (self.code, self.index) {
            (SelfSigning::Ed25519Sha512, Index::BothSame(_)) => 1,
            (SelfSigning::Ed25519Sha512, Index::Dual(_, _))
            | (SelfSigning::Ed25519Sha512, Index::BigDual(_, _)) => 4,
            (SelfSigning::Ed25519Sha512, Index::CurrentOnly(_)) => 1,
            (SelfSigning::Ed25519Sha512, Index::BigCurrentOnly(_)) => 4,
            (SelfSigning::ECDSAsecp256k1Sha256, Index::BothSame(_)) => 1,
            (SelfSigning::ECDSAsecp256k1Sha256, Index::Dual(_, _)) => todo!(),
            (SelfSigning::ECDSAsecp256k1Sha256, Index::BigDual(_, _)) => 4,
            (SelfSigning::ECDSAsecp256k1Sha256, Index::CurrentOnly(_)) => 1,
            (SelfSigning::ECDSAsecp256k1Sha256, Index::BigCurrentOnly(_)) => 4,
            (SelfSigning::Ed448, Index::Dual(_, _)) => 2,
            (SelfSigning::Ed448, Index::BigDual(_, _)) => 6,
            (SelfSigning::Ed448, Index::CurrentOnly(_)) => 2,
            (SelfSigning::Ed448, Index::BigCurrentOnly(_)) => 6,
            _ => todo!(),
        }
    }

    fn hard_size(&self) -> usize {
        match (self.code, self.index) {
            (SelfSigning::Ed25519Sha512, Index::BothSame(_)) => 1,
            (SelfSigning::Ed25519Sha512, Index::Dual(_, _)) => todo!(),
            (SelfSigning::Ed25519Sha512, Index::BigDual(_, _)) => 2,
            (SelfSigning::Ed25519Sha512, Index::CurrentOnly(_)) => 1,
            (SelfSigning::Ed25519Sha512, Index::BigCurrentOnly(_)) => 2,
            (SelfSigning::ECDSAsecp256k1Sha256, Index::BothSame(_)) => 1,
            (SelfSigning::ECDSAsecp256k1Sha256, Index::Dual(_, _)) => todo!(),
            (SelfSigning::ECDSAsecp256k1Sha256, Index::BigDual(_, _)) => 2,
            (SelfSigning::ECDSAsecp256k1Sha256, Index::CurrentOnly(_)) => 1,
            (SelfSigning::ECDSAsecp256k1Sha256, Index::BigCurrentOnly(_)) => 2,
            (SelfSigning::Ed448, Index::BothSame(_)) => todo!(),
            (SelfSigning::Ed448, Index::Dual(_, _)) => 2,
            (SelfSigning::Ed448, Index::BigDual(_, _)) => 2,
            (SelfSigning::Ed448, Index::CurrentOnly(_)) => 2,
            (SelfSigning::Ed448, Index::BigCurrentOnly(_)) => 2,
        }
    }

    fn value_size(&self) -> usize {
        match (self.code, self.index) {
            (SelfSigning::Ed25519Sha512, _) => 86,
            (SelfSigning::ECDSAsecp256k1Sha256, _) => 86,
            (SelfSigning::Ed448, _) => 152,
        }
    }

    fn to_str(&self) -> String {
        let code = match (self.code, self.index) {
            (SelfSigning::Ed25519Sha512, Index::BothSame(_)) => "A",
            (SelfSigning::Ed25519Sha512, Index::Dual(_, _))
            | (SelfSigning::Ed25519Sha512, Index::BigDual(_, _)) => "2A",
            (SelfSigning::Ed25519Sha512, Index::CurrentOnly(_)) => "B",
            (SelfSigning::Ed25519Sha512, Index::BigCurrentOnly(_)) => "2B",
            (SelfSigning::ECDSAsecp256k1Sha256, Index::BothSame(_)) => "C",
            (SelfSigning::ECDSAsecp256k1Sha256, Index::Dual(_, _)) => "D",
            (SelfSigning::ECDSAsecp256k1Sha256, Index::BigDual(_, _)) => "2C",
            (SelfSigning::ECDSAsecp256k1Sha256, Index::CurrentOnly(_)) => todo!(),
            (SelfSigning::ECDSAsecp256k1Sha256, Index::BigCurrentOnly(_)) => "2D",
            (SelfSigning::Ed448, Index::BothSame(_)) => todo!(),
            (SelfSigning::Ed448, Index::Dual(_, _)) => "0A",
            (SelfSigning::Ed448, Index::BigDual(_, _)) => "2C",
            (SelfSigning::Ed448, Index::CurrentOnly(_)) => "0B",
            (SelfSigning::Ed448, Index::BigCurrentOnly(_)) => "2D",
        };
        let indexes_str = match self.index {
            Index::BothSame(i) | Index::CurrentOnly(i) | Index::BigCurrentOnly(i) => {
                adjust_with_num(i, self.soft_size())
            }
            Index::Dual(i, pi) | Index::BigDual(i, pi) => [
                adjust_with_num(i, self.soft_size() / 2),
                adjust_with_num(pi, self.soft_size() / 2),
            ]
            .join(""),
        };
        [code, &indexes_str].join("")
    }
}

impl FromStr for AttachedSignatureCode {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match &s[..1] {
            "A" => Ok(Self::new(
                SelfSigning::Ed25519Sha512,
                Index::BothSame(b64_to_num(&s.as_bytes()[1..2])?),
            )),
            "B" => Ok(Self::new(
                SelfSigning::Ed25519Sha512,
                Index::CurrentOnly(b64_to_num(&s.as_bytes()[1..2])?),
            )),
            "C" => Ok(Self::new(
                SelfSigning::ECDSAsecp256k1Sha256,
                Index::BothSame(b64_to_num(&s.as_bytes()[1..2])?),
            )),
            "D" => Ok(Self::new(
                SelfSigning::ECDSAsecp256k1Sha256,
                Index::CurrentOnly(b64_to_num(&s.as_bytes()[1..2])?),
            )),
            "0" => match &s[1..2] {
                "A" => Ok(Self::new(
                    SelfSigning::Ed448,
                    Index::Dual(
                        b64_to_num(&s.as_bytes()[2..3])?,
                        b64_to_num(&s.as_bytes()[3..4])?,
                    ),
                )),
                "B" => Ok(Self::new(
                    SelfSigning::Ed448,
                    Index::CurrentOnly(b64_to_num(&s.as_bytes()[2..4])?),
                )),
                _ => Err(Error::UnknownCodeError),
            },
            "2" => match &s[1..2] {
                "A" => Ok(Self::new(
                    SelfSigning::Ed25519Sha512,
                    Index::BigDual(
                        b64_to_num(&s.as_bytes()[2..4])?,
                        b64_to_num(&s.as_bytes()[4..6])?,
                    ),
                )),
                "B" => {
                    if b64_to_num(&s.as_bytes()[4..6])? == 0 {
                        Ok(Self::new(
                            SelfSigning::Ed25519Sha512,
                            Index::BigCurrentOnly(b64_to_num(&s.as_bytes()[2..4])?),
                        ))
                    } else {
                        Err(Error::EmptyCodeError)
                    }
                }
                "C" => Ok(Self::new(
                    SelfSigning::ECDSAsecp256k1Sha256,
                    Index::BigDual(
                        b64_to_num(&s.as_bytes()[2..4])?,
                        b64_to_num(&s.as_bytes()[4..6])?,
                    ),
                )),
                "D" => Ok(Self::new(
                    SelfSigning::ECDSAsecp256k1Sha256,
                    Index::BigCurrentOnly(b64_to_num(&s.as_bytes()[2..6])?),
                )),
                _ => Err(Error::UnknownCodeError),
            },
            "3" => match &s[1..2] {
                "A" => Ok(Self::new(
                    SelfSigning::Ed448,
                    Index::BothSame(b64_to_num(&s.as_bytes()[2..6])?),
                )),
                "B" => Ok(Self::new(
                    SelfSigning::Ed448,
                    Index::CurrentOnly(b64_to_num(&s.as_bytes()[2..10])?),
                )),
                _ => Err(Error::UnknownCodeError),
            },
            _ => Err(Error::UnknownCodeError),
        }
    }
}

#[test]
pub fn test() {
    let code = "2AADAC";
    let c: AttachedSignatureCode = code.parse().unwrap();
    assert_eq!(code, c.to_str());

    let code = "2AAAAB";
    let c: AttachedSignatureCode = code.parse().unwrap();
    assert_eq!(code, c.to_str());
}