Skip to content

Instantly share code, notes, and snippets.

@crukundo
Forked from SeverinAlexB/scidConverter.ts
Last active October 16, 2023 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crukundo/5bae6a32cb616433e15eabeda223227d to your computer and use it in GitHub Desktop.
Save crukundo/5bae6a32cb616433e15eabeda223227d to your computer and use it in GitHub Desktop.
Lightning Network short channel id (CLN) to decimal id (LND) converter
/** By LnRouter.app */
function bitShift(n: number, shiftBy: number): number {
let base = n;
for (let i = 0; i < shiftBy; i++) {
base = base * 2;
}
return base;
}
/**
* Takes SCID as input and returns channel ID in decimal,
* @param {string} scid
*/
export const shortChannelIdToDecimalId = (scid: string): string => {
const [blockHeightS, transactionIndexS, outputIndexS] = scid.split("x");
const blockHeight = Number.parseInt(blockHeightS);
const transactionIndex = Number.parseInt(transactionIndexS);
const outputIndex = Number.parseInt(outputIndexS);
const result = BigInt(bitShift(blockHeight, 40)) | BigInt(bitShift(transactionIndex, 16)) | BigInt(outputIndex);
return result.toString();
}
/**
* Takes channel id in decimal as input and returns SCID,
* @param {string} decimalId
*/
export const channelIdToScid = (decimalId: string): string => {
// Parse the decimal ID as a BigInt
const decimalBigInt = BigInt(decimalId);
// Extract the individual components
const outputIndex = Number(decimalBigInt & BigInt(0xffff));
const transactionIndex = Number((decimalBigInt >> BigInt(16)) & BigInt(0xffffff));
const blockHeight = Number((decimalBigInt >> BigInt(40)) & BigInt(0xffffff));
// Construct the short channel ID string
const scid = `${blockHeight}x${transactionIndex}x${outputIndex}`;
return scid;
}
const decimalId = shortChannelIdToDecimalId('811818x1325x1');
const channelScid = channelIdToScid('892603330724691969');
console.log(decimalId) // 892603330724691969
console.log(channelScid) // 811818x1325x1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment