@decryption/bip32 0.2.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the “Software”), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,75 @@
1
+ # @decryption/bip32
2
+
3
+ > **NOTE:** This is a fork of [`@scure/bip32`](https://www.npmjs.com/package/@scure/bip32) (v2.2.0).
4
+ > We dual-publish as both **CJS and ESM** because upstream is ESM-only (`"type": "module"`), which breaks
5
+ > `require()` in Jest, older bundlers and CJS-based Node.js tooling. The source is unchanged from upstream —
6
+ > only the build tooling differs, plus `@noble/*` / `@scure/*` import specifiers are rewritten to their
7
+ > `@decryption/*` forks.
8
+
9
+ Audited & minimal implementation of BIP32 hierarchical deterministic (HD) wallets. Dual CJS+ESM fork of @scure/bip32.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install @decryption/bip32
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ Import submodules directly — `dist/` is the package root once published, so deep imports work in both CJS and ESM:
20
+
21
+ ```typescript
22
+ import { sha256 } from '@decryption/hashes/sha2';
23
+ import { xchacha20poly1305 } from '@decryption/ciphers/chacha';
24
+ ```
25
+
26
+ Refer to the [upstream documentation](https://github.com/paulmillr/bip32) for the full API.
27
+
28
+ ## Syncing upstream
29
+
30
+ ```bash
31
+ ./scripts/vendor-fork.sh @scure/bip32 <version> bip32
32
+ node scripts/fix-imports.js packages/bip32 bip32
33
+ pnpm --filter @decryption/bip32 build && pnpm --filter @decryption/bip32 test
34
+ ```
35
+
36
+ ## License
37
+
38
+ MIT — Copyright (c) 2022 Paul Miller (https://paulmillr.com). See [LICENSE](./LICENSE).
39
+
40
+ ---
41
+
42
+ ## Development
43
+
44
+ ### Setup
45
+
46
+ 1. Clone the repository:
47
+
48
+ ```bash
49
+ git clone https://github.com/constructive-io/decryption.git
50
+ ```
51
+
52
+ 2. Install dependencies:
53
+
54
+ ```bash
55
+ cd decryption
56
+ pnpm install
57
+ pnpm build
58
+ ```
59
+
60
+ 3. Test the package of interest:
61
+
62
+ ```bash
63
+ cd packages/<packagename>
64
+ pnpm test:watch
65
+ ```
66
+
67
+ ## Credits
68
+
69
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
70
+
71
+ ## Disclaimer
72
+
73
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
74
+
75
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/esm/index.js ADDED
@@ -0,0 +1,312 @@
1
+ /**
2
+ * BIP32 hierarchical deterministic (HD) wallets over secp256k1.
3
+ * @module
4
+ * @example
5
+ * ```js
6
+ * import { HDKey } from "@decryption/bip32";
7
+ * import { sha256 } from '@decryption/hashes/sha2';
8
+ * import { randomBytes } from '@decryption/hashes/utils';
9
+ * const seed = randomBytes(32);
10
+ * const root = HDKey.fromMasterSeed(seed);
11
+ * const base58key = root.privateExtendedKey;
12
+ * const restored = HDKey.fromExtendedKey(base58key);
13
+ * const fromJson = HDKey.fromJSON({ xpriv: base58key });
14
+ * const child = fromJson.derive("m/0/2147483647'/1");
15
+ * const msgHash = sha256(new TextEncoder().encode('hello scure-bip32'));
16
+ *
17
+ * // props
18
+ * [root.depth, root.index, root.chainCode];
19
+ * [restored.privateKey, restored.publicKey];
20
+ * const sig = child.sign(msgHash);
21
+ * child.verify(msgHash, sig);
22
+ * ```
23
+ */
24
+ /*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
25
+ import { secp256k1 as secp } from '@decryption/curves/secp256k1';
26
+ import { hmac } from '@decryption/hashes/hmac';
27
+ import { ripemd160 } from '@decryption/hashes/legacy';
28
+ import { sha256, sha512 } from '@decryption/hashes/sha2';
29
+ import { abytes, concatBytes, createView } from '@decryption/hashes/utils';
30
+ import { createBase58check } from '@decryption/base';
31
+ const Point = /* @__PURE__ */ (() => secp.Point)();
32
+ const Fn = /* @__PURE__ */ (() => Point.Fn)();
33
+ const base58check = /* @__PURE__ */ createBase58check(sha256);
34
+ const MASTER_SECRET = /* @__PURE__ */ (() => {
35
+ return Uint8Array.from('Bitcoin seed'.split(''), (char) => char.charCodeAt(0));
36
+ })();
37
+ const BITCOIN_VERSIONS = { private: 0x0488ade4, public: 0x0488b21e };
38
+ /** Hardened child index offset from BIP32. */
39
+ export const HARDENED_OFFSET = 0x80000000;
40
+ const hash160 = (data) => ripemd160(sha256(data));
41
+ const fromU32 = (data) => createView(data).getUint32(0, false);
42
+ const toU32 = (n) => {
43
+ if (typeof n !== 'number')
44
+ throw new TypeError('invalid number, should be from 0 to 2**32-1, got ' + n);
45
+ if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1)
46
+ throw new RangeError('invalid number, should be from 0 to 2**32-1, got ' + n);
47
+ const buf = new Uint8Array(4);
48
+ createView(buf).setUint32(0, n, false);
49
+ return buf;
50
+ };
51
+ /**
52
+ * HDKey from BIP32
53
+ * @param opt - Node fields used to construct one HDKey instance.
54
+ * @example
55
+ * ```js
56
+ * import { HDKey } from '@decryption/bip32';
57
+ * import { randomBytes } from '@decryption/hashes/utils';
58
+ *
59
+ * const seed = randomBytes(32);
60
+ * const root = HDKey.fromMasterSeed(seed);
61
+ * const account0 = root.derive("m/0/1'");
62
+ * account0.publicKey;
63
+ * ```
64
+ */
65
+ export class HDKey {
66
+ get fingerprint() {
67
+ if (!this.pubHash) {
68
+ throw new Error('No publicKey set!');
69
+ }
70
+ return fromU32(this.pubHash);
71
+ }
72
+ get identifier() {
73
+ return this.pubHash;
74
+ }
75
+ get pubKeyHash() {
76
+ return this.pubHash;
77
+ }
78
+ // Returns the live private key buffer for this instance.
79
+ // Copy it first if you need an immutable snapshot.
80
+ get privateKey() {
81
+ return this._privateKey || null;
82
+ }
83
+ get publicKey() {
84
+ return this._publicKey || null;
85
+ }
86
+ get privateExtendedKey() {
87
+ const priv = this._privateKey;
88
+ if (!priv) {
89
+ throw new Error('No private key');
90
+ }
91
+ return base58check.encode(this.serialize(this.versions.private, concatBytes(Uint8Array.of(0), priv)));
92
+ }
93
+ get publicExtendedKey() {
94
+ if (!this._publicKey) {
95
+ throw new Error('No public key');
96
+ }
97
+ return base58check.encode(this.serialize(this.versions.public, this._publicKey));
98
+ }
99
+ static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) {
100
+ abytes(seed);
101
+ if (8 * seed.length < 128 || 8 * seed.length > 512) {
102
+ throw new RangeError('HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +
103
+ seed.length);
104
+ }
105
+ const I = hmac(sha512, MASTER_SECRET, seed);
106
+ const privateKey = I.slice(0, 32);
107
+ const chainCode = I.slice(32);
108
+ return new HDKey({ versions, chainCode, privateKey });
109
+ }
110
+ static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) {
111
+ // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
112
+ const keyBuffer = base58check.decode(base58key);
113
+ const keyView = createView(keyBuffer);
114
+ const version = keyView.getUint32(0, false);
115
+ const opt = {
116
+ versions,
117
+ depth: keyBuffer[4],
118
+ parentFingerprint: keyView.getUint32(5, false),
119
+ index: keyView.getUint32(9, false),
120
+ chainCode: keyBuffer.slice(13, 45),
121
+ };
122
+ const key = keyBuffer.slice(45);
123
+ const isPriv = key[0] === 0;
124
+ if (version !== versions[isPriv ? 'private' : 'public']) {
125
+ throw new Error('Version mismatch');
126
+ }
127
+ if (isPriv) {
128
+ return new HDKey({ ...opt, privateKey: key.slice(1) });
129
+ }
130
+ else {
131
+ return new HDKey({ ...opt, publicKey: key });
132
+ }
133
+ }
134
+ static fromJSON(json) {
135
+ return HDKey.fromExtendedKey(json.xpriv);
136
+ }
137
+ versions;
138
+ depth = 0;
139
+ index = 0;
140
+ chainCode = null;
141
+ parentFingerprint = 0;
142
+ _privateKey;
143
+ _publicKey;
144
+ pubHash;
145
+ constructor(opt) {
146
+ if (!opt || typeof opt !== 'object') {
147
+ throw new Error('HDKey.constructor must not be called directly');
148
+ }
149
+ this.versions = opt.versions || BITCOIN_VERSIONS;
150
+ this.depth = opt.depth || 0;
151
+ this.chainCode = opt.chainCode ? Uint8Array.from(opt.chainCode) : null;
152
+ this.index = opt.index || 0;
153
+ this.parentFingerprint = opt.parentFingerprint || 0;
154
+ if (!this.depth) {
155
+ if (this.parentFingerprint || this.index) {
156
+ throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');
157
+ }
158
+ }
159
+ if (this.depth > 255) {
160
+ throw new Error('HDKey: depth exceeds the serializable value 255');
161
+ }
162
+ if (opt.publicKey && opt.privateKey) {
163
+ throw new Error('HDKey: publicKey and privateKey at same time.');
164
+ }
165
+ if (opt.privateKey) {
166
+ if (!secp.utils.isValidSecretKey(opt.privateKey))
167
+ throw new Error('Invalid private key');
168
+ // Don't alias caller-owned secret buffers.
169
+ this._privateKey = Uint8Array.from(opt.privateKey);
170
+ this._publicKey = secp.getPublicKey(this._privateKey, true);
171
+ }
172
+ else if (opt.publicKey) {
173
+ this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true); // force compressed point
174
+ }
175
+ else {
176
+ throw new Error('HDKey: no public or private key provided');
177
+ }
178
+ this.pubHash = hash160(this._publicKey);
179
+ }
180
+ derive(path) {
181
+ if (!/^[mM]'?/.test(path)) {
182
+ throw new Error('Path must start with "m" or "M"');
183
+ }
184
+ if (/^[mM]'?$/.test(path)) {
185
+ return this;
186
+ }
187
+ const parts = path.replace(/^[mM]'?\//, '').split('/');
188
+ // tslint:disable-next-line
189
+ let child = this;
190
+ for (const c of parts) {
191
+ const m = /^(\d+)('?)$/.exec(c);
192
+ const m1 = m && m[1];
193
+ if (!m || m.length !== 3 || typeof m1 !== 'string')
194
+ throw new Error('invalid child index: ' + c);
195
+ let idx = +m1;
196
+ if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {
197
+ throw new Error('Invalid index');
198
+ }
199
+ // hardened key
200
+ if (m[2] === "'") {
201
+ idx += HARDENED_OFFSET;
202
+ }
203
+ child = child.deriveChild(idx);
204
+ }
205
+ return child;
206
+ }
207
+ /**
208
+ * @param _I - Test-only override for the 64-byte HMAC-SHA512 output; normal callers must omit it.
209
+ */
210
+ deriveChild(index, _I) {
211
+ if (!this._publicKey || !this.chainCode) {
212
+ throw new Error('No publicKey or chainCode set');
213
+ }
214
+ let data = toU32(index);
215
+ if (index >= HARDENED_OFFSET) {
216
+ // Hardened
217
+ const priv = this._privateKey;
218
+ if (!priv) {
219
+ throw new Error('Could not derive hardened child key');
220
+ }
221
+ // Hardened child: 0x00 || ser256(kpar) || ser32(index)
222
+ data = concatBytes(Uint8Array.of(0), priv, data);
223
+ }
224
+ else {
225
+ // Normal child: serP(point(kpar)) || ser32(index)
226
+ data = concatBytes(this._publicKey, data);
227
+ }
228
+ const out = _I || hmac(sha512, this.chainCode, data);
229
+ abytes(out, 64);
230
+ const childTweak = out.slice(0, 32);
231
+ const chainCode = out.slice(32);
232
+ const opt = {
233
+ versions: this.versions,
234
+ chainCode,
235
+ depth: this.depth + 1,
236
+ parentFingerprint: this.fingerprint,
237
+ index,
238
+ };
239
+ // Fail early instead of re-trying different index
240
+ if (opt.depth > 255) {
241
+ throw new Error('HDKey: depth exceeds the serializable value 255');
242
+ }
243
+ try {
244
+ const ctweak = Fn.fromBytes(childTweak);
245
+ // BIP-32 private derivation retries only when parse256(I_L) >= n or k_i = 0.
246
+ // BIP-32 public derivation retries only when parse256(I_L) >= n or K_i is infinity.
247
+ // So I_L = 0 is valid here; Fn.fromBytes still rejects parse256(I_L) >= n.
248
+ if (this._privateKey) {
249
+ const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak);
250
+ if (!Fn.isValidNot0(added)) {
251
+ throw new Error('The tweak was out of range or the resulted private key is invalid');
252
+ }
253
+ opt.privateKey = Fn.toBytes(added);
254
+ }
255
+ else {
256
+ const point = Point.fromBytes(this._publicKey);
257
+ const added = ctweak === 0n ? point : point.add(Point.BASE.multiply(ctweak));
258
+ // Cryptographically impossible: hmac-sha512 preimage would need to be found
259
+ if (added.equals(Point.ZERO)) {
260
+ throw new Error('The tweak was equal to negative P, which made the result key invalid');
261
+ }
262
+ opt.publicKey = added.toBytes(true);
263
+ }
264
+ return new HDKey(opt);
265
+ }
266
+ catch (err) {
267
+ return this.deriveChild(index + 1);
268
+ }
269
+ }
270
+ sign(hash) {
271
+ if (!this._privateKey) {
272
+ throw new Error('No privateKey set!');
273
+ }
274
+ abytes(hash, 32);
275
+ return secp.sign(hash, this._privateKey, { prehash: false });
276
+ }
277
+ verify(hash, signature) {
278
+ abytes(hash, 32);
279
+ abytes(signature, 64);
280
+ if (!this._publicKey) {
281
+ throw new Error('No publicKey set!');
282
+ }
283
+ return secp.verify(signature, hash, this._publicKey, { prehash: false });
284
+ }
285
+ wipePrivateData() {
286
+ if (this._privateKey) {
287
+ this._privateKey.fill(0);
288
+ this._privateKey = undefined;
289
+ }
290
+ return this;
291
+ }
292
+ toJSON() {
293
+ return {
294
+ xpriv: this.privateExtendedKey,
295
+ xpub: this.publicExtendedKey,
296
+ };
297
+ }
298
+ serialize(version, key) {
299
+ if (!this.chainCode) {
300
+ throw new Error('No chainCode set');
301
+ }
302
+ abytes(key, 33);
303
+ // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
304
+ return concatBytes(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key);
305
+ }
306
+ }
307
+ export const __TESTS = /* @__PURE__ */ Object.freeze({
308
+ deriveChildWithI(key, index, I) {
309
+ // Bytes wrappers widen the exported test seam, but deriveChild still needs concrete inputs.
310
+ return key.deriveChild(index, I);
311
+ },
312
+ });
package/index.d.ts ADDED
@@ -0,0 +1,74 @@
1
+ import { type TArg, type TRet } from '@decryption/hashes/utils';
2
+ /** Network-specific BIP32 version bytes. */
3
+ export interface Versions {
4
+ /** 4-byte version used when serializing private extended keys. */
5
+ private: number;
6
+ /** 4-byte version used when serializing public extended keys. */
7
+ public: number;
8
+ }
9
+ /** Hardened child index offset from BIP32. */
10
+ export declare const HARDENED_OFFSET: number;
11
+ interface HDKeyOpt {
12
+ versions?: Versions;
13
+ depth?: number;
14
+ index?: number;
15
+ parentFingerprint?: number;
16
+ chainCode?: Uint8Array;
17
+ publicKey?: Uint8Array;
18
+ privateKey?: Uint8Array;
19
+ }
20
+ /**
21
+ * HDKey from BIP32
22
+ * @param opt - Node fields used to construct one HDKey instance.
23
+ * @example
24
+ * ```js
25
+ * import { HDKey } from '@decryption/bip32';
26
+ * import { randomBytes } from '@decryption/hashes/utils';
27
+ *
28
+ * const seed = randomBytes(32);
29
+ * const root = HDKey.fromMasterSeed(seed);
30
+ * const account0 = root.derive("m/0/1'");
31
+ * account0.publicKey;
32
+ * ```
33
+ */
34
+ export declare class HDKey {
35
+ get fingerprint(): number;
36
+ get identifier(): Uint8Array | undefined;
37
+ get pubKeyHash(): Uint8Array | undefined;
38
+ get privateKey(): Uint8Array | null;
39
+ get publicKey(): Uint8Array | null;
40
+ get privateExtendedKey(): string;
41
+ get publicExtendedKey(): string;
42
+ static fromMasterSeed(seed: Uint8Array, versions?: Versions): HDKey;
43
+ static fromExtendedKey(base58key: string, versions?: Versions): HDKey;
44
+ static fromJSON(json: {
45
+ xpriv: string;
46
+ }): HDKey;
47
+ readonly versions: Versions;
48
+ readonly depth: number;
49
+ readonly index: number;
50
+ readonly chainCode: Uint8Array | null;
51
+ readonly parentFingerprint: number;
52
+ private _privateKey?;
53
+ private _publicKey?;
54
+ private pubHash;
55
+ constructor(opt: HDKeyOpt);
56
+ derive(path: string): HDKey;
57
+ /**
58
+ * @param _I - Test-only override for the 64-byte HMAC-SHA512 output; normal callers must omit it.
59
+ */
60
+ deriveChild(index: number, _I?: Uint8Array): HDKey;
61
+ sign(hash: Uint8Array): Uint8Array;
62
+ verify(hash: Uint8Array, signature: Uint8Array): boolean;
63
+ wipePrivateData(): this;
64
+ toJSON(): {
65
+ xpriv: string;
66
+ xpub: string;
67
+ };
68
+ private serialize;
69
+ }
70
+ type Tests = Readonly<{
71
+ deriveChildWithI(key: TArg<HDKey>, index: number, I: TArg<Uint8Array>): TRet<HDKey>;
72
+ }>;
73
+ export declare const __TESTS: TRet<Tests>;
74
+ export {};
package/index.js ADDED
@@ -0,0 +1,316 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.__TESTS = exports.HDKey = exports.HARDENED_OFFSET = void 0;
4
+ /**
5
+ * BIP32 hierarchical deterministic (HD) wallets over secp256k1.
6
+ * @module
7
+ * @example
8
+ * ```js
9
+ * import { HDKey } from "@decryption/bip32";
10
+ * import { sha256 } from '@decryption/hashes/sha2';
11
+ * import { randomBytes } from '@decryption/hashes/utils';
12
+ * const seed = randomBytes(32);
13
+ * const root = HDKey.fromMasterSeed(seed);
14
+ * const base58key = root.privateExtendedKey;
15
+ * const restored = HDKey.fromExtendedKey(base58key);
16
+ * const fromJson = HDKey.fromJSON({ xpriv: base58key });
17
+ * const child = fromJson.derive("m/0/2147483647'/1");
18
+ * const msgHash = sha256(new TextEncoder().encode('hello scure-bip32'));
19
+ *
20
+ * // props
21
+ * [root.depth, root.index, root.chainCode];
22
+ * [restored.privateKey, restored.publicKey];
23
+ * const sig = child.sign(msgHash);
24
+ * child.verify(msgHash, sig);
25
+ * ```
26
+ */
27
+ /*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
28
+ const secp256k1_1 = require("@decryption/curves/secp256k1");
29
+ const hmac_1 = require("@decryption/hashes/hmac");
30
+ const legacy_1 = require("@decryption/hashes/legacy");
31
+ const sha2_1 = require("@decryption/hashes/sha2");
32
+ const utils_1 = require("@decryption/hashes/utils");
33
+ const base_1 = require("@decryption/base");
34
+ const Point = /* @__PURE__ */ (() => secp256k1_1.secp256k1.Point)();
35
+ const Fn = /* @__PURE__ */ (() => Point.Fn)();
36
+ const base58check = /* @__PURE__ */ (0, base_1.createBase58check)(sha2_1.sha256);
37
+ const MASTER_SECRET = /* @__PURE__ */ (() => {
38
+ return Uint8Array.from('Bitcoin seed'.split(''), (char) => char.charCodeAt(0));
39
+ })();
40
+ const BITCOIN_VERSIONS = { private: 0x0488ade4, public: 0x0488b21e };
41
+ /** Hardened child index offset from BIP32. */
42
+ exports.HARDENED_OFFSET = 0x80000000;
43
+ const hash160 = (data) => (0, legacy_1.ripemd160)((0, sha2_1.sha256)(data));
44
+ const fromU32 = (data) => (0, utils_1.createView)(data).getUint32(0, false);
45
+ const toU32 = (n) => {
46
+ if (typeof n !== 'number')
47
+ throw new TypeError('invalid number, should be from 0 to 2**32-1, got ' + n);
48
+ if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1)
49
+ throw new RangeError('invalid number, should be from 0 to 2**32-1, got ' + n);
50
+ const buf = new Uint8Array(4);
51
+ (0, utils_1.createView)(buf).setUint32(0, n, false);
52
+ return buf;
53
+ };
54
+ /**
55
+ * HDKey from BIP32
56
+ * @param opt - Node fields used to construct one HDKey instance.
57
+ * @example
58
+ * ```js
59
+ * import { HDKey } from '@decryption/bip32';
60
+ * import { randomBytes } from '@decryption/hashes/utils';
61
+ *
62
+ * const seed = randomBytes(32);
63
+ * const root = HDKey.fromMasterSeed(seed);
64
+ * const account0 = root.derive("m/0/1'");
65
+ * account0.publicKey;
66
+ * ```
67
+ */
68
+ class HDKey {
69
+ get fingerprint() {
70
+ if (!this.pubHash) {
71
+ throw new Error('No publicKey set!');
72
+ }
73
+ return fromU32(this.pubHash);
74
+ }
75
+ get identifier() {
76
+ return this.pubHash;
77
+ }
78
+ get pubKeyHash() {
79
+ return this.pubHash;
80
+ }
81
+ // Returns the live private key buffer for this instance.
82
+ // Copy it first if you need an immutable snapshot.
83
+ get privateKey() {
84
+ return this._privateKey || null;
85
+ }
86
+ get publicKey() {
87
+ return this._publicKey || null;
88
+ }
89
+ get privateExtendedKey() {
90
+ const priv = this._privateKey;
91
+ if (!priv) {
92
+ throw new Error('No private key');
93
+ }
94
+ return base58check.encode(this.serialize(this.versions.private, (0, utils_1.concatBytes)(Uint8Array.of(0), priv)));
95
+ }
96
+ get publicExtendedKey() {
97
+ if (!this._publicKey) {
98
+ throw new Error('No public key');
99
+ }
100
+ return base58check.encode(this.serialize(this.versions.public, this._publicKey));
101
+ }
102
+ static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) {
103
+ (0, utils_1.abytes)(seed);
104
+ if (8 * seed.length < 128 || 8 * seed.length > 512) {
105
+ throw new RangeError('HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +
106
+ seed.length);
107
+ }
108
+ const I = (0, hmac_1.hmac)(sha2_1.sha512, MASTER_SECRET, seed);
109
+ const privateKey = I.slice(0, 32);
110
+ const chainCode = I.slice(32);
111
+ return new HDKey({ versions, chainCode, privateKey });
112
+ }
113
+ static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) {
114
+ // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
115
+ const keyBuffer = base58check.decode(base58key);
116
+ const keyView = (0, utils_1.createView)(keyBuffer);
117
+ const version = keyView.getUint32(0, false);
118
+ const opt = {
119
+ versions,
120
+ depth: keyBuffer[4],
121
+ parentFingerprint: keyView.getUint32(5, false),
122
+ index: keyView.getUint32(9, false),
123
+ chainCode: keyBuffer.slice(13, 45),
124
+ };
125
+ const key = keyBuffer.slice(45);
126
+ const isPriv = key[0] === 0;
127
+ if (version !== versions[isPriv ? 'private' : 'public']) {
128
+ throw new Error('Version mismatch');
129
+ }
130
+ if (isPriv) {
131
+ return new HDKey({ ...opt, privateKey: key.slice(1) });
132
+ }
133
+ else {
134
+ return new HDKey({ ...opt, publicKey: key });
135
+ }
136
+ }
137
+ static fromJSON(json) {
138
+ return HDKey.fromExtendedKey(json.xpriv);
139
+ }
140
+ versions;
141
+ depth = 0;
142
+ index = 0;
143
+ chainCode = null;
144
+ parentFingerprint = 0;
145
+ _privateKey;
146
+ _publicKey;
147
+ pubHash;
148
+ constructor(opt) {
149
+ if (!opt || typeof opt !== 'object') {
150
+ throw new Error('HDKey.constructor must not be called directly');
151
+ }
152
+ this.versions = opt.versions || BITCOIN_VERSIONS;
153
+ this.depth = opt.depth || 0;
154
+ this.chainCode = opt.chainCode ? Uint8Array.from(opt.chainCode) : null;
155
+ this.index = opt.index || 0;
156
+ this.parentFingerprint = opt.parentFingerprint || 0;
157
+ if (!this.depth) {
158
+ if (this.parentFingerprint || this.index) {
159
+ throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');
160
+ }
161
+ }
162
+ if (this.depth > 255) {
163
+ throw new Error('HDKey: depth exceeds the serializable value 255');
164
+ }
165
+ if (opt.publicKey && opt.privateKey) {
166
+ throw new Error('HDKey: publicKey and privateKey at same time.');
167
+ }
168
+ if (opt.privateKey) {
169
+ if (!secp256k1_1.secp256k1.utils.isValidSecretKey(opt.privateKey))
170
+ throw new Error('Invalid private key');
171
+ // Don't alias caller-owned secret buffers.
172
+ this._privateKey = Uint8Array.from(opt.privateKey);
173
+ this._publicKey = secp256k1_1.secp256k1.getPublicKey(this._privateKey, true);
174
+ }
175
+ else if (opt.publicKey) {
176
+ this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true); // force compressed point
177
+ }
178
+ else {
179
+ throw new Error('HDKey: no public or private key provided');
180
+ }
181
+ this.pubHash = hash160(this._publicKey);
182
+ }
183
+ derive(path) {
184
+ if (!/^[mM]'?/.test(path)) {
185
+ throw new Error('Path must start with "m" or "M"');
186
+ }
187
+ if (/^[mM]'?$/.test(path)) {
188
+ return this;
189
+ }
190
+ const parts = path.replace(/^[mM]'?\//, '').split('/');
191
+ // tslint:disable-next-line
192
+ let child = this;
193
+ for (const c of parts) {
194
+ const m = /^(\d+)('?)$/.exec(c);
195
+ const m1 = m && m[1];
196
+ if (!m || m.length !== 3 || typeof m1 !== 'string')
197
+ throw new Error('invalid child index: ' + c);
198
+ let idx = +m1;
199
+ if (!Number.isSafeInteger(idx) || idx >= exports.HARDENED_OFFSET) {
200
+ throw new Error('Invalid index');
201
+ }
202
+ // hardened key
203
+ if (m[2] === "'") {
204
+ idx += exports.HARDENED_OFFSET;
205
+ }
206
+ child = child.deriveChild(idx);
207
+ }
208
+ return child;
209
+ }
210
+ /**
211
+ * @param _I - Test-only override for the 64-byte HMAC-SHA512 output; normal callers must omit it.
212
+ */
213
+ deriveChild(index, _I) {
214
+ if (!this._publicKey || !this.chainCode) {
215
+ throw new Error('No publicKey or chainCode set');
216
+ }
217
+ let data = toU32(index);
218
+ if (index >= exports.HARDENED_OFFSET) {
219
+ // Hardened
220
+ const priv = this._privateKey;
221
+ if (!priv) {
222
+ throw new Error('Could not derive hardened child key');
223
+ }
224
+ // Hardened child: 0x00 || ser256(kpar) || ser32(index)
225
+ data = (0, utils_1.concatBytes)(Uint8Array.of(0), priv, data);
226
+ }
227
+ else {
228
+ // Normal child: serP(point(kpar)) || ser32(index)
229
+ data = (0, utils_1.concatBytes)(this._publicKey, data);
230
+ }
231
+ const out = _I || (0, hmac_1.hmac)(sha2_1.sha512, this.chainCode, data);
232
+ (0, utils_1.abytes)(out, 64);
233
+ const childTweak = out.slice(0, 32);
234
+ const chainCode = out.slice(32);
235
+ const opt = {
236
+ versions: this.versions,
237
+ chainCode,
238
+ depth: this.depth + 1,
239
+ parentFingerprint: this.fingerprint,
240
+ index,
241
+ };
242
+ // Fail early instead of re-trying different index
243
+ if (opt.depth > 255) {
244
+ throw new Error('HDKey: depth exceeds the serializable value 255');
245
+ }
246
+ try {
247
+ const ctweak = Fn.fromBytes(childTweak);
248
+ // BIP-32 private derivation retries only when parse256(I_L) >= n or k_i = 0.
249
+ // BIP-32 public derivation retries only when parse256(I_L) >= n or K_i is infinity.
250
+ // So I_L = 0 is valid here; Fn.fromBytes still rejects parse256(I_L) >= n.
251
+ if (this._privateKey) {
252
+ const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak);
253
+ if (!Fn.isValidNot0(added)) {
254
+ throw new Error('The tweak was out of range or the resulted private key is invalid');
255
+ }
256
+ opt.privateKey = Fn.toBytes(added);
257
+ }
258
+ else {
259
+ const point = Point.fromBytes(this._publicKey);
260
+ const added = ctweak === 0n ? point : point.add(Point.BASE.multiply(ctweak));
261
+ // Cryptographically impossible: hmac-sha512 preimage would need to be found
262
+ if (added.equals(Point.ZERO)) {
263
+ throw new Error('The tweak was equal to negative P, which made the result key invalid');
264
+ }
265
+ opt.publicKey = added.toBytes(true);
266
+ }
267
+ return new HDKey(opt);
268
+ }
269
+ catch (err) {
270
+ return this.deriveChild(index + 1);
271
+ }
272
+ }
273
+ sign(hash) {
274
+ if (!this._privateKey) {
275
+ throw new Error('No privateKey set!');
276
+ }
277
+ (0, utils_1.abytes)(hash, 32);
278
+ return secp256k1_1.secp256k1.sign(hash, this._privateKey, { prehash: false });
279
+ }
280
+ verify(hash, signature) {
281
+ (0, utils_1.abytes)(hash, 32);
282
+ (0, utils_1.abytes)(signature, 64);
283
+ if (!this._publicKey) {
284
+ throw new Error('No publicKey set!');
285
+ }
286
+ return secp256k1_1.secp256k1.verify(signature, hash, this._publicKey, { prehash: false });
287
+ }
288
+ wipePrivateData() {
289
+ if (this._privateKey) {
290
+ this._privateKey.fill(0);
291
+ this._privateKey = undefined;
292
+ }
293
+ return this;
294
+ }
295
+ toJSON() {
296
+ return {
297
+ xpriv: this.privateExtendedKey,
298
+ xpub: this.publicExtendedKey,
299
+ };
300
+ }
301
+ serialize(version, key) {
302
+ if (!this.chainCode) {
303
+ throw new Error('No chainCode set');
304
+ }
305
+ (0, utils_1.abytes)(key, 33);
306
+ // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
307
+ return (0, utils_1.concatBytes)(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key);
308
+ }
309
+ }
310
+ exports.HDKey = HDKey;
311
+ exports.__TESTS = Object.freeze({
312
+ deriveChildWithI(key, index, I) {
313
+ // Bytes wrappers widen the exported test seam, but deriveChild still needs concrete inputs.
314
+ return key.deriveChild(index, I);
315
+ },
316
+ });
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@decryption/bip32",
3
+ "version": "0.2.0",
4
+ "description": "Audited & minimal implementation of BIP32 hierarchical deterministic (HD) wallets. Dual CJS+ESM fork of @scure/bip32.",
5
+ "author": "Constructive <developers@constructive.io>",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/decryption",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/decryption"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/decryption/issues"
21
+ },
22
+ "scripts": {
23
+ "copy": "makage assets",
24
+ "clean": "makage clean",
25
+ "prepublishOnly": "npm run build",
26
+ "build": "makage build && cp LICENSE dist/LICENSE",
27
+ "lint": "echo \"vendored fork — linted upstream\" && exit 0",
28
+ "test": "jest",
29
+ "test:watch": "jest --watch"
30
+ },
31
+ "keywords": [
32
+ "bip32",
33
+ "hd",
34
+ "wallet",
35
+ "derivation",
36
+ "hdkey"
37
+ ],
38
+ "dependencies": {
39
+ "@decryption/base": "0.2.0",
40
+ "@decryption/curves": "0.2.0",
41
+ "@decryption/hashes": "0.2.0"
42
+ },
43
+ "devDependencies": {
44
+ "makage": "0.3.0"
45
+ },
46
+ "gitHead": "8d85fbfdbb1d57da93e99904a03e6e8d8531d281"
47
+ }