Current Folder
This commit is contained in:
1 parent
8b3382289b
commit
cfcada880d
4379 files changed
No files matched your search
+38
@@ -0,0 +1,38 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var browserifyAes = require("browserify-aes");
|
||||
var SUPPORTED_MODES = ["aes-128-ctr", "aes-128-cbc", "aes-256-cbc"];
|
||||
function ensureAesMode(mode) {
|
||||
if (!mode.startsWith("aes-")) {
|
||||
throw new Error("AES submodule doesn't support mode " + mode);
|
||||
}
|
||||
}
|
||||
function warnIfUnsuportedMode(mode) {
|
||||
if (!SUPPORTED_MODES.includes(mode)) {
|
||||
// tslint:disable-next-line no-console
|
||||
console.warn("Using an unsupported AES mode. Consider using aes-128-ctr.");
|
||||
}
|
||||
}
|
||||
function encrypt(msg, key, iv, mode, pkcs7PaddingEnabled) {
|
||||
if (mode === void 0) { mode = "aes-128-ctr"; }
|
||||
if (pkcs7PaddingEnabled === void 0) { pkcs7PaddingEnabled = true; }
|
||||
ensureAesMode(mode);
|
||||
var cipher = browserifyAes.createCipheriv(mode, key, iv);
|
||||
cipher.setAutoPadding(pkcs7PaddingEnabled);
|
||||
var encrypted = cipher.update(msg);
|
||||
var final = cipher.final();
|
||||
return Buffer.concat([encrypted, final]);
|
||||
}
|
||||
exports.encrypt = encrypt;
|
||||
function decrypt(cypherText, key, iv, mode, pkcs7PaddingEnabled) {
|
||||
if (mode === void 0) { mode = "aes-128-ctr"; }
|
||||
if (pkcs7PaddingEnabled === void 0) { pkcs7PaddingEnabled = true; }
|
||||
ensureAesMode(mode);
|
||||
var decipher = browserifyAes.createDecipheriv(mode, key, iv);
|
||||
decipher.setAutoPadding(pkcs7PaddingEnabled);
|
||||
var encrypted = decipher.update(cypherText);
|
||||
var final = decipher.final();
|
||||
return Buffer.concat([encrypted, final]);
|
||||
}
|
||||
exports.decrypt = decrypt;
|
||||
//# sourceMappingURL=aes.js.map
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __generator = (this && this.__generator) || function (thisArg, body) {
|
||||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
||||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
||||
function verb(n) { return function (v) { return step([n, v]); }; }
|
||||
function step(op) {
|
||||
if (f) throw new TypeError("Generator is already executing.");
|
||||
while (_) try {
|
||||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
||||
if (y = 0, t) op = [op[0] & 2, t.value];
|
||||
switch (op[0]) {
|
||||
case 0: case 1: t = op; break;
|
||||
case 4: _.label++; return { value: op[1], done: false };
|
||||
case 5: _.label++; y = op[1]; op = [0]; continue;
|
||||
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
||||
default:
|
||||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
||||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
||||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
||||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
||||
if (t[2]) _.ops.pop();
|
||||
_.trys.pop(); continue;
|
||||
}
|
||||
op = body.call(thisArg, _);
|
||||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
||||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
||||
}
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var bip39 = require("../vendor/bip39-without-wordlists");
|
||||
function generateMnemonic(wordlist, strength) {
|
||||
if (strength === void 0) { strength = 128; }
|
||||
return bip39.generateMnemonic(strength, undefined, wordlist);
|
||||
}
|
||||
exports.generateMnemonic = generateMnemonic;
|
||||
function mnemonicToEntropy(mnemonic, wordlist) {
|
||||
return bip39.mnemonicToEntropy(mnemonic, wordlist);
|
||||
}
|
||||
exports.mnemonicToEntropy = mnemonicToEntropy;
|
||||
function entropyToMnemonic(entropy, wordlist) {
|
||||
return bip39.entropyToMnemonic(entropy, wordlist);
|
||||
}
|
||||
exports.entropyToMnemonic = entropyToMnemonic;
|
||||
function validateMnemonic(mnemonic, wordlist) {
|
||||
return bip39.validateMnemonic(mnemonic, wordlist);
|
||||
}
|
||||
exports.validateMnemonic = validateMnemonic;
|
||||
function mnemonicToSeed(mnemonic, passphrase) {
|
||||
if (passphrase === void 0) { passphrase = ""; }
|
||||
return __awaiter(this, void 0, void 0, function () {
|
||||
return __generator(this, function (_a) {
|
||||
return [2 /*return*/, bip39.mnemonicToSeed(mnemonic, passphrase)];
|
||||
});
|
||||
});
|
||||
}
|
||||
exports.mnemonicToSeed = mnemonicToSeed;
|
||||
function mnemonicToSeedSync(mnemonic, passphrase) {
|
||||
if (passphrase === void 0) { passphrase = ""; }
|
||||
return bip39.mnemonicToSeedSync(mnemonic, passphrase);
|
||||
}
|
||||
exports.mnemonicToSeedSync = mnemonicToSeedSync;
|
||||
//# sourceMappingURL=index.js.map
|
||||
+2053
File diff suppressed because it is too large.
Load diff
+2053
File diff suppressed because it is too large.
Load diff
+2053
File diff suppressed because it is too large.
Load diff
+2053
File diff suppressed because it is too large.
Load diff
+2053
File diff suppressed because it is too large.
Load diff
+2053
File diff suppressed because it is too large.
Load diff
Generated
Vendored
+2053
File diff suppressed because it is too large.
Load diff
+2053
File diff suppressed because it is too large.
Load diff
Generated
Vendored
+2053
File diff suppressed because it is too large.
Load diff
+12
@@ -0,0 +1,12 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var blake2bJs = require("blakejs");
|
||||
function blake2b(input, outputLength) {
|
||||
if (outputLength === void 0) { outputLength = 64; }
|
||||
if (outputLength <= 0 || outputLength > 64) {
|
||||
throw Error("Invalid outputLength");
|
||||
}
|
||||
return Buffer.from(blake2bJs.blake2b(input, undefined, outputLength));
|
||||
}
|
||||
exports.blake2b = blake2b;
|
||||
//# sourceMappingURL=blake2b.js.map
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
function createHashFunction(hashConstructor) {
|
||||
return function (msg) {
|
||||
var hash = hashConstructor();
|
||||
hash.update(msg);
|
||||
return Buffer.from(hash.digest());
|
||||
};
|
||||
}
|
||||
exports.createHashFunction = createHashFunction;
|
||||
//# sourceMappingURL=hash-utils.js.map
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var hdkey = require("./vendor/hdkey-without-crypto");
|
||||
exports.HDKey = hdkey;
|
||||
//# sourceMappingURL=hdkey.js.map
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
"use strict";
|
||||
throw new Error("This package has no entry-point. Please consult the README.md to learn how to use it.");
|
||||
//# sourceMappingURL=index.js.map
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var hash_utils_1 = require("./hash-utils");
|
||||
var createKeccakHash = require("keccak");
|
||||
exports.keccak224 = hash_utils_1.createHashFunction(function () {
|
||||
return createKeccakHash("keccak224");
|
||||
});
|
||||
exports.keccak256 = hash_utils_1.createHashFunction(function () {
|
||||
return createKeccakHash("keccak256");
|
||||
});
|
||||
exports.keccak384 = hash_utils_1.createHashFunction(function () {
|
||||
return createKeccakHash("keccak384");
|
||||
});
|
||||
exports.keccak512 = hash_utils_1.createHashFunction(function () {
|
||||
return createKeccakHash("keccak512");
|
||||
});
|
||||
//# sourceMappingURL=keccak.js.map
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
{
|
||||
"_from": "ethereum-cryptography@^0.1.3",
|
||||
"_id": "ethereum-cryptography@0.1.3",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-w8/4x1SGGzc+tO97TASLja6SLd3fRIK2tLVcV2Gx4IB21hE19atll5Cq9o3d0ZmAYC/8aw0ipieTSiekAea4SQ==",
|
||||
"_location": "/ethereum-cryptography",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "ethereum-cryptography@^0.1.3",
|
||||
"name": "ethereum-cryptography",
|
||||
"escapedName": "ethereum-cryptography",
|
||||
"rawSpec": "^0.1.3",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^0.1.3"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/ethereumjs-util"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/ethereum-cryptography/-/ethereum-cryptography-0.1.3.tgz",
|
||||
"_shasum": "8d6143cfc3d74bf79bbd8edecdf29e4ae20dd191",
|
||||
"_spec": "ethereum-cryptography@^0.1.3",
|
||||
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\BackendServers\\node_modules\\ethereumjs-util",
|
||||
"browser": {
|
||||
"./hdkey.js": "./pure/hdkey.js",
|
||||
"./ripemd160.js": "./pure/ripemd160.js",
|
||||
"./sha256.js": "./pure/sha256.js"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/ethereum/js-ethereum-cryptography/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Patricio Palladino",
|
||||
"email": "patricio@nomiclabs.io"
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"@types/pbkdf2": "^3.0.0",
|
||||
"@types/secp256k1": "^4.0.1",
|
||||
"blakejs": "^1.1.0",
|
||||
"browserify-aes": "^1.2.0",
|
||||
"bs58check": "^2.1.2",
|
||||
"create-hash": "^1.2.0",
|
||||
"create-hmac": "^1.1.7",
|
||||
"hash.js": "^1.1.7",
|
||||
"keccak": "^3.0.0",
|
||||
"pbkdf2": "^3.0.17",
|
||||
"randombytes": "^2.1.0",
|
||||
"safe-buffer": "^5.1.2",
|
||||
"scrypt-js": "^3.0.0",
|
||||
"secp256k1": "^4.0.1",
|
||||
"setimmediate": "^1.0.5"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "All the cryptographic primitives used in Ethereum",
|
||||
"devDependencies": {
|
||||
"@types/chai": "^4.2.1",
|
||||
"@types/mocha": "^5.2.7",
|
||||
"@types/node": "^8.10.52",
|
||||
"browserify": "^16.5.0",
|
||||
"chai": "^4.2.0",
|
||||
"karma": "^4.3.0",
|
||||
"karma-chai": "^0.1.0",
|
||||
"karma-chrome-launcher": "^3.1.0",
|
||||
"karma-mocha": "^1.3.0",
|
||||
"karma-mocha-reporter": "^2.2.5",
|
||||
"mocha": "^6.2.0",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"parcel-bundler": "^1.12.3",
|
||||
"prettier": "1.18.2",
|
||||
"rimraf": "^3.0.0",
|
||||
"rollup": "^1.20.3",
|
||||
"rollup-plugin-alias": "^2.0.0",
|
||||
"rollup-plugin-commonjs": "^10.1.0",
|
||||
"rollup-plugin-json": "^4.0.0",
|
||||
"rollup-plugin-node-builtins": "^2.1.2",
|
||||
"rollup-plugin-node-globals": "^1.4.0",
|
||||
"rollup-plugin-node-resolve": "^5.2.0",
|
||||
"rollup-plugin-replace": "^2.2.0",
|
||||
"ts-node": "^8.3.0",
|
||||
"tslint": "^5.19.0",
|
||||
"tslint-config-prettier": "^1.18.0",
|
||||
"tslint-plugin-prettier": "^2.0.1",
|
||||
"typescript": "~3.6.2",
|
||||
"webpack": "^4.39.3",
|
||||
"webpack-cli": "^3.3.8"
|
||||
},
|
||||
"files": [
|
||||
"src",
|
||||
"vendor",
|
||||
"shims",
|
||||
"bip39",
|
||||
"*.js",
|
||||
"*.js.map",
|
||||
"*.d.ts",
|
||||
"*.d.ts.map",
|
||||
"pure/**/*.js",
|
||||
"pure/**/*.js.map",
|
||||
"pure/**/*.d.ts",
|
||||
"pure/**/*.d.ts.map"
|
||||
],
|
||||
"homepage": "https://github.com/ethereum/js-ethereum-cryptography#readme",
|
||||
"keywords": [
|
||||
"ethereum",
|
||||
"cryptography",
|
||||
"digital signature",
|
||||
"hash",
|
||||
"encryption",
|
||||
"prng",
|
||||
"keccak",
|
||||
"scrypt",
|
||||
"pbkdf2",
|
||||
"sha-256",
|
||||
"ripemd-160",
|
||||
"blake2b",
|
||||
"aes",
|
||||
"advanced encryption standar",
|
||||
"secp256k1",
|
||||
"ecdsa",
|
||||
"bip32",
|
||||
"hierarchical deterministic keys",
|
||||
"hdwallet",
|
||||
"hdkeys"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "./index.js",
|
||||
"name": "ethereum-cryptography",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/ethereum/js-ethereum-cryptography.git"
|
||||
},
|
||||
"scripts": {
|
||||
"bip39-without-wordlists:build": "bash -x scripts/build-bip39-without-wordlists.sh",
|
||||
"bip39-without-wordlists:copy": "mkdir -p vendor && cp src/vendor/bip39-without-wordlists.js ./vendor",
|
||||
"browser-tests": "npm-run-all browser-tests:build browser-tests:test",
|
||||
"browser-tests:build": "bash -x ./scripts/build-browser-tests.sh",
|
||||
"browser-tests:test": "npm-run-all browser-tests:test-parcel browser-tests:test-browserify browser-tests:test-webpack browser-tests:test-rollup",
|
||||
"browser-tests:test-browserify": "karma start --single-run --browsers ChromeHeadless test/karma.browserify.conf.js",
|
||||
"browser-tests:test-parcel": "karma start --single-run --browsers ChromeHeadless test/karma.parcel.conf.js",
|
||||
"browser-tests:test-rollup": "karma start --single-run --browsers ChromeHeadless test/karma.rollup.conf.js",
|
||||
"browser-tests:test-webpack": "karma start --single-run --browsers ChromeHeadless test/karma.webpack.conf.js",
|
||||
"build": "npm-run-all build:tsc hdkey-without-crypto:build hdkey-without-crypto:copy bip39-without-wordlists:build bip39-without-wordlists:copy",
|
||||
"build:tsc": "tsc --project tsconfig.prod.json",
|
||||
"clean": "rimraf vendor test-builds pure shims hdkey-without-crypto-build bip39-without-wordlists-build bip39 '*.js' '*.js.map' '*.d.ts' '*.d.ts.map' 'src/**/*.js'",
|
||||
"hdkey-without-crypto:build": "bash -x scripts/build-hdkey-without-crypto.sh",
|
||||
"hdkey-without-crypto:copy": "mkdir -p vendor pure/vendor && cp src/vendor/hdkey-without-crypto.js ./vendor && cp src/pure/vendor/hdkey-without-crypto.js ./pure/vendor",
|
||||
"lint": "tslint --project tsconfig.json",
|
||||
"lint:fix": "tslint --fix --project tsconfig.json",
|
||||
"prepare": "npm run build",
|
||||
"test": "npm-run-all hdkey-without-crypto:build bip39-without-wordlists:build test:node",
|
||||
"test:node": "mocha"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"types": "./index.d.ts",
|
||||
"version": "0.1.3"
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
"use strict";
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
||||
result["default"] = mod;
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var pbkdf2Js = __importStar(require("pbkdf2"));
|
||||
function pbkdf2(password, salt, iterations, keylen, digest) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
pbkdf2Js.pbkdf2(password, salt, iterations, keylen, digest, function (err, result) {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve(result);
|
||||
});
|
||||
});
|
||||
}
|
||||
exports.pbkdf2 = pbkdf2;
|
||||
function pbkdf2Sync(password, salt, iterations, keylen, digest) {
|
||||
return pbkdf2Js.pbkdf2Sync(password, salt, iterations, keylen, digest);
|
||||
}
|
||||
exports.pbkdf2Sync = pbkdf2Sync;
|
||||
//# sourceMappingURL=pbkdf2.js.map
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var hdkey = require("./vendor/hdkey-without-crypto");
|
||||
exports.HDKey = hdkey;
|
||||
//# sourceMappingURL=hdkey.js.map
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var Ripemd160 = require("hash.js/lib/hash/ripemd").ripemd160;
|
||||
var hash_utils_1 = require("../hash-utils");
|
||||
exports.ripemd160 = hash_utils_1.createHashFunction(function () { return new Ripemd160(); });
|
||||
//# sourceMappingURL=ripemd160.js.map
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var Sha256Hash = require("hash.js/lib/hash/sha/256");
|
||||
var hash_utils_1 = require("../hash-utils");
|
||||
exports.sha256 = hash_utils_1.createHashFunction(function () { return new Sha256Hash(); });
|
||||
//# sourceMappingURL=sha256.js.map
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var ripemd160_1 = require("../ripemd160");
|
||||
var sha256_1 = require("../sha256");
|
||||
exports.createHmac = require("create-hmac");
|
||||
exports.randomBytes = require("randombytes");
|
||||
var Hash = /** @class */ (function () {
|
||||
function Hash(hashFunction) {
|
||||
this.hashFunction = hashFunction;
|
||||
this.buffers = [];
|
||||
}
|
||||
Hash.prototype.update = function (buffer) {
|
||||
if (!Buffer.isBuffer(buffer)) {
|
||||
throw new Error("hdkey-crypto shim is outdated");
|
||||
}
|
||||
this.buffers.push(buffer);
|
||||
return this;
|
||||
};
|
||||
Hash.prototype.digest = function (param) {
|
||||
if (param) {
|
||||
throw new Error("hdkey-crypto shim is outdated");
|
||||
}
|
||||
return this.hashFunction(Buffer.concat(this.buffers));
|
||||
};
|
||||
return Hash;
|
||||
}());
|
||||
// We don't use create-hash here, as it doesn't work well with Rollup
|
||||
exports.createHash = function (name) {
|
||||
if (name === "ripemd160") {
|
||||
return new Hash(ripemd160_1.ripemd160);
|
||||
}
|
||||
if (name === "sha256") {
|
||||
return new Hash(sha256_1.sha256);
|
||||
}
|
||||
throw new Error("hdkey-crypto shim is outdated");
|
||||
};
|
||||
//# sourceMappingURL=hdkey-crypto.js.map
|
||||
Generated
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
function __export(m) {
|
||||
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
|
||||
}
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
__export(require("../../shims/hdkey-secp256k1v3"));
|
||||
//# sourceMappingURL=hdkey-secp256k1v3.js.map
|
||||
Generated
Vendored
+255
@@ -0,0 +1,255 @@
|
||||
'use strict';
|
||||
|
||||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
|
||||
|
||||
var assert = _interopDefault(require('assert'));
|
||||
var safeBuffer = _interopDefault(require('safe-buffer'));
|
||||
var bs58check = _interopDefault(require('bs58check'));
|
||||
|
||||
var cryptoShim = require("../shims/hdkey-crypto");
|
||||
|
||||
var secp256k1Shim = require("../shims/hdkey-secp256k1v3");
|
||||
|
||||
var Buffer = safeBuffer.Buffer;
|
||||
|
||||
|
||||
|
||||
|
||||
var MASTER_SECRET = Buffer.from('Bitcoin seed', 'utf8');
|
||||
var HARDENED_OFFSET = 0x80000000;
|
||||
var LEN = 78;
|
||||
|
||||
// Bitcoin hardcoded by default, can use package `coininfo` for others
|
||||
var BITCOIN_VERSIONS = {private: 0x0488ADE4, public: 0x0488B21E};
|
||||
|
||||
function HDKey (versions) {
|
||||
this.versions = versions || BITCOIN_VERSIONS;
|
||||
this.depth = 0;
|
||||
this.index = 0;
|
||||
this._privateKey = null;
|
||||
this._publicKey = null;
|
||||
this.chainCode = null;
|
||||
this._fingerprint = 0;
|
||||
this.parentFingerprint = 0;
|
||||
}
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'fingerprint', { get: function () { return this._fingerprint } });
|
||||
Object.defineProperty(HDKey.prototype, 'identifier', { get: function () { return this._identifier } });
|
||||
Object.defineProperty(HDKey.prototype, 'pubKeyHash', { get: function () { return this.identifier } });
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'privateKey', {
|
||||
get: function () {
|
||||
return this._privateKey
|
||||
},
|
||||
set: function (value) {
|
||||
assert.equal(value.length, 32, 'Private key must be 32 bytes.');
|
||||
assert(secp256k1Shim.privateKeyVerify(value) === true, 'Invalid private key');
|
||||
|
||||
this._privateKey = value;
|
||||
this._publicKey = secp256k1Shim.publicKeyCreate(value, true);
|
||||
this._identifier = hash160(this.publicKey);
|
||||
this._fingerprint = this._identifier.slice(0, 4).readUInt32BE(0);
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'publicKey', {
|
||||
get: function () {
|
||||
return this._publicKey
|
||||
},
|
||||
set: function (value) {
|
||||
assert(value.length === 33 || value.length === 65, 'Public key must be 33 or 65 bytes.');
|
||||
assert(secp256k1Shim.publicKeyVerify(value) === true, 'Invalid public key');
|
||||
|
||||
this._publicKey = secp256k1Shim.publicKeyConvert(value, true); // force compressed point
|
||||
this._identifier = hash160(this.publicKey);
|
||||
this._fingerprint = this._identifier.slice(0, 4).readUInt32BE(0);
|
||||
this._privateKey = null;
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'privateExtendedKey', {
|
||||
get: function () {
|
||||
if (this._privateKey) return bs58check.encode(serialize(this, this.versions.private, Buffer.concat([Buffer.alloc(1, 0), this.privateKey])))
|
||||
else return null
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'publicExtendedKey', {
|
||||
get: function () {
|
||||
return bs58check.encode(serialize(this, this.versions.public, this.publicKey))
|
||||
}
|
||||
});
|
||||
|
||||
HDKey.prototype.derive = function (path) {
|
||||
if (path === 'm' || path === 'M' || path === "m'" || path === "M'") {
|
||||
return this
|
||||
}
|
||||
|
||||
var entries = path.split('/');
|
||||
var hdkey = this;
|
||||
entries.forEach(function (c, i) {
|
||||
if (i === 0) {
|
||||
assert(/^[mM]{1}/.test(c), 'Path must start with "m" or "M"');
|
||||
return
|
||||
}
|
||||
|
||||
var hardened = (c.length > 1) && (c[c.length - 1] === "'");
|
||||
var childIndex = parseInt(c, 10); // & (HARDENED_OFFSET - 1)
|
||||
assert(childIndex < HARDENED_OFFSET, 'Invalid index');
|
||||
if (hardened) childIndex += HARDENED_OFFSET;
|
||||
|
||||
hdkey = hdkey.deriveChild(childIndex);
|
||||
});
|
||||
|
||||
return hdkey
|
||||
};
|
||||
|
||||
HDKey.prototype.deriveChild = function (index) {
|
||||
var isHardened = index >= HARDENED_OFFSET;
|
||||
var indexBuffer = Buffer.allocUnsafe(4);
|
||||
indexBuffer.writeUInt32BE(index, 0);
|
||||
|
||||
var data;
|
||||
|
||||
if (isHardened) { // Hardened child
|
||||
assert(this.privateKey, 'Could not derive hardened child key');
|
||||
|
||||
var pk = this.privateKey;
|
||||
var zb = Buffer.alloc(1, 0);
|
||||
pk = Buffer.concat([zb, pk]);
|
||||
|
||||
// data = 0x00 || ser256(kpar) || ser32(index)
|
||||
data = Buffer.concat([pk, indexBuffer]);
|
||||
} else { // Normal child
|
||||
// data = serP(point(kpar)) || ser32(index)
|
||||
// = serP(Kpar) || ser32(index)
|
||||
data = Buffer.concat([this.publicKey, indexBuffer]);
|
||||
}
|
||||
|
||||
var I = cryptoShim.createHmac('sha512', this.chainCode).update(data).digest();
|
||||
var IL = I.slice(0, 32);
|
||||
var IR = I.slice(32);
|
||||
|
||||
var hd = new HDKey(this.versions);
|
||||
|
||||
// Private parent key -> private child key
|
||||
if (this.privateKey) {
|
||||
// ki = parse256(IL) + kpar (mod n)
|
||||
try {
|
||||
hd.privateKey = secp256k1Shim.privateKeyTweakAdd(this.privateKey, IL);
|
||||
// throw if IL >= n || (privateKey + IL) === 0
|
||||
} catch (err) {
|
||||
// In case parse256(IL) >= n or ki == 0, one should proceed with the next value for i
|
||||
return this.deriveChild(index + 1)
|
||||
}
|
||||
// Public parent key -> public child key
|
||||
} else {
|
||||
// Ki = point(parse256(IL)) + Kpar
|
||||
// = G*IL + Kpar
|
||||
try {
|
||||
hd.publicKey = secp256k1Shim.publicKeyTweakAdd(this.publicKey, IL, true);
|
||||
// throw if IL >= n || (g**IL + publicKey) is infinity
|
||||
} catch (err) {
|
||||
// In case parse256(IL) >= n or Ki is the point at infinity, one should proceed with the next value for i
|
||||
return this.deriveChild(index + 1)
|
||||
}
|
||||
}
|
||||
|
||||
hd.chainCode = IR;
|
||||
hd.depth = this.depth + 1;
|
||||
hd.parentFingerprint = this.fingerprint;// .readUInt32BE(0)
|
||||
hd.index = index;
|
||||
|
||||
return hd
|
||||
};
|
||||
|
||||
HDKey.prototype.sign = function (hash) {
|
||||
return secp256k1Shim.sign(hash, this.privateKey).signature
|
||||
};
|
||||
|
||||
HDKey.prototype.verify = function (hash, signature) {
|
||||
return secp256k1Shim.verify(hash, signature, this.publicKey)
|
||||
};
|
||||
|
||||
HDKey.prototype.wipePrivateData = function () {
|
||||
if (this._privateKey) cryptoShim.randomBytes(this._privateKey.length).copy(this._privateKey);
|
||||
this._privateKey = null;
|
||||
return this
|
||||
};
|
||||
|
||||
HDKey.prototype.toJSON = function () {
|
||||
return {
|
||||
xpriv: this.privateExtendedKey,
|
||||
xpub: this.publicExtendedKey
|
||||
}
|
||||
};
|
||||
|
||||
HDKey.fromMasterSeed = function (seedBuffer, versions) {
|
||||
var I = cryptoShim.createHmac('sha512', MASTER_SECRET).update(seedBuffer).digest();
|
||||
var IL = I.slice(0, 32);
|
||||
var IR = I.slice(32);
|
||||
|
||||
var hdkey = new HDKey(versions);
|
||||
hdkey.chainCode = IR;
|
||||
hdkey.privateKey = IL;
|
||||
|
||||
return hdkey
|
||||
};
|
||||
|
||||
HDKey.fromExtendedKey = function (base58key, versions) {
|
||||
// => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
|
||||
versions = versions || BITCOIN_VERSIONS;
|
||||
var hdkey = new HDKey(versions);
|
||||
|
||||
var keyBuffer = bs58check.decode(base58key);
|
||||
|
||||
var version = keyBuffer.readUInt32BE(0);
|
||||
assert(version === versions.private || version === versions.public, 'Version mismatch: does not match private or public');
|
||||
|
||||
hdkey.depth = keyBuffer.readUInt8(4);
|
||||
hdkey.parentFingerprint = keyBuffer.readUInt32BE(5);
|
||||
hdkey.index = keyBuffer.readUInt32BE(9);
|
||||
hdkey.chainCode = keyBuffer.slice(13, 45);
|
||||
|
||||
var key = keyBuffer.slice(45);
|
||||
if (key.readUInt8(0) === 0) { // private
|
||||
assert(version === versions.private, 'Version mismatch: version does not match private');
|
||||
hdkey.privateKey = key.slice(1); // cut off first 0x0 byte
|
||||
} else {
|
||||
assert(version === versions.public, 'Version mismatch: version does not match public');
|
||||
hdkey.publicKey = key;
|
||||
}
|
||||
|
||||
return hdkey
|
||||
};
|
||||
|
||||
HDKey.fromJSON = function (obj) {
|
||||
return HDKey.fromExtendedKey(obj.xpriv)
|
||||
};
|
||||
|
||||
function serialize (hdkey, version, key) {
|
||||
// => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
|
||||
var buffer = Buffer.allocUnsafe(LEN);
|
||||
|
||||
buffer.writeUInt32BE(version, 0);
|
||||
buffer.writeUInt8(hdkey.depth, 4);
|
||||
|
||||
var fingerprint = hdkey.depth ? hdkey.parentFingerprint : 0x00000000;
|
||||
buffer.writeUInt32BE(fingerprint, 5);
|
||||
buffer.writeUInt32BE(hdkey.index, 9);
|
||||
|
||||
hdkey.chainCode.copy(buffer, 13);
|
||||
key.copy(buffer, 45);
|
||||
|
||||
return buffer
|
||||
}
|
||||
|
||||
function hash160 (buf) {
|
||||
var sha = cryptoShim.createHash('sha256').update(buf).digest();
|
||||
return cryptoShim.createHash('ripemd160').update(sha).digest()
|
||||
}
|
||||
|
||||
HDKey.HARDENED_OFFSET = HARDENED_OFFSET;
|
||||
var hdkey = HDKey;
|
||||
|
||||
module.exports = hdkey;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var randombytes = require("randombytes");
|
||||
function getRandomBytes(bytes) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
randombytes(bytes, function (err, resp) {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve(resp);
|
||||
});
|
||||
});
|
||||
}
|
||||
exports.getRandomBytes = getRandomBytes;
|
||||
function getRandomBytesSync(bytes) {
|
||||
return randombytes(bytes);
|
||||
}
|
||||
exports.getRandomBytesSync = getRandomBytesSync;
|
||||
//# sourceMappingURL=random.js.map
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var crypto_1 = __importDefault(require("crypto"));
|
||||
var hash_utils_1 = require("./hash-utils");
|
||||
exports.ripemd160 = hash_utils_1.createHashFunction(function () {
|
||||
return crypto_1.default.createHash("ripemd160");
|
||||
});
|
||||
//# sourceMappingURL=ripemd160.js.map
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __generator = (this && this.__generator) || function (thisArg, body) {
|
||||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
||||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
||||
function verb(n) { return function (v) { return step([n, v]); }; }
|
||||
function step(op) {
|
||||
if (f) throw new TypeError("Generator is already executing.");
|
||||
while (_) try {
|
||||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
||||
if (y = 0, t) op = [op[0] & 2, t.value];
|
||||
switch (op[0]) {
|
||||
case 0: case 1: t = op; break;
|
||||
case 4: _.label++; return { value: op[1], done: false };
|
||||
case 5: _.label++; y = op[1]; op = [0]; continue;
|
||||
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
||||
default:
|
||||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
||||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
||||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
||||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
||||
if (t[2]) _.ops.pop();
|
||||
_.trys.pop(); continue;
|
||||
}
|
||||
op = body.call(thisArg, _);
|
||||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
||||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
||||
}
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
require("scrypt-js/thirdparty/setImmediate");
|
||||
var scryptJs = require("scrypt-js");
|
||||
function scrypt(password, salt, n, p, r, dklen) {
|
||||
return __awaiter(this, void 0, void 0, function () {
|
||||
var _a, _b;
|
||||
return __generator(this, function (_c) {
|
||||
switch (_c.label) {
|
||||
case 0:
|
||||
_b = (_a = Buffer).from;
|
||||
return [4 /*yield*/, scryptJs.scrypt(password, salt, n, r, p, dklen)];
|
||||
case 1: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
exports.scrypt = scrypt;
|
||||
function scryptSync(password, salt, n, p, r, dklen) {
|
||||
return Buffer.from(scryptJs.syncScrypt(password, salt, n, r, p, dklen));
|
||||
}
|
||||
exports.scryptSync = scryptSync;
|
||||
//# sourceMappingURL=scrypt.js.map
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __generator = (this && this.__generator) || function (thisArg, body) {
|
||||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
||||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
||||
function verb(n) { return function (v) { return step([n, v]); }; }
|
||||
function step(op) {
|
||||
if (f) throw new TypeError("Generator is already executing.");
|
||||
while (_) try {
|
||||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
||||
if (y = 0, t) op = [op[0] & 2, t.value];
|
||||
switch (op[0]) {
|
||||
case 0: case 1: t = op; break;
|
||||
case 4: _.label++; return { value: op[1], done: false };
|
||||
case 5: _.label++; y = op[1]; op = [0]; continue;
|
||||
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
||||
default:
|
||||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
||||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
||||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
||||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
||||
if (t[2]) _.ops.pop();
|
||||
_.trys.pop(); continue;
|
||||
}
|
||||
op = body.call(thisArg, _);
|
||||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
||||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
||||
}
|
||||
};
|
||||
function __export(m) {
|
||||
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
|
||||
}
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var secp256k1_1 = require("secp256k1");
|
||||
var random_1 = require("./random");
|
||||
var SECP256K1_PRIVATE_KEY_SIZE = 32;
|
||||
function createPrivateKey() {
|
||||
return __awaiter(this, void 0, void 0, function () {
|
||||
var pk;
|
||||
return __generator(this, function (_a) {
|
||||
switch (_a.label) {
|
||||
case 0:
|
||||
if (!true) return [3 /*break*/, 2];
|
||||
return [4 /*yield*/, random_1.getRandomBytes(SECP256K1_PRIVATE_KEY_SIZE)];
|
||||
case 1:
|
||||
pk = _a.sent();
|
||||
if (secp256k1_1.privateKeyVerify(pk)) {
|
||||
return [2 /*return*/, pk];
|
||||
}
|
||||
return [3 /*break*/, 0];
|
||||
case 2: return [2 /*return*/];
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
exports.createPrivateKey = createPrivateKey;
|
||||
function createPrivateKeySync() {
|
||||
while (true) {
|
||||
var pk = random_1.getRandomBytesSync(SECP256K1_PRIVATE_KEY_SIZE);
|
||||
if (secp256k1_1.privateKeyVerify(pk)) {
|
||||
return pk;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.createPrivateKeySync = createPrivateKeySync;
|
||||
__export(require("secp256k1"));
|
||||
//# sourceMappingURL=secp256k1.js.map
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var crypto_1 = __importDefault(require("crypto"));
|
||||
var hash_utils_1 = require("./hash-utils");
|
||||
exports.sha256 = hash_utils_1.createHashFunction(function () { return crypto_1.default.createHash("sha256"); });
|
||||
//# sourceMappingURL=sha256.js.map
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var crypto_1 = require("crypto");
|
||||
exports.createHash = crypto_1.createHash;
|
||||
exports.createHmac = crypto_1.createHmac;
|
||||
exports.randomBytes = crypto_1.randomBytes;
|
||||
//# sourceMappingURL=hdkey-crypto.js.map
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
"use strict";
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
||||
result["default"] = mod;
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var secp256k1 = __importStar(require("secp256k1"));
|
||||
function privateKeyVerify(privateKey) {
|
||||
return secp256k1.privateKeyVerify(privateKey);
|
||||
}
|
||||
exports.privateKeyVerify = privateKeyVerify;
|
||||
function publicKeyCreate(privateKey, compressed) {
|
||||
if (compressed === void 0) { compressed = true; }
|
||||
return Buffer.from(secp256k1.publicKeyCreate(privateKey, compressed));
|
||||
}
|
||||
exports.publicKeyCreate = publicKeyCreate;
|
||||
function publicKeyVerify(publicKey) {
|
||||
return secp256k1.publicKeyVerify(publicKey);
|
||||
}
|
||||
exports.publicKeyVerify = publicKeyVerify;
|
||||
function publicKeyConvert(publicKey, compressed) {
|
||||
if (compressed === void 0) { compressed = true; }
|
||||
return Buffer.from(secp256k1.publicKeyConvert(publicKey, compressed));
|
||||
}
|
||||
exports.publicKeyConvert = publicKeyConvert;
|
||||
function privateKeyTweakAdd(publicKey, tweak) {
|
||||
return Buffer.from(secp256k1.privateKeyTweakAdd(Buffer.from(publicKey), tweak));
|
||||
}
|
||||
exports.privateKeyTweakAdd = privateKeyTweakAdd;
|
||||
function publicKeyTweakAdd(publicKey, tweak, compressed) {
|
||||
if (compressed === void 0) { compressed = true; }
|
||||
return Buffer.from(secp256k1.publicKeyTweakAdd(Buffer.from(publicKey), tweak, compressed));
|
||||
}
|
||||
exports.publicKeyTweakAdd = publicKeyTweakAdd;
|
||||
function sign(message, privateKey) {
|
||||
var ret = secp256k1.ecdsaSign(message, privateKey);
|
||||
return { signature: Buffer.from(ret.signature), recovery: ret.recid };
|
||||
}
|
||||
exports.sign = sign;
|
||||
function verify(message, signature, publicKey) {
|
||||
return secp256k1.ecdsaVerify(signature, message, publicKey);
|
||||
}
|
||||
exports.verify = verify;
|
||||
//# sourceMappingURL=hdkey-secp256k1v3.js.map
|
||||
Generated
Vendored
+255
@@ -0,0 +1,255 @@
|
||||
'use strict';
|
||||
|
||||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
|
||||
|
||||
var assert = _interopDefault(require('assert'));
|
||||
var safeBuffer = _interopDefault(require('safe-buffer'));
|
||||
var bs58check = _interopDefault(require('bs58check'));
|
||||
|
||||
var cryptoShim = require("../shims/hdkey-crypto");
|
||||
|
||||
var secp256k1Shim = require("../shims/hdkey-secp256k1v3");
|
||||
|
||||
var Buffer = safeBuffer.Buffer;
|
||||
|
||||
|
||||
|
||||
|
||||
var MASTER_SECRET = Buffer.from('Bitcoin seed', 'utf8');
|
||||
var HARDENED_OFFSET = 0x80000000;
|
||||
var LEN = 78;
|
||||
|
||||
// Bitcoin hardcoded by default, can use package `coininfo` for others
|
||||
var BITCOIN_VERSIONS = {private: 0x0488ADE4, public: 0x0488B21E};
|
||||
|
||||
function HDKey (versions) {
|
||||
this.versions = versions || BITCOIN_VERSIONS;
|
||||
this.depth = 0;
|
||||
this.index = 0;
|
||||
this._privateKey = null;
|
||||
this._publicKey = null;
|
||||
this.chainCode = null;
|
||||
this._fingerprint = 0;
|
||||
this.parentFingerprint = 0;
|
||||
}
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'fingerprint', { get: function () { return this._fingerprint } });
|
||||
Object.defineProperty(HDKey.prototype, 'identifier', { get: function () { return this._identifier } });
|
||||
Object.defineProperty(HDKey.prototype, 'pubKeyHash', { get: function () { return this.identifier } });
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'privateKey', {
|
||||
get: function () {
|
||||
return this._privateKey
|
||||
},
|
||||
set: function (value) {
|
||||
assert.equal(value.length, 32, 'Private key must be 32 bytes.');
|
||||
assert(secp256k1Shim.privateKeyVerify(value) === true, 'Invalid private key');
|
||||
|
||||
this._privateKey = value;
|
||||
this._publicKey = secp256k1Shim.publicKeyCreate(value, true);
|
||||
this._identifier = hash160(this.publicKey);
|
||||
this._fingerprint = this._identifier.slice(0, 4).readUInt32BE(0);
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'publicKey', {
|
||||
get: function () {
|
||||
return this._publicKey
|
||||
},
|
||||
set: function (value) {
|
||||
assert(value.length === 33 || value.length === 65, 'Public key must be 33 or 65 bytes.');
|
||||
assert(secp256k1Shim.publicKeyVerify(value) === true, 'Invalid public key');
|
||||
|
||||
this._publicKey = secp256k1Shim.publicKeyConvert(value, true); // force compressed point
|
||||
this._identifier = hash160(this.publicKey);
|
||||
this._fingerprint = this._identifier.slice(0, 4).readUInt32BE(0);
|
||||
this._privateKey = null;
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'privateExtendedKey', {
|
||||
get: function () {
|
||||
if (this._privateKey) return bs58check.encode(serialize(this, this.versions.private, Buffer.concat([Buffer.alloc(1, 0), this.privateKey])))
|
||||
else return null
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'publicExtendedKey', {
|
||||
get: function () {
|
||||
return bs58check.encode(serialize(this, this.versions.public, this.publicKey))
|
||||
}
|
||||
});
|
||||
|
||||
HDKey.prototype.derive = function (path) {
|
||||
if (path === 'm' || path === 'M' || path === "m'" || path === "M'") {
|
||||
return this
|
||||
}
|
||||
|
||||
var entries = path.split('/');
|
||||
var hdkey = this;
|
||||
entries.forEach(function (c, i) {
|
||||
if (i === 0) {
|
||||
assert(/^[mM]{1}/.test(c), 'Path must start with "m" or "M"');
|
||||
return
|
||||
}
|
||||
|
||||
var hardened = (c.length > 1) && (c[c.length - 1] === "'");
|
||||
var childIndex = parseInt(c, 10); // & (HARDENED_OFFSET - 1)
|
||||
assert(childIndex < HARDENED_OFFSET, 'Invalid index');
|
||||
if (hardened) childIndex += HARDENED_OFFSET;
|
||||
|
||||
hdkey = hdkey.deriveChild(childIndex);
|
||||
});
|
||||
|
||||
return hdkey
|
||||
};
|
||||
|
||||
HDKey.prototype.deriveChild = function (index) {
|
||||
var isHardened = index >= HARDENED_OFFSET;
|
||||
var indexBuffer = Buffer.allocUnsafe(4);
|
||||
indexBuffer.writeUInt32BE(index, 0);
|
||||
|
||||
var data;
|
||||
|
||||
if (isHardened) { // Hardened child
|
||||
assert(this.privateKey, 'Could not derive hardened child key');
|
||||
|
||||
var pk = this.privateKey;
|
||||
var zb = Buffer.alloc(1, 0);
|
||||
pk = Buffer.concat([zb, pk]);
|
||||
|
||||
// data = 0x00 || ser256(kpar) || ser32(index)
|
||||
data = Buffer.concat([pk, indexBuffer]);
|
||||
} else { // Normal child
|
||||
// data = serP(point(kpar)) || ser32(index)
|
||||
// = serP(Kpar) || ser32(index)
|
||||
data = Buffer.concat([this.publicKey, indexBuffer]);
|
||||
}
|
||||
|
||||
var I = cryptoShim.createHmac('sha512', this.chainCode).update(data).digest();
|
||||
var IL = I.slice(0, 32);
|
||||
var IR = I.slice(32);
|
||||
|
||||
var hd = new HDKey(this.versions);
|
||||
|
||||
// Private parent key -> private child key
|
||||
if (this.privateKey) {
|
||||
// ki = parse256(IL) + kpar (mod n)
|
||||
try {
|
||||
hd.privateKey = secp256k1Shim.privateKeyTweakAdd(this.privateKey, IL);
|
||||
// throw if IL >= n || (privateKey + IL) === 0
|
||||
} catch (err) {
|
||||
// In case parse256(IL) >= n or ki == 0, one should proceed with the next value for i
|
||||
return this.deriveChild(index + 1)
|
||||
}
|
||||
// Public parent key -> public child key
|
||||
} else {
|
||||
// Ki = point(parse256(IL)) + Kpar
|
||||
// = G*IL + Kpar
|
||||
try {
|
||||
hd.publicKey = secp256k1Shim.publicKeyTweakAdd(this.publicKey, IL, true);
|
||||
// throw if IL >= n || (g**IL + publicKey) is infinity
|
||||
} catch (err) {
|
||||
// In case parse256(IL) >= n or Ki is the point at infinity, one should proceed with the next value for i
|
||||
return this.deriveChild(index + 1)
|
||||
}
|
||||
}
|
||||
|
||||
hd.chainCode = IR;
|
||||
hd.depth = this.depth + 1;
|
||||
hd.parentFingerprint = this.fingerprint;// .readUInt32BE(0)
|
||||
hd.index = index;
|
||||
|
||||
return hd
|
||||
};
|
||||
|
||||
HDKey.prototype.sign = function (hash) {
|
||||
return secp256k1Shim.sign(hash, this.privateKey).signature
|
||||
};
|
||||
|
||||
HDKey.prototype.verify = function (hash, signature) {
|
||||
return secp256k1Shim.verify(hash, signature, this.publicKey)
|
||||
};
|
||||
|
||||
HDKey.prototype.wipePrivateData = function () {
|
||||
if (this._privateKey) cryptoShim.randomBytes(this._privateKey.length).copy(this._privateKey);
|
||||
this._privateKey = null;
|
||||
return this
|
||||
};
|
||||
|
||||
HDKey.prototype.toJSON = function () {
|
||||
return {
|
||||
xpriv: this.privateExtendedKey,
|
||||
xpub: this.publicExtendedKey
|
||||
}
|
||||
};
|
||||
|
||||
HDKey.fromMasterSeed = function (seedBuffer, versions) {
|
||||
var I = cryptoShim.createHmac('sha512', MASTER_SECRET).update(seedBuffer).digest();
|
||||
var IL = I.slice(0, 32);
|
||||
var IR = I.slice(32);
|
||||
|
||||
var hdkey = new HDKey(versions);
|
||||
hdkey.chainCode = IR;
|
||||
hdkey.privateKey = IL;
|
||||
|
||||
return hdkey
|
||||
};
|
||||
|
||||
HDKey.fromExtendedKey = function (base58key, versions) {
|
||||
// => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
|
||||
versions = versions || BITCOIN_VERSIONS;
|
||||
var hdkey = new HDKey(versions);
|
||||
|
||||
var keyBuffer = bs58check.decode(base58key);
|
||||
|
||||
var version = keyBuffer.readUInt32BE(0);
|
||||
assert(version === versions.private || version === versions.public, 'Version mismatch: does not match private or public');
|
||||
|
||||
hdkey.depth = keyBuffer.readUInt8(4);
|
||||
hdkey.parentFingerprint = keyBuffer.readUInt32BE(5);
|
||||
hdkey.index = keyBuffer.readUInt32BE(9);
|
||||
hdkey.chainCode = keyBuffer.slice(13, 45);
|
||||
|
||||
var key = keyBuffer.slice(45);
|
||||
if (key.readUInt8(0) === 0) { // private
|
||||
assert(version === versions.private, 'Version mismatch: version does not match private');
|
||||
hdkey.privateKey = key.slice(1); // cut off first 0x0 byte
|
||||
} else {
|
||||
assert(version === versions.public, 'Version mismatch: version does not match public');
|
||||
hdkey.publicKey = key;
|
||||
}
|
||||
|
||||
return hdkey
|
||||
};
|
||||
|
||||
HDKey.fromJSON = function (obj) {
|
||||
return HDKey.fromExtendedKey(obj.xpriv)
|
||||
};
|
||||
|
||||
function serialize (hdkey, version, key) {
|
||||
// => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
|
||||
var buffer = Buffer.allocUnsafe(LEN);
|
||||
|
||||
buffer.writeUInt32BE(version, 0);
|
||||
buffer.writeUInt8(hdkey.depth, 4);
|
||||
|
||||
var fingerprint = hdkey.depth ? hdkey.parentFingerprint : 0x00000000;
|
||||
buffer.writeUInt32BE(fingerprint, 5);
|
||||
buffer.writeUInt32BE(hdkey.index, 9);
|
||||
|
||||
hdkey.chainCode.copy(buffer, 13);
|
||||
key.copy(buffer, 45);
|
||||
|
||||
return buffer
|
||||
}
|
||||
|
||||
function hash160 (buf) {
|
||||
var sha = cryptoShim.createHash('sha256').update(buf).digest();
|
||||
return cryptoShim.createHash('ripemd160').update(sha).digest()
|
||||
}
|
||||
|
||||
HDKey.HARDENED_OFFSET = HARDENED_OFFSET;
|
||||
var hdkey = HDKey;
|
||||
|
||||
module.exports = hdkey;
|
||||
Generated
Vendored
+206
@@ -0,0 +1,206 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
|
||||
|
||||
var createHash = _interopDefault(require('create-hash'));
|
||||
var pbkdf2 = _interopDefault(require('pbkdf2'));
|
||||
var randombytes = _interopDefault(require('randombytes'));
|
||||
|
||||
function unwrapExports (x) {
|
||||
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
||||
}
|
||||
|
||||
function createCommonjsModule(fn, module) {
|
||||
return module = { exports: {} }, fn(module, module.exports), module.exports;
|
||||
}
|
||||
|
||||
|
||||
|
||||
var emptyModule = /*#__PURE__*/Object.freeze({
|
||||
__proto__: null
|
||||
});
|
||||
|
||||
var src = createCommonjsModule(function (module, exports) {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
|
||||
|
||||
|
||||
|
||||
let DEFAULT_WORDLIST = emptyModule._default;
|
||||
const INVALID_MNEMONIC = 'Invalid mnemonic';
|
||||
const INVALID_ENTROPY = 'Invalid entropy';
|
||||
const INVALID_CHECKSUM = 'Invalid mnemonic checksum';
|
||||
const WORDLIST_REQUIRED = 'A wordlist is required but a default could not be found.\n' +
|
||||
'Please explicitly pass a 2048 word array explicitly.';
|
||||
function lpad(str, padString, length) {
|
||||
while (str.length < length)
|
||||
str = padString + str;
|
||||
return str;
|
||||
}
|
||||
function binaryToByte(bin) {
|
||||
return parseInt(bin, 2);
|
||||
}
|
||||
function bytesToBinary(bytes) {
|
||||
return bytes.map(x => lpad(x.toString(2), '0', 8)).join('');
|
||||
}
|
||||
function deriveChecksumBits(entropyBuffer) {
|
||||
const ENT = entropyBuffer.length * 8;
|
||||
const CS = ENT / 32;
|
||||
const hash = createHash('sha256')
|
||||
.update(entropyBuffer)
|
||||
.digest();
|
||||
return bytesToBinary([...hash]).slice(0, CS);
|
||||
}
|
||||
function salt(password) {
|
||||
return 'mnemonic' + (password || '');
|
||||
}
|
||||
function mnemonicToSeedSync(mnemonic, password) {
|
||||
const mnemonicBuffer = Buffer.from((mnemonic || '').normalize('NFKD'), 'utf8');
|
||||
const saltBuffer = Buffer.from(salt((password || '').normalize('NFKD')), 'utf8');
|
||||
return pbkdf2.pbkdf2Sync(mnemonicBuffer, saltBuffer, 2048, 64, 'sha512');
|
||||
}
|
||||
exports.mnemonicToSeedSync = mnemonicToSeedSync;
|
||||
function mnemonicToSeed(mnemonic, password) {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const mnemonicBuffer = Buffer.from((mnemonic || '').normalize('NFKD'), 'utf8');
|
||||
const saltBuffer = Buffer.from(salt((password || '').normalize('NFKD')), 'utf8');
|
||||
pbkdf2.pbkdf2(mnemonicBuffer, saltBuffer, 2048, 64, 'sha512', (err, data) => {
|
||||
if (err)
|
||||
return reject(err);
|
||||
else
|
||||
return resolve(data);
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
return reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.mnemonicToSeed = mnemonicToSeed;
|
||||
function mnemonicToEntropy(mnemonic, wordlist) {
|
||||
wordlist = wordlist || DEFAULT_WORDLIST;
|
||||
if (!wordlist) {
|
||||
throw new Error(WORDLIST_REQUIRED);
|
||||
}
|
||||
const words = (mnemonic || '').normalize('NFKD').split(' ');
|
||||
if (words.length % 3 !== 0)
|
||||
throw new Error(INVALID_MNEMONIC);
|
||||
// convert word indices to 11 bit binary strings
|
||||
const bits = words
|
||||
.map(word => {
|
||||
const index = wordlist.indexOf(word);
|
||||
if (index === -1)
|
||||
throw new Error(INVALID_MNEMONIC);
|
||||
return lpad(index.toString(2), '0', 11);
|
||||
})
|
||||
.join('');
|
||||
// split the binary string into ENT/CS
|
||||
const dividerIndex = Math.floor(bits.length / 33) * 32;
|
||||
const entropyBits = bits.slice(0, dividerIndex);
|
||||
const checksumBits = bits.slice(dividerIndex);
|
||||
// calculate the checksum and compare
|
||||
const entropyBytes = entropyBits.match(/(.{1,8})/g).map(binaryToByte);
|
||||
if (entropyBytes.length < 16)
|
||||
throw new Error(INVALID_ENTROPY);
|
||||
if (entropyBytes.length > 32)
|
||||
throw new Error(INVALID_ENTROPY);
|
||||
if (entropyBytes.length % 4 !== 0)
|
||||
throw new Error(INVALID_ENTROPY);
|
||||
const entropy = Buffer.from(entropyBytes);
|
||||
const newChecksum = deriveChecksumBits(entropy);
|
||||
if (newChecksum !== checksumBits)
|
||||
throw new Error(INVALID_CHECKSUM);
|
||||
return entropy.toString('hex');
|
||||
}
|
||||
exports.mnemonicToEntropy = mnemonicToEntropy;
|
||||
function entropyToMnemonic(entropy, wordlist) {
|
||||
if (!Buffer.isBuffer(entropy))
|
||||
entropy = Buffer.from(entropy, 'hex');
|
||||
wordlist = wordlist || DEFAULT_WORDLIST;
|
||||
if (!wordlist) {
|
||||
throw new Error(WORDLIST_REQUIRED);
|
||||
}
|
||||
// 128 <= ENT <= 256
|
||||
if (entropy.length < 16)
|
||||
throw new TypeError(INVALID_ENTROPY);
|
||||
if (entropy.length > 32)
|
||||
throw new TypeError(INVALID_ENTROPY);
|
||||
if (entropy.length % 4 !== 0)
|
||||
throw new TypeError(INVALID_ENTROPY);
|
||||
const entropyBits = bytesToBinary([...entropy]);
|
||||
const checksumBits = deriveChecksumBits(entropy);
|
||||
const bits = entropyBits + checksumBits;
|
||||
const chunks = bits.match(/(.{1,11})/g);
|
||||
const words = chunks.map(binary => {
|
||||
const index = binaryToByte(binary);
|
||||
return wordlist[index];
|
||||
});
|
||||
return wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093' // Japanese wordlist
|
||||
? words.join('\u3000')
|
||||
: words.join(' ');
|
||||
}
|
||||
exports.entropyToMnemonic = entropyToMnemonic;
|
||||
function generateMnemonic(strength, rng, wordlist) {
|
||||
strength = strength || 128;
|
||||
if (strength % 32 !== 0)
|
||||
throw new TypeError(INVALID_ENTROPY);
|
||||
rng = rng || randombytes;
|
||||
return entropyToMnemonic(rng(strength / 8), wordlist);
|
||||
}
|
||||
exports.generateMnemonic = generateMnemonic;
|
||||
function validateMnemonic(mnemonic, wordlist) {
|
||||
try {
|
||||
mnemonicToEntropy(mnemonic, wordlist);
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
exports.validateMnemonic = validateMnemonic;
|
||||
function setDefaultWordlist(language) {
|
||||
const result = emptyModule.wordlists[language];
|
||||
if (result)
|
||||
DEFAULT_WORDLIST = result;
|
||||
else
|
||||
throw new Error('Could not find wordlist for language "' + language + '"');
|
||||
}
|
||||
exports.setDefaultWordlist = setDefaultWordlist;
|
||||
function getDefaultWordlist() {
|
||||
if (!DEFAULT_WORDLIST)
|
||||
throw new Error('No Default Wordlist set');
|
||||
return Object.keys(emptyModule.wordlists).filter(lang => {
|
||||
if (lang === 'JA' || lang === 'EN')
|
||||
return false;
|
||||
return emptyModule.wordlists[lang].every((word, index) => word === DEFAULT_WORDLIST[index]);
|
||||
})[0];
|
||||
}
|
||||
exports.getDefaultWordlist = getDefaultWordlist;
|
||||
var _wordlists_2 = emptyModule;
|
||||
exports.wordlists = _wordlists_2.wordlists;
|
||||
});
|
||||
|
||||
var index = unwrapExports(src);
|
||||
var src_1 = src.mnemonicToSeedSync;
|
||||
var src_2 = src.mnemonicToSeed;
|
||||
var src_3 = src.mnemonicToEntropy;
|
||||
var src_4 = src.entropyToMnemonic;
|
||||
var src_5 = src.generateMnemonic;
|
||||
var src_6 = src.validateMnemonic;
|
||||
var src_7 = src.setDefaultWordlist;
|
||||
var src_8 = src.getDefaultWordlist;
|
||||
var src_9 = src.wordlists;
|
||||
|
||||
exports.default = index;
|
||||
exports.entropyToMnemonic = src_4;
|
||||
exports.generateMnemonic = src_5;
|
||||
exports.getDefaultWordlist = src_8;
|
||||
exports.mnemonicToEntropy = src_3;
|
||||
exports.mnemonicToSeed = src_2;
|
||||
exports.mnemonicToSeedSync = src_1;
|
||||
exports.setDefaultWordlist = src_7;
|
||||
exports.validateMnemonic = src_6;
|
||||
exports.wordlists = src_9;
|
||||
Generated
Vendored
+255
@@ -0,0 +1,255 @@
|
||||
'use strict';
|
||||
|
||||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
|
||||
|
||||
var assert = _interopDefault(require('assert'));
|
||||
var safeBuffer = _interopDefault(require('safe-buffer'));
|
||||
var bs58check = _interopDefault(require('bs58check'));
|
||||
|
||||
var cryptoShim = require("../shims/hdkey-crypto");
|
||||
|
||||
var secp256k1Shim = require("../shims/hdkey-secp256k1v3");
|
||||
|
||||
var Buffer = safeBuffer.Buffer;
|
||||
|
||||
|
||||
|
||||
|
||||
var MASTER_SECRET = Buffer.from('Bitcoin seed', 'utf8');
|
||||
var HARDENED_OFFSET = 0x80000000;
|
||||
var LEN = 78;
|
||||
|
||||
// Bitcoin hardcoded by default, can use package `coininfo` for others
|
||||
var BITCOIN_VERSIONS = {private: 0x0488ADE4, public: 0x0488B21E};
|
||||
|
||||
function HDKey (versions) {
|
||||
this.versions = versions || BITCOIN_VERSIONS;
|
||||
this.depth = 0;
|
||||
this.index = 0;
|
||||
this._privateKey = null;
|
||||
this._publicKey = null;
|
||||
this.chainCode = null;
|
||||
this._fingerprint = 0;
|
||||
this.parentFingerprint = 0;
|
||||
}
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'fingerprint', { get: function () { return this._fingerprint } });
|
||||
Object.defineProperty(HDKey.prototype, 'identifier', { get: function () { return this._identifier } });
|
||||
Object.defineProperty(HDKey.prototype, 'pubKeyHash', { get: function () { return this.identifier } });
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'privateKey', {
|
||||
get: function () {
|
||||
return this._privateKey
|
||||
},
|
||||
set: function (value) {
|
||||
assert.equal(value.length, 32, 'Private key must be 32 bytes.');
|
||||
assert(secp256k1Shim.privateKeyVerify(value) === true, 'Invalid private key');
|
||||
|
||||
this._privateKey = value;
|
||||
this._publicKey = secp256k1Shim.publicKeyCreate(value, true);
|
||||
this._identifier = hash160(this.publicKey);
|
||||
this._fingerprint = this._identifier.slice(0, 4).readUInt32BE(0);
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'publicKey', {
|
||||
get: function () {
|
||||
return this._publicKey
|
||||
},
|
||||
set: function (value) {
|
||||
assert(value.length === 33 || value.length === 65, 'Public key must be 33 or 65 bytes.');
|
||||
assert(secp256k1Shim.publicKeyVerify(value) === true, 'Invalid public key');
|
||||
|
||||
this._publicKey = secp256k1Shim.publicKeyConvert(value, true); // force compressed point
|
||||
this._identifier = hash160(this.publicKey);
|
||||
this._fingerprint = this._identifier.slice(0, 4).readUInt32BE(0);
|
||||
this._privateKey = null;
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'privateExtendedKey', {
|
||||
get: function () {
|
||||
if (this._privateKey) return bs58check.encode(serialize(this, this.versions.private, Buffer.concat([Buffer.alloc(1, 0), this.privateKey])))
|
||||
else return null
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'publicExtendedKey', {
|
||||
get: function () {
|
||||
return bs58check.encode(serialize(this, this.versions.public, this.publicKey))
|
||||
}
|
||||
});
|
||||
|
||||
HDKey.prototype.derive = function (path) {
|
||||
if (path === 'm' || path === 'M' || path === "m'" || path === "M'") {
|
||||
return this
|
||||
}
|
||||
|
||||
var entries = path.split('/');
|
||||
var hdkey = this;
|
||||
entries.forEach(function (c, i) {
|
||||
if (i === 0) {
|
||||
assert(/^[mM]{1}/.test(c), 'Path must start with "m" or "M"');
|
||||
return
|
||||
}
|
||||
|
||||
var hardened = (c.length > 1) && (c[c.length - 1] === "'");
|
||||
var childIndex = parseInt(c, 10); // & (HARDENED_OFFSET - 1)
|
||||
assert(childIndex < HARDENED_OFFSET, 'Invalid index');
|
||||
if (hardened) childIndex += HARDENED_OFFSET;
|
||||
|
||||
hdkey = hdkey.deriveChild(childIndex);
|
||||
});
|
||||
|
||||
return hdkey
|
||||
};
|
||||
|
||||
HDKey.prototype.deriveChild = function (index) {
|
||||
var isHardened = index >= HARDENED_OFFSET;
|
||||
var indexBuffer = Buffer.allocUnsafe(4);
|
||||
indexBuffer.writeUInt32BE(index, 0);
|
||||
|
||||
var data;
|
||||
|
||||
if (isHardened) { // Hardened child
|
||||
assert(this.privateKey, 'Could not derive hardened child key');
|
||||
|
||||
var pk = this.privateKey;
|
||||
var zb = Buffer.alloc(1, 0);
|
||||
pk = Buffer.concat([zb, pk]);
|
||||
|
||||
// data = 0x00 || ser256(kpar) || ser32(index)
|
||||
data = Buffer.concat([pk, indexBuffer]);
|
||||
} else { // Normal child
|
||||
// data = serP(point(kpar)) || ser32(index)
|
||||
// = serP(Kpar) || ser32(index)
|
||||
data = Buffer.concat([this.publicKey, indexBuffer]);
|
||||
}
|
||||
|
||||
var I = cryptoShim.createHmac('sha512', this.chainCode).update(data).digest();
|
||||
var IL = I.slice(0, 32);
|
||||
var IR = I.slice(32);
|
||||
|
||||
var hd = new HDKey(this.versions);
|
||||
|
||||
// Private parent key -> private child key
|
||||
if (this.privateKey) {
|
||||
// ki = parse256(IL) + kpar (mod n)
|
||||
try {
|
||||
hd.privateKey = secp256k1Shim.privateKeyTweakAdd(this.privateKey, IL);
|
||||
// throw if IL >= n || (privateKey + IL) === 0
|
||||
} catch (err) {
|
||||
// In case parse256(IL) >= n or ki == 0, one should proceed with the next value for i
|
||||
return this.deriveChild(index + 1)
|
||||
}
|
||||
// Public parent key -> public child key
|
||||
} else {
|
||||
// Ki = point(parse256(IL)) + Kpar
|
||||
// = G*IL + Kpar
|
||||
try {
|
||||
hd.publicKey = secp256k1Shim.publicKeyTweakAdd(this.publicKey, IL, true);
|
||||
// throw if IL >= n || (g**IL + publicKey) is infinity
|
||||
} catch (err) {
|
||||
// In case parse256(IL) >= n or Ki is the point at infinity, one should proceed with the next value for i
|
||||
return this.deriveChild(index + 1)
|
||||
}
|
||||
}
|
||||
|
||||
hd.chainCode = IR;
|
||||
hd.depth = this.depth + 1;
|
||||
hd.parentFingerprint = this.fingerprint;// .readUInt32BE(0)
|
||||
hd.index = index;
|
||||
|
||||
return hd
|
||||
};
|
||||
|
||||
HDKey.prototype.sign = function (hash) {
|
||||
return secp256k1Shim.sign(hash, this.privateKey).signature
|
||||
};
|
||||
|
||||
HDKey.prototype.verify = function (hash, signature) {
|
||||
return secp256k1Shim.verify(hash, signature, this.publicKey)
|
||||
};
|
||||
|
||||
HDKey.prototype.wipePrivateData = function () {
|
||||
if (this._privateKey) cryptoShim.randomBytes(this._privateKey.length).copy(this._privateKey);
|
||||
this._privateKey = null;
|
||||
return this
|
||||
};
|
||||
|
||||
HDKey.prototype.toJSON = function () {
|
||||
return {
|
||||
xpriv: this.privateExtendedKey,
|
||||
xpub: this.publicExtendedKey
|
||||
}
|
||||
};
|
||||
|
||||
HDKey.fromMasterSeed = function (seedBuffer, versions) {
|
||||
var I = cryptoShim.createHmac('sha512', MASTER_SECRET).update(seedBuffer).digest();
|
||||
var IL = I.slice(0, 32);
|
||||
var IR = I.slice(32);
|
||||
|
||||
var hdkey = new HDKey(versions);
|
||||
hdkey.chainCode = IR;
|
||||
hdkey.privateKey = IL;
|
||||
|
||||
return hdkey
|
||||
};
|
||||
|
||||
HDKey.fromExtendedKey = function (base58key, versions) {
|
||||
// => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
|
||||
versions = versions || BITCOIN_VERSIONS;
|
||||
var hdkey = new HDKey(versions);
|
||||
|
||||
var keyBuffer = bs58check.decode(base58key);
|
||||
|
||||
var version = keyBuffer.readUInt32BE(0);
|
||||
assert(version === versions.private || version === versions.public, 'Version mismatch: does not match private or public');
|
||||
|
||||
hdkey.depth = keyBuffer.readUInt8(4);
|
||||
hdkey.parentFingerprint = keyBuffer.readUInt32BE(5);
|
||||
hdkey.index = keyBuffer.readUInt32BE(9);
|
||||
hdkey.chainCode = keyBuffer.slice(13, 45);
|
||||
|
||||
var key = keyBuffer.slice(45);
|
||||
if (key.readUInt8(0) === 0) { // private
|
||||
assert(version === versions.private, 'Version mismatch: version does not match private');
|
||||
hdkey.privateKey = key.slice(1); // cut off first 0x0 byte
|
||||
} else {
|
||||
assert(version === versions.public, 'Version mismatch: version does not match public');
|
||||
hdkey.publicKey = key;
|
||||
}
|
||||
|
||||
return hdkey
|
||||
};
|
||||
|
||||
HDKey.fromJSON = function (obj) {
|
||||
return HDKey.fromExtendedKey(obj.xpriv)
|
||||
};
|
||||
|
||||
function serialize (hdkey, version, key) {
|
||||
// => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
|
||||
var buffer = Buffer.allocUnsafe(LEN);
|
||||
|
||||
buffer.writeUInt32BE(version, 0);
|
||||
buffer.writeUInt8(hdkey.depth, 4);
|
||||
|
||||
var fingerprint = hdkey.depth ? hdkey.parentFingerprint : 0x00000000;
|
||||
buffer.writeUInt32BE(fingerprint, 5);
|
||||
buffer.writeUInt32BE(hdkey.index, 9);
|
||||
|
||||
hdkey.chainCode.copy(buffer, 13);
|
||||
key.copy(buffer, 45);
|
||||
|
||||
return buffer
|
||||
}
|
||||
|
||||
function hash160 (buf) {
|
||||
var sha = cryptoShim.createHash('sha256').update(buf).digest();
|
||||
return cryptoShim.createHash('ripemd160').update(sha).digest()
|
||||
}
|
||||
|
||||
HDKey.HARDENED_OFFSET = HARDENED_OFFSET;
|
||||
var hdkey = HDKey;
|
||||
|
||||
module.exports = hdkey;
|
||||
Generated
Vendored
+206
@@ -0,0 +1,206 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
|
||||
|
||||
var createHash = _interopDefault(require('create-hash'));
|
||||
var pbkdf2 = _interopDefault(require('pbkdf2'));
|
||||
var randombytes = _interopDefault(require('randombytes'));
|
||||
|
||||
function unwrapExports (x) {
|
||||
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
||||
}
|
||||
|
||||
function createCommonjsModule(fn, module) {
|
||||
return module = { exports: {} }, fn(module, module.exports), module.exports;
|
||||
}
|
||||
|
||||
|
||||
|
||||
var emptyModule = /*#__PURE__*/Object.freeze({
|
||||
__proto__: null
|
||||
});
|
||||
|
||||
var src = createCommonjsModule(function (module, exports) {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
|
||||
|
||||
|
||||
|
||||
let DEFAULT_WORDLIST = emptyModule._default;
|
||||
const INVALID_MNEMONIC = 'Invalid mnemonic';
|
||||
const INVALID_ENTROPY = 'Invalid entropy';
|
||||
const INVALID_CHECKSUM = 'Invalid mnemonic checksum';
|
||||
const WORDLIST_REQUIRED = 'A wordlist is required but a default could not be found.\n' +
|
||||
'Please explicitly pass a 2048 word array explicitly.';
|
||||
function lpad(str, padString, length) {
|
||||
while (str.length < length)
|
||||
str = padString + str;
|
||||
return str;
|
||||
}
|
||||
function binaryToByte(bin) {
|
||||
return parseInt(bin, 2);
|
||||
}
|
||||
function bytesToBinary(bytes) {
|
||||
return bytes.map(x => lpad(x.toString(2), '0', 8)).join('');
|
||||
}
|
||||
function deriveChecksumBits(entropyBuffer) {
|
||||
const ENT = entropyBuffer.length * 8;
|
||||
const CS = ENT / 32;
|
||||
const hash = createHash('sha256')
|
||||
.update(entropyBuffer)
|
||||
.digest();
|
||||
return bytesToBinary([...hash]).slice(0, CS);
|
||||
}
|
||||
function salt(password) {
|
||||
return 'mnemonic' + (password || '');
|
||||
}
|
||||
function mnemonicToSeedSync(mnemonic, password) {
|
||||
const mnemonicBuffer = Buffer.from((mnemonic || '').normalize('NFKD'), 'utf8');
|
||||
const saltBuffer = Buffer.from(salt((password || '').normalize('NFKD')), 'utf8');
|
||||
return pbkdf2.pbkdf2Sync(mnemonicBuffer, saltBuffer, 2048, 64, 'sha512');
|
||||
}
|
||||
exports.mnemonicToSeedSync = mnemonicToSeedSync;
|
||||
function mnemonicToSeed(mnemonic, password) {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const mnemonicBuffer = Buffer.from((mnemonic || '').normalize('NFKD'), 'utf8');
|
||||
const saltBuffer = Buffer.from(salt((password || '').normalize('NFKD')), 'utf8');
|
||||
pbkdf2.pbkdf2(mnemonicBuffer, saltBuffer, 2048, 64, 'sha512', (err, data) => {
|
||||
if (err)
|
||||
return reject(err);
|
||||
else
|
||||
return resolve(data);
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
return reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.mnemonicToSeed = mnemonicToSeed;
|
||||
function mnemonicToEntropy(mnemonic, wordlist) {
|
||||
wordlist = wordlist || DEFAULT_WORDLIST;
|
||||
if (!wordlist) {
|
||||
throw new Error(WORDLIST_REQUIRED);
|
||||
}
|
||||
const words = (mnemonic || '').normalize('NFKD').split(' ');
|
||||
if (words.length % 3 !== 0)
|
||||
throw new Error(INVALID_MNEMONIC);
|
||||
// convert word indices to 11 bit binary strings
|
||||
const bits = words
|
||||
.map(word => {
|
||||
const index = wordlist.indexOf(word);
|
||||
if (index === -1)
|
||||
throw new Error(INVALID_MNEMONIC);
|
||||
return lpad(index.toString(2), '0', 11);
|
||||
})
|
||||
.join('');
|
||||
// split the binary string into ENT/CS
|
||||
const dividerIndex = Math.floor(bits.length / 33) * 32;
|
||||
const entropyBits = bits.slice(0, dividerIndex);
|
||||
const checksumBits = bits.slice(dividerIndex);
|
||||
// calculate the checksum and compare
|
||||
const entropyBytes = entropyBits.match(/(.{1,8})/g).map(binaryToByte);
|
||||
if (entropyBytes.length < 16)
|
||||
throw new Error(INVALID_ENTROPY);
|
||||
if (entropyBytes.length > 32)
|
||||
throw new Error(INVALID_ENTROPY);
|
||||
if (entropyBytes.length % 4 !== 0)
|
||||
throw new Error(INVALID_ENTROPY);
|
||||
const entropy = Buffer.from(entropyBytes);
|
||||
const newChecksum = deriveChecksumBits(entropy);
|
||||
if (newChecksum !== checksumBits)
|
||||
throw new Error(INVALID_CHECKSUM);
|
||||
return entropy.toString('hex');
|
||||
}
|
||||
exports.mnemonicToEntropy = mnemonicToEntropy;
|
||||
function entropyToMnemonic(entropy, wordlist) {
|
||||
if (!Buffer.isBuffer(entropy))
|
||||
entropy = Buffer.from(entropy, 'hex');
|
||||
wordlist = wordlist || DEFAULT_WORDLIST;
|
||||
if (!wordlist) {
|
||||
throw new Error(WORDLIST_REQUIRED);
|
||||
}
|
||||
// 128 <= ENT <= 256
|
||||
if (entropy.length < 16)
|
||||
throw new TypeError(INVALID_ENTROPY);
|
||||
if (entropy.length > 32)
|
||||
throw new TypeError(INVALID_ENTROPY);
|
||||
if (entropy.length % 4 !== 0)
|
||||
throw new TypeError(INVALID_ENTROPY);
|
||||
const entropyBits = bytesToBinary([...entropy]);
|
||||
const checksumBits = deriveChecksumBits(entropy);
|
||||
const bits = entropyBits + checksumBits;
|
||||
const chunks = bits.match(/(.{1,11})/g);
|
||||
const words = chunks.map(binary => {
|
||||
const index = binaryToByte(binary);
|
||||
return wordlist[index];
|
||||
});
|
||||
return wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093' // Japanese wordlist
|
||||
? words.join('\u3000')
|
||||
: words.join(' ');
|
||||
}
|
||||
exports.entropyToMnemonic = entropyToMnemonic;
|
||||
function generateMnemonic(strength, rng, wordlist) {
|
||||
strength = strength || 128;
|
||||
if (strength % 32 !== 0)
|
||||
throw new TypeError(INVALID_ENTROPY);
|
||||
rng = rng || randombytes;
|
||||
return entropyToMnemonic(rng(strength / 8), wordlist);
|
||||
}
|
||||
exports.generateMnemonic = generateMnemonic;
|
||||
function validateMnemonic(mnemonic, wordlist) {
|
||||
try {
|
||||
mnemonicToEntropy(mnemonic, wordlist);
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
exports.validateMnemonic = validateMnemonic;
|
||||
function setDefaultWordlist(language) {
|
||||
const result = emptyModule.wordlists[language];
|
||||
if (result)
|
||||
DEFAULT_WORDLIST = result;
|
||||
else
|
||||
throw new Error('Could not find wordlist for language "' + language + '"');
|
||||
}
|
||||
exports.setDefaultWordlist = setDefaultWordlist;
|
||||
function getDefaultWordlist() {
|
||||
if (!DEFAULT_WORDLIST)
|
||||
throw new Error('No Default Wordlist set');
|
||||
return Object.keys(emptyModule.wordlists).filter(lang => {
|
||||
if (lang === 'JA' || lang === 'EN')
|
||||
return false;
|
||||
return emptyModule.wordlists[lang].every((word, index) => word === DEFAULT_WORDLIST[index]);
|
||||
})[0];
|
||||
}
|
||||
exports.getDefaultWordlist = getDefaultWordlist;
|
||||
var _wordlists_2 = emptyModule;
|
||||
exports.wordlists = _wordlists_2.wordlists;
|
||||
});
|
||||
|
||||
var index = unwrapExports(src);
|
||||
var src_1 = src.mnemonicToSeedSync;
|
||||
var src_2 = src.mnemonicToSeed;
|
||||
var src_3 = src.mnemonicToEntropy;
|
||||
var src_4 = src.entropyToMnemonic;
|
||||
var src_5 = src.generateMnemonic;
|
||||
var src_6 = src.validateMnemonic;
|
||||
var src_7 = src.setDefaultWordlist;
|
||||
var src_8 = src.getDefaultWordlist;
|
||||
var src_9 = src.wordlists;
|
||||
|
||||
exports.default = index;
|
||||
exports.entropyToMnemonic = src_4;
|
||||
exports.generateMnemonic = src_5;
|
||||
exports.getDefaultWordlist = src_8;
|
||||
exports.mnemonicToEntropy = src_3;
|
||||
exports.mnemonicToSeed = src_2;
|
||||
exports.mnemonicToSeedSync = src_1;
|
||||
exports.setDefaultWordlist = src_7;
|
||||
exports.validateMnemonic = src_6;
|
||||
exports.wordlists = src_9;
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
'use strict';
|
||||
|
||||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
|
||||
|
||||
var assert = _interopDefault(require('assert'));
|
||||
var safeBuffer = _interopDefault(require('safe-buffer'));
|
||||
var bs58check = _interopDefault(require('bs58check'));
|
||||
|
||||
var cryptoShim = require("../shims/hdkey-crypto");
|
||||
|
||||
var secp256k1Shim = require("../shims/hdkey-secp256k1v3");
|
||||
|
||||
var Buffer = safeBuffer.Buffer;
|
||||
|
||||
|
||||
|
||||
|
||||
var MASTER_SECRET = Buffer.from('Bitcoin seed', 'utf8');
|
||||
var HARDENED_OFFSET = 0x80000000;
|
||||
var LEN = 78;
|
||||
|
||||
// Bitcoin hardcoded by default, can use package `coininfo` for others
|
||||
var BITCOIN_VERSIONS = {private: 0x0488ADE4, public: 0x0488B21E};
|
||||
|
||||
function HDKey (versions) {
|
||||
this.versions = versions || BITCOIN_VERSIONS;
|
||||
this.depth = 0;
|
||||
this.index = 0;
|
||||
this._privateKey = null;
|
||||
this._publicKey = null;
|
||||
this.chainCode = null;
|
||||
this._fingerprint = 0;
|
||||
this.parentFingerprint = 0;
|
||||
}
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'fingerprint', { get: function () { return this._fingerprint } });
|
||||
Object.defineProperty(HDKey.prototype, 'identifier', { get: function () { return this._identifier } });
|
||||
Object.defineProperty(HDKey.prototype, 'pubKeyHash', { get: function () { return this.identifier } });
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'privateKey', {
|
||||
get: function () {
|
||||
return this._privateKey
|
||||
},
|
||||
set: function (value) {
|
||||
assert.equal(value.length, 32, 'Private key must be 32 bytes.');
|
||||
assert(secp256k1Shim.privateKeyVerify(value) === true, 'Invalid private key');
|
||||
|
||||
this._privateKey = value;
|
||||
this._publicKey = secp256k1Shim.publicKeyCreate(value, true);
|
||||
this._identifier = hash160(this.publicKey);
|
||||
this._fingerprint = this._identifier.slice(0, 4).readUInt32BE(0);
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'publicKey', {
|
||||
get: function () {
|
||||
return this._publicKey
|
||||
},
|
||||
set: function (value) {
|
||||
assert(value.length === 33 || value.length === 65, 'Public key must be 33 or 65 bytes.');
|
||||
assert(secp256k1Shim.publicKeyVerify(value) === true, 'Invalid public key');
|
||||
|
||||
this._publicKey = secp256k1Shim.publicKeyConvert(value, true); // force compressed point
|
||||
this._identifier = hash160(this.publicKey);
|
||||
this._fingerprint = this._identifier.slice(0, 4).readUInt32BE(0);
|
||||
this._privateKey = null;
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'privateExtendedKey', {
|
||||
get: function () {
|
||||
if (this._privateKey) return bs58check.encode(serialize(this, this.versions.private, Buffer.concat([Buffer.alloc(1, 0), this.privateKey])))
|
||||
else return null
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(HDKey.prototype, 'publicExtendedKey', {
|
||||
get: function () {
|
||||
return bs58check.encode(serialize(this, this.versions.public, this.publicKey))
|
||||
}
|
||||
});
|
||||
|
||||
HDKey.prototype.derive = function (path) {
|
||||
if (path === 'm' || path === 'M' || path === "m'" || path === "M'") {
|
||||
return this
|
||||
}
|
||||
|
||||
var entries = path.split('/');
|
||||
var hdkey = this;
|
||||
entries.forEach(function (c, i) {
|
||||
if (i === 0) {
|
||||
assert(/^[mM]{1}/.test(c), 'Path must start with "m" or "M"');
|
||||
return
|
||||
}
|
||||
|
||||
var hardened = (c.length > 1) && (c[c.length - 1] === "'");
|
||||
var childIndex = parseInt(c, 10); // & (HARDENED_OFFSET - 1)
|
||||
assert(childIndex < HARDENED_OFFSET, 'Invalid index');
|
||||
if (hardened) childIndex += HARDENED_OFFSET;
|
||||
|
||||
hdkey = hdkey.deriveChild(childIndex);
|
||||
});
|
||||
|
||||
return hdkey
|
||||
};
|
||||
|
||||
HDKey.prototype.deriveChild = function (index) {
|
||||
var isHardened = index >= HARDENED_OFFSET;
|
||||
var indexBuffer = Buffer.allocUnsafe(4);
|
||||
indexBuffer.writeUInt32BE(index, 0);
|
||||
|
||||
var data;
|
||||
|
||||
if (isHardened) { // Hardened child
|
||||
assert(this.privateKey, 'Could not derive hardened child key');
|
||||
|
||||
var pk = this.privateKey;
|
||||
var zb = Buffer.alloc(1, 0);
|
||||
pk = Buffer.concat([zb, pk]);
|
||||
|
||||
// data = 0x00 || ser256(kpar) || ser32(index)
|
||||
data = Buffer.concat([pk, indexBuffer]);
|
||||
} else { // Normal child
|
||||
// data = serP(point(kpar)) || ser32(index)
|
||||
// = serP(Kpar) || ser32(index)
|
||||
data = Buffer.concat([this.publicKey, indexBuffer]);
|
||||
}
|
||||
|
||||
var I = cryptoShim.createHmac('sha512', this.chainCode).update(data).digest();
|
||||
var IL = I.slice(0, 32);
|
||||
var IR = I.slice(32);
|
||||
|
||||
var hd = new HDKey(this.versions);
|
||||
|
||||
// Private parent key -> private child key
|
||||
if (this.privateKey) {
|
||||
// ki = parse256(IL) + kpar (mod n)
|
||||
try {
|
||||
hd.privateKey = secp256k1Shim.privateKeyTweakAdd(this.privateKey, IL);
|
||||
// throw if IL >= n || (privateKey + IL) === 0
|
||||
} catch (err) {
|
||||
// In case parse256(IL) >= n or ki == 0, one should proceed with the next value for i
|
||||
return this.deriveChild(index + 1)
|
||||
}
|
||||
// Public parent key -> public child key
|
||||
} else {
|
||||
// Ki = point(parse256(IL)) + Kpar
|
||||
// = G*IL + Kpar
|
||||
try {
|
||||
hd.publicKey = secp256k1Shim.publicKeyTweakAdd(this.publicKey, IL, true);
|
||||
// throw if IL >= n || (g**IL + publicKey) is infinity
|
||||
} catch (err) {
|
||||
// In case parse256(IL) >= n or Ki is the point at infinity, one should proceed with the next value for i
|
||||
return this.deriveChild(index + 1)
|
||||
}
|
||||
}
|
||||
|
||||
hd.chainCode = IR;
|
||||
hd.depth = this.depth + 1;
|
||||
hd.parentFingerprint = this.fingerprint;// .readUInt32BE(0)
|
||||
hd.index = index;
|
||||
|
||||
return hd
|
||||
};
|
||||
|
||||
HDKey.prototype.sign = function (hash) {
|
||||
return secp256k1Shim.sign(hash, this.privateKey).signature
|
||||
};
|
||||
|
||||
HDKey.prototype.verify = function (hash, signature) {
|
||||
return secp256k1Shim.verify(hash, signature, this.publicKey)
|
||||
};
|
||||
|
||||
HDKey.prototype.wipePrivateData = function () {
|
||||
if (this._privateKey) cryptoShim.randomBytes(this._privateKey.length).copy(this._privateKey);
|
||||
this._privateKey = null;
|
||||
return this
|
||||
};
|
||||
|
||||
HDKey.prototype.toJSON = function () {
|
||||
return {
|
||||
xpriv: this.privateExtendedKey,
|
||||
xpub: this.publicExtendedKey
|
||||
}
|
||||
};
|
||||
|
||||
HDKey.fromMasterSeed = function (seedBuffer, versions) {
|
||||
var I = cryptoShim.createHmac('sha512', MASTER_SECRET).update(seedBuffer).digest();
|
||||
var IL = I.slice(0, 32);
|
||||
var IR = I.slice(32);
|
||||
|
||||
var hdkey = new HDKey(versions);
|
||||
hdkey.chainCode = IR;
|
||||
hdkey.privateKey = IL;
|
||||
|
||||
return hdkey
|
||||
};
|
||||
|
||||
HDKey.fromExtendedKey = function (base58key, versions) {
|
||||
// => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
|
||||
versions = versions || BITCOIN_VERSIONS;
|
||||
var hdkey = new HDKey(versions);
|
||||
|
||||
var keyBuffer = bs58check.decode(base58key);
|
||||
|
||||
var version = keyBuffer.readUInt32BE(0);
|
||||
assert(version === versions.private || version === versions.public, 'Version mismatch: does not match private or public');
|
||||
|
||||
hdkey.depth = keyBuffer.readUInt8(4);
|
||||
hdkey.parentFingerprint = keyBuffer.readUInt32BE(5);
|
||||
hdkey.index = keyBuffer.readUInt32BE(9);
|
||||
hdkey.chainCode = keyBuffer.slice(13, 45);
|
||||
|
||||
var key = keyBuffer.slice(45);
|
||||
if (key.readUInt8(0) === 0) { // private
|
||||
assert(version === versions.private, 'Version mismatch: version does not match private');
|
||||
hdkey.privateKey = key.slice(1); // cut off first 0x0 byte
|
||||
} else {
|
||||
assert(version === versions.public, 'Version mismatch: version does not match public');
|
||||
hdkey.publicKey = key;
|
||||
}
|
||||
|
||||
return hdkey
|
||||
};
|
||||
|
||||
HDKey.fromJSON = function (obj) {
|
||||
return HDKey.fromExtendedKey(obj.xpriv)
|
||||
};
|
||||
|
||||
function serialize (hdkey, version, key) {
|
||||
// => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
|
||||
var buffer = Buffer.allocUnsafe(LEN);
|
||||
|
||||
buffer.writeUInt32BE(version, 0);
|
||||
buffer.writeUInt8(hdkey.depth, 4);
|
||||
|
||||
var fingerprint = hdkey.depth ? hdkey.parentFingerprint : 0x00000000;
|
||||
buffer.writeUInt32BE(fingerprint, 5);
|
||||
buffer.writeUInt32BE(hdkey.index, 9);
|
||||
|
||||
hdkey.chainCode.copy(buffer, 13);
|
||||
key.copy(buffer, 45);
|
||||
|
||||
return buffer
|
||||
}
|
||||
|
||||
function hash160 (buf) {
|
||||
var sha = cryptoShim.createHash('sha256').update(buf).digest();
|
||||
return cryptoShim.createHash('ripemd160').update(sha).digest()
|
||||
}
|
||||
|
||||
HDKey.HARDENED_OFFSET = HARDENED_OFFSET;
|
||||
var hdkey = HDKey;
|
||||
|
||||
module.exports = hdkey;
|
||||
Reference in new issue
Block a user