BigBlocks Docs
Components/Security

Type42KeyDerivation

BRC-42 compliant deterministic key derivation for Bitcoin applications. Generate consistent keys across different contexts and applications.

BRC-42 compliant deterministic key derivation for Bitcoin applications. Generate consistent keys across different contexts and applications with protocol-specific derivation paths.

View Type42KeyDerivation examples →

Installation

npm install bigblocks

Usage

import { Type42KeyDerivation } from 'bigblocks';

export default function KeyDerivation() {
  return (
    <Type42KeyDerivation
      privateKey="L1aW4aubDFB7yfras2S1mN3bqg9nwySY8nkoLmJebSLD5BWv3ENZ"
      onKeyDerived={(derivedKey) => {
        console.log('Derived key:', derivedKey.address);
        console.log('Invoice:', derivedKey.invoice);
      }}
    />
  );
}

Props

PropTypeDefaultDescription
privateKeystring-Master private key in WIF format
onKeyDerived(derivedKey: DerivedKey) => void-Callback when key derivation completes
classNamestring-Additional CSS classes

DerivedKey Interface

interface DerivedKey {
  wif: string;                    // Derived private key in WIF format
  address: string;                // Bitcoin address
  publicKey: string;              // Public key (hex)
  counterpartyPubKey: string;     // Counterparty public key
  invoice: string;                // Payment invoice string
}

Features

  • BRC-42 Compliance: Follows Bitcoin Request for Comment 42 standard
  • Deterministic Derivation: Same input always produces same output
  • Protocol Segregation: Different keys for different applications
  • Invoice Generation: Automatic payment invoice creation
  • Cross-Application: Consistent keys across different apps
  • Security Isolation: Protocol-specific key separation

Examples

Basic Key Derivation

<Type42KeyDerivation
  privateKey="L1aW4aubDFB7yfras2S1mN3bqg9nwySY8nkoLmJebSLD5BWv3ENZ"
  onKeyDerived={(derived) => {
    console.log('Derived Address:', derived.address);
    console.log('Public Key:', derived.publicKey);
    console.log('Payment Invoice:', derived.invoice);
  }}
/>

Protocol-Specific Derivation

function ProtocolKeyManager() {
  const [socialKey, setSocialKey] = useState(null);
  const [messageKey, setMessageKey] = useState(null);
  const [identityKey, setIdentityKey] = useState(null);

  const masterKey = "L1aW4aubDFB7yfras2S1mN3bqg9nwySY8nkoLmJebSLD5BWv3ENZ";

  return (
    <div className="protocol-keys">
      <div className="key-section">
        <h3>Social Media Keys</h3>
        <Type42KeyDerivation
          privateKey={masterKey}
          onKeyDerived={(key) => {
            setSocialKey(key);
            // Use for social media signing
            configureSocialSigning(key);
          }}
        />
      </div>

      <div className="key-section">
        <h3>Messaging Keys</h3>
        <Type42KeyDerivation
          privateKey={masterKey}
          onKeyDerived={(key) => {
            setMessageKey(key);
            // Use for encrypted messaging
            configureMessaging(key);
          }}
        />
      </div>

      <div className="key-section">
        <h3>Identity Keys</h3>
        <Type42KeyDerivation
          privateKey={masterKey}
          onKeyDerived={(key) => {
            setIdentityKey(key);
            // Use for identity verification
            configureIdentity(key);
          }}
        />
      </div>
    </div>
  );
}

Application-Specific Keys

function AppKeyDerivation() {
  const [appKeys, setAppKeys] = useState({});
  const masterKey = useWallet().privateKey;

  const deriveKeyForApp = (appName) => {
    return (
      <Type42KeyDerivation
        privateKey={masterKey}
        onKeyDerived={(key) => {
          setAppKeys(prev => ({
            ...prev,
            [appName]: key
          }));
          
          // Register key with application
          registerAppKey(appName, key);
        }}
      />
    );
  };

  return (
    <div className="app-keys">
      <h2>Application Keys</h2>
      
      <div className="app-section">
        <h3>Marketplace App</h3>
        {deriveKeyForApp('marketplace')}
      </div>

      <div className="app-section">
        <h3>Gaming App</h3>
        {deriveKeyForApp('gaming')}
      </div>

      <div className="app-section">
        <h3>DeFi App</h3>
        {deriveKeyForApp('defi')}
      </div>
    </div>
  );
}

Multi-Purpose Key Management

function MultiPurposeKeys() {
  const [keys, setKeys] = useState({
    signing: null,
    encryption: null,
    identity: null,
    payment: null
  });

  const masterKey = "L1aW4aubDFB7yfras2S1mN3bqg9nwySY8nkoLmJebSLD5BWv3ENZ";

  return (
    <div className="multipurpose-keys">
      <h2>Multi-Purpose Key Derivation</h2>
      
      {Object.entries(keys).map(([purpose, key]) => (
        <div key={purpose} className="key-purpose">
          <h3>{purpose.charAt(0).toUpperCase() + purpose.slice(1)} Key</h3>
          
          <Type42KeyDerivation
            privateKey={masterKey}
            onKeyDerived={(derivedKey) => {
              setKeys(prev => ({
                ...prev,
                [purpose]: derivedKey
              }));
              
              console.log(`${purpose} key derived:`, derivedKey.address);
            }}
          />
          
          {key && (
            <div className="key-info">
              <p>Address: {key.address}</p>
              <p>Invoice: {key.invoice}</p>
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

Enterprise Key Derivation

function EnterpriseKeyDerivation() {
  const [departmentKeys, setDepartmentKeys] = useState({});
  const [employeeKeys, setEmployeeKeys] = useState({});

  const organizationMasterKey = process.env.ORGANIZATION_MASTER_KEY;

  const deriveDepartmentKey = (department) => (
    <Type42KeyDerivation
      privateKey={organizationMasterKey}
      onKeyDerived={(key) => {
        setDepartmentKeys(prev => ({
          ...prev,
          [department]: key
        }));
        
        // Register department key
        registerDepartmentKey(department, key);
      }}
    />
  );

  return (
    <div className="enterprise-keys">
      <h2>Enterprise Key Management</h2>
      
      <div className="departments">
        <h3>Department Keys</h3>
        
        <div className="department">
          <h4>Finance Department</h4>
          {deriveDepartmentKey('finance')}
        </div>

        <div className="department">
          <h4>Engineering Department</h4>
          {deriveDepartmentKey('engineering')}
        </div>

        <div className="department">
          <h4>Legal Department</h4>
          {deriveDepartmentKey('legal')}
        </div>
      </div>
    </div>
  );
}

Development Environment Keys

function DevEnvironmentKeys() {
  const [envKeys, setEnvKeys] = useState({});
  const devMasterKey = useDevWallet();

  const environments = ['development', 'staging', 'production'];

  return (
    <div className="env-keys">
      <h2>Environment-Specific Keys</h2>
      
      {environments.map(env => (
        <div key={env} className="environment">
          <h3>{env.toUpperCase()} Environment</h3>
          
          <Type42KeyDerivation
            privateKey={devMasterKey}
            onKeyDerived={(key) => {
              setEnvKeys(prev => ({
                ...prev,
                [env]: key
              }));
              
              // Configure environment
              configureEnvironment(env, key);
            }}
          />
          
          {envKeys[env] && (
            <div className="env-config">
              <p>Address: {envKeys[env].address}</p>
              <p>Invoice: {envKeys[env].invoice}</p>
              <button onClick={() => deployToEnvironment(env, envKeys[env])}>
                Deploy to {env}
              </button>
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

Required Context

The component requires the following providers:

import { 
  BitcoinAuthProvider, 
  BitcoinQueryProvider 
} from 'bigblocks';

function App() {
  return (
    <BitcoinAuthProvider>
      <BitcoinQueryProvider>
        <Type42KeyDerivation
          privateKey={privateKey}
          onKeyDerived={handleKeyDerivation}
        />
      </BitcoinQueryProvider>
    </BitcoinAuthProvider>
  );
}

BRC-42 Standard

Specification Overview

BRC-42 (Bitcoin Request for Comment 42) defines a standard for deterministic key derivation:

  1. Protocol Identification: Unique identifiers for different protocols
  2. Derivation Paths: Hierarchical paths for key generation
  3. Key Segregation: Separate keys for different purposes
  4. Cross-Application: Consistent behavior across implementations

Derivation Formula

derivedKey = HMAC-SHA512(masterKey, protocol + purpose + counter)

Where:

  • masterKey: Master private key
  • protocol: Protocol identifier string
  • purpose: Key purpose (signing, encryption, identity)
  • counter: Optional counter for multiple keys

Standard Protocols

ProtocolPurposeDescription
socialSocial media interactionsPosts, likes, follows
messagingPrivate communicationsEncrypted messages
identityIdentity verificationAuthentication, attestation
paymentFinancial transactionsPayments, invoices
gamingGaming applicationsIn-game assets, scores
marketplaceCommerce platformsBuying, selling, escrow

Security Considerations

⚠️ Critical Security Guidelines

  1. Master Key Security

    • Store master key securely (hardware wallet, secure enclave)
    • Never transmit master key over network
    • Use strong entropy for master key generation
  2. Protocol Isolation

    • Use consistent protocol identifiers
    • Never reuse keys across protocols
    • Implement proper access controls
  3. Key Lifecycle

    • Rotate keys periodically
    • Implement key revocation procedures
    • Monitor for key compromise
  4. Implementation Security

    • Validate all inputs
    • Use secure random number generators
    • Implement proper error handling

Best Practices

// Good: Secure key derivation
<Type42KeyDerivation
  privateKey={securelyStoredMasterKey}
  onKeyDerived={(key) => {
    // Validate derived key
    if (validateKey(key)) {
      // Use key securely
      useKeySecurely(key);
    } else {
      handleKeyError();
    }
  }}
/>

Performance Considerations

  • CPU Intensive: Key derivation involves cryptographic operations
  • Memory Usage: Temporary storage of sensitive key material
  • Caching: Avoid caching derived keys in memory
  • Batch Operations: Derive multiple keys efficiently

Error Handling

Common Error Scenarios

<Type42KeyDerivation
  privateKey={privateKey}
  onKeyDerived={(key) => {
    try {
      // Validate derived key
      if (!validateDerivedKey(key)) {
        throw new Error('Invalid derived key');
      }
      
      // Use key
      applyDerivedKey(key);
      
    } catch (error) {
      console.error('Key derivation error:', error.message);
      handleDerivationError(error);
    }
  }}
/>

Validation Checks

  • WIF Format: Ensures proper private key encoding
  • Address Generation: Validates address derivation
  • Public Key: Verifies public key derivation
  • Invoice Format: Validates payment invoice