ScriptTemplate processes a script template with parameters and returns the corresponding script bytes. This functions allows Bitcoin scripts to be created using a DSL-like syntax, based on Go's templating system. An example of a simple p2pkh template would be: `OP_DUP OP_HASH160 0x14e8948c7afa71b
(scriptTmpl string, opts ...ScriptTemplateOption)
| 53 | // houses paramters to pass into the script, for example a local variable |
| 54 | // storing a computed public key. |
| 55 | func ScriptTemplate(scriptTmpl string, opts ...ScriptTemplateOption) ([]byte, error) { |
| 56 | cfg := &templateConfig{ |
| 57 | params: make(map[string]interface{}), |
| 58 | customFuncs: make(template.FuncMap), |
| 59 | } |
| 60 | |
| 61 | for _, opt := range opts { |
| 62 | opt(cfg) |
| 63 | } |
| 64 | |
| 65 | funcMap := template.FuncMap{ |
| 66 | "hex": hexEncode, |
| 67 | "hex_str": hexStr, |
| 68 | "unhex": hexDecode, |
| 69 | "range_iter": rangeIter, |
| 70 | } |
| 71 | |
| 72 | for k, v := range cfg.customFuncs { |
| 73 | funcMap[k] = v |
| 74 | } |
| 75 | |
| 76 | tmpl, err := template.New("script").Funcs(funcMap).Parse(scriptTmpl) |
| 77 | if err != nil { |
| 78 | return nil, fmt.Errorf("failed to parse template: %w", err) |
| 79 | } |
| 80 | |
| 81 | var buf bytes.Buffer |
| 82 | if err := tmpl.Execute(&buf, cfg.params); err != nil { |
| 83 | return nil, fmt.Errorf("failed to execute template: %w", err) |
| 84 | } |
| 85 | |
| 86 | return processScript(buf.String()) |
| 87 | } |
| 88 | |
| 89 | // looksLikeInt checks if a string looks like an integer. |
| 90 | func looksLikeInt(s string) bool { |
searching dependent graphs…