| 343 | |
| 344 | |
| 345 | class SimpleNode: |
| 346 | |
| 347 | def __init__(self, host, port=None, testnet=False, logging=False): |
| 348 | if port is None: |
| 349 | if testnet: |
| 350 | port = 18333 |
| 351 | else: |
| 352 | port = 8333 |
| 353 | self.testnet = testnet |
| 354 | self.logging = logging |
| 355 | # connect to socket |
| 356 | self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 357 | self.socket.connect((host, port)) |
| 358 | # create a stream that we can use with the rest of the library |
| 359 | self.stream = self.socket.makefile('rb', None) |
| 360 | |
| 361 | def handshake(self): |
| 362 | '''Do a handshake with the other node. |
| 363 | Handshake is sending a version message and getting a verack back.''' |
| 364 | # create a version message |
| 365 | version = VersionMessage() |
| 366 | # send the command |
| 367 | self.send(version) |
| 368 | # wait for a verack message |
| 369 | self.wait_for(VerAckMessage) |
| 370 | |
| 371 | def send(self, message): |
| 372 | '''Send a message to the connected node''' |
| 373 | # create a network envelope |
| 374 | envelope = NetworkEnvelope( |
| 375 | message.command, message.serialize(), testnet=self.testnet) |
| 376 | if self.logging: |
| 377 | print('sending: {}'.format(envelope)) |
| 378 | # send the serialized envelope over the socket using sendall |
| 379 | self.socket.sendall(envelope.serialize()) |
| 380 | |
| 381 | def read(self): |
| 382 | '''Read a message from the socket''' |
| 383 | envelope = NetworkEnvelope.parse(self.stream, testnet=self.testnet) |
| 384 | if self.logging: |
| 385 | print('receiving: {}'.format(envelope)) |
| 386 | return envelope |
| 387 | |
| 388 | def wait_for(self, *message_classes): |
| 389 | '''Wait for one of the messages in the list''' |
| 390 | # initialize the command we have, which should be None |
| 391 | command = None |
| 392 | command_to_class = {m.command: m for m in message_classes} |
| 393 | # loop until the command is in the commands we want |
| 394 | while command not in command_to_class.keys(): |
| 395 | # get the next network message |
| 396 | envelope = self.read() |
| 397 | # set the command to be evaluated |
| 398 | command = envelope.command |
| 399 | # we know how to respond to version and ping, handle that here |
| 400 | if command == VersionMessage.command: |
| 401 | # send verack |
| 402 | self.send(VerAckMessage()) |