āš ļøBlast API (blastapi.io) ends Oct 31. Migrate to Dwellir and skip Alchemy's expensive compute units.
Switch Today →
Skip to main content

author_rotateKeys - JSON-RPC Method

Description​

Generates a new set of session keys and returns them as a hex-encoded string. This JSON-RPC method is essential for validators to rotate their keys periodically for security. The generated keys are stored in the node's keystore and can be used to set on-chain session keys.

Parameters​

This method does not require any parameters.

Returns​

FieldTypeDescription
resultstringHex-encoded concatenated public keys for all session key types

Request Example​

{
"jsonrpc": "2.0",
"method": "author_rotateKeys",
"params": [],
"id": 1
}

Response Example​

{
"jsonrpc": "2.0",
"result": "0x9257c7a88f94f858a6f477743b4180f0c9471b2b1a2b0c1e1af9d7c2e2c3d4e5f6789abcdef1234567890abcdef1234567890abcdef1234567890abcdef123456",
"id": 1
}

Code Examples​

import requests
import json
from datetime import datetime

class ValidatorKeyManager:
def __init__(self, rpc_url: str, api_key: str):
self.rpc_url = rpc_url
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}

def rotate_keys(self) -> str:
"""Generate new session keys"""
payload = {
"jsonrpc": "2.0",
"method": "author_rotateKeys",
"params": [],
"id": 1
}

response = requests.post(
self.rpc_url,
headers=self.headers,
data=json.dumps(payload)
)

if response.status_code != 200:
raise Exception(f"RPC call failed: {response.text}")

result = response.json()
if "error" in result:
raise Exception(f"RPC error: {result['error']}")

return result["result"]

def parse_session_keys(self, keys_hex: str) -> dict:
"""Parse concatenated session keys"""
# Remove 0x prefix
keys_hex = keys_hex[2:] if keys_hex.startswith("0x") else keys_hex

# Each key is 32 bytes (64 hex characters)
key_length = 64

keys = {
"grandpa": "0x" + keys_hex[0:key_length],
"babe": "0x" + keys_hex[key_length:key_length*2],
"im_online": "0x" + keys_hex[key_length*2:key_length*3],
"authority_discovery": "0x" + keys_hex[key_length*3:key_length*4]
}

return keys

def backup_keys(self, keys: str, backup_path: str = None):
"""Backup session keys to file"""
timestamp = datetime.now().isoformat()
backup_data = {
"timestamp": timestamp,
"session_keys": keys,
"parsed": self.parse_session_keys(keys)
}

if backup_path:
with open(backup_path, 'w') as f:
json.dump(backup_data, f, indent=2)
print(f"Keys backed up to: {backup_path}")

return backup_data

def rotate_and_backup(self, backup_path: str = None):
"""Complete key rotation with backup"""
print("Rotating validator session keys...")

# Generate new keys
new_keys = self.rotate_keys()
print(f"āœ… New session keys generated")
print(f"Keys: {new_keys[:20]}...{new_keys[-20:]}")

# Parse keys
parsed = self.parse_session_keys(new_keys)
print("\nParsed keys:")
for key_type, key_value in parsed.items():
print(f" {key_type}: {key_value[:10]}...{key_value[-10:]}")

# Backup if requested
if backup_path:
self.backup_keys(new_keys, backup_path)

print("\nāš ļø Next steps:")
print("1. Save these keys securely")
print("2. Submit session.setKeys() extrinsic on-chain")
print("3. Wait for the next era for keys to become active")

return new_keys

# Usage
manager = ValidatorKeyManager("https://api-moonbase-alpha.n.dwellir.com/YOUR_API_KEY", "YOUR_API_KEY")

# Rotate keys with backup
new_keys = manager.rotate_and_backup("validator_keys_backup.json")

Security Best Practices​

  1. Regular Rotation: Rotate keys periodically (e.g., monthly)
  2. Secure Storage: Never expose session keys in logs or public repos
  3. Backup Keys: Always backup keys before rotation
  4. Verify Generation: Ensure keys are properly generated before submission
  5. Monitor Activation: Track when new keys become active

Session Key Types​

Key TypePurposeAlgorithm
GRANDPAFinality votingEd25519
BABEBlock productionSr25519
ImOnlineLiveness proofSr25519
ParaValidatorParachain validationSr25519
ParaAssignmentParachain assignmentSr25519
AuthorityDiscoveryPeer discoverySr25519

Use Cases​

  1. Validator Setup: Initial validator configuration
  2. Key Rotation: Periodic security key updates
  3. Key Recovery: Generate new keys after compromise
  4. Multi-node Setup: Configure backup validator nodes
  5. Security Audits: Regular key rotation policy

Notes​

  • Keys are generated and stored in the node's keystore
  • New keys must be submitted on-chain via session.setKeys()
  • Key changes take effect in the next era/session
  • Keep generated keys secure and backed up
  • Node must have --validator flag to generate keys