forked from bitcoinjs/bolt11
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoding.js
52 lines (40 loc) · 1.21 KB
/
encoding.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
51
52
const bech32 = require('bech32')
const bs58check = require('bs58check')
const typeforce = require('typeforce')
const types = require('./types')
const Buffer = require('safe-buffer').Buffer
function fromBase58Check (address) {
const payload = bs58check.decode(address)
if (payload.length < 21) throw new TypeError(address + ' is too short')
if (payload.length > 21) throw new TypeError(address + ' is too long')
const version = payload.readUInt8(0)
const hash = payload.slice(1)
return { version: version, hash: hash }
}
function toBase58Check (hash, version) {
typeforce(types.tuple(types.Hash160bit, types.UInt8), arguments)
const payload = Buffer.allocUnsafe(21)
payload.writeUInt8(version, 0)
hash.copy(payload, 1)
return bs58check.encode(payload)
}
function fromBech32 (address) {
const result = bech32.decode(address)
const data = bech32.fromWords(result.words.slice(1))
return {
version: result.words[0],
prefix: result.prefix,
data: Buffer.from(data)
}
}
function toBech32 (data, version, prefix) {
const words = bech32.toWords(data)
words.unshift(version)
return bech32.encode(prefix, words)
}
module.exports = {
fromBase58Check,
toBase58Check,
fromBech32,
toBech32
}