CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-polkadot--util-crypto

A collection of useful crypto utilities for Polkadot ecosystem projects

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

key-derivation.mddocs/

Hierarchical Key Derivation

Hierarchical deterministic key derivation supporting both hard and soft derivation paths for creating multiple keys from a single seed following BIP32-style derivation.

Capabilities

Path-Based Key Derivation

Derive keys from hierarchical paths using standard derivation notation.

/**
 * Derive key from hierarchical path
 * @param pair - Parent key pair
 * @param path - Derivation path (e.g., "//hard/soft/path")
 * @param type - Key type for derivation
 * @returns Derived key pair
 */
function keyFromPath(pair: Keypair, path: string, type: KeypairType): Keypair;

/**
 * Extract path components from derivation string
 * @param path - Full derivation path with optional password
 * @returns Parsed path components
 */
function keyExtractPath(path: string): { path: string; password?: string };

/**
 * Extract SURI (Secret URI) components
 * @param suri - Secret URI containing mnemonic and derivation
 * @returns Parsed SURI components
 */
function keyExtractSuri(suri: string): { phrase: string; path: string; password?: string };

Usage Example:

import { 
  sr25519PairFromSeed, 
  keyFromPath, 
  keyExtractPath,
  mnemonicToMiniSecret 
} from "@polkadot/util-crypto";

const mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
const seed = mnemonicToMiniSecret(mnemonic);
const rootPair = sr25519PairFromSeed(seed);

// Derive keys from paths
const alicePair = keyFromPath(rootPair, "//Alice", "sr25519");
const bobPair = keyFromPath(rootPair, "//Bob", "sr25519");
const childPair = keyFromPath(alicePair, "/soft/path", "sr25519");

// Extract path components
const { path, password } = keyExtractPath("//hard/soft///password");
console.log(path); // "//hard/soft"
console.log(password); // "password"

Algorithm-Specific Derivation

Hierarchical key derivation functions for specific cryptographic algorithms.

/**
 * Sr25519 hierarchical key derivation
 * @param seed - Parent seed
 * @param path - Derivation path
 * @returns Derived key pair
 */
function keyHdkdSr25519(seed: Uint8Array, path: string): Keypair;

/**
 * Ed25519 hierarchical key derivation
 * @param seed - Parent seed
 * @param path - Derivation path
 * @returns Derived key pair
 */
function keyHdkdEd25519(seed: Uint8Array, path: string): Keypair;

/**
 * ECDSA hierarchical key derivation
 * @param seed - Parent seed
 * @param path - Derivation path
 * @returns Derived key pair
 */
function keyHdkdEcdsa(seed: Uint8Array, path: string): Keypair;

Ethereum-Compatible HD Derivation

BIP32-compatible hierarchical deterministic key derivation for Ethereum.

/**
 * Ethereum-compatible HD key derivation (BIP32)
 * @param seed - Master seed
 * @param path - BIP32 derivation path (e.g., "m/44'/60'/0'/0/0")
 * @returns Derived key pair
 */
function hdEthereum(seed: Uint8Array, path?: string): Keypair;

Usage Example:

import { hdEthereum, mnemonicToLegacySeed } from "@polkadot/util-crypto";

const mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
const seed = mnemonicToLegacySeed(mnemonic);

// Ethereum account derivation paths
const account0 = hdEthereum(seed, "m/44'/60'/0'/0/0");
const account1 = hdEthereum(seed, "m/44'/60'/0'/0/1");

// Custom derivation path
const customPath = hdEthereum(seed, "m/44'/60'/1'/0/0");

Ledger-Compatible Derivation

Derivation compatible with Ledger hardware wallets.

/**
 * Ledger-compatible key derivation
 * @param mnemonic - 24-word mnemonic (or 25 with password)
 * @param path - Derivation path
 * @param rounds - Number of PBKDF2 rounds (default: 2048)
 * @returns Derived Ed25519 key pair
 */
function hdLedger(mnemonic: string, path: string, rounds?: number): Keypair;

Usage Example:

import { hdLedger } from "@polkadot/util-crypto";

// 24-word mnemonic
const mnemonic24 = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art";
const ledgerKey = hdLedger(mnemonic24, "m/44'/354'/0'/0'/0'");

// 25-word mnemonic (24 words + password)
const mnemonic25 = mnemonic24 + " password";
const ledgerKeyWithPassword = hdLedger(mnemonic25, "m/44'/354'/0'/0'/0'");

Hierarchical Deterministic Key Derivation (HDKD)

Lower-level HDKD functions for specific cryptographic schemes.

/**
 * SR25519 hierarchical deterministic key derivation
 * @param keypair - Parent keypair
 * @param junction - Derivation junction with chain code and hard/soft flag
 * @returns Derived keypair
 */
function keyHdkdSr25519(keypair: Keypair, junction: DeriveJunction): Keypair;

/**
 * Ed25519 hierarchical deterministic key derivation (hard derivation only)
 * @param keypair - Parent keypair  
 * @param junction - Derivation junction with chain code and hard flag
 * @returns Derived keypair
 */
function keyHdkdEd25519(keypair: Keypair, junction: DeriveJunction): Keypair;

/**
 * ECDSA/secp256k1 hierarchical deterministic key derivation (hard derivation only)
 * @param keypair - Parent keypair
 * @param junction - Derivation junction with chain code and hard flag  
 * @returns Derived keypair
 */
function keyHdkdEcdsa(keypair: Keypair, junction: DeriveJunction): Keypair;

SURI Extraction

Extracts components from Substrate URI (SURI) format strings.

interface ExtractResult {
  derivePath: string;
  password?: string;
  path: DeriveJunction[];
  phrase: string;
}

/**
 * Extract phrase, path and password from SURI format
 * @param suri - SURI string in format `<secret>/<soft-key>//<hard-key>///<password>`
 * @returns Parsed SURI components
 */
function keyExtractSuri(suri: string): ExtractResult;

Path Validation

Validate derivation paths for correctness.

/**
 * Validate hierarchical derivation path
 * @param path - Derivation path to validate
 * @returns true if path is valid
 */
function hdValidatePath(path: string): boolean;

Usage Example:

import { hdValidatePath } from "@polkadot/util-crypto";

console.log(hdValidatePath("m/44'/60'/0'/0/0")); // true
console.log(hdValidatePath("//Alice/stash")); // true
console.log(hdValidatePath("invalid-path")); // false

Derivation Path Notation

Substrate/Polkadot Style

  • //hard - Hard derivation
  • /soft - Soft derivation
  • ///password - Password for derivation
  • //Alice - Named hard derivation
  • /stash - Named soft derivation

BIP32 Style (Ethereum)

  • m/44'/60'/0'/0/0 - BIP32 path
  • ' indicates hardened derivation
  • Numbers are derivation indices

Complete Derivation Example

import {
  cryptoWaitReady,
  mnemonicGenerate,
  mnemonicToMiniSecret,
  sr25519PairFromSeed,
  keyFromPath,
  encodeAddress
} from "@polkadot/util-crypto";

async function createDerivedAccounts() {
  await cryptoWaitReady();
  
  // Generate master mnemonic
  const mnemonic = mnemonicGenerate(24);
  const seed = mnemonicToMiniSecret(mnemonic);
  const rootPair = sr25519PairFromSeed(seed);
  
  // Create derived accounts
  const accounts = {
    alice: keyFromPath(rootPair, "//Alice", "sr25519"),
    bob: keyFromPath(rootPair, "//Bob", "sr25519"),
    stash: keyFromPath(rootPair, "//Alice/stash", "sr25519"),
    controller: keyFromPath(rootPair, "//Alice/controller", "sr25519")
  };
  
  // Generate addresses
  const addresses = Object.fromEntries(
    Object.entries(accounts).map(([name, pair]) => [
      name,
      encodeAddress(pair.publicKey, 0) // Polkadot network
    ])
  );
  
  return { mnemonic, accounts, addresses };
}

Security Considerations

Hard vs Soft Derivation

  • Hard derivation (//): Cannot derive child public keys from parent public key
  • Soft derivation (/): Can derive child public keys, but less secure
  • Use hard derivation for account separation
  • Use soft derivation for address generation

Path Security

  • Keep derivation paths consistent and documented
  • Use meaningful names for derived keys
  • Protect passwords used in derivation paths
  • Consider using standard derivation paths for compatibility

Key Management

  • Store master seed securely
  • Derive keys on-demand rather than storing all derived keys
  • Use appropriate key types for specific use cases
  • Implement proper access controls for derived keys

Install with Tessl CLI

npx tessl i tessl/npm-polkadot--util-crypto

docs

address.md

base-encoding.md

crypto-init.md

ethereum.md

hashing.md

index.md

json-encryption.md

key-derivation-pbkdf.md

key-derivation.md

keypairs.md

mnemonic.md

random.md

signatures.md

tile.json