npm package: @subwallet/keyring
Description: Basic packages of SubWallet
Author: AnhMTV
Latest version: 0.1.14

# @subwallet/keyring

A comprehensive keyring library for managing cryptographic keypairs across multiple blockchain ecosystems. This library extends the functionality of `@polkadot/keyring` to support various blockchain networks including Substrate-based chains, Ethereum, Bitcoin, TON, and Cardano.

## Overview

The keyring provides a unified interface for creating, managing, and using cryptographic keypairs across different blockchain protocols. It supports both hierarchical deterministic (HD) wallets and individual keypair management with secure storage capabilities.

## Keyring Architecture Diagram
The following diagram illustrates the hierarchical structure of the keyring system, organized by cryptographic standards and target ecosystems:

```mermaid
%%{init: {"theme": "dark"}}%%
graph TD
    A["@subwallet/keyring"] --> B["Substrate Native Cryptography"]
    A --> C["BIP-44 Hierarchical Deterministic"]
    A --> D["Native Blockchain Standards"]

    %% Substrate Native Branch
    B --> E["sr25519<br/>Schnorr over Curve25519"]
    B --> F["ed25519<br/>Edwards Curve25519"]
    B --> G["ecdsa<br/>ECDSA over secp256k1"]
    
    E --> E1["Polkadot Ecosystem<br/>SS58 Address Format<br/>VRF Support"]
    F --> F1["Polkadot Ecosystem<br/>SS58 Address Format<br/>High Performance"]
    G --> G1["Polkadot Ecosystem<br/>SS58 Address Format<br/>Bitcoin Compatible"]

    %% BIP-44 HD Branch
    C --> H["Ethereum Ecosystem<br/>m/44'/60'/0'/0/x"]
    C --> I["Bitcoin Ecosystem"]
    C --> J["Cardano Ecosystem<br/>m/1852'/1815'/0'"]
    C --> K["TON Standard<br/>m/44'/607'/0'/0/x"]

    %% Ethereum Sub-branch
    H --> H1["ethereum<br/>secp256k1<br/>EIP-712 Support"]
    H1 --> H2["EVM Networks<br/>Ethereum, Polygon, BSC<br/>Arbitrum, Optimism"]

    %% Bitcoin Sub-branch
    I --> L["Legacy P2PKH<br/>m/44'/0'/0'/0/x"]
    I --> M["SegWit P2WPKH<br/>m/84'/0'/0'/0/x"]
    I --> N["Taproot P2TR<br/>m/86'/0'/0'/0/x"]
    
    L --> L1["bitcoin-44 (Mainnet)<br/>bittest-44 (Testnet)"]
    M --> M1["bitcoin-84 (Mainnet)<br/>bittest-84 (Testnet)"]
    N --> N1["bitcoin-86 (Mainnet)<br/>bittest-86 (Testnet)"]

    L1 --> L2["Bitcoin Network<br/>Legacy Addresses (1...)<br/>PSBT Support"]
    M1 --> M2["Bitcoin Network<br/>SegWit Addresses (bc1q...)<br/>Lower Fees"]
    N1 --> N2["Bitcoin Network<br/>Taproot Addresses (bc1p...)<br/>Privacy & Flexibility"]

    %% Cardano Sub-branch
    J --> J1["cardano<br/>BIP32-Ed25519<br/>CIP-1852 Standard"]
    J1 --> J2["Cardano Network<br/>Base & Reward Addresses<br/>CIP-8 Message Signing"]
    %% TON Standard Sub-branch
    K --> K1["ton<br/>BIP39 Compatible<br/>Multiple Contract Versions"]
    K1 --> K2["TON Blockchain<br/>Smart Contract Wallets<br/>v3r1, v3r2, v4, v5r1"]

    %% Native Standards Branch
    D --> O["TON Native Standard"]
    O --> O1["ton-native<br/>24-word Native Format<br/>Custom Validation"]
    O1 --> O2["TON Blockchain<br/>Native Mnemonic<br/>Direct Seed Conversion"]

    %% Styling
    classDef substrate fill:#263238,stroke:#4fc3f7,stroke-width:2px
    classDef bip44 fill:#4527a0,stroke:#ce93d8,stroke-width:2px
    classDef native fill:#3e2723,stroke:#ffb74d,stroke-width:2px
    classDef ecosystem fill:#1b5e20,stroke:#81c784,stroke-width:2px
    classDef keytype fill:#827717,stroke:#fff176,stroke-width:2px

    class B,E,F,G,E1,F1,G1 substrate
    class C,H,I,J,K,H1,L,M,N,L1,M1,N1,J1,K1 bip44
    class D,O,O1 native
    class H2,L2,M2,N2,J2,K2,O2 ecosystem
    class H1,L1,M1,N1,J1,K1,O1 keytype
```

### Key Components Explained

#### Cryptographic Standards
- **Substrate Native**: Purpose-built cryptography for Substrate-based blockchains
- **BIP-44 HD**: Industry-standard hierarchical deterministic wallet derivation
- **Native Standards**: Blockchain-specific mnemonic and key generation

#### Derivation Paths
- **Substrate**: `//hard/soft` paths with SS58 encoding
- **Ethereum**: `m/44'/60'/0'/0/x` (BIP-44 standard)
- **Bitcoin**: `m/44'/0'/0'/0/x` (P2PKH), `m/84'/0'/0'/0/x` (P2WPKH), `m/86'/0'/0'/0/x` (P2TR)
- **Cardano**: `m/1852'/1815'/0'` (CIP-1852 standard)
- **TON**: `m/44'/607'/0'/0/x` (BIP-44) or native seed conversion

#### Network Support
Each keyring type supports specific blockchain networks and address formats, ensuring compatibility with their respective ecosystems while maintaining security and standard compliance.

## Supported Keyring Types

### 1. Substrate Keypairs (`sr25519`, `ed25519`, `ecdsa`)

**Libraries Used:**
- `@polkadot/util-crypto` - Core cryptographic functions
- `@polkadot/util` - Utility functions

**How it works:**
- **sr25519**: Schnorr signature algorithm over Curve25519, the default for Polkadot/Substrate
- **ed25519**: Edwards-curve Digital Signature Algorithm over Curve25519
- **ecdsa**: Elliptic Curve Digital Signature Algorithm over secp256k1

**Key Features:**
- SS58 address encoding
- Hierarchical derivation using soft and hard paths
- VRF (Verifiable Random Function) support for sr25519
- Multi-signature compatibility

**Usage Example:**
```typescript
import { Keyring } from '@subwallet/keyring';

const keyring = new Keyring({ type: 'sr25519' });
const pair = keyring.addFromMnemonic('your mnemonic phrase here');

// Sign a message
const message = 'Hello Polkadot';
const signature = pair.sign(message);

// Derive child keypairs
const child = pair.substrate.derive('//hard/soft', { name: 'Child Account' });
```

### 2. Ethereum Keypairs (`ethereum`)

**Libraries Used:**
- `@metamask/eth-simple-keyring` - Ethereum transaction and message signing
- `@metamask/eth-sig-util` - Typed data signing utilities
- `@ethereumjs/tx` - Ethereum transaction handling
- `@polkadot/util-crypto` - HD wallet derivation

**How it works:**
- Uses secp256k1 elliptic curve cryptography
- Supports BIP44 hierarchical derivation (m/44'/60'/0'/0/x)
- Compatible with MetaMask and other Ethereum wallets
- Handles various Ethereum signing methods

**Key Features:**
- EIP-712 typed data signing
- Personal message signing
- Transaction signing with gas estimation
- HD derivation with custom paths
- Compatible with all EVM-based networks

**Usage Example:**
```typescript
const keyring = new Keyring({ type: 'ethereum' });
const pair = keyring.addFromMnemonic('your mnemonic phrase here');

// Sign a transaction
import { Transaction } from '@ethereumjs/tx';
const tx = Transaction.fromTxData({ /* transaction data */ });
const signedTx = pair.evm.signTransaction(tx);

// Sign typed data (EIP-712)
const typedData = { /* EIP-712 structured data */ };
const signature = await pair.evm.signMessage(typedData, 'eth_signTypedData_v4');

// Derive accounts
const account0 = pair.evm.derive(0); // m/44'/60'/0'/0/0
const account1 = pair.evm.derive(1); // m/44'/60'/0'/0/1
```

### 3. Bitcoin Keypairs (`bitcoin-44`, `bitcoin-84`, `bitcoin-86`, `bittest-44`, `bittest-84`, `bittest-86`)

**Libraries Used:**
- `bitcoinjs-lib` - Bitcoin transaction and address handling
- `ecpair` - ECDSA keypair management
- `tiny-secp256k1` - Secp256k1 elliptic curve operations
- `bip322-js` - BIP-322 message signing

**How it works:**
- **P2PKH (44)**: Pay-to-Public-Key-Hash, legacy Bitcoin addresses starting with '1'
- **P2WPKH (84)**: Pay-to-Witness-Public-Key-Hash, SegWit v0 addresses starting with 'bc1q'
- **P2TR (86)**: Pay-to-Taproot, SegWit v1 addresses starting with 'bc1p'

**Key Features:**
- Multi-format address support
- PSBT (Partially Signed Bitcoin Transaction) handling
- BIP-322 message signing
- Taproot and SegWit support
- Mainnet and testnet compatibility

**Usage Example:**
```typescript
const keyring = new Keyring({ type: 'sr25519' });

// Bitcoin mainnet P2WPKH (SegWit)
const btcPair = keyring.addFromMnemonic('mnemonic', {}, 'bitcoin-84');

// Sign a PSBT
import { Psbt } from 'bitcoinjs-lib';
const psbt = new Psbt({ network: bitcoin.networks.bitcoin });
// ... add inputs and outputs
const signedPsbt = btcPair.bitcoin.signTransaction(psbt, [0], [1]); // Sign input 0 with SIGHASH_ALL

// Sign a message
const message = 'Hello Bitcoin';
const signature = btcPair.bitcoin.signMessage(message);

// Derive accounts
const account0 = btcPair.bitcoin.derive(0); // m/84'/0'/0'/0/0
```

### 4. TON Keypairs (`ton`, `ton-native`)

**Libraries Used:**
- `@ton/core` - TON blockchain core functionality
- `@ton/crypto` - TON cryptographic operations
- `@ton/ton` - TON wallet contracts

**How it works:**
- **ton**: BIP44-compatible derivation with standard mnemonic
- **ton-native**: Native TON mnemonic format (24 words with custom validation)

**Key Features:**
- Multiple wallet contract versions (v3r1, v3r2, v4, v5r1)
- Bounceable and non-bounceable address formats
- Cell-based message signing
- Native TON mnemonic support

**Wallet Contract Versions:**
- **v3r1/v3r2**: Legacy wallet contracts
- **v4**: Standard wallet with improved features
- **v5r1**: Latest wallet with plugin support (default)

**Usage Example:**
```typescript
// Standard BIP44 TON wallet
const tonPair = keyring.addFromMnemonic('standard bip39 mnemonic', {}, 'ton');

// Native TON wallet
const tonNativePair = keyring.addFromMnemonic('24 word ton mnemonic', {}, 'ton-native');

// Sign a cell
import { Cell } from '@ton/core';
const cell = new Cell();
const signature = tonPair.ton.sign(cell);

// Get different contract versions
const v4Address = tonPair.ton.contractWithVersion('v4').address;
const v5Address = tonPair.ton.contractWithVersion('v5r1').address;

// Change contract version
keyring.changeTonWalletContractVersion(tonPair.address, 'v4');
```

### 5. Cardano Keypairs (`cardano`)

**Libraries Used:**
- `@emurgo/cardano-serialization-lib-nodejs` - Cardano transaction serialization
- `@emurgo/cardano-message-signing-browser` - CIP-8 message signing
- Custom BIP32-Ed25519 implementation

**How it works:**
- Uses BIP32-Ed25519 hierarchical derivation
- Follows CIP-1852 derivation standard (m/1852'/1815'/0')
- Supports both mainnet and testnet addresses
- Implements CIP-8 message signing standard

**Key Features:**
- Base addresses and reward addresses
- Payment and stake key derivation
- CIP-8 compliant message signing
- Transaction witness generation
- Multi-network support (mainnet/testnet)

**Usage Example:**
```typescript
const cardanoPair = keyring.addFromMnemonic('cardano mnemonic', {}, 'cardano');

// Sign a transaction
const txHex = '84a500...'; // CBOR transaction hex
const signedTx = cardanoPair.cardano.signTransaction(txHex);

// Sign a message (CIP-8)
const message = Buffer.from('Hello Cardano', 'utf8').toString('hex');
const { signature, key } = cardanoPair.cardano.signMessage(message, cardanoPair.address);

// Get reward address
const rewardAddress = cardanoPair.cardano.rewardAddress;

// Derive accounts
const account1 = cardanoPair.cardano.derive(1); // m/1852'/1815'/1'
```

## Advanced Features

### Master Password Management

The keyring supports master password functionality for enhanced security:

```typescript
const keyring = new Keyring();

// Setup master password
keyring.changeMasterPassword('your-master-password');

// Create encrypted pairs
const pair = keyring.addFromMnemonic('mnemonic');
const json = keyring.createJsonPairWithMasterPassword(pair);

// Unlock keyring
keyring.unlockKeyring('your-master-password');

// Unlock specific pair
keyring.unlockPair(pair.address);
```

### Multi-Chain Address Management

Handle multiple blockchain addresses from a single mnemonic:

```typescript
const mnemonic = 'your 24 word mnemonic phrase';

// Create keypairs for different networks
const substrateKP = keyring.addFromMnemonic(mnemonic, {}, 'sr25519');
const ethereumKP = keyring.addFromMnemonic(mnemonic, {}, 'ethereum');
const bitcoinKP = keyring.addFromMnemonic(mnemonic, {}, 'bitcoin-84');
const tonKP = keyring.addFromMnemonic(mnemonic, {}, 'ton');
const cardanoKP = keyring.addFromMnemonic(mnemonic, {}, 'cardano');

console.log('Substrate:', substrateKP.address);
console.log('Ethereum:', ethereumKP.address);
console.log('Bitcoin:', bitcoinKP.address);
console.log('TON:', tonKP.address);
console.log('Cardano:', cardanoKP.address);
```

### Read-Only Accounts

Create watch-only accounts without private keys:

```typescript
// Add read-only account
const readOnlyPair = keyring.addFromAddress(
  'some-blockchain-address',
  {
    isExternal: true,
    isReadOnly: true,
    noPublicKey: true
  },
  null,
  'ethereum'
);
```

## Installation

```bash
npm install @subwallet/keyring
```

## Dependencies

The library relies on several key dependencies:

- **@polkadot/util & @polkadot/util-crypto**: Core utilities and cryptographic functions
- **@emurgo/cardano-***: Cardano blockchain integration
- **@ethereumjs/tx**: Ethereum transaction handling
- **@metamask/eth-***: Ethereum signing utilities
- **@ton/***: TON blockchain integration
- **bitcoinjs-lib**: Bitcoin transaction and address utilities
- **bcryptjs**: Password hashing for master password feature

## Testing

The library includes comprehensive test suites for each keyring type:

```bash
npm test
```

Test files cover:
- Key derivation and address generation
- Message and transaction signing
- Master password functionality
- Multi-network compatibility

## Contributing

Contributions are welcome! Please ensure:
- All tests pass
- New features include appropriate tests
- Code follows the existing style guidelines
- Security implications are considered

## License

Apache-2.0