All files / src/chain private-key.ts

88.88% Statements 56/63
74.07% Branches 20/27
92.85% Functions 13/14
88.7% Lines 55/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197                                          1x           37x     37x                 43x 43x 36x 2x   34x   9x 9x         3x 3x 3x 1x   3x 3x     3x   6x                 26x 25x 25x     25x 25x     25x 25x   25x         64x 1x   63x 63x               145x 145x               130x                 12x           12x               56x 55x               3x 1x   2x       127x             5x                   43x 43x     43x   15x 15x     15x   15x     15x       15x     28x 28x 26x     26x      
import {Base58} from '../base58'
import {isInstanceOf} from '../utils'
 
import {getPublic} from '../crypto/get-public'
import {sharedSecret} from '../crypto/shared-secret'
import {sign} from '../crypto/sign'
import {generate} from '../crypto/generate'
 
import {
    Bytes,
    BytesType,
    Checksum256,
    Checksum256Type,
    Checksum512,
    KeyType,
    PublicKey,
    Signature,
} from '../'
 
export type PrivateKeyType = PrivateKey | string
 
export class PrivateKey {
    type: KeyType
    data: Bytes
 
    /** Create PrivateKey object from representing types. */
    static from(value: PrivateKeyType) {
        Iif (isInstanceOf(value, PrivateKey)) {
            return value
        } else {
            return this.fromString(value)
        }
    }
 
    /**
     * Create PrivateKey object from a string representation.
     * Accepts WIF (5...) and Antelope/EOSIO (PVT_...) style private keys.
     */
    static fromString(string: string, ignoreChecksumError = false) {
        try {
            const {type, data} = decodeKey(string)
            if (this.isAllZero(data)) {
                throw new Error('Invalid private key: All-zero private key is not allowed')
            }
            return new this(type, data)
        } catch (error: any) {
            error.message = `Invalid private key (${error.message})`
            if (
                ignoreChecksumError &&
                isInstanceOf(error, Base58.DecodingError) &&
                error.code === Base58.ErrorCode.E_CHECKSUM
            ) {
                const type = string.startsWith('PVT_R1') ? KeyType.R1 : KeyType.K1
                const data = new Bytes(error.info.data)
                if (data.length === 33) {
                    data.dropFirst()
                }
                data.zeropad(32, true)
                Iif (this.isAllZero(data)) {
                    throw new Error('Invalid private key: All-zero private key is not allowed')
                }
                return new this(type, data)
            }
            throw error
        }
    }
 
    /**
     * Generate new PrivateKey.
     * @throws If a secure random source isn't available.
     */
    static generate(type: KeyType | string) {
        const keyType = KeyType.from(type)
        const maxRetries = 3
        let attempts = 0
        let data: Bytes
 
        do {
            Iif (attempts >= maxRetries) {
                throw new Error('Failed to generate valid private key: Maximum retries exceeded')
            }
            data = new Bytes(generate(keyType))
            attempts++
        } while (this.isAllZero(data))
        return new PrivateKey(keyType, data)
    }
 
    /** @internal */
    constructor(type: KeyType, data: Bytes) {
        if ((type === KeyType.K1 || type === KeyType.R1) && data.length !== 32) {
            throw new Error('Invalid private key length')
        }
        this.type = type
        this.data = data
    }
 
    /**
     * Sign message digest using this key.
     * @throws If the key type isn't R1 or K1.
     */
    signDigest(digest: Checksum256Type) {
        digest = Checksum256.from(digest)
        return Signature.from(sign(this.data.array, digest.array, this.type))
    }
 
    /**
     * Sign message using this key.
     * @throws If the key type isn't R1 or K1.
     */
    signMessage(message: BytesType) {
        return this.signDigest(Checksum256.hash(message))
    }
 
    /**
     * Derive the shared secret between this private key and given public key.
     * The `legacy` option replicates the divergent pre-2.0 x-coordinate derivation.
     * @throws If the key type isn't R1 or K1.
     */
    sharedSecret(publicKey: PublicKey, options?: {legacy?: boolean}) {
        const shared = sharedSecret(
            this.data.array,
            publicKey.data.array,
            this.type,
            options && options.legacy
        )
        return Checksum512.hash(shared)
    }
 
    /**
     * Get the corresponding public key.
     * @throws If the key type isn't R1 or K1.
     */
    toPublic() {
        const compressed = getPublic(this.data.array, this.type)
        return PublicKey.from({compressed, type: this.type})
    }
 
    /**
     * Return WIF representation of this private key
     * @throws If the key type isn't K1.
     */
    toWif() {
        if (this.type !== KeyType.K1) {
            throw new Error('Unable to generate WIF for non-k1 key')
        }
        return Base58.encodeCheck(Bytes.from([0x80]).appending(this.data))
    }
 
    static isAllZero(data: Bytes): boolean {
        return data.array.every((byte) => byte === 0)
    }
 
    /**
     * Return the key in Antelope/EOSIO PVT_<type>_<base58check> format.
     */
    toString() {
        return `PVT_${this.type}_${Base58.encodeRipemd160Check(this.data, this.type)}`
    }
 
    toJSON() {
        return this.toString()
    }
}
 
/** @internal */
function decodeKey(value: string) {
    const type = typeof value
    Iif (type !== 'string') {
        throw new Error(`Expected string, got ${type}`)
    }
    if (value.startsWith('PVT_')) {
        // Antelope/EOSIO format
        const parts = value.split('_')
        Iif (parts.length !== 3) {
            throw new Error('Invalid PVT format')
        }
        const type = KeyType.from(parts[1])
        let size: number | undefined
        switch (type) {
            case KeyType.K1:
            case KeyType.R1:
                size = 32
                break
        }
        const data = Base58.decodeRipemd160Check(parts[2], size, type)
        return {type, data}
    } else {
        // WIF format
        const type = KeyType.K1
        const data = Base58.decodeCheck(value)
        Iif (data.array[0] !== 0x80) {
            throw new Error('Invalid WIF')
        }
        return {type, data: data.droppingFirst()}
    }
}