Skip to content

Latest commit

 

History

History
321 lines (239 loc) · 10.1 KB

File metadata and controls

321 lines (239 loc) · 10.1 KB

Bitcoin Transaction Scripts Project

Overview

This project implements Bitcoin transaction scripts including Pay-To-Public-Key-Hash (P2PKH), custom scripts, multisignature transactions, and a cross-chain atomic swap protocol. The implementation demonstrates fundamental Bitcoin scripting concepts and advanced techniques for trustless cryptocurrency exchanges across different blockchains.

Project Structure

Bitcoin_transactions/
├── Starter Code/
│   ├── Q1.py              # P2PKH implementation
│   ├── Q2a.py             # Custom script creation
│   ├── Q2b.py             # Custom script redemption
│   ├── Q3a.py             # Multisig script creation (2-of-3)
│   ├── Q3b.py             # Multisig script redemption
│   ├── Q4.py              # Atomic swap script implementations
│   ├── alice.py           # Alice's atomic swap functions
│   ├── bob.py             # Bob's atomic swap functions
│   ├── swap.py            # Main atomic swap orchestration
│   ├── lib/
│   │   ├── config.py      # Configuration and keys
│   │   ├── utils.py       # Utility functions
│   │   ├── keygen.py      # Key generation utility
│   │   └── split_test_coins.py  # Coin splitting utility
│   ├── docs/
│   │   ├── Q4design_doc.txt     # Design document for Q4
│   │   └── transactions.py      # Additional transaction helpers
│   ├── requirements.txt   # Python dependencies
│   ├── README.md         # This file
│   └── TESTING.md        # Testing guide
└── bitcoin.pdf           # Project specification

Features Implemented

Question 1: Pay-To-Public-Key-Hash (P2PKH)

P2PKH_scriptPubKey:

  • Implements the standard Bitcoin P2PKH locking script
  • Uses OP_DUP, OP_HASH160, OP_EQUALVERIFY, and OP_CHECKSIG opcodes
  • Locks coins to a specific public key hash

P2PKH_scriptSig:

  • Provides the unlocking script for P2PKH transactions
  • Supplies signature and public key to unlock funds

Question 2: Custom Script with SHA-256 Hash Check

Q2a - Script Creation:

  • Creates a custom script that requires two identical inputs
  • Uses SHA-256 hashing to verify both inputs hash to the same value
  • Ensures the two inputs are equal using OP_2DUP and OP_EQUAL

Q2b - Script Redemption:

  • Demonstrates how to redeem the custom script
  • Provides two copies of the secret value "secret"

Question 3: Multi-Signature Transaction (2-of-3)

Q3a - Multisig Creation:

  • Implements a 2-of-3 multisignature script
  • Requires any 2 out of 3 signatures to unlock funds
  • Uses OP_CHECKMULTISIG opcode

Q3b - Multisig Redemption:

  • Shows how to redeem a multisig transaction
  • Provides 2 valid signatures (accounting for CHECKMULTISIG bug with OP_0)

Question 4: Cross-Chain Atomic Swap

coinExchangeScript:

  • Implements a conditional script with two redemption paths:
    1. Secret Hash Path (OP_IF): Recipient can redeem by providing the secret x where SHA256(x) = hash_of_secret
    2. Refund Path (OP_ELSE): Both parties can cooperatively refund after timelock using 2-of-2 multisig

coinExchangeScriptSig1:

  • Script signature for the recipient to redeem using the secret
  • Provides recipient signature, secret, and OP_TRUE to trigger IF branch

coinExchangeScriptSig2:

  • Script signature for refund scenario
  • Provides both sender and recipient signatures and OP_FALSE to trigger ELSE branch

Atomic Swap Protocol:

  • Alice wants to exchange BTC on Testnet3 for Bob's BTC on BCY Testnet
  • Both parties create symmetric transactions with hash-locked outputs
  • Alice knows secret x; only she can initiate the swap
  • Once Alice redeems, x is revealed on blockchain, allowing Bob to redeem
  • If Alice doesn't redeem, both parties can safely recover their coins after timelock

Installation

Prerequisites

  • Python 3.7 or higher
  • pip (Python package installer)

Setup

  1. Clone or download the project:
cd $HOME/Bitcoin_transactions/Starter\ Code/
  1. Install required dependencies:
pip install -r requirements.txt

The main dependencies are:

  • python-bitcoinlib: Bitcoin protocol implementation
  • requests: HTTP library for API calls

Configuration

Before running the scripts, you need to configure your Bitcoin addresses and private keys in lib/config.py:

  1. Generate keys for Questions 1-3:
python lib/keygen.py
  1. Get test coins:
  1. Update lib/config.py:
my_private_key = CBitcoinSecret('your_testnet_private_key_here')
  1. For Question 4, configure both BTC and BCY keys:
  • Generate BTC testnet keys with keygen.py
  • Generate BCY testnet keys using BlockCypher API:
curl -X POST https://api.blockcypher.com/v1/bcy/test/addrs?token=YOUR_TOKEN

Usage

Question 1: P2PKH Transaction

python Q1.py

Before running, set the parameters in Q1.py:

  • amount_to_send: Amount minus transaction fee (in BTC)
  • txid_to_spend: Transaction ID of the UTXO you're spending
  • utxo_index: Output index of the UTXO (usually 0 or 1)

Question 2: Custom Script

Create custom script transaction:

python Q2a.py

Redeem custom script transaction:

python Q2b.py

Make sure to update the transaction parameters in each file.

Question 3: Multisig Transaction

Create multisig transaction:

python Q3a.py

First, generate three customer key pairs using keygen.py and update Q3a.py with these keys.

Redeem multisig transaction:

python Q3b.py

Question 4: Atomic Swap

Configure the swap parameters in Q4.py:

alice_txid_to_spend = "your_btc_txid"
alice_utxo_index = 0
alice_amount_to_send = 0.001

bob_txid_to_spend = "your_bcy_txid"
bob_utxo_index = 0
bob_amount_to_send = 0.001

broadcast_transactions = True  # Set to True to actually broadcast
alice_redeems = True  # Set to False to test refund path

Run the atomic swap:

python swap.py

The script will:

  1. Alice creates her swap transaction on BTC testnet
  2. Bob creates his swap transaction on BCY testnet
  3. Either:
    • Alice redeems Bob's coins (revealing secret), then Bob redeems Alice's coins
    • OR both parties wait for timelock and cooperatively refund

Technical Details

Bitcoin Script Opcodes Used

  • OP_DUP: Duplicates top stack item
  • OP_HASH160: Hashes top stack item with SHA-256 then RIPEMD-160
  • OP_SHA256: Hashes top stack item with SHA-256
  • OP_EQUALVERIFY: Verifies top two stack items are equal
  • OP_CHECKSIG: Verifies signature against public key
  • OP_CHECKMULTISIG: Verifies multiple signatures
  • OP_IF/OP_ELSE/OP_ENDIF: Conditional execution
  • OP_2DUP: Duplicates top 2 stack items
  • OP_SWAP: Swaps top 2 stack items
  • OP_VERIFY: Marks transaction invalid if top stack is false

Security Considerations

  1. Private Key Management: Never commit private keys to version control
  2. Test Networks Only: This code is for testnet use only
  3. Transaction Fees: Always account for appropriate transaction fees
  4. Timelock Values: Ensure alice_locktime > bob_locktime in atomic swaps
  5. Secret Generation: Use cryptographically secure random values for secrets

Network Information

BTC Testnet3

BCY Testnet (BlockCypher)

  • Faucet API:
curl -d '{"address": "YOUR_ADDRESS", "amount": 1000000}' \
  https://api.blockcypher.com/v1/bcy/test/faucet?token=YOUR_TOKEN

Troubleshooting

Common Issues

  1. "Insufficient funds" error:

    • Ensure you have test coins from the faucet
    • Check that amount_to_send is less than available balance
    • Account for transaction fees (typically 0.0001 BTC)
  2. "Script verification failed" error:

    • Verify scriptPubKey and scriptSig are correctly implemented
    • Check that signatures are created with correct parameters
    • Ensure public keys match the addresses used
  3. "Transaction already in block chain" error:

    • You're trying to spend a UTXO that's already been spent
    • Get a new UTXO from the faucet
  4. "Missing inputs" error:

    • Verify the txid_to_spend is correct
    • Check that utxo_index is valid (usually 0 or 1)
    • Confirm the UTXO hasn't been spent

Debugging Tips

  1. Enable verbose output:

    • Check API responses for detailed error messages
    • Use print statements to verify script contents
  2. Verify transactions:

    • Use blockchain explorers to verify transaction status
    • Check that previous transactions are confirmed
  3. Test with small amounts:

    • Use minimal amounts when testing
    • Get multiple small UTXOs for repeated testing

Design Decisions

Q4 Atomic Swap Design

The atomic swap implementation uses a hash-timelock contract (HTLC) approach:

  1. Hash Lock: Ensures only the party with the secret can redeem unilaterally
  2. Time Lock: Provides a refund mechanism if the swap doesn't complete
  3. 2-of-2 Multisig: Requires cooperation for refunds, preventing theft
  4. Asymmetric Timelocks: Alice has more time than Bob, ensuring fairness

See docs/Q4design_doc.txt for detailed design rationale.

References

License

This project is for educational purposes.

Contributors

  • Original framework by Max Spero
  • Edited by Belce Dogru and Blake Pagon

Support

For questions or issues:

  1. Check the TESTING.md file for testing procedures
  2. Review the design document in docs/Q4design_doc.txt
  3. Consult Bitcoin Script documentation
  4. Check BlockCypher API status for network issues