THAMER
Sovereign Bitcoin Wallet

WALLET AI BITCOIN

Your Bitcoin Wallet. Your Keys. Your Engine.

Self-hosted Bitcoin software built for developers, applications, and AI agents.

CREATE WALLET

script.go

TEXT FILE

5.1 KB · Public source code for developers, search crawlers and AI agents

Download / RawBack to folder
Go · 250 lines
1// Package scriptstack is an offline teaching subset, NOT a consensus engine.
2package scriptstack
3
4import (
5	"bytes"
6	"crypto/sha256"
7	"encoding/binary"
8	"fmt"
9)
10
11// EncodeNum encodes a four-byte-range signed magnitude Script number.
12func EncodeNum(n int64) ([]byte, error) {
13	if n < -2147483647 || n > 2147483647 {
14		return nil, fmt.Errorf("number range")
15	}
16	if n == 0 {
17		return nil, nil
18	}
19	neg := n < 0
20	if neg {
21		n = -n
22	}
23	var b []byte
24	for n > 0 {
25		b = append(b, byte(n))
26		n >>= 8
27	}
28	if b[len(b)-1]&128 != 0 {
29		if neg {
30			b = append(b, 128)
31		} else {
32			b = append(b, 0)
33		}
34	} else if neg {
35		b[len(b)-1] |= 128
36	}
37	return b, nil
38}
39
40// DecodeNum optionally rejects nonminimal signed magnitude encodings.
41func DecodeNum(b []byte, minimal bool) (int64, error) {
42	if len(b) > 4 {
43		return 0, fmt.Errorf("numeric operand too long")
44	}
45	if len(b) == 0 {
46		return 0, nil
47	}
48	if minimal && b[len(b)-1]&127 == 0 && (len(b) == 1 || b[len(b)-2]&128 == 0) {
49		return 0, fmt.Errorf("nonminimal number")
50	}
51	var n int64
52	for i, v := range b {
53		n |= int64(v) << uint(8*i)
54	}
55	if b[len(b)-1]&128 != 0 {
56		n &^= int64(128) << uint(8*(len(b)-1))
57		n = -n
58	}
59	return n, nil
60}
61
62// Truth implements Script boolean conversion, including negative zero.
63func Truth(b []byte) bool {
64	for i, v := range b {
65		if v != 0 {
66			return !(i == len(b)-1 && v == 128)
67		}
68	}
69	return false
70}
71
72// PushData builds a minimal data push for an element of at most 520 bytes.
73func PushData(b []byte) ([]byte, error) {
74	n := len(b)
75	switch {
76	case n > 520:
77		return nil, fmt.Errorf("element too large")
78	case n == 0:
79		return []byte{0}, nil
80	case n == 1 && b[0] >= 1 && b[0] <= 16:
81		return []byte{0x50 + b[0]}, nil
82	case n == 1 && b[0] == 0x81:
83		return []byte{0x4f}, nil
84	case n <= 75:
85		return append([]byte{byte(n)}, b...), nil
86	case n <= 255:
87		return append([]byte{0x4c, byte(n)}, b...), nil
88	default:
89		return append([]byte{0x4d, byte(n), byte(n >> 8)}, b...), nil
90	}
91}
92
93type Token struct {
94	Op   byte
95	Data []byte
96	Push bool
97}
98
99// Parse decodes pushes, without interpreting non-push opcodes.
100func Parse(s []byte) ([]Token, error) {
101	if len(s) > 10000 {
102		return nil, fmt.Errorf("script too long")
103	}
104	var out []Token
105	for i := 0; i < len(s); {
106		op := s[i]
107		i++
108		t := Token{Op: op}
109		var n uint64
110		switch {
111		case op <= 75:
112			n = uint64(op)
113			t.Push = true
114		case op >= 0x4c && op <= 0x4e:
115			k := 1 << uint(op-0x4c)
116			if len(s)-i < k {
117				return nil, fmt.Errorf("truncated length")
118			}
119			var buf [4]byte
120			copy(buf[:], s[i:i+k])
121			n = uint64(binary.LittleEndian.Uint32(buf[:]))
122			i += k
123			t.Push = true
124		}
125		if t.Push {
126			if n > uint64(len(s)-i) {
127				return nil, fmt.Errorf("truncated push")
128			}
129			t.Data = bytes.Clone(s[i : i+int(n)])
130			i += int(n)
131		}
132		out = append(out, t)
133	}
134	return out, nil
135}
136
137// Eval executes a deliberately small straight-line subset with strict limits.
138// Stack order is bottom to top. Unsupported instructions fail closed.
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}
239
240// Check requires exactly one true item: a teaching clean-stack rule.
241func Check(script []byte) error {
242	st, e := Eval(script)
243	if e != nil {
244		return e
245	}
246	if len(st) != 1 || !Truth(st[0]) {
247		return fmt.Errorf("expected one true item")
248	}
249	return nil
250}
Read-only source · Select a line number to link directly · Raw download above

Latest from the Lab

THAMER illustrated developer portrait and signature

ABOUT THE DEVELOPER

Independent Software Developer specializing in Bitcoin Script, Golang, and AI Agents.

Software engineering · Independent research · Open-source projects