diff --git a/BTC/Advanced/Lighting Network/README-EN.md b/BTC/Advanced/Lighting Network/README-EN.md new file mode 100644 index 000000000..3a51147db --- /dev/null +++ b/BTC/Advanced/Lighting Network/README-EN.md @@ -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. \ No newline at end of file diff --git a/BTC/Advanced/Lighting Network/lightning-network.js b/BTC/Advanced/Lighting Network/lightning-network.js new file mode 100644 index 000000000..6d1afed61 --- /dev/null +++ b/BTC/Advanced/Lighting Network/lightning-network.js @@ -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); \ No newline at end of file diff --git a/BTC/Advanced/Multisign/README-EN.md b/BTC/Advanced/Multisign/README-EN.md new file mode 100644 index 000000000..9bf43ee65 --- /dev/null +++ b/BTC/Advanced/Multisign/README-EN.md @@ -0,0 +1,103 @@ +# Multi-Signature Introduction + +## Overview +In the Bitcoin (BTC) network, Multi-Signature (Multi-Sig) is a security enhancement technology that requires multiple keys to sign to execute a transaction. Specifically, the multi-sig mechanism allows users to create a wallet address where funds can only be used when certain signature conditions are met. Multi-signature technology can be used to enhance security, implement distributed control, and manage funds. + +### How Multi-Signature Works +1. **Creating Multi-sig Address**: + - Multi-sig addresses are typically generated from multiple participants' public keys. + - For example, a 2-of-3 multi-sig address means it requires three public keys, and at least two corresponding private keys to sign transactions. + +2. **Constructing Transactions**: + - When using bitcoins in a multi-sig address, a transaction containing all necessary signatures must be constructed. + - For example, for a 2-of-3 multi-sig address, signatures from at least two participants are required to execute the transaction. + +3. **Broadcasting Transactions**: + - Fully signed transactions can be broadcast to the Bitcoin network for verification and packaging by miners. + +### Multi-Signature Use Cases +1. **Enhanced Security**: + - Theft of a single private key cannot transfer funds; multiple private keys must be stolen simultaneously for malicious transactions. + +2. **Distributed Control**: + - Can be used for joint fund control, such as multi-party management of company funds, preventing single-person abuse. + +3. **Smart Contracts and DApps**: + - Multi-signatures can serve as simple smart contract mechanisms, supporting more complex transaction conditions and logic. + +### Example +A simple 2-of-3 multi-sig transaction process might look like this: +1. Generate three key pairs (User A, User B, User C). +2. Create a 2-of-3 multi-sig address using the three public keys. +3. Transfer bitcoins to this multi-sig address. +4. When needing to transfer bitcoins, Users A and B (or A and C, or B and C) jointly sign the transaction. +5. Broadcast the transaction to the network and wait for confirmation. + +## Multi-Signature OPCodes +In the Bitcoin network, multi-signature allows enhanced security and flexibility by requiring multiple signatures for transaction execution. Bitcoin Script provides several key operation codes (OPCodes) to implement multi-signatures. Here are the main multi-signature-related OPCodes and their functions: + +### Main Multi-Signature OPCodes + +1. **OP_CHECKMULTISIG** + - **Function**: Verifies multi-signature transactions. + - **Description**: Pops n public keys and m signatures from the stack, checks if at least m signatures are valid. Returns true if valid, false otherwise. + - **Example**: + ``` + OP_CHECKMULTISIG + ``` + where `` is minimum required signatures, `` is number of provided public keys. + +2. **OP_CHECKMULTISIGVERIFY** + - **Function**: Similar to OP_CHECKMULTISIG but terminates execution and returns error on verification failure. + - **Description**: Works same as OP_CHECKMULTISIG, but script immediately fails if check fails. + - **Example**: + ``` + OP_CHECKMULTISIGVERIFY + ``` + +3. **OP_CHECKSIGADD** + - **Function**: Used for efficient multi-signature verification in Taproot and Schnorr signature schemes. + - **Description**: Takes a public key and signature from stack, verifies signature validity, adds result to counter indicating total valid signatures. + - **Example**: + ``` + OP_CHECKSIGADD + OP_CHECKSIGADD + OP_CHECKSIGADD + <2> OP_EQUAL + ``` + +### Script Examples + +#### P2SH (Pay-to-Script-Hash) Multi-sig Transaction +1. **Create Redeem Script**: + ``` + <2> <3> OP_CHECKMULTISIG + ``` + +2. **Generate P2SH Address**: + - Use hash of redeem script as P2SH address for receiving bitcoins. + +3. **Spend P2SH Multi-sig Transaction**: + - Unlocking Script: + ``` + <0> + ``` + +#### Taproot Multi-sig Script +``` + OP_CHECKSIGADD + OP_CHECKSIGADD + OP_CHECKSIGADD +<2> OP_EQUAL +``` + +### OPCode Comparison + +| OPCode | Function | Description | Advantages | Disadvantages | Script Types | BIP Number | Example | +|--------|----------|-------------|------------|---------------|--------------|------------|---------| +| **OP_CHECKMULTISIG** | Multi-sig verification | Verifies m-of-n signatures | Widely supported | Larger scripts, requires dummy value | P2SH, P2WSH | BIP 11, 16 | `<2> <3> OP_CHECKMULTISIG` | +| **OP_CHECKMULTISIGVERIFY** | Multi-sig verify with error | Like OP_CHECKMULTISIG with immediate failure | Simplified error handling | Requires dummy value | P2SH, P2WSH | BIP 11, 16 | `<2> <3> OP_CHECKMULTISIGVERIFY` | +| **OP_CHECKSIGADD** | Efficient multi-sig | Incremental signature verification | More efficient, smaller transactions | Only for Taproot | Taproot | BIP 340, 341 | ` OP_CHECKSIGADD...` | + +### Summary +These OPCodes provide various ways to implement multi-signatures in the Bitcoin network. OP_CHECKMULTISIG and OP_CHECKMULTISIGVERIFY are traditional implementations, while OP_CHECKSIGADD is a more efficient and flexible implementation introduced with Taproot and Schnorr signatures. Together, these technologies enhance Bitcoin transaction security and flexibility, meeting requirements for different use cases. diff --git a/BTC/README-EN.md b/BTC/README-EN.md new file mode 100644 index 000000000..2ed70e88e --- /dev/null +++ b/BTC/README-EN.md @@ -0,0 +1,125 @@ +# Bitcoin (BTC) + +This knowledge base aims to provide comprehensive information about Bitcoin (BTC) technology, covering basic functions, advanced applications, and various protocols and tools in the ecosystem. Whether you're a beginner or an experienced developer, this guide will help you better understand and use Bitcoin technology. + +## Introduction + +Bitcoin is the first decentralized digital currency based on blockchain technology, proposed by a person or team under the pseudonym "Satoshi Nakamoto" in 2008 and officially launched in 2009. It revolutionizes the traditional financial system by enabling trustless value transfer through cryptography and distributed networks. It serves as both a payment tool and investment vehicle, and is viewed as a social experiment redefining the boundaries of money and trust. + +Bitcoin combines cryptography, economics, and distributed systems, pioneering decentralized digital assets. Its value stems from technical reliability (censorship resistance, scarcity), social consensus (the "digital gold" narrative), and macro environment (fiat currency inflation, geopolitical conflicts). Despite facing scaling bottlenecks, energy controversies, and regulatory uncertainties, Bitcoin continues to drive financial system reform, becoming a core symbol of the blockchain revolution and redefining the future of money, trust, and value. + +## Core Technical Mechanisms + +-Blockchain and Decentralization +Transaction data is stored in a transparent distributed ledger (blockchain) maintained by global nodes without central control. Chain structure (blocks linked by hash values) and timestamp technology ensure data immutability. + +-Cryptography and Security +Uses SHA-256 hash algorithm and asymmetric encryption (public key addresses and private key signatures) to ensure transaction ownership and security. Proof of Work (PoW): Miners compete with computing power to verify transactions and generate new blocks, exchanging energy consumption for network security while receiving new coins as rewards. + +-Deflationary Model +Total supply capped at 21 million coins, with new coin issuance "halving" every four years, complete mining by 2140, scarcity comparable to gold. + +## Core Features and Innovations + +-Trustless +No need for bank or government endorsement, code rules drive system operation, users independently control assets (private key equals ownership). + +-Censorship Resistance and Globalization +Transactions unrestricted by borders, node network resistant to blocking, particularly suitable for cross-border payments and inflation hedging (e.g., El Salvador adopting as legal tender). + +-Pseudonymity +Users transact via encrypted addresses without direct identity binding, but on-chain records are publicly traceable, requiring mixing tools for enhanced privacy. + +-Irreversibility +Transactions once confirmed on blockchain cannot be reversed, reducing fraud risk but requiring careful operation (e.g., mistaken transfers cannot be recovered). + +-High Volatility +Market supply/demand, policy regulation and speculative sentiment cause dramatic price fluctuations, reaching $60,000 in 2021 and dropping to $16,000 in 2022. + +## Historical Evolution and Social Impact + +-Milestone Events + +2008 Whitepaper: Satoshi Nakamoto published "Bitcoin: A Peer-to-Peer Electronic Cash System", proposing decentralized currency vision. + +2010 First Physical Transaction: Programmer purchased 2 pizzas with 10,000 BTC (now worth hundreds of millions), initiating cryptocurrency practicality. + +2017 Fork and Scaling Controversy: Community disagreement led to Bitcoin fork into BTC (main chain) and BCH (Bitcoin Cash), exposing decentralized governance challenges. + +2021 Institutionalization: Tesla, MicroStrategy etc. included in balance sheets, Bitcoin futures ETF approved, promoting mainstream financial acceptance. + +-Application Scenario Expansion + +Payment Network: Lightning Network (Layer 2) enables small fast transactions, solving main chain low throughput (about 7 TPS) issue. + +Store of Value: Citizens in some countries (e.g., Argentina, Nigeria) use it as anti-inflation asset to hedge against fiat currency depreciation risk. + +Technical Derivative Ecosystem: Catalyzed innovations like smart contracts, DeFi (Decentralized Finance), NFTs, but Bitcoin itself remains focused on "digital gold" positioning. + +Through this knowledge base, you will learn Bitcoin's core functions, advanced features and ecosystem applications, helping you stay ahead in this rapidly developing field. + +## Task Status Legend: +⬜ Not Started ⌛ In Progress ✅ Completed + +## 1. Basic Functions + +### 1.1 Payment Addresses +Bitcoin address types and encoding methods: +- **P2PKH** (Pay to Public Key Hash) ✅ +- **P2SH-P2PKH** (Pay to Script Hash - Pay to Public Key Hash) ✅ +- **P2WPKH** (Pay to Witness Public Key Hash) ✅ +- **P2TR** (Pay to Taproot) ✅ +- **Base58 Encoding** ✅ +- **Bech32 Encoding** ✅ +- **Bech32m Encoding** ✅ + +### 1.2 Wallets +Bitcoin wallet types and characteristics: +- **Standard Wallets** ⌛ +- **Hierarchical Deterministic Wallets (HD Wallets)** ✅ + +### 1.3 Transactions +Bitcoin transaction knowledge: +- **UTXO Analysis** ⌛ +- **Coinbase Transactions** ⬜ +- **Transaction Construction** ⌛ +- **Fee Estimation** ⌛ +- **Signature Algorithms** ✅ + +### 1.4 Tools +Common tools in Bitcoin ecosystem: +- **Blockchain Explorers** ⌛ +- **Network Hashrate** ⬜ +- **API Services** ⬜ +- **Data Analysis Tools** ⬜ + +## 2. Advanced Functions + +### 2.1 PSBT (Partially Signed Bitcoin Transactions) +Introduction and usage of PSBT: +- **PSBT Protocol Introduction** ✅ +- **Creating and Parsing PSBT** ✅ +- **PSBT V2** ⬜ + +### 2.2 Taproot +Introduction and advantages of Taproot technology: +- **Schnorr Signatures** ✅ +- **MAST** (Merkelized Abstract Syntax Tree) ✅ +- **Privacy and Efficiency Improvements** ⬜ +- **Differences between Key Path and Script Path** ⬜ + +### 2.3 Multisignature Addresses +Usage and advantages of multisignature addresses: +- **Multisignature Introduction** ✅ +- **OP_CHECKMULTISIG** ✅ +- **OP_CHECKMULTISIGVERIFY** ✅ +- **OP_CHECKSIGADD** ✅ + +## 3. Ecosystem Applications +- **BRC20 Protocol Introduction** ✅ +- **ARC20 Protocol Introduction** ✅ +- **Runes Protocol Introduction** ✅ +- **Lightning Network Introduction** ⌛ +- **Lightning Network Core Logic** ⌛ +- **OP_CAT** ✅ +- **Babylon | BTC Staking** ⬜ \ No newline at end of file diff --git a/btc/Advanced/Psbt/rawParsePSBT.js b/btc/Advanced/Psbt/rawParsePSBT.js index ed664d5c5..9a177cd98 100644 --- a/btc/Advanced/Psbt/rawParsePSBT.js +++ b/btc/Advanced/Psbt/rawParsePSBT.js @@ -5,18 +5,20 @@ const parsePSBT = (psbtBase64) => { // 魔术字节和分隔符 const magicBytes = psbtBuffer.slice(index, index + 5); index += 5; - if (magicBytes.toString('hex') !== '70736274ff') { + if (magicBytes.toString('hex') !== '70736274ff') { // Check for valid PSBT magic bytes throw new Error('Not a valid PSBT'); } // 解析全局部分 console.log('Global Data:'); while (psbtBuffer[index] !== 0x00 && index < psbtBuffer.length) { + // Parse key if (index + 2 > psbtBuffer.length) break; // Prevent reading beyond buffer const keyLen = psbtBuffer[index]; const key = psbtBuffer.slice(index + 1, index + 1 + keyLen); index += 1 + keyLen; + // Parse value if (index + 1 > psbtBuffer.length) break; // Prevent reading beyond buffer const valueLen = psbtBuffer.readIntLE(index, 1); const value = psbtBuffer.slice(index + 1, index + 1 + valueLen); @@ -24,11 +26,12 @@ const parsePSBT = (psbtBase64) => { console.log(`Key: ${key.toString('hex')}, Value: ${value.toString('hex')}`); } - index++; // Skip separator + index++; // Move past separator byte // 解析输入部分 console.log('Inputs:'); while (index < psbtBuffer.length && psbtBuffer[index] !== 0x00) { + // Process each input's key-value pairs while (psbtBuffer[index] !== 0x00 && index < psbtBuffer.length) { if (index + 2 > psbtBuffer.length) break; const keyLen = psbtBuffer[index]; @@ -41,14 +44,15 @@ const parsePSBT = (psbtBase64) => { index += 1 + valueLen; console.log(`Key: ${key.toString('hex')}, Value: ${value.toString('hex')}`); } - index++; // Skip separator + index++; // Move to next input or separator } - index++; // Skip separator + index++; // Move past input separator - // 解析输出部分 + // 解析输出部分 console.log('Outputs:'); while (index < psbtBuffer.length && psbtBuffer[index] !== 0x00) { console.log(`Output at index ${index}:`); + // Process each output's key-value pairs while (psbtBuffer[index] !== 0x00 && index < psbtBuffer.length) { if (index + 2 > psbtBuffer.length) break; const keyLen = psbtBuffer[index]; @@ -62,11 +66,11 @@ const parsePSBT = (psbtBase64) => { console.log(`Key: ${key.toString('hex')}, Value: ${value.toString('hex')}`); } - index++; // Skip separator + index++; // Move to next output or end } }; // 用你提供的Base64字符串测试 const psbtBase64 = 'cHNidP8BAHUCAAAAASaBcTce3/KF6Tet7qSze3gADAVmy7OtZGQXE8pCFxv2AAAAAAD+////AtPf9QUAAAAAGXapFNDFmQPFusKGh2DpD9UhpGZap2UgiKwA4fUFAAAAABepFDVF5uM7gyxHBQ8k0+65PJwDlIvHh7MuEwAAAQD9pQEBAAAAAAECiaPHHqtNIOA3G7ukzGmPopXJRjr6Ljl/hTPMti+VZ+UBAAAAFxYAFL4Y0VKpsBIDna89p95PUzSe7LmF/////4b4qkOnHf8USIk6UwpyN+9rRgi7st0tAXHmOuxqSJC0AQAAABcWABT+Pp7xp0XpdNkCxDVZQ6vLNL1TU/////8CAMLrCwAAAAAZdqkUhc/xCX/Z4Ai7NK9wnGIZeziXikiIrHL++E4sAAAAF6kUM5cluiHv1irHU6m80GfWx6ajnQWHAkcwRAIgJxK+IuAnDzlPVoMR3HyppolwuAJf3TskAinwf4pfOiQCIAGLONfc0xTnNMkna9b7QPZzMlvEuqFEyADS8vAtsnZcASED0uFWdJQbrUqZY3LLh+GFbTZSYG2YVi/jnF6efkE/IQUCSDBFAiEA0SuFLYXc2WHS9fSrZgZU327tzHlMDDPOXMMJ/7X85Y0CIGczio4OFyXBl/saiK9Z9R5E5CVbIBZ8hoQDHAXR8lkqASECI7cr7vCWXRC+B3jv7NYfysb3mk6haTkzgHNEZPhPKrMAAAAAAAAA'; -parsePSBT(psbtBase64); +parsePSBT(psbtBase64); \ No newline at end of file