Skip to content

Commit

Permalink
Enhancement: JSON Marshalling of *bscript.Script (#85)
Browse files Browse the repository at this point in the history
* added json marshal and unmarshal funcs

* fixed unmarshalling

* changed out to a pointer in tests
  • Loading branch information
tigh-latte authored Nov 25, 2021
1 parent 0121a8f commit 792a281
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
17 changes: 17 additions & 0 deletions bscript/script.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"crypto/rand"
"encoding/binary"
"encoding/hex"
"fmt"
"strings"

"github.com/libsv/go-bk/bec"
Expand Down Expand Up @@ -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
}
35 changes: 35 additions & 0 deletions bscript/script_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package bscript_test
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"strings"
"testing"

Expand Down Expand Up @@ -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())
})
}
}

0 comments on commit 792a281

Please sign in to comment.