chik-base 0.1.7__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. chik_base-0.1.7/LICENSE +201 -0
  2. chik_base-0.1.7/PKG-INFO +12 -0
  3. chik_base-0.1.7/README.md +1 -0
  4. chik_base-0.1.7/chik_base/__init__.py +0 -0
  5. chik_base-0.1.7/chik_base/atoms/__init__.py +27 -0
  6. chik_base-0.1.7/chik_base/atoms/hexbytes.py +11 -0
  7. chik_base-0.1.7/chik_base/atoms/ints.py +59 -0
  8. chik_base-0.1.7/chik_base/atoms/sized_bytes.py +43 -0
  9. chik_base-0.1.7/chik_base/atoms/struct_stream.py +24 -0
  10. chik_base-0.1.7/chik_base/bls12_381/__init__.py +11 -0
  11. chik_base-0.1.7/chik_base/bls12_381/bls_public_key.py +129 -0
  12. chik_base-0.1.7/chik_base/bls12_381/bls_secret_exponent.py +138 -0
  13. chik_base-0.1.7/chik_base/bls12_381/bls_signature.py +81 -0
  14. chik_base-0.1.7/chik_base/bls12_381/secret_key_utils.py +24 -0
  15. chik_base-0.1.7/chik_base/cbincode/__init__.py +43 -0
  16. chik_base-0.1.7/chik_base/cbincode/parser.py +163 -0
  17. chik_base-0.1.7/chik_base/cbincode/streamer.py +190 -0
  18. chik_base-0.1.7/chik_base/cbincode/util.py +29 -0
  19. chik_base-0.1.7/chik_base/contrib/__init__.py +0 -0
  20. chik_base-0.1.7/chik_base/contrib/bech32m.py +150 -0
  21. chik_base-0.1.7/chik_base/core/__init__.py +6 -0
  22. chik_base-0.1.7/chik_base/core/coin.py +24 -0
  23. chik_base-0.1.7/chik_base/core/coin_spend.py +17 -0
  24. chik_base-0.1.7/chik_base/core/conlang.py +41 -0
  25. chik_base-0.1.7/chik_base/core/spend_bundle.py +25 -0
  26. chik_base-0.1.7/chik_base/meta/__init__.py +0 -0
  27. chik_base-0.1.7/chik_base/meta/optional.py +16 -0
  28. chik_base-0.1.7/chik_base/meta/type_tree.py +70 -0
  29. chik_base-0.1.7/chik_base/meta/typing.py +17 -0
  30. chik_base-0.1.7/chik_base/py.typed +0 -0
  31. chik_base-0.1.7/chik_base/util/__init__.py +0 -0
  32. chik_base-0.1.7/chik_base/util/bech32.py +30 -0
  33. chik_base-0.1.7/chik_base/util/std_hash.py +13 -0
  34. chik_base-0.1.7/chik_base.egg-info/PKG-INFO +12 -0
  35. chik_base-0.1.7/chik_base.egg-info/SOURCES.txt +42 -0
  36. chik_base-0.1.7/chik_base.egg-info/dependency_links.txt +1 -0
  37. chik_base-0.1.7/chik_base.egg-info/requires.txt +7 -0
  38. chik_base-0.1.7/chik_base.egg-info/top_level.txt +1 -0
  39. chik_base-0.1.7/pyproject.toml +26 -0
  40. chik_base-0.1.7/setup.cfg +4 -0
  41. chik_base-0.1.7/setup.py +7 -0
  42. chik_base-0.1.7/tests/test_bls.py +166 -0
  43. chik_base-0.1.7/tests/test_core.py +118 -0
  44. chik_base-0.1.7/tests/test_streamable.py +182 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022 Chik Network Inc
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.1
2
+ Name: chik_base
3
+ Version: 0.1.7
4
+ Summary: Common types and simple utilities used through chik code base
5
+ Author-email: Richard Kiss <him@richardkiss.com>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/Chik-Network/chik_base.git
8
+ Description-Content-Type: text/markdown
9
+ Provides-Extra: dev
10
+ License-File: LICENSE
11
+
12
+ chik_base: base data types for chik coins, spends and contract development
@@ -0,0 +1 @@
1
+ chik_base: base data types for chik coins, spends and contract development
File without changes
@@ -0,0 +1,27 @@
1
+ """
2
+ This module defines some useful atomic types for building more complex
3
+ data structures.
4
+
5
+ Except for `hexbytes` (which is just a hex-printing subclass of `bytes`,
6
+ these types are all fixed-sized, simplifying serializing and parsing, like
7
+ those used in `cbincode` (the slight modification to the `bincode` standard that
8
+ chik uses).
9
+ """
10
+
11
+ from .hexbytes import hexbytes
12
+ from .ints import int8, uint8, int16, uint16, int32, uint32, int64, uint64
13
+ from .sized_bytes import bytes32
14
+
15
+
16
+ __all__ = [
17
+ "int8",
18
+ "int16",
19
+ "int32",
20
+ "int64",
21
+ "uint8",
22
+ "uint16",
23
+ "uint32",
24
+ "uint64",
25
+ "hexbytes",
26
+ "bytes32",
27
+ ]
@@ -0,0 +1,11 @@
1
+ class hexbytes(bytes):
2
+ """
3
+ This is a subclass of bytes that prints itself out as hex,
4
+ which is much easier on the eyes for binary data that is very non-ascii .
5
+ """
6
+
7
+ def __str__(self):
8
+ return self.hex()
9
+
10
+ def __repr__(self):
11
+ return "<%s: %s>" % (self.__class__.__name__, str(self))
@@ -0,0 +1,59 @@
1
+ """
2
+ Some ints of fixed size. Their fixed size makes them easier to parse and serialize.
3
+
4
+ Each implements these two class methods:
5
+
6
+ * `.parse(f: BinaryIO)`
7
+ * `._class_stream(obj, f: BinaryIO)`
8
+
9
+ """
10
+
11
+ from .struct_stream import struct_stream
12
+
13
+
14
+ class int8(int, struct_stream):
15
+ "signed 8-bit int"
16
+
17
+ PACK = "!b"
18
+
19
+
20
+ class uint8(int, struct_stream):
21
+ "unsigned 8-bit int"
22
+
23
+ PACK = "!B"
24
+
25
+
26
+ class int16(int, struct_stream):
27
+ "signed 16-bit int"
28
+
29
+ PACK = "!h"
30
+
31
+
32
+ class uint16(int, struct_stream):
33
+ "unsigned 16-bit int"
34
+
35
+ PACK = "!H"
36
+
37
+
38
+ class int32(int, struct_stream):
39
+ "signed 32-bit int"
40
+
41
+ PACK = "!l"
42
+
43
+
44
+ class uint32(int, struct_stream):
45
+ "unsigned 32-bit int"
46
+
47
+ PACK = "!L"
48
+
49
+
50
+ class int64(int, struct_stream):
51
+ "signed 64-bit int"
52
+
53
+ PACK = "!q"
54
+
55
+
56
+ class uint64(int, struct_stream):
57
+ "unsigned 64-bit int"
58
+
59
+ PACK = "!Q"
@@ -0,0 +1,43 @@
1
+ from typing import BinaryIO
2
+ from .hexbytes import hexbytes
3
+
4
+
5
+ class SizedBytes(hexbytes):
6
+ """
7
+ Intended to be subclassed, this base class makes it easy to create
8
+ subclasses of `bytes` that require the length to be a specific value.
9
+
10
+ Having a specific number of bytes means we can easily parse and stream
11
+ """
12
+
13
+ _size: int
14
+
15
+ def __new__(cls, v):
16
+ "`v` must be castable to `bytes`"
17
+ v = bytes(v)
18
+ if not isinstance(v, bytes) or len(v) != cls._size:
19
+ raise ValueError("bad %s initializer %s" % (cls.__name__, v))
20
+ return hexbytes.__new__(cls, v)
21
+
22
+ @classmethod
23
+ def parse(cls, f: BinaryIO) -> bytes:
24
+ b = f.read(cls._size)
25
+ if len(b) != cls._size:
26
+ msg = f"unexpected EOS: {len(b)} bytes read, {cls._size} expected"
27
+ raise ValueError(msg)
28
+ return cls(b)
29
+
30
+ @classmethod
31
+ def _class_stream(cls, obj: bytes, f: BinaryIO) -> None:
32
+ if len(obj) != cls._size:
33
+ msg = f"got {len(obj)} bytes when we expected {cls._size}"
34
+ raise ValueError(msg)
35
+ f.write(obj)
36
+
37
+
38
+ class bytes32(SizedBytes):
39
+ """
40
+ A subclass of `bytes` that requires the length to be 32.
41
+ """
42
+
43
+ _size = 32
@@ -0,0 +1,24 @@
1
+ import struct
2
+
3
+ from typing import BinaryIO, TypeVar, Type
4
+
5
+
6
+ _T = TypeVar("_T", bound="struct_stream")
7
+
8
+
9
+ class struct_stream:
10
+ """
11
+ This is a base class. Subclasses should define `cls.PACK` as a struct.pack
12
+ template string. In return, you get implementations of `parse` and
13
+ `_class_stream`.
14
+ """
15
+
16
+ PACK: str
17
+
18
+ @classmethod
19
+ def parse(cls: Type[_T], f: BinaryIO) -> _T:
20
+ return cls(*struct.unpack(cls.PACK, f.read(struct.calcsize(cls.PACK))))
21
+
22
+ @classmethod
23
+ def _class_stream(cls: Type[_T], obj: _T, f: BinaryIO) -> None:
24
+ f.write(struct.pack(cls.PACK, obj))
@@ -0,0 +1,11 @@
1
+ """
2
+ The `chik_rs` wheel has some rough edges in its api. This module smooths them over
3
+ with a more ergonomic api.
4
+ """
5
+
6
+ from .bls_public_key import BLSPublicKey
7
+ from .bls_secret_exponent import BLSSecretExponent
8
+ from .bls_signature import BLSSignature
9
+
10
+
11
+ __all__ = ["BLSPublicKey", "BLSSecretExponent", "BLSSignature"]
@@ -0,0 +1,129 @@
1
+ from typing import BinaryIO, List
2
+
3
+ import chik_rs # type: ignore
4
+
5
+ from chik_base.atoms import hexbytes
6
+ from chik_base.util.bech32 import bech32_decode, bech32_encode, Encoding
7
+
8
+ from .secret_key_utils import public_key_from_int
9
+
10
+ BECH32M_PUBLIC_KEY_PREFIX = "bls1238"
11
+
12
+
13
+ class BLSPublicKey:
14
+ """
15
+ This corresponds to an element in bls12-381's G1 group, represented
16
+ when serialized by a 48-byte x element (with a few extra bits at the
17
+ beginning for metadata).
18
+ """
19
+ def __init__(self, g1: chik_rs.G1Element):
20
+ assert isinstance(g1, chik_rs.G1Element)
21
+ self._g1 = g1
22
+
23
+ @classmethod
24
+ def from_bytes(cls, blob):
25
+ "parse from a binary blob"
26
+ bls_public_hd_key = chik_rs.G1Element.from_bytes(blob)
27
+ return BLSPublicKey(bls_public_hd_key)
28
+
29
+ @classmethod
30
+ def parse(cls, f: BinaryIO):
31
+ "parse from a stream"
32
+ return cls.from_bytes(f.read(48))
33
+
34
+ @classmethod
35
+ def generator(cls):
36
+ "return the well-known generator"
37
+ return BLSPublicKey(chik_rs.G1Element.generator())
38
+
39
+ @classmethod
40
+ def zero(cls):
41
+ "return the well-known zero"
42
+ return cls(chik_rs.G1Element())
43
+
44
+ def stream(self, f: BinaryIO) -> None:
45
+ "write the serialized version to the file f"
46
+ f.write(bytes(self._g1))
47
+
48
+ def __add__(self, other):
49
+ "add two elements, returning the sum. Use `+`"
50
+ return BLSPublicKey(self._g1 + other._g1)
51
+
52
+ def __mul__(self, other: int):
53
+ "multiply an element by a scalar"
54
+ if other < 0:
55
+ raise ValueError("can't multiply by a negative value")
56
+ if self == self.generator():
57
+ # there is a special method in chik_rs that multiplies
58
+ # the generator by an integer that is not susceptible to
59
+ # timing attacks. Since public keys are generate times integer,
60
+ # using this method with the generator could expose to timing
61
+ # attacks. So instead we use the more clever code specifically
62
+ # for the generator
63
+ return BLSPublicKey(public_key_from_int(other))
64
+ if other == 0:
65
+ return self.zero()
66
+ if other == 1:
67
+ return self
68
+ # use recursion on `__mul__` in a sneaky clever way
69
+ parity = other & 1
70
+ v = self.__mul__(other >> 1)
71
+ v += v
72
+ if parity:
73
+ v += self
74
+ return v
75
+
76
+ def __rmul__(self, other: int):
77
+ return self.__mul__(other)
78
+
79
+ def __eq__(self, other):
80
+ if isinstance(other, type(self)):
81
+ return self._g1 == other._g1
82
+ return False
83
+
84
+ def __bytes__(self) -> bytes:
85
+ return hexbytes(self._g1)
86
+
87
+ def child(self, index: int) -> "BLSPublicKey":
88
+ "unhardened child derivation"
89
+ return BLSPublicKey(
90
+ chik_rs.AugSchemeMPL.derive_child_pk_unhardened(self._g1, index)
91
+ )
92
+
93
+ def child_for_path(self, path: List[int]) -> "BLSPublicKey":
94
+ "A path is a list of child integer derivations"
95
+ r = self
96
+ for index in path:
97
+ r = r.child(index)
98
+ return r
99
+
100
+ def fingerprint(self) -> int:
101
+ "return a 32-bit unsigned integer"
102
+ return self._g1.get_fingerprint()
103
+
104
+ def as_bech32m(self) -> str:
105
+ "convert to a bech32m string"
106
+ return bech32_encode(BECH32M_PUBLIC_KEY_PREFIX, bytes(self), Encoding.BECH32M)
107
+
108
+ @classmethod
109
+ def from_bech32m(cls, text: str) -> "BLSPublicKey":
110
+ "convert from a bech32m string"
111
+ r = bech32_decode(text, max_length=91)
112
+ if r is not None:
113
+ prefix, base8_data, encoding = r
114
+ if (
115
+ encoding == Encoding.BECH32M
116
+ and prefix == BECH32M_PUBLIC_KEY_PREFIX
117
+ and len(base8_data) == 49
118
+ ):
119
+ return cls.from_bytes(base8_data[:48])
120
+ raise ValueError("not bls12_381 bech32m pubkey")
121
+
122
+ def __hash__(self):
123
+ return bytes(self).__hash__()
124
+
125
+ def __str__(self):
126
+ return self.as_bech32m()
127
+
128
+ def __repr__(self):
129
+ return "<%s: %s>" % (self.__class__.__name__, self)
@@ -0,0 +1,138 @@
1
+ from typing import BinaryIO, List, Optional
2
+
3
+ import chik_rs # type: ignore
4
+
5
+ from chik_base.util.bech32 import bech32_decode, bech32_encode, Encoding
6
+
7
+ from .bls_public_key import BLSPublicKey
8
+ from .bls_signature import BLSSignature
9
+ from .secret_key_utils import private_key_from_int
10
+
11
+
12
+ BECH32M_SECRET_EXPONENT_PREFIX = "se"
13
+
14
+
15
+ class BLSSecretExponent:
16
+ """
17
+ This is essentially an `int` with convenience functions.
18
+
19
+ We don't subclass `int` because we have a different implementation of
20
+ `__bytes__` which could cause confusion.
21
+ """
22
+
23
+ def __init__(self, sk: chik_rs.PrivateKey):
24
+ self._sk = sk
25
+
26
+ @classmethod
27
+ def from_seed(cls, seed: bytes) -> "BLSSecretExponent":
28
+ """
29
+ convert from a seed using the specification at
30
+ https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-05
31
+ """
32
+ return BLSSecretExponent(chik_rs.AugSchemeMPL.key_gen(seed))
33
+
34
+ @classmethod
35
+ def from_int(cls, secret_exponent) -> "BLSSecretExponent":
36
+ "convert from the given int"
37
+ return cls(private_key_from_int(secret_exponent))
38
+
39
+ @classmethod
40
+ def from_bytes(cls, blob) -> "BLSSecretExponent":
41
+ "deserialize from the given blob. A blob of length 32 bytes is expected"
42
+ return cls(chik_rs.PrivateKey.from_bytes(blob))
43
+
44
+ @classmethod
45
+ def parse(cls, f: BinaryIO):
46
+ "deserialize from the given stream"
47
+ return cls.from_bytes(f.read(32))
48
+
49
+ def stream(self, f: BinaryIO) -> None:
50
+ "serialize to the given stream"
51
+ f.write(bytes(self._sk))
52
+
53
+ def fingerprint(self) -> int:
54
+ "return a 32-bit unsigned integer. The public key fingerprint will match."
55
+ return self._sk.get_g1().get_fingerprint()
56
+
57
+ def sign(
58
+ self, message: bytes, final_public_key: Optional[BLSPublicKey] = None
59
+ ) -> BLSSignature:
60
+ "generate a signature"
61
+ if final_public_key:
62
+ return BLSSignature(
63
+ chik_rs.AugSchemeMPL.sign(self._sk, message, final_public_key._g1)
64
+ )
65
+ return BLSSignature(chik_rs.AugSchemeMPL.sign(self._sk, message))
66
+
67
+ def public_key(self) -> BLSPublicKey:
68
+ "return the corresponding public key"
69
+ return BLSPublicKey(self._sk.get_g1())
70
+
71
+ def secret_exponent(self) -> int:
72
+ "return the exponent as an `int`"
73
+ return int.from_bytes(bytes(self), "big")
74
+
75
+ def hardened_child(self, index: int) -> "BLSSecretExponent":
76
+ "return the hardened child"
77
+ return BLSSecretExponent(chik_rs.AugSchemeMPL.derive_child_sk(self._sk, index))
78
+
79
+ def child(self, index: int) -> "BLSSecretExponent":
80
+ "return the unhardened child. This will match the corresponding public_key child"
81
+ return BLSSecretExponent(
82
+ chik_rs.AugSchemeMPL.derive_child_sk_unhardened(self._sk, index)
83
+ )
84
+
85
+ def child_for_path(self, path: List[int]) -> "BLSSecretExponent":
86
+ "A path is a list of child integer derivations. Unhardened only"
87
+ r = self
88
+ for index in path:
89
+ r = r.child(index)
90
+ return r
91
+
92
+ def as_bech32m(self):
93
+ "convert to a bech32m string"
94
+ return bech32_encode(
95
+ BECH32M_SECRET_EXPONENT_PREFIX, bytes(self), Encoding.BECH32M
96
+ )
97
+
98
+ @classmethod
99
+ def from_bech32m(cls, text: str) -> "BLSSecretExponent":
100
+ "convert from a bech32m string"
101
+ r = bech32_decode(text)
102
+ if r is not None:
103
+ prefix, base8_data, encoding = r
104
+ if (
105
+ encoding == Encoding.BECH32M
106
+ and prefix == BECH32M_SECRET_EXPONENT_PREFIX
107
+ and len(base8_data) == 33
108
+ ):
109
+ return cls.from_bytes(base8_data[:32])
110
+ raise ValueError("not secret exponent")
111
+
112
+ @classmethod
113
+ def zero(cls) -> "BLSSecretExponent":
114
+ "returns the secret exponent corresponding to 0. This shouldn't be used to sign"
115
+ return ZERO
116
+
117
+ def __add__(self, other):
118
+ return self.from_int(int(self) + int(other))
119
+
120
+ def __int__(self):
121
+ return self.secret_exponent()
122
+
123
+ def __eq__(self, other):
124
+ if isinstance(other, int):
125
+ other = BLSSecretExponent.from_int(other)
126
+ return self._sk == other._sk
127
+
128
+ def __bytes__(self):
129
+ return bytes(self._sk)
130
+
131
+ def __str__(self):
132
+ return "<prv for:%s>" % self.public_key()
133
+
134
+ def __repr__(self):
135
+ return "<%s: %s>" % (self.__class__.__name__, self)
136
+
137
+
138
+ ZERO = BLSSecretExponent.from_int(0)