Bitcoin OP_ADD and Script Arithmetic in Go
OP_ADD decodes two numeric operands and pushes their sum. Bitcoin can produce a five-byte result from four-byte operands; this teaching subset deliberately rejects sums outside its four-byte range.
Go implementation
139func Eval(script []byte) ([][]byte, error) {
140 ts, err := Parse(script)
141 if err != nil {
142 return nil, err
143 }
144 var st [][]byte
145 ops := 0
146 pop := func() ([]byte, error) {
147 if len(st) == 0 {
148 return nil, fmt.Errorf("stack underflow")
149 }
150 v := st[len(st)-1]
151 st = st[:len(st)-1]
152 return v, nil
153 }
154 for _, t := range ts {
155 if t.Op > 0x60 {
156 ops++
157 if ops > 201 {
158 return nil, fmt.Errorf("opcode limit")
159 }
160 }
161 switch {
162 case t.Push:
163 if len(t.Data) > 520 {
164 return nil, fmt.Errorf("element limit")
165 }
166 st = append(st, t.Data)
167 case t.Op == 0x4f:
168 st = append(st, []byte{0x81})
169 case t.Op >= 0x51 && t.Op <= 0x60:
170 st = append(st, []byte{t.Op - 0x50})
171 case t.Op == 0x76:
172 if len(st) == 0 {
173 return nil, fmt.Errorf("stack underflow")
174 }
175 st = append(st, bytes.Clone(st[len(st)-1]))
176 case t.Op == 0x75:
177 if _, err := pop(); err != nil {
178 return nil, err
179 }
180 case t.Op == 0x69:
181 v, e := pop()
182 if e != nil {
183 return nil, e
184 }
185 if !Truth(v) {
186 return nil, fmt.Errorf("verify failed")
187 }
188 case t.Op == 0xa8:
189 v, e := pop()
190 if e != nil {
191 return nil, e
192 }
193 h := sha256.Sum256(v)
194 st = append(st, h[:])
195 case t.Op == 0x87 || t.Op == 0x88 || t.Op == 0x93:
196 b, e := pop()
197 if e != nil {
198 return nil, e
199 }
200 a, e := pop()
201 if e != nil {
202 return nil, e
203 }
204 if t.Op == 0x93 {
205 x, e := DecodeNum(a, true)
206 if e != nil {
207 return nil, e
208 }
209 y, e := DecodeNum(b, true)
210 if e != nil {
211 return nil, e
212 }
213 v, e := EncodeNum(x + y)
214 if e != nil {
215 return nil, e
216 }
217 st = append(st, v)
218 } else {
219 eq := bytes.Equal(a, b)
220 if t.Op == 0x88 {
221 if !eq {
222 return nil, fmt.Errorf("equalverify failed")
223 }
224 } else if eq {
225 st = append(st, []byte{1})
226 } else {
227 st = append(st, nil)
228 }
229 }
230 default:
231 return nil, fmt.Errorf("unsupported opcode %02x", t.Op)
232 }
233 if len(st) > 1000 {
234 return nil, fmt.Errorf("stack limit")
235 }
236 }
237 return st, nil
238}Practical exercise
Evaluate 5253 93 (remove the space before decoding) and expect 05. Test maximum positive operand plus one and observe the teaching range error.
Local verification
From the repository directory golang-bitcoin/007-script-stack, run:
go test -race -v ./...
go vet ./...
1package scriptstack
2
3import (
4 "bytes"
5 "encoding/hex"
6 "testing"
7)
8
9func TestNumbers(t *testing.T) {
10 for _, v := range []int64{0, 1, -1, 127, 128, -128, 255, -255, 2147483647, -2147483647} {
11 b, e := EncodeNum(v)
12 if e != nil {
13 t.Fatal(e)
14 }
15 n, e := DecodeNum(b, true)
16 if e != nil || n != v {
17 t.Fatalf("%d %x %d %v", v, b, n, e)
18 }
19 }
20 if _, e := DecodeNum([]byte{0x80}, true); e == nil {
21 t.Fatal("negative zero minimal")
22 }
23 if Truth([]byte{0, 128}) || !Truth([]byte{128, 0}) {
24 t.Fatal("truth")
25 }
26}
27func TestPush(t *testing.T) {
28 for _, n := range []int{0, 1, 75, 76, 255, 256, 520} {
29 b := bytes.Repeat([]byte{42}, n)
30 s, e := PushData(b)
31 if e != nil {
32 t.Fatal(e)
33 }
34 st, e := Eval(s)
35 if e != nil || len(st) != 1 || !bytes.Equal(st[0], b) {
36 t.Fatalf("push %d: %v", n, e)
37 }
38 }
39 if _, e := PushData(make([]byte, 521)); e == nil {
40 t.Fatal("oversize")
41 }
42}
43func TestScripts(t *testing.T) {
44 for _, s := range []string{"5253935587", "517687", "51518851", "006951"} {
45 b, _ := hex.DecodeString(s)
46 e := Check(b)
47 if (s == "006951") != (e != nil) {
48 t.Fatalf("%s: %v", s, e)
49 }
50 }
51}
52func TestReject(t *testing.T) {
53 for _, s := range []string{"4c", "4d0100", "4effffffff", "76", "93", "ac", "5151", "00", "515287"} {
54 b, _ := hex.DecodeString(s)
55 if Check(b) == nil {
56 t.Fatalf("accepted %s", s)
57 }
58 }
59 if _, e := Eval(bytes.Repeat([]byte{0x51}, 1001)); e == nil {
60 t.Fatal("stack limit")
61 }
62}
63func TestHash(t *testing.T) {
64 s := []byte{3, 'a', 'b', 'c', 0xa8}
65 st, e := Eval(s)
66 if e != nil || hex.EncodeToString(st[0]) != "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" {
67 t.Fatal(st, e)
68 }
69}
70func FuzzParse(f *testing.F) {
71 f.Add([]byte{0x4c, 1, 42})
72 f.Fuzz(func(t *testing.T, b []byte) { _, _ = Parse(b) })
73}Scope and security
This offline educational subset is not a Bitcoin consensus engine. It starts with an empty stack, does not validate transactions, signatures, witness programs or conditional branches, and uses deliberately stricter numeric and final-stack rules. Do not use it to authorize real funds. For production validation use established Bitcoin implementations.
References
https://github.com/bitcoin/bitcoin/tree/master/src/script
https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki
