All files / src/crypto sign.ts

100% Statements 14/14
91.66% Branches 11/12
100% Functions 2/2
100% Lines 14/14

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              145x       145x 132x 132x 276x           275x 275x 275x     13x         13x 13x 13x   144x                   275x              
import {getCurve} from './curves'
 
/**
 * Sign digest using private key.
 * @internal
 */
export function sign(secret: Uint8Array, message: Uint8Array, type: string) {
    const curve = getCurve(type)
    let recid: number
    let r: Uint8Array
    let s: Uint8Array
    if (type === 'K1') {
        let attempt = 1
        do {
            const sig = curve.sign(message, secret, {
                prehash: false,
                format: 'recovered',
                lowS: true,
                extraEntropy: new Uint8Array([attempt++]),
            })
            recid = sig[0]
            r = sig.subarray(1, 33)
            s = sig.subarray(33, 65)
        } while (!isCanonical(r, s))
    } else {
        const sig = curve.sign(message, secret, {
            prehash: false,
            format: 'recovered',
            lowS: true,
        })
        recid = sig[0]
        r = sig.subarray(1, 33)
        s = sig.subarray(33, 65)
    }
    return {type, r, s, recid: recid || 0}
}
 
/**
 * Here be dragons
 * - https://github.com/steemit/steem/issues/1944
 * - https://github.com/EOSIO/eos/issues/6699
 * @internal
 */
function isCanonical(r: Uint8Array, s: Uint8Array) {
    return (
        !(r[0] & 0x80) &&
        !(r[0] === 0 && !(r[1] & 0x80)) &&
        !(s[0] & 0x80) &&
        !(s[0] === 0 && !(s[1] & 0x80))
    )
}