This repository has been archived by the owner on Oct 15, 2024. It is now read-only.
forked from koii-network/kohaku
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
570 lines (520 loc) · 17.9 KB
/
index.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
const { serialize, deserialize } = require("v8");
const { BigNumber } = require("bignumber.js");
const clarity = require("@weavery/clarity");
const smartweave = require("smartweave");
const { execute } = require("smartweave/lib/contract-step");
const {
arrayToHex,
getTag,
normalizeContractSource
} = require("smartweave/lib/utils");
const { SmartWeaveGlobal } = require("smartweave/lib/smartweave-global");
// Maximum number of transactions we can get from graphql at once
const MAX_REQUEST = 100;
const CHUNK_SIZE = 2000;
/**
* Cache singleton
*
* cache: {
* contracts: {
* [contractTxId]: {
* info: {
* contractSrcTxId: string,
* owner: string
* }
* state: unknown
* validity: {
* [transactionId]: boolean
* }
* }
* },
* contractSrcs: {
* [contractSrcTxId]: {
* contractSrc: string,
* handler: Function,
* isRecursive: boolean
* }
* },
* height: number
* }
*/
let cache = {
contracts: {},
contractSrcs: {},
height: 0
};
let readLock = false;
let swGlobal;
/**
* Imports a cache externally. Used to improve startup times
* @param {string} importString JSON string to be deserialized
*/
function importCache(arweave, importString) {
if (!swGlobal) swGlobal = new SmartWeaveGlobal(arweave, {});
cache = JSON.parse(importString);
for (const contractSrcId in cache.contractSrcs) {
const srcData = cache.contractSrcs[contractSrcId];
const returningSrc = normalizeContractSource(srcData.contractSrc);
const getContractFunction = new Function(returningSrc);
srcData.handler = getContractFunction(swGlobal, BigNumber, clarity);
}
}
/**
* Exports the cache as a serialized JSON string, this can be slow so use sparingly
* @param {string[]?} exportContracts Array containing contracts to export. Will export all contracts if falsy
* @returns {string} Cache serialized in JSON as a string
*/
function exportCache(exportContracts) {
if (!exportContracts) return JSON.stringify(cache);
const contracts = {},
contractSrcs = {};
for (const id in cache.contracts) {
if (!exportContracts.includes(id)) continue;
contracts[id] = cache.contracts[id];
const src = cache.contracts[id].info.contractSrcTxId;
if (!(src in contractSrcs)) contractSrcs[src] = cache.contractSrcs[src];
}
return JSON.stringify({ contracts, contractSrcs, height: cache.height });
}
/**
* Exports recursive contracts in the cache as a serialized JSON string, this can be slow so use sparingly
* @param {string[]?} exportContracts Array containing recursive contracts to export. Will export all contracts if falsy
* @returns {string} Cache serialized in JSON as a string
*/
function exportRecursiveCache(exportContracts) {
const contracts = {},
contractSrcs = {};
for (const id in cache.contracts) {
const src = cache.contracts[id].info.contractSrcTxId;
if (
(exportContracts && !exportContracts.includes(id)) ||
!cache.contractSrcs[src].isRecursive
)
continue;
contracts[id] = cache.contracts[id];
if (!(src in contractSrcs)) contractSrcs[src] = cache.contractSrcs[src];
}
return JSON.stringify({ contracts, contractSrcs, height: cache.height });
}
/**
* Reads a contract from the cache as a string, will error if contract is not present in cache
* @param {string} contractId Transaction ID of the contract to read
* @param {boolean} returnValidity if true, the function will return valid and invalid transaction IDs along with the state
* @returns {{string} | {string, string}} String or object that includes the state and validity array as strings
*/
function readContractCache(contractId, returnValidity) {
const state = cache.contracts[contractId].state;
if (!returnValidity) return state;
const validity = cache.contracts[contractId].validity;
return { state, validity };
}
/**
* Get Contract IDs in cache
* @returns {string[]} Contract IDs in present cache
*/
function getCacheContractIds() {
return Object.keys(cache.contracts);
}
/**
* Checks whether a contract is cached
* @param {string} contractId Transaction ID of the contract to check
* @returns {boolean} Whether a contract is present in the cache
*/
function isContractCached(contractId) {
return Object.prototype.hasOwnProperty.call(cache.contracts, contractId);
}
/**
* Mutex-like lock to prevent state rewriting
* @param {Arweave} arweave Arweave client instance
* @param {string} contractId Transaction Id of the contract
* @param {number} height if specified the contract will be replayed only to this block height
* @param {boolean} returnValidity if true, the function will return valid and invalid transaction IDs along with the state
*/
async function readContract(arweave, contractId, height, returnValidity) {
if (readLock) return _readContract(arweave, contractId, -1, returnValidity);
readLock = true;
try {
const res = await _readContract(
arweave,
contractId,
height,
returnValidity
);
readLock = false;
return res;
} catch (e) {
readLock = false;
throw e;
}
}
/**
* Reads contract and returns state if height matches, otherwise, executes
* new transactions across all contracts up to block height then return state
* @param {Arweave} arweave Arweave client instance
* @param {string} contractId Transaction Id of the contract
* @param {number} height if specified the contract will be replayed only to this block height
* @param {boolean} returnValidity if true, the function will return valid and invalid transaction IDs along with the state
*/
async function _readContract(arweave, contractId, height, returnValidity) {
// If height undefined, default to current network height
if (typeof height !== "number")
height = (await arweave.network.getInfo()).height;
// Return what's in the current cache if height <= cache height
if (height < cache.height && height !== -1)
console.warn(
"Kohaku read height is less than cache height, defaulting to cache height"
);
if (height <= cache.height && contractId in cache.contracts) {
const state = JSON.parse(cache.contracts[contractId].state);
if (!returnValidity) return state;
const validity = JSON.parse(cache.contracts[contractId].validity);
return { state, validity };
}
if (height < cache.height) height = cache.height;
if (!Object.keys(cache.contracts).length)
console.log("Initializing Kohaku cache with root", contractId);
// If not contract in local cache, load it
let newContract;
if (!cache.contracts[contractId]) {
const [info, state] = await loadContract(arweave, contractId);
// Return current height for newly loaded recursive contracts
if (
cache.contractSrcs[info.contractSrcTxId].isRecursive &&
height === cache.height
)
return returnValidity ? { state, validity: {} } : state;
newContract = {
info,
state,
validity: {}
};
}
// Fetch and sort transactions for all contracts since cache height up to height
const partialReads = Object.keys(cache.contracts);
let txQueue = [];
if (newContract) {
if (cache.contractSrcs[newContract.info.contractSrcTxId].isRecursive)
partialReads.push(contractId);
else
txQueue = await fetchTransactions(
arweave,
[contractId],
undefined,
height
);
}
txQueue = txQueue.concat(
await fetchTransactions(arweave, partialReads, cache.height + 1, height)
);
await sortTransactions(arweave, txQueue);
// Clone cache to new cache
const newContracts = newContract ? { [contractId]: newContract } : {};
for (const key in cache.contracts) {
const contract = cache.contracts[key];
newContracts[key] = {
info: contract.info,
state: JSON.parse(contract.state),
validity: JSON.parse(contract.validity)
};
}
const newCache = {
contracts: newContracts,
height: cache.height
};
// Sort and execute transactions to update the state
while (txQueue.length) {
const currentTx = txQueue.shift().node;
if (currentTx.block.height > newCache.height)
newCache.height = currentTx.block.height;
await executeTx(currentTx);
}
// Save reference to results
const state = newCache.contracts[contractId].state;
const validity = newCache.contracts[contractId].validity;
// Update state cache and return state, only update cache here so any errors won't mutate the cache
for (const id in newCache.contracts) {
const contract = newCache.contracts[id];
// Cache as string for better immutability and clone performance
contract.state = JSON.stringify(contract.state);
contract.validity = JSON.stringify(contract.validity);
}
cache.contracts = newCache.contracts;
cache.height = newCache.height;
// Return results
return returnValidity ? { state, validity } : state;
// TODO FIXME Contract evolution is not supported
/**
* Used for reading a contract within a contract, does not do any execution unless non-recursive
* @param {string} contractId Transaction Id of the contract
*/
async function internalReadContract(_contractId, _height, _returnValidity) {
_height = _height || newCache.height;
if (_height !== newCache.height)
throw new Error(
"Kohaku internal read height must match transaction height"
);
// If not contract in local cache
if (!newCache.contracts[_contractId]) {
// Load and cache it
const [info, state] = await loadContract(arweave, _contractId);
newCache.contracts[_contractId] = {
info,
state,
validity: {}
};
let newTxs;
// Add txs from recursive contracts to txQueue
if (cache.contractSrcs[info.contractSrcTxId].isRecursive) {
newTxs = await fetchTransactions(
arweave,
[_contractId],
newCache.height + 1,
height
);
} else {
// For non recursive contracts, immediately execute txs below height
newTxs = await fetchTransactions(
arweave,
[_contractId],
undefined,
height
);
if (newTxs.length) {
await sortTransactions(arweave, newTxs);
let i = 0;
while (
i < newTxs.length &&
newTxs[i].node.block.height <= newCache.height
)
++i;
const nonRecTxs = newTxs.slice(0, i);
while (nonRecTxs.length) await executeTx(nonRecTxs.shift().node);
// Add remaining to txQueue
newTxs = newTxs.slice(i);
}
}
// Fetch and sort new transactions for this contract since cache height up to height
if (newTxs.length) {
txQueue = txQueue.concat(newTxs);
await sortTransactions(arweave, txQueue);
}
}
// Clone output variables so newCache state isn't mutated
const cacheContract = newCache.contracts[_contractId];
const state = clone(cacheContract.state);
if (!_returnValidity) return state;
const validity = clone(cacheContract.validity);
return { state, validity };
}
async function executeTx(currentTx) {
let txContractId, input;
const tags = currentTx.tags;
for (let i = 0; i < tags.length - 1; ++i) {
if (
tags[i].name === "Contract" &&
tags[i].value in newCache.contracts &&
tags[i + 1].name === "Input"
) {
txContractId = tags[i].value;
input = tags[i + 1].value;
break;
}
}
if (!txContractId) return;
// Get transaction input
try {
input = JSON.parse(input);
} catch (e) {
return;
}
if (!input) return;
// Setup execution env
const contract = newCache.contracts[txContractId];
const handler = cache.contractSrcs[contract.info.contractSrcTxId].handler;
swGlobal.contract.id = txContractId;
swGlobal.contract.owner = contract.info.owner;
swGlobal.contracts.readContractState = internalReadContract; // TODO remove this from hotpath, only needs to be set once
swGlobal._activeTx = currentTx;
const interaction = { input, caller: currentTx.owner.address };
// Execute and update contract
const result = await execute(
handler,
interaction,
newCache.contracts[txContractId].state
);
contract.validity[currentTx.id] = result.type === "ok";
contract.state = result.state;
}
}
/**
* Loads the contract source, initial state and other parameters
* @param arweave an Arweave client instance
* @param contractID the Transaction Id of the contract
*/
async function loadContract(arweave, contractID, contractSrcTxId) {
// Generate an object containing the details about a contract in one place.
const contractTX = await arweave.transactions.get(contractID);
const contractOwner = await arweave.wallets.ownerToAddress(contractTX.owner);
contractSrcTxId = contractSrcTxId || getTag(contractTX, "Contract-Src");
let state;
if (getTag(contractTX, "Init-State")) {
state = getTag(contractTX, "Init-State");
} else if (getTag(contractTX, "Init-State-TX")) {
const stateTX = await arweave.transactions.get(
getTag(contractTX, "Init-State-TX")
);
state = stateTX.get("data", { decode: true, string: true });
} else {
state = contractTX.get("data", { decode: true, string: true });
}
if (!swGlobal) swGlobal = new SmartWeaveGlobal(arweave, {});
if (
!Object.prototype.hasOwnProperty.call(cache.contractSrcs, contractSrcTxId)
) {
const contractSrcTX = await arweave.transactions.get(contractSrcTxId);
const contractSrc = contractSrcTX.get("data", {
decode: true,
string: true
});
const returningSrc = normalizeContractSource(contractSrc);
const getContractFunction = new Function(returningSrc);
cache.contractSrcs[contractSrcTxId] = {
contractSrc,
handler: getContractFunction(swGlobal, BigNumber, clarity),
isRecursive: contractSrc.includes("readContractState")
};
}
return [
{
contractSrcTxId,
owner: contractOwner
},
JSON.parse(state)
];
}
/**
* Grab all transactions from a specific height
* @param {Arweave} arweave Arweave client instance
* @param {string[]} contractIds Array of contract IDs to fetch
* @param {number} min Lowest block to fetch from
* @param {number} max Highest block to fetch from
* @returns {any[]} Transaction objects
*/
async function fetchTransactions(arweave, contractIds, min, max) {
min = min || 1; // Using a min block height of 1 removes null blocks
let txInfos = [];
for (let i = 0; i < contractIds.length; i += CHUNK_SIZE) {
const chunk = contractIds.slice(i, i + CHUNK_SIZE);
let variables = {
tags: [
{ name: "App-Name", values: ["SmartWeaveAction"] },
{ name: "Contract", values: chunk }
],
blockFilter: { min, max },
first: MAX_REQUEST
};
let transactions = await getNextPage(arweave, variables);
txInfos = txInfos.concat(
transactions.edges.filter((tx) => !tx.node.parent || !tx.node.parent.id)
);
while (transactions.pageInfo.hasNextPage) {
const cursor = transactions.edges[MAX_REQUEST - 1].cursor;
variables = {
...variables,
after: cursor
};
transactions = await getNextPage(arweave, variables);
txInfos = txInfos.concat(
transactions.edges.filter((tx) => !tx.node.parent || !tx.node.parent.id)
);
}
}
return txInfos;
}
/**
* Get cache height
* returns {number} Last guaranteed block height processed
*/
function getCacheHeight() {
return cache.height;
}
/**
* Gets the next GQL page and check for null blocks. Throws error on null block
* @param {Arweave} arweave Arweave instance
* @param {*} variables GQL query variables
* @returns {*[]} Array of transactions
*/
async function getNextPage(arweave, variables) {
const query = `query Transactions($tags: [TagFilter!]!, $blockFilter: BlockFilter!, $first: Int!, $after: String) {
transactions(tags: $tags, block: $blockFilter, first: $first, sort: HEIGHT_ASC, after: $after) {
pageInfo { hasNextPage }
edges {
node {
id
owner { address }
recipient
tags { name value }
block { height id timestamp }
fee { winston }
quantity { winston }
parent { id }
}
cursor
}
}
}`;
const response = await arweave.api.post("graphql", {
query,
variables
});
if (response.status !== 200) {
throw new Error(
`Unable to retrieve transactions. Arweave gateway responded with status ${response.status}.`
);
}
const data = response.data;
const txs = data.data.transactions;
if (txs.edges.some((tx) => tx.node.block === null)) {
const nullBlockError = new Error("Null block found");
nullBlockError.name = "Null block";
throw nullBlockError;
}
return txs;
}
/**
* Deep clones an object
* @param {unknown} obj Object to be cloned
* @returns {unknown} Cloned object
*/
function clone(obj) {
return deserialize(serialize(obj));
}
// Exact copy of smartweave implementation
async function sortTransactions(arweave, txInfos) {
const addKeysFuncs = txInfos.map((tx) => addSortKey(arweave, tx));
await Promise.all(addKeysFuncs);
txInfos.sort((a, b) => a.sortKey.localeCompare(b.sortKey));
}
async function addSortKey(arweave, txInfo) {
const { node } = txInfo;
const blockHashBytes = arweave.utils.b64UrlToBuffer(node.block.id);
const txIdBytes = arweave.utils.b64UrlToBuffer(node.id);
const concatted = arweave.utils.concatBuffers([blockHashBytes, txIdBytes]);
const hashed = arrayToHex(await arweave.crypto.hash(concatted));
const blockHeight = `000000${node.block.height}`.slice(-12);
txInfo.sortKey = `${blockHeight},${hashed}`;
}
// Create a proxy wrapper over the smartweave object for exporting
const smartweaveProxy = {
readContract,
readContractCache,
getCacheHeight,
getCacheContractIds,
isContractCached,
importCache,
exportCache,
exportRecursiveCache
};
for (const key in smartweave)
if (key !== "readContract") smartweaveProxy[key] = smartweave[key];
module.exports = smartweaveProxy;