1 | 'use strict';
|
2 |
|
3 | var _ = require('lodash');
|
4 | var bs58 = require('bs58');
|
5 | var buffer = require('buffer');
|
6 |
|
7 | var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.split('');
|
8 |
|
9 | var Base58 = function Base58(obj) {
|
10 |
|
11 | if (!(this instanceof Base58)) {
|
12 | return new Base58(obj);
|
13 | }
|
14 | if (Buffer.isBuffer(obj)) {
|
15 | var buf = obj;
|
16 | this.fromBuffer(buf);
|
17 | } else if (typeof obj === 'string') {
|
18 | var str = obj;
|
19 | this.fromString(str);
|
20 | } else if (obj) {
|
21 | this.set(obj);
|
22 | }
|
23 | };
|
24 |
|
25 | Base58.validCharacters = function validCharacters(chars) {
|
26 | if (buffer.Buffer.isBuffer(chars)) {
|
27 | chars = chars.toString();
|
28 | }
|
29 | return _.every(_.map(chars, function(char) { return _.includes(ALPHABET, char); }));
|
30 | };
|
31 |
|
32 | Base58.prototype.set = function(obj) {
|
33 | this.buf = obj.buf || this.buf || undefined;
|
34 | return this;
|
35 | };
|
36 |
|
37 | Base58.encode = function(buf) {
|
38 | if (!buffer.Buffer.isBuffer(buf)) {
|
39 | throw new Error('Input should be a buffer');
|
40 | }
|
41 | return bs58.encode(buf);
|
42 | };
|
43 |
|
44 | Base58.decode = function(str) {
|
45 | if (typeof str !== 'string') {
|
46 | throw new Error('Input should be a string');
|
47 | }
|
48 | return Buffer.from(bs58.decode(str));
|
49 | };
|
50 |
|
51 | Base58.prototype.fromBuffer = function(buf) {
|
52 | this.buf = buf;
|
53 | return this;
|
54 | };
|
55 |
|
56 | Base58.prototype.fromString = function(str) {
|
57 | var buf = Base58.decode(str);
|
58 | this.buf = buf;
|
59 | return this;
|
60 | };
|
61 |
|
62 | Base58.prototype.toBuffer = function() {
|
63 | return this.buf;
|
64 | };
|
65 |
|
66 | Base58.prototype.toString = function() {
|
67 | return Base58.encode(this.buf);
|
68 | };
|
69 |
|
70 | module.exports = Base58;
|