Skip to content

Commit 7acba5f

Browse files
committed
feat: add KeyUtils.magicSign({ privKeyBytes, doubleSha256Bytes })
1 parent 543646a commit 7acba5f

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

key-utils.js

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ let Secp256k1 = require("@dashincubator/secp256k1");
77
* @typedef KeyUtilsPartial
88
* @prop {KeySet} set
99
* @prop {KeySignAsn1} signAsn1
10-
* @prop {KeySignEth} signEth
10+
* @prop {KeySignMagic} magicSign
1111
* @prop {KeySignP1363} signP1363
1212
* @prop {ASN1ToP1363Signature} asn1ToP1363Signature
1313
*/
@@ -27,9 +27,10 @@ let Secp256k1 = require("@dashincubator/secp256k1");
2727
*/
2828

2929
/**
30-
* @callback KeySignEth
31-
* @param {Uint8Array} privateKey
32-
* @param {Uint8Array} hashBytes
30+
* @callback KeySignMagic
31+
* @param {Object} opts
32+
* @param {Uint8Array} opts.privKeyBytes
33+
* @param {Uint8Array} opts.doubleSha256Bytes
3334
* @returns {Promise<Uint8Array>}
3435
*/
3536

@@ -84,23 +85,27 @@ KeyUtils.signAsn1 = async function (privKeyBytes, hashBytes) {
8485
return sigBytes;
8586
};
8687

87-
KeyUtils.signEth = async function (privKeyBytes, hashBytes) {
88-
let ETH_OFFSET = 27; // maybe the right number... maybe not
88+
KeyUtils.magicSign = async function ({ privKeyBytes, doubleSha256Bytes }) {
89+
if (doubleSha256Bytes?.length !== 32) {
90+
throw new Error(`'doubleSha256Bytes' must be a 32-byte double sha256 hash`);
91+
}
92+
93+
let MAGIC_OFFSET = 27 + 4; // 27 because bitcoin, 4 because "compressed" key
8994
let testing = true;
9095
let sigOpts = { canonical: true, der: false, recovered: true };
9196
if (!testing) {
9297
Object.assign({ extraEntropy: true });
9398
}
94-
let recoverySig = await Secp256k1.sign(hashBytes, privKeyBytes, sigOpts);
95-
let ethSig = new Uint8Array(65);
96-
let recovery = ETH_OFFSET + recoverySig[1];
97-
ethSig[0] = recovery;
98-
ethSig.set(recoverySig[0], 1);
99-
// console.log(`DEBUG [SIGNATURE] rawBytes:`);
100-
// console.log(recoverySig[0]);
101-
// console.log(`DEBUG [RECOVERY] rawBytes:`);
102-
// console.log(recoverySig[1]);
103-
return ethSig;
99+
let recoverySig = await Secp256k1.sign(
100+
doubleSha256Bytes,
101+
privKeyBytes,
102+
sigOpts,
103+
);
104+
let magicSig = new Uint8Array(65);
105+
// the magic byte is prepended (the signature is NOT reversed)
106+
magicSig[0] = MAGIC_OFFSET + recoverySig[1];
107+
magicSig.set(recoverySig[0], 1);
108+
return magicSig;
104109
};
105110

106111
KeyUtils.signP1363 = async function (privKeyBytes, hashBytes, sigBytes) {

0 commit comments

Comments
 (0)