|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +let Secp256k1 = require("@dashincubator/secp256k1"); |
| 4 | + |
| 5 | +/** @typedef {Required<import('dashtx').TxKeyUtils>} TxKeyUtils */ |
| 6 | +/** |
| 7 | + * @typedef KeyUtilsPartial |
| 8 | + * @prop {KeySet} set |
| 9 | + */ |
| 10 | +/** @typedef {TxKeyUtils & KeyUtilsPartial} KeyUtils */ |
| 11 | + |
| 12 | +/** |
| 13 | + * @callback KeySet |
| 14 | + * @param {String} id |
| 15 | + * @param {KeyInfo} keyInfo |
| 16 | + */ |
| 17 | + |
| 18 | +/** @type {KeyUtils} */ |
| 19 | +let KeyUtils = module.exports; |
| 20 | + |
| 21 | +/** |
| 22 | + * @typedef KeyInfo |
| 23 | + * @prop {String} [walletId] - from DashHd.toId(walletKey) |
| 24 | + * @prop {String} [hdpath] - ex: m/44'/5'/0'/0/0 |
| 25 | + * @prop {String} address - generally convenient |
| 26 | + * @prop {Uint8Array} privateKey - for signing |
| 27 | + * @prop {Uint8Array} publicKey - for TxInput |
| 28 | + * @prop {String} pubKeyHash - for TxOutput |
| 29 | + */ |
| 30 | + |
| 31 | +/** @type Object.<String, KeyInfo> */ |
| 32 | +let keysMap = {}; |
| 33 | + |
| 34 | +KeyUtils.set = function (id, keyInfo) { |
| 35 | + if (!id) { |
| 36 | + throw new Error(`key identifier is not defined)`); |
| 37 | + } |
| 38 | + keysMap[id] = keyInfo; |
| 39 | +}; |
| 40 | + |
| 41 | +KeyUtils.sign = async function (privKeyBytes, hashBytes) { |
| 42 | + let sigOpts = { canonical: true, extraEntropy: true }; |
| 43 | + let sigBytes = await Secp256k1.sign(hashBytes, privKeyBytes, sigOpts); |
| 44 | + return sigBytes; |
| 45 | +}; |
| 46 | +KeyUtils.getPrivateKey = async function (input) { |
| 47 | + if (!input.address) { |
| 48 | + //throw new Error('should put the address on the input there buddy...'); |
| 49 | + console.warn("missing address:", input.txid, input.outputIndex); |
| 50 | + return null; |
| 51 | + } |
| 52 | + |
| 53 | + let keyInfo = keysMap[input.address]; |
| 54 | + return keyInfo.privateKey; |
| 55 | +}; |
| 56 | + |
| 57 | +KeyUtils.getPublicKey = async function (txInput, i) { |
| 58 | + let privKeyBytes = await KeyUtils.getPrivateKey(txInput, i); |
| 59 | + if (!privKeyBytes) { |
| 60 | + return null; |
| 61 | + } |
| 62 | + let pubKeyBytes = await KeyUtils.toPublicKey(privKeyBytes); |
| 63 | + |
| 64 | + return pubKeyBytes; |
| 65 | +}; |
| 66 | + |
| 67 | +KeyUtils.toPublicKey = async function (privKeyBytes) { |
| 68 | + let isCompressed = true; |
| 69 | + let pubKeyBytes = Secp256k1.getPublicKey(privKeyBytes, isCompressed); |
| 70 | + |
| 71 | + return pubKeyBytes; |
| 72 | +}; |
0 commit comments