processScript converts the template output to actual script bytes. We scan each line, then go through each element one by one, deciding to either add a normal op code, a push data, or an integer value.
(script string)
| 107 | // each line, then go through each element one by one, deciding to either add a |
| 108 | // normal op code, a push data, or an integer value. |
| 109 | func processScript(script string) ([]byte, error) { |
| 110 | var builder ScriptBuilder |
| 111 | |
| 112 | // We'll a bufio scanner to take care of some of the parsing for us. |
| 113 | // bufio.ScanWords will split on word boundaries, based on unicode |
| 114 | // characters. |
| 115 | scanner := bufio.NewScanner(strings.NewReader(script)) |
| 116 | scanner.Split(bufio.ScanWords) |
| 117 | |
| 118 | // Run through each word, deciding if we should add an op code, a push |
| 119 | // data, or an integer value. |
| 120 | for scanner.Scan() { |
| 121 | token := scanner.Text() |
| 122 | switch { |
| 123 | // If it starts with OP_, then we'll try to parse out the op |
| 124 | // code. |
| 125 | case strings.HasPrefix(token, "OP_"): |
| 126 | opcode, ok := OpcodeByName[token] |
| 127 | if !ok { |
| 128 | return nil, fmt.Errorf("unknown opcode: "+ |
| 129 | "%s", token) |
| 130 | } |
| 131 | |
| 132 | builder.AddOp(opcode) |
| 133 | |
| 134 | // If it has an 0x prefix, then we'll try to decode it as a hex |
| 135 | // string to push data. |
| 136 | case strings.HasPrefix(token, "0x"): |
| 137 | data, err := hex.DecodeString( |
| 138 | strings.TrimPrefix(token, "0x"), |
| 139 | ) |
| 140 | if err != nil { |
| 141 | return nil, fmt.Errorf("invalid hex "+ |
| 142 | "data: %s", token) |
| 143 | } |
| 144 | |
| 145 | builder.AddData(data) |
| 146 | |
| 147 | // Next, we'll try to parse ints for the integer op code. |
| 148 | case looksLikeInt(token): |
| 149 | val, err := strconv.ParseInt(token, 10, 64) |
| 150 | if err != nil { |
| 151 | return nil, fmt.Errorf("invalid "+ |
| 152 | "integer: %s", token) |
| 153 | } |
| 154 | |
| 155 | builder.AddInt64(val) |
| 156 | |
| 157 | // Otherwise, we assume it's a byte string without the 0x |
| 158 | // prefix. |
| 159 | default: |
| 160 | data, err := hex.DecodeString(token) |
| 161 | if err != nil { |
| 162 | return nil, fmt.Errorf("invalid token: %s", |
| 163 | token) |
| 164 | } |
| 165 | |
| 166 | builder.AddData(data) |
no test coverage detected
searching dependent graphs…