Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions ledger/common/script.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package common
import (
"errors"
"fmt"
"slices"

"github.com/blinklabs-io/gouroboros/cbor"
)
Expand All @@ -28,8 +29,11 @@ const (
ScriptRefTypePlutusV3 = 3
)

type ScriptHash = Blake2b224

type Script interface {
isScript()
Hash() ScriptHash
}

type ScriptRef struct {
Expand Down Expand Up @@ -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
}

Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions ledger/common/script_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}