forked from rareweave/glome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexecute.js
224 lines (203 loc) · 10.2 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
const Arweave = require('arweave');
const ivm = require('isolated-vm');
const { LuaFactory } = require('wasmoon')
let fs = require("fs");
const { wait } = 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(2.56e+8)
isolate.global.setTimeout(Date.now() + 2000)
isolate.global.set("console",console)
isolate.global.set("print",console.log)
isolate.global.set("UncacheableError",(msg)=>{
notCache=true;
isolate.global.get("error")(msg)
})
let code=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;
isolate.global.get("error")(msg)
}),
viewContractState: (id) => require("./reader-api.js").viewUpTo(id, interaction.timestamp,(msg)=>{
notCache=true;
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
})
await lua.doString(executionContexts[contractInfo.id].script)
let handle=executionContexts[contractInfo.id].isolate.global.get("handle")
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{
throw new Error(e)
}
}
return res
}
async function executeJS(codeId, state, interaction, contractInfo) {
if (!executionContexts[contractInfo.id] || executionContexts[contractInfo.id].codeId != codeId) {
const isolate = new ivm.Isolate({ memoryLimit: 256 });
const context = isolate.createContextSync();
const arweave = Arweave.init({
host: 'arweave.net',
port: 443,
protocol: 'https'
});
context.global.setSync("global", context.global.derefInto())
context.global.setSync('console', convertToRuntimePassable(console));
context.evalSync(`
global.ContractError=class ContractError extends Error { constructor(message) { super(message); this.name = \'ContractError\' } };
global.UncacheableError = class UncacheableError extends Error { constructor(message) { super(message); this.name = \'UncacheableError\' } };
global.ContractAssert= function ContractAssert(cond, message) { if (!cond) throw new ContractError(message) };
`)
let code = await databases.codes.get(codeId)
let contractScript = isolate.compileScriptSync(code.split("export default").join("").split("export").join(""));
executionContexts[contractInfo.id] = {
codeId: codeId,
script: contractScript,
arweaveClient: arweave,
isolate: isolate,
context: context
}
}
let internals = new ivm.Reference({})
executionContexts[contractInfo.id].context.global.setSync("internals", internals)
executionContexts[contractInfo.id].context.global.setSync("SmartWeave", convertToRuntimePassable({
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))
executionContexts[contractInfo.id].context.global.setSync("_ivm", ivm)
executionContexts[contractInfo.id].context.evalSync(executePromisifyWarmup)
await executionContexts[contractInfo.id].script.run(executionContexts[contractInfo.id].context)
executionContexts[contractInfo.id].context.global.setSync("__state", convertToRuntimePassable(state))
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
executionContexts[contractInfo.id].context.global.setSync("__action", convertToRuntimePassable({ input: JSON.parse(input), caller: interaction.owner.address }))
return (await executionContexts[contractInfo.id].context.evalSync(`handle(__state,__action)`, { promise: true, externalCopy: true })).copy()
}
class UncacheableError extends Error { constructor(message) {this.name = 'UncacheableError'; super(message)} }
module.exports = execute