Skip to content

Instantly share code, notes, and snippets.

@ahmedbodi
Last active July 27, 2020 18:42
Show Gist options
  • Save ahmedbodi/c19eae5afddb72348a53d7b71b185bae to your computer and use it in GitHub Desktop.
Save ahmedbodi/c19eae5afddb72348a53d7b71b185bae to your computer and use it in GitHub Desktop.
import struct
import socket
import time
import hashlib
import random
from p2p.encoding import ser_string
magic = bytes.fromhex("f9beb4d9")
class CAddress(object):
def __init__(self):
self.nTime = int(time.time())
self.nServices = 1
self.pchReserved = b"\x00" * 10 + b"\xff" * 2
self.ip = "0.0.0.0"
self.port = 0
def deserialize(self, f):
self.nTime = struct.unpack(b"<I", f.read(4))[0]
self.nServices = struct.unpack(b"<Q", f.read(8))[0]
self.pchReserved = f.read(12)
self.ip = socket.inet_ntoa(f.read(4))
self.port = struct.unpack(b">H", f.read(2))[0]
def serialize(self):
r = b""
r += struct.pack(b"<I", self.nTime)
r += struct.pack(b"<Q", self.nServices)
r += self.pchReserved
r += socket.inet_aton(self.ip)
r += struct.pack(b">H", self.port)
return r
def __repr__(self):
return "CAddress(nTime=%d nServices=%i ip=%s port=%i)" % (self.nTime, self.nServices, self.ip, self.port)
class VersionMessage(object):
def __init__(self):
self.magic = magic
self.nVersion = 60002
self.nServices = 9
self.nTime = int(time.time())
self.addrTo = CAddress()
self.addrFrom = CAddress()
self.nNonce = random.getrandbits(64)
self.strSubVer = b'/python-bitcoin-0.0.1/'
self.nStartingHeight = -1
@property
def command(self) -> bytes:
return b"version"
def serialize(self):
r = b""
r += struct.pack(b"<i", self.nVersion)
r += struct.pack(b"<Q", self.nServices)
r += struct.pack(b"<q", self.nTime)
r += self.addrTo.serialize()
r += self.addrFrom.serialize()
r += struct.pack(b"<Q", self.nNonce)
r += ser_string(self.strSubVer)
r += struct.pack(b"<i", self.nStartingHeight)
return r
def finalize(self):
payload = self.serialize()
checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()
result = b""
result += self.magic
result += struct.pack('12s', self.command)
result += struct.pack("<I", len(payload))
result += checksum[:4]
result += payload
return result
ip = socket.gethostbyname("127.0.0.1")
port = 8333
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("connected to node...")
sock.connect((ip, port))
print("sending version packet")
sock.send(VersionMessage().finalize())
while 1:
msg = sock.recv(2 ** 10)
if not msg:
print("done")
exit()
else:
print(msg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment