docs_rpc_importprivkey - reddcoin-project/reddcoin GitHub Wiki

Reddcoin RPC Command: importprivkey

Overview

The importprivkey command imports a private key into the Reddcoin wallet, making the associated address available for transactions. This command adds the private key to the wallet's keypool, allowing you to spend from the corresponding Reddcoin address. The wallet must be unlocked and not in watch-only mode for this operation to succeed.

Primary Use Cases:

  • Importing private keys from paper wallets
  • Migrating addresses between wallets
  • Recovery of addresses from backup private keys
  • Adding externally generated addresses to your wallet

⚠️ Security Warning

CRITICAL SECURITY NOTICE: Private keys provide complete control over the associated Reddcoin address. Handle with extreme caution:

  • Never share private keys with untrusted parties
  • Always use encrypted connections when transmitting private keys
  • Ensure your wallet is encrypted and backed up before importing
  • The imported key will be stored unencrypted in memory until the wallet is locked
  • Consider the security implications of importing keys from unknown sources

Command Syntax

importprivkey "private_key" ( "label" rescan )

Parameters

Parameter Type Required Description
private_key string Yes The private key in WIF (Wallet Import Format)
label string No An optional label to assign to the address
rescan boolean No Rescan the blockchain for transactions (default: true)

Return Value

The command returns null on success. If an error occurs, an exception will be thrown.

Example Usage

CLI Format

# Basic import
reddcoin-cli importprivkey "7QyTgZJ8zQR9Xg8r2Y5K4F3D6B9N8M1P4S7V6E5H2J9L3Q8W"

# Import with label
reddcoin-cli importprivkey "7QyTgZJ8zQR9Xg8r2Y5K4F3D6B9N8M1P4S7V6E5H2J9L3Q8W" "Paper Wallet 001"

# Import without rescanning (faster, but may miss historical transactions)
reddcoin-cli importprivkey "7QyTgZJ8zQR9Xg8r2Y5K4F3D6B9N8M1P4S7V6E5H2J9L3Q8W" "Quick Import" false

JSON-RPC Format

{
  "jsonrpc": "2.0",
  "id": "import_key_001",
  "method": "importprivkey",
  "params": [
    "7QyTgZJ8zQR9Xg8r2Y5K4F3D6B9N8M1P4S7V6E5H2J9L3Q8W",
    "Paper Wallet Main",
    true
  ]
}

cURL Example:

curl -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": "import_001",
    "method": "importprivkey",
    "params": [
      "7QyTgZJ8zQR9Xg8r2Y5K4F3D6B9N8M1P4S7V6E5H2J9L3Q8W",
      "Imported Address",
      true
    ]
  }' \
  http://rpcuser:[email protected]:45443/

Example Response

Successful Import

{
  "jsonrpc": "2.0",
  "id": "import_001",
  "result": null,
  "error": null
}

Error Response

{
  "jsonrpc": "2.0",
  "id": "import_001",
  "result": null,
  "error": {
    "code": -4,
    "message": "Error adding key to wallet"
  }
}

Notes

Important Considerations:

  • Wallet State: The wallet must be unlocked for encryption/decryption operations
  • Rescan Impact: When rescan is true (default), the operation may take significant time as it scans the entire blockchain for transactions involving the imported address
  • Duplicate Keys: Importing an already existing private key will not create a duplicate but may update the label
  • Address Format: The imported key will generate a Reddcoin address starting with 'R' (e.g., RoKXkMJiYRGNtL5eCcJwCHJLzwFBhQqyK9)
  • Memory Usage: Large rescans may consume significant memory and CPU resources
  • Network Activity: Rescan operations may generate increased network traffic

Performance Tips:

  • Use rescan: false for bulk imports, then run rescanblockchain once at the end
  • Import during off-peak hours to minimize impact on other operations
  • Ensure sufficient disk space for wallet.dat expansion

Related Commands

  • dumpprivkey - Export private key for a given address
  • dumpwallet - Export all private keys to a file
  • importwallet - Import multiple private keys from a wallet dump file
  • importaddress - Import an address for watch-only monitoring
  • importpubkey - Import a public key for watch-only functionality
  • rescanblockchain - Manually rescan blockchain for wallet transactions
  • encryptwallet - Encrypt wallet with a passphrase
  • walletpassphrase - Unlock encrypted wallet

Python Code Example

import requests
import json

class ReddcoinRPC:
    def __init__(self, host='127.0.0.1', port=45443, user='rpcuser', password='rpcpassword'):
        self.url = f"http://{host}:{port}/"
        self.auth = (user, password)
        self.headers = {'Content-Type': 'application/json'}
    
    def importprivkey(self, private_key, label=None, rescan=True):
        """
        Import a private key into the Reddcoin wallet
        
        Args:
            private_key (str): WIF format private key
            label (str, optional): Label for the imported address
            rescan (bool): Whether to rescan blockchain for transactions
            
        Returns:
            dict: RPC response
        """
        params = [private_key]
        if label is not None:
            params.append(label)
            if not rescan:
                params.append(rescan)
        elif not rescan:
            params.extend([None, rescan])
        
        payload = {
            "jsonrpc": "2.0",
            "id": "importprivkey",
            "method": "importprivkey",
            "params": params
        }
        
        try:
            response = requests.post(
                self.url, 
                data=json.dumps(payload),
                headers=self.headers,
                auth=self.auth,
                timeout=300  # 5 minute timeout for rescan operations
            )
            response.raise_for_status()
            return response.json()
            
        except requests.exceptions.RequestException as e:
            raise Exception(f"RPC request failed: {e}")
        except json.JSONDecodeError as e:
            raise Exception(f"Invalid JSON response: {e}")

# Usage example
def main():
    # Initialize RPC client
    rpc = ReddcoinRPC(
        host='127.0.0.1',
        port=45443,
        user='your_rpc_username',
        password='your_rpc_password'
    )
    
    # Import private key with error handling
    try:
        private_key = "7QyTgZJ8zQR9Xg8r2Y5K4F3D6B9N8M1P4S7V6E5H2J9L3Q8W"
        result = rpc.importprivkey(
            private_key=private_key,
            label="Python Import Test",
            rescan=True
        )
        
        if result.get('error'):
            print(f"Error: {result['error']['message']}")
        else:
            print("Private key imported successfully!")
            
    except Exception as e:
        print(f"Import failed: {e}")

if __name__ == "__main__":
    main()

Security Best Practices

Essential Security Measures:

  1. Environment Security

    • Always run imports on a secure, offline machine when possible
    • Use encrypted connections (SSL/TLS) for all RPC communications
    • Ensure your system is free from malware and keyloggers
  2. Private Key Handling

    • Never store private keys in plain text files
    • Clear clipboard and command history after handling private keys
    • Use secure methods to generate and store private keys
  3. Wallet Protection

    • Always encrypt your wallet with a strong passphrase
    • Create secure backups of your wallet.dat file
    • Consider using hardware wallets for large amounts
  4. Network Security

    • Bind RPC to localhost only unless absolutely necessary
    • Use strong, unique RPC credentials
    • Implement proper firewall rules
  5. Operational Security

    • Test imports with small amounts first
    • Verify addresses after import using validateaddress
    • Monitor wallet balance changes after import operations

Additional Resources

Official Documentation:

Development Resources:

Community Support:


Last Updated: May 2025 | Reddcoin Core Version: 4.x.x