File: heads.py

package info (click to toggle)
python-duniterpy 1.1.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,228 kB
  • sloc: python: 10,624; makefile: 182; sh: 17
file content (220 lines) | stat: -rw-r--r-- 6,871 bytes parent folder | download | duplicates (2)
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
# Copyright  2014-2022 Vincent Texier <vit@free.fr>
#
# DuniterPy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DuniterPy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import re

import attr

from ...constants import (
    BLOCK_ID_REGEX,
    PUBKEY_REGEX,
    SIGNATURE_REGEX,
    WS2P_HEAD_REGEX,
    WS2P_PRIVATE_PREFIX_REGEX,
    WS2P_PUBLIC_PREFIX_REGEX,
    WS2PID_REGEX,
)
from ...key import VerifyingKey
from ..block_id import BlockID
from ..document import MalformedDocumentError


@attr.s()
class API:
    private = attr.ib(type=str)
    public = attr.ib(type=str)

    re_inline = re.compile(
        f"WS2P({WS2P_PRIVATE_PREFIX_REGEX})?({WS2P_PUBLIC_PREFIX_REGEX})?"
    )

    @classmethod
    def from_inline(cls, inline: str):
        data = API.re_inline.match(inline)
        if data is None:
            raise MalformedDocumentError("WS2P API Document")
        private = "" if data.group(1) is None else data.group(1)
        public = "" if data.group(2) is None else data.group(2)
        return cls(private, public)

    def __str__(self) -> str:
        return f"WS2P{self.private}{self.public}"


@attr.s()
class Head:
    version = attr.ib(type=int)

    re_inline = re.compile(WS2P_HEAD_REGEX)

    @classmethod
    def from_inline(cls, inline: str, signature: str):
        try:
            data = Head.re_inline.match(inline)
            if data is None:
                raise MalformedDocumentError("Head")
            head = data.group(0).split(":")
            version = int(head[1]) if len(head) == 2 else 0
            return cls(version)
        except AttributeError:
            raise MalformedDocumentError("Head") from AttributeError

    def __str__(self) -> str:
        return "HEAD" if self.version == 0 else f"HEAD:{str(self.version)}"


@attr.s()
class HeadV0(Head):
    signature = attr.ib(type=str)
    api = attr.ib(type=API)
    head = attr.ib(type=Head)
    pubkey = attr.ib(type=str)
    block_id = attr.ib(type=BlockID)

    re_inline = re.compile(
        f"^(WS2P(?:{WS2P_PRIVATE_PREFIX_REGEX})?(?:{WS2P_PUBLIC_PREFIX_REGEX})?):\
({WS2P_HEAD_REGEX}):({PUBKEY_REGEX}):({BLOCK_ID_REGEX})(?::)?(.*)"
    )

    re_signature = re.compile(SIGNATURE_REGEX)

    @classmethod
    def from_inline(cls, inline: str, signature: str):
        try:
            data = HeadV0.re_inline.match(inline)
            if data is None:
                raise MalformedDocumentError("HeadV0")
            api = API.from_inline(data.group(1))
            head = Head.from_inline(data.group(2), "")
            pubkey = data.group(3)
            block_id = BlockID.from_str(data.group(4))
            offload = data.group(5)
            return cls(head.version, signature, api, head, pubkey, block_id), offload
        except AttributeError:
            raise MalformedDocumentError("HeadV0") from AttributeError

    def inline(self) -> str:
        values = (
            str(v)
            for v in attr.astuple(
                self,
                recurse=False,
                filter=attr.filters.exclude(
                    attr.fields(HeadV0).version,
                    attr.fields(HeadV0).signature,
                    attr.fields(HeadV0).api,
                ),
            )
        )
        return f'{str(self.api)}:{":".join(values)}'

    def check_signature(self, pubkey: str) -> bool:
        """
        Check if Head signature is from head pubkey

        :param pubkey: Pubkey to check signature upon
        :return:
        """
        verifying_key = VerifyingKey(pubkey)

        return verifying_key.check_signature(self.inline(), self.signature)


@attr.s()
class HeadV1(HeadV0):
    ws2pid = attr.ib(type=str)
    software = attr.ib(type=str)
    software_version = attr.ib(type=str)
    pow_prefix = attr.ib(type=int)

    re_inline = re.compile(
        "({ws2pid}):({software}):({software_version}):({pow_prefix})(?::)?(.*)".format(
            ws2pid=WS2PID_REGEX,
            software="[A-Za-z-_]+",
            software_version="[0-9]+[.][0-9]+[.][0-9]+[-\\w]*",
            pow_prefix="[0-9]+",
        )
    )

    @classmethod
    def from_inline(cls, inline: str, signature: str):
        try:
            v0, offload = HeadV0.from_inline(inline, signature)
            data = HeadV1.re_inline.match(offload)
            if data is None:
                raise MalformedDocumentError("HeadV1")
            ws2pid = data.group(1)
            software = data.group(2)
            software_version = data.group(3)
            pow_prefix = int(data.group(4))
            offload = data.group(5)
            return (
                cls(
                    v0.version,
                    v0.signature,
                    v0.api,
                    v0.head,
                    v0.pubkey,
                    v0.block_id,
                    ws2pid,
                    software,
                    software_version,
                    pow_prefix,
                ),
                offload,
            )
        except AttributeError:
            raise MalformedDocumentError("HeadV1") from AttributeError


@attr.s
class HeadV2(HeadV1):
    free_member_room = attr.ib(type=int)
    free_mirror_room = attr.ib(type=int)

    re_inline = re.compile(
        "({free_member_room}):({free_mirror_room})(?::)?(.*)".format(
            free_member_room="[0-9]+", free_mirror_room="[0-9]+"
        )
    )

    @classmethod
    def from_inline(cls, inline: str, signature: str):
        try:
            v1, offload = HeadV1.from_inline(inline, signature)
            data = HeadV2.re_inline.match(offload)
            if data is None:
                raise MalformedDocumentError("HeadV2")
            free_member_room = int(data.group(1))
            free_mirror_room = int(data.group(2))
            return (
                cls(
                    v1.version,
                    v1.signature,
                    v1.api,
                    v1.head,
                    v1.pubkey,
                    v1.block_id,
                    v1.ws2pid,
                    v1.software,
                    v1.software_version,
                    v1.pow_prefix,
                    free_member_room,
                    free_mirror_room,
                ),
                "",
            )
        except AttributeError:
            raise MalformedDocumentError("HeadV2") from AttributeError