-
Notifications
You must be signed in to change notification settings - Fork 2
/
execute.js
242 lines (206 loc) · 9.94 KB
/
execute.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
const Arweave = require('arweave');
const Glomium=require("glomium")
const { LuaFactory } = require('glome-wasmoon')
let fs = require("fs");
const { wait,syncify } = require('./utils.js');
const luaFactory = new LuaFactory()
const executePromisifyWarmup = fs.readFileSync("./execute-promisify-warmup.js", "utf-8")
let executionContexts = {}
function callbackify(O, internals) {
let mO;
if (!O) { return O }
if (!Array.isArray(O)) {
mO = {}
Object.keys(O).forEach(k => {
if (typeof O[k] == 'function') {
if (O[k].constructor.name === "AsyncFunction") {
let internalName = Date.now().toString(16) + (Math.random().toString(16).split(".")[1])
internals.setSync(internalName, new ivm.Callback((resolve, reject, args) => {
// console.log("hello");
(O[k](...args)).then(res => resolve.applyIgnored(undefined, [new ivm.ExternalCopy(res).copyInto()])).catch(e => reject.applyIgnored(undefined, [new ivm.ExternalCopy(e).copyInto()]))
}));
mO[k] = "glome-internal:" + internalName
// new ivm.Reference(async (...args) => { return new ivm.ExternalCopy(await O[k](...args)) })
} else {
mO[k] = new ivm.Callback((...args) => { return new ivm.ExternalCopy(O[k](...args)).copyInto() })
}
} else if (typeof O[k] == "object") {
mO[k] = callbackify(O[k], internals)
} else {
mO[k] = O[k]
}
})
} else {
mO = [];
O.forEach((el, elIndex) => {
if (typeof el == "function") {
if (el.constructor.name === "AsyncFunction") {
let internalName = Date.now().toString(16) + (Math.random().toString(16).split(".")[1])
internals.setSync(internalName, new ivm.Callback((resolve, reject, args) => {
// console.log("hello");
(el(...args)).then(res => resolve.applyIgnored(undefined, [new ivm.ExternalCopy(res).copyInto()])).catch(e => reject.applyIgnored(undefined, [new ivm.ExternalCopy(e).copyInto()]))
}));
mO.push("glome-internal:" + internalName)
// new ivm.Reference(async (...args) => { return new ivm.ExternalCopy(await O[k](...args)) })
} else {
mO.push(new ivm.Callback((...args) => { return new ivm.ExternalCopy(el(...args)).copyInto() }))
}
} else if (typeof el == "object") {
mO.push(callbackify(el, internals))
} else {
mO.push(el)
}
})
}
return mO
}
function convertToRuntimePassable(O, internals) {
return new ivm.ExternalCopy(callbackify(O, internals)).copyInto()
}
async function execute(codeId,state,interaction,contractInfo){
let contractContentType=await global.databases.contentTypes.get(codeId);
return await ((
{
"application/javascript":executeJS,
"application/lua":executeLua,
})[contractContentType](codeId,state,interaction,contractInfo))
}
async function executeLua(codeId,state,interaction,contractInfo){
let notCache=false
if (!executionContexts[contractInfo.id] || executionContexts[contractInfo.id].codeId != codeId) {
let isolate = await luaFactory.createEngine({ traceAllocations: true })
const arweave = Arweave.init({
host: 'arweave.net',
port: 443,
protocol: 'https'
});
isolate.global.setMemoryMax(10e+8)
isolate.global.setTimeout(Date.now() + 8000)
isolate.global.set("console",console)
isolate.global.set("print", console.log)
console.log()
// console.log("yield", isolate.global.lua.lua_yield(isolate.global.address,0))
isolate.global.set("UncacheableError",(msg)=>{
notCache=true;
isolate.global.get("error")(msg)
})
let code = codeId == 'i6VO1Yw6bG1FdW0rH7m0tXvRKrtL7gNnd3o6SKQDg1A' ? fs.readFileSync("./contract-mock.lua", 'utf-8') : await databases.codes.get(codeId)
executionContexts[contractInfo.id] = {
codeId: codeId,
script: code,
arweaveClient: arweave,
isolate: isolate,
context: isolate
}
}
executionContexts[contractInfo.id].isolate.global.set("SmartWeave", {
extensions: global.plugins,
transaction: {
bundled: interaction.bundled,
timestamp: interaction.timestamp,
id: interaction.id,
owner: interaction.owner.address,
tags: interaction.tags,
quantity: interaction.quantity.winston,
target: interaction.recipient,
reward: interaction.fee.winston,
}, contract: {
id: contractInfo.id,
owner: contractInfo.owner.address
}, contracts: {
readContractState: (id) => require("./reader-api.js").readUpTo(id, interaction.timestamp,(msg)=>{
notCache=true;
executionContexts[contractInfo.id].isolate.global.get("error")(msg)
}),
viewContractState: (id) => require("./reader-api.js").viewUpTo(id, interaction.timestamp,(msg)=>{
notCache=true;
executionContexts[contractInfo.id].isolate.global.get("error")(msg)
})
}, block: interaction.block ? { height: interaction.block.height, timestamp: interaction.block.timestamp, indep_hash: interaction.block.id } : null,//Maybe not mined yet
arweave: {
utils: executionContexts[contractInfo.id].arweaveClient.utils, crypto:executionContexts[contractInfo.id].arweaveClient.crypto, wallets: executionContexts[contractInfo.id].arweaveClient.wallets, ar: executionContexts[contractInfo.id].arweaveClient.ar
},
unsafeClient: executionContexts[contractInfo.id].arweaveClient
})
const execThread=executionContexts[contractInfo.id].isolate.global.newThread()
await execThread.loadString(executionContexts[contractInfo.id].script)
await execThread.run()
let handle = (...args) =>execThread.call('handle',...args)
let contractCallIndex = interaction.tags.filter(tag => tag.name == "Contract").findIndex(tag => tag.value == contractInfo.id)
let input = interaction.tags.filter(tag => tag.name == "Input")[contractCallIndex]?.value
let action={ input: JSON.parse(input), caller: interaction.owner.address }
let res
try{
res=await handle(state,action)
}catch(e){
if(notCache){
throw new UncacheableError(e)
} else {
console.error(e)
throw new Error(e)
}
}
return res
}
async function runLuaFunction(main, co, funcName, args) {
// Get the function from the main thread and move it to the coroutine's stack
main.lua.lua_getglobal(main.address, funcName);
main.lua.lua_xmove(main, co.address, 1);
// Push the arguments for the function onto the coroutine's stack
for (const arg of args) {
co.pushValue(arg);
}
// Resume the coroutine, effectively running the function
return await co.runSync(args.length);
}
async function executeJS(codeId, state, interaction, contractInfo) {
if (!executionContexts[contractInfo.id] || executionContexts[contractInfo.id].codeId != codeId) {
const vm = new Glomium(config.glomiumConfig)
const arweave = Arweave.init({
host: 'arweave.net',
port: 443,
protocol: 'https'
});
context.global.setSync('console', console);
let code = await databases.codes.get(codeId)
executionContexts[contractInfo.id] = {
vm,
codeId: codeId,
code,
arweaveClient: arweave,
}
}
executionContexts[contractInfo.id].vm.clear()
await executionContexts[contractInfo.id].vm.set("SmartWeave", {
extensions: global.plugins,
transaction: {
bundled: interaction.bundled,
timestamp: interaction.timestamp,
id: interaction.id,
owner: interaction.owner.address,
tags: interaction.tags,
quantity: interaction.quantity.winston,
target: interaction.recipient,
reward: interaction.fee.winston,
}, contract: {
id: contractInfo.id,
owner: contractInfo.owner.address
}, contracts: {
readContractState: (id) => require("./reader-api.js").readUpTo(id, interaction.timestamp),
viewContractState: (id) => require("./reader-api.js").viewUpTo(id, interaction.timestamp)
}, block: interaction.block ? { height: interaction.block.height, timestamp: interaction.block.timestamp, indep_hash: interaction.block.id } : null,//Maybe not mined yet
arweave: {
utils: executionContexts[contractInfo.id].arweaveClient.utils, crypto:
{
hash: async (d,a)=>await executionContexts[contractInfo.id].arweaveClient.crypto.hash(new Uint8Array(d),a)
}, wallets: executionContexts[contractInfo.id].arweaveClient.wallets, ar: executionContexts[contractInfo.id].arweaveClient.ar
},
unsafeClient: executionContexts[contractInfo.id].arweaveClient
}, internals)
await executionContexts[contractInfo.id].vm.run(executionContexts[contractInfo.id].code)
let contractCallIndex = interaction.tags.filter(tag => tag.name == "Contract").findIndex(tag => tag.value == contractInfo.id)
let input = interaction.tags.filter(tag => tag.name == "Input")[contractCallIndex]?.value
return (await executionContexts[contractInfo.id].vm.get(`handle`))(state, { input: JSON.parse(input), caller: interaction.owner.address })
}
class UncacheableError extends Error { constructor(message) {this.name = 'UncacheableError'; super(message)} }
module.exports = execute