bipsea 0.1__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.
bipsea-0.1/LICENSE.md ADDED
@@ -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 [yyyy] [name of copyright owner]
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.
bipsea-0.1/PKG-INFO ADDED
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.1
2
+ Name: bipsea
3
+ Version: 0.1
4
+ Summary: Python implementation of BIP 85 (and BIP 32)
5
+ Author: Aneesh Karve
6
+ Author-email: bonded_metals_0u@icloud.com
7
+ Project-URL: Source, https://github.com/akarve/bipsea
8
+ Keywords: Bitcoin BIP85 BIP32 cryptography
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ License-File: LICENSE.md
16
+ Requires-Dist: click
17
+ Requires-Dist: base58
18
+ Requires-Dist: ecdsa
19
+ Requires-Dist: pytest
bipsea-0.1/README.md ADDED
@@ -0,0 +1,243 @@
1
+ # `bipsea`: unlimited cryptographic entropy for Bitcoin, passwords, and other secrets
2
+
3
+ > _One Seed to rule them all,
4
+ > One Key to find them,
5
+ > One Path to bring them all,
6
+ > And in cryptography bind them._
7
+ > —[BIP-85](https://github.com/bitcoin/bips/blob/master/bip-0085.mediawiki)
8
+
9
+ bipsea is a standalone, test-driven implementation of BIP-85 and BIP-32.
10
+ bipsea is designed for readability and security. bipsea offers a command-line
11
+ interface and an API.
12
+
13
+ bipsea relies on cryptographic primitives from Python (`secrets`, `hashlib`),
14
+ and the [python-ecdsa](https://github.com/tlsfuzzer/python-ecdsa). bipsea does not
15
+ rely on third-party libraries from any wallet vendor.
16
+
17
+ You can run bipsea offline on to generate general-use passwords, Bitcoin seed words,
18
+ and more. Consider dedicated cold hardware that runs [Tails](https://tails.net),
19
+ never has network access, and disables
20
+ [Intel Management Engine](https://support.system76.com/articles/intel-me/)
21
+ and other possible backdoors.
22
+
23
+ # How is this useful?
24
+
25
+ BIP-85 is the foundation for a next generation password manager that enables you
26
+ to protect and store a _single_ master secret that can derive _millions of independent, multi-purpose secrets_.
27
+
28
+ BIP-85 offers the following benefits:
29
+ * The security of numerous independent passwords with the operational efficiency
30
+ of a single master password. (The master secret can be multi-factor.)
31
+ * Uses Bitcoin's well-tested hierarchical deterministic wallet
32
+ tree (including primitives like ECDSA and hardened children)
33
+ * Can generate millions of new Bitcoin wallet seed words and master keys
34
+ * Can generate millions of new passwords from a single master root key (xprv)
35
+ and a short derivation path.
36
+
37
+ Unlike a password manager, which protects many secrets with one hot secret,
38
+ BIP-85 _derives_ many secrets from one protected secret. Therefore you only need
39
+ to back up the derivation paths and the services they are for. You do not need to
40
+ back up the derived secrets.
41
+
42
+ You could safely store all derivation paths in a hot password manager
43
+ like Keychain. You could even store the derived secrets in a hot password manager
44
+ at no risk to the master private key.
45
+
46
+ > Note: bipsea alone is not password manager, but you might use it to implement one.
47
+
48
+ # How does it work?
49
+
50
+ The root of your BIP-85 password tree is a standard Bitcoin master private key (xprv).
51
+
52
+ > In general, you _should not use a wallet seed with funds in it_.
53
+ > In any case, fresh seeds are free and easy to generate with bipsea.
54
+
55
+ The master key then uses the BIP-32 derivation tree with a clever twist: the
56
+ derivation path includes a purpose code (`83696968'`) followed by an _application_
57
+ code. In this way, each unique derivation path produces a unique, independent,
58
+ and secure _derived entropy_ as a pure function of the master private key and the
59
+ derivation path.
60
+
61
+ BIP-85 specifies a variety of application codes including the following:
62
+
63
+ | application code | description |
64
+ |------------------|-------------|
65
+ | `39'` | as in BIP-39, to generate seed words |
66
+ | `2'` | for HD-Seed wallet import format ([WIF](https://en.bitcoin.it/wiki/Wallet_import_format)) |
67
+ | `32'` | as in BIP-32, to generate extended private keys (xprv) |
68
+ | `128169'` | for 16 to 64 bytes of random hex |
69
+ | `707764'` | for 20 to 86 characters of a base64 password |
70
+ | `707785'` | for 10 to 80 characters of a base85 password |
71
+
72
+ bipsea implements all of the above applications plus the BIP-85 discrete random
73
+ number generator (DRNG). bipsea does not implement the RSA application codes from
74
+ BIP-85 but you could potentially use the DRNG for RSA and similar applications.
75
+
76
+ ## Example derivation path
77
+
78
+ Consider `m/83696968'/707764'/10'/0'`. It produces the password
79
+ `dKLoepugzd` according to the following logic:
80
+
81
+ | path segment | description |
82
+ |--------------|-------------------------------------------|
83
+ | `m` | master private key |
84
+ | `83696968'` | purpose code for BIP-85 |
85
+ | `707764'` | application code for base64 password |
86
+ | `10'` | number of password characters |
87
+ | `0'` | index, 0 to 2³¹ - 1 for millions of unique passwords |
88
+
89
+ > `'` denotes hardened child derivation, recommended for all BIP-85 applications.
90
+ _Hardened_ derivation means that, even if both the parent public key and the child
91
+ private key are exposed, the parent private key remains secure.
92
+
93
+ ## BIP-32 hierarchical deterministic wallet tree
94
+
95
+ ![](imgs/derivation.png)
96
+
97
+ ## How do I know the bipsea implementation is correct?
98
+
99
+ bipsea passes all BIP-32 and BIP-85 test vectors plus its own unit tests with the
100
+ following provisos:
101
+ * Only generates seed phrases in English
102
+ * Fails one partial test for derived entropy (but passes all others) from BIP-85
103
+
104
+ ### TODO
105
+
106
+ * [ ] File the above and other "TODO" issues to BIP-85
107
+
108
+ Run `make test` for details.
109
+
110
+ # Usage
111
+
112
+ ```
113
+ pip install bipsea
114
+ ```
115
+ ```
116
+ bipsea --help
117
+ ```
118
+
119
+ ## `bipsea seed`
120
+
121
+ ### New seed words
122
+
123
+ ```sh
124
+ bipsea seed -n 12 --pretty
125
+ ```
126
+ 1) crumble
127
+ 2) shallow
128
+ 3) hair
129
+ 4) federal
130
+ 5) cycle
131
+ 6) grid
132
+ 7) million
133
+ 8) twist
134
+ 9) turn
135
+ 10) verb
136
+ 11) orphan
137
+ 12) suggest
138
+
139
+ ### xprv from existing seed words
140
+
141
+ ```
142
+ bipsea seed -f words -i "airport letter idea forget broccoli prefer panda food delay struggle ridge salute above want dinner" -t xprv
143
+ ```
144
+ xprv9s21ZrQH143K3YwuXcacSSghcUfrrEyj9hTHU3a2gmr6SzPBaxmuTgKGBWtFdnnCjwGYMkU7mLvxba8FFPGLQUMvyACZTEdSCJ8uBwh5Aqs
145
+
146
+ ## xprv from dice rolls (or any string)
147
+ ```
148
+ bipsea seed -f string -i "123456123456123456" -t xprv
149
+ ```
150
+
151
+ <pre><code style="color: #CCCC00">Warning: stretched 144 bits of entropy to 256 bits. Provide more entropy.</code></pre>
152
+
153
+ xprv9s21ZrQH143K35QDSCrHfhTJNQGS8ehYV74s65pMwTHfHq89oqcqVQJU4iD3B2M68skmz32eT8Kdr1thXJ6tHXRpy77QtAN1dhEdvqYPiVm
154
+
155
+ This is similar to how coldcard implements
156
+ [verifiable dice rolls](https://coldcard.com/docs/verifying-dice-roll-math/).
157
+ If you are now thinking, _I could use any string to derive a master key_,
158
+ then you get it. And we haven't even gottent into BIP-85.
159
+
160
+ > That said, **do not get cute and derive valuable keys or secrets from short
161
+ > strings**. You can only stretch entropy so far. **Weak entropy in, weaker entropy out**.
162
+ > Short, common strings are also susceptible to
163
+ [rainbow table attacks](https://en.wikipedia.org/wiki/Rainbow_table).
164
+
165
+
166
+ ## `bipsea entropy`
167
+
168
+ `bipsea entropy` requires you to pipe in an xprv.
169
+
170
+ ### base64 password
171
+
172
+ ```
173
+ bipsea seed -f string -i "yoooooooooooooooo" -t xprv -n 12 | bipsea entropy -a base85 -n 10
174
+ ```
175
+ C(s>@zBUg8
176
+
177
+ Increment the index to get a fresh password.
178
+
179
+ ```
180
+ bipsea seed -f string -i "yoooooooooooooooo" -t xprv -n 12 | bipsea entropy -a base85 -n 10 -i 1
181
+ ```
182
+ p6Ft=F40(*
183
+
184
+ Alternatively you can pipe in an existing xprv:
185
+
186
+ ```
187
+ echo "$XPRV" | bipsea entropy -a base85 -n 10
188
+ ```
189
+
190
+ ### Derived seed words
191
+
192
+ ```
193
+ bipsea seed -t xprv | bipsea entropy -a words
194
+ ```
195
+ loan height quality library maid defense minor token thought music claim actual hour ship robust burst live broccoli
196
+
197
+ ### DRNG, enter the matrix
198
+
199
+ ```
200
+ bipsea seed -t xprv | bipsea entropy -a drng -n 10000
201
+ ```
202
+ <10K hex chars from the DRNG>
203
+
204
+ # For the curious and paranoid
205
+
206
+ BIP-85 derives the entropy for each application by computing an HMAC of the private
207
+ ECDSA key of the last hardened child. Private child keys are pure functions of the
208
+ parent key and the child index. In this way BIP-85 entropy is hierarchical,
209
+ deterministic, and irreversibly hardened as long as ECDSA remains secure.
210
+ ECDSA is believed to be secure but no one knows for certain. It may not even be
211
+ possible to conclusively prove the security of any cryptographic algorithm as such
212
+ a proof would simultaneously prove that "P is not equal to NP."
213
+
214
+ All of that to say **even the hardest cryptography falls to the problem of induction**:
215
+ > Just because no one broke has yet broken ECDSA
216
+ > doesn't mean no one will break ECDSA.
217
+
218
+ ECDSA is not [post-quantum secure](https://blog.cloudflare.com/pq-2024).
219
+ If someone were to creates the elusive quant computer with sufficiently many
220
+ logical q-bits to run Shor's algorithm on large keys, then suddenly private
221
+ could be reverse-engineered from public keys. As unlikely as a quantum computer
222
+ may seem, the Chromium team is
223
+ [taking no chances](https://blog.chromium.org/2024/05/advancing-our-amazing-bet-on-asymmetric.html)
224
+ and has begun to roll out quantum-resistant changes to SSL.
225
+
226
+ # Developer
227
+
228
+ ```
229
+ make install
230
+ make install-go
231
+ make test
232
+ ```
233
+
234
+ See [Makefile](./Makefile) for more commands.
235
+
236
+ # References
237
+
238
+ 1. [BIP-32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)
239
+ hierarchical deterministic wallets
240
+ 1. [BIP-85](https://github.com/bitcoin/bips/blob/master/bip-0085.mediawiki)
241
+ generalized cryptographic entropy
242
+ 1. [BIP-44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)
243
+ generalized BIP-32 paths
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.1
2
+ Name: bipsea
3
+ Version: 0.1
4
+ Summary: Python implementation of BIP 85 (and BIP 32)
5
+ Author: Aneesh Karve
6
+ Author-email: bonded_metals_0u@icloud.com
7
+ Project-URL: Source, https://github.com/akarve/bipsea
8
+ Keywords: Bitcoin BIP85 BIP32 cryptography
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ License-File: LICENSE.md
16
+ Requires-Dist: click
17
+ Requires-Dist: base58
18
+ Requires-Dist: ecdsa
19
+ Requires-Dist: pytest
@@ -0,0 +1,13 @@
1
+ LICENSE.md
2
+ README.md
3
+ setup.py
4
+ bipsea.egg-info/PKG-INFO
5
+ bipsea.egg-info/SOURCES.txt
6
+ bipsea.egg-info/dependency_links.txt
7
+ bipsea.egg-info/entry_points.txt
8
+ bipsea.egg-info/requires.txt
9
+ bipsea.egg-info/top_level.txt
10
+ tests/test_bip32.py
11
+ tests/test_bip39.py
12
+ tests/test_bip85.py
13
+ tests/test_cli.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ bipsea = bipsea:cli
@@ -0,0 +1,4 @@
1
+ click
2
+ base58
3
+ ecdsa
4
+ pytest
@@ -0,0 +1 @@
1
+
bipsea-0.1/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
bipsea-0.1/setup.py ADDED
@@ -0,0 +1,41 @@
1
+ from setuptools import find_packages, setup
2
+
3
+ from util import __app_name__, __version__
4
+
5
+ setup(
6
+ name=__app_name__,
7
+ version=__version__,
8
+ packages=find_packages(),
9
+ description="Python implementation of BIP 85 (and BIP 32)",
10
+ author="Aneesh Karve",
11
+ author_email="bonded_metals_0u@icloud.com",
12
+ classifiers=[
13
+ "Development Status :: 4 - Beta",
14
+ "Intended Audience :: Developers",
15
+ "License :: OSI Approved :: Apache Software License",
16
+ "Programming Language :: Python :: 3.8",
17
+ "Programming Language :: Python :: 3.9",
18
+ "Programming Language :: Python :: 3.10",
19
+ ],
20
+ keywords="Bitcoin BIP85 BIP32 cryptography",
21
+ install_requires=[
22
+ "click",
23
+ "base58",
24
+ "ecdsa",
25
+ "pytest",
26
+ ],
27
+ tests_require=[
28
+ "black",
29
+ "isort",
30
+ "pytest",
31
+ "requests",
32
+ ],
33
+ project_urls={
34
+ "Source": "https://github.com/akarve/bipsea",
35
+ },
36
+ entry_points={
37
+ "console_scripts": [
38
+ "bipsea=bipsea:cli",
39
+ ],
40
+ },
41
+ )
@@ -0,0 +1,43 @@
1
+ import logging
2
+
3
+ import pytest
4
+ from data.bip32_vectors import INVALID_KEYS, VECTORS
5
+
6
+ from bip32 import to_master_key
7
+ from bip32types import parse_ext_key
8
+ from bip85 import derive
9
+ from util import LOGGER, from_hex
10
+
11
+ logger = logging.getLogger(LOGGER)
12
+
13
+
14
+ @pytest.mark.parametrize(
15
+ "vector",
16
+ VECTORS,
17
+ ids=[
18
+ f"Vector-{i + 1}-{', '.join(e['chain'].keys())}" for i, e in enumerate(VECTORS)
19
+ ],
20
+ )
21
+ def test_vectors(vector):
22
+ seed = from_hex(vector["seed_hex"])
23
+ for ch, tests in vector["chain"].items():
24
+ for type_, expected in tests.items():
25
+ assert type_ in ("ext pub", "ext prv")
26
+ master = to_master_key(seed, mainnet=True, private=True)
27
+ derived = derive(master, ch, private=type_ == "ext prv")
28
+ if not str(derived) == expected:
29
+ logger.error("derived:")
30
+ logger.error(repr(derived))
31
+ logger.error("expected:")
32
+ logger.error(repr(parse_ext_key(expected)))
33
+ assert str(derived) == expected
34
+
35
+
36
+ @pytest.mark.parametrize(
37
+ "key, reason",
38
+ INVALID_KEYS,
39
+ ids=[f"Vector-5-{reason[:32]}-{key[:8]}" for key, reason in INVALID_KEYS],
40
+ )
41
+ def test_invalid_keys(key, reason):
42
+ with pytest.raises((AssertionError, ValueError)):
43
+ parse_ext_key(key)
@@ -0,0 +1,62 @@
1
+ import hashlib
2
+ import logging
3
+ import re
4
+ import warnings
5
+ from unicodedata import is_normalized
6
+
7
+ import pytest
8
+ import requests
9
+ from data.bip39_vectors import VECTORS
10
+
11
+ from bip32 import to_master_key
12
+ from seedwords import DICT_HASH, N_MNEMONICS, entropy_to_words, to_master_seed
13
+ from util import LOGGER, from_hex
14
+
15
+ logger = logging.getLogger(LOGGER)
16
+
17
+ WORD_COUNTS = {12, 15, 18, 21, 24}
18
+
19
+
20
+ @pytest.mark.parametrize(
21
+ "language, vectors", VECTORS.items(), ids=[l for l in VECTORS.keys()]
22
+ )
23
+ def test_vectors(language, vectors):
24
+ for vector in vectors:
25
+ _, mnemonic, seed, xprv = vector
26
+ expected_words = re.split(r"\s", mnemonic)
27
+ expected_seed = from_hex(seed)
28
+ computed_seed = to_master_seed(expected_words, passphrase="TREZOR")
29
+ assert expected_seed == computed_seed
30
+ computed_xprv = to_master_key(expected_seed, mainnet=True, private=True)
31
+ assert str(computed_xprv) == xprv
32
+
33
+
34
+ @pytest.mark.parametrize(
35
+ "language, vectors", VECTORS.items(), ids=[l for l in VECTORS.keys()]
36
+ )
37
+ def test_seed_word_generation(language, vectors):
38
+ for vector in vectors:
39
+ entropy_str, mnemonic, seed, xprv = vector
40
+ expected_words = re.split(r"\s", mnemonic)
41
+ if language == "english":
42
+ entropy_bytes = from_hex(entropy_str)
43
+ if all(b == 0 for b in entropy_bytes):
44
+ warnings.simplefilter("ignore")
45
+ computed_words = entropy_to_words(
46
+ len(expected_words), user_entropy=entropy_bytes, passphrase="TREZOR"
47
+ )
48
+ assert expected_words == computed_words
49
+ else:
50
+ pytest.skip(f"{language} not supported")
51
+
52
+
53
+ @pytest.mark.network
54
+ def test_words_in_bip39_wordlist():
55
+ """make sure we match github"""
56
+ url = "https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/english.txt"
57
+ response = requests.get(url)
58
+ wordlist = response.text.split()
59
+ assert all(is_normalized("NFKD", w) for w in wordlist)
60
+ assert len(wordlist) == N_MNEMONICS
61
+ response_hash = hashlib.sha256(response.content).hexdigest()
62
+ assert response_hash == DICT_HASH, f"Hash mismatch: {response_hash} != {DICT_HASH}"
@@ -0,0 +1,109 @@
1
+ import logging
2
+
3
+ import pytest
4
+ from data.bip85_vectors import (
5
+ BIP39,
6
+ EXT_KEY_TO_ENTROPY,
7
+ HEX,
8
+ PWD_BASE64,
9
+ PWD_BASE85,
10
+ WIF,
11
+ XPRV,
12
+ )
13
+
14
+ from bip32types import parse_ext_key
15
+ from bip85 import DRNG, apply_85, derive, to_entropy, to_hex_string
16
+ from util import LOGGER, to_hex_string
17
+
18
+ logger = logging.getLogger(LOGGER)
19
+
20
+
21
+ @pytest.mark.parametrize(
22
+ "vector",
23
+ EXT_KEY_TO_ENTROPY,
24
+ ids=[f"Vector-{i + 1}" for i, e in enumerate(EXT_KEY_TO_ENTROPY)],
25
+ )
26
+ def test_entropy(vector):
27
+ master = parse_ext_key(vector["master"])
28
+ derived_key = derive(master, vector["path"])
29
+ secret = derived_key.data[1:] # chop the BIP32 byte prefix
30
+ assert to_hex_string(secret) == vector["derived_key"]
31
+ entropy = to_entropy(secret)
32
+ assert to_hex_string(entropy) == vector["derived_entropy"]
33
+ if "drng" in vector:
34
+ output = DRNG(entropy).read(vector["drng_length"])
35
+ assert to_hex_string(output) == vector["drng"]
36
+
37
+
38
+ @pytest.mark.parametrize("vector", PWD_BASE64)
39
+ def test_pwd_base64(vector):
40
+ master = parse_ext_key(vector["master"])
41
+ path = vector["path"]
42
+ output = apply_85(derive(master, path), path)
43
+ assert vector["derived_pwd"] == output["application"]
44
+
45
+
46
+ @pytest.mark.parametrize("vector", PWD_BASE64)
47
+ @pytest.mark.xfail(reason="wut!? correct password, bad entropy; file to BIP-85")
48
+ def test_pwd_base64_entropy(vector):
49
+ master = parse_ext_key(vector["master"])
50
+ path = vector["path"]
51
+ output = apply_85(derive(master, path), path)
52
+ assert vector["derived_entropy"] == to_hex_string(output["entropy"])
53
+
54
+
55
+ @pytest.mark.parametrize("vector", PWD_BASE85)
56
+ def test_pwd_base85(vector):
57
+ master = parse_ext_key(vector["master"])
58
+ path = vector["path"]
59
+ output = apply_85(derive(master, path), path)
60
+ assert vector["derived_pwd"] == output["application"]
61
+ assert vector["derived_entropy"] == to_hex_string(output["entropy"])
62
+
63
+
64
+ @pytest.mark.parametrize("vector", BIP39)
65
+ def test_bip39(vector):
66
+ master = parse_ext_key(vector["master"])
67
+ path = vector["path"]
68
+ output = apply_85(derive(master, path), path)
69
+ assert to_hex_string(output["entropy"]) == vector["derived_entropy"]
70
+ assert len(output["application"].split(" ")) == vector["mnemonic_length"]
71
+ assert output["application"] == vector["derived_mnemonic"]
72
+
73
+
74
+ @pytest.mark.parametrize("vector", HEX)
75
+ def test_hex(vector):
76
+ master = parse_ext_key(vector["master"])
77
+ path = vector["path"]
78
+ output = apply_85(derive(master, path), path)
79
+ assert vector["derived_entropy"] == output["application"]
80
+
81
+
82
+ @pytest.mark.parametrize("vector", XPRV)
83
+ def test_rsa_unsupported(vector):
84
+ """currently no support for RSA application.
85
+ path format: m/83696968'/828365'/{key_bits}'/{key_index}'"""
86
+ rsa_path = "m/83696968'/828365'/1024'/0'"
87
+ master = parse_ext_key(vector["master"])
88
+ with pytest.raises(NotImplementedError):
89
+ apply_85(derive(master, rsa_path), rsa_path)
90
+
91
+
92
+ @pytest.mark.parametrize("vector", WIF)
93
+ def test_wif(vector):
94
+ master = parse_ext_key(vector["master"])
95
+ path = vector["path"]
96
+ output = apply_85(derive(master, path), path)
97
+ assert to_hex_string(output["entropy"]) == vector["derived_entropy"]
98
+ # TODO: file against BIP85 poor test case does not include WIF checksum
99
+ # (not a correct WIF)
100
+ assert output["application"].decode("utf-8") == vector["derived_wif"]
101
+
102
+
103
+ @pytest.mark.parametrize("vector", XPRV)
104
+ def test_xprv(vector):
105
+ master = parse_ext_key(vector["master"])
106
+ path = vector["path"]
107
+ output = apply_85(derive(master, path), path)
108
+ assert vector["derived_key"] == output["application"]
109
+ assert to_hex_string(output["entropy"]) == vector["derived_entropy"]
@@ -0,0 +1,196 @@
1
+ import logging
2
+
3
+ import pytest
4
+ from click.testing import CliRunner
5
+
6
+ from bipsea import N_WORDS_ALLOWED, cli
7
+ from tests.data.bip39_vectors import VECTORS
8
+ from tests.data.bip85_vectors import BIP39, HEX, PWD_BASE64, PWD_BASE85, WIF
9
+ from util import LOGGER
10
+
11
+ logger = logging.getLogger(LOGGER)
12
+
13
+
14
+ @pytest.fixture
15
+ def runner():
16
+ return CliRunner()
17
+
18
+
19
+ @pytest.mark.parametrize("language, vectors", VECTORS.items())
20
+ def test_seed_command_to_actual_seed(runner, language, vectors):
21
+ for vector in vectors:
22
+ _, mnemonic, _, xprv = vector
23
+
24
+ for upper in (True, False):
25
+ mnemonic = mnemonic.upper() if upper else mnemonic
26
+ result = runner.invoke(
27
+ cli,
28
+ ["seed", "-t", "xprv", "-f", "words", "-i", mnemonic, "-p", "TREZOR"],
29
+ )
30
+ assert result.exit_code == 0
31
+ assert result.output.strip() == xprv
32
+
33
+
34
+ @pytest.mark.parametrize("language, vectors", VECTORS.items())
35
+ def test_seed_option_sensitivity(runner, language, vectors):
36
+ """prove that passphrase and mnemonic changes alter xprv (but white space around
37
+ mnemonic doesn't)"""
38
+ # make tests faster by only covering one per language
39
+ for vector in vectors[:1]:
40
+ _, mnemonic, _, xprv = vector
41
+
42
+ change_passphrase = runner.invoke(
43
+ cli, ["seed", "-t", "xprv", "-f", "words", "-i", mnemonic, "-p", "TrEZOR"]
44
+ )
45
+ assert change_passphrase.exit_code == 0
46
+ assert change_passphrase.output.strip() != xprv
47
+
48
+ append_mnemonic = runner.invoke(
49
+ cli,
50
+ ["seed", "-t", "xprv", "-f", "words", "-i", mnemonic + ".", "-p", "TREZOR"],
51
+ )
52
+ assert append_mnemonic.exit_code == 0
53
+ assert append_mnemonic.output.strip() != xprv
54
+
55
+ whitespace_mnemonic = runner.invoke(
56
+ cli,
57
+ [
58
+ "seed",
59
+ "-t",
60
+ "xprv",
61
+ "-f",
62
+ "words",
63
+ "-i",
64
+ " " + mnemonic + " \t\n ",
65
+ "-p",
66
+ "TREZOR",
67
+ ],
68
+ )
69
+ assert whitespace_mnemonic.exit_code == 0
70
+ assert whitespace_mnemonic.output.strip() == xprv
71
+
72
+ testnet = runner.invoke(
73
+ cli, ["seed", "-t", "tprv", "-f", "words", "-i", mnemonic, "-p", "TREZOR"]
74
+ )
75
+ assert testnet.exit_code == 0
76
+ tprv = testnet.output.strip()
77
+ assert tprv != xprv
78
+ assert tprv.startswith("tprv")
79
+
80
+
81
+ @pytest.mark.parametrize("n", N_WORDS_ALLOWED)
82
+ def test_seed_command_n_words(runner, n):
83
+ for from_ in ("string", "rand"):
84
+ cmd = ["seed", "-t", "words", "-n", str(n)]
85
+ cmd += ["-f", from_]
86
+ if from_ == "string":
87
+ # "s"*15 is shorter than the lowest entropy of 128 bits
88
+ # "l"*32 is longer than the highest entropy of 256 bits
89
+ for input in ("s" * 15, "l" * 32):
90
+ cmd += ["-i", input]
91
+ result = runner.invoke(cli, cmd, catch_exceptions=False)
92
+ if "s" in input:
93
+ assert "Warning" in result.output
94
+ else:
95
+ assert "Warning" not in result.output
96
+ assert len(result.output.split()) == int(n)
97
+ assert result.exit_code == 0
98
+
99
+
100
+ def test_seed_from_and_to_words(runner):
101
+ result = runner.invoke(cli, ["seed", "--from", "words", "--to", "words"])
102
+ assert result.exit_code != 0
103
+ assert "--input" in result.output
104
+ assert "--from rand" in result.output
105
+
106
+
107
+ def test_seed_from_and_n(runner):
108
+ result = runner.invoke(cli, ["seed", "--from", "words", "-n", "45"])
109
+ assert result.exit_code != 0
110
+ assert "--number" in result.output
111
+
112
+
113
+ def test_seed_bad_from(runner):
114
+ result = runner.invoke(cli, ["seed", "--from", "baz"])
115
+ assert result.exit_code != 0
116
+ assert "not one of" in result.output
117
+
118
+
119
+ def test_seed_bad_to(runner):
120
+ result = runner.invoke(cli, ["seed", "--to", "blah"])
121
+ assert result.exit_code != 0
122
+ assert "not one of" in result.output
123
+
124
+
125
+ @pytest.mark.parametrize("vector", PWD_BASE64)
126
+ def test_bipsea_integration(runner, vector):
127
+ result_seed = runner.invoke(
128
+ cli,
129
+ ["seed", "-f", "string", "-i", "yooooooooooooooo", "-n", "12", "-t", "xprv"],
130
+ )
131
+ xprv = result_seed.output.strip()
132
+ assert result_seed.exit_code == 0
133
+ result_entropy = runner.invoke(
134
+ cli, ["entropy", "-a", "base64", "-n", "20", "--input", xprv]
135
+ )
136
+ assert result_entropy.exit_code == 0
137
+ pwd64 = result_entropy.output.strip()
138
+ assert pwd64 == "lGqIFs50nYCWA0DjxHRB"
139
+ assert len(pwd64) == 20
140
+
141
+
142
+ @pytest.mark.parametrize("vector", PWD_BASE85)
143
+ def test_entropy_n(runner, vector):
144
+ xprv = vector["master"]
145
+ for app in ("base64", "base85", "hex", "drng"):
146
+ for n in (20, 50, 64):
147
+ result = runner.invoke(
148
+ cli, ["entropy", "-a", app, "-n", n, "--input", xprv]
149
+ )
150
+ assert result.exit_code == 0
151
+ answer = result.output.strip()
152
+ length = len(answer)
153
+ if app in ("hex", "drng"):
154
+ length = length // 2
155
+ assert length == n
156
+
157
+
158
+ @pytest.mark.parametrize("vector", PWD_BASE85)
159
+ def test_entropy_n_out_of_range(runner, vector):
160
+ xprv = vector["master"]
161
+ for app in ("base64", "base85", "hex", "drng"):
162
+ for n in (-1, 0, 1025):
163
+ if n == 1025 and app == "drng":
164
+ break
165
+ result = runner.invoke(
166
+ cli, ["entropy", "-a", app, "-n", n, "--input", xprv]
167
+ )
168
+ assert result.exit_code != 0
169
+ assert "Error" in result.output
170
+
171
+
172
+ @pytest.mark.parametrize("vector", BIP39)
173
+ def test_entropy_bip39(runner, vector):
174
+ xprv = vector["master"]
175
+ n_words = vector["mnemonic_length"]
176
+ result = runner.invoke(
177
+ cli, ["entropy", "-a", "words", "--input", xprv, "-n", n_words]
178
+ )
179
+ assert result.exit_code == 0
180
+ assert result.output.strip() == vector["derived_mnemonic"]
181
+
182
+
183
+ @pytest.mark.parametrize("vector", HEX)
184
+ def test_entropy_hex(runner, vector):
185
+ xprv = vector["master"]
186
+ result = runner.invoke(cli, ["entropy", "-a", "hex", "--input", xprv, "-n", 64])
187
+ assert result.exit_code == 0
188
+ assert result.output.strip() == vector["derived_entropy"]
189
+
190
+
191
+ @pytest.mark.parametrize("vector", WIF)
192
+ def test_entropy_wif(runner, vector):
193
+ xprv = vector["master"]
194
+ result = runner.invoke(cli, ["entropy", "-a", "wif", "--input", xprv])
195
+ assert result.exit_code == 0
196
+ assert result.output.strip() == vector["derived_wif"]