UNPKG

936 BJavaScriptView Raw
1/**
2 * Base58 Encoding
3 * ===============
4 *
5 * Base58 (no check)
6 */
7'use strict'
8
9import bs58 from 'bs58'
10import { Struct } from './struct'
11
12class Base58 extends Struct {
13 constructor (buf) {
14 super({ buf })
15 }
16
17 fromHex (hex) {
18 return this.fromBuffer(Buffer.from(hex, 'hex'))
19 }
20
21 toHex () {
22 return this.toBuffer().toString('hex')
23 }
24
25 static encode (buf) {
26 if (!Buffer.isBuffer(buf)) {
27 throw new Error('Input should be a buffer')
28 }
29 return bs58.encode(buf)
30 }
31
32 static decode (str) {
33 if (typeof str !== 'string') {
34 throw new Error('Input should be a string')
35 }
36 return Buffer.from(bs58.decode(str))
37 }
38
39 fromBuffer (buf) {
40 this.buf = buf
41 return this
42 }
43
44 fromString (str) {
45 const buf = Base58.decode(str)
46 this.buf = buf
47 return this
48 }
49
50 toBuffer () {
51 return this.buf
52 }
53
54 toString () {
55 return Base58.encode(this.buf)
56 }
57}
58
59export { Base58 }