All files decoder.ts

98.26% Statements 113/115
96.72% Branches 59/61
100% Functions 5/5
98.08% Lines 102/104

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219        1x 1x 1x 1x 1x 1x 1x 1x             1x     34x     33x     26x   26x   26x 26x     26x 68x 68x       68x       26x   26x 1x 1x   25x     1x 1x 1x 1x 2x                 1x   2x 2x     6x 6x 6x       6x         1x 1x     5x   18x 18x   4x 4x 1x 1x   3x   7x 7x 1x 1x   6x   3x 3x   1x 1x 1x     63x     26x 26x 26x 26x   26x 26x 26x 26x         63x 26x             26x     25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x                               33x 32x 32x     32x 32x   32x 125x   125x 91x 25x     125x 58x 18x       125x 19x 2x         30x     23x   29x 27x   26x             29x       27x    
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
 
import { BufferReader } from "@node-lightning/bufio";
import bech32 from "bech32";
import { ADDRESS_VERSION } from "./address-version";
import * as crypto from "./crypto";
import { FIELD_TYPE } from "./field-type";
import { hrpToPico } from "./hrp-pico";
import { Invoice } from "./invoice";
import { WordCursor } from "./word-cursor";
 
/**
 * Decodes an invoice into an Invoice object
 * @param invoice
 * @return
 */
export function decode(invoice: string): Invoice {
    // Decode the invoice into prefix and words.
    // The words will be interated over to decode the rest of thee invoice
    const { prefix, words } = bech32.decode(invoice, Number.MAX_SAFE_INTEGER);
 
    // Parse the prefix into the network and the value in pico bitcoin.
    const { network, picoBtc } = parsePrefix(prefix);
 
    // Construct a word cursor to read from the remaining data
    const wordcursor = new WordCursor(words);
 
    const timestamp = wordcursor.readUIntBE(7); // read 7 words / 35 bits
 
    const fields = [];
    const unknownFields = [];
 
    // read fields until at signature
    while (wordcursor.wordsRemaining > 104) {
        const type = wordcursor.readUIntBE(1); // read 1 word / 5 bits
        const len = wordcursor.readUIntBE(2); // read 2 words / 10 bits
 
        let value;
 
        switch (type) {
            case 0:
                continue; // read off padding
            case FIELD_TYPE.PAYMENT_HASH: // p - 256-bit sha256 payment_hash
                value = wordcursor.readBytes(len);
                // push non-standard length field into unknown fields
                if (len !== 52) {
                    unknownFields.push({ type, value });
                    continue;
                }
                break;
            case FIELD_TYPE.ROUTE: // r - variable, one or more entries containing extra routing info
                {
                    value = [];
                    const bytes = wordcursor.readBytes(len);
                    const bytecursor = new BufferReader(bytes);
                    while (!bytecursor.eof) {
                        value.push({
                            pubkey: bytecursor.readBytes(33),
                            short_channel_id: bytecursor.readBytes(8),
                            fee_base_msat: bytecursor.readUInt32BE(),
                            fee_proportional_millionths: bytecursor.readUInt32BE(),
                            cltv_expiry_delta: bytecursor.readUInt16BE(),
                        });
                    }
                }
                break;
            case FIELD_TYPE.EXPIRY: // x - expiry time in seconds
                value = wordcursor.readUIntBE(len);
                break;
            case FIELD_TYPE.FALLBACK_ADDRESS: // f - variable depending on version
                {
                    const version = wordcursor.readUIntBE(1);
                    const address = wordcursor.readBytes(len - 1);
                    value = {
                        version,
                        address,
                    };
                    if (
                        version !== ADDRESS_VERSION.SEGWIT &&
                        version !== ADDRESS_VERSION.P2PKH &&
                        version !== ADDRESS_VERSION.P2SH
                    ) {
                        unknownFields.push({ type, value });
                        continue;
                    }
                }
                break;
            case FIELD_TYPE.SHORT_DESC: // d - short description of purpose of payment utf-8
                value = wordcursor.readBytes(len).toString("utf8");
                break;
            case FIELD_TYPE.PAYEE_NODE: // n - 33-byte public key of the payee node
                value = wordcursor.readBytes(len);
                if (len !== 53) {
                    unknownFields.push({ type, value });
                    continue;
                }
                break;
            case FIELD_TYPE.HASH_DESC: // h - 256-bit sha256 description of purpose of payment
                value = wordcursor.readBytes(len);
                if (len !== 52) {
                    unknownFields.push({ type, value });
                    continue;
                }
                break;
            case FIELD_TYPE.MIN_FINAL_CLTV_EXPIRY: // c - min_final_cltv_expiry to use for the last HTLC in the route
                value = wordcursor.readUIntBE(len);
                break;
            default:
                value = wordcursor.readBytes(len);
                unknownFields.push({ type, value });
                continue;
        }
 
        fields.push({ type, value });
    }
 
    const sigBytes = wordcursor.readBytes(103); // read 512-bit sig
    const r = sigBytes.slice(0, 32);
    const s = sigBytes.slice(32);
    const recoveryFlag = wordcursor.readUIntBE(1);
 
    wordcursor.position = 0;
    let preHashData = wordcursor.readBytes(words.length - 104, true);
    preHashData = Buffer.concat([Buffer.from(prefix), preHashData]);
    const hashData = crypto.sha256(preHashData);
 
    // extract the pubkey for verifying the signature by either:
    // 1: using the payee field value (n)
    // 2: performing signature recovery
    const payeeNodeField = fields.find(p => p.type === FIELD_TYPE.PAYEE_NODE);
    const pubkey = payeeNodeField
        ? payeeNodeField.value // use payee node provided
        : crypto.ecdsaRecovery(hashData, sigBytes, recoveryFlag); // recovery pubkey from ecdsa sig
 
    // validate signature
    // note if we performed signature recovery this will always match
    // so we may want to just skip this if we had signature recovery
    if (!crypto.ecdsaVerify(pubkey, hashData, sigBytes)) throw new Error("Signature invalid");
 
    // constuct the invoice
    const result = new Invoice();
    result._value = picoBtc; // directly assign pico value since there is not setter
    result.network = network;
    result.timestamp = timestamp;
    result.fields = fields;
    result.unknownFields = unknownFields;
    result.signature = { r, s, recoveryFlag };
    result.pubkey = pubkey;
    result.hashData = hashData;
    result.usedSigRecovery = !!payeeNodeField;
    return result;
}
 
//////////////
 
/**
 * Parses the prefix into network and value and then performs
 * validations on the values.
 *
 * This code is rough. Should refactor into two steps:
 * 1) tokenize
 * 2) parse tokens
 *
 * Value is returned as pico bitcoin.
 */
function parsePrefix(prefix: string): { network: string; picoBtc: bigint } {
    if (!prefix.startsWith("ln")) throw new Error("Invalid prefix");
    let network = "";
    let tempValue = "";
    let value;
    let multiplier;
    let hasNetwork = false;
    let hasAmount = false;
 
    for (let i = 2; i < prefix.length; i++) {
        const charCode = prefix.charCodeAt(i);
 
        if (!hasNetwork) {
            if (charCode >= 97 && charCode <= 122) network += prefix[i];
            else hasNetwork = true;
        }
 
        if (hasNetwork && !hasAmount) {
            if (charCode >= 48 && charCode <= 57) tempValue += prefix[i];
            else Eif (tempValue) hasAmount = true;
            else throw new Error("Invalid amount");
        }
 
        if (hasAmount) {
            if (charCode >= 97 && charCode <= 122) multiplier = prefix[i];
            else throw new Error("Invalid character");
        }
    }
 
    // returns null if we do not have a value
    if (tempValue === "") value = null;
    // otherwise we multiply by the value by the pico amount to obtain
    // the actual pico value of the
    else value = BigInt(tempValue) * hrpToPico(multiplier);
 
    if (!isValidNetwork(network)) throw new Error("Invalid network");
    if (!isValidValue(value)) throw new Error("Invalid amount");
 
    return {
        network,
        picoBtc: value,
    };
}
 
function isValidNetwork(network) {
    return network === "bc" || network === "tb" || network === "bcrt" || network === "sb";
}
 
function isValidValue(value) {
    return value === null || value > 0;
}