Skip to content

Commit

Permalink
🚚 Improve Mina Merkle path service
Browse files Browse the repository at this point in the history
  • Loading branch information
KimlikDAO-bot committed May 25, 2024
1 parent cdc659a commit 415bf3e
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 43 deletions.
2 changes: 1 addition & 1 deletion lib
Submodule lib updated 1 files
+15 βˆ’0 cloudflare/durableObject.d.js
17 changes: 7 additions & 10 deletions mina/Makefile
Original file line number Diff line number Diff line change
@@ -1,33 +1,30 @@
include mina/test/Makefile

build/mina/mina.js: mina/mina.js mina/mina.d.js \
mina/MerkleTree.js \
mina/MerkleTree.js mina/MinaState.js \
$(lib)/cloudflare/moduleWorker.d.js \
$(lib)/cloudflare/durableObject.d.js \
$(lib)/cloudflare/types.d.js \
$(lib)/crypto/poseidon.js \
$(lib)/crypto/modular.js \
$(lib)/mina/mina.d.js \
$(lib)/util/hex.js
$(lib)/util/merkleTree.js $(lib)/util/hex.js
mkdir -p $(dir $@)
mkdir -p build/input/mina && cp -rf mina/* build/input/mina/
mkdir -p build/input/node_modules/@kimlikdao
ln -sfn ../../../../$(lib) build/input/node_modules/@kimlikdao/lib
sed -i.bak '/cloudflare:workers/d' build/input/mina/MerkleTree.js
echo 'globalThis["MinaWorker"] = MinaWorker;\nglobalThis["MerkleTree"] = MerkleTree;' >> build/input/mina/mina.js
cd build/input; bun google-closure-compiler $(GCC_MODULE) \
sed -i.bak '/cloudflare:workers/d' build/input/mina/MinaState.js
echo 'globalThis["MinaWorker"] = MinaWorker;\nglobalThis["MerkleTree"] = MerkleTree;\nglobalThis["MinaState"] = MinaState;' >> build/input/mina/mina.js
cd build/input; bun google-closure-compiler $(call gccModule, $^, ../../$@) \
--jscomp_error=checkTypes \
--jscomp_error=strictCheckTypes \
--jscomp_error=unusedLocalVariables \
--jscomp_error=reportUnknownTypes \
--entry_point $< \
--js $^ \
--js_output_file ../../$@
--jscomp_error=unusedLocalVariables
rm -rf build/input/
bun uglifyjs $@ -m -c toplevel,unsafe,drop_console -o $@
bun $(lib)/birimler/bigintCompressor.js $@
wc $@

build/mina.deployment: build/mina/mina.js mina/prod.toml
bun wrangler deploy $< --compatibility-date $(shell date -v -1d +%Y-%m-%d) \
bun wrangler deploy --compatibility-date $(shell date -v -1d +%Y-%m-%d) \
--config mina/prod.toml
18 changes: 16 additions & 2 deletions mina/MinaState.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,35 @@
import { DurableObject } from "cloudflare:workers";

/**
* @implements {cloudflare.DurableObject}
*/
class MinaState extends DurableObject {
/**
* @param {!cloudflare.DurableObjectState} state
* @param {!cloudflare.Environment} env
*/
constructor(state, env) {
super(state, env);
/** @const {!cloudflare.DurableobjectStorage} */
/** @const {!cloudflare.DurableObjectStorage} */
this.storage = state.storage;
/** @type {number} */
this.height = 0;

state.blockConcurrencyWhile(() => state.storage.get("height")
.then((/** nummber */ height) => this.height = height));
.then((/** number */ height) => this.height = height || 0));
}

/**
* @return {number}
*/
getHeight() {
return this.height;
}

/**
* @param {number} height
* @return {!Promise<void>}
*/
setHeight(height) {
this.height = height;
return this.storage.put("height", height);
Expand Down
12 changes: 3 additions & 9 deletions mina/mina.d.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
/** @externs */

/**
* @constructor
* @implements {cloudflare.DurableObject}
*
* @param {!cloudflare.DurableObjectState} state
* @param {!cloudflare.Environment} env
*/
const DurableObject = function (state, env) { }

/**
* @interface
* @extends {cloudflare.Environment}
Expand All @@ -17,3 +8,6 @@ const MinaEnv = function () { }

/** @const {!cloudflare.DurableObjectBinding} */
MinaEnv.prototype.MerkleTree;

/** @const {!cloudflare.DurableObjectBinding} */
MinaEnv.prototype.MinaState;
73 changes: 57 additions & 16 deletions mina/mina.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import hex from "@kimlikdao/lib/util/hex";
import { MerkleTree } from "./MerkleTree";
import { MinaState } from "./MinaState";

Expand Down Expand Up @@ -47,58 +46,100 @@ const MinaWorker = {
const merkleTree = /** @type {!MerkleTree} */ (
env.MerkleTree.get(env.MerkleTree.idFromName(address)));

return merkleTree.getWitness(index).then((witness) => {
console.log(witness);
witness.forEach((w) => w.sibling = w.sibling.toString(16));
return new Response(JSON.stringify(witness), {
return merkleTree.getWitness(index).then((witness) =>
new Response(JSON.stringify(witness.map((w) => /** @type {mina.Witness} */({
sibling: w.sibling.toString(16),
isLeft: w.isLeft
}))), {
headers: {
'content-type': 'application/json',
'access-control-allow-origin': '*'
}
})
});
);
}
return Promise.reject();
},

/**
* TODO(KimlikDAO-bot): Implement a robust Mina synchronizer.
*
* A very simple and error prone Mina sychronization method.
* Will not survive forks.
*
* @param {!MinaEnv} env
*/
async scheduled(event, env) {
/** @const {!MerkleTree} */
const merkleTree = env.MerkleTree.get(env.MerkleTree.idFromName(LEARN2EARN));
const merkleTree = /** @type {!MerkleTree} */(env.MerkleTree.get(env.MerkleTree.idFromName(LEARN2EARN)));
/** @const {!MinaState} */
const minaState = env.MinaState.get(env.MinaState.idFromName(""));
/** @const */
const lastHeight = minaState.getHeight();
const minaState = /** @type {!MinaState} */(env.MinaState.get(env.MinaState.idFromName("")));
/** @const {number} */
const lastHeight = await minaState.getHeight();
console.log("Last height", lastHeight);

/**
* @typedef {{
* height: number
* }}
*/
const BlockInfo = {};

/**
* @typedef {{
* status: string
* }}
*/
const TransactionInfo = {};

let events = await fetch(MINA_NODE_URL, {
/**
* @typedef {{
* transactionInfo: TransactionInfo,
* data: !Array<string>
* }}
*/
const EventData = {};

/**
* @typedef {{
* blockInfo: BlockInfo,
* eventData: !Array<EventData>
* }}
*/
const EventInfo = {};

/** @type {!Array<EventInfo>} */
let events = /** @type {!Array<EventInfo>} */(await fetch(MINA_NODE_URL, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ query: EventsQuery }),
})
.then((res) => res.json())
.then((data) => data["data"]["events"].filter((e) =>
.then((data) => /** !Array<EventInfo> */(data["data"]["events"]).filter((/** EventInfo */ e) =>
e.eventData[0].transactionInfo.status == "applied" &&
e.blockInfo.height > lastHeight
));
)));
events.sort((x, y) => x.blockInfo.height - y.blockInfo.height);

for (const e of events) {
const [type, val] = e.eventData[0].data;
switch (type) {
case "1":
await merkleTree.setHeight(+val);
console.log(`height set ${+val}`);
break;
case "0": await merkleTree.setLeaf(
BigInt(val).toString(16) & 0xffffffffn);
case "0":
await merkleTree.setLeaf(BigInt(val).toString(16), 1n);
console.log(`leaf set ${val}`);
break;
}
}

return minaState.setHeight(events[events.length - 1].blockInfo.height);
if (events.length) {
const height = +(events.pop().blockInfo.height);
console.log(`mina state height set ${height}`);
await minaState.setHeight(height);
}
},
};

Expand Down
6 changes: 1 addition & 5 deletions mina/prod.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,7 @@ class_name = "MinaState"

[[migrations]]
tag = "v1"
new_classes = ["MerkleTree"]

[[migrations]]
tag = "v2"
new_classes = ["MinaState"]
new_classes = ["MerkleTree", "MinaState"]

[triggers]
crons = ["* * * * *"]

0 comments on commit 415bf3e

Please sign in to comment.