1 | 'use strict';
|
2 |
|
3 | var bech32 = require('bech32');
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | var decode = function(str) {
|
11 | if (typeof str !== 'string') {
|
12 | throw new Error('Input should be a string');
|
13 | }
|
14 |
|
15 | var decoded;
|
16 | let fromWords = bech32.bech32.fromWords;
|
17 | let encoding = encodings.BECH32;
|
18 | try {
|
19 | decoded = bech32.bech32.decode(str);
|
20 | } catch (e) {
|
21 | if (e.message.indexOf('Invalid checksum') > -1) {
|
22 | decoded = bech32.bech32m.decode(str);
|
23 | encoding = encodings.BECH32M;
|
24 | fromWords = bech32.bech32m.fromWords;
|
25 | } else {
|
26 | throw e;
|
27 | }
|
28 | }
|
29 |
|
30 | const version = decoded.words[0];
|
31 | if (version >= 1 && encoding !== encodings.BECH32M) {
|
32 | throw new Error('Version 1+ witness address must use Bech32m checksum');
|
33 | }
|
34 |
|
35 | return {
|
36 | prefix: decoded.prefix,
|
37 | data: Buffer.from(fromWords(decoded.words.slice(1))),
|
38 | version
|
39 | };
|
40 | };
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 | var encode = function(prefix, version, data, encoding) {
|
51 | if (typeof prefix !== 'string') {
|
52 | throw new Error('Prefix should be a string');
|
53 | }
|
54 | if (typeof version !== 'number') {
|
55 | throw new Error('version should be a number');
|
56 | }
|
57 |
|
58 | if (encoding && typeof encoding == 'string') {
|
59 | encoding = encodings[encoding.toUpperCase()] || -1;
|
60 | }
|
61 | if (encoding && !(encoding == encodings.BECH32 || encoding == encodings.BECH32M)) {
|
62 | throw new Error('Invalid encoding specified');
|
63 | }
|
64 |
|
65 | let b32Variety = encoding == encodings.BECH32M ? bech32.bech32m : bech32.bech32;
|
66 | let words = b32Variety.toWords(data);
|
67 |
|
68 | words.unshift(version);
|
69 | return b32Variety.encode(prefix, words);
|
70 | }
|
71 |
|
72 | const encodings = {
|
73 | BECH32: 1,
|
74 | BECH32M: 2
|
75 | }
|
76 |
|
77 | module.exports = { decode: decode, encode: encode, encodings };
|