📜  发送和接收比特币(1)

📅  最后修改于: 2023-12-03 15:37:08.010000             🧑  作者: Mango

发送和接收比特币介绍

比特币作为一种去中心化的加密数字货币,已经被越来越多的人所认知和使用。在使用过程中,不可避免地会遇到发送和接收比特币的问题。本文将为程序员介绍如何在代码中实现发送和接收比特币。

发送比特币

发送比特币需要以下步骤:

  1. 创建钱包
  2. 配置网络
  3. 构建交易
  4. 签名交易
  5. 广播交易
创建钱包

在发送比特币之前,需要先创建钱包。比特币钱包可分为热钱包和冷钱包。热钱包是在线的钱包,冷钱包则是离线的钱包。这里以热钱包为例介绍钱包创建过程。

使用Python库创建钱包

Python库 pywallet 提供了创建比特币钱包的功能。可以通过以下代码创建一个新的比特币钱包:

from pywallet import wallet
seed = wallet.generate_mnemonic()
my_wallet = wallet.create_wallet(network='BTC', seed=seed, children=1)
print(my_wallet)

输出的信息中包含了钱包所在的地址,以及相应的私钥和公钥。需要注意的是,私钥是非常重要的信息,需要妥善保管,不要泄露出去。

配置网络

在发送比特币之前,需要配置网络。比特币网络有主网和测试网两种,测试网可以用来测试发送比特币的过程。

连接到比特币测试网络

可以通过以下代码连接到比特币测试网络:

from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException

rpc_user = ‘your_username’
rpc_password = ‘your_password’
rpc_port = 18332  # or 18334 for testnet
rpc_connection = AuthServiceProxy(f"http://{rpc_user}:{rpc_password}localhost:{rpc_port}/")

print(rpc_connection.getblockchaininfo())
构建交易

构建交易需要使用到钱包地址和接收地址。可以通过以下代码构建一个简单的比特币交易:

from bitcoin.core import b2x, serialize, CMutableTransaction, CMutableTxIn, CMutableTxOut, CTransaction, CTransactionOutPoint, Hash160

# 配置发送方、接收方、交易金额等信息
my_address = 'my_wallet_address'
receiving_address = 'receiving_wallet_address'
amount = 0.001
fee = 0.0001

# 获取UTXO
my_utxo = rpc_connection.listunspent(1, 9999, [my_address])
my_utxo = my_utxo[0]

# 构建TX_IN和TX_OUT
tx_ins = []
tx_ins.append(CMutableTxIn(CTransactionOutPoint(my_utxo['txid'], my_utxo['vout'])))
tx_outs = []
tx_outs.append(CMutableTxOut(amount, Hash160(receiving_address)))
tx_outs.append(CMutableTxOut(my_utxo['amount'] - amount - fee, Hash160(my_address)))

# 构建交易
tx = CMutableTransaction(tx_ins, tx_outs)

# 获取交易的hash
tx_hash = tx.GetTxid()

# 序列化交易
serialized_tx = b2x(serialize(tx))
签名交易

构建好交易之后,需要对交易进行签名。可以使用钱包库 bitcoin-tool 对交易进行签名:

import os
os.environ['PYCOIN_NATIVE'] = 'openssl'

from bitcoin.wallet import CBitcoinSecret
from bitcoin.core import x, Hash160, COIN, COutPoint, CTransaction, CTxOut, CMutableTransaction, CMutableTxOut, CMutableTxIn, Hash160
from bitcoin.core.script import CScript, OP_DUP, OP_HASH160, OP_EQUALVERIFY, OP_CHECKSIG

# 配置发送方和接收方等信息
my_address = 'my_wallet_address'
receiving_address = 'receiving_wallet_address'

# 获取输入和输出
utxo = rpc_connection.listunspent(0)
txin = CMutableTxIn(COutPoint(x(utxo[0]['txid'])[::-1], utxo[0]['vout']))
txout = CMutableTxOut(int(0.9 * utxo[0]['amount'] * COIN), CBitcoinAddress(receiving_address).to_scriptPubKey())

tx = CMutableTransaction([txin], [txout])
sighash = SignatureHash(txin.scriptSig, tx, 0, SIGHASH_ALL)

# 获取私钥
key = CBitcoinSecret.from_wif('my_private_key')
sig = key.sign(sighash) + bytes(bytearray([SIGHASH_ALL]))
txin.scriptSig = CScript([sig, key.pub])
txid = rpc_connection.sendrawtransaction(tx)
print("Transaction sent with ID:", txid)
广播交易

将交易广播到比特币网络中:

raw_tx = ...  # 这里指的是上一步签名后的交易

try:
    result = rpc_connection.sendrawtransaction(raw_tx)
    print(result)
except JSONRPCException as e:
    print(e.error)
接收比特币

接收比特币需要以下步骤:

  1. 获取比特币地址
  2. 监听交易
获取比特币地址

在接收比特币之前,需要获取比特币地址,可以使用之前创建的钱包中的地址。

监听交易

接收比特币需要监听比特币网络中的交易,可以使用以下代码监听比特币网络中的交易:

from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException

rpc_user = ‘your_username’
rpc_password = ‘your_password’
rpc_port = 18332  # or 18334 for testnet
rpc_connection = AuthServiceProxy(f"http://{rpc_user}:{rpc_password}localhost:{rpc_port}/")

def callback(tx_hash):
    print("Transaction received with id:", tx_hash)

# 监听比特币交易
rpc_connection.notified(["hashblock", "utxos"], callback)

这样就可以在比特币网络中监听到新的交易了。

总结

本文介绍了如何在Python中实现发送和接收比特币的过程。比特币作为新兴的数字货币,拥有广泛的应用场景和巨大的发展潜力。希望本文能为程序员们提供一些帮助,让他们更好地理解比特币的运作原理和实现方式。