(data: number[], inBits: number, outBits: number, pad: boolean)
| 46 | } |
| 47 | |
| 48 | function bech32Convert(data: number[], inBits: number, outBits: number, pad: boolean): number[] { |
| 49 | let value = 0, bits = 0 |
| 50 | const maxV = (1 << outBits) - 1 |
| 51 | const maxAcc = (1 << (inBits + outBits - 1)) - 1 |
| 52 | const maxInput = (1 << inBits) - 1 |
| 53 | const result: number[] = [] |
| 54 | for (const byte of data) { |
| 55 | if (!Number.isInteger(byte) || byte < 0 || byte > maxInput) { |
| 56 | throw new Error(`Invalid value for ${inBits}-bit input: ${byte}`) |
| 57 | } |
| 58 | value = ((value << inBits) | byte) & maxAcc |
| 59 | bits += inBits |
| 60 | while (bits >= outBits) { |
| 61 | bits -= outBits |
| 62 | result.push((value >> bits) & maxV) |
| 63 | } |
| 64 | } |
| 65 | if (pad) { |
| 66 | if (bits > 0) { result.push((value << (outBits - bits)) & maxV) } |
| 67 | } else if (bits >= inBits || ((value << (outBits - bits)) & maxV) !== 0) { |
| 68 | throw new Error('Invalid bech32 padding') |
| 69 | } |
| 70 | return result |
| 71 | } |
| 72 | |
| 73 | function bech32Decode(str: string): { prefix: string; words: number[] } { |
| 74 | const lower = str.toLowerCase() |
no outgoing calls
no test coverage detected