0% found this document useful (0 votes)
10 views62 pages

Understanding P2WSH in Bitcoin Script

Bitcoin primarily utilizes a scripting language called Bitcoin Script, which is stack-based and non-Turing complete, to facilitate transactions and enforce rules. Key features include standard transactions, multisignature transactions, and timelocks, with various opcodes for arithmetic, stack manipulation, and cryptographic operations. The document also covers specific transaction types like Pay-to-PubKey-Hash (P2PKH), Pay-to-Script-Hash (P2SH), and Segregated Witness (SegWit) transactions, detailing their locking and unlocking scripts.

Uploaded by

Isam Abdul Aziz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views62 pages

Understanding P2WSH in Bitcoin Script

Bitcoin primarily utilizes a scripting language called Bitcoin Script, which is stack-based and non-Turing complete, to facilitate transactions and enforce rules. Key features include standard transactions, multisignature transactions, and timelocks, with various opcodes for arithmetic, stack manipulation, and cryptographic operations. The document also covers specific transaction types like Pay-to-PubKey-Hash (P2PKH), Pay-to-Script-Hash (P2SH), and Segregated Witness (SegWit) transactions, detailing their locking and unlocking scripts.

Uploaded by

Isam Abdul Aziz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

BITCOIN

SCRIPTING
MODULE 3
SCRIPTING LANGUAGES AND
APPLICATIONS
• Bitcoin primarily uses a single scripting language called Bitcoin
Script. However, there are various aspects and extensions to
Bitcoin Script that might give the impression of multiple scripting
languages.
• Bitcoin uses several scripting languages
• To facilitate transactions
• To enforce rules
• Manage the execution of scripts within the network.
• Each scripting method serves distinct purposes, from standard transactions to
complex conditions and data embedding, ensuring a flexible and robust system
for managing Bitcoin transactions.

• Primary scripting languages used in Bitcoin are


• Bitcoin Script
• Pay-to-PubKey-Hash (P2PKH)
• Pay-to-Script-Hash (P2SH)
• Pay-to-Witness-PubKey-Hash (P2WPKH) and Pay-to-Witness-Script-Hash
(P2WSH)
Bitcoin Script
• Bitcoin Script is a stack-based
• It is a interpretable language
• It's not Turing-complete
• Used to define the conditions under which a
Bitcoin transaction can be spent.
• It is a fundamental part of Bitcoin's transaction
validation process.
BITCOIN SCRIPT
-KEY FEATURES
• Stack-Based: Bitcoin Script operates using a
stack, where operations push and pop values
from the stack.
• Non-Turing Complete: Script is intentionally
limited in functionality to prevent complex
computations and loops, which helps to maintain
security and efficiency.
• Simple and Secure: Designed to be simple to
verify and resistant to attacks
BITCOIN SCRIPT- USES
• Standard Transactions: Most Bitcoin transactions use a
standard script that requires a digital signature from the
private key corresponding to the public key specified in the
script.
• Multisignature Transactions: Scripts can specify that
multiple signatures are required to authorize a transaction,
enhancing security by requiring agreement from multiple
parties.
• Timelocks: Bitcoin Script can enforce conditions such as
time-based restrictions, where a transaction can only be
spent after a certain time or block height.
BITCOIN SCRIPT OPCODES

• Opcodes are fundamental operations that are


executed by the Bitcoin network to validate
transactions.
• These opcodes perform tasks such as
• arithmetic operations,
• logical operations
• stack manipulations.
ARITHMETIC OPERATIONS

• OP_ADD: Adds the top two stack elements.


• OP_SUB: Subtracts the top stack element from the second-
to-top stack element.
• OP_NEGATE: Negates the top stack element (changes its
sign).
• OP_ABS: Takes the absolute value of the top stack element.
• OP_NOT: Computes the logical NOT of the top stack
element.
• OP_0 to OP_16: Pushes a single byte integer value (0 to 16)
onto the stack
STACK OPERATIONS

• OP_DUP: Duplicates the top stack element.


• OP_DROP: Removes the top stack element.
• OP_SWAP: Swaps the top two stack elements.
• OP_OVER: Copies the second-to-top stack
element to the top.
FLOW CONTROL

• OP_IF / OP_NOTIF: Conditional execution; if


the top stack element is true, the following
block of code executes.
• OP_ELSE: Executes the alternate block of code
if the preceding OP_IF or OP_NOTIF condition is
false.
• OP_ENDIF: Ends the OP_IF or OP_NOTIF block.
CRYPTOGRAPHIC OPERATIONS

• OP_HASH160: Performs a hash operation consisting of SHA-256


followed by RIPEMD-160.
• OP_RIPEMD160: Computes the RIPEMD-160 hash of the top stack
element.
• OP_SHA1: Computes the SHA-1 hash of the top stack element.
• OP_SHA256: Computes the SHA-256 hash of the top stack
element.
• OP_CHECKSIG: Verifies a digital signature against the public key
and the transaction data.
• OP_CHECKMULTISIG: Verifies multiple signatures against a list of
public keys and the transaction data.
DATA OPERATIONS

• OP_RETURN: Marks the output as provably unspendable and


allows embedding data in the blockchain.
• OP_PUSH: Pushes data onto the stack. There are various
opcodes for different sizes of data, such as OP_DATA1,
OP_DATA2, and OP_DATA4.
• OP_NOP: No operation; used as a placeholder or for future
extensions.
• OP_VERIFY: Checks that the top stack element is true. If not,
it terminates the script with failure.
• OP_SIZE: Pushes the size of the top stack element onto the
stack
COMPARISON OPERATIONS

• OP_EQUAL: Compares the top two stack


elements for equality.
• OP_EQUALVERIFY: Similar to OP_EQUAL, but
also removes the top two stack elements if they
are equal; otherwise, it terminates the script.
P2SH (PAY-TO-SCRIPT-HASH) AND
SEGWIT (SEGREGATED WITNESS)

• OP_HASH160: Used in P2SH to hash the


redeem script.
• OP_0: Used in SegWit addresses to denote
empty witness programs.
PAY-TO-PUBKEY-HASH
(P2PKH)
• P2PKH is the most common type of Bitcoin script, used for
standard Bitcoin transactions.

Key Characteristics:

• Format: Requires a public key and a digital signature.

• Script Flow: The scriptPubKey (the locking script) is a hash


of the public key, and the scriptSig (the unlocking script)
contains the actual public key and signature.

• Script Example:

• Locking Script (scriptPubKey): OP_DUP OP_HASH160


<PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG

• Unlocking Script (scriptSig): <Signature> <PublicKey>


PAY-TO-PUBKEY-HASH (P2PKH)
SCRIPT
• Locking Script (ScriptPubKey)
• Validates the transaction
• OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG

Explanation:
• OP_DUP: Duplicates the top element of the stack (the publickey).
• OP_HASH160: Hashes the top element of the stack (the public key)
using SHA-256 followed by RIPEMD-160.
• <PubKeyHash>: This is the hash of the public key that was used when
creating the transaction output.
• OP_EQUALVERIFY: Compares the top two stack elements (the result of
the OP_HASH160 operation and the expected <PubKeyHash>) and
removes them if they are equal. If they are not equal, the script fails.
• OP_CHECKSIG: Checks that the provided signature is valid for the
transaction data using the provided public key.
UNLOCKING SCRIPT
(SCRIPTSIG)
• This script provides the data necessary to satisfy the conditions imposed by
the Locking Script.
• <Signature> <PublicKey>
• <Signature>: A digital signature that proves ownership of the private key
associated with the public key.
• <PublicKey>: The public key corresponding to the <PubKeyHash> used in
the Locking Script.
Example:
• Public Key Hash (PubKeyHash):
76a91489abcdefabbaabbaabbaabbaabbaabbaabba88ac
• Public Key: 0234abcd... (an example public key in compressed format)
• Signature: 3045022100abcd... (an example digital signature)
EXAMPLE
• Suppose Alice’s public key hash (address hash)
= 1a2b3c... (RIPEMD-160(SHA-256(pubkey))).
• If Bob tries to spend without Alice’s private key,
his public key hash won’t match
<AlicePubKeyHash>, so the script fails at
OP_EQUALVERIFY.
• If Alice spends, her public key hash matches
and her signature is valid. The transaction
succeeds.
PAY-TO-SCRIPT-HASH (P2SH)
• P2SH allows users to send Bitcoin to a script hash, enabling more
complex scripts to be used for spending conditions.
• This allows for more complex spending conditions by using a script
hash. The locking script (ScriptPubKey) contains the hash of a
more complex redeem script.
• The unlocking script (ScriptSig) provides the redeem script and the
necessary data to satisfy the conditions.
• This method also leverages Bitcoin Script, but the complexity is
abstracted away behind the script hash
Key Characteristics:
• Format: The scriptPubKey contains a hash of the redeem script,
and the redeem script is provided in the scriptSig during spending.
• Flexibility: Enables more complex spending conditions while
keeping the main transaction script simple.
PAY-TO-SCRIPT-HASH (P2SH)

• Script Example:
• Locking Script (scriptPubKey): OP_HASH160
<ScriptHash> OP_EQUAL
• Unlocking Script (scriptSig):
<RedeemScript> <Signature(s)>
CREATING A P2SH
TRANSACTION
Locking Script (ScriptPubKey)
• When creating a P2SH output, the locking script
(ScriptPubKey) is a hash of the redeem script.
• Locking Script Format:
• OP_HASH160 <ScriptHash> OP_EQUAL
• OP_HASH160: Computes the hash of the redeem script
using SHA-256 followed by RIPEMD-160.
• <ScriptHash>: The result of hashing the redeem script.
• OP_EQUAL: Compares the result of OP_HASH160 with the
<ScriptHash>. If they match, the script succeeds.
REDEEM SCRIPT
• We have a redeem script that requires 2 out of 3 signatures to unlock the funds.
The redeem script would look like this:
• 2 <PubKey1> <PubKey2> <PubKey3> 3 OP_CHECKMULTISIG
• 2: The number of signatures required.
• <PubKey1> <PubKey2> <PubKey3>: The public keys involved in the
multisignature requirement.
• 3: The total number of public keys provided.
• OP_CHECKMULTISIG: Checks if the provided signatures match the required
number of public keys.
• Hash the Redeem Script: Calculate the hash of the redeem script using SHA-
256 followed by RIPEMD-160.
• 76a91489abcdefabbaabbaabbaabbaabbaabbaabba88ac –sample
• Sample locking script
• OP_HASH160 76a91489abcdefabbaabbaabbaabbaabbaabbaabba88ac
OP_EQUAL
SPENDING A P2SH
• TRANSACTION
To spend from a P2SH output, you need to provide the redeem
script and satisfy its conditions.
• Unlocking Script (ScriptSig)
• The unlocking script (ScriptSig) must provide the redeem
script followed by the necessary data to satisfy the conditions
of the redeem script.
• <RedeemScript> <Signature1> <Signature2>
• <RedeemScript>: The redeem script that was hashed to
create the P2SH address.
• <Signature1>: A signature from one of the public keys
specified in the redeem script.
• <Signature2>: A signature from another public key specified
in the redeem script.
P2SH TRANSACTION
VALIDATION
• Stack Initialization: Push the unlocking script onto the stack.
• <Signature1>, <Signature2>, 2, 0234abcd..., 0256efgh...,
0278ijkl..., 3, OP_CHECKMULTISIG]
• Execute the Locking Script (ScriptPubKey):
• OP_HASH160: Compute the hash of the redeem script.
• OP_EQUAL: Compare this hash with the hash in the locking script.
• Execute the Redeem Script:
• 2: The number of required signatures.
• OP_CHECKMULTISIG: Check if the provided signatures match the
required public keys.
PAY-TO-WITNESS-PUBKEY-HASH (P2WPKH)
AND PAY-TO-WITNESS-SCRIPT-HASH (P2WSH)

• These are part of Bitcoin’s Segregated Witness (SegWit) upgrade, designed to


improve scalability and reduce transaction size.
• Script execution is still fundamentally Bitcoin Script but optimized for SegWit
addresses.
Key Characteristics:
• P2WPKH: Similar to P2PKH but uses SegWit addresses and reduces data size.
• P2WSH: Similar to P2SH but uses SegWit, allowing for complex scripts while
benefiting from SegWit’s advantages.
Script Example:
• P2WPKH Locking Script (Witness Program): `OP_0 OP_20
<PubKeyHash>`
• P2WSH Locking Script (Witness Program): `OP_0 OP_20 <ScriptHash>`
P2WPKH - EXAMPLE

• Pay-to-Witness-PubKey-Hash (P2WPKH) is a
Bitcoin transaction type introduced with
Segregated Witness (SegWit).
• It simplifies and enhances Bitcoin transactions
by segregating witness data (signatures and
public keys) from the main transaction data,
which improves scalability and efficiency.
P2WPKH - EXAMPLE
• Locking Script (Witness Program)
• In a P2WPKH transaction, the locking script, also known as the "witness
program," uses a specific format to define the conditions for spending the
funds.
• Locking Script Format:
• OP_0 OP_20 <PubKeyHash>
• OP_0: Indicates the start of a witness program with a 20-byte hash. It is used
in P2WPKH and P2WSH.
• OP_20: Specifies that the witness program will use a 20-byte (160-bit) hash.
• <PubKeyHash>: The 20-byte hash of the public key, computed using SHA-
256 followed by RIPEMD-160.
• Example: Let's assume the public key hash is
89abcdefabbaabbaabbaabbaabbaabbaabbaabba.
• Locking Script (Witness Program):
• OP_0 OP_20 89abcdefabbaabbaabbaabbaabbaabbaabbaabba
P2WPKH - EXAMPLE

• Spending a P2WPKH Transaction


• To spend a P2WPKH output, the unlocking script (witness data) must provide a valid
signature and the corresponding public key that matches the hash in the locking script.
• Unlocking Script (Witness Data) Format:
• <Signature> <PublicKey>
• <Signature>: A digital signature that proves ownership of the private key
corresponding to the public key.
• <PublicKey>: The public key corresponding to the public key hash in the locking script.
• Example: Assume the signature is 3045022100abcd... and the public key is 0234abcd....
• Unlocking Script (Witness Data):
• Copy code
• 3045022100abcd... 0234abcd...
P2WPKH – TRANSACTION
VALIDATION
• Stack Initialization: The unlocking script (witness data) is used to provide
the necessary data for validation. It is pushed onto the stack during the
execution of the script.
• Initial Stack:
• [3045022100abcd..., 0234abcd...]
Validation Steps:
• Check Public Key Hash: Compute the hash of the provided public key
using SHA-256 followed by RIPEMD-160.
• If the computed hash matches the <PubKeyHash> from the locking script,
the script continues to the next step.
• Verify Signature: Use the provided signature and public key to verify the
transaction data. This involves checking that the signature is valid for the
transaction data using the public key.
DATA RECORDED IN BLOCK

• 1. TXID: Unique identifier for the transaction.


• 2. Version Number: Indicates the transaction format.
• 3. Inputs: Previous transaction details, typically with an
empty ScriptSig for P2WPKH.
• 4. Witness Data: Contains the unlocking information, such
as the signature and public key.
• 5. Outputs: Specifies the transfer amount and conditions
for spending.
• 6. Locktime: The earliest time/block height for the
transaction to be confirmed.
DATA RECORDED IN BLOCK
3 . Inputs (Vin):

• Each input will include:

• Previous Transaction Hash (PrevTXID): The hash of the previous


transaction being spent.

• Output Index (Vout): The specific output in the previous transaction


being used as an input.

• ScriptSig: Typically empty for P2WPKH transactions.

• Sequence Number: A number to enable replacement of the transaction


before it is finalized.

• 4. Witness Data (Not directly recorded in the block but stored in


a separate witness structure):

• Witness Stack: Contains the unlocking script with the following


elements:
• Signature: The signature of the user authorizing the transaction.
• Public Key: The public key corresponding to the hashed public key
in the ScriptPubKey.
DATA RECORDED IN BLOCK
• 5. Outputs (Vout):
• Each output will include:
• Value: The amount of Bitcoin being
transferred (in satoshis).
• ScriptPubKey: Specifies the conditions for
spending the output, which will look like 0
<20-byte-key-hash> for P2WPKH
transactions.
• 6. Locktime:
• Specifies the earliest time or block height at
which the transaction can be added to the
blockchain.
OP_RETURN

• OP_RETURN is a special opcode that allows data to be embedded in a


transaction output. This data is provably unspendable.
Key Characteristics:
• Data Embedding: Used for storing small pieces of data on the Bitcoin
blockchain.
• Non-Spendable: Outputs with OP_RETURN cannot be spent, thus not
increasing the blockchain’s UTXO set.
Common Uses:
• Proof of Existence: Storing hashes of documents or other data for
timestamping and verification.
• Colored Coins: Implementing metadata or tokens on the Bitcoin
blockchain.
EXAMPLE :OP_RETURN

• 1. Transaction ID: 123456789abcdef


• 2. Inputs: [Address1, Address2]
• 3. Outputs:
• - Output 1: Address3, 0.5 BTC
• - Output 2: OP_RETURN, Data: "Hello, World!"
• Output 1 is a standard spendable output where 0.5 BTC is sent to
Address3.
• Output 2 uses the OP_RETURN opcode, making it unspendable, and
includes the data "Hello, World!"
• The data embedded with OP_RETURN is typically encoded in
hexadecimal format and can be up to 80 bytes long. This data is
permanently stored on the blockchain and publicly visible
STORING DATA
• Bitcoin Script is not designed for general-purpose data
storage
• But rather for defining conditions under which Bitcoin
transactions can be unlocked and spent.
• This language is intentionally limited to avoid complexity
and ensure security.
• If you want to store data on the Bitcoin blockchain, it's
important to understand that this is typically done in a very
limited and cost-ineffective manner due to the constraints
and costs associated with blockchain storage.
USING OP_RETURN
• Bitcoin Script includes an OP_RETURN opcode that allows you
to embed a small amount of arbitrary data in a transaction.
• This is the most common way to store data on the Bitcoin
blockchain.
• Data Size: The OP_RETURN opcode allows you to store up to
80 bytes of data.
• Usage: This opcode is used to mark a transaction output as
non-spendable and to embed data in that output.
• OP_RETURN <data>
• bitcoin-cli createrawtransaction
"[{\"txid\":\"<txid>\",\"vout\":<vout>}]"
"{\"data\":\"<hex_encoded_data>\"}“
• <txid> and <vout> specify the input transaction and output
index you are spending.
DATA STORAGE
• Costs:CONSIDERATIONS
Storing data on the Bitcoin blockchain is expensive.
• The cost is proportional to the size of the transaction, and
since blockchain space is limited, storing large amounts of
data is generally impractical and costly.
• Privacy: Data stored on the blockchain is visible to
everyone. If the data contains sensitive information, this
could be a privacy concern.
• Use Cases: Typical use cases include embedding hashes of
documents, proving data existence, or associating metadata
with transactions.
ALTERNATIVES

• For storing larger or more private data, consider using


alternatives such as:
• Sidechains or Layer 2 Solutions: These can offer more
flexibility and lower costs for data storage.
• Dedicated Storage Solutions: Platforms like the
InterPlanetary File System (IPFS) can be used to store data
off-chain while storing just a reference or hash on the Bitcoin
blockchain.
• By using OP_RETURN judiciously and understanding the
implications of blockchain data storage, you can leverage
Bitcoin’s scripting capabilities for your needs while
considering the cost and privacy aspects.
TIMELOCKS

• Timelocks in Bitcoin Script are used to enforce


conditions based on time, determining when a
transaction can be spent or unlocked.
• They are crucial for creating more complex
financial agreements and smart contract-like
behaviors.
• Types of Timelocks
• Absolute Timelock (nLockTime)
• Relative Timelock (OP_CHECKLOCKTIMEVERIFY or OP_CLTV)
Absolute Timelock (nLockTime)
• The nLockTime field in a Bitcoin transaction specifies a point in time
after which the transaction can be included in a block. This is used to
enforce a delay before the transaction can be mined.
• Setting nLockTime: You set nLockTime when creating a transaction.
The transaction will only be valid after the specified lock time. This can
be a block height or a Unix timestamp.
• Creating a Transaction with nLockTime:
• Set the nLockTime: When constructing the transaction, set the nLockTime field in
the raw transaction to the desired value.

• bitcoin-cli createrawtransaction '[{"txid":"<txid>","vout":<vout>}]'


'{"<address>":<amount>}‘
• After creating the raw transaction, use bitcoin-cli to set the
nLockTime:
• bitcoin-cli signrawtransactionwithkey <raw_transaction>
"[\"<private_key>\"]" '[{"txid":"<txid>","vout":<vout>}]' 0
<nLockTime>
RELATIVE TIME LOCK
(OP_CHECKLOCKTIMEVERIFY OR OP_CLTV)

• OP_CHECKLOCKTIMEVERIFY (CLTV) is an opcode in Bitcoin Script that allows


you to enforce a condition based on the current block height or time
relative to when the transaction was created.
• <locktime> OP_CHECKLOCKTIMEVERIFY OP_DROP <pubkey> OP_CHECKSIG
• <locktime>: The earliest time (block height or timestamp) when the
transaction can be spent.
• OP_CHECKLOCKTIMEVERIFY: Checks that the current block height or
time is greater than or equal to the specified locktime.
• OP_DROP: Removes the locktime value from the stack.
• <pubkey>: The public key that can spend the output once the locktime
condition is met.
• OP_CHECKSIG: Verifies the signature of the transaction.
• Suppose you want to lock the funds until block 700,000:
• 700000 OP_CHECKLOCKTIMEVERIFY OP_DROP <pubkey> OP_CHECKSIG
CONSIDERATIONS

• Broadcast:
• bitcoin-cli sendrawtransaction <signed_transaction>

• Security: Timelocks are crucial for creating secure, time-based


conditions in Bitcoin transactions, but make sure to test
thoroughly.
• Complexity: Using timelocks increases script complexity. Ensure
that you understand the implications and test your scripts
thoroughly.
• Cost: Adding complex scripts to transactions might increase
their size, impacting transaction fees.
HASH TIME LOCKED
CONTRACTS
• In Bitcoin scripting, HTLCs combine hash locks and
time locks to create these conditional contracts.
• Hash Time-Locked Contracts (HTLCs) are a type of
smart contract used to ensure that a transaction
will be completed only if a certain condition is met
within a specific time frame.
• HTLCs are commonly used in various applications,
such as payment channels and atomic swaps.
COMPONENTS AND
STRUCTURE
• Hash Lock: A hash lock ensures that funds can only
be spent if a certain pre-image (a piece of data) is
revealed, which, when hashed, matches a specified
hash value.
• Time Lock: A time lock ensures that if the hash lock
condition is not met, the funds can still be refunded
after a certain time has passed.
• An HTLC typically involves a combination of
OP_CHECKLOCKTIMEVERIFY (CLTV) and OP_HASH160
or OP_CHECKSIG opcodes.
EXAMPLE SCRIPT
• Create a simple HTLC script where:
• The recipient can claim the funds if they provide a pre-image that hashes to
a specific hash.
• The sender can reclaim the funds after a timeout if the recipient hasn’t
claimed the funds.
• OP_IF
• <hash> OP_HASH160 <pubkey_hash> OP_EQUAL
• OP_ELSE
• <locktime> OP_CHECKLOCKTIMEVERIFY OP_DROP <sender_pubkey>
OP_CHECKSIG
• OP_ENDIF
• <hash>: The hash of the pre-image.<pubkey_hash>: The hash of the
recipient’s public key. <locktime>: The block height or timestamp after which
the sender can reclaim the funds. <sender_pubkey>: The public key of the
sender.
CONSIDERATIONS

• Complexity: HTLCs add complexity to Bitcoin


scripts. Make sure to test thoroughly.
• Security: Ensure the hash and locktime values
are securely handled.
• Costs: HTLCs can increase transaction size and
fees.
ATOMIC SWAPS

• Atomic swaps are a method for exchanging


cryptocurrencies between different blockchains without
the need for a trusted intermediary.
• They rely on Hash Time-Locked Contracts (HTLCs) to
ensure that both parties either complete the swap or get
a refund if one party fails to fulfill their side of the
agreement.
• Hash Lock: Both parties agree on a secret hash. The
hash of this secret will be used in both contracts.
• Time Lock: If one party doesn’t complete their side of
the deal, the other party can reclaim their funds after a
timeout period.
IMPLEMENTATION
• Create HTLC Scripts

• Both parties create HTLCs to lock their funds. The HTLC


script must be able to:
• Lock funds with a hash condition.

• Allow for a refund if the hash condition is not met within


a specified time frame.
• Execute the Swap

• Both parties need to perform the following steps:

• Party A locks their Bitcoin using HTLC.

• Party B locks their altcoin using an HTLC script similar


to Bitcoin’s but for their respective blockchain.
• Party A reveals the secret to Party B, allowing Party B
to claim the Bitcoin.
• Party B reveals the secret to Party A, allowing Party A
to claim the altcoin.
EXAMPLE

• Party A – selling Bitcoin from bitcoin network


• OP_IF
• <hash> OP_HASH160 <pubkey_hash>
OP_EQUAL
• OP_ELSE
• <locktime> OP_CHECKLOCKTIMEVERIFY
OP_DROP <partyA_pubkey> OP_CHECKSIG
OP_ENDIF
CONSIDERATIONS

• Cross-Chain Compatibility: The scripts and their


implementation vary between blockchains. For non-Bitcoin
blockchains, you need to implement similar HTLC logic in the
respective blockchain’s scripting or smart contract language.
• Security: Ensure that the secret is kept secure and only
revealed to the intended party. Mismanagement of the secret
can result in a failed swap.
• Testing: Before executing an atomic swap with real funds,
thoroughly test the process on testnets or with small amounts.
PAYMENT CHANNELS IN LIGHTNING
NETWORK
• Bitcoin's scripting language and the concept of
payment channels, which are a key component
of the Lightning Network.
• Payment channels enable off-chain
transactions
• Allows parties to transact quickly and with
lower fees while still using the security of the
Bitcoin network.
PAYMENT CHANNELS AND SCRIPT
USAGE
• Payment channels utilize scripts to enable two parties to
transact off-chain while still settling on the blockchain , Various
actions in Payment channels
• 1. Channel Funding:
• To open a payment channel, both parties create a multi-signature (multi-
sig) address. Typically, this is a 2-of-2 multi-sig address where both parties
need to sign off to spend the funds.
• The script for a 2-of-2 multi-sig address might look like this
• 2 <PublicKey1> <PublicKey2> 2 OP_CHECKMULTISIG
• This script means that to spend the funds, both signatures from the
provided public keys are required.
PAYMENT CHANNELS AND SCRIPT
•USAGE
Channel State Updates:
• Inside the channel, transactions are updated off-chain. Each state
(transaction) reflects the current balance distribution between the
parties.
• When updating the channel state, the new state is signed by both
parties. These state updates are not broadcast to the Bitcoin network
immediately but are kept off-chain.
• Channel Closing:

• To close the channel, the latest state (which includes the final
balance distribution) is broadcasted to the Bitcoin network.
• The closing transaction is a standard transaction, which can be either
cooperative or unilateral:
• Cooperative Close: Both parties agree on the final state and
broadcast the closing transaction.
• Unilateral Close: One party broadcasts the last known state,
which might be done in case of a dispute.
PAYMENT CHANNELS AND SCRIPT
USAGE
Revocation Scripts:
• To prevent fraud, revocation scripts are used to make older states
invalid. Each party can publish a transaction that penalizes the other
party if they try to use an outdated state.
• A typical revocation script involves a time-lock or a penalty mechanism
that allows the honest party to reclaim the funds in case of a dispute.
Lightning Network
• The Lightning Network builds upon these concepts and provides
additional features like hash time-locked contracts (HTLCs) to facilitate
multi-hop payments across a network of payment channels.
• HTLCs are used to ensure that payments are either fully completed or
refunded if not settled.

You might also like