def getBlocks(self, startHash, howmany, d):
    """ Ask connected node for howmany blocks from best-block chain, callback d when we've got them all """
    self._blocks_to_fetch = min(howmany, self.peerVersion.nStartingHeight)
    self._blocks_fetched = 0
    self._batch_remaining = 0
    self._blocks = []
    self._getBlocksCallback = d

    m = msg_getblocks(version=self.ver_send)
    if startHash is None:
      m.locator = [ self.factory.genesis_value ]
    else:
      m.locator = [ startHash, self.factory.genesis_value ]

    self.addHandler(msg_inv, self._gotInv) # ... expect inv message
    self.sendMessage(m)
  def _gotBlock(self, message):
    blockhash = message.calc_sha256()
    if blockhash not in self._expectedBlocks:
      # Ignore blocks we're not expecting:
      self.addHandler(msg_block, self._gotBlock) # Handle next block
      return

    self._blocks.append(message)
    self._blocks_fetched += 1
    self._batch_remaining -= 1
    if self._blocks_fetched >= self._blocks_to_fetch:
      d, self._getBlocksCallback = self._getBlocksCallback, None
      blocks, self._blocks = self._blocks, None
      d.callback(blocks)
    elif self._batch_remaining == 0:
      m = msg_getblocks(version=self.ver_send)
      m.locator = [ blockhash, self.factory.genesis_value ]
      self.addHandler(msg_inv, self._gotInv) # new round of getblocks --> inv
      self.sendMessage(m)
    else:
      self.addHandler(msg_block, self._gotBlock) # Handle next block