From af3d7c2a011389035c832adc0b0476cb9d08b6d7 Mon Sep 17 00:00:00 2001 From: Aurora Gaffney Date: Sat, 16 Aug 2025 10:36:13 -0400 Subject: [PATCH] refactor: helper for generating script hash Fixes #1135 Signed-off-by: Aurora Gaffney --- ledger/common/script.go | 42 ++++++++++++++++++++++++++++++++++++ ledger/common/script_test.go | 10 +++++++++ 2 files changed, 52 insertions(+) diff --git a/ledger/common/script.go b/ledger/common/script.go index 604c158c..6c7455e8 100644 --- a/ledger/common/script.go +++ b/ledger/common/script.go @@ -17,6 +17,7 @@ package common import ( "errors" "fmt" + "slices" "github.com/blinklabs-io/gouroboros/cbor" ) @@ -28,8 +29,11 @@ const ( ScriptRefTypePlutusV3 = 3 ) +type ScriptHash = Blake2b224 + type Script interface { isScript() + Hash() ScriptHash } type ScriptRef struct { @@ -82,15 +86,43 @@ type PlutusV1Script []byte func (PlutusV1Script) isScript() {} +func (s PlutusV1Script) Hash() ScriptHash { + return Blake2b224Hash( + slices.Concat( + []byte{ScriptRefTypePlutusV1}, + []byte(s), + ), + ) +} + type PlutusV2Script []byte func (PlutusV2Script) isScript() {} +func (s PlutusV2Script) Hash() ScriptHash { + return Blake2b224Hash( + slices.Concat( + []byte{ScriptRefTypePlutusV2}, + []byte(s), + ), + ) +} + type PlutusV3Script []byte func (PlutusV3Script) isScript() {} +func (s PlutusV3Script) Hash() ScriptHash { + return Blake2b224Hash( + slices.Concat( + []byte{ScriptRefTypePlutusV3}, + []byte(s), + ), + ) +} + type NativeScript struct { + cbor.DecodeStoreCbor item any } @@ -101,6 +133,7 @@ func (n *NativeScript) Item() any { } func (n *NativeScript) UnmarshalCBOR(data []byte) error { + n.SetCbor(data) id, err := cbor.DecodeIdFromList(data) if err != nil { return err @@ -128,6 +161,15 @@ func (n *NativeScript) UnmarshalCBOR(data []byte) error { return nil } +func (s NativeScript) Hash() ScriptHash { + return Blake2b224Hash( + slices.Concat( + []byte{ScriptRefTypeNativeScript}, + []byte(s.Cbor()), + ), + ) +} + type NativeScriptPubkey struct { cbor.StructAsArray Type uint diff --git a/ledger/common/script_test.go b/ledger/common/script_test.go index 0c5609a6..fa14cb44 100644 --- a/ledger/common/script_test.go +++ b/ledger/common/script_test.go @@ -40,3 +40,13 @@ func TestScriptRefDecode(t *testing.T) { ) } } + +func TestPlutusV3ScriptHash(t *testing.T) { + testScriptBytes, _ := hex.DecodeString("587f01010032323232323225333002323232323253330073370e900118041baa0011323232533300a3370e900018059baa00513232533300f301100214a22c6eb8c03c004c030dd50028b18069807001180600098049baa00116300a300b0023009001300900230070013004375400229309b2b2b9a5573aaae7955cfaba157441") + testScript := common.PlutusV3Script(testScriptBytes) + expectedScriptHash := "2909c3d0441e76cd6ae1fc09664bb209868902e191c2b8c30b82d331" + tmpHash := testScript.Hash() + if tmpHash.String() != expectedScriptHash { + t.Errorf("did not get expected script hash, got %s, wanted %s", tmpHash.String(), expectedScriptHash) + } +}