|
| 1 | +# Copyright 2024 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 __future__ import annotations |
| 16 | + |
| 17 | +from collections import defaultdict |
| 18 | +from typing import Iterator, Self |
| 19 | + |
| 20 | +from structlog import get_logger |
| 21 | + |
| 22 | +from hathor.conf.settings import HathorSettings |
| 23 | +from hathor.daa import DifficultyAdjustmentAlgorithm |
| 24 | +from hathor.dag_builder.artifacts import DAGArtifacts |
| 25 | +from hathor.dag_builder.tokenizer import Token, TokenType |
| 26 | +from hathor.dag_builder.types import ( |
| 27 | + AttributeType, |
| 28 | + DAGInput, |
| 29 | + DAGNode, |
| 30 | + DAGNodeType, |
| 31 | + DAGOutput, |
| 32 | + VertexResolverType, |
| 33 | + WalletFactoryType, |
| 34 | +) |
| 35 | +from hathor.wallet import BaseWallet |
| 36 | + |
| 37 | +logger = get_logger() |
| 38 | + |
| 39 | + |
| 40 | +class DAGBuilder: |
| 41 | + def __init__( |
| 42 | + self, |
| 43 | + settings: HathorSettings, |
| 44 | + daa: DifficultyAdjustmentAlgorithm, |
| 45 | + genesis_wallet: BaseWallet, |
| 46 | + wallet_factory: WalletFactoryType, |
| 47 | + vertex_resolver: VertexResolverType, |
| 48 | + ) -> None: |
| 49 | + from hathor.dag_builder.default_filler import DefaultFiller |
| 50 | + from hathor.dag_builder.tokenizer import tokenize |
| 51 | + from hathor.dag_builder.vertex_exporter import VertexExporter |
| 52 | + |
| 53 | + self.log = logger.new() |
| 54 | + |
| 55 | + self._nodes: dict[str, DAGNode] = {} |
| 56 | + self._tokenize = tokenize |
| 57 | + self._filler = DefaultFiller(self, settings, daa) |
| 58 | + self._exporter = VertexExporter( |
| 59 | + builder=self, |
| 60 | + settings=settings, |
| 61 | + daa=daa, |
| 62 | + genesis_wallet=genesis_wallet, |
| 63 | + wallet_factory=wallet_factory, |
| 64 | + vertex_resolver=vertex_resolver, |
| 65 | + ) |
| 66 | + |
| 67 | + def parse_tokens(self, tokens: Iterator[Token]) -> None: |
| 68 | + for parts in tokens: |
| 69 | + match parts: |
| 70 | + case (TokenType.PARENT, (_from, _to)): |
| 71 | + self.add_parent_edge(_from, _to) |
| 72 | + |
| 73 | + case (TokenType.SPEND, (_from, _to, _txout_index)): |
| 74 | + self.add_spending_edge(_from, _to, _txout_index) |
| 75 | + |
| 76 | + case (TokenType.ATTRIBUTE, (name, key, value)): |
| 77 | + self.add_attribute(name, key, value) |
| 78 | + |
| 79 | + case (TokenType.ORDER_BEFORE, (_from, _to)): |
| 80 | + self.add_deps(_from, _to) |
| 81 | + |
| 82 | + case (TokenType.OUTPUT, (name, index, amount, token, attrs)): |
| 83 | + self.set_output(name, index, amount, token, attrs) |
| 84 | + |
| 85 | + case (TokenType.BLOCKCHAIN, (name, first_parent, begin_index, end_index)): |
| 86 | + self.add_blockchain(name, first_parent, begin_index, end_index) |
| 87 | + |
| 88 | + case _: |
| 89 | + raise NotImplementedError(parts) |
| 90 | + |
| 91 | + def _get_node(self, name: str) -> DAGNode: |
| 92 | + return self._nodes[name] |
| 93 | + |
| 94 | + def _get_or_create_node(self, name: str, *, default_type: DAGNodeType = DAGNodeType.Unknown) -> DAGNode: |
| 95 | + if name not in self._nodes: |
| 96 | + node = DAGNode(name=name, type=default_type) |
| 97 | + self._nodes[name] = node |
| 98 | + else: |
| 99 | + node = self._nodes[name] |
| 100 | + if node.type is DAGNodeType.Unknown: |
| 101 | + node.type = default_type |
| 102 | + else: |
| 103 | + if default_type != DAGNodeType.Unknown: |
| 104 | + assert node.type is default_type, f'{node.type} != {default_type}' |
| 105 | + return node |
| 106 | + |
| 107 | + def add_deps(self, _from: str, _to: str) -> Self: |
| 108 | + from_node = self._get_or_create_node(_from) |
| 109 | + self._get_or_create_node(_to) |
| 110 | + from_node.deps.add(_to) |
| 111 | + return self |
| 112 | + |
| 113 | + def add_blockchain(self, prefix: str, first_parent: str | None, first_index: int, last_index: int) -> Self: |
| 114 | + prev = first_parent |
| 115 | + for i in range(first_index, last_index + 1): |
| 116 | + name = f'{prefix}{i}' |
| 117 | + self._get_or_create_node(name, default_type=DAGNodeType.Block) |
| 118 | + if prev is not None: |
| 119 | + self.add_parent_edge(name, prev) |
| 120 | + prev = name |
| 121 | + return self |
| 122 | + |
| 123 | + def add_parent_edge(self, _from: str, _to: str) -> Self: |
| 124 | + self._get_or_create_node(_to) |
| 125 | + from_node = self._get_or_create_node(_from) |
| 126 | + from_node.parents.add(_to) |
| 127 | + return self |
| 128 | + |
| 129 | + def add_spending_edge(self, _from: str, _to: str, _txout_index: int) -> Self: |
| 130 | + to_node = self._get_or_create_node(_to) |
| 131 | + if len(to_node.outputs) <= _txout_index: |
| 132 | + to_node.outputs.extend([None] * (_txout_index - len(to_node.outputs) + 1)) |
| 133 | + to_node.outputs[_txout_index] = DAGOutput(0, '', {}) |
| 134 | + from_node = self._get_or_create_node(_from) |
| 135 | + from_node.inputs.add(DAGInput(_to, _txout_index)) |
| 136 | + return self |
| 137 | + |
| 138 | + def set_output(self, name: str, index: int, amount: int, token: str, attrs: AttributeType) -> Self: |
| 139 | + node = self._get_or_create_node(name) |
| 140 | + if len(node.outputs) <= index: |
| 141 | + node.outputs.extend([None] * (index - len(node.outputs) + 1)) |
| 142 | + node.outputs[index] = DAGOutput(amount, token, attrs) |
| 143 | + if token != 'HTR': |
| 144 | + self._get_or_create_node(token, default_type=DAGNodeType.Token) |
| 145 | + node.deps.add(token) |
| 146 | + return self |
| 147 | + |
| 148 | + def add_attribute(self, name: str, key: str, value: str) -> Self: |
| 149 | + node = self._get_or_create_node(name) |
| 150 | + if key == 'type': |
| 151 | + node.type = DAGNodeType(value) |
| 152 | + else: |
| 153 | + node.attrs[key] = value |
| 154 | + return self |
| 155 | + |
| 156 | + def topological_sorting(self) -> Iterator[DAGNode]: |
| 157 | + direct_deps: dict[str, set[str]] = {} |
| 158 | + rev_deps: dict[str, set[str]] = defaultdict(set) |
| 159 | + seen: set[str] = set() |
| 160 | + candidates: list[str] = [] |
| 161 | + for name, node in self._nodes.items(): |
| 162 | + assert name == node.name |
| 163 | + deps = set(node.get_all_dependencies()) |
| 164 | + assert name not in direct_deps |
| 165 | + direct_deps[name] = deps |
| 166 | + for x in deps: |
| 167 | + rev_deps[x].add(name) |
| 168 | + if len(deps) == 0: |
| 169 | + candidates.append(name) |
| 170 | + |
| 171 | + for _ in range(len(self._nodes)): |
| 172 | + if len(candidates) == 0: |
| 173 | + self.log('fail because there is at least one cycle in the dependencies', |
| 174 | + direct_deps=direct_deps, |
| 175 | + rev_deps=rev_deps, |
| 176 | + seen=seen, |
| 177 | + not_seen=set(self._nodes.keys()) - seen, |
| 178 | + nodes=self._nodes) |
| 179 | + raise RuntimeError('there is at least one cycle') |
| 180 | + name = candidates.pop() |
| 181 | + assert name not in seen |
| 182 | + seen.add(name) |
| 183 | + for d in rev_deps[name]: |
| 184 | + direct_deps[d].remove(name) |
| 185 | + if len(direct_deps[d]) == 0: |
| 186 | + candidates.append(d) |
| 187 | + del direct_deps[d] |
| 188 | + node = self._get_node(name) |
| 189 | + yield node |
| 190 | + |
| 191 | + def build(self) -> DAGArtifacts: |
| 192 | + self._filler.run() |
| 193 | + return DAGArtifacts(self._exporter.export()) |
| 194 | + |
| 195 | + def build_from_str(self, content: str) -> DAGArtifacts: |
| 196 | + self.parse_tokens(self._tokenize(content)) |
| 197 | + return self.build() |
0 commit comments