UNPKG

2.12 kBJavaScriptView Raw
1'use strict';
2
3var bech32 = require('bech32');
4
5/**
6 * Decode bech32/bech32m string
7 * @param {String} str String to decode
8 * @returns {Object} Decoded string info
9 */
10var 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 * Encode using BECH32 encoding
44 * @param {String} prefix bech32 prefix
45 * @param {Number} version
46 * @param {String|Buffer} data
47 * @param {String|Number} encoding (optional, default=bech32) Valid encodings are 'bech32', 'bech32m', 0, and 1.
48 * @returns {String} encoded string
49 */
50var 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 // convert string to number
58 if (encoding && typeof encoding == 'string') {
59 encoding = encodings[encoding.toUpperCase()] || -1; // fallback to -1 so it throws invalid encoding below
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
72const encodings = {
73 BECH32: 1,
74 BECH32M: 2
75}
76
77module.exports = { decode: decode, encode: encode, encodings };