All files / src/chain private-key.ts

90% Statements 45/50
82.75% Branches 24/29
91.66% Functions 11/12
90% Lines 45/50

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                                                      20x     20x                 26x 26x 19x   7x 7x         3x 3x 3x 1x   3x 3x   4x                 5x         27x 1x   26x 26x               11x 11x               4x               2x 2x               3x 3x               3x 1x   2x             5x                   26x 26x     26x   10x 10x     10x   10x     10x 10x   10x 5x     16x 16x 14x     14x      
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)
            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)
                return new this(type, data)
            }
            throw error
        }
    }
 
    /**
     * Generate new PrivateKey.
     * @throws If a secure random source isn't available.
     */
    static generate(type: KeyType | string) {
        return new PrivateKey(KeyType.from(type), new Bytes(generate(type)))
    }
 
    /** @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.
     * @throws If the key type isn't R1 or K1.
     */
    sharedSecret(publicKey: PublicKey) {
        const shared = sharedSecret(this.data.array, publicKey.data.array, this.type)
        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))
    }
 
    /**
     * 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()}
    }
}