|
4 | 4 | import warnings
|
5 | 5 | from typing import Dict, List, Optional, Union
|
6 | 6 |
|
| 7 | +import cbor2 |
7 | 8 | from blockfrost import ApiError, ApiUrls, BlockFrostApi
|
8 | 9 | from blockfrost.utils import Namespace
|
9 | 10 |
|
|
18 | 19 | from pycardano.hash import SCRIPT_HASH_SIZE, DatumHash, ScriptHash
|
19 | 20 | from pycardano.nativescript import NativeScript
|
20 | 21 | from pycardano.network import Network
|
21 |
| -from pycardano.plutus import ExecutionUnits, PlutusV1Script, PlutusV2Script |
| 22 | +from pycardano.plutus import ExecutionUnits, PlutusV1Script, PlutusV2Script, script_hash |
22 | 23 | from pycardano.serialization import RawCBOR
|
23 | 24 | from pycardano.transaction import (
|
24 | 25 | Asset,
|
|
34 | 35 | __all__ = ["BlockFrostChainContext"]
|
35 | 36 |
|
36 | 37 |
|
| 38 | +def _try_fix_script( |
| 39 | + scripth: str, script: Union[PlutusV1Script, PlutusV2Script] |
| 40 | +) -> Union[PlutusV1Script, PlutusV2Script]: |
| 41 | + if str(script_hash(script)) == scripth: |
| 42 | + return script |
| 43 | + else: |
| 44 | + new_script = script.__class__(cbor2.loads(script)) |
| 45 | + if str(script_hash(new_script)) == scripth: |
| 46 | + return new_script |
| 47 | + else: |
| 48 | + raise ValueError("Cannot recover script from hash.") |
| 49 | + |
| 50 | + |
37 | 51 | class BlockFrostChainContext(ChainContext):
|
38 | 52 | """A `BlockFrost <https://blockfrost.io/>`_ API wrapper for the client code to interact with.
|
39 | 53 |
|
@@ -151,9 +165,15 @@ def _get_script(
|
151 | 165 | ) -> Union[PlutusV1Script, PlutusV2Script, NativeScript]:
|
152 | 166 | script_type = self.api.script(script_hash).type
|
153 | 167 | if script_type == "plutusV1":
|
154 |
| - return PlutusV1Script(bytes.fromhex(self.api.script_cbor(script_hash).cbor)) |
| 168 | + v1script = PlutusV1Script( |
| 169 | + bytes.fromhex(self.api.script_cbor(script_hash).cbor) |
| 170 | + ) |
| 171 | + return _try_fix_script(script_hash, v1script) |
155 | 172 | elif script_type == "plutusV2":
|
156 |
| - return PlutusV2Script(bytes.fromhex(self.api.script_cbor(script_hash).cbor)) |
| 173 | + v2script = PlutusV2Script( |
| 174 | + bytes.fromhex(self.api.script_cbor(script_hash).cbor) |
| 175 | + ) |
| 176 | + return _try_fix_script(script_hash, v2script) |
157 | 177 | else:
|
158 | 178 | script_json: JsonDict = self.api.script_json(
|
159 | 179 | script_hash, return_type="json"
|
|
0 commit comments