Bitcoin OP_CODESEPARATOR in Go
GOLANG + BITCOIN SCRIPT — Stage 008, Lesson 17 of 20.
Engineering concept
CODESEPARATOR changes signature-hash context. Legacy, SegWit v0 and Tapscript use different rules; Tapscript commits to the last executed separator position.
Go implementation
1// Package opcodes demonstrates selected Bitcoin Script operations, not consensus validation.
2package opcodes
3
4import (
5 "bytes"
6 "crypto/sha256"
7 "errors"
8)
9
10// Truth implements Script boolean conversion, including negative zero.
11func Truth(v []byte) bool {
12 for i, b := range v {
13 if b != 0 {
14 return !(i == len(v)-1 && b == 0x80)
15 }
16 }
17 return false
18}
19func boolean(v bool) []byte {
20 if v {
21 return []byte{1}
22 }
23 return nil
24}
25
26// Eval executes a bounded teaching subset. Unsupported opcodes fail even in skipped branches.
27func Eval(script []byte) ([][]byte, error) {
28 if len(script) > 10000 {
29 return nil, errors.New("script too long")
30 }
31 var stack, alt [][]byte
32 var branches []bool
33 active := func() bool {
34 for _, v := range branches {
35 if !v {
36 return false
37 }
38 }
39 return true
40 }
41 pop := func() ([]byte, error) {
42 if len(stack) == 0 {
43 return nil, errors.New("stack underflow")
44 }
45 v := stack[len(stack)-1]
46 stack = stack[:len(stack)-1]
47 return v, nil
48 }
49 fail := func() ([][]byte, error) { return nil, errors.New("invalid or unsupported opcode") }
50 for pc := 0; pc < len(script); {
51 op := script[pc]
52 pc++
53 if op <= 75 {
54 n := int(op)
55 if n > len(script)-pc {
56 return fail()
57 }
58 if active() {
59 stack = append(stack, bytes.Clone(script[pc:pc+n]))
60 }
61 pc += n
62 } else if op >= 0x51 && op <= 0x60 {
63 if active() {
64 stack = append(stack, []byte{op - 0x50})
65 }
66 } else {
67 switch op {
68 case 0x63, 0x64: // IF, NOTIF
69 v := false
70 if active() {
71 x, e := pop()
72 if e != nil {
73 return nil, e
74 }
75 v = Truth(x)
76 if op == 0x64 {
77 v = !v
78 }
79 }
80 branches = append(branches, v)
81 case 0x67: // ELSE
82 if len(branches) == 0 {
83 return fail()
84 }
85 branches[len(branches)-1] = !branches[len(branches)-1]
86 case 0x68: // ENDIF
87 if len(branches) == 0 {
88 return fail()
89 }
90 branches = branches[:len(branches)-1]
91 case 0x61, 0x69, 0x6a, 0x6b, 0x6c, 0x75, 0x76, 0x78, 0x7c, 0x82, 0x87, 0x88, 0x9a, 0x9b, 0xa8, 0xaa:
92 if !active() {
93 continue
94 }
95 switch op {
96 case 0x61: // NOP
97 case 0x69:
98 x, e := pop()
99 if e != nil || !Truth(x) {
100 return fail()
101 }
102 case 0x6a:
103 return fail() // RETURN
104 case 0x6b:
105 x, e := pop()
106 if e != nil {
107 return nil, e
108 }
109 alt = append(alt, x)
110 case 0x6c:
111 if len(alt) == 0 {
112 return fail()
113 }
114 stack = append(stack, alt[len(alt)-1])
115 alt = alt[:len(alt)-1]
116 case 0x75:
117 if _, e := pop(); e != nil {
118 return nil, e
119 }
120 case 0x76:
121 if len(stack) < 1 {
122 return fail()
123 }
124 stack = append(stack, bytes.Clone(stack[len(stack)-1]))
125 case 0x78:
126 if len(stack) < 2 {
127 return fail()
128 }
129 stack = append(stack, bytes.Clone(stack[len(stack)-2]))
130 case 0x7c:
131 if len(stack) < 2 {
132 return fail()
133 }
134 n := len(stack)
135 stack[n-1], stack[n-2] = stack[n-2], stack[n-1]
136 case 0x82:
137 if len(stack) < 1 {
138 return fail()
139 }
140 n := len(stack[len(stack)-1])
141 if n > 127 {
142 return fail()
143 }
144 if n == 0 {
145 stack = append(stack, nil)
146 } else {
147 stack = append(stack, []byte{byte(n)})
148 }
149 case 0x87, 0x88, 0x9a, 0x9b:
150 a, e := pop()
151 if e != nil {
152 return nil, e
153 }
154 b, e := pop()
155 if e != nil {
156 return nil, e
157 }
158 v := bytes.Equal(a, b)
159 if op == 0x9a || op == 0x9b {
160 if len(a) > 4 || len(b) > 4 {
161 return fail()
162 }
163 v = Truth(a) && Truth(b)
164 if op == 0x9b {
165 v = Truth(a) || Truth(b)
166 }
167 }
168 if op == 0x88 {
169 if !v {
170 return fail()
171 }
172 } else {
173 stack = append(stack, boolean(v))
174 }
175 case 0xa8, 0xaa:
176 x, e := pop()
177 if e != nil {
178 return nil, e
179 }
180 h := sha256.Sum256(x)
181 if op == 0xaa {
182 h = sha256.Sum256(h[:])
183 }
184 stack = append(stack, h[:])
185 }
186 default:
187 return fail()
188 }
189 }
190 if len(stack)+len(alt) > 1000 {
191 return fail()
192 }
193 }
194 if len(branches) != 0 {
195 return fail()
196 }
197 return stack, nil
198}Practical exercise
Decode ab with encoding/hex and pass the bytes to Eval. The subset rejects CODESEPARATOR. Never remove separators without considering the signature version. Inspect the returned error and stack separately. Stack items are byte slices, ordered bottom to top.
Verification
From golang-bitcoin/008-opcodes run go test -race -v ./... and go vet ./.... The tests cover selected instructions, not every exercise or consensus rule.
1package opcodes
2
3import (
4 "bytes"
5 "crypto/sha256"
6 "encoding/hex"
7 "testing"
8)
9
10func TestEval(t *testing.T) {
11 for _, c := range []struct{ s, w string }{{"516352675368", "02"}, {"006352675368", "03"}, {"006351635268675468", "04"}, {"516b6c", "01"}, {"51527c75", "02"}, {"51527887", ""}, {"517687", "01"}, {"00519b", "01"}, {"00519a", ""}, {"02010282", "02"}, {"00636a6851", "01"}, {"516452675368", "03"}} {
12 s, _ := hex.DecodeString(c.s)
13 w, _ := hex.DecodeString(c.w)
14 v, e := Eval(s)
15 if e != nil || len(v) == 0 || !bytes.Equal(v[len(v)-1], w) {
16 t.Errorf("%s: %x %v", c.s, v, e)
17 }
18 }
19}
20func TestReject(t *testing.T) {
21 for _, s := range []string{"63", "67", "68", "5163", "6a", "76", "6c", "0201", "0063ff68", "00 69", "515288"} {
22 s = string(bytes.ReplaceAll([]byte(s), []byte(" "), nil))
23 b, _ := hex.DecodeString(s)
24 if _, e := Eval(b); e == nil {
25 t.Errorf("accepted %s", s)
26 }
27 }
28}
29func TestHash(t *testing.T) {
30 v, e := Eval([]byte{1, 42, 0xaa})
31 h := sha256.Sum256([]byte{42})
32 h = sha256.Sum256(h[:])
33 if e != nil || !bytes.Equal(v[0], h[:]) {
34 t.Fatal(v, e)
35 }
36}
37func FuzzEval(f *testing.F) {
38 f.Add([]byte{0x51, 0x76})
39 f.Fuzz(func(t *testing.T, b []byte) { Eval(b) })
40}Scope
This offline teaching evaluator starts with an empty stack and supports only selected opcodes and direct pushes. It does not implement transaction context, signatures, full numeric rules, minimal pushes, all consensus limits or final-stack validation. Unsupported instructions fail even in inactive branches. Do not use it to authorize funds.
References
https://github.com/bitcoin/bitcoin/tree/master/src/script
https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki
https://github.com/bitcoin/bips/blob/master/bip-0147.mediawiki
