UNPKG

@sangaman/xud

Version:
99 lines 3.43 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_js_1 = __importDefault(require("crypto-js")); const crypto_1 = require("crypto"); const secp256k1_1 = __importDefault(require("secp256k1")); const fs_1 = __importDefault(require("fs")); /** * A class representing an ECDSA public/private key pair that identifies an XU node on the network * and can sign messages to prove their veracity. */ class NodeKey { constructor(privKey) { this.privKey = privKey; /** * Sign a message with the private key. * @param msg the data to sign * @returns the signature */ this.sign = (msg) => { return secp256k1_1.default.sign(msg, this.privKey).signature; }; /** * Save the private key to a file, optionally encrypted by a password. * @param path the path at which to save the file * @param password an optional password parameter for encrypting the private key */ this.toFile = (path, password) => { let buf; if (password) { const lwa = crypto_js_1.default.lib.WordArray.create(this.privKey.buffer); buf = crypto_js_1.default.AES.encrypt(lwa, password); } else { buf = this.privKey; } fs_1.default.writeFileSync(path, buf); }; const pubKey = secp256k1_1.default.publicKeyCreate(privKey); this.pubKeyStr = pubKey.toString('hex'); } get nodePubKey() { return this.pubKeyStr; } } /** * Generate a random NodeKey. */ NodeKey.generate = () => { let privKey; do { privKey = crypto_1.randomBytes(32); } while (!secp256k1_1.default.privateKeyVerify(privKey)); return new NodeKey(privKey); }; /** * Load a NodeKey from a file. * @param path the path to the file * @param password an optional password to decrypt the file * @returns a NodeKey if a file containing a valid ECDSA private key exists at the given path */ NodeKey.fromFile = (path, password) => { let buf; if (password) { const encryptedString = fs_1.default.readFileSync(path, 'utf8'); const decryptedString = crypto_js_1.default.AES.decrypt(encryptedString, password).toString(crypto_js_1.default.enc.Hex); buf = Buffer.from(decryptedString, 'hex'); } else { buf = fs_1.default.readFileSync(path); } if (secp256k1_1.default.privateKeyVerify(buf)) { return new NodeKey(buf); } else { throw new Error(`${path} does not contain a valid ECDSA private key`); } }; /** * Load a node key from a file or create one if none exists. See [[fromFile]] and [[generate]]. */ NodeKey.load = (xudir, instanceId = 0) => { const path = instanceId > 0 ? `${xudir}/nodekey_${instanceId}.dat` : `${xudir}/nodekey.dat`; let nodeKey; if (fs_1.default.existsSync(path)) { nodeKey = NodeKey.fromFile(path); } else { nodeKey = NodeKey.generate(); nodeKey.toFile(path); } return nodeKey; }; exports.default = NodeKey; //# sourceMappingURL=NodeKey.js.map