This repository has been archived by the owner on Jan 10, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
solc-server.js
executable file
·393 lines (337 loc) · 11.4 KB
/
solc-server.js
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#!/usr/bin/env node
// OPTIONS:
// -d: development mode. If set, open 'localhost:8080' in the browser, use the local build instead
// --path=<PATH>: path to the default directory (optional, use working directory if missing)
const argv = require('minimist')(process.argv.slice(2))
for(let key in process.argv) {
if(process.argv[key].startsWith('--path=')) {
process.argv.splice(key, 1)
break
}
}
const FILE_SEPARATOR = process.platform == 'win32' ? '\\': '/'
var directory = argv.path ? argv.path : process.cwd()
const PORT = 8081
const FORBIDDEN_CHARACTERS = "\\\\|<|>|:|\\\"|\\'|\\||\\?|\\*|~|#|\\n|\\t|\\v|\\f|\\r"
const fs = require('fs')
const solc = require('solc')
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const ignored = ['build', 'node_modules']
console.log("Starting solc server...")
if(!directory.endsWith(FILE_SEPARATOR))
directory += FILE_SEPARATOR
if (!fs.existsSync(directory) || !fs.lstatSync(directory).isDirectory()) {
console.error('"' + directory + '" doesn\'t exist or is not a directory.')
process.exit(1)
}
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Methods", "OPTIONS, HEAD, GET, POST, PUT, DELETE")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
res.header("Content-Type", "application/json")
next()
})
app.get('/compile', function (req, res) {
const sources = listDirForCompile('', {})
const input = {
language: 'Solidity',
sources: sources,
settings: {
outputSelection: {
'*': {
'*': [ '*' ]
}
}
}
}
let output = solc.compile(JSON.stringify(input))
output = output.replace(new RegExp(directory.replace(/\\/g, '\\\\\\\\').replace(/\./g, '\\.'), 'g'), '')
if(process.platform == 'win32') {
output = output.replace(/\//g, FILE_SEPARATOR.repeat(2))
}
// Save built files
const jsonOutput = JSON.parse(output)
rmdir(directory + 'build')
for(let file in jsonOutput.contracts) {
const contract = jsonOutput.contracts[file]
for(let contractName in contract) {
const dir = directory + 'build' + FILE_SEPARATOR + file + FILE_SEPARATOR + contractName
try {
fs.mkdirSync(dir, { recursive: true })
} catch(err) {
fs.mkdirSync(dir, { recursive: true })
}
fs.writeFileSync(dir + FILE_SEPARATOR + contractName + '_bytecode.json', JSON.stringify(contract[contractName].evm.bytecode))
fs.writeFileSync(dir + FILE_SEPARATOR + contractName + '_abi.json', JSON.stringify(contract[contractName].abi))
}
}
res.end(output)
console.log('Compile')
})
//------------------------------------
// FILESYSTEM
app.get('/directory', function(req, res) {
try {
if(req.query.root) {
if (!fs.existsSync(req.query.root) || !fs.lstatSync(req.query.root).isDirectory()) {
res.status(400)
res.end('Given root directory doesn\'t exist or is not a directory.')
return
}
directory = req.query.root
if(!directory.endsWith('/'))
directory += '/'
if(process.platform == 'win32') {
directory = directory.replace(/\//g, FILE_SEPARATOR)
}
console.log('Change root directory: ' + directory)
}
if(req.query.dir) {
if (!fs.existsSync(directory + req.query.dir) || !fs.lstatSync(directory + req.query.dir).isDirectory()) {
res.status(400)
res.end('Given directory doesn\'t exist or is not a directory.')
return
}
if(!req.query.dir.endsWith('/')) {
req.query.dir += '/'
}
if(process.platform == 'win32') {
req.query.dir = req.query.dir.replace(/\//g, FILE_SEPARATOR)
}
}
const path = req.query.dir ? req.query.dir : ''
const result = listDir(path)
res.end(JSON.stringify(result))
console.log('List directory content: ' + (path.length ? path : './'))
} catch(error) {
res.status(403)
res.end(error.message)
console.log('Couldn\'t list directory content: ' + file)
}
})
// Fetch file
app.get('/file', function(req, res) {
if(req.query.file) {
let file = directory + req.query.file
if(process.platform == 'win32') {
file = file.replace(/\//g, FILE_SEPARATOR)
}
if (validateFile(file, res)) {
try {
res.end(fs.readFileSync(file).toString())
console.log('Fetch file: ' + file)
} catch(error) {
res.status(403)
res.end(error.message)
console.log('Couldn\'t fetch file: ' + file)
}
}
} else {
res.status(400)
res.end('File is required.')
}
})
// Create file
app.post('/create', function(req, res) {
if(req.body.file) {
let path = directory + req.body.file
if(process.platform == 'win32') {
path = path.replace(/\//g, FILE_SEPARATOR)
}
if (new RegExp(FORBIDDEN_CHARACTERS).test(req.body.file)) {
res.status(400)
res.end('Given file name contains forbidden characters.')
return
} else if(!validateSolidityFile(path)) {
res.status(400)
res.end('Given file is not a solidity file.')
return
} else if (fs.existsSync(path)) {
res.status(400)
res.end('File already exists.')
return
}
try {
if(path.indexOf(FILE_SEPARATOR) != -1) {
fs.mkdirSync(path.substring(0, path.lastIndexOf(FILE_SEPARATOR)), { recursive: true })
}
fs.writeFileSync(path, '')
res.status(201)
res.end()
console.log('Create file: ' + path)
} catch(error) {
res.status(403)
res.end(error.message)
console.log('Couldn\'t create file: ' + file)
}
} else {
res.status(400)
res.end('File is required.')
}
})
// Save file
app.put('/save', function(req, res) {
let file = ''
if(req.body.file) {
file = directory + req.body.file
if(process.platform == 'win32') {
file = file.replace(/\//g, FILE_SEPARATOR)
}
if (!validateFile(file, res)) {
return
}
} else {
res.status(400)
res.end('File is required.')
return
}
if(req.body.content != undefined) {
try {
fs.writeFileSync(file, req.body.content)
res.status(204)
res.end()
console.log('Save file: ' + file)
} catch(error) {
res.status(403)
res.end(error.message)
console.log('Couldn\'t save file: ' + error.message)
}
} else {
res.status(400)
res.end('Content is required.')
}
})
// Delete file
app.delete('/delete', function(req, res) {
if(req.body.file) {
let file = directory + req.body.file
if(process.platform == 'win32') {
file = file.replace(/\//g, FILE_SEPARATOR)
}
if (validateFile(file, res)) {
try {
fs.unlinkSync(file)
res.status(204)
res.end()
console.log('Delete file: ' + file)
} catch(error) {
res.status(403)
res.end(error.message)
console.log('Couldn\'t delete file: ' + error.message)
}
}
} else {
res.status(400)
res.end('File is required.')
return
}
})
function listDir(dir) {
const result = []
const items = fs.readdirSync(directory + dir)
for(let key in items) {
const item = items[key]
try {
const stats = fs.lstatSync(directory + dir + item)
if((stats.isFile() && !item.endsWith('.sol')) || (!stats.isFile() && !stats.isDirectory())) {
continue // Skip non-sol files and non-directories
}
const file = {name: item, path: (dir + item).replace(/\\/g, '/'), directory: stats.isDirectory(), state: 0, saved: true}
result.push(file)
if(stats.isDirectory()) {
file.childs = []
}
} catch(err) {
// Ignore files without permission
}
}
return result
}
function listDirForCompile(dir, result) {
const items = fs.readdirSync(directory + dir)
for(let key in items) {
const item = items[key]
const path = directory + dir + item
const stats = fs.lstatSync(path)
if(stats.isFile() && item.endsWith('.sol')) { // Skip non-sol files and non-directories
try {
fs.accessSync(path, fs.constants.R_OK)
result[path] = { content: fs.readFileSync(path).toString() }
} catch(err) {
// Skip if no read permission
}
}
if(stats.isDirectory() && checkNotIgnored(item)) {
listDirForCompile(dir + item + '/', result)
}
}
return result
}
function checkNotIgnored(dir) {
for(let key in ignored) {
if(dir.endsWith(ignored[key])) {
return false
}
}
return true
}
function validateFile(path, res) {
try {
fs.accessSync(path, fs.constants.S_IFREG & fs.constants.R_OK)
if (!path.endsWith('.sol')) {
res.status(400)
res.end('Given file doesn\'t exist or is not a solidity file.')
return false
}
} catch(error) {
res.status(403)
res.end(error.message)
return false
}
return true
}
function validateSolidityFile(path) {
return path.endsWith('.sol') && path.substring(path.lastIndexOf('/') + 1) != '.sol'
}
function rmdir(path) {
let files = [];
while(fs.existsSync(path)) {
files = fs.readdirSync(path)
for(let key in files) {
const curPath = path + FILE_SEPARATOR + files[key]
if(fs.lstatSync(curPath).isDirectory()) {
rmdir(curPath)
} else {
fs.unlinkSync(curPath)
}
}
try {
fs.rmdirSync(path)
} catch(err) { /* try again if failed (windows patch) */ }
}
}
// TODO Create directory without creating file
//------------------------------------
app.get('/shutdown', function() {
console.log('IDE closed, exiting.')
process.exit(0)
})
app.listen(PORT, 'localhost', function () {
console.log('Started solc server. Listening on localhost:' + PORT + ', directory "' + directory + '"')
})
if(argv.noganache !== true) {
setTimeout(function() {
console.log("Starting ganache...")
require('ganache-cli/cli')
}, 1)
}
if(argv.d !== true) { // Not in dev mode
let url = '"file://' + __dirname + '/dist/index.html"'
if(process.platform == 'win32') url = '"" ' + url
const start = (process.platform == 'darwin'? 'open': process.platform == 'win32' ? 'start': 'xdg-open')
require('child_process').exec(start + ' ' + url)
}