-
Notifications
You must be signed in to change notification settings - Fork 5
/
compiler.go
249 lines (215 loc) · 5.05 KB
/
compiler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package solc
import (
"bytes"
"crypto/sha256"
_ "embed"
"encoding/json"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"sync"
"github.com/lmittmann/go-solc/internal/console"
"github.com/lmittmann/go-solc/internal/mod"
"golang.org/x/sync/singleflight"
)
var (
// The path within the module root where solc binaries are stored.
binPath = ".solc/bin/"
perm = os.FileMode(0o0775)
// global compiler cache
group = new(singleflight.Group)
cacheMux sync.RWMutex
cache = make(map[string]cacheItem)
)
type cacheItem struct {
out *output
err error
}
type Compiler struct {
version SolcVersion // Solc version
once sync.Once
solcAbsPath string // solc absolute path
err error // initialization error
}
func New(version SolcVersion) *Compiler {
return &Compiler{
version: version,
}
}
// init initializes the compiler.
func (c *Compiler) init() {
// check mod root is set
if mod.Root == "" {
c.err = fmt.Errorf("solc: no go.mod detected")
return
}
// check or download solc version
c.solcAbsPath, c.err = checkSolc(c.version)
}
// Compile all contracts in the given directory and return the contract code of
// the contract with the given name.
func (c *Compiler) Compile(dir, contract string, opts ...Option) (*Contract, error) {
out, err := c.compile(dir, contract, opts)
if err != nil {
return nil, err
}
// check for compilation errors
if err := out.Err(); err != nil {
return nil, err
}
// find contract code
var con *Contract
for _, conMap := range out.Contracts {
for conName, c := range conMap {
if conName == contract {
con = &Contract{
Runtime: c.EVM.DeployedBytecode.Object,
Constructor: c.EVM.Bytecode.Object,
Code: c.EVM.DeployedBytecode.Object,
DeployCode: c.EVM.Bytecode.Object,
}
break
}
}
}
if con == nil {
return nil, fmt.Errorf("solc: unknown contract %q", contract)
}
return con, nil
}
// MustCompile is like [Compiler.Compile] but panics on error.
func (c *Compiler) MustCompile(dir, contract string, opts ...Option) *Contract {
code, err := c.Compile(dir, contract, opts...)
if err != nil {
panic(err)
}
return code
}
// compile
func (c *Compiler) compile(baseDir, contract string, opts []Option) (*output, error) {
// init an return on error
c.once.Do(c.init)
if c.err != nil {
return nil, c.err
}
// check the directory exists
if stat, err := os.Stat(baseDir); err != nil || !stat.IsDir() {
return nil, err
}
// get absolute path of base directory
absDir, err := filepath.Abs(baseDir)
if err != nil {
return nil, err
}
// build src map
srcMap, err := buildSrcMap(absDir)
if err != nil {
return nil, err
}
// add console.sol to src map
srcMap["console.sol"] = src{
Content: console.Src,
}
// build settings
s := c.buildSettings(opts)
in := &input{
Lang: s.lang,
Sources: srcMap,
Settings: s,
}
// run solc
return c.runWithCache(absDir, in)
}
func (c *Compiler) runWithCache(baseDir string, in *input) (*output, error) {
// hash input
h := sha256.New()
if err := json.NewEncoder(h).Encode(in); err != nil {
return nil, err
}
var hash [32]byte
h.Sum(hash[:0])
// run with cache
cacheKey := fmt.Sprintf("%s_%x", c.version, hash)
out, err, _ := group.Do(cacheKey, func() (any, error) {
// check cache
cacheMux.RLock()
val, ok := cache[cacheKey]
cacheMux.RUnlock()
if ok {
return val.out, val.err
}
// run solc
out, err := c.run(baseDir, in)
// update cache
cacheMux.Lock()
cache[cacheKey] = cacheItem{out, err}
cacheMux.Unlock()
return out, err
})
if err != nil {
return nil, err
}
return out.(*output), nil
}
func (c *Compiler) run(baseDir string, in *input) (*output, error) {
inputBuf := bytes.NewBuffer(nil)
outputBuf := bytes.NewBuffer(nil)
// encode input
if err := json.NewEncoder(inputBuf).Encode(in); err != nil {
return nil, err
}
// run solc
ex := exec.Command(c.solcAbsPath,
"--allow-paths", baseDir,
"--standard-json",
)
ex.Stdin = inputBuf
ex.Stdout = outputBuf
if err := ex.Run(); err != nil {
return nil, err
}
// decode output
var output *output
if err := json.NewDecoder(outputBuf).Decode(&output); err != nil {
return nil, err
}
return output, nil
}
func buildSrcMap(absDir string) (map[string]src, error) {
fsys := os.DirFS(absDir)
srcMap := make(map[string]src)
err := fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error {
if d.IsDir() || filepath.Ext(p) != ".sol" {
return nil
}
srcMap[p] = src{
URLS: []string{filepath.Join(absDir, p)},
}
return nil
})
if err != nil {
return nil, err
}
return srcMap, nil
}
// buildSettings builds the default settings and applies all options.
func (c *Compiler) buildSettings(opts []Option) *Settings {
defaultEVMVersion, ok := defaultEVMVersions[c.version]
if !ok {
panic("unexpected solc version")
}
s := &Settings{
lang: defaultLang,
Remappings: defaultRemappings,
Optimizer: defaultOptimizer,
ViaIR: defaultViaIR,
EVMVersion: defaultEVMVersion,
}
for _, opt := range opts {
opt(s)
}
s.OutputSelection = defaultOutputSelection
return s
}