@totemsdk/txpow 0.1.0

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.
@@ -0,0 +1,86 @@
1
+ /**
2
+ * calibrate.ts — Hash rate measurement and mining cost estimation.
3
+ *
4
+ * calibrateHashRate() measures how many SHA3-256 hashes/sec the current
5
+ * environment can produce. Used by the extension UX to show a warning
6
+ * before starting a mine on slow devices.
7
+ *
8
+ * estimateMiningCost() converts a difficulty target + hash rate into an
9
+ * expected time and confidence label.
10
+ */
11
+
12
+ import { sha3_256 } from '@noble/hashes/sha3.js';
13
+
14
+ export interface MiningEstimate {
15
+ expectedHashes: bigint;
16
+ expectedSeconds: number;
17
+ confidence: 'fast' | 'normal' | 'slow';
18
+ }
19
+
20
+ /**
21
+ * Run 100K trial SHA3-256 hashes and return the measured hash rate (hashes/sec).
22
+ *
23
+ * Call once per session and cache the result — the cost is ~50ms on a
24
+ * typical desktop and ~300ms on a mid-range mobile.
25
+ */
26
+ export async function calibrateHashRate(): Promise<number> {
27
+ const TRIAL_COUNT = 100_000;
28
+ const data = new Uint8Array(150).fill(0xab);
29
+
30
+ const start = typeof performance !== 'undefined'
31
+ ? performance.now()
32
+ : Date.now();
33
+
34
+ for (let i = 0; i < TRIAL_COUNT; i++) {
35
+ sha3_256(data);
36
+ }
37
+
38
+ const elapsed = (typeof performance !== 'undefined' ? performance.now() : Date.now()) - start;
39
+ return Math.round(TRIAL_COUNT / (elapsed / 1000));
40
+ }
41
+
42
+ /**
43
+ * Given a difficulty target and a measured hash rate, return the expected
44
+ * number of hashes, expected wall-clock time, and a confidence label.
45
+ *
46
+ * expectedHashes ≈ MAX_HASH / txnDifficulty
47
+ * (geometric distribution: each hash has P(valid) = txnDifficulty / MAX_HASH)
48
+ *
49
+ * Confidence labels:
50
+ * fast < 2 s
51
+ * normal 2 – 15 s
52
+ * slow > 15 s
53
+ */
54
+ export function estimateMiningCost(
55
+ txnDifficulty: Uint8Array,
56
+ hashRatePerSec: number
57
+ ): MiningEstimate {
58
+ if (hashRatePerSec <= 0) {
59
+ throw new Error('hashRatePerSec must be positive');
60
+ }
61
+
62
+ const diffBigInt = txnDifficulty.reduce(
63
+ (acc, b) => (acc << 8n) | BigInt(b),
64
+ 0n
65
+ );
66
+
67
+ if (diffBigInt === 0n) {
68
+ return { expectedHashes: 0n, expectedSeconds: 0, confidence: 'fast' };
69
+ }
70
+
71
+ const MAX_HASH_BIGINT = (2n ** 256n) - 1n;
72
+ const expectedHashes = MAX_HASH_BIGINT / diffBigInt;
73
+
74
+ const expectedSeconds = Number(expectedHashes) / hashRatePerSec;
75
+
76
+ let confidence: 'fast' | 'normal' | 'slow';
77
+ if (expectedSeconds < 2) {
78
+ confidence = 'fast';
79
+ } else if (expectedSeconds < 15) {
80
+ confidence = 'normal';
81
+ } else {
82
+ confidence = 'slow';
83
+ }
84
+
85
+ return { expectedHashes, expectedSeconds, confidence };
86
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * constants.ts — TxPoW-level constants matching Minima Java protocol values.
3
+ *
4
+ * ZERO_HASH: 32-byte all-zeros — used for MMRRoot, CustomHash, super-parent slot.
5
+ * MAX_HASH: 32-byte all-0xFF — default mBlockDifficulty / mTxnDifficulty for
6
+ * MEG-side-mined paths. Rejected by checkTxPoWSimple() at block level.
7
+ * TX_POW_MIN_DIFFICULTY: Safe transaction difficulty target.
8
+ * ≈ MAX_HASH / 1,000,000 = Magic.getMinTxPowWork() floor.
9
+ * Local-mining paths MUST use a target ≤ this value.
10
+ * MAIN_NET_CHAIN_ID: 1-byte [0x00] — Java MiniData("0x00") = MAIN_NET chain ID.
11
+ * CASCADE_LEVELS: 32 — number of super-parent slots in a fresh TxPoW header.
12
+ */
13
+
14
+ export const CASCADE_LEVELS = 32;
15
+
16
+ export const ZERO_HASH = new Uint8Array(32);
17
+
18
+ export const MAX_HASH: Uint8Array = (() => {
19
+ const b = new Uint8Array(32);
20
+ b.fill(0xff);
21
+ return b;
22
+ })();
23
+
24
+ /**
25
+ * TX_POW_MIN_DIFFICULTY = floor((2^256 - 1) / 1_000_000)
26
+ *
27
+ * This is the hardcoded floor constant matching Magic.getMinTxPowWork().
28
+ * Any locally mined TxPoW must have mTxnDifficulty ≤ this value to pass
29
+ * TxPoWChecker.checkTxPoWSimple() at block inclusion.
30
+ *
31
+ * Computed: (2n**256n - 1n) / 1_000_000n
32
+ * Hex: 0x000010C6F7A0B5ED8538AACDD46595F0C7AC73E0E9DBF12F70000000000000000
33
+ */
34
+ export const TX_POW_MIN_DIFFICULTY: Uint8Array = (() => {
35
+ const maxHashBigInt = (2n ** 256n) - 1n;
36
+ const minDiffBigInt = maxHashBigInt / 1_000_000n;
37
+
38
+ let hex = minDiffBigInt.toString(16);
39
+ if (hex.length % 2 !== 0) hex = '0' + hex;
40
+ while (hex.length < 64) hex = '00' + hex;
41
+
42
+ const bytes = new Uint8Array(32);
43
+ for (let i = 0; i < 32; i++) {
44
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
45
+ }
46
+ return bytes;
47
+ })();
48
+
49
+ export const MAIN_NET_CHAIN_ID = new Uint8Array([0x00]);
@@ -0,0 +1,69 @@
1
+ /**
2
+ * difficulty.ts — Fetch and manage the TxPoW difficulty target.
3
+ *
4
+ * The live value comes from `GET /v1/wallet/txpow-params` on the Axia API.
5
+ * On any error (timeout, network failure, invalid response) we fall back to
6
+ * the hardcoded TX_POW_MIN_DIFFICULTY constant, which is the protocol floor.
7
+ */
8
+
9
+ import { TX_POW_MIN_DIFFICULTY } from './constants.js';
10
+
11
+ export interface TxPowParams {
12
+ minTxPowWork: string;
13
+ }
14
+
15
+ function hexToBytes(hex: string): Uint8Array {
16
+ const h = hex.startsWith('0x') ? hex.slice(2) : hex;
17
+ const out = new Uint8Array(h.length / 2);
18
+ for (let i = 0; i < h.length; i += 2) {
19
+ out[i / 2] = parseInt(h.slice(i, i + 2), 16);
20
+ }
21
+ return out;
22
+ }
23
+
24
+ /**
25
+ * Fetch the current minimum TxPoW work from the Axia API.
26
+ *
27
+ * Falls back to TX_POW_MIN_DIFFICULTY (the hardcoded protocol floor) on any
28
+ * error: network failure, timeout, or malformed response.
29
+ *
30
+ * @param axiaBaseUrl Base URL of the Axia API, e.g. "https://api.axia.to"
31
+ * @param timeoutMs Request timeout in ms (default: 3000)
32
+ */
33
+ export async function fetchTxPowTarget(
34
+ axiaBaseUrl: string,
35
+ timeoutMs = 3000
36
+ ): Promise<Uint8Array> {
37
+ try {
38
+ const base = axiaBaseUrl.replace(/\/$/, '');
39
+ const url = `${base}/v1/wallet/txpow-params`;
40
+
41
+ const controller = new AbortController();
42
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
43
+
44
+ let response: Response;
45
+ try {
46
+ response = await fetch(url, { signal: controller.signal });
47
+ } finally {
48
+ clearTimeout(timer);
49
+ }
50
+
51
+ if (!response.ok) {
52
+ throw new Error(`HTTP ${response.status}`);
53
+ }
54
+
55
+ const data = (await response.json()) as TxPowParams;
56
+ if (typeof data.minTxPowWork !== 'string') {
57
+ throw new Error('Missing minTxPowWork field');
58
+ }
59
+
60
+ const clean = data.minTxPowWork.replace('0x', '').replace(/\s/g, '');
61
+ if (clean.length !== 64) {
62
+ throw new Error(`Invalid minTxPowWork length: ${clean.length} (expected 64 hex chars)`);
63
+ }
64
+
65
+ return hexToBytes(clean);
66
+ } catch {
67
+ return new Uint8Array(TX_POW_MIN_DIFFICULTY);
68
+ }
69
+ }
package/src/index.ts ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @totemsdk/txpow
3
+ *
4
+ * TxPoW envelope serialization and proof-of-work mining for the Minima protocol.
5
+ *
6
+ * USAGE — MEG-side mining (byte-identical to extension current behaviour):
7
+ * const txpow = serializeTxPoW(txBytes, witnessBytes);
8
+ * // Submit to Axia: node re-mines with correct difficulty
9
+ *
10
+ * USAGE — Local mining:
11
+ * const target = await fetchTxPowTarget(axiaBaseUrl);
12
+ * const txBody = serializeTxBody(txBytes, witnessBytes, { txnDifficulty: target });
13
+ * const result = await mineTxPoW(txBody, target);
14
+ * const txpow = concat(result.minedHeaderBytes, new Uint8Array([0x01]), txBody);
15
+ *
16
+ * USAGE — Verify (relay nodes):
17
+ * const check = verifyProofOfWork(txpowId, mTxnDifficulty);
18
+ * if (!check.valid) drop(check.reason);
19
+ */
20
+
21
+ export {
22
+ serializeTxHeader,
23
+ serializeTxBody,
24
+ serializeTxPoW,
25
+ computeTxPoWId,
26
+ type TxHeaderOptions,
27
+ type TxBodyOptions,
28
+ type TxPoWOptions,
29
+ } from './serialization.js';
30
+
31
+ export {
32
+ MAX_HASH,
33
+ ZERO_HASH,
34
+ TX_POW_MIN_DIFFICULTY,
35
+ CASCADE_LEVELS,
36
+ MAIN_NET_CHAIN_ID,
37
+ } from './constants.js';
38
+
39
+ export { serializeMagic } from './magic.js';
40
+
41
+ export {
42
+ mineTxPoW,
43
+ isLessThan,
44
+ type MineResult,
45
+ type MineOptions,
46
+ } from './mine.js';
47
+
48
+ export { fetchTxPowTarget, type TxPowParams } from './difficulty.js';
49
+
50
+ export { verifyProofOfWork, type VerifyResult } from './verify.js';
51
+
52
+ export {
53
+ calibrateHashRate,
54
+ estimateMiningCost,
55
+ type MiningEstimate,
56
+ } from './calibrate.js';
package/src/magic.ts ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * magic.ts — Serialize the Minima Magic struct.
3
+ *
4
+ * Ported from the extension's MinimaTransactionBuilder.ts::serializeMagic().
5
+ * Matches Magic.writeDataStream() in Java exactly.
6
+ *
7
+ * Magic contains two copies of 4 fields (current + desired parameters):
8
+ * maxTxPoWSize (MiniNumber)
9
+ * maxKISSVMOps (MiniNumber)
10
+ * maxTxnPerBlock(MiniNumber)
11
+ * minTxPoWWork (MiniData — 32 bytes)
12
+ *
13
+ * Default values from Magic.java:
14
+ * maxTxPoWSize = 65536
15
+ * maxKISSVMOps = 1024
16
+ * maxTxnPerBlock = 256
17
+ * minTxPoWWork = MAX_HASH (all 0xFF, 32 bytes) — placeholder in fresh TxPoW
18
+ */
19
+
20
+ import { writeMiniNumber, writeMiniData, concat } from '@totemsdk/core';
21
+ import { MAX_HASH } from './constants.js';
22
+
23
+ export function serializeMagic(): Uint8Array {
24
+ const parts: Uint8Array[] = [];
25
+
26
+ parts.push(writeMiniNumber(65536n));
27
+ parts.push(writeMiniNumber(1024n));
28
+ parts.push(writeMiniNumber(256n));
29
+ parts.push(writeMiniData(MAX_HASH));
30
+
31
+ parts.push(writeMiniNumber(65536n));
32
+ parts.push(writeMiniNumber(1024n));
33
+ parts.push(writeMiniNumber(256n));
34
+ parts.push(writeMiniData(MAX_HASH));
35
+
36
+ return concat(...parts);
37
+ }
package/src/mine.ts ADDED
@@ -0,0 +1,212 @@
1
+ /**
2
+ * mine.ts — Local TxPoW proof-of-work mining loop.
3
+ *
4
+ * Algorithm (from TxPoWChecker.java):
5
+ * txpowId = SHA3-256( serialize(TxHeader) )
6
+ * valid = txpowId < mTxnDifficulty (big-endian 256-bit comparison)
7
+ *
8
+ * Strategy:
9
+ * 1. The TxBody is fixed during mining — only mNonce in the header changes.
10
+ * 2. We precompute the "header tail" (everything after mNonce) once per mine.
11
+ * 3. Within each chunk (fixed nonce encoding length), we update only the nonce
12
+ * value bytes in place — no per-iteration allocation.
13
+ * 4. At each MiniNumber encoding boundary (nonce 128, 32768, 8388608, …) we
14
+ * re-allocate a new header buffer with the wider nonce field.
15
+ * 5. Between chunks we yield to the event loop so the caller thread isn't blocked.
16
+ */
17
+
18
+ import { sha3_256 } from '@noble/hashes/sha3.js';
19
+ import {
20
+ writeMiniNumber,
21
+ writeMiniData,
22
+ writeHashToStream,
23
+ concat,
24
+ } from '@totemsdk/core';
25
+ import { serializeMagic } from './magic.js';
26
+ import { MAX_HASH, ZERO_HASH, CASCADE_LEVELS, MAIN_NET_CHAIN_ID } from './constants.js';
27
+
28
+ // ─────────────────────────────────────────────────────────────────────────────
29
+ // Public types
30
+ // ─────────────────────────────────────────────────────────────────────────────
31
+
32
+ export interface MineResult {
33
+ /** Fully serialized TxHeader bytes with the winning nonce. */
34
+ minedHeaderBytes: Uint8Array;
35
+ /** SHA3-256(minedHeaderBytes) — the canonical TxPoW ID. */
36
+ txpowId: Uint8Array;
37
+ nonce: bigint;
38
+ elapsedMs: number;
39
+ /** 'wasm' when the WASM binary is present; 'js' otherwise. */
40
+ source: 'wasm' | 'js';
41
+ }
42
+
43
+ export interface MineOptions {
44
+ /**
45
+ * Hash iterations per async yield (default: 10_000).
46
+ * Lower = more responsive UI; higher = slightly faster mining.
47
+ */
48
+ chunkSize?: number;
49
+ /**
50
+ * Hard cap on total iterations (default: unlimited).
51
+ * Throws if exhausted without finding a valid nonce.
52
+ */
53
+ maxIterations?: number;
54
+ /** AbortSignal — rejects the Promise when aborted. */
55
+ signal?: AbortSignal;
56
+ }
57
+
58
+ // ─────────────────────────────────────────────────────────────────────────────
59
+ // Internal helpers
60
+ // ─────────────────────────────────────────────────────────────────────────────
61
+
62
+ /**
63
+ * Big-endian 256-bit comparison: true if a < b.
64
+ * Used to check: txpowId < mTxnDifficulty.
65
+ */
66
+ export function isLessThan(a: Uint8Array, b: Uint8Array): boolean {
67
+ for (let i = 0; i < 32; i++) {
68
+ if (a[i] < b[i]) return true;
69
+ if (a[i] > b[i]) return false;
70
+ }
71
+ return false;
72
+ }
73
+
74
+ /**
75
+ * Returns the first nonce value that would require more bytes in its
76
+ * MiniNumber encoding (i.e. the next boundary at 128, 32768, 8388608, …).
77
+ *
78
+ * Pattern: bigIntToByteArray(n) grows by 1 byte at 2^(8k−1) for k=1,2,3,…
79
+ * k=1: 2^7 = 128
80
+ * k=2: 2^15 = 32768
81
+ * k=3: 2^23 = 8388608
82
+ */
83
+ function nextNonceBoundary(nonce: bigint): bigint {
84
+ const nonceValueLen = writeMiniNumber(nonce).length - 2;
85
+ return 2n ** BigInt(8 * nonceValueLen - 1);
86
+ }
87
+
88
+ /**
89
+ * Build the "header tail" — the part of TxHeader that follows mNonce.
90
+ *
91
+ * This is computed once at the start of a mine and never changes during it.
92
+ */
93
+ function buildHeaderTail(txBodyHash: Uint8Array, timeMilli: bigint): Uint8Array {
94
+ return concat(
95
+ writeMiniData(MAIN_NET_CHAIN_ID),
96
+ writeMiniNumber(timeMilli),
97
+ writeMiniNumber(0n),
98
+ writeMiniData(MAX_HASH),
99
+ new Uint8Array([CASCADE_LEVELS]),
100
+ writeHashToStream(ZERO_HASH),
101
+ writeHashToStream(ZERO_HASH),
102
+ writeMiniNumber(0n),
103
+ serializeMagic(),
104
+ writeHashToStream(ZERO_HASH),
105
+ writeHashToStream(txBodyHash)
106
+ );
107
+ }
108
+
109
+ /**
110
+ * Synchronously mine a chunk of nonces within a fixed encoding boundary.
111
+ *
112
+ * Mutates headerBuf in place — only the nonce value bytes at offset 2 change.
113
+ * Returns the found nonce, or null if not found in this chunk.
114
+ */
115
+ function mineChunk(
116
+ headerBuf: Uint8Array,
117
+ nonceValueLen: number,
118
+ target: Uint8Array,
119
+ startNonce: bigint,
120
+ endNonce: bigint
121
+ ): bigint | null {
122
+ const nonceValueOffset = 2;
123
+
124
+ for (let nonce = startNonce; nonce < endNonce; nonce++) {
125
+ let n = nonce;
126
+ for (let i = nonceValueLen - 1; i >= 0; i--) {
127
+ headerBuf[nonceValueOffset + i] = Number(n & 0xffn);
128
+ n >>= 8n;
129
+ }
130
+ const hash = sha3_256(headerBuf);
131
+ if (isLessThan(hash, target)) return nonce;
132
+ }
133
+ return null;
134
+ }
135
+
136
+ // ─────────────────────────────────────────────────────────────────────────────
137
+ // Public API
138
+ // ─────────────────────────────────────────────────────────────────────────────
139
+
140
+ /**
141
+ * Mine a TxPoW locally by iterating the header nonce until
142
+ * SHA3-256( TxHeader ) < txnDifficulty
143
+ *
144
+ * @param txBodyBytes Pre-serialized TxBody bytes (from serializeTxBody).
145
+ * @param txnDifficulty 32-byte target. MUST be ≤ TX_POW_MIN_DIFFICULTY.
146
+ * Passing MAX_HASH here will loop forever and be rejected
147
+ * at block level by TxPoWChecker.checkTxPoWSimple().
148
+ * @param options Chunk size, max iterations, abort signal.
149
+ */
150
+ export async function mineTxPoW(
151
+ txBodyBytes: Uint8Array,
152
+ txnDifficulty: Uint8Array,
153
+ options?: MineOptions
154
+ ): Promise<MineResult> {
155
+ const chunkSize = BigInt(options?.chunkSize ?? 10_000);
156
+ const maxIterations = options?.maxIterations !== undefined
157
+ ? BigInt(options.maxIterations)
158
+ : undefined;
159
+ const signal = options?.signal;
160
+
161
+ const bodyHash = sha3_256(txBodyBytes);
162
+ const timeMilli = BigInt(Date.now());
163
+ const headerTail = buildHeaderTail(bodyHash, timeMilli);
164
+
165
+ const startTime = Date.now();
166
+ let totalIterations = 0n;
167
+ let nonce = 0n;
168
+
169
+ while (true) {
170
+ if (signal?.aborted) {
171
+ throw new DOMException('Mining aborted', 'AbortError');
172
+ }
173
+ if (maxIterations !== undefined && totalIterations >= maxIterations) {
174
+ throw new Error(
175
+ `Mining exhausted: ${totalIterations} iterations without finding a valid nonce`
176
+ );
177
+ }
178
+
179
+ const boundary = nextNonceBoundary(nonce);
180
+ const chunkEnd = nonce + chunkSize < boundary ? nonce + chunkSize : boundary;
181
+
182
+ const nonceBytes = writeMiniNumber(nonce);
183
+ const nonceValueLen = nonceBytes.length - 2;
184
+ const headerBuf = concat(nonceBytes, headerTail);
185
+
186
+ const found = mineChunk(headerBuf, nonceValueLen, txnDifficulty, nonce, chunkEnd);
187
+
188
+ if (found !== null) {
189
+ const finalNonceBytes = writeMiniNumber(found);
190
+ const finalHeader = concat(finalNonceBytes, headerTail);
191
+ const txpowId = sha3_256(finalHeader);
192
+ return {
193
+ minedHeaderBytes: finalHeader,
194
+ txpowId,
195
+ nonce: found,
196
+ elapsedMs: Date.now() - startTime,
197
+ source: 'js',
198
+ };
199
+ }
200
+
201
+ totalIterations += chunkEnd - nonce;
202
+ nonce = chunkEnd;
203
+
204
+ await new Promise<void>(resolve => {
205
+ if (typeof setImmediate !== 'undefined') {
206
+ setImmediate(resolve);
207
+ } else {
208
+ setTimeout(resolve, 0);
209
+ }
210
+ });
211
+ }
212
+ }