@proto-kit/protocol 0.1.1-develop.340 → 0.1.1-develop.455

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/dist/blockmodules/AccountStateModule.d.ts +1 -1
  2. package/dist/blockmodules/AccountStateModule.d.ts.map +1 -1
  3. package/dist/blockmodules/BlockHeightHook.d.ts +7 -0
  4. package/dist/blockmodules/BlockHeightHook.d.ts.map +1 -0
  5. package/dist/blockmodules/BlockHeightHook.js +16 -0
  6. package/dist/blockmodules/NoopBlockHook.d.ts +7 -0
  7. package/dist/blockmodules/NoopBlockHook.d.ts.map +1 -0
  8. package/dist/blockmodules/NoopBlockHook.js +9 -0
  9. package/dist/blockmodules/NoopTransactionHook.d.ts +1 -1
  10. package/dist/blockmodules/NoopTransactionHook.d.ts.map +1 -1
  11. package/dist/blockmodules/NoopTransactionHook.js +1 -2
  12. package/dist/hooks/AccountStateHook.d.ts +38 -0
  13. package/dist/hooks/AccountStateHook.d.ts.map +1 -0
  14. package/dist/hooks/AccountStateHook.js +36 -0
  15. package/dist/hooks/BlockHeightHook.d.ts +7 -0
  16. package/dist/hooks/BlockHeightHook.d.ts.map +1 -0
  17. package/dist/hooks/BlockHeightHook.js +14 -0
  18. package/dist/hooks/NoopBlockHook.d.ts +7 -0
  19. package/dist/hooks/NoopBlockHook.d.ts.map +1 -0
  20. package/dist/hooks/NoopBlockHook.js +9 -0
  21. package/dist/hooks/NoopTransactionHook.d.ts +6 -0
  22. package/dist/hooks/NoopTransactionHook.d.ts.map +1 -0
  23. package/dist/hooks/NoopTransactionHook.js +4 -0
  24. package/dist/hooks/TransactionFeeHook.d.ts +16 -0
  25. package/dist/hooks/TransactionFeeHook.d.ts.map +1 -0
  26. package/dist/hooks/TransactionFeeHook.js +39 -0
  27. package/dist/index.d.ts +4 -4
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +4 -4
  30. package/dist/model/Option.d.ts +29 -22
  31. package/dist/model/Option.d.ts.map +1 -1
  32. package/dist/model/Option.js +51 -45
  33. package/dist/model/StateTransition.d.ts +4 -2
  34. package/dist/model/StateTransition.d.ts.map +1 -1
  35. package/dist/model/StateTransition.js +2 -2
  36. package/dist/model/network/NetworkState.d.ts +1 -40
  37. package/dist/model/network/NetworkState.d.ts.map +1 -1
  38. package/dist/model/network/NetworkState.js +9 -10
  39. package/dist/protocol/Protocol.d.ts +4 -18
  40. package/dist/protocol/Protocol.d.ts.map +1 -1
  41. package/dist/protocol/Protocol.js +20 -9
  42. package/dist/protocol/ProtocolModule.d.ts +2 -2
  43. package/dist/protocol/ProtocolModule.d.ts.map +1 -1
  44. package/dist/protocol/ProtocolModule.js +1 -1
  45. package/dist/protocol/ProvableBlockHook.d.ts +16 -0
  46. package/dist/protocol/ProvableBlockHook.d.ts.map +1 -0
  47. package/dist/protocol/ProvableBlockHook.js +4 -0
  48. package/dist/protocol/ProvableTransactionHook.d.ts +2 -1
  49. package/dist/protocol/ProvableTransactionHook.d.ts.map +1 -1
  50. package/dist/protocol/TransitioningProtocolModule.d.ts +4 -0
  51. package/dist/protocol/TransitioningProtocolModule.d.ts.map +1 -1
  52. package/dist/protocol/TransitioningProtocolModule.js +4 -0
  53. package/dist/prover/block/BlockProvable.d.ts +21 -6
  54. package/dist/prover/block/BlockProvable.d.ts.map +1 -1
  55. package/dist/prover/block/BlockProvable.js +3 -1
  56. package/dist/prover/block/BlockProver.d.ts +9 -4
  57. package/dist/prover/block/BlockProver.d.ts.map +1 -1
  58. package/dist/prover/block/BlockProver.js +66 -16
  59. package/dist/prover/block/BlockTransactionPosition.d.ts +36 -0
  60. package/dist/prover/block/BlockTransactionPosition.d.ts.map +1 -0
  61. package/dist/prover/block/BlockTransactionPosition.js +25 -0
  62. package/dist/prover/statetransition/StateTransitionProver.d.ts +1 -1
  63. package/dist/prover/statetransition/StateTransitionProver.d.ts.map +1 -1
  64. package/dist/prover/statetransition/StateTransitionProver.js +4 -5
  65. package/dist/prover/statetransition/StateTransitionWitnessProvider.d.ts +3 -3
  66. package/dist/prover/statetransition/StateTransitionWitnessProvider.d.ts.map +1 -1
  67. package/dist/prover/statetransition/StateTransitionWitnessProvider.js +2 -2
  68. package/dist/state/State.d.ts +8 -1
  69. package/dist/state/State.d.ts.map +1 -1
  70. package/dist/state/State.js +11 -4
  71. package/dist/state/StateServiceProvider.d.ts +0 -2
  72. package/dist/state/StateServiceProvider.d.ts.map +1 -1
  73. package/dist/state/StateServiceProvider.js +5 -17
  74. package/package.json +3 -2
  75. package/src/blockmodules/AccountStateModule.ts +2 -2
  76. package/src/blockmodules/BlockHeightHook.ts +22 -0
  77. package/src/blockmodules/NoopBlockHook.ts +16 -0
  78. package/src/blockmodules/NoopTransactionHook.ts +3 -4
  79. package/src/index.ts +4 -4
  80. package/src/model/Option.ts +71 -56
  81. package/src/model/StateTransition.ts +2 -2
  82. package/src/model/network/NetworkState.ts +9 -9
  83. package/src/protocol/Protocol.ts +33 -32
  84. package/src/protocol/ProtocolModule.ts +3 -3
  85. package/src/protocol/ProvableBlockHook.ts +22 -0
  86. package/src/protocol/ProvableTransactionHook.ts +4 -1
  87. package/src/protocol/TransitioningProtocolModule.ts +4 -0
  88. package/src/prover/block/BlockProvable.ts +4 -2
  89. package/src/prover/block/BlockProver.ts +134 -21
  90. package/src/prover/block/BlockTransactionPosition.ts +34 -0
  91. package/src/prover/statetransition/StateTransitionProver.ts +6 -13
  92. package/src/prover/statetransition/StateTransitionWitnessProvider.ts +4 -5
  93. package/src/state/State.ts +11 -4
  94. package/src/state/StateServiceProvider.ts +2 -10
  95. package/test/Option.test.ts +64 -0
  96. package/test/StateTransition.test.ts +1 -1
  97. package/dist/utils/merkletree/InMemoryMerkleTreeStorage.d.ts +0 -11
  98. package/dist/utils/merkletree/InMemoryMerkleTreeStorage.d.ts.map +0 -1
  99. package/dist/utils/merkletree/InMemoryMerkleTreeStorage.js +0 -12
  100. package/dist/utils/merkletree/MerkleTreeStore.d.ts +0 -11
  101. package/dist/utils/merkletree/MerkleTreeStore.d.ts.map +0 -1
  102. package/dist/utils/merkletree/MerkleTreeStore.js +0 -1
  103. package/dist/utils/merkletree/RollupMerkleTree.d.ts +0 -132
  104. package/dist/utils/merkletree/RollupMerkleTree.d.ts.map +0 -1
  105. package/dist/utils/merkletree/RollupMerkleTree.js +0 -251
  106. package/src/utils/merkletree/InMemoryMerkleTreeStorage.ts +0 -17
  107. package/src/utils/merkletree/MerkleTreeStore.ts +0 -15
  108. package/src/utils/merkletree/RollupMerkleTree.ts +0 -275
  109. package/src/utils/merkletree/VirtualMerkleTreeStore.ts +0 -21
  110. package/test/utils/MerkleTree.test.ts +0 -82
@@ -6,13 +6,10 @@ import {
6
6
  log,
7
7
  PlainZkProgram,
8
8
  provableMethod,
9
+ RollupMerkleTreeWitness,
9
10
  ZkProgrammable,
10
11
  } from "@proto-kit/common";
11
12
 
12
- import {
13
- MerkleTreeUtils,
14
- RollupMerkleWitness,
15
- } from "../../utils/merkletree/RollupMerkleTree.js";
16
13
  import {
17
14
  DefaultProvableHashList,
18
15
  ProvableHashList,
@@ -25,7 +22,7 @@ import {
25
22
  import { constants } from "../../Constants";
26
23
  import { ProtocolModule } from "../../protocol/ProtocolModule";
27
24
 
28
- import { StateTransitionWitnessProvider } from "./StateTransitionWitnessProvider.js";
25
+ import { StateTransitionWitnessProvider } from "./StateTransitionWitnessProvider";
29
26
  import {
30
27
  StateTransitionProvable,
31
28
  StateTransitionProverPublicInput,
@@ -192,12 +189,11 @@ export class StateTransitionProverProgrammable extends ZkProgrammable<
192
189
  type: ProvableStateTransitionType,
193
190
  index = 0
194
191
  ) {
195
- const treeWitness = Provable.witness(RollupMerkleWitness, () =>
192
+ const witness = Provable.witness(RollupMerkleTreeWitness, () =>
196
193
  this.witnessProvider.getWitness(transition.path)
197
194
  );
198
195
 
199
- const membershipValid = MerkleTreeUtils.checkMembership(
200
- treeWitness,
196
+ const membershipValid = witness.checkMembership(
201
197
  state.stateRoot,
202
198
  transition.path,
203
199
  transition.from.value
@@ -212,10 +208,7 @@ export class StateTransitionProverProgrammable extends ZkProgrammable<
212
208
  )
213
209
  );
214
210
 
215
- const newRoot = MerkleTreeUtils.computeRoot(
216
- treeWitness,
217
- transition.to.value
218
- );
211
+ const newRoot = witness.calculateRoot(transition.to.value);
219
212
 
220
213
  state.stateRoot = Provable.if(
221
214
  transition.to.isSome,
@@ -345,7 +338,7 @@ export class StateTransitionProverProgrammable extends ZkProgrammable<
345
338
 
346
339
  @injectable()
347
340
  export class StateTransitionProver
348
- extends ProtocolModule<object>
341
+ extends ProtocolModule
349
342
  implements StateTransitionProvable
350
343
  {
351
344
  public readonly zkProgrammable: StateTransitionProverProgrammable;
@@ -1,7 +1,6 @@
1
1
  import type { Field } from "o1js";
2
2
  import { injectable } from "tsyringe";
3
-
4
- import { RollupMerkleWitness } from "../../utils/merkletree/RollupMerkleTree.js";
3
+ import { RollupMerkleTreeWitness } from "@proto-kit/common";
5
4
 
6
5
  /**
7
6
  * Interface for providing merkle witnesses to the state-transition prover
@@ -11,14 +10,14 @@ export interface StateTransitionWitnessProvider {
11
10
  * Provides the merkle witness corresponding to the given key
12
11
  * @param key Merkle-tree key
13
12
  */
14
- getWitness: (key: Field) => RollupMerkleWitness;
13
+ getWitness: (key: Field) => RollupMerkleTreeWitness;
15
14
  }
16
15
 
17
16
  @injectable()
18
17
  export class NoOpStateTransitionWitnessProvider
19
18
  implements StateTransitionWitnessProvider
20
19
  {
21
- public getWitness(): RollupMerkleWitness {
22
- return new RollupMerkleWitness({ path: [], isLeft: [] });
20
+ public getWitness(): RollupMerkleTreeWitness {
21
+ return new RollupMerkleTreeWitness({ path: [], isLeft: [] });
23
22
  }
24
23
  }
@@ -54,6 +54,13 @@ export class State<Value> extends Mixin(WithPath, WithStateServiceProvider) {
54
54
  super();
55
55
  }
56
56
 
57
+ /**
58
+ * Returns the state that is currently the current state tree
59
+ * value: The value-fields, or if not state was found, dummy values
60
+ * isSome: Whether the values where found in the state or not
61
+ * (Basically, whether the value-fields are dummy values or actual values
62
+ * @private
63
+ */
57
64
  private getState(): { value: Value; isSome: Bool } {
58
65
  this.hasStateServiceOrFail();
59
66
  this.hasPathOrFail();
@@ -99,7 +106,7 @@ export class State<Value> extends Mixin(WithPath, WithStateServiceProvider) {
99
106
  *
100
107
  * @returns Optional value of the current state
101
108
  */
102
- private witnessState() {
109
+ private witnessFromState() {
103
110
  // get the value from storage, or return a dummy value instead
104
111
  const value = Provable.witness(this.valueType, () => this.getState().value);
105
112
 
@@ -116,7 +123,7 @@ export class State<Value> extends Mixin(WithPath, WithStateServiceProvider) {
116
123
  * @returns Option representation of the current state.
117
124
  */
118
125
  public get(): Option<Value> {
119
- const option = this.witnessState();
126
+ const option = this.witnessFromState();
120
127
 
121
128
  this.hasPathOrFail();
122
129
 
@@ -142,8 +149,8 @@ export class State<Value> extends Mixin(WithPath, WithStateServiceProvider) {
142
149
  */
143
150
  public set(value: Value) {
144
151
  // link the transition to the current state
145
- const fromOption = this.witnessState();
146
- const toOption = Option.from(Bool(true), value, this.valueType);
152
+ const fromOption = this.witnessFromState();
153
+ const toOption = Option.fromValue(value, this.valueType);
147
154
 
148
155
  this.hasPathOrFail();
149
156
 
@@ -14,14 +14,6 @@ const errors = {
14
14
  export class StateServiceProvider {
15
15
  private readonly stateServiceStack: StateService[] = [];
16
16
 
17
- public constructor(
18
- @inject("StateService") private readonly baseStateService?: StateService
19
- ) {
20
- if (baseStateService !== undefined) {
21
- this.stateServiceStack.push(baseStateService);
22
- }
23
- }
24
-
25
17
  public get stateService(): StateService {
26
18
  if (this.stateServiceStack.length === 0) {
27
19
  throw errors.stateServiceNotSet();
@@ -37,8 +29,8 @@ export class StateServiceProvider {
37
29
  }
38
30
 
39
31
  public popCurrentStateService() {
40
- if (this.stateServiceStack.length === 1) {
41
- log.trace("Trying to pop last available (root) stateservice");
32
+ if (this.stateServiceStack.length === 0) {
33
+ log.trace("Trying to pop from empty state-service stack");
42
34
  return;
43
35
  }
44
36
  this.stateServiceStack.pop();
@@ -0,0 +1,64 @@
1
+ import { Bool, Field, Poseidon } from "o1js";
2
+
3
+ import {
4
+ Option,
5
+ ProvableOption,
6
+ ProvableStateTransition,
7
+ StateTransition,
8
+ } from "../src";
9
+
10
+ describe("option", () => {
11
+ it.each([
12
+ [
13
+ Option.from(Bool(true), Field(5), Bool(false), Field),
14
+ { isSome: true, value: Poseidon.hash([Field(5)]) },
15
+ ],
16
+ [
17
+ Option.from(Bool(true), Field(0), Bool(false), Field),
18
+ { isSome: true, value: Poseidon.hash([Field(0)]) },
19
+ ],
20
+ [
21
+ Option.from(Bool(true), Field(0), Bool(true), Field),
22
+ { isSome: true, value: Field(0) },
23
+ ],
24
+ [
25
+ Option.from(Bool(false), Field(1), Bool(false), Field),
26
+ { isSome: false, value: Poseidon.hash([Field(1)]) },
27
+ ],
28
+ ])("should encode to correct provable", (option, provableTemplate) => {
29
+ expect.assertions(4);
30
+
31
+ const provableInput = new ProvableOption({
32
+ isSome: Bool(provableTemplate.isSome),
33
+ value: provableTemplate.value,
34
+ });
35
+
36
+ const provable = option.toProvable();
37
+ const fields = ProvableOption.toFields(provable);
38
+
39
+ expect(provable.value.toBigInt()).toStrictEqual(
40
+ provableInput.value.toBigInt()
41
+ );
42
+ expect(provable.isSome.toBoolean()).toStrictEqual(
43
+ provableInput.isSome.toBoolean()
44
+ );
45
+
46
+ expect(fields[0]).toStrictEqual(provableInput.isSome.toFields()[0]);
47
+ expect(fields[1]).toStrictEqual(provableInput.value);
48
+ });
49
+ });
50
+
51
+ describe.skip("StateTransition", () => {
52
+ it.each([
53
+ StateTransition.fromTo(
54
+ Field(
55
+ "12400094993176908175853015388851707312254268028646194084157588096832563763032"
56
+ ),
57
+ Option.fromValue(Field(0), Field),
58
+ Option.fromValue(Field(100), Field)
59
+ ),
60
+ ])("should encode StateTransition correctly", (st) => {
61
+ const provable = st.toProvable();
62
+ console.log(ProvableStateTransition.toJSON(provable));
63
+ });
64
+ });
@@ -13,7 +13,7 @@ import {
13
13
  import {
14
14
  RollupMerkleTree,
15
15
  type RollupMerkleWitness,
16
- } from "../src/utils/merkletree/RollupMerkleTree.js";
16
+ } from "../../common/src/trees/RollupMerkleTree.js";
17
17
  import { StateTransitionProver } from "../src/prover/statetransition/StateTransitionProver.js";
18
18
  import type { StateTransitionWitnessProvider } from "../src/prover/statetransition/StateTransitionWitnessProvider.js";
19
19
 
@@ -1,11 +0,0 @@
1
- import { MerkleTreeStore } from "./MerkleTreeStore";
2
- export declare class InMemoryMerkleTreeStorage implements MerkleTreeStore {
3
- protected readonly nodes: {
4
- [key: number]: {
5
- [key: string]: bigint;
6
- };
7
- };
8
- getNode(key: bigint, level: number): bigint | undefined;
9
- setNode(key: bigint, level: number, value: bigint): void;
10
- }
11
- //# sourceMappingURL=InMemoryMerkleTreeStorage.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"InMemoryMerkleTreeStorage.d.ts","sourceRoot":"","sources":["../../../src/utils/merkletree/InMemoryMerkleTreeStorage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEpD,qBAAa,yBAA0B,YAAW,eAAe;IAC/D,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE;QACxB,CAAC,GAAG,EAAE,MAAM,GAAG;YACb,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;SACvB,CAAC;KACH,CAAM;IAEA,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAIvD,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;CAGhE"}
@@ -1,12 +0,0 @@
1
- export class InMemoryMerkleTreeStorage {
2
- constructor() {
3
- this.nodes = {};
4
- }
5
- getNode(key, level) {
6
- return this.nodes[level]?.[key.toString()];
7
- }
8
- setNode(key, level, value) {
9
- var _a;
10
- ((_a = this.nodes)[level] ?? (_a[level] = {}))[key.toString()] = value;
11
- }
12
- }
@@ -1,11 +0,0 @@
1
- export interface AsyncMerkleTreeStore {
2
- openTransaction: () => void;
3
- commit: () => void;
4
- setNodeAsync: (key: bigint, level: number, value: bigint) => Promise<void>;
5
- getNodeAsync: (key: bigint, level: number) => Promise<bigint | undefined>;
6
- }
7
- export interface MerkleTreeStore {
8
- setNode: (key: bigint, level: number, value: bigint) => void;
9
- getNode: (key: bigint, level: number) => bigint | undefined;
10
- }
11
- //# sourceMappingURL=MerkleTreeStore.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"MerkleTreeStore.d.ts","sourceRoot":"","sources":["../../../src/utils/merkletree/MerkleTreeStore.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,oBAAoB;IACnC,eAAe,EAAE,MAAM,IAAI,CAAC;IAE5B,MAAM,EAAE,MAAM,IAAI,CAAC;IAEnB,YAAY,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAE3E,YAAY,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;CAC3E;AAED,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAE7D,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;CAC7D"}
@@ -1 +0,0 @@
1
- export {};
@@ -1,132 +0,0 @@
1
- import { Bool, Field } from "o1js";
2
- import { MerkleTreeStore } from "./MerkleTreeStore";
3
- export { RollupMerkleTree, RollupMerkleWitness };
4
- export { maybeSwap };
5
- declare const RollupMerkleWitness_base: (new (value: {
6
- path: import("o1js/dist/node/lib/field").Field[];
7
- isLeft: import("o1js/dist/node/lib/bool").Bool[];
8
- }) => {
9
- path: import("o1js/dist/node/lib/field").Field[];
10
- isLeft: import("o1js/dist/node/lib/bool").Bool[];
11
- }) & {
12
- _isStruct: true;
13
- } & import("o1js/dist/node/snarky").ProvablePure<{
14
- path: import("o1js/dist/node/lib/field").Field[];
15
- isLeft: import("o1js/dist/node/lib/bool").Bool[];
16
- }> & {
17
- toInput: (x: {
18
- path: import("o1js/dist/node/lib/field").Field[];
19
- isLeft: import("o1js/dist/node/lib/bool").Bool[];
20
- }) => {
21
- fields?: import("o1js/dist/node/lib/field").Field[] | undefined;
22
- packed?: [import("o1js/dist/node/lib/field").Field, number][] | undefined;
23
- };
24
- toJSON: (x: {
25
- path: import("o1js/dist/node/lib/field").Field[];
26
- isLeft: import("o1js/dist/node/lib/bool").Bool[];
27
- }) => {
28
- path: string[];
29
- isLeft: boolean[];
30
- };
31
- fromJSON: (x: {
32
- path: string[];
33
- isLeft: boolean[];
34
- }) => {
35
- path: import("o1js/dist/node/lib/field").Field[];
36
- isLeft: import("o1js/dist/node/lib/bool").Bool[];
37
- };
38
- };
39
- /**
40
- * The {@link BaseMerkleWitness} class defines a circuit-compatible base class
41
- * for [Merkle Witness'](https://computersciencewiki.org/index.php/Merkle_proof).
42
- */
43
- declare class RollupMerkleWitness extends RollupMerkleWitness_base {
44
- static height: number;
45
- height(): number;
46
- /**
47
- * Calculates a root depending on the leaf value.
48
- * @param leaf Value of the leaf node that belongs to this Witness.
49
- * @returns The calculated root.
50
- */
51
- calculateRoot(hash: Field): Field;
52
- /**
53
- * Calculates the index of the leaf node that belongs to this Witness.
54
- * @returns Index of the leaf.
55
- */
56
- calculateIndex(): Field;
57
- toShortenedEntries(): string[];
58
- }
59
- /**
60
- * A [Merkle Tree](https://en.wikipedia.org/wiki/Merkle_tree) is a binary tree in
61
- * which every leaf is the cryptography hash of a piece of data,
62
- * and every node is the hash of the concatenation of its two child nodes.
63
- *
64
- * A Merkle Tree allows developers to easily and securely verify
65
- * the integrity of large amounts of data.
66
- *
67
- * Take a look at our [documentation](https://docs.minaprotocol.com/en/zkapps)
68
- * on how to use Merkle Trees in combination with zkApps and
69
- * zero knowledge programming!
70
- *
71
- * Levels are indexed from leaves (level 0) to root (level N - 1).
72
- */
73
- declare class RollupMerkleTree {
74
- static height: number;
75
- static get leafCount(): bigint;
76
- private readonly zeroes;
77
- readonly store: MerkleTreeStore;
78
- constructor(store: MerkleTreeStore);
79
- /**
80
- * Returns a node which lives at a given index and level.
81
- * @param level Level of the node.
82
- * @param index Index of the node.
83
- * @returns The data of the node.
84
- */
85
- getNode(level: number, index: bigint): Field;
86
- /**
87
- * Returns the root of the [Merkle Tree](https://en.wikipedia.org/wiki/Merkle_tree).
88
- * @returns The root of the Merkle Tree.
89
- */
90
- getRoot(): Field;
91
- private setNode;
92
- /**
93
- * TODO: if this is passed an index bigger than the max, it will set a couple
94
- * of out-of-bounds nodes but not affect the real Merkle root. OK?
95
- */
96
- /**
97
- * Sets the value of a leaf node at a given index to a given value.
98
- * @param index Position of the leaf node.
99
- * @param leaf New value.
100
- */
101
- setLeaf(index: bigint, leaf: Field): void;
102
- /**
103
- * Returns the witness (also known as
104
- * [Merkle Proof or Merkle Witness](https://computersciencewiki.org/index.php/Merkle_proof))
105
- * for the leaf at the given index.
106
- * @param index Position of the leaf node.
107
- * @returns The witness that belongs to the leaf.
108
- */
109
- getWitness(index: bigint): RollupMerkleWitness;
110
- /**
111
- * Fills all leaves of the tree.
112
- * @param leaves Values to fill the leaves with.
113
- */
114
- fill(leaves: Field[]): void;
115
- /**
116
- * Returns the amount of leaf nodes.
117
- * @returns Amount of leaf nodes.
118
- */
119
- get leafCount(): bigint;
120
- }
121
- export declare namespace MerkleTreeUtils {
122
- function normalizeKey(key: Field): Field;
123
- function checkMembership(witness: RollupMerkleWitness, root: Field, key: Field, value: Field): Bool;
124
- function checkMembershipGetRoots(witness: RollupMerkleWitness, root: Field, key: Field, value: Field): [Bool, Field, Field];
125
- function computeRoot(witness: RollupMerkleWitness, value: Field): Field;
126
- }
127
- /**
128
- * More efficient version of `maybeSwapBad` which
129
- * reuses an intermediate variable
130
- */
131
- declare function maybeSwap(b: Bool, x: Field, y: Field): [Field, Field];
132
- //# sourceMappingURL=RollupMerkleTree.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"RollupMerkleTree.d.ts","sourceRoot":"","sources":["../../../src/utils/merkletree/RollupMerkleTree.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,IAAI,EAAE,KAAK,EAA8B,MAAM,MAAM,CAAC;AAK/D,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAIpD,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,CAAC;AAIjD,OAAO,EAAE,SAAS,EAAE,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErB;;;GAGG;AACH,cAAM,mBAAoB,SAAQ,wBAGhC;IACA,OAAc,MAAM,SAAO;IAEpB,MAAM,IAAI,MAAM;IAIvB;;;;OAIG;IACI,aAAa,CAAC,IAAI,EAAE,KAAK,GAAG,KAAK;IAaxC;;;OAGG;IACI,cAAc,IAAI,KAAK;IAkBvB,kBAAkB;CAO1B;AAED;;;;;;;;;;;;;GAaG;AACH,cAAM,gBAAgB;IACpB,OAAc,MAAM,SAAO;IAE3B,WAAkB,SAAS,IAAI,MAAM,CAEpC;IAED,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAW;IAElC,SAAgB,KAAK,EAAE,eAAe,CAAC;gBAEpB,KAAK,EAAE,eAAe;IAYzC;;;;;OAKG;IAEI,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,KAAK;IAInD;;;OAGG;IAEI,OAAO,IAAI,KAAK;IAMvB,OAAO,CAAC,OAAO;IAIf;;;OAGG;IAEH;;;;OAIG;IAEI,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK;IAgBzC;;;;;;OAMG;IACI,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,mBAAmB;IAqBrD;;;OAGG;IAEI,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE;IAM3B;;;OAGG;IACH,IAAW,SAAS,IAAI,MAAM,CAE7B;CACF;AAGD,yBAAiB,eAAe,CAAC;IAC/B,SAAgB,YAAY,CAAC,GAAG,EAAE,KAAK,GAAG,KAAK,CAS9C;IAED,SAAgB,eAAe,CAC7B,OAAO,EAAE,mBAAmB,EAC5B,IAAI,EAAE,KAAK,EACX,GAAG,EAAE,KAAK,EACV,KAAK,EAAE,KAAK,GACX,IAAI,CAKN;IAED,SAAgB,uBAAuB,CACrC,OAAO,EAAE,mBAAmB,EAC5B,IAAI,EAAE,KAAK,EACX,GAAG,EAAE,KAAK,EACV,KAAK,EAAE,KAAK,GACX,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,CAKtB;IAED,SAAgB,WAAW,CACzB,OAAO,EAAE,mBAAmB,EAC5B,KAAK,EAAE,KAAK,GACX,KAAK,CAEP;CACF;AAED;;;GAGG;AACH,iBAAS,SAAS,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAK9D"}
@@ -1,251 +0,0 @@
1
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
6
- };
7
- var __metadata = (this && this.__metadata) || function (k, v) {
8
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
- };
10
- /* eslint-disable id-length */
11
- /* eslint-disable line-comment-position */
12
- /* eslint-disable no-inline-comments */
13
- /* eslint-disable @typescript-eslint/no-magic-numbers */
14
- import { Bool, Field, Poseidon, Provable, Struct } from "o1js";
15
- import { range } from "@proto-kit/common";
16
- import { notInCircuit } from "../utils";
17
- // external API
18
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
19
- export { RollupMerkleTree, RollupMerkleWitness };
20
- // internal API
21
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
22
- export { maybeSwap };
23
- /**
24
- * The {@link BaseMerkleWitness} class defines a circuit-compatible base class
25
- * for [Merkle Witness'](https://computersciencewiki.org/index.php/Merkle_proof).
26
- */
27
- class RollupMerkleWitness extends Struct({
28
- path: Provable.Array(Field, 256 - 1),
29
- isLeft: Provable.Array(Bool, 256 - 1),
30
- }) {
31
- height() {
32
- return RollupMerkleWitness.height;
33
- }
34
- /**
35
- * Calculates a root depending on the leaf value.
36
- * @param leaf Value of the leaf node that belongs to this Witness.
37
- * @returns The calculated root.
38
- */
39
- calculateRoot(hash) {
40
- const n = this.height();
41
- for (let index = 1; index < n; ++index) {
42
- const isLeft = this.isLeft[index - 1];
43
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
44
- const [left, right] = maybeSwap(isLeft, hash, this.path[index - 1]);
45
- hash = Poseidon.hash([left, right]);
46
- }
47
- return hash;
48
- }
49
- /**
50
- * Calculates the index of the leaf node that belongs to this Witness.
51
- * @returns Index of the leaf.
52
- */
53
- calculateIndex() {
54
- let powerOfTwo = Field(1);
55
- let index = Field(0);
56
- const n = this.height();
57
- // eslint-disable-next-line no-underscore-dangle
58
- for (let index_ = 1; index_ < n; ++index_) {
59
- index = Provable.if(this.isLeft[index_ - 1], index, index.add(powerOfTwo));
60
- powerOfTwo = powerOfTwo.mul(2);
61
- }
62
- return index;
63
- }
64
- toShortenedEntries() {
65
- return range(0, 5)
66
- .concat(range(251, 255))
67
- .map((index) => [this.path[index].toString(), this.isLeft[index].toString()].toString());
68
- }
69
- }
70
- RollupMerkleWitness.height = 256;
71
- /**
72
- * A [Merkle Tree](https://en.wikipedia.org/wiki/Merkle_tree) is a binary tree in
73
- * which every leaf is the cryptography hash of a piece of data,
74
- * and every node is the hash of the concatenation of its two child nodes.
75
- *
76
- * A Merkle Tree allows developers to easily and securely verify
77
- * the integrity of large amounts of data.
78
- *
79
- * Take a look at our [documentation](https://docs.minaprotocol.com/en/zkapps)
80
- * on how to use Merkle Trees in combination with zkApps and
81
- * zero knowledge programming!
82
- *
83
- * Levels are indexed from leaves (level 0) to root (level N - 1).
84
- */
85
- class RollupMerkleTree {
86
- static get leafCount() {
87
- return 2n ** BigInt(RollupMerkleTree.height - 1);
88
- }
89
- constructor(store) {
90
- this.store = store;
91
- // eslint-disable-next-line @shopify/prefer-class-properties
92
- this.zeroes = [0n];
93
- for (let index = 1; index < RollupMerkleTree.height; index += 1) {
94
- const previousLevel = Field(this.zeroes[index - 1]);
95
- this.zeroes.push(Poseidon.hash([previousLevel, previousLevel]).toBigInt());
96
- }
97
- }
98
- /**
99
- * Returns a node which lives at a given index and level.
100
- * @param level Level of the node.
101
- * @param index Index of the node.
102
- * @returns The data of the node.
103
- */
104
- getNode(level, index) {
105
- return Field(this.store.getNode(index, level) ?? this.zeroes[level]);
106
- }
107
- /**
108
- * Returns the root of the [Merkle Tree](https://en.wikipedia.org/wiki/Merkle_tree).
109
- * @returns The root of the Merkle Tree.
110
- */
111
- getRoot() {
112
- return this.getNode(RollupMerkleTree.height - 1, 0n);
113
- }
114
- // eslint-disable-next-line no-warning-comments
115
- // TODO: this allows to set a node at an index larger than the size. OK?
116
- setNode(level, index, value) {
117
- this.store.setNode(index, level, value.toBigInt());
118
- }
119
- /**
120
- * TODO: if this is passed an index bigger than the max, it will set a couple
121
- * of out-of-bounds nodes but not affect the real Merkle root. OK?
122
- */
123
- /**
124
- * Sets the value of a leaf node at a given index to a given value.
125
- * @param index Position of the leaf node.
126
- * @param leaf New value.
127
- */
128
- setLeaf(index, leaf) {
129
- if (index >= this.leafCount) {
130
- index %= this.leafCount;
131
- }
132
- this.setNode(0, index, leaf);
133
- let currentIndex = index;
134
- for (let level = 1; level < RollupMerkleTree.height; level += 1) {
135
- currentIndex /= 2n;
136
- const left = this.getNode(level - 1, currentIndex * 2n);
137
- const right = this.getNode(level - 1, currentIndex * 2n + 1n);
138
- this.setNode(level, currentIndex, Poseidon.hash([left, right]));
139
- }
140
- }
141
- /**
142
- * Returns the witness (also known as
143
- * [Merkle Proof or Merkle Witness](https://computersciencewiki.org/index.php/Merkle_proof))
144
- * for the leaf at the given index.
145
- * @param index Position of the leaf node.
146
- * @returns The witness that belongs to the leaf.
147
- */
148
- getWitness(index) {
149
- if (index >= this.leafCount) {
150
- throw new Error("Index too large for merkle height");
151
- }
152
- const path = [];
153
- const isLefts = [];
154
- for (let level = 0; level < RollupMerkleTree.height - 1; level += 1) {
155
- const isLeft = index % 2n === 0n;
156
- const sibling = this.getNode(level, isLeft ? index + 1n : index - 1n);
157
- isLefts.push(Bool(isLeft));
158
- path.push(sibling);
159
- index /= 2n;
160
- }
161
- return new RollupMerkleWitness({
162
- isLeft: isLefts,
163
- path,
164
- });
165
- }
166
- // eslint-disable-next-line no-warning-comments, max-len
167
- // TODO: should this take an optional offset? should it fail if the array is too long?
168
- /**
169
- * Fills all leaves of the tree.
170
- * @param leaves Values to fill the leaves with.
171
- */
172
- fill(leaves) {
173
- leaves.forEach((value, index) => {
174
- this.setLeaf(BigInt(index), value);
175
- });
176
- }
177
- /**
178
- * Returns the amount of leaf nodes.
179
- * @returns Amount of leaf nodes.
180
- */
181
- get leafCount() {
182
- return RollupMerkleTree.leafCount;
183
- }
184
- }
185
- RollupMerkleTree.height = 256;
186
- __decorate([
187
- notInCircuit(),
188
- __metadata("design:type", Function),
189
- __metadata("design:paramtypes", [Number, BigInt]),
190
- __metadata("design:returntype", Field)
191
- ], RollupMerkleTree.prototype, "getNode", null);
192
- __decorate([
193
- notInCircuit(),
194
- __metadata("design:type", Function),
195
- __metadata("design:paramtypes", []),
196
- __metadata("design:returntype", Field)
197
- ], RollupMerkleTree.prototype, "getRoot", null);
198
- __decorate([
199
- notInCircuit(),
200
- __metadata("design:type", Function),
201
- __metadata("design:paramtypes", [BigInt, Field]),
202
- __metadata("design:returntype", void 0)
203
- ], RollupMerkleTree.prototype, "setLeaf", null);
204
- __decorate([
205
- notInCircuit(),
206
- __metadata("design:type", Function),
207
- __metadata("design:paramtypes", [Array]),
208
- __metadata("design:returntype", void 0)
209
- ], RollupMerkleTree.prototype, "fill", null);
210
- // eslint-disable-next-line @typescript-eslint/no-namespace
211
- export var MerkleTreeUtils;
212
- (function (MerkleTreeUtils) {
213
- function normalizeKey(key) {
214
- // if(NJORD_MERKLE_TREE_HEIGHT < 256){
215
- // return fieldMod(key, Field(RollupMerkleTree.leafCount).toConstant())
216
- // eslint-disable-next-line max-len
217
- // // return modPower2(key, RollupMerkleTree.height - 1) //TODO Fix modPower2
218
- // }else{
219
- return key;
220
- // }
221
- }
222
- MerkleTreeUtils.normalizeKey = normalizeKey;
223
- function checkMembership(witness, root, key, value) {
224
- const root2 = witness.calculateRoot(value);
225
- const key2 = witness.calculateIndex();
226
- key.assertEquals(key2, "Keys of MerkleWitness does not match");
227
- return root.equals(root2);
228
- }
229
- MerkleTreeUtils.checkMembership = checkMembership;
230
- function checkMembershipGetRoots(witness, root, key, value) {
231
- const root2 = witness.calculateRoot(value);
232
- const key2 = witness.calculateIndex();
233
- key.assertEquals(key2, "Keys of MerkleWitness does not match");
234
- return [root.equals(root2), root, root2];
235
- }
236
- MerkleTreeUtils.checkMembershipGetRoots = checkMembershipGetRoots;
237
- function computeRoot(witness, value) {
238
- return witness.calculateRoot(value);
239
- }
240
- MerkleTreeUtils.computeRoot = computeRoot;
241
- })(MerkleTreeUtils || (MerkleTreeUtils = {}));
242
- /**
243
- * More efficient version of `maybeSwapBad` which
244
- * reuses an intermediate variable
245
- */
246
- function maybeSwap(b, x, y) {
247
- const m = b.toField().mul(x.sub(y)); // b*(x - y)
248
- const x1 = y.add(m); // y + b*(x - y)
249
- const y2 = x.sub(m); // x - b*(x - y) = x + b*(y - x)
250
- return [x1, y2];
251
- }