forked from ferrumnet/bs58check
-
Notifications
You must be signed in to change notification settings - Fork 1
/
base.js
50 lines (40 loc) · 1.17 KB
/
base.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
'use strict'
var base58 = require('bs58')
var Buffer = require('safe-buffer').Buffer
module.exports = function (checksumFn) {
// Encode a buffer as a base58-check encoded string
function encode (payload) {
var checksum = checksumFn(payload)
return base58.encode(Buffer.concat([
payload,
checksum
], payload.length + 4))
}
function decodeRaw (buffer) {
var payload = buffer.slice(0, -4)
var checksum = buffer.slice(-4)
var newChecksum = checksumFn(payload)
if (checksum[0] ^ newChecksum[0] |
checksum[1] ^ newChecksum[1] |
checksum[2] ^ newChecksum[2] |
checksum[3] ^ newChecksum[3]) return
return payload
}
// Decode a base58-check encoded string to a buffer, no result if checksum is wrong
function decodeUnsafe (string) {
var buffer = base58.decodeUnsafe(string)
if (!buffer) return
return decodeRaw(buffer)
}
function decode (string) {
var buffer = base58.decode(string)
var payload = decodeRaw(buffer, checksumFn)
if (!payload) throw new Error('Invalid checksum')
return payload
}
return {
encode: encode,
decode: decode,
decodeUnsafe: decodeUnsafe
}
}