diff --git a/bscript/script.go b/bscript/script.go index 29887ee6..bec8d8b9 100644 --- a/bscript/script.go +++ b/bscript/script.go @@ -5,6 +5,7 @@ import ( "crypto/rand" "encoding/binary" "encoding/hex" + "fmt" "strings" "github.com/libsv/go-bk/bec" @@ -394,3 +395,19 @@ func (s *Script) EqualsBytes(b []byte) bool { func (s *Script) EqualsHex(h string) bool { return s.String() == h } + +// MarshalJSON convert script into json. +func (s *Script) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, s.String())), nil +} + +// UnmarshalJSON covert from json into *bscript.Script. +func (s *Script) UnmarshalJSON(bb []byte) error { + ss, err := NewFromHexString(string(bytes.Trim(bb, `"`))) + if err != nil { + return err + } + + *s = *ss + return nil +} diff --git a/bscript/script_test.go b/bscript/script_test.go index e9796dd3..0fecd7e6 100644 --- a/bscript/script_test.go +++ b/bscript/script_test.go @@ -3,6 +3,7 @@ package bscript_test import ( "crypto/rand" "encoding/hex" + "encoding/json" "strings" "testing" @@ -288,3 +289,37 @@ func TestScript_Equals(t *testing.T) { }) } } + +func TestScript_MarshalJSON(t *testing.T) { + script, err := bscript.NewFromASM("OP_2 OP_2 OP_ADD OP_4 OP_EQUALVERIFY") + assert.NoError(t, err) + + bb, err := json.Marshal(script) + assert.NoError(t, err) + + assert.Equal(t, `"5252935488"`, string(bb)) +} + +func TestScript_UnmarshalJSON(t *testing.T) { + tests := map[string]struct { + jsonString string + exp string + }{ + "script with content": { + jsonString: `"5252935488"`, + exp: "5252935488", + }, + "empty script": { + jsonString: `""`, + exp: "", + }, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + var out *bscript.Script + assert.NoError(t, json.Unmarshal([]byte(test.jsonString), &out)) + assert.Equal(t, test.exp, out.String()) + }) + } +}