2014-12-29 20:59:18 +01:00
|
|
|
/**
|
2014-12-30 18:00:28 +01:00
|
|
|
* Implements WIF encoding/decoding.
|
|
|
|
* @see {@link https://en.bitcoin.it/wiki/Wallet_import_format}
|
2014-12-29 20:59:18 +01:00
|
|
|
* @module bitmessage/wif
|
|
|
|
*/
|
|
|
|
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
var bufferEqual = require("buffer-equal");
|
|
|
|
var bs58 = require("bs58");
|
2015-01-22 01:00:58 +01:00
|
|
|
var assert = require("./_util").assert;
|
2014-12-29 20:59:18 +01:00
|
|
|
var bmcrypto = require("./crypto");
|
|
|
|
|
|
|
|
// Compute the WIF checksum for the given data.
|
2015-01-08 03:00:19 +01:00
|
|
|
function getwifchecksum(data) {
|
2015-01-03 15:52:27 +01:00
|
|
|
return bmcrypto.sha256(bmcrypto.sha256(data)).slice(0, 4);
|
2014-12-29 20:59:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2015-02-11 20:56:14 +01:00
|
|
|
* Decode WIF-encoded private key (corresponded to a uncompressed public
|
|
|
|
* key).
|
2014-12-30 18:00:28 +01:00
|
|
|
* @param {string} wif - Encoded key
|
2015-01-03 15:52:27 +01:00
|
|
|
* @return {Buffer} Private key.
|
2014-12-29 20:59:18 +01:00
|
|
|
*/
|
2014-12-30 18:00:28 +01:00
|
|
|
exports.decode = function(wif) {
|
2015-01-03 15:52:27 +01:00
|
|
|
var bytes = bs58.decode(wif);
|
|
|
|
assert(bytes[0] === 0x80, "Bad WIF");
|
2023-01-03 05:17:21 +01:00
|
|
|
var data = Buffer.from(bytes.slice(0, -4));
|
|
|
|
var checksum = Buffer.from(bytes.slice(-4));
|
2015-01-08 03:00:19 +01:00
|
|
|
assert(bufferEqual(checksum, getwifchecksum(data)), "Bad checkum");
|
2015-01-03 15:52:27 +01:00
|
|
|
return data.slice(1);
|
2014-12-29 20:59:18 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
2015-02-11 20:56:14 +01:00
|
|
|
* Convert private key to a WIF (corresponded to a uncompressed public
|
|
|
|
* key).
|
2014-12-29 20:59:18 +01:00
|
|
|
* @param {Buffer} privateKey - A private key to encode
|
2015-02-11 20:56:14 +01:00
|
|
|
* @return {string} WIF-encoded private key.
|
2014-12-29 20:59:18 +01:00
|
|
|
*/
|
|
|
|
exports.encode = function(privateKey) {
|
2023-01-03 05:17:21 +01:00
|
|
|
var data = Buffer.concat([Buffer.from([0x80]), privateKey]);
|
2015-01-08 03:00:19 +01:00
|
|
|
var checksum = getwifchecksum(data);
|
2015-01-03 15:52:27 +01:00
|
|
|
var bytes = Buffer.concat([data, checksum]);
|
|
|
|
return bs58.encode(bytes);
|
2014-12-29 20:59:18 +01:00
|
|
|
};
|