Quick Example¶
Coinbits includes a basic client example for interacting on the peer-to-peer network. Here’s an example of a client that extends BitcoinClient and requests information on a block hash:
from coinbits.client import BitcoinClient
from coinbits.protocol.serializers import GetBlocks
class MyClient(BitcoinClient):
def message_received(self, message_header, message):
print "Got a message:", message_header.command, message
super(MyClient, self).message_received(message_header, message)
def send_message(self, message):
print "Sending a message:", str(message)
super(MyClient, self).send_message(message)
def connected(self):
hash = int('00000000000000000f69e991ee47a3536770f5d452967ec7edeb8d8cb28f9f28', 16)
gh = GetBlocks([hash])
self.send_message(gh)
def handle_inv(self, message_header, message):
print "Got some inventory:", message
MyClient("bitcoin.sipa.be").loop()
The connected method will be called as soon as the client has connected and finished handshaking. The serializers module contains all of the messages that can be serialized on the network, like the GetBlocks message command (described here). In this case, the send_message and message_received methods have been overwritten just for debugging. The handle_inv method is an example of the method dispatch - any message command type can have an associated handle_* method that will be called whenever a message of that type is received.
Sending a Transaction¶
Creating a transaction and sending it on the network is pretty straightforward. All you need to know is the private key that will be “sending” the money, the receipient’s address, and the output transaction to use as the input for this transaction. Here’s an example that sends 2M Satoshis after connecting to the P2P network:
from coinbits.client import BitcoinClient
from coinbits.txns.keys import PrivateKey
from coinbits.txns.wallet import Teller
from coinbits.protocol.serializers import OutPoint
class MyClient(BitcoinClient):
def connected(self):
# build a teller that will spend from the given private key
key = PrivateKey('e1385343f7ea362b0de7e5772a6c766d44ce4bf69e1380381630bf1892c638d5')
teller = Teller(key)
# specify the origin transaction hash and output index to use for this transaction's input
hexouthash = '8ed9e37a3c585ad2b28ebc9a7a76ff0bf250bd4a1d19cb42f8d29d62da8d3e67'
outpoint = OutPoint()
outpoint.out_hash = int(hexouthash, 16)
outpoint.index = 0
# pay 2M Satoshis to 1wYiNC2EERnKPWP7QbvWGEfNprtHg1bsz
tx = teller.make_standard_tx(outpoint, '1wYiNC2EERnKPWP7QbvWGEfNprtHg1bsz', 2000000)
print "New transaction's hash:", tx.calculate_hash()
self.send_message(tx)
def handle_inv(self, message_header, message):
print "Got some inventory:", message
for txn in message.inventory:
print txn
MyClient("bitcoin.sipa.be").loop()