From 3b402d00c61fc50a290a8d3f6bfb3749b8c13e63 Mon Sep 17 00:00:00 2001 From: junderw Date: Fri, 12 Apr 2019 17:44:55 +0900 Subject: [PATCH] Add low R grinding option --- src/ecpair.js | 19 +++++++++++++++++-- ts_src/ecpair.ts | 18 ++++++++++++++++-- types/ecpair.d.ts | 2 +- 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/src/ecpair.js b/src/ecpair.js index 2026c63..6bb7eb9 100644 --- a/src/ecpair.js +++ b/src/ecpair.js @@ -35,10 +35,25 @@ class ECPair { throw new Error('Missing private key'); return wif.encode(this.network.wif, this.__D, this.compressed); } - sign(hash) { + sign(hash, lowR = false) { if (!this.__D) throw new Error('Missing private key'); - return ecc.sign(hash, this.__D); + if (lowR === false) { + return ecc.sign(hash, this.__D); + } + else { + let sig = ecc.sign(hash, this.__D); + const extraData = Buffer.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc.signWithEntropy(hash, this.__D, extraData); + } + return sig; + } } verify(hash, signature) { return ecc.verify(hash, this.publicKey, signature); diff --git a/ts_src/ecpair.ts b/ts_src/ecpair.ts index 3941afa..7245d0d 100644 --- a/ts_src/ecpair.ts +++ b/ts_src/ecpair.ts @@ -61,9 +61,23 @@ class ECPair implements ECPairInterface { return wif.encode(this.network.wif, this.__D, this.compressed); } - sign(hash: Buffer): Buffer { + sign(hash: Buffer, lowR: boolean = false): Buffer { if (!this.__D) throw new Error('Missing private key'); - return ecc.sign(hash, this.__D); + if (lowR === false) { + return ecc.sign(hash, this.__D); + } else { + let sig = ecc.sign(hash, this.__D); + const extraData = Buffer.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc.signWithEntropy(hash, this.__D, extraData); + } + return sig; + } } verify(hash: Buffer, signature: Buffer): Buffer { diff --git a/types/ecpair.d.ts b/types/ecpair.d.ts index a5ae716..2f9bbc4 100644 --- a/types/ecpair.d.ts +++ b/types/ecpair.d.ts @@ -24,7 +24,7 @@ declare class ECPair implements ECPairInterface { readonly privateKey: Buffer | undefined; readonly publicKey: Buffer | undefined; toWIF(): string; - sign(hash: Buffer): Buffer; + sign(hash: Buffer, lowR?: boolean): Buffer; verify(hash: Buffer, signature: Buffer): Buffer; } declare function fromPrivateKey(buffer: Buffer, options?: ECPairOptions): ECPair;