|
| 1 | +# Copyright 2023 Hathor Labs |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from typing import TYPE_CHECKING, Optional |
| 16 | + |
| 17 | +from structlog import get_logger |
| 18 | +from twisted.internet.defer import Deferred |
| 19 | + |
| 20 | +from hathor.p2p.sync_v2.exception import ( |
| 21 | + BlockNotConnectedToPreviousBlock, |
| 22 | + InvalidVertexError, |
| 23 | + StreamingError, |
| 24 | + TooManyRepeatedVerticesError, |
| 25 | + TooManyVerticesReceivedError, |
| 26 | +) |
| 27 | +from hathor.p2p.sync_v2.streamers import StreamEnd |
| 28 | +from hathor.transaction import Block |
| 29 | +from hathor.transaction.exceptions import HathorError |
| 30 | +from hathor.types import VertexId |
| 31 | + |
| 32 | +if TYPE_CHECKING: |
| 33 | + from hathor.p2p.sync_v2.agent import NodeBlockSync, _HeightInfo |
| 34 | + |
| 35 | +logger = get_logger() |
| 36 | + |
| 37 | + |
| 38 | +class BlockchainStreamingClient: |
| 39 | + def __init__(self, sync_agent: 'NodeBlockSync', start_block: '_HeightInfo', end_block: '_HeightInfo') -> None: |
| 40 | + self.sync_agent = sync_agent |
| 41 | + self.protocol = self.sync_agent.protocol |
| 42 | + self.tx_storage = self.sync_agent.tx_storage |
| 43 | + self.manager = self.sync_agent.manager |
| 44 | + |
| 45 | + self.log = logger.new(peer=self.protocol.get_short_peer_id()) |
| 46 | + |
| 47 | + self.start_block = start_block |
| 48 | + self.end_block = end_block |
| 49 | + |
| 50 | + # When syncing blocks we start streaming with all peers |
| 51 | + # so the moment I get some repeated blocks, I stop the download |
| 52 | + # because it's probably a streaming that I've already received |
| 53 | + self.max_repeated_blocks = 10 |
| 54 | + |
| 55 | + self._deferred: Deferred[StreamEnd] = Deferred() |
| 56 | + |
| 57 | + self._blk_received: int = 0 |
| 58 | + self._blk_repeated: int = 0 |
| 59 | + |
| 60 | + self._blk_max_quantity = self.end_block.height - self.start_block.height + 1 |
| 61 | + self._reverse: bool = False |
| 62 | + if self._blk_max_quantity < 0: |
| 63 | + self._blk_max_quantity = -self._blk_max_quantity |
| 64 | + self._reverse = True |
| 65 | + |
| 66 | + self._last_received_block: Optional[Block] = None |
| 67 | + |
| 68 | + self._partial_blocks: list[Block] = [] |
| 69 | + |
| 70 | + def wait(self) -> Deferred[StreamEnd]: |
| 71 | + """Return the deferred.""" |
| 72 | + return self._deferred |
| 73 | + |
| 74 | + def fails(self, reason: 'StreamingError') -> None: |
| 75 | + """Fail the execution by resolving the deferred with an error.""" |
| 76 | + self._deferred.errback(reason) |
| 77 | + |
| 78 | + def partial_vertex_exists(self, vertex_id: VertexId) -> bool: |
| 79 | + """Return true if the vertex exists no matter its validation state.""" |
| 80 | + with self.tx_storage.allow_partially_validated_context(): |
| 81 | + return self.tx_storage.transaction_exists(vertex_id) |
| 82 | + |
| 83 | + def handle_blocks(self, blk: Block) -> None: |
| 84 | + """This method is called by the sync agent when a BLOCKS message is received.""" |
| 85 | + if self._deferred.called: |
| 86 | + return |
| 87 | + |
| 88 | + self._blk_received += 1 |
| 89 | + if self._blk_received > self._blk_max_quantity: |
| 90 | + self.log.warn('too many blocks received', |
| 91 | + blk_received=self._blk_received, |
| 92 | + blk_max_quantity=self._blk_max_quantity) |
| 93 | + self.fails(TooManyVerticesReceivedError()) |
| 94 | + return |
| 95 | + |
| 96 | + assert blk.hash is not None |
| 97 | + is_duplicated = False |
| 98 | + if self.partial_vertex_exists(blk.hash): |
| 99 | + # We reached a block we already have. Skip it. |
| 100 | + self._blk_repeated += 1 |
| 101 | + is_duplicated = True |
| 102 | + if self._blk_repeated > self.max_repeated_blocks: |
| 103 | + self.log.debug('too many repeated block received', total_repeated=self._blk_repeated) |
| 104 | + self.fails(TooManyRepeatedVerticesError()) |
| 105 | + |
| 106 | + # basic linearity validation, crucial for correctly predicting the next block's height |
| 107 | + if self._reverse: |
| 108 | + if self._last_received_block and blk.hash != self._last_received_block.get_block_parent_hash(): |
| 109 | + self.fails(BlockNotConnectedToPreviousBlock()) |
| 110 | + return |
| 111 | + else: |
| 112 | + if self._last_received_block and blk.get_block_parent_hash() != self._last_received_block.hash: |
| 113 | + self.fails(BlockNotConnectedToPreviousBlock()) |
| 114 | + return |
| 115 | + |
| 116 | + try: |
| 117 | + # this methods takes care of checking if the block already exists, |
| 118 | + # it will take care of doing at least a basic validation |
| 119 | + if is_duplicated: |
| 120 | + self.log.debug('block early terminate?', blk_id=blk.hash.hex()) |
| 121 | + else: |
| 122 | + self.log.debug('block received', blk_id=blk.hash.hex()) |
| 123 | + self.sync_agent.on_new_tx(blk, propagate_to_peers=False, quiet=True) |
| 124 | + except HathorError: |
| 125 | + self.fails(InvalidVertexError()) |
| 126 | + return |
| 127 | + else: |
| 128 | + self._last_received_block = blk |
| 129 | + self._blk_repeated = 0 |
| 130 | + # XXX: debugging log, maybe add timing info |
| 131 | + if self._blk_received % 500 == 0: |
| 132 | + self.log.debug('block streaming in progress', blocks_received=self._blk_received) |
| 133 | + |
| 134 | + if not blk.can_validate_full(): |
| 135 | + self._partial_blocks.append(blk) |
| 136 | + |
| 137 | + def handle_blocks_end(self, response_code: StreamEnd) -> None: |
| 138 | + """This method is called by the sync agent when a BLOCKS-END message is received.""" |
| 139 | + if self._deferred.called: |
| 140 | + return |
| 141 | + self._deferred.callback(response_code) |
0 commit comments