-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.go
More file actions
112 lines (99 loc) · 2.11 KB
/
Copy pathscript.go
File metadata and controls
112 lines (99 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package script
import (
"bytes"
"encoding/hex"
"fmt"
"github.com/YOwatari/programmingbitcoin/helper"
"strings"
)
type Script struct {
cmds [][]byte
}
func NewScript(cmds [][]byte) *Script {
return &Script{cmds: cmds}
}
func ParseScript(r *bytes.Reader) (*Script, error) {
length := helper.ReadVarInt(r)
var cmds [][]byte
count := 0
for count < length {
current, err := r.ReadByte() // opcode or element
if err != nil {
return nil, err
}
count++
switch {
case current >= 1 && current <= 75:
n := int(current)
buf := make([]byte, n)
r.Read(buf)
cmds = append(cmds, buf)
count += n
case current == 76:
data, err := r.ReadByte()
if err != nil {
return nil, err
}
n := int(data)
buf := make([]byte, n)
r.Read(buf)
cmds = append(cmds, buf)
count += n + 1
case current == 77:
data := make([]byte, 2)
r.Read(data)
n := int(helper.LittleEndianToInt64(data))
buf := make([]byte, n)
r.Read(buf)
cmds = append(cmds, buf)
count += n + 2
default:
opcode := current
cmds = append(cmds, []byte{opcode})
}
}
if count != length {
return nil, fmt.Errorf("cannot parse script. length: %d, count: %d", length, count)
}
return NewScript(cmds), nil
}
func (s *Script) Serialize() []byte {
raw := new(bytes.Buffer)
for _, cmd := range s.cmds {
length := len(cmd)
switch {
case length == 1:
raw.WriteByte(cmd[0])
case length < 76:
raw.WriteByte(byte(length))
case length < 0x100:
raw.WriteByte(byte(76))
raw.WriteByte(byte(length))
case length <= 520:
raw.WriteByte(byte(77))
raw.WriteByte(byte(length))
default:
raw.Write(cmd)
}
}
buf := new(bytes.Buffer)
buf.Write(helper.EncodeVarInt(raw.Len()))
buf.Write(raw.Bytes())
return buf.Bytes()
}
func (s *Script) String() string {
result := make([]string, len(s.cmds))
for i, cmd := range s.cmds {
if len(cmd) == 1 {
opcode := int(cmd[0])
if name, ok := opcodeName[opcode]; ok {
result[i] = name
} else {
result[i] = fmt.Sprintf("OP_[%d]", opcode)
}
} else {
result[i] = hex.EncodeToString(cmd)
}
}
return strings.Join(result, " ")
}