@ocap/merkle-tree 1.30.24 → 1.30.25
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.
- package/esm/abi.d.mts +16 -0
- package/esm/abi.mjs +111 -0
- package/esm/index.d.mts +47 -0
- package/esm/index.mjs +143 -0
- package/lib/abi.cjs +111 -0
- package/lib/abi.d.cts +16 -0
- package/lib/index.cjs +144 -0
- package/lib/index.d.cts +47 -0
- package/package.json +23 -7
- package/lib/abi.js +0 -221
- package/lib/index.js +0 -196
package/esm/abi.d.mts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
//#region src/abi.d.ts
|
|
2
|
+
interface SolidityValue {
|
|
3
|
+
t?: string;
|
|
4
|
+
type?: string;
|
|
5
|
+
v?: unknown;
|
|
6
|
+
value?: unknown;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Encode packed args to hex
|
|
10
|
+
*
|
|
11
|
+
* @method encodePacked
|
|
12
|
+
* @return {String} the hex encoded arguments
|
|
13
|
+
*/
|
|
14
|
+
declare const encodePacked: (...args: SolidityValue[]) => string;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { SolidityValue, encodePacked };
|
package/esm/abi.mjs
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { Hasher } from "@ocap/mcrypto";
|
|
2
|
+
import { BN, isBN, isBigNumber, isHexStrict, leftPad, rightPad, utf8ToHex } from "@ocap/util";
|
|
3
|
+
|
|
4
|
+
//#region src/abi.ts
|
|
5
|
+
const keccak256 = Hasher.Keccak.hash256;
|
|
6
|
+
const isAddress = (address) => {
|
|
7
|
+
if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) return false;
|
|
8
|
+
if (/^(0x|0X)?[0-9a-f]{40}$/.test(address) || /^(0x|0X)?[0-9A-F]{40}$/.test(address)) return true;
|
|
9
|
+
return checkAddressChecksum(address);
|
|
10
|
+
};
|
|
11
|
+
const checkAddressChecksum = (address) => {
|
|
12
|
+
const origin = address.replace(/^0x/i, "");
|
|
13
|
+
const addressHash = keccak256(origin.toLowerCase()).replace(/^0x/i, "");
|
|
14
|
+
for (let i = 0; i < 40; i++) if (Number.parseInt(addressHash[i], 16) > 7 && origin[i].toUpperCase() !== origin[i] || Number.parseInt(addressHash[i], 16) <= 7 && origin[i].toLowerCase() !== origin[i]) return false;
|
|
15
|
+
return true;
|
|
16
|
+
};
|
|
17
|
+
const _elementaryName = (name) => {
|
|
18
|
+
if (name.startsWith("int[")) return `int256${name.slice(3)}`;
|
|
19
|
+
if (name === "int") return "int256";
|
|
20
|
+
if (name.startsWith("uint[")) return `uint256${name.slice(4)}`;
|
|
21
|
+
if (name === "uint") return "uint256";
|
|
22
|
+
if (name.startsWith("fixed[")) return `fixed128x128${name.slice(5)}`;
|
|
23
|
+
if (name === "fixed") return "fixed128x128";
|
|
24
|
+
if (name.startsWith("ufixed[")) return `ufixed128x128${name.slice(6)}`;
|
|
25
|
+
if (name === "ufixed") return "ufixed128x128";
|
|
26
|
+
return name;
|
|
27
|
+
};
|
|
28
|
+
const _parseTypeN = (type) => {
|
|
29
|
+
const size = /^\D+(\d+).*$/.exec(type);
|
|
30
|
+
return size ? Number.parseInt(size[1], 10) : null;
|
|
31
|
+
};
|
|
32
|
+
const _parseTypeNArray = (type) => {
|
|
33
|
+
const arraySize = /^\D+\d*\[(\d+)\]$/.exec(type);
|
|
34
|
+
return arraySize ? Number.parseInt(arraySize[1], 10) : null;
|
|
35
|
+
};
|
|
36
|
+
const _parseNumber = (arg) => {
|
|
37
|
+
const type = typeof arg;
|
|
38
|
+
if (type === "string") {
|
|
39
|
+
if (isHexStrict(arg)) return new BN(arg.replace(/0x/i, ""), 16);
|
|
40
|
+
return new BN(arg, 10);
|
|
41
|
+
}
|
|
42
|
+
if (type === "number") return new BN(arg);
|
|
43
|
+
if (isBigNumber(arg)) return new BN(arg.toString(10));
|
|
44
|
+
if (isBN(arg)) return arg;
|
|
45
|
+
throw new Error(`${arg} is not a number`);
|
|
46
|
+
};
|
|
47
|
+
const _solidityPack = (rawType, value, arraySize) => {
|
|
48
|
+
let size;
|
|
49
|
+
let num;
|
|
50
|
+
const type = _elementaryName(rawType);
|
|
51
|
+
if (type === "bytes") {
|
|
52
|
+
const str = value;
|
|
53
|
+
if (str.replace(/^0x/i, "").length % 2 !== 0) throw new Error(`Invalid bytes characters ${str.length}`);
|
|
54
|
+
return str;
|
|
55
|
+
}
|
|
56
|
+
if (type === "string") return utf8ToHex(value);
|
|
57
|
+
if (type === "bool") return value ? "01" : "00";
|
|
58
|
+
if (type.startsWith("address")) {
|
|
59
|
+
size = arraySize ? 64 : 40;
|
|
60
|
+
if (!isAddress(value)) throw new Error(`${value} is not a valid address, or the checksum is invalid.`);
|
|
61
|
+
return leftPad(value.toLowerCase(), size, "0");
|
|
62
|
+
}
|
|
63
|
+
size = _parseTypeN(type);
|
|
64
|
+
if (type.startsWith("bytes")) {
|
|
65
|
+
if (!size) throw new Error("bytes[] not yet supported in solidity");
|
|
66
|
+
if (arraySize) size = 32;
|
|
67
|
+
if (size < 1 || size > 32 || size < value.replace(/^0x/i, "").length / 2) throw new Error(`Invalid bytes${size} for ${value}`);
|
|
68
|
+
return rightPad(value, size * 2, "0");
|
|
69
|
+
}
|
|
70
|
+
if (type.startsWith("uint")) {
|
|
71
|
+
if (!size || size % 8 || size < 8 || size > 256) throw new Error(`Invalid uint${size} size`);
|
|
72
|
+
num = _parseNumber(value);
|
|
73
|
+
if (num.bitLength() > size) throw new Error(`Supplied uint exceeds width: ${size} vs ${num.bitLength()}`);
|
|
74
|
+
if (num.lt(new BN(0))) throw new Error(`Supplied uint ${num.toString()} is negative`);
|
|
75
|
+
return size ? leftPad(num.toString("hex"), size / 8 * 2, "0") : num.toString("hex");
|
|
76
|
+
}
|
|
77
|
+
if (type.startsWith("int")) {
|
|
78
|
+
if (!size || size % 8 || size < 8 || size > 256) throw new Error(`Invalid int${size} size`);
|
|
79
|
+
num = _parseNumber(value);
|
|
80
|
+
if (num.bitLength() > size) throw new Error(`Supplied int exceeds width: ${size} vs ${num.bitLength()}`);
|
|
81
|
+
if (num.lt(new BN(0))) return num.toTwos(size).toString("hex");
|
|
82
|
+
return size ? leftPad(num.toString("hex"), size / 8 * 2, "0") : num.toString("hex");
|
|
83
|
+
}
|
|
84
|
+
throw new Error(`Unsupported or invalid type: ${type}`);
|
|
85
|
+
};
|
|
86
|
+
const _processSolidityEncodePackedArgs = (arg) => {
|
|
87
|
+
if (!arg || typeof arg !== "object") throw new Error("arg must be an object");
|
|
88
|
+
let arraySize;
|
|
89
|
+
const type = arg.t || arg.type;
|
|
90
|
+
let value = arg.v || arg.value;
|
|
91
|
+
if ((type.startsWith("int") || type.startsWith("uint")) && typeof value === "string" && !/^(-)?0x/i.test(value)) value = new BN(value);
|
|
92
|
+
if (Array.isArray(value)) {
|
|
93
|
+
arraySize = _parseTypeNArray(type);
|
|
94
|
+
if (arraySize && value.length !== arraySize) throw new Error(`${type} is not matching the given array ${JSON.stringify(value)}`);
|
|
95
|
+
arraySize = value.length;
|
|
96
|
+
}
|
|
97
|
+
if (Array.isArray(value)) return value.map((val) => _solidityPack(type, val, arraySize).replace("0x", "")).join("");
|
|
98
|
+
return _solidityPack(type, value, arraySize).replace("0x", "");
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* Encode packed args to hex
|
|
102
|
+
*
|
|
103
|
+
* @method encodePacked
|
|
104
|
+
* @return {String} the hex encoded arguments
|
|
105
|
+
*/
|
|
106
|
+
const encodePacked = (...args) => {
|
|
107
|
+
return `0x${args.map(_processSolidityEncodePackedArgs).join("").toLowerCase()}`;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
//#endregion
|
|
111
|
+
export { encodePacked };
|
package/esm/index.d.mts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { SolidityValue } from "./abi.mjs";
|
|
2
|
+
import * as _ocap_util0 from "@ocap/util";
|
|
3
|
+
|
|
4
|
+
//#region src/index.d.ts
|
|
5
|
+
interface MerkleTreeTx {
|
|
6
|
+
hash: string;
|
|
7
|
+
to?: string;
|
|
8
|
+
amount?: string | number;
|
|
9
|
+
}
|
|
10
|
+
interface MerkleBlockLike {
|
|
11
|
+
height: number;
|
|
12
|
+
previousHash: string;
|
|
13
|
+
merkleRoot: string;
|
|
14
|
+
txsHash: string;
|
|
15
|
+
}
|
|
16
|
+
declare class MerkleTree {
|
|
17
|
+
elements: Buffer[];
|
|
18
|
+
layers: Buffer[][];
|
|
19
|
+
constructor(elements: string[]);
|
|
20
|
+
getLayers(elements: Buffer[]): Buffer[][];
|
|
21
|
+
getNextLayer(elements: Buffer[]): Buffer[];
|
|
22
|
+
combinedHash(first: Buffer | undefined, second: Buffer | undefined): Buffer;
|
|
23
|
+
getRoot(): Buffer;
|
|
24
|
+
getHexRoot(): string;
|
|
25
|
+
getProof(el: string | Buffer): Buffer[];
|
|
26
|
+
getHexProof(el: string | Buffer): string[];
|
|
27
|
+
verify(proofs: Array<string | Buffer>, merkleRoot: string, leaf: string | Buffer): boolean;
|
|
28
|
+
getPairElement(idx: number, layer: Buffer[]): Buffer | null;
|
|
29
|
+
bufIndexOf(el: string | Buffer, arr: Buffer[]): number;
|
|
30
|
+
bufDeduplicate(elements: Buffer[]): Buffer[];
|
|
31
|
+
bufArrToHexArr(arr: Buffer[]): string[];
|
|
32
|
+
sortAndConcat(...args: Buffer[]): Buffer;
|
|
33
|
+
static BLACK_HOLE: string;
|
|
34
|
+
static keccak256: (data: _ocap_util0.BytesType, round?: number, encoding?: _ocap_util0.EncodingType) => _ocap_util0.BytesType;
|
|
35
|
+
static encodePacked: (...args: SolidityValue[]) => string;
|
|
36
|
+
static getListHash: (list: string[]) => string;
|
|
37
|
+
static getBlockHash: (block: MerkleBlockLike | null | undefined) => string;
|
|
38
|
+
static getBlockMerkleTree: (txs: Array<MerkleTreeTx | null | undefined>) => MerkleTree | {
|
|
39
|
+
getHexRoot: () => string;
|
|
40
|
+
getHexProof: () => string[];
|
|
41
|
+
elements: never[];
|
|
42
|
+
layers: never[];
|
|
43
|
+
verify: () => boolean;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
export { MerkleBlockLike, MerkleTreeTx, MerkleTree as default };
|
package/esm/index.mjs
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { encodePacked } from "./abi.mjs";
|
|
2
|
+
import { Hasher } from "@ocap/mcrypto";
|
|
3
|
+
import { toBuffer, toHex } from "@ocap/util";
|
|
4
|
+
|
|
5
|
+
//#region src/index.ts
|
|
6
|
+
const keccak256 = Hasher.Keccak.hash256;
|
|
7
|
+
const keccakFromString = (str) => toBuffer(keccak256(str));
|
|
8
|
+
var MerkleTree = class MerkleTree {
|
|
9
|
+
constructor(elements) {
|
|
10
|
+
this.elements = elements.filter(Boolean).map((x) => keccakFromString(x));
|
|
11
|
+
this.elements.sort(Buffer.compare);
|
|
12
|
+
this.elements = this.bufDeduplicate(this.elements);
|
|
13
|
+
this.layers = this.getLayers(this.elements);
|
|
14
|
+
}
|
|
15
|
+
getLayers(elements) {
|
|
16
|
+
if (elements.length === 0) return [[""]];
|
|
17
|
+
const layers = [];
|
|
18
|
+
layers.push(elements);
|
|
19
|
+
while (layers[layers.length - 1].length > 1) layers.push(this.getNextLayer(layers[layers.length - 1]));
|
|
20
|
+
return layers;
|
|
21
|
+
}
|
|
22
|
+
getNextLayer(elements) {
|
|
23
|
+
return elements.reduce((layer, el, idx, arr) => {
|
|
24
|
+
if (idx % 2 === 0) layer.push(this.combinedHash(el, arr[idx + 1]));
|
|
25
|
+
return layer;
|
|
26
|
+
}, []);
|
|
27
|
+
}
|
|
28
|
+
combinedHash(first, second) {
|
|
29
|
+
if (!first) return second;
|
|
30
|
+
if (!second) return first;
|
|
31
|
+
return toBuffer(keccak256(this.sortAndConcat(first, second)));
|
|
32
|
+
}
|
|
33
|
+
getRoot() {
|
|
34
|
+
return this.layers[this.layers.length - 1][0];
|
|
35
|
+
}
|
|
36
|
+
getHexRoot() {
|
|
37
|
+
return toHex(this.getRoot());
|
|
38
|
+
}
|
|
39
|
+
getProof(el) {
|
|
40
|
+
let idx = this.bufIndexOf(el, this.elements);
|
|
41
|
+
if (idx === -1) throw new Error("Element does not exist in Merkle tree");
|
|
42
|
+
return this.layers.reduce((proof, layer) => {
|
|
43
|
+
const pairElement = this.getPairElement(idx, layer);
|
|
44
|
+
if (pairElement) proof.push(pairElement);
|
|
45
|
+
idx = Math.floor(idx / 2);
|
|
46
|
+
return proof;
|
|
47
|
+
}, []);
|
|
48
|
+
}
|
|
49
|
+
getHexProof(el) {
|
|
50
|
+
const proof = this.getProof(el);
|
|
51
|
+
return this.bufArrToHexArr(proof);
|
|
52
|
+
}
|
|
53
|
+
verify(proofs, merkleRoot, leaf) {
|
|
54
|
+
if (!Array.isArray(proofs) || !leaf || !merkleRoot) return false;
|
|
55
|
+
if (proofs.length === 0 && this.elements.length > 1) return false;
|
|
56
|
+
let computedHash = toBuffer(leaf);
|
|
57
|
+
if (!computedHash || computedHash.length === 0) return false;
|
|
58
|
+
for (let i = 0; i < proofs.length; i++) {
|
|
59
|
+
if (!proofs[i]) return false;
|
|
60
|
+
const proofElement = toBuffer(proofs[i]);
|
|
61
|
+
if (!proofElement || proofElement.length === 0) return false;
|
|
62
|
+
computedHash = this.combinedHash(proofElement, computedHash);
|
|
63
|
+
}
|
|
64
|
+
return toHex(computedHash) === merkleRoot;
|
|
65
|
+
}
|
|
66
|
+
getPairElement(idx, layer) {
|
|
67
|
+
const pairIdx = idx % 2 === 0 ? idx + 1 : idx - 1;
|
|
68
|
+
if (pairIdx < layer.length) return layer[pairIdx];
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
bufIndexOf(el, arr) {
|
|
72
|
+
let hash;
|
|
73
|
+
if (el.length !== 32 || !Buffer.isBuffer(el)) hash = keccakFromString(el);
|
|
74
|
+
else hash = el;
|
|
75
|
+
for (let i = 0; i < arr.length; i++) if (hash.equals(arr[i])) return i;
|
|
76
|
+
return -1;
|
|
77
|
+
}
|
|
78
|
+
bufDeduplicate(elements) {
|
|
79
|
+
return elements.filter((el, idx) => idx === 0 || !elements[idx - 1].equals(el));
|
|
80
|
+
}
|
|
81
|
+
bufArrToHexArr(arr) {
|
|
82
|
+
if (arr.some((el) => !Buffer.isBuffer(el))) throw new Error("Array is not an array of buffers");
|
|
83
|
+
return arr.map((el) => `0x${el.toString("hex")}`);
|
|
84
|
+
}
|
|
85
|
+
sortAndConcat(...args) {
|
|
86
|
+
return Buffer.concat([...args].sort(Buffer.compare));
|
|
87
|
+
}
|
|
88
|
+
static {
|
|
89
|
+
this.BLACK_HOLE = "0x0000000000000000000000000000000000000000";
|
|
90
|
+
}
|
|
91
|
+
static {
|
|
92
|
+
this.keccak256 = keccak256;
|
|
93
|
+
}
|
|
94
|
+
static {
|
|
95
|
+
this.encodePacked = encodePacked;
|
|
96
|
+
}
|
|
97
|
+
static {
|
|
98
|
+
this.getListHash = (list) => list.length ? keccak256(list.map((x) => x.startsWith("0x") ? x : `0x${x}`).reduce((acc, x) => encodePacked({
|
|
99
|
+
type: "bytes",
|
|
100
|
+
value: acc
|
|
101
|
+
}, {
|
|
102
|
+
type: "bytes",
|
|
103
|
+
value: x
|
|
104
|
+
}), "")) : "";
|
|
105
|
+
}
|
|
106
|
+
static {
|
|
107
|
+
this.getBlockHash = (block) => block ? keccak256(encodePacked({
|
|
108
|
+
type: "uint256",
|
|
109
|
+
value: block.height
|
|
110
|
+
}, {
|
|
111
|
+
type: "bytes32",
|
|
112
|
+
value: block.previousHash
|
|
113
|
+
}, {
|
|
114
|
+
type: "bytes32",
|
|
115
|
+
value: block.merkleRoot
|
|
116
|
+
}, {
|
|
117
|
+
type: "bytes32",
|
|
118
|
+
value: block.txsHash
|
|
119
|
+
})) : "";
|
|
120
|
+
}
|
|
121
|
+
static {
|
|
122
|
+
this.getBlockMerkleTree = (txs) => txs.length ? new MerkleTree(txs.map((x) => encodePacked({
|
|
123
|
+
type: "bytes32",
|
|
124
|
+
value: x.hash.startsWith("0x") ? x.hash : `0x${x.hash}`
|
|
125
|
+
}, {
|
|
126
|
+
type: "address",
|
|
127
|
+
value: x.to
|
|
128
|
+
}, {
|
|
129
|
+
type: "uint256",
|
|
130
|
+
value: x.amount
|
|
131
|
+
}))) : {
|
|
132
|
+
getHexRoot: () => "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
|
|
133
|
+
getHexProof: () => [],
|
|
134
|
+
elements: [],
|
|
135
|
+
layers: [],
|
|
136
|
+
verify: () => false
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
var src_default = MerkleTree;
|
|
141
|
+
|
|
142
|
+
//#endregion
|
|
143
|
+
export { src_default as default };
|
package/lib/abi.cjs
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
let _ocap_mcrypto = require("@ocap/mcrypto");
|
|
2
|
+
let _ocap_util = require("@ocap/util");
|
|
3
|
+
|
|
4
|
+
//#region src/abi.ts
|
|
5
|
+
const keccak256 = _ocap_mcrypto.Hasher.Keccak.hash256;
|
|
6
|
+
const isAddress = (address) => {
|
|
7
|
+
if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) return false;
|
|
8
|
+
if (/^(0x|0X)?[0-9a-f]{40}$/.test(address) || /^(0x|0X)?[0-9A-F]{40}$/.test(address)) return true;
|
|
9
|
+
return checkAddressChecksum(address);
|
|
10
|
+
};
|
|
11
|
+
const checkAddressChecksum = (address) => {
|
|
12
|
+
const origin = address.replace(/^0x/i, "");
|
|
13
|
+
const addressHash = keccak256(origin.toLowerCase()).replace(/^0x/i, "");
|
|
14
|
+
for (let i = 0; i < 40; i++) if (Number.parseInt(addressHash[i], 16) > 7 && origin[i].toUpperCase() !== origin[i] || Number.parseInt(addressHash[i], 16) <= 7 && origin[i].toLowerCase() !== origin[i]) return false;
|
|
15
|
+
return true;
|
|
16
|
+
};
|
|
17
|
+
const _elementaryName = (name) => {
|
|
18
|
+
if (name.startsWith("int[")) return `int256${name.slice(3)}`;
|
|
19
|
+
if (name === "int") return "int256";
|
|
20
|
+
if (name.startsWith("uint[")) return `uint256${name.slice(4)}`;
|
|
21
|
+
if (name === "uint") return "uint256";
|
|
22
|
+
if (name.startsWith("fixed[")) return `fixed128x128${name.slice(5)}`;
|
|
23
|
+
if (name === "fixed") return "fixed128x128";
|
|
24
|
+
if (name.startsWith("ufixed[")) return `ufixed128x128${name.slice(6)}`;
|
|
25
|
+
if (name === "ufixed") return "ufixed128x128";
|
|
26
|
+
return name;
|
|
27
|
+
};
|
|
28
|
+
const _parseTypeN = (type) => {
|
|
29
|
+
const size = /^\D+(\d+).*$/.exec(type);
|
|
30
|
+
return size ? Number.parseInt(size[1], 10) : null;
|
|
31
|
+
};
|
|
32
|
+
const _parseTypeNArray = (type) => {
|
|
33
|
+
const arraySize = /^\D+\d*\[(\d+)\]$/.exec(type);
|
|
34
|
+
return arraySize ? Number.parseInt(arraySize[1], 10) : null;
|
|
35
|
+
};
|
|
36
|
+
const _parseNumber = (arg) => {
|
|
37
|
+
const type = typeof arg;
|
|
38
|
+
if (type === "string") {
|
|
39
|
+
if ((0, _ocap_util.isHexStrict)(arg)) return new _ocap_util.BN(arg.replace(/0x/i, ""), 16);
|
|
40
|
+
return new _ocap_util.BN(arg, 10);
|
|
41
|
+
}
|
|
42
|
+
if (type === "number") return new _ocap_util.BN(arg);
|
|
43
|
+
if ((0, _ocap_util.isBigNumber)(arg)) return new _ocap_util.BN(arg.toString(10));
|
|
44
|
+
if ((0, _ocap_util.isBN)(arg)) return arg;
|
|
45
|
+
throw new Error(`${arg} is not a number`);
|
|
46
|
+
};
|
|
47
|
+
const _solidityPack = (rawType, value, arraySize) => {
|
|
48
|
+
let size;
|
|
49
|
+
let num;
|
|
50
|
+
const type = _elementaryName(rawType);
|
|
51
|
+
if (type === "bytes") {
|
|
52
|
+
const str = value;
|
|
53
|
+
if (str.replace(/^0x/i, "").length % 2 !== 0) throw new Error(`Invalid bytes characters ${str.length}`);
|
|
54
|
+
return str;
|
|
55
|
+
}
|
|
56
|
+
if (type === "string") return (0, _ocap_util.utf8ToHex)(value);
|
|
57
|
+
if (type === "bool") return value ? "01" : "00";
|
|
58
|
+
if (type.startsWith("address")) {
|
|
59
|
+
size = arraySize ? 64 : 40;
|
|
60
|
+
if (!isAddress(value)) throw new Error(`${value} is not a valid address, or the checksum is invalid.`);
|
|
61
|
+
return (0, _ocap_util.leftPad)(value.toLowerCase(), size, "0");
|
|
62
|
+
}
|
|
63
|
+
size = _parseTypeN(type);
|
|
64
|
+
if (type.startsWith("bytes")) {
|
|
65
|
+
if (!size) throw new Error("bytes[] not yet supported in solidity");
|
|
66
|
+
if (arraySize) size = 32;
|
|
67
|
+
if (size < 1 || size > 32 || size < value.replace(/^0x/i, "").length / 2) throw new Error(`Invalid bytes${size} for ${value}`);
|
|
68
|
+
return (0, _ocap_util.rightPad)(value, size * 2, "0");
|
|
69
|
+
}
|
|
70
|
+
if (type.startsWith("uint")) {
|
|
71
|
+
if (!size || size % 8 || size < 8 || size > 256) throw new Error(`Invalid uint${size} size`);
|
|
72
|
+
num = _parseNumber(value);
|
|
73
|
+
if (num.bitLength() > size) throw new Error(`Supplied uint exceeds width: ${size} vs ${num.bitLength()}`);
|
|
74
|
+
if (num.lt(new _ocap_util.BN(0))) throw new Error(`Supplied uint ${num.toString()} is negative`);
|
|
75
|
+
return size ? (0, _ocap_util.leftPad)(num.toString("hex"), size / 8 * 2, "0") : num.toString("hex");
|
|
76
|
+
}
|
|
77
|
+
if (type.startsWith("int")) {
|
|
78
|
+
if (!size || size % 8 || size < 8 || size > 256) throw new Error(`Invalid int${size} size`);
|
|
79
|
+
num = _parseNumber(value);
|
|
80
|
+
if (num.bitLength() > size) throw new Error(`Supplied int exceeds width: ${size} vs ${num.bitLength()}`);
|
|
81
|
+
if (num.lt(new _ocap_util.BN(0))) return num.toTwos(size).toString("hex");
|
|
82
|
+
return size ? (0, _ocap_util.leftPad)(num.toString("hex"), size / 8 * 2, "0") : num.toString("hex");
|
|
83
|
+
}
|
|
84
|
+
throw new Error(`Unsupported or invalid type: ${type}`);
|
|
85
|
+
};
|
|
86
|
+
const _processSolidityEncodePackedArgs = (arg) => {
|
|
87
|
+
if (!arg || typeof arg !== "object") throw new Error("arg must be an object");
|
|
88
|
+
let arraySize;
|
|
89
|
+
const type = arg.t || arg.type;
|
|
90
|
+
let value = arg.v || arg.value;
|
|
91
|
+
if ((type.startsWith("int") || type.startsWith("uint")) && typeof value === "string" && !/^(-)?0x/i.test(value)) value = new _ocap_util.BN(value);
|
|
92
|
+
if (Array.isArray(value)) {
|
|
93
|
+
arraySize = _parseTypeNArray(type);
|
|
94
|
+
if (arraySize && value.length !== arraySize) throw new Error(`${type} is not matching the given array ${JSON.stringify(value)}`);
|
|
95
|
+
arraySize = value.length;
|
|
96
|
+
}
|
|
97
|
+
if (Array.isArray(value)) return value.map((val) => _solidityPack(type, val, arraySize).replace("0x", "")).join("");
|
|
98
|
+
return _solidityPack(type, value, arraySize).replace("0x", "");
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* Encode packed args to hex
|
|
102
|
+
*
|
|
103
|
+
* @method encodePacked
|
|
104
|
+
* @return {String} the hex encoded arguments
|
|
105
|
+
*/
|
|
106
|
+
const encodePacked = (...args) => {
|
|
107
|
+
return `0x${args.map(_processSolidityEncodePackedArgs).join("").toLowerCase()}`;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
//#endregion
|
|
111
|
+
exports.encodePacked = encodePacked;
|
package/lib/abi.d.cts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
//#region src/abi.d.ts
|
|
2
|
+
interface SolidityValue {
|
|
3
|
+
t?: string;
|
|
4
|
+
type?: string;
|
|
5
|
+
v?: unknown;
|
|
6
|
+
value?: unknown;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Encode packed args to hex
|
|
10
|
+
*
|
|
11
|
+
* @method encodePacked
|
|
12
|
+
* @return {String} the hex encoded arguments
|
|
13
|
+
*/
|
|
14
|
+
declare const encodePacked: (...args: SolidityValue[]) => string;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { SolidityValue, encodePacked };
|
package/lib/index.cjs
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
2
|
+
const require_abi = require('./abi.cjs');
|
|
3
|
+
let _ocap_mcrypto = require("@ocap/mcrypto");
|
|
4
|
+
let _ocap_util = require("@ocap/util");
|
|
5
|
+
|
|
6
|
+
//#region src/index.ts
|
|
7
|
+
const keccak256 = _ocap_mcrypto.Hasher.Keccak.hash256;
|
|
8
|
+
const keccakFromString = (str) => (0, _ocap_util.toBuffer)(keccak256(str));
|
|
9
|
+
var MerkleTree = class MerkleTree {
|
|
10
|
+
constructor(elements) {
|
|
11
|
+
this.elements = elements.filter(Boolean).map((x) => keccakFromString(x));
|
|
12
|
+
this.elements.sort(Buffer.compare);
|
|
13
|
+
this.elements = this.bufDeduplicate(this.elements);
|
|
14
|
+
this.layers = this.getLayers(this.elements);
|
|
15
|
+
}
|
|
16
|
+
getLayers(elements) {
|
|
17
|
+
if (elements.length === 0) return [[""]];
|
|
18
|
+
const layers = [];
|
|
19
|
+
layers.push(elements);
|
|
20
|
+
while (layers[layers.length - 1].length > 1) layers.push(this.getNextLayer(layers[layers.length - 1]));
|
|
21
|
+
return layers;
|
|
22
|
+
}
|
|
23
|
+
getNextLayer(elements) {
|
|
24
|
+
return elements.reduce((layer, el, idx, arr) => {
|
|
25
|
+
if (idx % 2 === 0) layer.push(this.combinedHash(el, arr[idx + 1]));
|
|
26
|
+
return layer;
|
|
27
|
+
}, []);
|
|
28
|
+
}
|
|
29
|
+
combinedHash(first, second) {
|
|
30
|
+
if (!first) return second;
|
|
31
|
+
if (!second) return first;
|
|
32
|
+
return (0, _ocap_util.toBuffer)(keccak256(this.sortAndConcat(first, second)));
|
|
33
|
+
}
|
|
34
|
+
getRoot() {
|
|
35
|
+
return this.layers[this.layers.length - 1][0];
|
|
36
|
+
}
|
|
37
|
+
getHexRoot() {
|
|
38
|
+
return (0, _ocap_util.toHex)(this.getRoot());
|
|
39
|
+
}
|
|
40
|
+
getProof(el) {
|
|
41
|
+
let idx = this.bufIndexOf(el, this.elements);
|
|
42
|
+
if (idx === -1) throw new Error("Element does not exist in Merkle tree");
|
|
43
|
+
return this.layers.reduce((proof, layer) => {
|
|
44
|
+
const pairElement = this.getPairElement(idx, layer);
|
|
45
|
+
if (pairElement) proof.push(pairElement);
|
|
46
|
+
idx = Math.floor(idx / 2);
|
|
47
|
+
return proof;
|
|
48
|
+
}, []);
|
|
49
|
+
}
|
|
50
|
+
getHexProof(el) {
|
|
51
|
+
const proof = this.getProof(el);
|
|
52
|
+
return this.bufArrToHexArr(proof);
|
|
53
|
+
}
|
|
54
|
+
verify(proofs, merkleRoot, leaf) {
|
|
55
|
+
if (!Array.isArray(proofs) || !leaf || !merkleRoot) return false;
|
|
56
|
+
if (proofs.length === 0 && this.elements.length > 1) return false;
|
|
57
|
+
let computedHash = (0, _ocap_util.toBuffer)(leaf);
|
|
58
|
+
if (!computedHash || computedHash.length === 0) return false;
|
|
59
|
+
for (let i = 0; i < proofs.length; i++) {
|
|
60
|
+
if (!proofs[i]) return false;
|
|
61
|
+
const proofElement = (0, _ocap_util.toBuffer)(proofs[i]);
|
|
62
|
+
if (!proofElement || proofElement.length === 0) return false;
|
|
63
|
+
computedHash = this.combinedHash(proofElement, computedHash);
|
|
64
|
+
}
|
|
65
|
+
return (0, _ocap_util.toHex)(computedHash) === merkleRoot;
|
|
66
|
+
}
|
|
67
|
+
getPairElement(idx, layer) {
|
|
68
|
+
const pairIdx = idx % 2 === 0 ? idx + 1 : idx - 1;
|
|
69
|
+
if (pairIdx < layer.length) return layer[pairIdx];
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
bufIndexOf(el, arr) {
|
|
73
|
+
let hash;
|
|
74
|
+
if (el.length !== 32 || !Buffer.isBuffer(el)) hash = keccakFromString(el);
|
|
75
|
+
else hash = el;
|
|
76
|
+
for (let i = 0; i < arr.length; i++) if (hash.equals(arr[i])) return i;
|
|
77
|
+
return -1;
|
|
78
|
+
}
|
|
79
|
+
bufDeduplicate(elements) {
|
|
80
|
+
return elements.filter((el, idx) => idx === 0 || !elements[idx - 1].equals(el));
|
|
81
|
+
}
|
|
82
|
+
bufArrToHexArr(arr) {
|
|
83
|
+
if (arr.some((el) => !Buffer.isBuffer(el))) throw new Error("Array is not an array of buffers");
|
|
84
|
+
return arr.map((el) => `0x${el.toString("hex")}`);
|
|
85
|
+
}
|
|
86
|
+
sortAndConcat(...args) {
|
|
87
|
+
return Buffer.concat([...args].sort(Buffer.compare));
|
|
88
|
+
}
|
|
89
|
+
static {
|
|
90
|
+
this.BLACK_HOLE = "0x0000000000000000000000000000000000000000";
|
|
91
|
+
}
|
|
92
|
+
static {
|
|
93
|
+
this.keccak256 = keccak256;
|
|
94
|
+
}
|
|
95
|
+
static {
|
|
96
|
+
this.encodePacked = require_abi.encodePacked;
|
|
97
|
+
}
|
|
98
|
+
static {
|
|
99
|
+
this.getListHash = (list) => list.length ? keccak256(list.map((x) => x.startsWith("0x") ? x : `0x${x}`).reduce((acc, x) => require_abi.encodePacked({
|
|
100
|
+
type: "bytes",
|
|
101
|
+
value: acc
|
|
102
|
+
}, {
|
|
103
|
+
type: "bytes",
|
|
104
|
+
value: x
|
|
105
|
+
}), "")) : "";
|
|
106
|
+
}
|
|
107
|
+
static {
|
|
108
|
+
this.getBlockHash = (block) => block ? keccak256(require_abi.encodePacked({
|
|
109
|
+
type: "uint256",
|
|
110
|
+
value: block.height
|
|
111
|
+
}, {
|
|
112
|
+
type: "bytes32",
|
|
113
|
+
value: block.previousHash
|
|
114
|
+
}, {
|
|
115
|
+
type: "bytes32",
|
|
116
|
+
value: block.merkleRoot
|
|
117
|
+
}, {
|
|
118
|
+
type: "bytes32",
|
|
119
|
+
value: block.txsHash
|
|
120
|
+
})) : "";
|
|
121
|
+
}
|
|
122
|
+
static {
|
|
123
|
+
this.getBlockMerkleTree = (txs) => txs.length ? new MerkleTree(txs.map((x) => require_abi.encodePacked({
|
|
124
|
+
type: "bytes32",
|
|
125
|
+
value: x.hash.startsWith("0x") ? x.hash : `0x${x.hash}`
|
|
126
|
+
}, {
|
|
127
|
+
type: "address",
|
|
128
|
+
value: x.to
|
|
129
|
+
}, {
|
|
130
|
+
type: "uint256",
|
|
131
|
+
value: x.amount
|
|
132
|
+
}))) : {
|
|
133
|
+
getHexRoot: () => "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
|
|
134
|
+
getHexProof: () => [],
|
|
135
|
+
elements: [],
|
|
136
|
+
layers: [],
|
|
137
|
+
verify: () => false
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
var src_default = MerkleTree;
|
|
142
|
+
|
|
143
|
+
//#endregion
|
|
144
|
+
exports.default = src_default;
|
package/lib/index.d.cts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { SolidityValue } from "./abi.cjs";
|
|
2
|
+
import * as _ocap_util0 from "@ocap/util";
|
|
3
|
+
|
|
4
|
+
//#region src/index.d.ts
|
|
5
|
+
interface MerkleTreeTx {
|
|
6
|
+
hash: string;
|
|
7
|
+
to?: string;
|
|
8
|
+
amount?: string | number;
|
|
9
|
+
}
|
|
10
|
+
interface MerkleBlockLike {
|
|
11
|
+
height: number;
|
|
12
|
+
previousHash: string;
|
|
13
|
+
merkleRoot: string;
|
|
14
|
+
txsHash: string;
|
|
15
|
+
}
|
|
16
|
+
declare class MerkleTree {
|
|
17
|
+
elements: Buffer[];
|
|
18
|
+
layers: Buffer[][];
|
|
19
|
+
constructor(elements: string[]);
|
|
20
|
+
getLayers(elements: Buffer[]): Buffer[][];
|
|
21
|
+
getNextLayer(elements: Buffer[]): Buffer[];
|
|
22
|
+
combinedHash(first: Buffer | undefined, second: Buffer | undefined): Buffer;
|
|
23
|
+
getRoot(): Buffer;
|
|
24
|
+
getHexRoot(): string;
|
|
25
|
+
getProof(el: string | Buffer): Buffer[];
|
|
26
|
+
getHexProof(el: string | Buffer): string[];
|
|
27
|
+
verify(proofs: Array<string | Buffer>, merkleRoot: string, leaf: string | Buffer): boolean;
|
|
28
|
+
getPairElement(idx: number, layer: Buffer[]): Buffer | null;
|
|
29
|
+
bufIndexOf(el: string | Buffer, arr: Buffer[]): number;
|
|
30
|
+
bufDeduplicate(elements: Buffer[]): Buffer[];
|
|
31
|
+
bufArrToHexArr(arr: Buffer[]): string[];
|
|
32
|
+
sortAndConcat(...args: Buffer[]): Buffer;
|
|
33
|
+
static BLACK_HOLE: string;
|
|
34
|
+
static keccak256: (data: _ocap_util0.BytesType, round?: number, encoding?: _ocap_util0.EncodingType) => _ocap_util0.BytesType;
|
|
35
|
+
static encodePacked: (...args: SolidityValue[]) => string;
|
|
36
|
+
static getListHash: (list: string[]) => string;
|
|
37
|
+
static getBlockHash: (block: MerkleBlockLike | null | undefined) => string;
|
|
38
|
+
static getBlockMerkleTree: (txs: Array<MerkleTreeTx | null | undefined>) => MerkleTree | {
|
|
39
|
+
getHexRoot: () => string;
|
|
40
|
+
getHexProof: () => string[];
|
|
41
|
+
elements: never[];
|
|
42
|
+
layers: never[];
|
|
43
|
+
verify: () => boolean;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
export { MerkleBlockLike, MerkleTreeTx, MerkleTree as default };
|
package/package.json
CHANGED
|
@@ -3,24 +3,40 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "1.30.
|
|
6
|
+
"version": "1.30.25",
|
|
7
7
|
"description": "Merkle tree implementation that powers DID Rollup",
|
|
8
|
-
"main": "lib/index.
|
|
8
|
+
"main": "./lib/index.cjs",
|
|
9
|
+
"module": "./esm/index.mjs",
|
|
10
|
+
"types": "./esm/index.d.mts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./esm/index.d.mts",
|
|
14
|
+
"import": "./esm/index.mjs",
|
|
15
|
+
"default": "./lib/index.cjs"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
9
18
|
"files": [
|
|
10
|
-
"lib"
|
|
19
|
+
"lib",
|
|
20
|
+
"esm"
|
|
11
21
|
],
|
|
12
22
|
"scripts": {
|
|
13
23
|
"lint": "biome check",
|
|
14
24
|
"lint:fix": "biome check --write",
|
|
15
25
|
"test": "bun test",
|
|
16
|
-
"coverage": "npm run test -- --coverage"
|
|
26
|
+
"coverage": "npm run test -- --coverage",
|
|
27
|
+
"build": "tsdown",
|
|
28
|
+
"build:watch": "tsdown -w",
|
|
29
|
+
"clean": "rm -rf lib esm"
|
|
17
30
|
},
|
|
18
31
|
"keywords": [],
|
|
19
32
|
"author": "wangshijun <wangshijun2010@gmail.com> (http://github.com/wangshijun)",
|
|
20
33
|
"license": "MIT",
|
|
21
|
-
"devDependencies": {
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@types/node": "^22.7.5",
|
|
36
|
+
"tsdown": "^0.18.4"
|
|
37
|
+
},
|
|
22
38
|
"dependencies": {
|
|
23
|
-
"@ocap/mcrypto": "1.30.
|
|
24
|
-
"@ocap/util": "1.30.
|
|
39
|
+
"@ocap/mcrypto": "1.30.25",
|
|
40
|
+
"@ocap/util": "1.30.25"
|
|
25
41
|
}
|
|
26
42
|
}
|
package/lib/abi.js
DELETED
|
@@ -1,221 +0,0 @@
|
|
|
1
|
-
// Ported from: https://github.com/ChainSafe/web3.js/blob/1.x/packages/web3-utils/src/soliditySha3.js
|
|
2
|
-
|
|
3
|
-
const Mcrypto = require('@ocap/mcrypto');
|
|
4
|
-
const { BN, isHexStrict, isBigNumber, isBN, utf8ToHex, leftPad, rightPad } = require('@ocap/util');
|
|
5
|
-
|
|
6
|
-
const keccak256 = Mcrypto.Hasher.Keccak.hash256;
|
|
7
|
-
|
|
8
|
-
const isAddress = (address) => {
|
|
9
|
-
if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) {
|
|
10
|
-
return false;
|
|
11
|
-
}
|
|
12
|
-
if (/^(0x|0X)?[0-9a-f]{40}$/.test(address) || /^(0x|0X)?[0-9A-F]{40}$/.test(address)) {
|
|
13
|
-
return true;
|
|
14
|
-
}
|
|
15
|
-
return checkAddressChecksum(address);
|
|
16
|
-
};
|
|
17
|
-
|
|
18
|
-
const checkAddressChecksum = (address) => {
|
|
19
|
-
const origin = address.replace(/^0x/i, '');
|
|
20
|
-
const addressHash = keccak256(origin.toLowerCase()).replace(/^0x/i, '');
|
|
21
|
-
for (let i = 0; i < 40; i++) {
|
|
22
|
-
if (
|
|
23
|
-
(Number.parseInt(addressHash[i], 16) > 7 && origin[i].toUpperCase() !== origin[i]) ||
|
|
24
|
-
(Number.parseInt(addressHash[i], 16) <= 7 && origin[i].toLowerCase() !== origin[i])
|
|
25
|
-
) {
|
|
26
|
-
return false;
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
return true;
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
const _elementaryName = (name) => {
|
|
33
|
-
if (name.startsWith('int[')) {
|
|
34
|
-
return `int256${name.slice(3)}`;
|
|
35
|
-
}
|
|
36
|
-
if (name === 'int') {
|
|
37
|
-
return 'int256';
|
|
38
|
-
}
|
|
39
|
-
if (name.startsWith('uint[')) {
|
|
40
|
-
return `uint256${name.slice(4)}`;
|
|
41
|
-
}
|
|
42
|
-
if (name === 'uint') {
|
|
43
|
-
return 'uint256';
|
|
44
|
-
}
|
|
45
|
-
if (name.startsWith('fixed[')) {
|
|
46
|
-
return `fixed128x128${name.slice(5)}`;
|
|
47
|
-
}
|
|
48
|
-
if (name === 'fixed') {
|
|
49
|
-
return 'fixed128x128';
|
|
50
|
-
}
|
|
51
|
-
if (name.startsWith('ufixed[')) {
|
|
52
|
-
return `ufixed128x128${name.slice(6)}`;
|
|
53
|
-
}
|
|
54
|
-
if (name === 'ufixed') {
|
|
55
|
-
return 'ufixed128x128';
|
|
56
|
-
}
|
|
57
|
-
return name;
|
|
58
|
-
};
|
|
59
|
-
|
|
60
|
-
// Parse N from type<N>
|
|
61
|
-
const _parseTypeN = (type) => {
|
|
62
|
-
const size = /^\D+(\d+).*$/.exec(type);
|
|
63
|
-
return size ? Number.parseInt(size[1], 10) : null;
|
|
64
|
-
};
|
|
65
|
-
|
|
66
|
-
// Parse N from type[<N>]
|
|
67
|
-
const _parseTypeNArray = (type) => {
|
|
68
|
-
const arraySize = /^\D+\d*\[(\d+)\]$/.exec(type);
|
|
69
|
-
return arraySize ? Number.parseInt(arraySize[1], 10) : null;
|
|
70
|
-
};
|
|
71
|
-
|
|
72
|
-
const _parseNumber = (arg) => {
|
|
73
|
-
const type = typeof arg;
|
|
74
|
-
if (type === 'string') {
|
|
75
|
-
if (isHexStrict(arg)) {
|
|
76
|
-
return new BN(arg.replace(/0x/i, ''), 16);
|
|
77
|
-
}
|
|
78
|
-
return new BN(arg, 10);
|
|
79
|
-
}
|
|
80
|
-
if (type === 'number') {
|
|
81
|
-
return new BN(arg);
|
|
82
|
-
}
|
|
83
|
-
if (isBigNumber(arg)) {
|
|
84
|
-
return new BN(arg.toString(10));
|
|
85
|
-
}
|
|
86
|
-
if (isBN(arg)) {
|
|
87
|
-
return arg;
|
|
88
|
-
}
|
|
89
|
-
throw new Error(`${arg} is not a number`);
|
|
90
|
-
};
|
|
91
|
-
|
|
92
|
-
const _solidityPack = (type, value, arraySize) => {
|
|
93
|
-
let size;
|
|
94
|
-
let num;
|
|
95
|
-
type = _elementaryName(type);
|
|
96
|
-
|
|
97
|
-
if (type === 'bytes') {
|
|
98
|
-
if (value.replace(/^0x/i, '').length % 2 !== 0) {
|
|
99
|
-
throw new Error(`Invalid bytes characters ${value.length}`);
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
return value;
|
|
103
|
-
}
|
|
104
|
-
if (type === 'string') {
|
|
105
|
-
return utf8ToHex(value);
|
|
106
|
-
}
|
|
107
|
-
if (type === 'bool') {
|
|
108
|
-
return value ? '01' : '00';
|
|
109
|
-
}
|
|
110
|
-
if (type.startsWith('address')) {
|
|
111
|
-
if (arraySize) {
|
|
112
|
-
size = 64;
|
|
113
|
-
} else {
|
|
114
|
-
size = 40;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
if (!isAddress(value)) {
|
|
118
|
-
throw new Error(`${value} is not a valid address, or the checksum is invalid.`);
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
return leftPad(value.toLowerCase(), size, '0');
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
size = _parseTypeN(type);
|
|
125
|
-
|
|
126
|
-
if (type.startsWith('bytes')) {
|
|
127
|
-
if (!size) {
|
|
128
|
-
throw new Error('bytes[] not yet supported in solidity');
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// must be 32 byte slices when in an array
|
|
132
|
-
if (arraySize) {
|
|
133
|
-
size = 32;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
if (size < 1 || size > 32 || size < value.replace(/^0x/i, '').length / 2) {
|
|
137
|
-
throw new Error(`Invalid bytes${size} for ${value}`);
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
return rightPad(value, size * 2, '0');
|
|
141
|
-
}
|
|
142
|
-
if (type.startsWith('uint')) {
|
|
143
|
-
if (size % 8 || size < 8 || size > 256) {
|
|
144
|
-
throw new Error(`Invalid uint${size} size`);
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
num = _parseNumber(value);
|
|
148
|
-
if (num.bitLength() > size) {
|
|
149
|
-
throw new Error(`Supplied uint exceeds width: ${size} vs ${num.bitLength()}`);
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
if (num.lt(new BN(0))) {
|
|
153
|
-
throw new Error(`Supplied uint ${num.toString()} is negative`);
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
return size ? leftPad(num.toString('hex'), (size / 8) * 2, '0') : num;
|
|
157
|
-
}
|
|
158
|
-
if (type.startsWith('int')) {
|
|
159
|
-
if (size % 8 || size < 8 || size > 256) {
|
|
160
|
-
throw new Error(`Invalid int${size} size`);
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
num = _parseNumber(value);
|
|
164
|
-
if (num.bitLength() > size) {
|
|
165
|
-
throw new Error(`Supplied int exceeds width: ${size} vs ${num.bitLength()}`);
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
if (num.lt(new BN(0))) {
|
|
169
|
-
return num.toTwos(size).toString('hex');
|
|
170
|
-
}
|
|
171
|
-
return size ? leftPad(num.toString('hex'), (size / 8) * 2, '0') : num;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
// FIXME: support all other types
|
|
175
|
-
throw new Error(`Unsupported or invalid type: ${type}`);
|
|
176
|
-
};
|
|
177
|
-
|
|
178
|
-
const _processSolidityEncodePackedArgs = (arg) => {
|
|
179
|
-
if (!arg || typeof arg !== 'object') {
|
|
180
|
-
throw new Error('arg must be an object');
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
let arraySize;
|
|
184
|
-
|
|
185
|
-
const type = arg.t || arg.type;
|
|
186
|
-
let value = arg.v || arg.value;
|
|
187
|
-
|
|
188
|
-
if ((type.startsWith('int') || type.startsWith('uint')) && typeof value === 'string' && !/^(-)?0x/i.test(value)) {
|
|
189
|
-
value = new BN(value);
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
// get the array size
|
|
193
|
-
if (Array.isArray(value)) {
|
|
194
|
-
arraySize = _parseTypeNArray(type);
|
|
195
|
-
if (arraySize && value.length !== arraySize) {
|
|
196
|
-
throw new Error(`${type} is not matching the given array ${JSON.stringify(value)}`);
|
|
197
|
-
}
|
|
198
|
-
arraySize = value.length;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
if (Array.isArray(value)) {
|
|
202
|
-
return value.map((val) => _solidityPack(type, val, arraySize).toString('hex').replace('0x', '')).join('');
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
return _solidityPack(type, value, arraySize).toString('hex').replace('0x', '');
|
|
206
|
-
};
|
|
207
|
-
|
|
208
|
-
/**
|
|
209
|
-
* Encode packed args to hex
|
|
210
|
-
*
|
|
211
|
-
* @method encodePacked
|
|
212
|
-
* @return {String} the hex encoded arguments
|
|
213
|
-
*/
|
|
214
|
-
const encodePacked = (...args) => {
|
|
215
|
-
const hexArgs = args.map(_processSolidityEncodePackedArgs);
|
|
216
|
-
return `0x${hexArgs.join('').toLowerCase()}`;
|
|
217
|
-
};
|
|
218
|
-
|
|
219
|
-
module.exports = {
|
|
220
|
-
encodePacked,
|
|
221
|
-
};
|
package/lib/index.js
DELETED
|
@@ -1,196 +0,0 @@
|
|
|
1
|
-
const Mcrypto = require('@ocap/mcrypto');
|
|
2
|
-
const { toHex, toBuffer } = require('@ocap/util');
|
|
3
|
-
|
|
4
|
-
const { encodePacked } = require('./abi');
|
|
5
|
-
|
|
6
|
-
const keccak256 = Mcrypto.Hasher.Keccak.hash256;
|
|
7
|
-
const keccakFromString = (str) => toBuffer(keccak256(str));
|
|
8
|
-
|
|
9
|
-
class MerkleTree {
|
|
10
|
-
constructor(elements) {
|
|
11
|
-
// Filter empty strings and hash elements
|
|
12
|
-
this.elements = elements.filter(Boolean).map((x) => keccakFromString(x));
|
|
13
|
-
|
|
14
|
-
// Sort elements
|
|
15
|
-
this.elements.sort(Buffer.compare);
|
|
16
|
-
|
|
17
|
-
// Deduplicate elements
|
|
18
|
-
this.elements = this.bufDeduplicate(this.elements);
|
|
19
|
-
|
|
20
|
-
// Create layers
|
|
21
|
-
this.layers = this.getLayers(this.elements);
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
getLayers(elements) {
|
|
25
|
-
if (elements.length === 0) {
|
|
26
|
-
return [['']];
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
const layers = [];
|
|
30
|
-
layers.push(elements);
|
|
31
|
-
|
|
32
|
-
// Get next layer until we reach the root
|
|
33
|
-
while (layers[layers.length - 1].length > 1) {
|
|
34
|
-
layers.push(this.getNextLayer(layers[layers.length - 1]));
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
return layers;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
getNextLayer(elements) {
|
|
41
|
-
return elements.reduce((layer, el, idx, arr) => {
|
|
42
|
-
if (idx % 2 === 0) {
|
|
43
|
-
// Hash the current element with its pair element
|
|
44
|
-
layer.push(this.combinedHash(el, arr[idx + 1]));
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
return layer;
|
|
48
|
-
}, []);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
combinedHash(first, second) {
|
|
52
|
-
if (!first) {
|
|
53
|
-
return second;
|
|
54
|
-
}
|
|
55
|
-
if (!second) {
|
|
56
|
-
return first;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
return toBuffer(keccak256(this.sortAndConcat(first, second)));
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
getRoot() {
|
|
63
|
-
return this.layers[this.layers.length - 1][0];
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
getHexRoot() {
|
|
67
|
-
return toHex(this.getRoot());
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
getProof(el) {
|
|
71
|
-
let idx = this.bufIndexOf(el, this.elements);
|
|
72
|
-
|
|
73
|
-
if (idx === -1) {
|
|
74
|
-
throw new Error('Element does not exist in Merkle tree');
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
return this.layers.reduce((proof, layer) => {
|
|
78
|
-
const pairElement = this.getPairElement(idx, layer);
|
|
79
|
-
|
|
80
|
-
if (pairElement) {
|
|
81
|
-
proof.push(pairElement);
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
idx = Math.floor(idx / 2);
|
|
85
|
-
|
|
86
|
-
return proof;
|
|
87
|
-
}, []);
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
getHexProof(el) {
|
|
91
|
-
const proof = this.getProof(el);
|
|
92
|
-
return this.bufArrToHexArr(proof);
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
verify(proofs, merkleRoot, leaf) {
|
|
96
|
-
let computedHash = toBuffer(leaf);
|
|
97
|
-
|
|
98
|
-
for (let i = 0; i < proofs.length; i++) {
|
|
99
|
-
const proofElement = toBuffer(proofs[i]);
|
|
100
|
-
computedHash = this.combinedHash(proofElement, computedHash);
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
return toHex(computedHash) === merkleRoot;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
getPairElement(idx, layer) {
|
|
107
|
-
const pairIdx = idx % 2 === 0 ? idx + 1 : idx - 1;
|
|
108
|
-
|
|
109
|
-
if (pairIdx < layer.length) {
|
|
110
|
-
return layer[pairIdx];
|
|
111
|
-
}
|
|
112
|
-
return null;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
bufIndexOf(el, arr) {
|
|
116
|
-
let hash;
|
|
117
|
-
|
|
118
|
-
// Convert element to 32 byte hash if it is not one already
|
|
119
|
-
if (el.length !== 32 || !Buffer.isBuffer(el)) {
|
|
120
|
-
hash = keccakFromString(el);
|
|
121
|
-
} else {
|
|
122
|
-
hash = el;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
for (let i = 0; i < arr.length; i++) {
|
|
126
|
-
if (hash.equals(arr[i])) {
|
|
127
|
-
return i;
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
return -1;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
bufDeduplicate(elements) {
|
|
135
|
-
return elements.filter((el, idx) => idx === 0 || !elements[idx - 1].equals(el));
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
bufArrToHexArr(arr) {
|
|
139
|
-
if (arr.some((el) => !Buffer.isBuffer(el))) {
|
|
140
|
-
throw new Error('Array is not an array of buffers');
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
return arr.map((el) => `0x${el.toString('hex')}`);
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
sortAndConcat(...args) {
|
|
147
|
-
return Buffer.concat([...args].sort(Buffer.compare));
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
module.exports = MerkleTree;
|
|
152
|
-
|
|
153
|
-
module.exports.BLACK_HOLE = '0x0000000000000000000000000000000000000000';
|
|
154
|
-
|
|
155
|
-
module.exports.keccak256 = keccak256;
|
|
156
|
-
module.exports.encodePacked = encodePacked;
|
|
157
|
-
|
|
158
|
-
module.exports.getListHash = (list) =>
|
|
159
|
-
list.length
|
|
160
|
-
? keccak256(
|
|
161
|
-
list
|
|
162
|
-
.map((x) => (x.startsWith('0x') ? x : `0x${x}`))
|
|
163
|
-
.reduce((acc, x) => encodePacked({ type: 'bytes', value: acc }, { type: 'bytes', value: x }), '')
|
|
164
|
-
)
|
|
165
|
-
: '';
|
|
166
|
-
|
|
167
|
-
module.exports.getBlockHash = (block) =>
|
|
168
|
-
block
|
|
169
|
-
? keccak256(
|
|
170
|
-
encodePacked(
|
|
171
|
-
{ type: 'uint256', value: block.height },
|
|
172
|
-
{ type: 'bytes32', value: block.previousHash },
|
|
173
|
-
{ type: 'bytes32', value: block.merkleRoot },
|
|
174
|
-
{ type: 'bytes32', value: block.txsHash }
|
|
175
|
-
)
|
|
176
|
-
)
|
|
177
|
-
: '';
|
|
178
|
-
|
|
179
|
-
module.exports.getBlockMerkleTree = (txs) =>
|
|
180
|
-
txs.length
|
|
181
|
-
? new MerkleTree(
|
|
182
|
-
txs.map((x) =>
|
|
183
|
-
encodePacked(
|
|
184
|
-
{ type: 'bytes32', value: x.hash.startsWith('0x') ? x.hash : `0x${x.hash}` },
|
|
185
|
-
{ type: 'address', value: x.to },
|
|
186
|
-
{ type: 'uint256', value: x.amount }
|
|
187
|
-
)
|
|
188
|
-
)
|
|
189
|
-
)
|
|
190
|
-
: {
|
|
191
|
-
getHexRoot: () => '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
|
|
192
|
-
getHexProof: () => [],
|
|
193
|
-
elements: [],
|
|
194
|
-
layers: [],
|
|
195
|
-
verify: () => false,
|
|
196
|
-
};
|