bitmessage-js/lib/wif.js

55 lines
1.4 KiB
JavaScript
Raw Normal View History

2014-12-29 19:59:18 +00:00
/**
2014-12-30 17:00:28 +00:00
* Implements WIF encoding/decoding.
* @see {@link https://en.bitcoin.it/wiki/Wallet_import_format}
2014-12-29 19:59:18 +00:00
* @module bitmessage/wif
*/
"use strict";
require("es6-promise").polyfill();
var assert = require("assert");
var bufferEqual = require("buffer-equal");
var bs58 = require("bs58");
var bmcrypto = require("./crypto");
// Compute the WIF checksum for the given data.
function getchecksum(data) {
return bmcrypto.sha256(data).then(bmcrypto.sha256).then(function(dhash) {
return dhash.slice(0, 4);
});
}
/**
* Decode WIF encoded private key.
2014-12-30 17:00:28 +00:00
* @param {string} wif - Encoded key
* @return {Promise.<Buffer>} Private key.
2014-12-29 19:59:18 +00:00
*/
2014-12-30 17:00:28 +00:00
exports.decode = function(wif) {
2014-12-29 19:59:18 +00:00
var bytes;
try {
2014-12-30 17:00:28 +00:00
bytes = bs58.decode(wif);
2014-12-29 19:59:18 +00:00
assert(bytes[0] === 0x80, "Bad WIF");
} catch(e) {
return Promise.reject(e);
}
var data = new Buffer(bytes.slice(0, -4));
var checksum = new Buffer(bytes.slice(-4));
return getchecksum(data).then(function(realchecksum) {
assert(bufferEqual(checksum, realchecksum), "Bad checkum");
return data.slice(1);
});
};
/**
* Convert private key to a WIF.
* @param {Buffer} privateKey - A private key to encode
2014-12-30 17:00:28 +00:00
* @return {Promise.<string>} Encoded private key.
2014-12-29 19:59:18 +00:00
*/
exports.encode = function(privateKey) {
var data = Buffer.concat([new Buffer([0x80]), privateKey]);
return getchecksum(data).then(function(checksum) {
var bytes = Buffer.concat([data, checksum]);
return bs58.encode(bytes);
});
};