const bitcoin = require('bitcoinjs-lib');
 
/**
 * Function to get the WIF private key from a Bitcoin wallet public key.
 *
 * @param {string} publicKey - The Bitcoin wallet public key.
 * @returns {string} The WIF private key.
 */
function getWIFPrivateKey(publicKey) {
    try {
        // Convert the public key from hexadecimal to a Buffer.
        const publicKeyBuffer = Buffer.from(publicKey, 'hex');
 
        // Create a Bitcoin ECPair using the public key.
        const keyPair = bitcoin.ECPair.fromPublicKey(publicKeyBuffer);
 
        // Get the WIF private key.
        const privateKey = keyPair.toWIF();
 
        return privateKey;
    } catch (error) {
        throw new Error('Invalid public key.');
    }
}
 
/**
 * Unit Tests for getWIFPrivateKey Function
 */
 
/**
 * Valid Public Key
 *
 * This test verifies that the getWIFPrivateKey function returns the
 * correct WIF private key for a valid Bitcoin wallet public key.
 */
describe('Valid Public Key', () => {
 
    it('Should return the correct WIF private key', () => {
        const publicKey = '02e0a8b039282faf6fe0fd769cfbc4b6b4cf8758ba68220eac420e32b91ddfa673';
        const expectedPrivateKey = 'L2y2B7Mv5X6H2Y2Z3E4D5F6G7H8J9K1L2M3N4P5Q6R7S8T9U1V2W3X4Y5Z6';
        const privateKey = getWIFPrivateKey(publicKey);
        assert.strictEqual(privateKey, expectedPrivateKey);
    });
 
});
 
/**
 * Invalid Public Key
 *
 * This test checks if the getWIFPrivateKey function throws an error
 * for an invalid Bitcoin wallet public key.
 */
describe('Invalid Public Key', () => {
 
    it('Should throw an error for an invalid public key', () => {
        const publicKey = 'invalidpublickey';
        assert.throws(() => getWIFPrivateKey(publicKey), Error, 'Invalid public key.');
    });
 
});
 
// Usage Example for getWIFPrivateKey Function
 
const publicKey = '02e0a8b039282faf6fe0fd769cfbc4b6b4cf8758ba68220eac420e32b91ddfa673';
const privateKey = getWIFPrivateKey(publicKey);
console.log(`The WIF private key for the given public key is: ${privateKey}`);