# chain_getBlockHash - Kusama RPC Method

Returns the block hash for a given block number on Kusama. This is the primary method for converting block numbers into block hashes, which are required by most other chain RPC methods.

> **Why Kusama?** Build on Polkadot's canary network for real-world testing with live economic conditions with 7-day governance cycles (vs 1 month on Polkadot), lower bonding requirements, live KSM token economy, and first-to-market feature testing.

## When to Use This Method

`chain_getBlockHash` is fundamental for experimental dApp developers, parachain teams, and early adopters validating new features:

- **Historical Queries** - Convert block numbers to hashes for state queries at specific heights on Kusama
- **Block Navigation** - Navigate the blockchain history for parachain experimentation, early feature deployment, and production-grade testing with real value
- **Data Indexing** - Build block number-to-hash mappings for indexers and explorers
- **Cross-Reference** - Translate block numbers from events or logs into hashes for detailed lookups

## Best Practices

- Use before `chain_getBlock` if you need hash-based block lookup on Kusama
- Block numbers may change during chain reorganizations -- hashes are immutable
- Returns `null` for future blocks that do not exist yet
- Cache the genesis block hash as a known reference point

## Request Parameters

- `blockNumber` (`Number, optional`): Block number to look up. If omitted, returns the hash of the latest block

## Request Example

```json
{
  "jsonrpc": "2.0",
  "method": "chain_getBlockHash",
  "params": [1000000],
  "id": 1
}
```

## Response Fields

- `result` (`Hash, required`): Hex-encoded 32-byte block hash, or null if block number does not exist

## Successful Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": "0xa1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2"
}
```

## Error Responses

### Error Response

- Code: `-32602`

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32602,
    "message": "Invalid block number"
  }
}
```

## Code Examples

cURL
JavaScript
Python
Rust

```bash
# Get hash for a specific block number
curl -X POST https://kusama-rpc.n.dwellir.com \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "chain_getBlockHash",
    "params": [1000000],
    "id": 1
  }'

# Get hash for the latest block
curl -X POST https://kusama-rpc.n.dwellir.com \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "chain_getBlockHash",
    "params": [],
    "id": 1
  }'
```

```javascript
import { ApiPromise, WsProvider } from '@polkadot/api';

const provider = new WsProvider('wss://kusama-rpc.n.dwellir.com');
const api = await ApiPromise.create({ provider });

// Get hash for specific block number
const blockNumber = 1000000;
const blockHash = await api.rpc.chain.getBlockHash(blockNumber);
console.log(`Block ${blockNumber} hash:`, blockHash.toHex());

// Get hash for latest block
const latestHash = await api.rpc.chain.getBlockHash();
console.log('Latest block hash:', latestHash.toHex());

// Get genesis block hash
const genesisHash = await api.rpc.chain.getBlockHash(0);
console.log('Genesis hash:', genesisHash.toHex());

await api.disconnect();
```

```python
import requests

def get_block_hash(block_number=None):
    url = 'https://kusama-rpc.n.dwellir.com'
    params = [block_number] if block_number is not None else []

    payload = {
        'jsonrpc': '2.0',
        'method': 'chain_getBlockHash',
        'params': params,
        'id': 1
    }

    response = requests.post(url, json=payload)
    result = response.json()

    if 'error' in result:
        raise Exception(f"RPC Error: {result['error']}")

    return result['result']

# Get specific block hash
block_hash = get_block_hash(1000000)
print(f'Block 1000000 hash: {block_hash}')

# Get latest block hash
latest_hash = get_block_hash()
print(f'Latest block hash: {latest_hash}')

# Get genesis hash
genesis_hash = get_block_hash(0)
print(f'Genesis hash: {genesis_hash}')
```

```rust
use subxt::{OnlineClient, PolkadotConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api = OnlineClient::<PolkadotConfig>::from_url(
        "wss://kusama-rpc.n.dwellir.com"
    ).await?;

    // Get hash for a specific block number
    let block_hash = api.rpc()
        .chain_get_block_hash(Some(1_000_000u32.into()))
        .await?;

    println!("Block 1000000 hash: {:?}", block_hash);

    // Get latest block hash
    let latest_hash = api.rpc()
        .chain_get_block_hash(None)
        .await?;

    println!("Latest block hash: {:?}", latest_hash);

    Ok(())
}
```

## Common Use Cases

### 1. Block Range Iterator

Iterate over a range of blocks on Kusama for indexing:

```javascript
async function iterateBlocks(api, startBlock, endBlock) {
  for (let num = startBlock; num <= endBlock; num++) {
    const hash = await api.rpc.chain.getBlockHash(num);
    const block = await api.rpc.chain.getBlock(hash);

    console.log(`Block #${num}: ${block.block.extrinsics.length} extrinsics`);
  }
}
```

### 2. Historical State Query

Query Kusama state at a specific block height:

```javascript
async function getBalanceAtBlock(api, address, blockNumber) {
  const blockHash = await api.rpc.chain.getBlockHash(blockNumber);
  const apiAt = await api.at(blockHash);
  const account = await apiAt.query.system.account(address);

  return {
    blockNumber,
    free: account.data.free.toString(),
    reserved: account.data.reserved.toString()
  };
}
```

### 3. Genesis Hash Verification

Verify you are connected to the correct Kusama network:

```javascript
async function verifyNetwork(api, expectedGenesisHash) {
  const genesisHash = await api.rpc.chain.getBlockHash(0);

  if (genesisHash.toHex() !== expectedGenesisHash) {
    throw new Error(`Wrong network! Expected ${expectedGenesisHash}, got ${genesisHash.toHex()}`);
  }

  console.log('Connected to correct network');
}
```

## Related Methods

- [`chain_getBlock`](https://www.dwellir.com/docs/kusama/chain_getBlock) - Get full block data by hash
- [`chain_getHeader`](https://www.dwellir.com/docs/kusama/chain_getHeader) - Get block header by hash
- [`chain_getFinalizedHead`](https://www.dwellir.com/docs/kusama/chain_getFinalizedHead) - Get the latest finalized block hash
