brbitcoin


Namebrbitcoin JSON
Version 0.1.0 PyPI version JSON
download
home_pageNone
SummaryNone
upload_time2025-01-25 06:28:14
maintainerNone
docs_urlNone
authorLucas Oliveira
requires_python<4.0,>=3.9
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 🇧🇷 BrBitcoin Python SDK

> [!NOTE]
> This SDK is under active development. Report issues on [GitHub](https://github.com/youruser/brbitcoin).

> [!WARNING]
>  Always test with Regtest before mainnet usage.

## Features

- **Automatic Zeroization**: Sensitive data wiped from memory using context managers
- **Multi-Layer Security**: Hierarchical deterministic wallets with encrypted backups
- **Network Agnostic**: Supports Regtest/Testnet/Mainnet via multiple backends
- **Full RPC Support**: Direct access to Bitcoin Core JSON-RPC API

## 📦 Installation

### Via Poetry (Recommended)

```bash
poetry add brbitcoin
```

### Via pip

```bash
pip install brbitcoin
```

## 🚀 Quick Start

### 1. Wallet Management

```python
from brbitcoin import Wallet, Network

# Create random HD wallet (testnet by default)
with Wallet.create(network=Network.TESTNET) as wallet:
    print(f"New address: {wallet.address}")
    # Always store encrypted backups
    wallet.export_encrypted("wallet.bak", password=os.environ["WALLET_PASS"])

# Import from existing hex private key
with Wallet.from_private_key("beefcafe...") as wallet:
    print(f"Imported address: {wallet.address}")

# Create from BIP39 mnemonic
mnemonic = "absorb lecture valley scissors giant evolve planet rotate siren chaos"
with Wallet.from_mnemonic(mnemonic, network=Network.MAINNET) as wallet:
    print(f"Mainnet address: {wallet.address}")
```

### 2. Blockchain Interaction

#### 2.1 Address Information

```python
from brbitcoin import Wallet, get_address_info

info = get_address_info("bc1q...", Network.MAINNET)
print(f"Balance: {info.balance} satoshis")
print(f"UTXOs: {len(info.utxos)}")

with Wallet(network=Network.TESTNET) as wallet:
    print(f"Wallet balance: {wallet.balance} sats")
```

#### 2.2 Transaction Inspection

```python
from brbitcoin import Wallet, get_transaction

tx = get_transaction("aabb...", Network.REGTEST)
print(f"Confirmations: {tx.confirmations}")
for output in tx.outputs:
    print(f"Output value: {output.value}")

with Wallet.from_private_key("beef...") as wallet:
    utxos = wallet.utxos()
    for utxo in utxos:
        print(f"UTXO: {utxo.txid}:{utxo.vout} - {utxo.value} sats")
```

#### 2.3 Block Exploration

```python
from brbitcoin import get_block

block = get_block_by_hash("000000000019d6...", Network.MAINNET)
print(f"The Block has {len(block.txn)} transactions")

genesis = get_block_by_number(0, Network.MAINNET)
print(f"Genesis block timestamp: {genesis.timestamp}")
```

### 3. Transaction Building

#### 3.1 High-Level (Recommended)

```python
from brbitcoin import Wallet, Fee

RECEIVER = "tb123..."
AMOUNT = 0.001 # BTC

with Wallet(network=Network.REGTEST) as wallet:
    txid = wallet.send(to=RECEIVER, amount=AMOUNT)

    print(f"Broadcasted TX ID: {txid}")
```

#### 3.2 Mid-Level Control

```python
from brbitcoin import Wallet, Transaction, to_btc

RECEIVER = "tb123..."
AMOUNT = 100_000 # Satoshis == 0.001 BTC
FEE = 500 # Satoshi == 0.0000005 BTC

with Wallet.from_private_key("fff...") as wallet:
    utxos = wallet.utxos()

    txid = (
        Transaction(network=wallet.network)
        .add_input(utxos[0])
        .add_output(RECEIVER, to_btc(AMOUNT))
        .fee(to_btc(FEE))
        # .estimate_fee()
        .sign(wallet)
        .broadcast()
    )
    print(f"Broadcasted TX ID: {txid}")
```

#### 3.3 Low-Level Scripting

```python
from brbitcoin import Wallet, Script, Transaction

# Create a P2SH lock script
lock_script = (
    Script()
    .push_op_dup()
    .push_op_hash_160()
    .push_bytes(pubkey_hash)
    .push_op_equal_verify()
    .push_op_check_sig()
)

with Wallet(network=Network.REGTEST) as wallet:
    inputs = wallet.utxos()
    AMOUNT = 0.0001 # BTC
    txid = (
        Transaction(network=Network.REGTEST)
        .add_input(inputs[0])
        .add_output_script(lock_script, AMOUNT)
        .sign(wallet)
        .broadcast()
    )

    print(f"Broadcasted TX ID: {txid}")
```

### 4. Security Practices

#### 4.1 Encrypted Private Key Backup

```python
from brbitcoin import Wallet

with Wallet.create() as wallet:
    wallet.export_encrypted(path="wallet.json",password="pass123")
```

#### 4.2 Restore from Encrypted backup

```python
from brbitcoin import Wallet

with Wallet.from_encrypted("wallet.json", password="pass123") as wallet:
    print(f"Recovered address: {w.address}")
```

#### 4.3 Zeroization Guarantees

```python
# Keys are wiped:
# - When context manager exits
# - After signing/broadcast
# - On object destruction
with Wallet.from_private_key("c0ffee...") as wallet:
    txid = wallet.send("bc1q...", 0.001)
    # Key no longer in memory here
```

### 5. Node Management

#### 5.1 Network Configuration

```python
from brbitcoin import ClientNode

# Connect to Bitcoin Core
client = ClientNode(
    network=Network.REGTEST,
    rpc_user="user",
    rpc_password="pass",
    host="localhost",
    port=18444
)
```

#### 5.2 Node Operations

```python
# Get blockchain info
info = client.get_blockchain_info()
print(f"Blocks: {info.blocks}, Difficulty: {info.difficulty}")

# Generate regtest blocks
if client.network == Network.REGTEST:
    blocks = client.generate_to_address(10, "bcrt1q...")
    print(f"Mined block: {blocks[-1]}")

# Get fee estimates
fees = electrum_client.estimate_fee(targets=[1, 3, 6])
print(f"1-block fee: {fees[1]} BTC/kvB")
```

#### 5.3 Direct RPC Access

```python
# Raw RPC commands
mempool = client.rpc("getmempoolinfo")
print(f"Mempool size: {mempool['size']}")

# Batch requests
results = client.batch_rpc([
    ("getblockcount", []),
    ("getblockhash", [0]),
    ("getblockheader", ["000000000019d6..."])
])
print(f"Block count: {results[0]}")
```


#### 5.4 Bitcoin Core RPC Command Reference (Partial)

| Category       | Command                | Description                   | Example Usage                                                      |
| -------------- | ---------------------- | ----------------------------- | ------------------------------------------------------------------ |
| **Blockchain** | `getblockchaininfo`    | Returns blockchain state      | `getblockchaininfo`                                                |
|                | `getblock`             | Get block data by hash/height | `getblock "blockhash" 2`                                           |
|                | `gettxoutsetinfo`      | UTXO set statistics           | `gettxoutsetinfo`                                                  |
| **Wallet**     | `listtransactions`     | Wallet transaction history    | `listtransactions "*" 10 0`                                        |
|                | `sendtoaddress`        | Send to Bitcoin address       | `sendtoaddress "addr" 0.01`                                        |
|                | `backupwallet`         | Backup wallet.dat             | `backupwallet "/path/backup.dat"`                                  |
| **Network**    | `getnetworkinfo`       | Network connections/version   | `getnetworkinfo`                                                   |
|                | `addnode`              | Manage peer connections       | `addnode "ip:port" "add"`                                          |
| **Mining**     | `getblocktemplate`     | Get mining template           | `getblocktemplate {"rules":["segwit"]}`                            |
|                | `submitblock`          | Submit mined block            | `submitblock "hexdata"`                                            |
| **Utility**    | `validateaddress`      | Validate address              | `validateaddress "bc1q..."`                                        |
|                | `estimatesmartfee`     | Estimate transaction fee      | `estimatesmartfee 6`                                               |
| **Raw Tx**     | `createrawtransaction` | Create raw transaction        | `createrawtransaction '[{"txid":"...","vout":0}]' '{"addr":0.01}'` |
|                | `signrawtransaction`   | Sign raw transaction          | `signrawtransaction "hex"`                                         |
| **Control**    | `stop`                 | Shut down node                | `stop`                                                             |
|                | `uptime`               | Node uptime                   | `uptime`                                                           |

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "brbitcoin",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.9",
    "maintainer_email": null,
    "keywords": null,
    "author": "Lucas Oliveira",
    "author_email": "olivmath@protonmail.com",
    "download_url": "https://files.pythonhosted.org/packages/cf/15/5afc2e7bfb1e79727791a285f245d540f5df40c963f6c42830e45df4023f/brbitcoin-0.1.0.tar.gz",
    "platform": null,
    "description": "# \ud83c\udde7\ud83c\uddf7 BrBitcoin Python SDK\n\n> [!NOTE]\n> This SDK is under active development. Report issues on [GitHub](https://github.com/youruser/brbitcoin).\n\n> [!WARNING]\n>  Always test with Regtest before mainnet usage.\n\n## Features\n\n- **Automatic Zeroization**: Sensitive data wiped from memory using context managers\n- **Multi-Layer Security**: Hierarchical deterministic wallets with encrypted backups\n- **Network Agnostic**: Supports Regtest/Testnet/Mainnet via multiple backends\n- **Full RPC Support**: Direct access to Bitcoin Core JSON-RPC API\n\n## \ud83d\udce6 Installation\n\n### Via Poetry (Recommended)\n\n```bash\npoetry add brbitcoin\n```\n\n### Via pip\n\n```bash\npip install brbitcoin\n```\n\n## \ud83d\ude80 Quick Start\n\n### 1. Wallet Management\n\n```python\nfrom brbitcoin import Wallet, Network\n\n# Create random HD wallet (testnet by default)\nwith Wallet.create(network=Network.TESTNET) as wallet:\n    print(f\"New address: {wallet.address}\")\n    # Always store encrypted backups\n    wallet.export_encrypted(\"wallet.bak\", password=os.environ[\"WALLET_PASS\"])\n\n# Import from existing hex private key\nwith Wallet.from_private_key(\"beefcafe...\") as wallet:\n    print(f\"Imported address: {wallet.address}\")\n\n# Create from BIP39 mnemonic\nmnemonic = \"absorb lecture valley scissors giant evolve planet rotate siren chaos\"\nwith Wallet.from_mnemonic(mnemonic, network=Network.MAINNET) as wallet:\n    print(f\"Mainnet address: {wallet.address}\")\n```\n\n### 2. Blockchain Interaction\n\n#### 2.1 Address Information\n\n```python\nfrom brbitcoin import Wallet, get_address_info\n\ninfo = get_address_info(\"bc1q...\", Network.MAINNET)\nprint(f\"Balance: {info.balance} satoshis\")\nprint(f\"UTXOs: {len(info.utxos)}\")\n\nwith Wallet(network=Network.TESTNET) as wallet:\n    print(f\"Wallet balance: {wallet.balance} sats\")\n```\n\n#### 2.2 Transaction Inspection\n\n```python\nfrom brbitcoin import Wallet, get_transaction\n\ntx = get_transaction(\"aabb...\", Network.REGTEST)\nprint(f\"Confirmations: {tx.confirmations}\")\nfor output in tx.outputs:\n    print(f\"Output value: {output.value}\")\n\nwith Wallet.from_private_key(\"beef...\") as wallet:\n    utxos = wallet.utxos()\n    for utxo in utxos:\n        print(f\"UTXO: {utxo.txid}:{utxo.vout} - {utxo.value} sats\")\n```\n\n#### 2.3 Block Exploration\n\n```python\nfrom brbitcoin import get_block\n\nblock = get_block_by_hash(\"000000000019d6...\", Network.MAINNET)\nprint(f\"The Block has {len(block.txn)} transactions\")\n\ngenesis = get_block_by_number(0, Network.MAINNET)\nprint(f\"Genesis block timestamp: {genesis.timestamp}\")\n```\n\n### 3. Transaction Building\n\n#### 3.1 High-Level (Recommended)\n\n```python\nfrom brbitcoin import Wallet, Fee\n\nRECEIVER = \"tb123...\"\nAMOUNT = 0.001 # BTC\n\nwith Wallet(network=Network.REGTEST) as wallet:\n    txid = wallet.send(to=RECEIVER, amount=AMOUNT)\n\n    print(f\"Broadcasted TX ID: {txid}\")\n```\n\n#### 3.2 Mid-Level Control\n\n```python\nfrom brbitcoin import Wallet, Transaction, to_btc\n\nRECEIVER = \"tb123...\"\nAMOUNT = 100_000 # Satoshis == 0.001 BTC\nFEE = 500 # Satoshi == 0.0000005 BTC\n\nwith Wallet.from_private_key(\"fff...\") as wallet:\n    utxos = wallet.utxos()\n\n    txid = (\n        Transaction(network=wallet.network)\n        .add_input(utxos[0])\n        .add_output(RECEIVER, to_btc(AMOUNT))\n        .fee(to_btc(FEE))\n        # .estimate_fee()\n        .sign(wallet)\n        .broadcast()\n    )\n    print(f\"Broadcasted TX ID: {txid}\")\n```\n\n#### 3.3 Low-Level Scripting\n\n```python\nfrom brbitcoin import Wallet, Script, Transaction\n\n# Create a P2SH lock script\nlock_script = (\n    Script()\n    .push_op_dup()\n    .push_op_hash_160()\n    .push_bytes(pubkey_hash)\n    .push_op_equal_verify()\n    .push_op_check_sig()\n)\n\nwith Wallet(network=Network.REGTEST) as wallet:\n    inputs = wallet.utxos()\n    AMOUNT = 0.0001 # BTC\n    txid = (\n        Transaction(network=Network.REGTEST)\n        .add_input(inputs[0])\n        .add_output_script(lock_script, AMOUNT)\n        .sign(wallet)\n        .broadcast()\n    )\n\n    print(f\"Broadcasted TX ID: {txid}\")\n```\n\n### 4. Security Practices\n\n#### 4.1 Encrypted Private Key Backup\n\n```python\nfrom brbitcoin import Wallet\n\nwith Wallet.create() as wallet:\n    wallet.export_encrypted(path=\"wallet.json\",password=\"pass123\")\n```\n\n#### 4.2 Restore from Encrypted backup\n\n```python\nfrom brbitcoin import Wallet\n\nwith Wallet.from_encrypted(\"wallet.json\", password=\"pass123\") as wallet:\n    print(f\"Recovered address: {w.address}\")\n```\n\n#### 4.3 Zeroization Guarantees\n\n```python\n# Keys are wiped:\n# - When context manager exits\n# - After signing/broadcast\n# - On object destruction\nwith Wallet.from_private_key(\"c0ffee...\") as wallet:\n    txid = wallet.send(\"bc1q...\", 0.001)\n    # Key no longer in memory here\n```\n\n### 5. Node Management\n\n#### 5.1 Network Configuration\n\n```python\nfrom brbitcoin import ClientNode\n\n# Connect to Bitcoin Core\nclient = ClientNode(\n    network=Network.REGTEST,\n    rpc_user=\"user\",\n    rpc_password=\"pass\",\n    host=\"localhost\",\n    port=18444\n)\n```\n\n#### 5.2 Node Operations\n\n```python\n# Get blockchain info\ninfo = client.get_blockchain_info()\nprint(f\"Blocks: {info.blocks}, Difficulty: {info.difficulty}\")\n\n# Generate regtest blocks\nif client.network == Network.REGTEST:\n    blocks = client.generate_to_address(10, \"bcrt1q...\")\n    print(f\"Mined block: {blocks[-1]}\")\n\n# Get fee estimates\nfees = electrum_client.estimate_fee(targets=[1, 3, 6])\nprint(f\"1-block fee: {fees[1]} BTC/kvB\")\n```\n\n#### 5.3 Direct RPC Access\n\n```python\n# Raw RPC commands\nmempool = client.rpc(\"getmempoolinfo\")\nprint(f\"Mempool size: {mempool['size']}\")\n\n# Batch requests\nresults = client.batch_rpc([\n    (\"getblockcount\", []),\n    (\"getblockhash\", [0]),\n    (\"getblockheader\", [\"000000000019d6...\"])\n])\nprint(f\"Block count: {results[0]}\")\n```\n\n\n#### 5.4 Bitcoin Core RPC Command Reference (Partial)\n\n| Category       | Command                | Description                   | Example Usage                                                      |\n| -------------- | ---------------------- | ----------------------------- | ------------------------------------------------------------------ |\n| **Blockchain** | `getblockchaininfo`    | Returns blockchain state      | `getblockchaininfo`                                                |\n|                | `getblock`             | Get block data by hash/height | `getblock \"blockhash\" 2`                                           |\n|                | `gettxoutsetinfo`      | UTXO set statistics           | `gettxoutsetinfo`                                                  |\n| **Wallet**     | `listtransactions`     | Wallet transaction history    | `listtransactions \"*\" 10 0`                                        |\n|                | `sendtoaddress`        | Send to Bitcoin address       | `sendtoaddress \"addr\" 0.01`                                        |\n|                | `backupwallet`         | Backup wallet.dat             | `backupwallet \"/path/backup.dat\"`                                  |\n| **Network**    | `getnetworkinfo`       | Network connections/version   | `getnetworkinfo`                                                   |\n|                | `addnode`              | Manage peer connections       | `addnode \"ip:port\" \"add\"`                                          |\n| **Mining**     | `getblocktemplate`     | Get mining template           | `getblocktemplate {\"rules\":[\"segwit\"]}`                            |\n|                | `submitblock`          | Submit mined block            | `submitblock \"hexdata\"`                                            |\n| **Utility**    | `validateaddress`      | Validate address              | `validateaddress \"bc1q...\"`                                        |\n|                | `estimatesmartfee`     | Estimate transaction fee      | `estimatesmartfee 6`                                               |\n| **Raw Tx**     | `createrawtransaction` | Create raw transaction        | `createrawtransaction '[{\"txid\":\"...\",\"vout\":0}]' '{\"addr\":0.01}'` |\n|                | `signrawtransaction`   | Sign raw transaction          | `signrawtransaction \"hex\"`                                         |\n| **Control**    | `stop`                 | Shut down node                | `stop`                                                             |\n|                | `uptime`               | Node uptime                   | `uptime`                                                           |\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": null,
    "version": "0.1.0",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6ab149ae5672bf725a82aa2ce3b6c551b6a28f85b7c0b216a3a0ef74f1c77bf6",
                "md5": "ad2147f861b722c0a3a3eba157c35bb8",
                "sha256": "22a8abd66e83876bba0b859f7b69358b6686551afefb6784b390ae1965c99ebc"
            },
            "downloads": -1,
            "filename": "brbitcoin-0.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ad2147f861b722c0a3a3eba157c35bb8",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.9",
            "size": 3861,
            "upload_time": "2025-01-25T06:28:10",
            "upload_time_iso_8601": "2025-01-25T06:28:10.836697Z",
            "url": "https://files.pythonhosted.org/packages/6a/b1/49ae5672bf725a82aa2ce3b6c551b6a28f85b7c0b216a3a0ef74f1c77bf6/brbitcoin-0.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "cf155afc2e7bfb1e79727791a285f245d540f5df40c963f6c42830e45df4023f",
                "md5": "95b5caac79d8a61ccbb50b88a1fbc6b8",
                "sha256": "d68dbc8adc32b229908c03890e560664fc9bb98315e7070ac5a35fb5394d05a6"
            },
            "downloads": -1,
            "filename": "brbitcoin-0.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "95b5caac79d8a61ccbb50b88a1fbc6b8",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.9",
            "size": 3578,
            "upload_time": "2025-01-25T06:28:14",
            "upload_time_iso_8601": "2025-01-25T06:28:14.368864Z",
            "url": "https://files.pythonhosted.org/packages/cf/15/5afc2e7bfb1e79727791a285f245d540f5df40c963f6c42830e45df4023f/brbitcoin-0.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-01-25 06:28:14",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "brbitcoin"
}
        
Elapsed time: 0.40604s