@midnightntwrk/wallet-sdk-hd 3.0.3

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/README.md ADDED
@@ -0,0 +1,51 @@
1
+ # Midnight SDK HD Wallet
2
+
3
+ This package provides support for Hierarchical Deterministic (HD) Wallet.
4
+
5
+ To allow deterministic derivation of keys for different features, Midnight follows algorithms and structure being a mix
6
+ of [BIP-32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki),
7
+ [BIP-44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) and
8
+ [CIP-1852](https://github.com/cardano-foundation/CIPs/blob/master/CIP-1852/README.md). Specifically, derivation follows
9
+ BIP-32, and following path for a key pair is used:
10
+
11
+ ```
12
+ m / purpose' / coin_type' / account' / role / index
13
+ ```
14
+
15
+ Where:
16
+
17
+ - `purpose` is integer `44` (`0x8000002c`) - despite extensions, Night part of the hierarchy follows BIP-44
18
+ - `coin_type` is integer `2400` (`0x80000960`)
19
+ - `account` follows BIP-44 recommendations
20
+ - `role` follows table below
21
+ - `index` follows BIP-44 recommendations
22
+
23
+ | Role name | Value | Description |
24
+ | -------------------- | ----- | ------------------------------------------------------- |
25
+ | Night External chain | 0 | Night is Midnight's main token of value, Follows BIP-44 |
26
+ | Night Internal chain | 1 | as above |
27
+ | Dust | 2 | Dust is needed to pay fees on Midnight |
28
+ | Zswap | 3 | Zswap is a sub-protocol for shielded native tokens |
29
+ | Metadata | 4 | Keys for signing metadata |
30
+
31
+ ## How to derive the keys?
32
+
33
+ Below you can find an example on how to derive keys from a random seed:
34
+
35
+ ```typescript
36
+ import { generateRandomSeed, HDWallet, Roles } from '@midnightntwrk/wallet-sdk-hd';
37
+
38
+ const seed = generateRandomSeed();
39
+ const generatedWallet = HDWallet.fromSeed(seed);
40
+
41
+ if (generatedWallet.type == 'seedOk') {
42
+ const zswapKey = generatedWallet.hdWallet.selectAccount(0).selectRole(Roles.Zswap).deriveKeyAt(0);
43
+ if (zswapKey.type === 'keyDerived') {
44
+ console.log('success', zswapKey.key);
45
+ } else {
46
+ console.error('Error deriving key');
47
+ }
48
+ } else {
49
+ console.error('Error generating HDWallet');
50
+ }
51
+ ```
@@ -0,0 +1,69 @@
1
+ import { HDKey } from '@scure/bip32';
2
+ type ValueOf<T> = T[keyof T];
3
+ export declare const Roles: {
4
+ readonly NightExternal: 0;
5
+ readonly NightInternal: 1;
6
+ readonly Dust: 2;
7
+ readonly Zswap: 3;
8
+ readonly Metadata: 4;
9
+ };
10
+ export type Role = ValueOf<typeof Roles>;
11
+ type DerivationResult = {
12
+ readonly type: 'keyDerived';
13
+ readonly key: Uint8Array;
14
+ } | {
15
+ readonly type: 'keyOutOfBounds';
16
+ };
17
+ type CompositeDerivationResult<T extends readonly Role[]> = {
18
+ readonly type: 'keysDerived';
19
+ readonly keys: Record<T[number], Uint8Array>;
20
+ } | {
21
+ readonly type: 'keyOutOfBounds';
22
+ readonly roles: readonly Role[];
23
+ };
24
+ type HDWalletResult = {
25
+ readonly type: 'seedOk';
26
+ readonly hdWallet: HDWallet;
27
+ } | {
28
+ readonly type: 'seedError';
29
+ readonly error: unknown;
30
+ };
31
+ declare const CompositeDerivationResult: {
32
+ fromResults: <T extends readonly Role[]>(results: {
33
+ role: T[number];
34
+ result: DerivationResult;
35
+ }[]) => CompositeDerivationResult<T>;
36
+ };
37
+ export declare class HDWallet {
38
+ private readonly rootKey;
39
+ private constructor();
40
+ static fromSeed(seed: Uint8Array): HDWalletResult;
41
+ selectAccount(account: number): AccountKey;
42
+ /**
43
+ * Once all keys are derived - clear internals from private data, so that they do not reside in memory longer than
44
+ * needed.
45
+ */
46
+ clear(): void;
47
+ }
48
+ export declare class AccountKey {
49
+ private readonly rootKey;
50
+ private readonly account;
51
+ constructor(rootKey: HDKey, account: number);
52
+ selectRole(role: Role): RoleKey;
53
+ selectRoles<T extends readonly Role[]>(roles: T): CompositeRoleKey<T>;
54
+ }
55
+ export declare class RoleKey {
56
+ private readonly rootKey;
57
+ private readonly account;
58
+ private readonly role;
59
+ constructor(rootKey: HDKey, account: number, role: Role);
60
+ deriveKeyAt(index: number): DerivationResult;
61
+ }
62
+ export declare class CompositeRoleKey<T extends readonly Role[]> {
63
+ private readonly rootKey;
64
+ private readonly account;
65
+ private readonly roles;
66
+ constructor(rootKey: HDKey, account: number, roles: T);
67
+ deriveKeysAt(index: number): CompositeDerivationResult<T>;
68
+ }
69
+ export {};
@@ -0,0 +1,121 @@
1
+ // This file is part of MIDNIGHT-WALLET-SDK.
2
+ // Copyright (C) Midnight Foundation
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // You may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ import { HARDENED_OFFSET, HDKey } from '@scure/bip32';
14
+ export const Roles = {
15
+ NightExternal: 0,
16
+ NightInternal: 1,
17
+ Dust: 2,
18
+ Zswap: 3,
19
+ Metadata: 4,
20
+ };
21
+ const PURPOSE = 44;
22
+ const COIN_TYPE = 2400;
23
+ // BIP32 path components (account, role, index) are integers in [0, 2^31);
24
+ // @scure/bip32 inlines this check inside derive() and throws, so guard here
25
+ const isValidChildIndex = (value) => Number.isSafeInteger(value) && value >= 0 && value < HARDENED_OFFSET;
26
+ const CompositeDerivationResult = {
27
+ fromResults: (results) => {
28
+ const { succeededKeys, failedRoles } = results.reduce((acc, result) => {
29
+ if (result.result.type === 'keyDerived') {
30
+ acc.succeededKeys[result.role] = result.result.key;
31
+ }
32
+ else {
33
+ acc.failedRoles.push(result.role);
34
+ }
35
+ return acc;
36
+ }, { succeededKeys: {}, failedRoles: [] });
37
+ if (failedRoles.length > 0) {
38
+ return { type: 'keyOutOfBounds', roles: failedRoles };
39
+ }
40
+ else {
41
+ return { type: 'keysDerived', keys: succeededKeys };
42
+ }
43
+ },
44
+ };
45
+ export class HDWallet {
46
+ rootKey;
47
+ constructor(key) {
48
+ this.rootKey = key;
49
+ }
50
+ static fromSeed(seed) {
51
+ try {
52
+ const rootKey = HDKey.fromMasterSeed(seed);
53
+ return { type: 'seedOk', hdWallet: new HDWallet(rootKey) };
54
+ }
55
+ catch (e) {
56
+ return { type: 'seedError', error: e };
57
+ }
58
+ }
59
+ // Begin by selecting an account.
60
+ selectAccount(account) {
61
+ return new AccountKey(this.rootKey, account);
62
+ }
63
+ /**
64
+ * Once all keys are derived - clear internals from private data, so that they do not reside in memory longer than
65
+ * needed.
66
+ */
67
+ clear() {
68
+ this.rootKey.wipePrivateData();
69
+ }
70
+ }
71
+ export class AccountKey {
72
+ rootKey;
73
+ account;
74
+ constructor(rootKey, account) {
75
+ this.account = account;
76
+ this.rootKey = rootKey;
77
+ }
78
+ // After account, select a role.
79
+ selectRole(role) {
80
+ return new RoleKey(this.rootKey, this.account, role);
81
+ }
82
+ selectRoles(roles) {
83
+ return new CompositeRoleKey(this.rootKey, this.account, roles);
84
+ }
85
+ }
86
+ export class RoleKey {
87
+ rootKey;
88
+ account;
89
+ role;
90
+ constructor(rootKey, account, role) {
91
+ this.role = role;
92
+ this.account = account;
93
+ this.rootKey = rootKey;
94
+ }
95
+ // Finally, derive the key at the given index.
96
+ deriveKeyAt(index) {
97
+ if (![this.account, this.role, index].every(isValidChildIndex)) {
98
+ return { type: 'keyOutOfBounds' };
99
+ }
100
+ const path = `m/${PURPOSE}'/${COIN_TYPE}'/${this.account}'/${this.role}/${index}`;
101
+ const derivedKey = this.rootKey.derive(path);
102
+ return derivedKey.privateKey ? { type: 'keyDerived', key: derivedKey.privateKey } : { type: 'keyOutOfBounds' };
103
+ }
104
+ }
105
+ export class CompositeRoleKey {
106
+ rootKey;
107
+ account;
108
+ roles;
109
+ constructor(rootKey, account, roles) {
110
+ this.roles = roles;
111
+ this.rootKey = rootKey;
112
+ this.account = account;
113
+ }
114
+ deriveKeysAt(index) {
115
+ const results = this.roles.map((role) => ({
116
+ role,
117
+ result: new RoleKey(this.rootKey, this.account, role).deriveKeyAt(index),
118
+ }));
119
+ return CompositeDerivationResult.fromResults(results);
120
+ }
121
+ }
@@ -0,0 +1,7 @@
1
+ export declare const mnemonicToWords: (mnemonic: string) => string[];
2
+ /** A wrapper around the bip39 package function, with default strength applied to produce 24 words */
3
+ export declare const generateMnemonicWords: (strength?: number) => string[];
4
+ export declare const joinMnemonicWords: (mnenomic: string[]) => string;
5
+ export declare const generateRandomSeed: (strength?: number) => Uint8Array;
6
+ /** A wrapper around the bip39 package function */
7
+ export declare const validateMnemonic: (mnemonic: string) => boolean;
@@ -0,0 +1,23 @@
1
+ // This file is part of MIDNIGHT-WALLET-SDK.
2
+ // Copyright (C) Midnight Foundation
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // You may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ import * as bip39 from '@scure/bip39';
14
+ import { wordlist as english } from '@scure/bip39/wordlists/english.js';
15
+ export const mnemonicToWords = (mnemonic) => mnemonic.split(' ');
16
+ /** A wrapper around the bip39 package function, with default strength applied to produce 24 words */
17
+ export const generateMnemonicWords = (strength = 256) => mnemonicToWords(bip39.generateMnemonic(english, strength));
18
+ export const joinMnemonicWords = (mnenomic) => mnenomic.join(' ');
19
+ export const generateRandomSeed = (strength = 256) => {
20
+ return crypto.getRandomValues(new Uint8Array(Math.ceil(strength / 8)));
21
+ };
22
+ /** A wrapper around the bip39 package function */
23
+ export const validateMnemonic = (mnemonic) => bip39.validateMnemonic(mnemonic, english);
@@ -0,0 +1,2 @@
1
+ export * from './HDWallet.js';
2
+ export * from './MnemonicUtils.js';
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ // This file is part of MIDNIGHT-WALLET-SDK.
2
+ // Copyright (C) Midnight Foundation
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // You may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ export * from './HDWallet.js';
14
+ export * from './MnemonicUtils.js';
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@midnightntwrk/wallet-sdk-hd",
3
+ "version": "3.0.3",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "author": "Midnight Foundation",
9
+ "license": "Apache-2.0",
10
+ "publishConfig": {
11
+ "registry": "https://registry.npmjs.org/",
12
+ "access": "public"
13
+ },
14
+ "files": [
15
+ "dist/"
16
+ ],
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/midnightntwrk/midnight-wallet.git",
20
+ "directory": "packages/hd"
21
+ },
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js"
26
+ }
27
+ },
28
+ "dependencies": {
29
+ "@scure/bip32": "^2.0.1",
30
+ "@scure/bip39": "^2.0.1"
31
+ },
32
+ "devDependencies": {
33
+ "@ethereumjs/wallet": "10.0.0"
34
+ },
35
+ "scripts": {
36
+ "typecheck": "tsc -b ./tsconfig.json --noEmit --force",
37
+ "test": "vitest run",
38
+ "lint": "eslint --max-warnings 0",
39
+ "format": "prettier --write \"**/*.{ts,js,json,yaml,yml,md}\"",
40
+ "format:check": "prettier --check \"**/*.{ts,js,json,yaml,yml,md}\"",
41
+ "dist": "tsc -b ./tsconfig.build.json",
42
+ "dist:publish": "tsc -b ./tsconfig.publish.json",
43
+ "clean": "rimraf --glob dist 'tsconfig.*.tsbuildinfo' && date +%s > .clean-timestamp",
44
+ "publint": "publint --strict"
45
+ }
46
+ }