8000 feat: add deriveElectrumWallet to chain classes by oritwoen · Pull Request #280 · agntn/keys · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ keys/
| Keystore files | `src/utils/store/` | Web3 Secret Storage v3: scrypt/PBKDF2, AES-128-CTR from `@agntn/ciphers/aes` |
| Add BIP/derivation | `src/utils/bip32/`, `bip39/`, `bip44/`, `slip10/` | Subdirs with index.ts |
| Mnemonic to wallet | `src/blockchain.ts` → `deriveHDWallet` + `src/utils/hd.ts` | Bitcoin family infers the address type; Sui overrides it, Cardano and Monero throw, Polkadot walks Substrate junctions |
| Electrum seed | `src/blockchain.ts` → `deriveElectrumWallet` + `src/utils/hd.ts` | Takes `deriveSeed` output, never the phrase; Bitcoin family picks P2WPKH or P2PKH by seed version, Decred and ed25519 throw |
| XRPL family seed | `src/blockchains/xrpl.ts` → `deriveSeedWallet` | `s...`/`sEd...` to account 0 as rippled derives it; `keys_wallet_derive` takes one as `privateKey` |
| Monero seed words | `src/blockchains/monero.ts` → `deriveSeedWallet` + `src/utils/monero-seed.ts` | 25 English words to the spend key, view key and standard address; `keys_wallet_derive` takes them as `privateKey` |
| Scan wallet paths | `src/utils/hd-scan.ts` → `scanSchemes` | Named schemes per chain as data; `keys_hd_wallet_scan` walks them |
Expand Down
28 changes: 14 additions & 14 deletions docs/content/1.guide/4.wallets.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ Things that will bite you:
- Polkadot doesn't walk BIP32 at all. It derives from the entropy, then `//hard` junctions like `//polkadot//0`, the way subkey does. Its [page](/blockchains/polkadot) has the junction rules.
- Monero throws. Its wallets restore from their own 25 words, not BIP39, so `deriveSeedWallet` takes those instead. Its [page](/blockchains/monero) has the word rules.
- Cardano throws. CIP-1852 starts from the entropy, not from the BIP39 seed, and pretending otherwise would hand you addresses that no Cardano wallet recognises.
- Decred throws too. Its HD derivation strips leading zero bytes where BIP32 keeps them, so a plain BIP32 walk lands on the wrong key for some paths and looks fine doing it. `deriveWallet` with a private key works on both.
- Decred throws too. Its HD derivation strips leading zero bytes where BIP32 keeps them, so a plain BIP32 walk lands on the wrong key for some paths and looks fine doing it. `deriveElectrumWallet` throws with it. `deriveWallet` with a private key works on both.

The mnemonic above is the public BIP39 test vector. It's fine for docs and tests and for nothing else.

Expand Down Expand Up @@ -287,27 +287,27 @@ Hardened children are safe. Their tweak hashes the parent private key, and there

## Electrum is a different scheme

`allowInvalidChecksum` doesn't turn BIP39 into Electrum. Use `deriveSeed` from `@agntn/keys/electrum` explicitly:
`allowInvalidChecksum` doesn't turn BIP39 into Electrum. Electrum seeds have their own version prefix and their own PBKDF2. `deriveSeed` from `@agntn/keys/electrum` reads the phrase. The chain walks the seed:

```js
import { deriveSeed, inspect } from "@agntn/keys/electrum";
import { getMasterKeyFromSeed } from "@agntn/keys/bip32";
import { deriveSeed } from "@agntn/keys/electrum";
import Bitcoin from "@agntn/keys/blockchains/bitcoin";

const phrase = "wild father tree among universe such mobile favorite target dynamic credit identify";
inspect(phrase);
const { seed, seedType, scheme } = deriveSeed(phrase);
const child = getMasterKeyFromSeed(seed).derive("m/0'/0/0");
const privateKey = Buffer.from(child.privateKey).toString("hex");
const bitcoin = new Bitcoin();
const addressType = seedType === "segwit" ? "segwit" : "legacy";
const wallet = bitcoin.deriveWallet(privateKey, { compressed: true }, addressType);
wallet.address;
const wallet = new Bitcoin().deriveElectrumWallet(deriveSeed(phrase), "m/0'/0/0");
wallet.address; // bc1q4794m2uuw9jmjszmplfj4wvvr5j272fpnx2cse
wallet.addressType; // "segwit"
```

This public Electrum test vector gives `bc1q4794m2uuw9jmjszmplfj4wvvr5j272fpnx2cse`. The result identifies `scheme` as `electrum` and `seedType` as `segwit`. The seed is 64 bytes, not a master private key. Standard seeds work too. Supply the exact path for the wallet being imported, not necessarily the SegWit path in this example. Inspection also recognizes `old`, `2fa` and `2fa_segwit`. `deriveSeed` rejects all three, along with `unknown`. Old seeds get their own functions, see below.
That's a public Electrum test vector. A SegWit seed writes P2WPKH, a standard one P2PKH, same as Electrum. An explicit address type in the fourth slot still wins. Electrum keeps SegWit addresses under `m/0'/0/i` and standard ones under `m/0/i`. Still, pass the exact path of the wallet you're importing.

Why a method on the chain instead of BIP32 glue? The glue skips the chain's rules. It happily handed Decred a key that `deriveHDWallet` refuses. Now Decred refuses an Electrum seed for the same reason. The ed25519 chains throw, since Electrum walks secp256k1 only. Sui walks it on `secp256k1`, the XRP Ledger refuses its `ed25519` side.

And why not hand the phrase straight to the chain? Telling an old seed apart takes Electrum's 1626-word list. Every chain would drag it along. Even an app that only verifies BIP322 signatures. So the phrase stays with `deriveSeed`. Hand the method anything else and it throws a `TypeError`.

`deriveSeed` returns `scheme`, `seedType` and a 64-byte `seed`. That seed is no master private key. `inspect` names the version without deriving anything. It also recognizes `old`, `2fa` and `2fa_segwit`. `deriveSeed` rejects all three, along with `unknown`. Old seeds get their own functions, see below.

The optional second argument is an Electrum passphrase. Both inputs undergo NFKD, lowercasing, removal of nonzero combining classes, whitespace collapsing and removal of spaces between Electrum's CJK characters. Unlike BIP39, passphrase case, accents and surrounding spaces don't distinguish wallets here. Unicode normalization uses the JavaScript runtime's Unicode tables, so newly assigned characters can differ from older Python/Electrum runtimes.
The optional second argument of `deriveSeed` is an Electrum passphrase. Both inputs undergo NFKD, lowercasing, removal of nonzero combining classes, whitespace collapsing and removal of spaces between Electrum's CJK characters. Unlike BIP39, passphrase case, accents and surrounding spaces don't distinguish wallets here. Unicode normalization uses the JavaScript runtime's Unicode tables, so newly assigned characters can differ from older Python/Electrum runtimes.

### What about seeds from before Electrum 2.0?

Expand Down
40 changes: 39 additions & 1 deletion src/blockchain.ts
8000
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ import {
SLIP132_FORMATS,
type ExtendedKeyFormats,
} from "./utils/extended-key.ts";
import { deriveMnemonicKey } from "./utils/hd.ts";
import { deriveElectrumKey, deriveMnemonicKey } from "./utils/hd.ts";
import type {
AddressType,
Blockchain,
Curve,
ElectrumSeed,
HDWalletOptions,
KeyOptions,
Keys,
Expand Down Expand Up @@ -224,6 +225,43 @@ export abstract class AbstractBlockchain implements Blockchain {
};
}

/**
* Address type an Electrum seed version stands for, on chains that write more than one.
* @param _seedType - Version of the seed the wallet came from
* @returns {AddressType | undefined} The type to write, or undefined to keep the chain's default
*/
protected electrumAddressType(_seedType: "standard" | "segwit"): AddressType | undefined {
return undefined;
}

/**
* Derives a wallet from the seed `deriveSeed` returns, so no chain loads Electrum's word list.
* @param seed - Standard or SegWit seed from `deriveSeed`
* @param path - Derivation path, `m/0/0` for standard seeds and `m/0'/0/0` for SegWit ones
* @param options - Key options of the wallet
* @param addressType - Address type that wins over the one the seed version picks
* @returns {Wallet} The wallet at the path
*/
deriveElectrumWallet(
seed: ElectrumSeed,
path: string,
options?: KeyOptions,
addressType?: AddressType,
): Wallet {
const curve = this.resolveCurve(options);
if (curve !== "secp256k1") {
throw new Error(
`${this.name} ${curve} keys do not derive from Electrum seeds, which walk BIP32 on secp256k1`,
);
}
const privateKey = deriveElectrumKey(seed, path);
return this.deriveWallet(
privateKey,
options,
addressType ?? this.electrumAddressType(seed.seedType),
);
}

/**
* Derives a wallet from the chain's own seed string, which only the XRP Ledger and Monero have:
* a family seed (`s...`) and 25 seed words. Every other chain takes a private key or BIP39 words.
Expand Down
6 changes: 3 additions & 3 deletions src/blockchains/AGENTS.md
8BD0
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Lazy-loaded class modules. Each file exports a named concrete class and the same
| **CryptoNote** | monero | none yet, SigV2 throws | 25 seed words to the spend key |
| **dual-curve** | sui, xrpl | Sui's `PersonalMessage` digest; XRPL DER over SHA-512Half, ed25519 raw | Sui ed25519 first, XRPL secp256k1 |

Decred uses `AbstractBlockchain` directly: ECDSA P2PKH with BLAKE-256, not Bitcoin address hashing or EVM signing. Its HD method throws because standard BIP32 does not preserve Decred's legacy derivation.
Decred uses `AbstractBlockchain` directly: ECDSA P2PKH with BLAKE-256, not Bitcoin address hashing or EVM signing. Its HD and Electrum methods throw because standard BIP32 does not preserve Decred's legacy derivation.

## ADDING A NEW CHAIN

Expand Down Expand Up @@ -51,9 +51,9 @@ Decred uses `AbstractBlockchain` directly: ECDSA P2PKH with BLAKE-256, not Bitco
- **EVM base class** - `Ethereum` and `Base` extend `AbstractEVMBlockchain`, which owns their shared key, address, validation, and signing behavior
- **Network params** - Bitcoin Cash and eCash keep their CashAddr prefixes in `CASHADDR_PARAMS`; Bitcoin, Litecoin, Bitcoin Gold, Bitcoin SV, Dash, Dogecoin, Zcash, and Cardano keep separate address parameters for each network in `NETWORK_PARAMS`; TRON uses `0x41` and `T` on mainnet, Shasta, and Nile
- **BIP44 coin type** - every chain sets `bip44` from `BIP44` enum or SLIP-0044 number. Paths read `coinType`, which is `bip44` except on testnet, where the Bitcoin bases and Decred answer SLIP-0044's `1`, as their nodes do, and on `Cosmos`, which follows its prefix
- **Dual-curve base** - `AbstractDualCurveBlockchain` in `utils/dual-curve.ts` reads the address type as the scheme in `deriveWallet`, `deriveHDWallet` and `generateWallet`, so one argument picks key, address and curve on Sui and the XRP Ledger
- **Dual-curve base** - `AbstractDualCurveBlockchain` in `utils/dual-curve.ts` reads the address type as the scheme in `deriveWallet`, `deriveHDWallet`, `deriveElectrumWallet` and `generateWallet`, so one argument picks key, address and curve on Sui and the XRP Ledger
- **SUI dual-curve** - `getKeyPublic` and `signMessage` check `options.scheme` to pick ed25519 or secp256k1, and `resolveCurve` throws on any other scheme; both sign the `signPersonalMessage` digest, secp256k1 over its sha256 like the SDK
- **HD wallets** - `deriveHDWallet` on the base class walks BIP32 or SLIP-10 by curve; Bitcoin, Litecoin and Bitcoin Gold infer the address type from the path purpose, Sui takes the curve from the scheme, Cardano throws because CIP-1852 derives differently
- **HD wallets** - `deriveHDWallet` on the base class walks BIP32 or SLIP-10 by curve; Bitcoin, Litecoin and Bitcoin Gold infer the address type from the path purpose, Sui takes the curve from the scheme, Cardano throws because CIP-1852 derives differently. `deriveElectrumWallet` walks the seed `deriveSeed` returns, never the phrase, so no chain loads Electrum's word list. It walks BIP32 on secp256k1 only, so ed25519 throws; the Bitcoin bases pick P2WPKH or P2PKH from the seed version through `electrumAddressType`
- **Extended public keys** - `deriveXpubWallet` on the base class walks normal levels below an `xpub` (`tpub` on testnet) on secp256k1 chains. `AbstractBitcoinBlockchain` adds SLIP-0132 `ypub`/`zpub` with the type each stands for, Litecoin its `Ltub`/`Mtub`/`ttub`. Decred throws like its `deriveHDWallet`
- **XRP Ledger** - `XRPL` writes ed25519 keys in XRPL's `ED` form and reads the curve from the key when `getAddress` gets no type. `deriveSeedWallet` takes a family seed (`s...`/`sEd...`) through rippled's root and intermediate scalars; the base class throws for every other chain. BIP39 and its path are secp256k1 only, as in xrpl.js, and signatures are ripple-keypairs' DER over SHA-512Half
- **NEAR** - `Near` writes the implicit account, the public key in lowercase hex, and validates only that shape, since no key derives a named or ETH-implicit account. `getAddress` and `verifyMessage` also read NEAR's `ed25519:` and base58 key; the tool executors take that form on `near` only
Expand Down
5 changes: 5 additions & 0 deletions src/blockchains/decred.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ export class Decred extends AbstractBlockchain {
throw new Error("Decred HD derivation is not supported");
}

/** An Electrum seed walks the same standard BIP32, so it lands on the same wrong keys. */
override deriveElectrumWallet(): Wallet {
throw new Error("Decred HD derivation is not supported");
}

/** Decred wallets export `dpub` keys, and its HD derivation is not supported here. */
override deriveXpubWallet(): XpubWallet {
throw new Error("Decred HD derivation is not supported");
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export type {
MessageSigner,
KeyOptions,
HDWalletOptions,
ElectrumSeed,
SigningOptions,
RecoverableSigningOptions,
Options,
Expand Down
12 changes: 3 additions & 9 deletions src/tool-operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import {
} from "./utils/electrum/index.ts";
import {
BIP32ChildMismatchError,
deriveHDKey,
getMasterKeyFromSeed,
recoverParent,
type RecoveredParent,
Expand Down Expand Up @@ -1561,14 +1560,9 @@ export async function deriveElectrumWallet(
}
const path = electrumPath(pathValue, change !== undefined || index !== undefined);
const { blockchain } = await getBlockchain("bitcoin", networkValue);
const { seed, seedType, scheme } = deriveElectrumSeed(mnemonic, passphrase);
const privateKey = deriveHDKey(getMasterKeyFromSeed(seed), path).privateKey;
if (!privateKey) throw new Error("No private key at the supplied path");
const wallet = blockchain.deriveWallet(
privateKey.toHex(),
{ compressed: true },
seedType === "segwit" ? "segwit" : "legacy",
);
const seed = deriveElectrumSeed(mnemonic, passphrase);
const wallet = blockchain.deriveElectrumWallet(seed, path);
const { scheme, seedType } = seed;
const details = {
chain: "bitcoin",
network: blockchain.network,
Expand Down
16 changes: 16 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,14 @@ export interface HDWalletOptions extends KeyOptions {
readonly wordlist?: readonly string[];
}

/** Standard or SegWit Electrum seed, as `deriveSeed` in `@agntn/keys/electrum` returns it. */
export interface ElectrumSeed {
readonly scheme: "electrum";
readonly seedType: "standard" | "segwit";
/** 64 bytes of PBKDF2 output, not a master private key. */
readonly seed: Uint8Array;
}

/**
* Options for a chain that fixes its own curve and digest but can still append the recovery byte.
*/
Expand Down Expand Up @@ -274,6 +282,14 @@ export interface Blockchain extends BlockchainImplementation {
addressType?: string,
) => Wallet;

/** Derives a complete wallet from an Electrum seed and derivation path. */
deriveElectrumWallet?: (
seed: ElectrumSeed,
path: string,
options?: KeyOptions,
addressType?: string,
) => Wallet;

/**
* Derives a watch-only wallet from an extended public key and normal levels below it.
*/
Expand Down
2 changes: 1 addition & 1 deletion src/utils/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Shared cryptographic primitives and encoding utilities. BIP32, BIP38, BIP322, BI
| `encoding.ts` | ~60 | address.ts, tron, zcash | Base58Check encode/decode/validate |
| `crypto-hash.ts` | ~70 | (internal) | Hash function wrappers |
| `bytes.ts` | ~15 | signing, wif, decred, stellar, sui, zcash | `concatBytes`, the one byte helper without a native equivalent |
| `hd.ts` | ~130 | blockchain.ts, tool-operations.ts, polkadot | Mnemonic to a key at a path: BIP32, SLIP-10, or the entropy Substrate starts from; names the BIP39 check a phrase fails |
| `hd.ts` | ~130 | blockchain.ts, tool-operations.ts, polkadot | Mnemonic to a key at a path: BIP32, SLIP-10, or the entropy Substrate starts from; Electrum seeds; names the BIP39 check a phrase fails |
| `monero-seed.ts` | | monero | Monero's English seed list; 25 or 24 words to the 32 bytes of the spend key, checksum word by CRC-32 |
| `monero-base58.ts` | ~60 | monero | Monero's block base58: 8 bytes per block, each padded to a fixed width |
| `ss58.ts` | ~100 | polkadot | SS58 for a 32-byte account under a one or two byte network prefix, blake2b-512 checksum |
Expand Down
9 changes: 9 additions & 0 deletions src/utils/bitcoin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,15 @@ export abstract class AbstractBitcoinBlockchain extends AbstractBitcoinMessageBl
return super.deriveHDWallet(mnemonic, path, options, addressType ?? inferredType);
}

/**
* SegWit seeds write P2WPKH and standard seeds P2PKH, as Electrum does with them.
* @param seedType - Version of the Electrum seed
* @returns {AddressType} The address type Electrum gives that version
*/
protected override electrumAddressType(seedType: "standard" | "segwit"): AddressType {
return seedType === "segwit" ? "segwit" : "legacy";
}

/**
* SLIP-0132 prefixes, so a `zpub` writes SegWit and a `ypub` P2SH without being told.
* @returns {ExtendedKeyFormats} Bitcoin's single signature prefixes on this network
Expand Down
12 changes: 11 additions & 1 deletion src/utils/dual-curve.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AbstractBlockchain } from "../blockchain.ts";
import type { AddressType, HDWalletOptions, KeyOptions, Wallet } from "../types.ts";
import type { AddressType, ElectrumSeed, HDWalletOptions, KeyOptions, Wallet } from "../types.ts";

/**
* Lets the address type name the signature scheme, so one argument drives key, address, and curve.
Expand Down Expand Up @@ -41,6 +41,16 @@ export abstract class AbstractDualCurveBlockchain extends AbstractBlockchain {
return super.deriveHDWallet(mnemonic, path, keyOptions, scheme);
}

override deriveElectrumWallet(
seed: ElectrumSeed,
path: string,
options?: KeyOptions,
addressType?: AddressType,
): Wallet {
const { scheme, keyOptions } = withScheme(options, addressType);
return super.deriveElectrumWallet(seed, path, keyOptions, scheme);
}

override generateWallet(options?: KeyOptions, addressType?: AddressType): Wallet {
const { scheme, keyOptions } = withScheme(options, addressType);
return super.generateWallet(keyOptions, scheme);
Expand Down
Loading
Loading
0