@decryption/wallet 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 +21 -0
- package/README.md +116 -0
- package/address.d.ts +12 -0
- package/address.js +67 -0
- package/esm/address.js +60 -0
- package/esm/index.js +4 -0
- package/esm/mnemonic.js +53 -0
- package/esm/networks.js +52 -0
- package/esm/wallet.js +52 -0
- package/index.d.ts +4 -0
- package/index.js +20 -0
- package/mnemonic.d.ts +33 -0
- package/mnemonic.js +64 -0
- package/networks.d.ts +30 -0
- package/networks.js +58 -0
- package/package.json +52 -0
- package/wallet.d.ts +36 -0
- package/wallet.js +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Constructive <developers@constructive.io>
|
|
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 all
|
|
13
|
+
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 THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# @decryption/wallet
|
|
2
|
+
|
|
3
|
+
BIP39 mnemonics, BIP32 derivation and address encoding — entirely offline. This package has no
|
|
4
|
+
chain registry, no RPC client and no transaction signing: it turns a mnemonic into addresses and
|
|
5
|
+
stops there.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @decryption/wallet
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import { createWallet, deriveAccounts, assertValidMnemonic } from '@decryption/wallet';
|
|
17
|
+
|
|
18
|
+
const { mnemonic, accounts } = createWallet(['cosmoshub', 'osmosis', 'ethereum'], 24);
|
|
19
|
+
// accounts[0] => { network: 'cosmoshub', path: "m/44'/118'/0'/0/0", address: 'cosmos1…', publicKey: '02…' }
|
|
20
|
+
|
|
21
|
+
assertValidMnemonic(userInput); // throws MnemonicError naming the actual problem
|
|
22
|
+
const restored = deriveAccounts(userInput, ['juno'], { account: 1, index: 3 });
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Chains that are not built in — most cosmos-family chains differ only by prefix and coin type:
|
|
26
|
+
|
|
27
|
+
```typescript
|
|
28
|
+
import { defineNetwork, deriveAccount } from '@decryption/wallet';
|
|
29
|
+
|
|
30
|
+
const dydx = defineNetwork({
|
|
31
|
+
id: 'dydx',
|
|
32
|
+
name: 'dYdX',
|
|
33
|
+
coinType: 118,
|
|
34
|
+
addressEncoding: 'bech32',
|
|
35
|
+
prefix: 'dydx',
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
deriveAccount(mnemonic, dydx);
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Built-in networks
|
|
42
|
+
|
|
43
|
+
| Network | Coin type | Address |
|
|
44
|
+
|---------|-----------|---------|
|
|
45
|
+
| `cosmoshub`, `osmosis`, `juno`, `stargaze`, `akash`, `celestia` | 118 | bech32 |
|
|
46
|
+
| `secret` | 529 | bech32 |
|
|
47
|
+
| `terra` | 330 | bech32 |
|
|
48
|
+
| `ethereum` | 60 | EIP-55 checksummed hex |
|
|
49
|
+
| `bitcoin` | 0 | bech32 P2WPKH |
|
|
50
|
+
|
|
51
|
+
## Mnemonics
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
import { createMnemonic, mnemonicToBytes, bytesToMnemonic } from '@decryption/wallet';
|
|
55
|
+
|
|
56
|
+
createMnemonic(12); // 12/15/18/21/24 words
|
|
57
|
+
mnemonicToBytes(mnemonic); // raw entropy, checksum verified
|
|
58
|
+
bytesToMnemonic(entropy);
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`assertValidMnemonic` distinguishes the three failure modes users actually hit — wrong word count,
|
|
62
|
+
a word outside the wordlist, and a failed checksum — so a UI can say which word is wrong instead
|
|
63
|
+
of "invalid mnemonic".
|
|
64
|
+
|
|
65
|
+
## Private keys
|
|
66
|
+
|
|
67
|
+
`deriveAccount` never returns private material and wipes the HD node before returning. When a
|
|
68
|
+
private key is genuinely needed, ask for it explicitly and zero it when you are done:
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
import { derivePrivateKey } from '@decryption/wallet';
|
|
72
|
+
|
|
73
|
+
const key = derivePrivateKey(mnemonic, 'cosmoshub');
|
|
74
|
+
try {
|
|
75
|
+
/* … */
|
|
76
|
+
} finally {
|
|
77
|
+
key.fill(0);
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## Development
|
|
84
|
+
|
|
85
|
+
### Setup
|
|
86
|
+
|
|
87
|
+
1. Clone the repository:
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
git clone https://github.com/constructive-io/decryption.git
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
2. Install dependencies:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
cd decryption
|
|
97
|
+
pnpm install
|
|
98
|
+
pnpm build
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
3. Test the package of interest:
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
cd packages/<packagename>
|
|
105
|
+
pnpm test:watch
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Credits
|
|
109
|
+
|
|
110
|
+
**🛠 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).**
|
|
111
|
+
|
|
112
|
+
## Disclaimer
|
|
113
|
+
|
|
114
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
115
|
+
|
|
116
|
+
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/address.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Network } from './networks';
|
|
2
|
+
/**
|
|
3
|
+
* Encodes a secp256k1 public key as an address for the given network. Pure computation — no
|
|
4
|
+
* chain registry, no RPC.
|
|
5
|
+
*/
|
|
6
|
+
export declare const publicKeyToAddress: (publicKey: Uint8Array, network: string | Network) => string;
|
|
7
|
+
/** EIP-55 mixed-case checksum encoding. */
|
|
8
|
+
export declare const toChecksumAddress: (hexAddress: string) => string;
|
|
9
|
+
/** Re-encodes a bech32 address under a different prefix, e.g. `cosmos1…` → `osmo1…`. */
|
|
10
|
+
export declare const convertBech32Prefix: (address: string, prefix: string) => string;
|
|
11
|
+
/** True when `address` is well-formed for the network (checksum included). */
|
|
12
|
+
export declare const isValidAddress: (address: string, network: string | Network) => boolean;
|
package/address.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isValidAddress = exports.convertBech32Prefix = exports.toChecksumAddress = exports.publicKeyToAddress = void 0;
|
|
4
|
+
const base_1 = require("@decryption/base");
|
|
5
|
+
const secp256k1_1 = require("@decryption/curves/secp256k1");
|
|
6
|
+
const legacy_1 = require("@decryption/hashes/legacy");
|
|
7
|
+
const sha2_1 = require("@decryption/hashes/sha2");
|
|
8
|
+
const sha3_1 = require("@decryption/hashes/sha3");
|
|
9
|
+
const utils_1 = require("@decryption/hashes/utils");
|
|
10
|
+
const networks_1 = require("./networks");
|
|
11
|
+
/**
|
|
12
|
+
* Encodes a secp256k1 public key as an address for the given network. Pure computation — no
|
|
13
|
+
* chain registry, no RPC.
|
|
14
|
+
*/
|
|
15
|
+
const publicKeyToAddress = (publicKey, network) => {
|
|
16
|
+
const resolved = (0, networks_1.resolveNetwork)(network);
|
|
17
|
+
switch (resolved.addressEncoding) {
|
|
18
|
+
case 'bech32':
|
|
19
|
+
return base_1.bech32.encode(resolved.prefix, base_1.bech32.toWords(cosmosHash(publicKey)));
|
|
20
|
+
case 'p2wpkh':
|
|
21
|
+
return base_1.bech32.encode(resolved.prefix, [0, ...base_1.bech32.toWords(cosmosHash(publicKey))]);
|
|
22
|
+
case 'evm':
|
|
23
|
+
return (0, exports.toChecksumAddress)((0, utils_1.bytesToHex)(evmHash(publicKey)));
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
exports.publicKeyToAddress = publicKeyToAddress;
|
|
27
|
+
/** `RIPEMD160(SHA256(compressed pubkey))` — the cosmos-family and Bitcoin pubkey hash. */
|
|
28
|
+
const cosmosHash = (publicKey) => (0, legacy_1.ripemd160)((0, sha2_1.sha256)(compress(publicKey)));
|
|
29
|
+
/** Last 20 bytes of `KECCAK256(uncompressed pubkey without the 0x04 prefix)`. */
|
|
30
|
+
const evmHash = (publicKey) => (0, sha3_1.keccak_256)(uncompress(publicKey).slice(1)).slice(-20);
|
|
31
|
+
const compress = (publicKey) => publicKey.length === 33 ? publicKey : secp256k1_1.secp256k1.Point.fromBytes(publicKey).toBytes(true);
|
|
32
|
+
const uncompress = (publicKey) => publicKey.length === 65 ? publicKey : secp256k1_1.secp256k1.Point.fromBytes(publicKey).toBytes(false);
|
|
33
|
+
/** EIP-55 mixed-case checksum encoding. */
|
|
34
|
+
const toChecksumAddress = (hexAddress) => {
|
|
35
|
+
const lower = hexAddress.replace(/^0x/, '').toLowerCase();
|
|
36
|
+
const hash = (0, utils_1.bytesToHex)((0, sha3_1.keccak_256)(new TextEncoder().encode(lower)));
|
|
37
|
+
let out = '0x';
|
|
38
|
+
for (let i = 0; i < lower.length; i++) {
|
|
39
|
+
out += parseInt(hash[i], 16) >= 8 ? lower[i].toUpperCase() : lower[i];
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
};
|
|
43
|
+
exports.toChecksumAddress = toChecksumAddress;
|
|
44
|
+
/** Re-encodes a bech32 address under a different prefix, e.g. `cosmos1…` → `osmo1…`. */
|
|
45
|
+
const convertBech32Prefix = (address, prefix) => {
|
|
46
|
+
const { words } = base_1.bech32.decode(address);
|
|
47
|
+
return base_1.bech32.encode(prefix, words);
|
|
48
|
+
};
|
|
49
|
+
exports.convertBech32Prefix = convertBech32Prefix;
|
|
50
|
+
/** True when `address` is well-formed for the network (checksum included). */
|
|
51
|
+
const isValidAddress = (address, network) => {
|
|
52
|
+
const resolved = (0, networks_1.resolveNetwork)(network);
|
|
53
|
+
try {
|
|
54
|
+
if (resolved.addressEncoding === 'evm') {
|
|
55
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(address))
|
|
56
|
+
return false;
|
|
57
|
+
const lower = address.toLowerCase();
|
|
58
|
+
return address === lower || address === (0, exports.toChecksumAddress)(lower);
|
|
59
|
+
}
|
|
60
|
+
const { prefix } = base_1.bech32.decode(address);
|
|
61
|
+
return prefix === resolved.prefix;
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
exports.isValidAddress = isValidAddress;
|
package/esm/address.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { bech32 } from '@decryption/base';
|
|
2
|
+
import { secp256k1 } from '@decryption/curves/secp256k1';
|
|
3
|
+
import { ripemd160 } from '@decryption/hashes/legacy';
|
|
4
|
+
import { sha256 } from '@decryption/hashes/sha2';
|
|
5
|
+
import { keccak_256 } from '@decryption/hashes/sha3';
|
|
6
|
+
import { bytesToHex } from '@decryption/hashes/utils';
|
|
7
|
+
import { resolveNetwork } from './networks';
|
|
8
|
+
/**
|
|
9
|
+
* Encodes a secp256k1 public key as an address for the given network. Pure computation — no
|
|
10
|
+
* chain registry, no RPC.
|
|
11
|
+
*/
|
|
12
|
+
export const publicKeyToAddress = (publicKey, network) => {
|
|
13
|
+
const resolved = resolveNetwork(network);
|
|
14
|
+
switch (resolved.addressEncoding) {
|
|
15
|
+
case 'bech32':
|
|
16
|
+
return bech32.encode(resolved.prefix, bech32.toWords(cosmosHash(publicKey)));
|
|
17
|
+
case 'p2wpkh':
|
|
18
|
+
return bech32.encode(resolved.prefix, [0, ...bech32.toWords(cosmosHash(publicKey))]);
|
|
19
|
+
case 'evm':
|
|
20
|
+
return toChecksumAddress(bytesToHex(evmHash(publicKey)));
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
/** `RIPEMD160(SHA256(compressed pubkey))` — the cosmos-family and Bitcoin pubkey hash. */
|
|
24
|
+
const cosmosHash = (publicKey) => ripemd160(sha256(compress(publicKey)));
|
|
25
|
+
/** Last 20 bytes of `KECCAK256(uncompressed pubkey without the 0x04 prefix)`. */
|
|
26
|
+
const evmHash = (publicKey) => keccak_256(uncompress(publicKey).slice(1)).slice(-20);
|
|
27
|
+
const compress = (publicKey) => publicKey.length === 33 ? publicKey : secp256k1.Point.fromBytes(publicKey).toBytes(true);
|
|
28
|
+
const uncompress = (publicKey) => publicKey.length === 65 ? publicKey : secp256k1.Point.fromBytes(publicKey).toBytes(false);
|
|
29
|
+
/** EIP-55 mixed-case checksum encoding. */
|
|
30
|
+
export const toChecksumAddress = (hexAddress) => {
|
|
31
|
+
const lower = hexAddress.replace(/^0x/, '').toLowerCase();
|
|
32
|
+
const hash = bytesToHex(keccak_256(new TextEncoder().encode(lower)));
|
|
33
|
+
let out = '0x';
|
|
34
|
+
for (let i = 0; i < lower.length; i++) {
|
|
35
|
+
out += parseInt(hash[i], 16) >= 8 ? lower[i].toUpperCase() : lower[i];
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
};
|
|
39
|
+
/** Re-encodes a bech32 address under a different prefix, e.g. `cosmos1…` → `osmo1…`. */
|
|
40
|
+
export const convertBech32Prefix = (address, prefix) => {
|
|
41
|
+
const { words } = bech32.decode(address);
|
|
42
|
+
return bech32.encode(prefix, words);
|
|
43
|
+
};
|
|
44
|
+
/** True when `address` is well-formed for the network (checksum included). */
|
|
45
|
+
export const isValidAddress = (address, network) => {
|
|
46
|
+
const resolved = resolveNetwork(network);
|
|
47
|
+
try {
|
|
48
|
+
if (resolved.addressEncoding === 'evm') {
|
|
49
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(address))
|
|
50
|
+
return false;
|
|
51
|
+
const lower = address.toLowerCase();
|
|
52
|
+
return address === lower || address === toChecksumAddress(lower);
|
|
53
|
+
}
|
|
54
|
+
const { prefix } = bech32.decode(address);
|
|
55
|
+
return prefix === resolved.prefix;
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
};
|
package/esm/index.js
ADDED
package/esm/mnemonic.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { entropyToMnemonic, generateMnemonic, mnemonicToEntropy, mnemonicToSeedSync, validateMnemonic, } from '@decryption/bip39';
|
|
2
|
+
import { wordlist as english } from '@decryption/bip39/wordlists/english';
|
|
3
|
+
/** Word counts permitted by BIP39, mapped to their entropy size in bits. */
|
|
4
|
+
export const WORD_COUNTS = { 12: 128, 15: 160, 18: 192, 21: 224, 24: 256 };
|
|
5
|
+
export class MnemonicError extends Error {
|
|
6
|
+
constructor(message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = new.target.name;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
const resolveWordlist = (options = {}) => options.wordlist ?? english;
|
|
12
|
+
/** Generates a fresh BIP39 mnemonic. Entropy comes from the platform CSPRNG. */
|
|
13
|
+
export const createMnemonic = (words = 24, options) => {
|
|
14
|
+
const strength = WORD_COUNTS[words];
|
|
15
|
+
if (!strength) {
|
|
16
|
+
throw new MnemonicError(`word count must be one of ${Object.keys(WORD_COUNTS).join(', ')}, got ${words}`);
|
|
17
|
+
}
|
|
18
|
+
return generateMnemonic(resolveWordlist(options), strength);
|
|
19
|
+
};
|
|
20
|
+
/** True when every word is in the wordlist and the BIP39 checksum holds. */
|
|
21
|
+
export const isValidMnemonic = (mnemonic, options) => validateMnemonic(normalizeMnemonic(mnemonic), resolveWordlist(options));
|
|
22
|
+
/**
|
|
23
|
+
* Throws a {@link MnemonicError} naming the actual problem — an unknown word, the wrong number of
|
|
24
|
+
* words, or a failed checksum — instead of a bare boolean.
|
|
25
|
+
*/
|
|
26
|
+
export const assertValidMnemonic = (mnemonic, options) => {
|
|
27
|
+
const wordlist = resolveWordlist(options);
|
|
28
|
+
const words = normalizeMnemonic(mnemonic).split(' ');
|
|
29
|
+
if (!(words.length in WORD_COUNTS)) {
|
|
30
|
+
throw new MnemonicError(`expected ${Object.keys(WORD_COUNTS).join('/')} words, got ${words.length}`);
|
|
31
|
+
}
|
|
32
|
+
const unknown = words.filter((word) => !wordlist.includes(word));
|
|
33
|
+
if (unknown.length) {
|
|
34
|
+
throw new MnemonicError(`not in the wordlist: ${[...new Set(unknown)].join(', ')}`);
|
|
35
|
+
}
|
|
36
|
+
if (!validateMnemonic(words.join(' '), wordlist)) {
|
|
37
|
+
throw new MnemonicError('mnemonic checksum is invalid: check the word order and spelling');
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
/** Collapses whitespace and lowercases, the normalization every BIP39 tool expects. */
|
|
41
|
+
export const normalizeMnemonic = (mnemonic) => mnemonic.trim().toLowerCase().split(/\s+/).join(' ');
|
|
42
|
+
/** BIP39 seed derivation (PBKDF2-HMAC-SHA512, 2048 iterations). */
|
|
43
|
+
export const mnemonicToSeed = (mnemonic, passphrase = '') => {
|
|
44
|
+
assertValidMnemonic(mnemonic);
|
|
45
|
+
return mnemonicToSeedSync(normalizeMnemonic(mnemonic), passphrase);
|
|
46
|
+
};
|
|
47
|
+
/** Raw entropy behind a mnemonic — useful for converting between word counts and formats. */
|
|
48
|
+
export const mnemonicToBytes = (mnemonic, options) => {
|
|
49
|
+
assertValidMnemonic(mnemonic, options);
|
|
50
|
+
return mnemonicToEntropy(normalizeMnemonic(mnemonic), resolveWordlist(options));
|
|
51
|
+
};
|
|
52
|
+
/** Inverse of {@link mnemonicToBytes}. */
|
|
53
|
+
export const bytesToMnemonic = (entropy, options) => entropyToMnemonic(entropy, resolveWordlist(options));
|
package/esm/networks.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
const cosmos = (id, name, prefix, coinType = 118) => ({
|
|
2
|
+
id,
|
|
3
|
+
name,
|
|
4
|
+
coinType,
|
|
5
|
+
addressEncoding: 'bech32',
|
|
6
|
+
prefix,
|
|
7
|
+
});
|
|
8
|
+
/** Built-in networks. Anything missing can be supplied with {@link defineNetwork}. */
|
|
9
|
+
export const NETWORKS = {
|
|
10
|
+
cosmoshub: cosmos('cosmoshub', 'Cosmos Hub', 'cosmos'),
|
|
11
|
+
osmosis: cosmos('osmosis', 'Osmosis', 'osmo'),
|
|
12
|
+
juno: cosmos('juno', 'Juno', 'juno'),
|
|
13
|
+
stargaze: cosmos('stargaze', 'Stargaze', 'stars'),
|
|
14
|
+
akash: cosmos('akash', 'Akash', 'akash'),
|
|
15
|
+
celestia: cosmos('celestia', 'Celestia', 'celestia'),
|
|
16
|
+
secret: cosmos('secret', 'Secret Network', 'secret', 529),
|
|
17
|
+
terra: cosmos('terra', 'Terra', 'terra', 330),
|
|
18
|
+
ethereum: {
|
|
19
|
+
id: 'ethereum',
|
|
20
|
+
name: 'Ethereum',
|
|
21
|
+
coinType: 60,
|
|
22
|
+
addressEncoding: 'evm',
|
|
23
|
+
},
|
|
24
|
+
bitcoin: {
|
|
25
|
+
id: 'bitcoin',
|
|
26
|
+
name: 'Bitcoin',
|
|
27
|
+
coinType: 0,
|
|
28
|
+
addressEncoding: 'p2wpkh',
|
|
29
|
+
prefix: 'bc',
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Builds a network definition for a chain that is not built in — the common case for
|
|
34
|
+
* cosmos-family chains, which differ only by bech32 prefix and coin type.
|
|
35
|
+
*/
|
|
36
|
+
export const defineNetwork = (network) => {
|
|
37
|
+
if (network.addressEncoding !== 'evm' && !network.prefix) {
|
|
38
|
+
throw new Error(`network ${network.id} requires a bech32 prefix`);
|
|
39
|
+
}
|
|
40
|
+
return network;
|
|
41
|
+
};
|
|
42
|
+
export const resolveNetwork = (network) => {
|
|
43
|
+
if (typeof network !== 'string')
|
|
44
|
+
return defineNetwork(network);
|
|
45
|
+
const found = NETWORKS[network];
|
|
46
|
+
if (!found) {
|
|
47
|
+
throw new Error(`unknown network "${network}"; known: ${Object.keys(NETWORKS).join(', ')} (use defineNetwork for others)`);
|
|
48
|
+
}
|
|
49
|
+
return found;
|
|
50
|
+
};
|
|
51
|
+
/** BIP44 path for a network: `m/44'/coinType'/account'/change/index`. */
|
|
52
|
+
export const derivationPath = (network, { account = 0, change = 0, index = 0 } = {}) => `m/44'/${network.coinType}'/${account}'/${change}/${index}`;
|
package/esm/wallet.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { HDKey } from '@decryption/bip32';
|
|
2
|
+
import { bytesToHex } from '@decryption/hashes/utils';
|
|
3
|
+
import { publicKeyToAddress } from './address';
|
|
4
|
+
import { createMnemonic, mnemonicToSeed } from './mnemonic';
|
|
5
|
+
import { derivationPath, resolveNetwork } from './networks';
|
|
6
|
+
/** Derives one account. The private key never leaves this function. */
|
|
7
|
+
export const deriveAccount = (mnemonic, network, options = {}) => {
|
|
8
|
+
const resolved = resolveNetwork(network);
|
|
9
|
+
const { hd, path } = deriveHdKey(mnemonic, resolved, options);
|
|
10
|
+
try {
|
|
11
|
+
const publicKey = hd.publicKey;
|
|
12
|
+
if (!publicKey)
|
|
13
|
+
throw new Error('derivation produced no public key');
|
|
14
|
+
return {
|
|
15
|
+
network: resolved.id,
|
|
16
|
+
path,
|
|
17
|
+
address: publicKeyToAddress(publicKey, resolved),
|
|
18
|
+
publicKey: bytesToHex(publicKey),
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
finally {
|
|
22
|
+
hd.wipePrivateData();
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Derives the private key for an account. Callers are responsible for zeroing the result;
|
|
27
|
+
* everything else in this package avoids materializing private keys at all.
|
|
28
|
+
*/
|
|
29
|
+
export const derivePrivateKey = (mnemonic, network, options = {}) => {
|
|
30
|
+
const { hd } = deriveHdKey(mnemonic, resolveNetwork(network), options);
|
|
31
|
+
const privateKey = hd.privateKey;
|
|
32
|
+
if (!privateKey)
|
|
33
|
+
throw new Error('derivation produced no private key');
|
|
34
|
+
return Uint8Array.from(privateKey);
|
|
35
|
+
};
|
|
36
|
+
/** Derives the same account index across several networks — the usual "show me my addresses" view. */
|
|
37
|
+
export const deriveAccounts = (mnemonic, networks, options = {}) => networks.map((network) => deriveAccount(mnemonic, network, options));
|
|
38
|
+
/** Generates a new mnemonic and derives its first account on each requested network. */
|
|
39
|
+
export const createWallet = (networks = ['cosmoshub'], words = 24, options = {}) => {
|
|
40
|
+
const mnemonic = createMnemonic(words);
|
|
41
|
+
return { mnemonic, accounts: deriveAccounts(mnemonic, networks, options) };
|
|
42
|
+
};
|
|
43
|
+
const deriveHdKey = (mnemonic, network, options) => {
|
|
44
|
+
const path = options.path ?? derivationPath(network, options);
|
|
45
|
+
const seed = mnemonicToSeed(mnemonic, options.passphrase ?? '');
|
|
46
|
+
try {
|
|
47
|
+
return { hd: HDKey.fromMasterSeed(seed).derive(path), path };
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
seed.fill(0);
|
|
51
|
+
}
|
|
52
|
+
};
|
package/index.d.ts
ADDED
package/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./address"), exports);
|
|
18
|
+
__exportStar(require("./mnemonic"), exports);
|
|
19
|
+
__exportStar(require("./networks"), exports);
|
|
20
|
+
__exportStar(require("./wallet"), exports);
|
package/mnemonic.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Word counts permitted by BIP39, mapped to their entropy size in bits. */
|
|
2
|
+
export declare const WORD_COUNTS: {
|
|
3
|
+
readonly 12: 128;
|
|
4
|
+
readonly 15: 160;
|
|
5
|
+
readonly 18: 192;
|
|
6
|
+
readonly 21: 224;
|
|
7
|
+
readonly 24: 256;
|
|
8
|
+
};
|
|
9
|
+
export type WordCount = keyof typeof WORD_COUNTS;
|
|
10
|
+
export declare class MnemonicError extends Error {
|
|
11
|
+
constructor(message: string);
|
|
12
|
+
}
|
|
13
|
+
export interface MnemonicOptions {
|
|
14
|
+
/** BIP39 wordlist. Defaults to English. */
|
|
15
|
+
wordlist?: string[];
|
|
16
|
+
}
|
|
17
|
+
/** Generates a fresh BIP39 mnemonic. Entropy comes from the platform CSPRNG. */
|
|
18
|
+
export declare const createMnemonic: (words?: WordCount, options?: MnemonicOptions) => string;
|
|
19
|
+
/** True when every word is in the wordlist and the BIP39 checksum holds. */
|
|
20
|
+
export declare const isValidMnemonic: (mnemonic: string, options?: MnemonicOptions) => boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Throws a {@link MnemonicError} naming the actual problem — an unknown word, the wrong number of
|
|
23
|
+
* words, or a failed checksum — instead of a bare boolean.
|
|
24
|
+
*/
|
|
25
|
+
export declare const assertValidMnemonic: (mnemonic: string, options?: MnemonicOptions) => void;
|
|
26
|
+
/** Collapses whitespace and lowercases, the normalization every BIP39 tool expects. */
|
|
27
|
+
export declare const normalizeMnemonic: (mnemonic: string) => string;
|
|
28
|
+
/** BIP39 seed derivation (PBKDF2-HMAC-SHA512, 2048 iterations). */
|
|
29
|
+
export declare const mnemonicToSeed: (mnemonic: string, passphrase?: string) => Uint8Array;
|
|
30
|
+
/** Raw entropy behind a mnemonic — useful for converting between word counts and formats. */
|
|
31
|
+
export declare const mnemonicToBytes: (mnemonic: string, options?: MnemonicOptions) => Uint8Array;
|
|
32
|
+
/** Inverse of {@link mnemonicToBytes}. */
|
|
33
|
+
export declare const bytesToMnemonic: (entropy: Uint8Array, options?: MnemonicOptions) => string;
|
package/mnemonic.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.bytesToMnemonic = exports.mnemonicToBytes = exports.mnemonicToSeed = exports.normalizeMnemonic = exports.assertValidMnemonic = exports.isValidMnemonic = exports.createMnemonic = exports.MnemonicError = exports.WORD_COUNTS = void 0;
|
|
4
|
+
const bip39_1 = require("@decryption/bip39");
|
|
5
|
+
const english_1 = require("@decryption/bip39/wordlists/english");
|
|
6
|
+
/** Word counts permitted by BIP39, mapped to their entropy size in bits. */
|
|
7
|
+
exports.WORD_COUNTS = { 12: 128, 15: 160, 18: 192, 21: 224, 24: 256 };
|
|
8
|
+
class MnemonicError extends Error {
|
|
9
|
+
constructor(message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = new.target.name;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
exports.MnemonicError = MnemonicError;
|
|
15
|
+
const resolveWordlist = (options = {}) => options.wordlist ?? english_1.wordlist;
|
|
16
|
+
/** Generates a fresh BIP39 mnemonic. Entropy comes from the platform CSPRNG. */
|
|
17
|
+
const createMnemonic = (words = 24, options) => {
|
|
18
|
+
const strength = exports.WORD_COUNTS[words];
|
|
19
|
+
if (!strength) {
|
|
20
|
+
throw new MnemonicError(`word count must be one of ${Object.keys(exports.WORD_COUNTS).join(', ')}, got ${words}`);
|
|
21
|
+
}
|
|
22
|
+
return (0, bip39_1.generateMnemonic)(resolveWordlist(options), strength);
|
|
23
|
+
};
|
|
24
|
+
exports.createMnemonic = createMnemonic;
|
|
25
|
+
/** True when every word is in the wordlist and the BIP39 checksum holds. */
|
|
26
|
+
const isValidMnemonic = (mnemonic, options) => (0, bip39_1.validateMnemonic)((0, exports.normalizeMnemonic)(mnemonic), resolveWordlist(options));
|
|
27
|
+
exports.isValidMnemonic = isValidMnemonic;
|
|
28
|
+
/**
|
|
29
|
+
* Throws a {@link MnemonicError} naming the actual problem — an unknown word, the wrong number of
|
|
30
|
+
* words, or a failed checksum — instead of a bare boolean.
|
|
31
|
+
*/
|
|
32
|
+
const assertValidMnemonic = (mnemonic, options) => {
|
|
33
|
+
const wordlist = resolveWordlist(options);
|
|
34
|
+
const words = (0, exports.normalizeMnemonic)(mnemonic).split(' ');
|
|
35
|
+
if (!(words.length in exports.WORD_COUNTS)) {
|
|
36
|
+
throw new MnemonicError(`expected ${Object.keys(exports.WORD_COUNTS).join('/')} words, got ${words.length}`);
|
|
37
|
+
}
|
|
38
|
+
const unknown = words.filter((word) => !wordlist.includes(word));
|
|
39
|
+
if (unknown.length) {
|
|
40
|
+
throw new MnemonicError(`not in the wordlist: ${[...new Set(unknown)].join(', ')}`);
|
|
41
|
+
}
|
|
42
|
+
if (!(0, bip39_1.validateMnemonic)(words.join(' '), wordlist)) {
|
|
43
|
+
throw new MnemonicError('mnemonic checksum is invalid: check the word order and spelling');
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
exports.assertValidMnemonic = assertValidMnemonic;
|
|
47
|
+
/** Collapses whitespace and lowercases, the normalization every BIP39 tool expects. */
|
|
48
|
+
const normalizeMnemonic = (mnemonic) => mnemonic.trim().toLowerCase().split(/\s+/).join(' ');
|
|
49
|
+
exports.normalizeMnemonic = normalizeMnemonic;
|
|
50
|
+
/** BIP39 seed derivation (PBKDF2-HMAC-SHA512, 2048 iterations). */
|
|
51
|
+
const mnemonicToSeed = (mnemonic, passphrase = '') => {
|
|
52
|
+
(0, exports.assertValidMnemonic)(mnemonic);
|
|
53
|
+
return (0, bip39_1.mnemonicToSeedSync)((0, exports.normalizeMnemonic)(mnemonic), passphrase);
|
|
54
|
+
};
|
|
55
|
+
exports.mnemonicToSeed = mnemonicToSeed;
|
|
56
|
+
/** Raw entropy behind a mnemonic — useful for converting between word counts and formats. */
|
|
57
|
+
const mnemonicToBytes = (mnemonic, options) => {
|
|
58
|
+
(0, exports.assertValidMnemonic)(mnemonic, options);
|
|
59
|
+
return (0, bip39_1.mnemonicToEntropy)((0, exports.normalizeMnemonic)(mnemonic), resolveWordlist(options));
|
|
60
|
+
};
|
|
61
|
+
exports.mnemonicToBytes = mnemonicToBytes;
|
|
62
|
+
/** Inverse of {@link mnemonicToBytes}. */
|
|
63
|
+
const bytesToMnemonic = (entropy, options) => (0, bip39_1.entropyToMnemonic)(entropy, resolveWordlist(options));
|
|
64
|
+
exports.bytesToMnemonic = bytesToMnemonic;
|
package/networks.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Offline network definitions: enough to derive and encode an address, and nothing else.
|
|
3
|
+
* There are no RPC endpoints here by design — this package never touches the network.
|
|
4
|
+
*/
|
|
5
|
+
export interface Network {
|
|
6
|
+
/** Lookup key, e.g. `cosmoshub`. */
|
|
7
|
+
id: string;
|
|
8
|
+
/** Human-readable name. */
|
|
9
|
+
name: string;
|
|
10
|
+
/** SLIP-44 coin type used in the derivation path. */
|
|
11
|
+
coinType: number;
|
|
12
|
+
/** How a public key becomes an address. */
|
|
13
|
+
addressEncoding: 'bech32' | 'evm' | 'p2wpkh';
|
|
14
|
+
/** Bech32 human-readable part, for `bech32` and `p2wpkh` encodings. */
|
|
15
|
+
prefix?: string;
|
|
16
|
+
}
|
|
17
|
+
/** Built-in networks. Anything missing can be supplied with {@link defineNetwork}. */
|
|
18
|
+
export declare const NETWORKS: Record<string, Network>;
|
|
19
|
+
/**
|
|
20
|
+
* Builds a network definition for a chain that is not built in — the common case for
|
|
21
|
+
* cosmos-family chains, which differ only by bech32 prefix and coin type.
|
|
22
|
+
*/
|
|
23
|
+
export declare const defineNetwork: (network: Network) => Network;
|
|
24
|
+
export declare const resolveNetwork: (network: string | Network) => Network;
|
|
25
|
+
/** BIP44 path for a network: `m/44'/coinType'/account'/change/index`. */
|
|
26
|
+
export declare const derivationPath: (network: Network, { account, change, index }?: {
|
|
27
|
+
account?: number;
|
|
28
|
+
change?: number;
|
|
29
|
+
index?: number;
|
|
30
|
+
}) => string;
|
package/networks.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.derivationPath = exports.resolveNetwork = exports.defineNetwork = exports.NETWORKS = void 0;
|
|
4
|
+
const cosmos = (id, name, prefix, coinType = 118) => ({
|
|
5
|
+
id,
|
|
6
|
+
name,
|
|
7
|
+
coinType,
|
|
8
|
+
addressEncoding: 'bech32',
|
|
9
|
+
prefix,
|
|
10
|
+
});
|
|
11
|
+
/** Built-in networks. Anything missing can be supplied with {@link defineNetwork}. */
|
|
12
|
+
exports.NETWORKS = {
|
|
13
|
+
cosmoshub: cosmos('cosmoshub', 'Cosmos Hub', 'cosmos'),
|
|
14
|
+
osmosis: cosmos('osmosis', 'Osmosis', 'osmo'),
|
|
15
|
+
juno: cosmos('juno', 'Juno', 'juno'),
|
|
16
|
+
stargaze: cosmos('stargaze', 'Stargaze', 'stars'),
|
|
17
|
+
akash: cosmos('akash', 'Akash', 'akash'),
|
|
18
|
+
celestia: cosmos('celestia', 'Celestia', 'celestia'),
|
|
19
|
+
secret: cosmos('secret', 'Secret Network', 'secret', 529),
|
|
20
|
+
terra: cosmos('terra', 'Terra', 'terra', 330),
|
|
21
|
+
ethereum: {
|
|
22
|
+
id: 'ethereum',
|
|
23
|
+
name: 'Ethereum',
|
|
24
|
+
coinType: 60,
|
|
25
|
+
addressEncoding: 'evm',
|
|
26
|
+
},
|
|
27
|
+
bitcoin: {
|
|
28
|
+
id: 'bitcoin',
|
|
29
|
+
name: 'Bitcoin',
|
|
30
|
+
coinType: 0,
|
|
31
|
+
addressEncoding: 'p2wpkh',
|
|
32
|
+
prefix: 'bc',
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Builds a network definition for a chain that is not built in — the common case for
|
|
37
|
+
* cosmos-family chains, which differ only by bech32 prefix and coin type.
|
|
38
|
+
*/
|
|
39
|
+
const defineNetwork = (network) => {
|
|
40
|
+
if (network.addressEncoding !== 'evm' && !network.prefix) {
|
|
41
|
+
throw new Error(`network ${network.id} requires a bech32 prefix`);
|
|
42
|
+
}
|
|
43
|
+
return network;
|
|
44
|
+
};
|
|
45
|
+
exports.defineNetwork = defineNetwork;
|
|
46
|
+
const resolveNetwork = (network) => {
|
|
47
|
+
if (typeof network !== 'string')
|
|
48
|
+
return (0, exports.defineNetwork)(network);
|
|
49
|
+
const found = exports.NETWORKS[network];
|
|
50
|
+
if (!found) {
|
|
51
|
+
throw new Error(`unknown network "${network}"; known: ${Object.keys(exports.NETWORKS).join(', ')} (use defineNetwork for others)`);
|
|
52
|
+
}
|
|
53
|
+
return found;
|
|
54
|
+
};
|
|
55
|
+
exports.resolveNetwork = resolveNetwork;
|
|
56
|
+
/** BIP44 path for a network: `m/44'/coinType'/account'/change/index`. */
|
|
57
|
+
const derivationPath = (network, { account = 0, change = 0, index = 0 } = {}) => `m/44'/${network.coinType}'/${account}'/${change}/${index}`;
|
|
58
|
+
exports.derivationPath = derivationPath;
|
package/package.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@decryption/wallet",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Offline BIP39/BIP32 wallets and address derivation for cosmos-family, EVM and Bitcoin",
|
|
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",
|
|
27
|
+
"lint": "eslint . --fix",
|
|
28
|
+
"test": "jest",
|
|
29
|
+
"test:watch": "jest --watch"
|
|
30
|
+
},
|
|
31
|
+
"keywords": [
|
|
32
|
+
"bip39",
|
|
33
|
+
"bip32",
|
|
34
|
+
"wallet",
|
|
35
|
+
"mnemonic",
|
|
36
|
+
"bech32",
|
|
37
|
+
"cosmos",
|
|
38
|
+
"ethereum",
|
|
39
|
+
"offline"
|
|
40
|
+
],
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"@decryption/base": "0.2.0",
|
|
43
|
+
"@decryption/bip32": "0.2.0",
|
|
44
|
+
"@decryption/bip39": "0.2.0",
|
|
45
|
+
"@decryption/curves": "0.2.0",
|
|
46
|
+
"@decryption/hashes": "0.2.0"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"makage": "0.3.0"
|
|
50
|
+
},
|
|
51
|
+
"gitHead": "8d85fbfdbb1d57da93e99904a03e6e8d8531d281"
|
|
52
|
+
}
|
package/wallet.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { WordCount } from './mnemonic';
|
|
2
|
+
import { Network } from './networks';
|
|
3
|
+
export interface AccountOptions {
|
|
4
|
+
/** BIP44 account index (`m/44'/coin'/<account>'/…`). */
|
|
5
|
+
account?: number;
|
|
6
|
+
/** BIP44 change index — 0 for external addresses. */
|
|
7
|
+
change?: number;
|
|
8
|
+
/** BIP44 address index. */
|
|
9
|
+
index?: number;
|
|
10
|
+
/** Optional BIP39 passphrase (the "25th word"). */
|
|
11
|
+
passphrase?: string;
|
|
12
|
+
/** Derivation path override. When set, `account`/`change`/`index` are ignored. */
|
|
13
|
+
path?: string;
|
|
14
|
+
}
|
|
15
|
+
export interface Account {
|
|
16
|
+
network: string;
|
|
17
|
+
path: string;
|
|
18
|
+
address: string;
|
|
19
|
+
/** Compressed secp256k1 public key, hex-encoded. */
|
|
20
|
+
publicKey: string;
|
|
21
|
+
}
|
|
22
|
+
/** Derives one account. The private key never leaves this function. */
|
|
23
|
+
export declare const deriveAccount: (mnemonic: string, network: string | Network, options?: AccountOptions) => Account;
|
|
24
|
+
/**
|
|
25
|
+
* Derives the private key for an account. Callers are responsible for zeroing the result;
|
|
26
|
+
* everything else in this package avoids materializing private keys at all.
|
|
27
|
+
*/
|
|
28
|
+
export declare const derivePrivateKey: (mnemonic: string, network: string | Network, options?: AccountOptions) => Uint8Array;
|
|
29
|
+
/** Derives the same account index across several networks — the usual "show me my addresses" view. */
|
|
30
|
+
export declare const deriveAccounts: (mnemonic: string, networks: (string | Network)[], options?: AccountOptions) => Account[];
|
|
31
|
+
export interface CreateWalletResult {
|
|
32
|
+
mnemonic: string;
|
|
33
|
+
accounts: Account[];
|
|
34
|
+
}
|
|
35
|
+
/** Generates a new mnemonic and derives its first account on each requested network. */
|
|
36
|
+
export declare const createWallet: (networks?: (string | Network)[], words?: WordCount, options?: AccountOptions) => CreateWalletResult;
|
package/wallet.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createWallet = exports.deriveAccounts = exports.derivePrivateKey = exports.deriveAccount = void 0;
|
|
4
|
+
const bip32_1 = require("@decryption/bip32");
|
|
5
|
+
const utils_1 = require("@decryption/hashes/utils");
|
|
6
|
+
const address_1 = require("./address");
|
|
7
|
+
const mnemonic_1 = require("./mnemonic");
|
|
8
|
+
const networks_1 = require("./networks");
|
|
9
|
+
/** Derives one account. The private key never leaves this function. */
|
|
10
|
+
const deriveAccount = (mnemonic, network, options = {}) => {
|
|
11
|
+
const resolved = (0, networks_1.resolveNetwork)(network);
|
|
12
|
+
const { hd, path } = deriveHdKey(mnemonic, resolved, options);
|
|
13
|
+
try {
|
|
14
|
+
const publicKey = hd.publicKey;
|
|
15
|
+
if (!publicKey)
|
|
16
|
+
throw new Error('derivation produced no public key');
|
|
17
|
+
return {
|
|
18
|
+
network: resolved.id,
|
|
19
|
+
path,
|
|
20
|
+
address: (0, address_1.publicKeyToAddress)(publicKey, resolved),
|
|
21
|
+
publicKey: (0, utils_1.bytesToHex)(publicKey),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
finally {
|
|
25
|
+
hd.wipePrivateData();
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
exports.deriveAccount = deriveAccount;
|
|
29
|
+
/**
|
|
30
|
+
* Derives the private key for an account. Callers are responsible for zeroing the result;
|
|
31
|
+
* everything else in this package avoids materializing private keys at all.
|
|
32
|
+
*/
|
|
33
|
+
const derivePrivateKey = (mnemonic, network, options = {}) => {
|
|
34
|
+
const { hd } = deriveHdKey(mnemonic, (0, networks_1.resolveNetwork)(network), options);
|
|
35
|
+
const privateKey = hd.privateKey;
|
|
36
|
+
if (!privateKey)
|
|
37
|
+
throw new Error('derivation produced no private key');
|
|
38
|
+
return Uint8Array.from(privateKey);
|
|
39
|
+
};
|
|
40
|
+
exports.derivePrivateKey = derivePrivateKey;
|
|
41
|
+
/** Derives the same account index across several networks — the usual "show me my addresses" view. */
|
|
42
|
+
const deriveAccounts = (mnemonic, networks, options = {}) => networks.map((network) => (0, exports.deriveAccount)(mnemonic, network, options));
|
|
43
|
+
exports.deriveAccounts = deriveAccounts;
|
|
44
|
+
/** Generates a new mnemonic and derives its first account on each requested network. */
|
|
45
|
+
const createWallet = (networks = ['cosmoshub'], words = 24, options = {}) => {
|
|
46
|
+
const mnemonic = (0, mnemonic_1.createMnemonic)(words);
|
|
47
|
+
return { mnemonic, accounts: (0, exports.deriveAccounts)(mnemonic, networks, options) };
|
|
48
|
+
};
|
|
49
|
+
exports.createWallet = createWallet;
|
|
50
|
+
const deriveHdKey = (mnemonic, network, options) => {
|
|
51
|
+
const path = options.path ?? (0, networks_1.derivationPath)(network, options);
|
|
52
|
+
const seed = (0, mnemonic_1.mnemonicToSeed)(mnemonic, options.passphrase ?? '');
|
|
53
|
+
try {
|
|
54
|
+
return { hd: bip32_1.HDKey.fromMasterSeed(seed).derive(path), path };
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
seed.fill(0);
|
|
58
|
+
}
|
|
59
|
+
};
|