Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions BTC/Advanced/Lighting Network/README-EN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Lightning Network

The Lightning Network is a Layer 2 payment protocol for Bitcoin, designed to enable fast, low-cost transactions by reducing on-chain transactions. Built on top of the Bitcoin blockchain, it aims to solve Bitcoin's current scalability and transaction speed issues. Here's a detailed introduction to the core concepts and functions of the Lightning Network:

### 1. **Core Concept: Payment Channels**

The Lightning Network operates through payment channels. The specific process is as follows:
- **Creating Payment Channels**: When two parties need frequent transactions, they can create a payment channel. This requires both parties to deposit initial funds into a multi-signature wallet, recorded on the blockchain as a single on-chain transaction.
- **Off-chain Transactions**: Once the channel is established, both parties can directly exchange signed balance updates off-chain, without requiring network-wide confirmation, greatly improving transaction speed.
- **Closing Channels**: When parties no longer need to continue transacting, they can choose to close the channel. The final balance state of the channel is then recorded on the Bitcoin blockchain as an on-chain transaction. This greatly reduces blockchain burden as multiple transactions only require two on-chain transactions (opening and closing).

### 2. **Transaction Mechanism in Lightning Network**

In the Lightning Network, transactions within channels are instantly confirmed. The specific process is:
- **Incremental Balance Updates**: Each off-chain transaction only updates the balance state in the payment channel, without broadcasting to the Bitcoin blockchain.
- **Decentralized Trust Transactions**: Each state update is confirmed by signatures from both parties, ensuring neither party can tamper with transaction balances, preventing attempts to take excess funds.

### 3. **Cross-Channel Payment Routing**

The Lightning Network supports not only direct payments between two channel users but also multi-hop payments, allowing funds to be transferred to target users through multiple channels. The specific process is:
- **Path Finding**: If there's no direct channel between two users, the network finds suitable paths through other nodes to complete the payment.
- **Payment Atomicity**: The entire payment only completes when all intermediate nodes in the path agree and complete their part of the payment, ensuring funds aren't intercepted during multi-hop processes.

### 4. **Main Advantages**

- **Scalability**: Through off-chain transactions, the Lightning Network significantly reduces Bitcoin blockchain load, theoretically supporting millions of transactions per second.
- **Lower Fees**: Most transactions occur off-chain, with very low transaction fees, only requiring a fraction of on-chain transaction fees.
- **Instant Payments**: Lightning Network transactions are almost instantaneous, making them suitable for daily consumption, unlike on-chain transactions that might take minutes.

### 5. **Challenges and Limitations**

- **Liquidity Requirements**: To ensure large transactions flow smoothly, each node in the path must have sufficient funds in the channel, otherwise transactions might be blocked.
- **Channel Management**: Users need to manually open and close channels, each operation requiring on-chain fees, making frequent operations costly.
- **Security Risks**: While the Lightning Network is highly secure, it's not without risks. Nodes need to stay online to prevent attackers from broadcasting outdated transactions.

### 6. **Lightning Network Applications and Future**

- **Micropayments**: Due to low fees, the Lightning Network is ideal for micropayments, such as content tipping, small donations, and in-app purchases.
- **Merchant and Retail**: With near-real-time transaction speeds, the Lightning Network can make Bitcoin an ideal payment method for retail, dining, and daily consumption.
- **Cross-border Payments**: It enables quick and low-cost international remittances, providing a convenient path for cross-border payments.

The Lightning Network continues to evolve with ongoing development and user growth. It provides a promising solution to Bitcoin's scalability, but to fully realize its potential, it requires support from a reliable and robust node network.
280 changes: 280 additions & 0 deletions BTC/Advanced/Lighting Network/lightning-network.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,280 @@
// Custom error class for payment channel operations
class PaymentChannelError extends Error {
constructor(message) {
super(message);
this.name = 'PaymentChannelError';
}
}

// Payment Channel class represents a bi-directional payment channel between two parties
class PaymentChannel {
constructor(channelId, partyA, partyB, initialDepositA, initialDepositB, timeoutBlocks = 144) {
// Validate input parameters
if (initialDepositA < 0 || initialDepositB < 0) {
throw new PaymentChannelError('Initial deposits must be positive');
}
if (!this._isValidParty(partyA) || !this._isValidParty(partyB)) {
throw new PaymentChannelError('Invalid party information');
}

this.channelId = channelId;
this.partyA = partyA;
this.partyB = partyB;
this.balanceA = initialDepositA;
this.balanceB = initialDepositB;
this.status = 'INITIALIZED';
this.nonce = 0;
this.updates = new Map();
this.timeoutBlocks = timeoutBlocks; // Default 24 hours (assuming 10 min blocks)
this.openBlockHeight = null;
}

// Create a new payment channel
async createChannel() {
try {
if (this.status !== 'INITIALIZED') {
throw new PaymentChannelError('Channel already created');
}

// Create multisig transaction
const multisigTx = await this._createMultisigTransaction();
this.openBlockHeight = await this._getCurrentBlockHeight();
this.status = 'OPEN';

// Record initial state
this._recordUpdate({
nonce: this.nonce,
sender: this.partyA.id,
receiver: this.partyB.id,
amount: 0,
balanceA: this.balanceA,
balanceB: this.balanceB,
timestamp: Date.now()
});

return true;
} catch (error) {
console.error('Failed to create channel:', error);
return false;
}
}

// Update channel balances
async updateBalance(sender, receiver, amount) {
try {
// Validate channel state
this._validateChannelState();

// Validate amount
if (amount <= 0) {
throw new PaymentChannelError('Amount must be positive');
}

// Update balances based on sender and receiver
if (sender === this.partyA.id && receiver === this.partyB.id) {
if (this.balanceA < amount) {
throw new PaymentChannelError('Insufficient funds for party A');
}
this.balanceA -= amount;
this.balanceB += amount;
} else if (sender === this.partyB.id && receiver === this.partyA.id) {
if (this.balanceB < amount) {
throw new PaymentChannelError('Insufficient funds for party B');
}
this.balanceB -= amount;
this.balanceA += amount;
} else {
throw new PaymentChannelError('Invalid parties for transfer');
}

// Create and record update
const update = {
nonce: ++this.nonce,
sender,
receiver,
amount,
balanceA: this.balanceA,
balanceB: this.balanceB,
timestamp: Date.now()
};

// Sign and verify update (implementation needed)
// update.signature = await this._signUpdate(update);
// if (!this._verifySignature(update)) {
// throw new PaymentChannelError('Invalid signature');
// }

this._recordUpdate(update);
return true;
} catch (error) {
console.error('Failed to update balance:', error);
return false;
}
}

// Close the payment channel and settle final balances
async closeChannel() {
try {
if (this.status === 'CLOSED') {
throw new PaymentChannelError('Channel already closed');
}

// Validate closing conditions
await this._validateCloseConditions();

// Create settlement transaction
const settlementTx = await this._createSettlementTransaction();
this.status = 'CLOSED';

// Emit settlement event
this._emitSettlementEvent(settlementTx);

return [this.balanceA, this.balanceB];
} catch (error) {
console.error('Failed to close channel:', error);
return [0, 0];
}
}

// Get current channel state
getChannelState() {
return {
nonce: this.nonce,
balanceA: this.balanceA,
balanceB: this.balanceB,
timestamp: Date.now()
};
}

// Private helper methods
_validateChannelState() {
if (this.status !== 'OPEN') {
throw new PaymentChannelError('Channel not open');
}
}

_isValidParty(party) {
return party && party.id && party.publicKey;
}

_recordUpdate(update) {
this.updates.set(update.nonce, update);
}

async _getCurrentBlockHeight() {
// Implementation needed: connect to blockchain node
return Promise.resolve(1000);
}

async _createMultisigTransaction() {
// Implementation needed: create actual multisig transaction
return Promise.resolve({
channelId: this.channelId,
partyA: this.partyA,
partyB: this.partyB,
totalAmount: this.balanceA + this.balanceB,
timestamp: Date.now()
});
}

async _createSettlementTransaction() {
// Implementation needed: create actual settlement transaction
return Promise.resolve({
channelId: this.channelId,
finalBalanceA: this.balanceA,
finalBalanceB: this.balanceB,
timestamp: Date.now()
});
}

async _validateCloseConditions() {
// Implementation needed: validate closing conditions
}

_emitSettlementEvent(settlementTx) {
// Implementation needed: emit settlement event
}
}

// Lightning Network class manages multiple payment channels
class LightningNetwork {
constructor() {
this.channels = new Map();
}

// Create a new payment channel
async createPaymentChannel(channelId, partyA, partyB, depositA, depositB) {
try {
const channel = new PaymentChannel(
channelId,
partyA,
partyB,
depositA,
depositB
);

if (await channel.createChannel()) {
this.channels.set(channelId, channel);
return channel;
}
return null;
} catch (error) {
console.error('Failed to create payment channel:', error);
return null;
}
}

// Get an existing payment channel
getChannel(channelId) {
return this.channels.get(channelId);
}
}

// Example usage
async function main() {
try {
// Create Lightning Network instance
const ln = new LightningNetwork();

// Create channel parties
const alice = {
id: 'Alice',
publicKey: '0x1234...', // Should be real public key
};
const bob = {
id: 'Bob',
publicKey: '0x5678...', // Should be real public key
};

// Create payment channel
const channel = await ln.createPaymentChannel(
'ch001',
alice,
bob,
1.0,
1.0
);

if (!channel) {
throw new Error('Failed to create channel');
}

// Perform payments
console.log('Initial state:', channel.getChannelState());

await channel.updateBalance(alice.id, bob.id, 0.3);
console.log('After first payment:', channel.getChannelState());

await channel.updateBalance(bob.id, alice.id, 0.1);
console.log('After second payment:', channel.getChannelState());

// Close channel
const [finalBalanceA, finalBalanceB] = await channel.closeChannel();
console.log('Final settlement:', { Alice: finalBalanceA, Bob: finalBalanceB });
} catch (error) {
console.error('Error in main:', error);
}
}

// Run the example
main().catch(console.error);
Loading