> For the complete documentation index, see [llms.txt](https://docs.xrpl-commons.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.xrpl-commons.org/core-dev-bootcamp/module04/appendices/codebase-navigation-guide.md).

# Appendix : Codebase Navigation Guide

### Introduction

This appendix provides a comprehensive guide to navigating rippled's cryptographic code. You'll learn where to find specific implementations, how files are organized, and which functions are most important to understand.

### Directory Structure

```
rippled/
├── include/xrpl/              # Public headers
│   ├── protocol/
│   │   ├── SecretKey.h        # Secret key class
│   │   ├── PublicKey.h        # Public key class
│   │   ├── digest.h           # Hash functions
│   │   ├── KeyType.h          # Key type enumeration
│   │   └── AccountID.h        # Account identifier
│   └── crypto/
│       ├── csprng.h           # CSPRNG interface
│       └── secure_erase.h     # Secure memory erasure
│
├── src/libxrpl/               # Core library implementation
│   ├── protocol/
│   │   ├── SecretKey.cpp      # Key generation, signing (404 lines)
│   │   ├── PublicKey.cpp      # Verification, canonicality (328 lines)
│   │   ├── digest.cpp         # Hash implementations (109 lines)
│   │   ├── AccountID.cpp      # Account ID utilities
│   │   └── tokens.cpp         # Base58 encoding/decoding
│   ├── crypto/
│   │   ├── csprng.cpp         # CSPRNG implementation (110 lines)
│   │   ├── secure_erase.cpp   # Memory wiping (35 lines)
│   │   └── RFC1751.cpp        # Mnemonic words
│   └── basics/
│       └── make_SSLContext.cpp # SSL/TLS configuration
│
└── src/xrpld/                 # Daemon-specific code
    ├── app/tx/impl/
    │   └── Transactor.cpp     # Transaction signature validation
    ├── app/ledger/
    │   └── LedgerMaster.cpp   # Ledger management
    └── overlay/detail/
        └── Handshake.cpp      # Peer cryptographic handshake
```

### Core Cryptographic Files

#### 1. SecretKey.cpp (404 lines)

**Location:** `src/libxrpl/protocol/SecretKey.cpp`

**Key functions:**

```
// Random key generation
SecretKey randomSecretKey();

// Deterministic key generation
SecretKey generateSecretKey(KeyType type, Seed const& seed);
std::pair<PublicKey, SecretKey> generateKeyPair(KeyType type, Seed const& seed);

// Public key derivation
PublicKey derivePublicKey(KeyType type, SecretKey const& sk);

// Signing
Buffer sign(PublicKey const& pk, SecretKey const& sk, Slice const& m);
Buffer signDigest(PublicKey const& pk, SecretKey const& sk, uint256 const& digest);
```

**Navigate to:**

* Line \~50: `randomSecretKey()` implementation
* Line \~100: `generateKeyPair()` for secp256k1
* Line \~150: `generateKeyPair()` for ed25519
* Line \~200: `derivePublicKey()` implementations
* Line \~300: `sign()` function

#### 2. PublicKey.cpp (328 lines)

**Location:** `src/libxrpl/protocol/PublicKey.cpp`

**Key functions:**

```
// Verification
bool verify(PublicKey const& pk, Slice const& m, Slice const& sig, bool canonical);
bool verifyDigest(PublicKey const& pk, uint256 const& digest, Slice const& sig, bool canonical);

// Canonicality checking
std::optional<ECDSACanonicality> ecdsaCanonicality(Slice const& sig);
bool ed25519Canonical(Slice const& sig);

// Key type detection
std::optional<KeyType> publicKeyType(Slice const& slice);
```

**Navigate to:**

* Line \~50: `verify()` function
* Line \~120: `verifyDigest()` for secp256k1
* Line \~180: Ed25519 verification
* Line \~240: `ecdsaCanonicality()` implementation

#### 3. digest.cpp (109 lines)

**Location:** `src/libxrpl/protocol/digest.cpp`

**Key implementations:**

```
// SHA-512-Half hasher
class sha512_half_hasher { /* ... */ };

// RIPESHA hasher
class ripesha_hasher { /* ... */ };

// Helper functions
uint256 sha512Half(Args const&... args);
uint256 sha512Half_s(Slice const& data);  // Secure variant
```

**Navigate to:**

* Line \~20: `sha512_half_hasher` class
* Line \~50: `ripesha_hasher` class
* Line \~80: Utility functions

#### 4. csprng.cpp (110 lines)

**Location:** `src/libxrpl/crypto/csprng.cpp`

**Key implementation:**

```
class csprng_engine {
    // Constructor: Initialize entropy
    // operator(): Generate random bytes
    // mix_entropy(): Add additional entropy
};

csprng_engine& crypto_prng();  // Global singleton
```

**Navigate to:**

* Line \~30: `csprng_engine` class definition
* Line \~50: Constructor (entropy initialization)
* Line \~70: `operator()` (random byte generation)
* Line \~90: `mix_entropy()` (additional entropy)

#### 5. tokens.cpp

**Location:** `src/libxrpl/protocol/tokens.cpp`

**Key functions:**

```
// Base58Check encoding
std::string encodeBase58Token(TokenType type, void const* token, std::size_t size);

// Base58Check decoding
std::string decodeBase58Token(std::string const& s, TokenType type);

// Helpers
std::string toBase58(AccountID const& id);
std::optional<AccountID> parseBase58(std::string const& s);
```

### Finding Specific Functionality

#### "Where is...?"

**Key generation:**

```
src/libxrpl/protocol/SecretKey.cpp
  → randomSecretKey()          // Random generation
  → generateKeyPair()          // Deterministic from seed
```

**Signing:**

```
src/libxrpl/protocol/SecretKey.cpp
  → sign()                     // Sign message
  → signDigest()               // Sign pre-hashed message
```

**Verification:**

```
src/libxrpl/protocol/PublicKey.cpp
  → verify()                   // Verify signature
  → verifyDigest()             // Verify digest signature
```

**Hashing:**

```
src/libxrpl/protocol/digest.cpp
  → sha512Half()               // SHA-512-Half hash
  → sha512Half_s()             // Secure variant

include/xrpl/protocol/digest.h
  → Hash function interfaces
```

**Random numbers:**

```
src/libxrpl/crypto/csprng.cpp
  → crypto_prng()              // Get CSPRNG instance
  → csprng_engine::operator()  // Generate random bytes
```

**Address encoding:**

```
src/libxrpl/protocol/tokens.cpp
  → encodeBase58Token()        // Encode to Base58Check
  → decodeBase58Token()        // Decode from Base58Check
```

**Transaction signing:**

```
src/libxrpl/protocol/STTx.cpp
  → STTx::sign()               // Sign transaction
  → STTx::checkSign()          // Verify transaction signature
```

**Peer handshake:**

```
src/xrpld/overlay/detail/Handshake.cpp
  → makeSharedValue()          // Derive session value
  → buildHandshake()           // Create handshake headers
  → verifyHandshake()          // Verify peer handshake
```

### Navigation by Task

#### Task: Understanding Ed25519 Signing

1. Start at `src/libxrpl/protocol/SecretKey.cpp:sign()`
2. Find Ed25519 case in switch statement
3. See call to `ed25519_sign()`
4. Note: External library (ed25519-donna)
5. Implementation in `src/ed25519-donna/`

#### Task: Understanding Secp256k1 Verification

1. Start at `src/libxrpl/protocol/PublicKey.cpp:verify()`
2. Find secp256k1 case
3. Follow to `verifyDigest()`
4. See canonicality check: `ecdsaCanonicality()`
5. See secp256k1 library calls: `secp256k1_ecdsa_verify()`
6. Implementation in `src/secp256k1/`

#### Task: Understanding Address Generation

1. Start at `src/libxrpl/protocol/AccountID.cpp:calcAccountID()`
2. See RIPESHA hash: `ripesha_hasher`
3. Implementation in `src/libxrpl/protocol/digest.cpp`
4. Double hash: SHA-256 then RIPEMD-160
5. Encoding: `src/libxrpl/protocol/tokens.cpp:encodeBase58Token()`

### Header vs Implementation

#### When to read headers:

```
// Headers show:
// - Function declarations
// - Class interfaces
// - Documentation comments
// - Public API

// Good for:
// - Understanding what's available
// - API reference
// - Quick lookup
```

#### When to read implementation:

```
// Implementation shows:
// - Actual algorithms
// - Error handling
// - Edge cases
// - Performance optimizations

// Good for:
// - Understanding how it works
// - Debugging
// - Learning
// - Contributing
```

### Search Patterns

#### Using grep to find code:

```
# Find all signing functions
grep -r "Buffer sign" src/libxrpl/protocol/

# Find CSPRNG usage
grep -r "crypto_prng()" src/

# Find signature verification
grep -r "verify.*signature" src/

# Find Base58 encoding
grep -r "encodeBase58" src/

# Find hash function usage
grep -r "sha512Half" src/
```

#### Using git blame:

```
# See who wrote/modified code and why
git blame src/libxrpl/protocol/SecretKey.cpp

# See commit that introduced a function
git log -S "randomSecretKey" --source --all
```

#### Using tags/symbols:

```
# Generate ctags for symbol navigation
ctags -R src/ include/

# Jump to definition in vim
# Position cursor on function name, press Ctrl-]
```

### Common Code Patterns

#### RAII Pattern:

```
// Look for:
class SomeKey {
    ~SomeKey() {
        secure_erase(/* ... */);
    }
};
```

#### Error Handling Pattern:

```
// Look for:
if (operation_failed()) {
    Throw<std::runtime_error>("Operation failed");
}
```

#### Key Type Detection Pattern:

```
// Look for:
switch (publicKeyType(pk)) {
    case KeyType::secp256k1:
        // ...
    case KeyType::ed25519:
        // ...
}
```

### Quick Reference

#### File → Purpose Mapping

| File            | Purpose                 | Key Functions                       |
| --------------- | ----------------------- | ----------------------------------- |
| `SecretKey.cpp` | Key management, signing | `randomSecretKey()`, `sign()`       |
| `PublicKey.cpp` | Verification            | `verify()`, `ecdsaCanonicality()`   |
| `digest.cpp`    | Hashing                 | `sha512Half()`, RIPESHA             |
| `csprng.cpp`    | Random generation       | `crypto_prng()`                     |
| `tokens.cpp`    | Base58 encoding         | `encodeBase58Token()`               |
| `Handshake.cpp` | Peer authentication     | `makeSharedValue()`                 |
| `STTx.cpp`      | Transaction signing     | `STTx::sign()`, `STTx::checkSign()` |

### Tips for Code Reading

1. **Start with tests**: Look in `src/test/` for usage examples
2. **Follow the data**: Track how data flows through functions
3. **Read comments**: rippled has good documentation in code
4. **Use a debugger**: Step through code to understand flow
5. **Check git history**: See why code was written that way
6. **Ask questions**: rippled has active developer community
