bitcore/lib/encoding/base58.js

71 lines
1.5 KiB
JavaScript
Raw Normal View History

2014-11-20 07:23:46 -08:00
'use strict';
2014-11-26 12:55:34 -08:00
var _ = require('lodash');
var bs58 = require('bs58');
2014-11-26 12:55:34 -08:00
var buffer = require('buffer');
var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.split('');
2014-08-28 15:27:58 -07:00
var Base58 = function Base58(obj) {
2014-11-26 12:55:34 -08:00
/* jshint maxcomplexity: 8 */
if (!(this instanceof Base58)) {
2014-08-28 15:27:58 -07:00
return new Base58(obj);
2014-11-26 12:55:34 -08:00
}
2014-09-17 14:26:19 -07:00
if (Buffer.isBuffer(obj)) {
var buf = obj;
this.fromBuffer(buf);
} else if (typeof obj === 'string') {
var str = obj;
this.fromString(str);
} else if (obj) {
2014-08-28 15:27:58 -07:00
this.set(obj);
2014-09-17 14:26:19 -07:00
}
2014-08-28 15:27:58 -07:00
};
2014-11-26 12:55:34 -08:00
Base58.validCharacters = function validCharacters(chars) {
if (buffer.Buffer.isBuffer(chars)) {
chars = chars.toString();
}
return _.all(_.map(chars, function(char) { return _.contains(ALPHABET, char); }));
};
2014-08-28 15:27:58 -07:00
Base58.prototype.set = function(obj) {
this.buf = obj.buf || this.buf || undefined;
return this;
};
Base58.encode = function(buf) {
2014-11-26 12:55:34 -08:00
if (!buffer.Buffer.isBuffer(buf)) {
throw new Error('Input should be a buffer');
2014-11-26 12:55:34 -08:00
}
return bs58.encode(buf);
};
Base58.decode = function(str) {
2014-11-26 12:55:34 -08:00
if (typeof str !== 'string') {
throw new Error('Input should be a string');
2014-11-26 12:55:34 -08:00
}
return new Buffer(bs58.decode(str));
};
Base58.prototype.fromBuffer = function(buf) {
this.buf = buf;
return this;
};
Base58.prototype.fromString = function(str) {
var buf = Base58.decode(str);
this.buf = buf;
return this;
};
Base58.prototype.toBuffer = function() {
return this.buf;
};
Base58.prototype.toString = function() {
return Base58.encode(this.buf);
};
module.exports = Base58;