Skip to content

Commit 3b06171

Browse files
authored
Merge pull request #1280 from ygcl9698/optimize
docs: Lightning Network - some documents have been added, and some annotations have been added
2 parents c824a8e + 1c21819 commit 3b06171

File tree

5 files changed

+561
-7
lines changed

5 files changed

+561
-7
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Lightning Network
2+
3+
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:
4+
5+
### 1. **Core Concept: Payment Channels**
6+
7+
The Lightning Network operates through payment channels. The specific process is as follows:
8+
- **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.
9+
- **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.
10+
- **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).
11+
12+
### 2. **Transaction Mechanism in Lightning Network**
13+
14+
In the Lightning Network, transactions within channels are instantly confirmed. The specific process is:
15+
- **Incremental Balance Updates**: Each off-chain transaction only updates the balance state in the payment channel, without broadcasting to the Bitcoin blockchain.
16+
- **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.
17+
18+
### 3. **Cross-Channel Payment Routing**
19+
20+
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:
21+
- **Path Finding**: If there's no direct channel between two users, the network finds suitable paths through other nodes to complete the payment.
22+
- **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.
23+
24+
### 4. **Main Advantages**
25+
26+
- **Scalability**: Through off-chain transactions, the Lightning Network significantly reduces Bitcoin blockchain load, theoretically supporting millions of transactions per second.
27+
- **Lower Fees**: Most transactions occur off-chain, with very low transaction fees, only requiring a fraction of on-chain transaction fees.
28+
- **Instant Payments**: Lightning Network transactions are almost instantaneous, making them suitable for daily consumption, unlike on-chain transactions that might take minutes.
29+
30+
### 5. **Challenges and Limitations**
31+
32+
- **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.
33+
- **Channel Management**: Users need to manually open and close channels, each operation requiring on-chain fees, making frequent operations costly.
34+
- **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.
35+
36+
### 6. **Lightning Network Applications and Future**
37+
38+
- **Micropayments**: Due to low fees, the Lightning Network is ideal for micropayments, such as content tipping, small donations, and in-app purchases.
39+
- **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.
40+
- **Cross-border Payments**: It enables quick and low-cost international remittances, providing a convenient path for cross-border payments.
41+
42+
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.
Lines changed: 280 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,280 @@
1+
// Custom error class for payment channel operations
2+
class PaymentChannelError extends Error {
3+
constructor(message) {
4+
super(message);
5+
this.name = 'PaymentChannelError';
6+
}
7+
}
8+
9+
// Payment Channel class represents a bi-directional payment channel between two parties
10+
class PaymentChannel {
11+
constructor(channelId, partyA, partyB, initialDepositA, initialDepositB, timeoutBlocks = 144) {
12+
// Validate input parameters
13+
if (initialDepositA < 0 || initialDepositB < 0) {
14+
throw new PaymentChannelError('Initial deposits must be positive');
15+
}
16+
if (!this._isValidParty(partyA) || !this._isValidParty(partyB)) {
17+
throw new PaymentChannelError('Invalid party information');
18+
}
19+
20+
this.channelId = channelId;
21+
this.partyA = partyA;
22+
this.partyB = partyB;
23+
this.balanceA = initialDepositA;
24+
this.balanceB = initialDepositB;
25+
this.status = 'INITIALIZED';
26+
this.nonce = 0;
27+
this.updates = new Map();
28+
this.timeoutBlocks = timeoutBlocks; // Default 24 hours (assuming 10 min blocks)
29+
this.openBlockHeight = null;
30+
}
31+
32+
// Create a new payment channel
33+
async createChannel() {
34+
try {
35+
if (this.status !== 'INITIALIZED') {
36+
throw new PaymentChannelError('Channel already created');
37+
}
38+
39+
// Create multisig transaction
40+
const multisigTx = await this._createMultisigTransaction();
41+
this.openBlockHeight = await this._getCurrentBlockHeight();
42+
this.status = 'OPEN';
43+
44+
// Record initial state
45+
this._recordUpdate({
46+
nonce: this.nonce,
47+
sender: this.partyA.id,
48+
receiver: this.partyB.id,
49+
amount: 0,
50+
balanceA: this.balanceA,
51+
balanceB: this.balanceB,
52+
timestamp: Date.now()
53+
});
54+
55+
return true;
56+
} catch (error) {
57+
console.error('Failed to create channel:', error);
58+
return false;
59+
}
60+
}
61+
62+
// Update channel balances
63+
async updateBalance(sender, receiver, amount) {
64+
try {
65+
// Validate channel state
66+
this._validateChannelState();
67+
68+
// Validate amount
69+
if (amount <= 0) {
70+
throw new PaymentChannelError('Amount must be positive');
71+
}
72+
73+
// Update balances based on sender and receiver
74+
if (sender === this.partyA.id && receiver === this.partyB.id) {
75+
if (this.balanceA < amount) {
76+
throw new PaymentChannelError('Insufficient funds for party A');
77+
}
78+
this.balanceA -= amount;
79+
this.balanceB += amount;
80+
} else if (sender === this.partyB.id && receiver === this.partyA.id) {
81+
if (this.balanceB < amount) {
82+
throw new PaymentChannelError('Insufficient funds for party B');
83+
}
84+
this.balanceB -= amount;
85+
this.balanceA += amount;
86+
} else {
87+
throw new PaymentChannelError('Invalid parties for transfer');
88+
}
89+
90+
// Create and record update
91+
const update = {
92+
nonce: ++this.nonce,
93+
sender,
94+
receiver,
95+
amount,
96+
balanceA: this.balanceA,
97+
balanceB: this.balanceB,
98+
timestamp: Date.now()
99+
};
100+
101+
// Sign and verify update (implementation needed)
102+
// update.signature = await this._signUpdate(update);
103+
// if (!this._verifySignature(update)) {
104+
// throw new PaymentChannelError('Invalid signature');
105+
// }
106+
107+
this._recordUpdate(update);
108+
return true;
109+
} catch (error) {
110+
console.error('Failed to update balance:', error);
111+
return false;
112+
}
113+
}
114+
115+
// Close the payment channel and settle final balances
116+
async closeChannel() {
117+
try {
118+
if (this.status === 'CLOSED') {
119+
throw new PaymentChannelError('Channel already closed');
120+
}
121+
122+
// Validate closing conditions
123+
await this._validateCloseConditions();
124+
125+
// Create settlement transaction
126+
const settlementTx = await this._createSettlementTransaction();
127+
this.status = 'CLOSED';
128+
129+
// Emit settlement event
130+
this._emitSettlementEvent(settlementTx);
131+
132+
return [this.balanceA, this.balanceB];
133+
} catch (error) {
134+
console.error('Failed to close channel:', error);
135+
return [0, 0];
136+
}
137+
}
138+
139+
// Get current channel state
140+
getChannelState() {
141+
return {
142+
nonce: this.nonce,
143+
balanceA: this.balanceA,
144+
balanceB: this.balanceB,
145+
timestamp: Date.now()
146+
};
147+
}
148+
149+
// Private helper methods
150+
_validateChannelState() {
151+
if (this.status !== 'OPEN') {
152+
throw new PaymentChannelError('Channel not open');
153+
}
154+
}
155+
156+
_isValidParty(party) {
157+
return party && party.id && party.publicKey;
158+
}
159+
160+
_recordUpdate(update) {
161+
this.updates.set(update.nonce, update);
162+
}
163+
164+
async _getCurrentBlockHeight() {
165+
// Implementation needed: connect to blockchain node
166+
return Promise.resolve(1000);
167+
}
168+
169+
async _createMultisigTransaction() {
170+
// Implementation needed: create actual multisig transaction
171+
return Promise.resolve({
172+
channelId: this.channelId,
173+
partyA: this.partyA,
174+
partyB: this.partyB,
175+
totalAmount: this.balanceA + this.balanceB,
176+
timestamp: Date.now()
177+
});
178+
}
179+
180+
async _createSettlementTransaction() {
181+
// Implementation needed: create actual settlement transaction
182+
return Promise.resolve({
183+
channelId: this.channelId,
184+
finalBalanceA: this.balanceA,
185+
finalBalanceB: this.balanceB,
186+
timestamp: Date.now()
187+
});
188+
}
189+
190+
async _validateCloseConditions() {
191+
// Implementation needed: validate closing conditions
192+
}
193+
194+
_emitSettlementEvent(settlementTx) {
195+
// Implementation needed: emit settlement event
196+
}
197+
}
198+
199+
// Lightning Network class manages multiple payment channels
200+
class LightningNetwork {
201+
constructor() {
202+
this.channels = new Map();
203+
}
204+
205+
// Create a new payment channel
206+
async createPaymentChannel(channelId, partyA, partyB, depositA, depositB) {
207+
try {
208+
const channel = new PaymentChannel(
209+
channelId,
210+
partyA,
211+
partyB,
212+
depositA,
213+
depositB
214+
);
215+
216+
if (await channel.createChannel()) {
217+
this.channels.set(channelId, channel);
218+
return channel;
219+
}
220+
return null;
221+
} catch (error) {
222+
console.error('Failed to create payment channel:', error);
223+
return null;
224+
}
225+
}
226+
227+
// Get an existing payment channel
228+
getChannel(channelId) {
229+
return this.channels.get(channelId);
230+
}
231+
}
232+
233+
// Example usage
234+
async function main() {
235+
try {
236+
// Create Lightning Network instance
237+
const ln = new LightningNetwork();
238+
239+
// Create channel parties
240+
const alice = {
241+
id: 'Alice',
242+
publicKey: '0x1234...', // Should be real public key
243+
};
244+
const bob = {
245+
id: 'Bob',
246+
publicKey: '0x5678...', // Should be real public key
247+
};
248+
249+
// Create payment channel
250+
const channel = await ln.createPaymentChannel(
251+
'ch001',
252+
alice,
253+
bob,
254+
1.0,
255+
1.0
256+
);
257+
258+
if (!channel) {
259+
throw new Error('Failed to create channel');
260+
}
261+
262+
// Perform payments
263+
console.log('Initial state:', channel.getChannelState());
264+
265+
await channel.updateBalance(alice.id, bob.id, 0.3);
266+
console.log('After first payment:', channel.getChannelState());
267+
268+
await channel.updateBalance(bob.id, alice.id, 0.1);
269+
console.log('After second payment:', channel.getChannelState());
270+
271+
// Close channel
272+
const [finalBalanceA, finalBalanceB] = await channel.closeChannel();
273+
console.log('Final settlement:', { Alice: finalBalanceA, Bob: finalBalanceB });
274+
} catch (error) {
275+
console.error('Error in main:', error);
276+
}
277+
}
278+
279+
// Run the example
280+
main().catch(console.error);

0 commit comments

Comments
 (0)