''' Implementation of Bitcoin's p2p protocol ''' from __future__ import division import hashlib import random import struct import time import traceback from twisted.internet import protocol, reactor from . import data as bitcoin_data import p2pool.util class BaseProtocol(protocol.Protocol): def connectionMade(self): self.dataReceived = p2pool.util.DataChunker(self.dataReceiver()) def dataReceiver(self): while True: start = '' while start != self._prefix: start = (start + (yield 1))[-len(self._prefix):] command = (yield 12).rstrip('\0') length, = struct.unpack('= 12: raise ValueError('command too long') if self.use_checksum: checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] else: checksum = '' data = self._prefix + struct.pack('<12sI', command, len(payload)) + checksum + payload self.transport.write(data) #print 'SEND', command, payload2 def __getattr__(self, attr): prefix = 'send_' if attr.startswith(prefix): command = attr[len(prefix):] return lambda **payload2: self.sendPacket(command, payload2) #return protocol.Protocol.__getattr__(self, attr) raise AttributeError(attr) class Protocol(BaseProtocol): def __init__(self, testnet=False): if testnet: self._prefix = 'fabfb5da'.decode('hex') else: self._prefix = 'f9beb4d9'.decode('hex') version = 0 @property def use_checksum(self): return self.version >= 209 message_version = bitcoin_data.ComposedType([ ('version', bitcoin_data.StructType('