@totemsdk/core 1.2.11 → 1.4.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.
Files changed (56) hide show
  1. package/README.md +58 -0
  2. package/dist/address-derivation.d.ts +36 -0
  3. package/dist/address-derivation.js +54 -0
  4. package/dist/bip39.js +1 -1
  5. package/dist/bytes.d.ts +11 -0
  6. package/dist/bytes.js +39 -0
  7. package/dist/canonical-hash.d.ts +1 -0
  8. package/dist/canonical-hash.js +12 -0
  9. package/dist/canonical.d.ts +6 -1
  10. package/dist/canonical.js +6 -5
  11. package/dist/cjs/address-derivation.d.ts +36 -0
  12. package/dist/cjs/address-derivation.js +60 -0
  13. package/dist/cjs/bytes.d.ts +11 -0
  14. package/dist/cjs/bytes.js +44 -0
  15. package/dist/cjs/canonical-hash.d.ts +1 -0
  16. package/dist/cjs/canonical-hash.js +15 -0
  17. package/dist/cjs/canonical.d.ts +6 -1
  18. package/dist/cjs/canonical.js +6 -6
  19. package/dist/cjs/index.d.ts +5 -2
  20. package/dist/cjs/index.js +60 -50
  21. package/dist/cjs/legacy.d.ts +15 -6
  22. package/dist/cjs/legacy.js +15 -6
  23. package/dist/cjs/mmr.d.ts +22 -0
  24. package/dist/cjs/mmr.js +33 -0
  25. package/dist/cjs/scripts/canonical.d.ts +20 -0
  26. package/dist/cjs/scripts/canonical.js +99 -0
  27. package/dist/cjs/scripts/contract-helpers.js +3 -3
  28. package/dist/cjs/scripts/index.d.ts +2 -1
  29. package/dist/cjs/scripts/index.js +4 -1
  30. package/dist/cjs/scripts/witness-serializer.d.ts +19 -0
  31. package/dist/cjs/scripts/witness-serializer.js +25 -5
  32. package/dist/cjs/wasm-sync.d.ts +3 -3
  33. package/dist/cjs/wasm-sync.js +10 -3
  34. package/dist/index.d.ts +5 -2
  35. package/dist/index.js +16 -11
  36. package/dist/javaStreamables.js +1 -1
  37. package/dist/legacy.d.ts +15 -6
  38. package/dist/legacy.js +15 -6
  39. package/dist/minima32.js +1 -1
  40. package/dist/mmr.d.ts +22 -0
  41. package/dist/mmr.js +34 -2
  42. package/dist/scripts/canonical.d.ts +20 -0
  43. package/dist/scripts/canonical.js +96 -0
  44. package/dist/scripts/contract-helpers.js +4 -4
  45. package/dist/scripts/index.d.ts +2 -1
  46. package/dist/scripts/index.js +2 -1
  47. package/dist/scripts/witness-serializer.d.ts +19 -0
  48. package/dist/scripts/witness-serializer.js +25 -6
  49. package/dist/transaction.js +1 -1
  50. package/dist/verify.js +1 -1
  51. package/dist/wasm-async.d.ts +81 -0
  52. package/dist/wasm-async.js +91 -0
  53. package/dist/wasm-sync.d.ts +3 -3
  54. package/dist/wasm-sync.js +7 -2
  55. package/dist/wots.js +1 -1
  56. package/package.json +47 -3
@@ -10,8 +10,10 @@
10
10
  * const sig = wotsSign(seed, 0, message); // synchronous!
11
11
  */
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.wasmTreeKeyFree = exports.wasmTreeKeyGetMaxUses = exports.wasmTreeKeySetUses = exports.wasmTreeKeyGetUses = exports.wasmTreeKeyGetPublicKey = exports.wasmTreeKeySign = exports.wasmTreeKeyNew = exports.mineTxPoWChunk = exports.mineTxPoW = exports.deriveFullPublicKeyBatch = exports.derivePKdigestBatch = exports.wotsSignBatch = exports.getParams = exports.verifyMMRProof = exports.mmrRootFromPublicKeys = exports.deriveUnifiedAddressPublicKey = exports.createUnifiedRootTreeKey = exports.createUnifiedChildTreeKey = exports.writeMiniString = exports.writeMiniData = exports.validateChallenge = exports.createChallenge = exports.timingSafeEqual = exports.verifyTreeSignature = exports.precomputeTransactionCoinID = exports.computeTransactionDigest = exports.serializeTransaction = exports.parseMxAddress = exports.makeMxAddress = exports.cleanSeedPhrase = exports.validatePhrase = exports.generateWordList = exports.phraseToSeed = exports.deriveRootPrivSeed = exports.derivePerAddressSeed = exports.deriveChainSeedJava = exports.wotsPublicKeyFromSeed = exports.wotsPkFromSig = exports.wotsVerifyDigest = exports.wotsVerify = exports.wotsSign = exports.deriveFullPublicKey = exports.derivePKdigest = exports.hashChain = exports.expandPrivateKey = exports.sha3_256 = exports.concatBytes = exports.hexToBytes = exports.bytesToHex = void 0;
13
+ exports.wasmTreeKeyFree = exports.wasmTreeKeyGetMaxUses = exports.wasmTreeKeySetUses = exports.wasmTreeKeyGetUses = exports.wasmTreeKeyGetPublicKey = exports.wasmTreeKeySign = exports.wasmTreeKeyNew = exports.mineTxPoWChunk = exports.mineTxPoW = exports.deriveFullPublicKeyBatch = exports.derivePKdigestBatch = exports.wotsSignBatch = exports.getParams = exports.verifyMMRProof = exports.mmrRootFromPublicKeys = exports.deriveUnifiedAddressPublicKey = exports.createUnifiedRootTreeKey = exports.createUnifiedChildTreeKey = exports.writeMiniString = exports.writeMiniData = exports.timingSafeEqual = exports.verifyTreeSignature = exports.precomputeTransactionCoinID = exports.computeTransactionDigest = exports.serializeTransaction = exports.parseMxAddress = exports.makeMxAddress = exports.cleanSeedPhrase = exports.validatePhrase = exports.generateWordList = exports.phraseToSeed = exports.deriveRootPrivSeed = exports.derivePerAddressSeed = exports.deriveChainSeedJava = exports.wotsPublicKeyFromSeed = exports.wotsPkFromSig = exports.wotsVerifyDigest = exports.wotsVerify = exports.wotsSign = exports.deriveFullPublicKey = exports.derivePKdigest = exports.hashChain = exports.expandPrivateKey = exports.sha3_256 = exports.concatBytes = exports.hexToBytes = exports.bytesToHex = void 0;
14
14
  exports.wotsAddressFromKeypair = wotsAddressFromKeypair;
15
+ exports.createChallenge = createChallenge;
16
+ exports.validateChallenge = validateChallenge;
15
17
  exports.writeMiniNumber = writeMiniNumber;
16
18
  exports.wotsKeypairFromSeed = wotsKeypairFromSeed;
17
19
  // The bundler target initializes WASM synchronously at import time.
@@ -55,8 +57,13 @@ exports.computeTransactionDigest = core_wasm_1.compute_transaction_digest_wasm;
55
57
  exports.precomputeTransactionCoinID = core_wasm_1.precompute_transaction_coin_id_wasm;
56
58
  exports.verifyTreeSignature = core_wasm_1.verify_tree_signature_wasm;
57
59
  exports.timingSafeEqual = core_wasm_1.timing_safe_equal_wasm;
58
- exports.createChallenge = core_wasm_1.create_challenge_wasm;
59
- exports.validateChallenge = core_wasm_1.validate_challenge_wasm;
60
+ // SystemTime panics on wasm32-unknown-unknown; supply the clock from JS.
61
+ function createChallenge(domain, statement) {
62
+ return (0, core_wasm_1.create_challenge_wasm)(domain, statement, Math.floor(Date.now() / 1000));
63
+ }
64
+ function validateChallenge(challengeJson, domain) {
65
+ return (0, core_wasm_1.validate_challenge_wasm)(challengeJson, domain, Math.floor(Date.now() / 1000));
66
+ }
60
67
  function writeMiniNumber(value, scale = 0) {
61
68
  return (0, core_wasm_1.write_mini_number_wasm)(value.toString(), scale);
62
69
  }
package/dist/index.d.ts CHANGED
@@ -10,7 +10,7 @@ export * from './adapters/index.js';
10
10
  export { LeaseStore, WatermarkStore, LeaseMonitor, prepareLease, finalizeLease, flatIndexFromLanes, type StoredLease, type LeaseStatus, type LeaseStoreConfig, type LeaseWotsIndices, type WatermarkState, type SyncResult, type WatermarkStoreConfig, type LeaseExpiryEvent, type LeaseExpiryCallback, type LeaseMonitorConfig, type PrepareArgs, type PrepareResp, } from './lease/index.js';
11
11
  export { TransactionService, TransactionLifecycle, TransactionLifecycleError, WatermarkExhaustedError, TransactionReceiptStore, type TransactionServiceConfig, type WotsSigningDependencies, type TransactionLifecycleConfig, type WatermarkSyncFunction, type PrepareResult, type TransactionReceiptStoreConfig, type PrepareRequest, type PrepareResponse, type SignRequest, type SignResult, type HierarchicalWitnessBundle, type WitnessBundle, type FinalizeRequest, type FinalizeResponse, type TransactionMetadata, type TransactionReceipt, type TransactionError, } from './tx/index.js';
12
12
  export type { WotsIndices } from './tx/index.js';
13
- export { bytesToHex, hexToBytes, concatBytes } from './wasm-sync.js';
13
+ export { bytesToHex, hexToBytes, concatBytes } from './bytes.js';
14
14
  export { sha3_256 } from './wasm-sync.js';
15
15
  export { expandPrivateKey, hashChain, derivePKdigest, deriveFullPublicKey, wotsSign, wotsVerify, wotsVerifyDigest, wotsPkFromSig, wotsPublicKeyFromSeed, wotsKeypairFromSeed, } from './wasm-sync.js';
16
16
  export * from './params.js';
@@ -28,17 +28,20 @@ export { makeMxAddress as encodeMx, parseMxAddress as decodeMx } from './wasm-sy
28
28
  export declare function mxToHex(address: string): string;
29
29
  export * from './mmr.js';
30
30
  export * from './scripts/index.js';
31
+ export { toNodeScript } from './scripts/canonical.js';
31
32
  export { scriptToAddress, addressToRoot } from './derive.js';
32
33
  export { WORD_LIST, convertStringToSeed, convertWordListToSeed, generateSeedPhrase, } from './bip39.js';
33
34
  export { MiniNumber } from './MiniNumber.js';
34
35
  export { type MinimaTransaction, type MinimaCoin, type ParsedMiniNumber, type MinimaToken, type StateVariable, type RawStateVariable, type CoinProofData, type SpendableCoinInput, type TransactionBuildResult, parseDecimalToMiniNumber, serializeCoin, serializeTransaction as serializeTransactionObject, computeTokenId, serializeTokenDescriptor, createDefaultTransaction, buildMinimaCoin, } from './transaction.js';
35
36
  export { verifySignature, verifySignatureDetailed, verifyTreeSignatureDetailed, deriveAddressFromPublicKey, normalizeHex, type VerificationResult, } from './verify.js';
37
+ export { deriveDeterministicAddress, deriveUnifiedAddress, deriveAddress, verifyDeterministicAddress, type AddressScheme, type DerivedAddress, } from './address-derivation.js';
36
38
  export { writeMiniByte, writeMMREntryNumber, writeSignature, writeSignatureProof, concat, bigIntToByteArray, type Bytes, } from './Streamable.js';
37
39
  export { serializeMiniNumber, serializeMiniData, hashAllObjects, deriveChildTreeSeedJava, hashObject, serializeMiniNumberZERO, serializeMiniNumberONE, writeHashToStream, javaHashAllObjects, indexToMiniDataBytes, deriveUnifiedChildSeed, createMMREntryNumber, serializeMMREntryNumber, serializeMMRData, serializeMMREntry, type MMREntryNumber as JavaMMREntryNumber, type MMRData as JavaMMRData, type MMREntry as JavaMMREntry, } from './javaStreamables.js';
38
40
  export { TreeKey, TreeKeyNode, serializeTreeSignature, deserializeTreeSignature, getRootPublicKey, DEFAULT_KEYS_PER_LEVEL, DEFAULT_LEVELS, createUnifiedChildTreeKeyAsync, createPerAddressTreeKey, createPerAddressTreeKeyAsync, setTreeKeyLogger, disableTreeKeyLogger, type KeyGenProgress, type ProgressCallback, type SignatureProof, type TreeSignature, } from './treekey.js';
39
41
  export type { WotsKeypair, WotsSignature } from './wots.js';
40
42
  export { F, hex, fromHex, setWotsLogger, disableWotsLogger, u16be, u32be, assert32, h, prfChainSeed, toWinternitzDigits, baseWWithChecksum, wotsSignLegacy, } from './wots.js';
41
- export { toHex, canonicalJson, hashCanonical } from './canonical.js';
43
+ export { toHex, canonicalJson } from './canonical.js';
44
+ export { hashCanonical } from './canonical-hash.js';
42
45
  export { utf8ToBytes, bytesToUtf8 } from './utils.js';
43
46
  export declare const MINIMA_CONSTANTS: {
44
47
  readonly WOTS_W: 8;
package/dist/index.js CHANGED
@@ -17,23 +17,24 @@ export { TransactionService, TransactionLifecycle, TransactionLifecycleError, Wa
17
17
  // Cryptographic primitives — backed by Rust/WASM (@totemsdk/core-wasm)
18
18
  // ---------------------------------------------------------------------------
19
19
  // Utilities
20
- export { bytesToHex, hexToBytes, concatBytes } from './wasm-sync.js';
21
- import { bytesToHex, parseMxAddress } from './wasm-sync.js';
20
+ export { bytesToHex, hexToBytes, concatBytes } from './bytes.js';
21
+ import { bytesToHex } from './bytes.js';
22
+ import { parseMxAddress } from './wasm-async.js';
22
23
  // SHA3-256
23
- export { sha3_256 } from './wasm-sync.js';
24
+ export { sha3_256 } from './wasm-async.js';
24
25
  // WOTS Signatures
25
- export { expandPrivateKey, hashChain, derivePKdigest, deriveFullPublicKey, wotsSign, wotsVerify, wotsVerifyDigest, wotsPkFromSig, wotsPublicKeyFromSeed, wotsKeypairFromSeed, } from './wasm-sync.js';
26
+ export { expandPrivateKey, hashChain, derivePKdigest, deriveFullPublicKey, wotsSign, wotsVerify, wotsVerifyDigest, wotsPkFromSig, wotsPublicKeyFromSeed, wotsKeypairFromSeed, } from './wasm-async.js';
26
27
  // WOTS Params (from params.ts — constants, no crypto)
27
28
  export * from './params.js';
28
29
  // Java-Compatible Serialization
29
- export { deriveChainSeedJava, derivePerAddressSeed, deriveRootPrivSeed, writeMiniNumber, writeMiniData, writeMiniString, precomputeTransactionCoinID, } from './wasm-sync.js';
30
+ export { deriveChainSeedJava, derivePerAddressSeed, deriveRootPrivSeed, writeMiniNumber, writeMiniData, writeMiniString, precomputeTransactionCoinID, } from './wasm-async.js';
30
31
  // TreeKey/TreeKeyNode — WASM-backed
31
32
  // createUnifiedChildTreeKey / createUnifiedRootTreeKey come from the TS
32
33
  // implementation (returning a full TreeKey object with setUses/sign/getPublicKey)
33
34
  // to match the object API that downstream consumers (server, root-identity)
34
35
  // rely on. The WASM binding only returns the root public key bytes.
35
36
  export { createUnifiedChildTreeKey, createUnifiedRootTreeKey, deriveUnifiedAddressPublicKey, verifyTreeSignature, } from './treekey.js';
36
- export { mmrRootFromPublicKeys, verifyMMRProof, } from './wasm-sync.js';
37
+ export { mmrRootFromPublicKeys, verifyMMRProof, } from './wasm-async.js';
37
38
  // BIP39 Seed Phrase Handling
38
39
  // The WASM binding (wasm-sync.ts) shares the canonical 2048-word BIP39 list
39
40
  // and Minima-compatible uppercase canonicalization with the TS implementation
@@ -42,20 +43,20 @@ export { mmrRootFromPublicKeys, verifyMMRProof, } from './wasm-sync.js';
42
43
  // canonical source of truth and avoids double-entering the list.
43
44
  export { phraseToSeed, generateWordList, validatePhrase, cleanSeedPhrase, } from './bip39.js';
44
45
  // Address Derivation
45
- export { makeMxAddress, parseMxAddress, wotsAddressFromKeypair, } from './wasm-sync.js';
46
+ export { makeMxAddress, parseMxAddress, wotsAddressFromKeypair, } from './wasm-async.js';
46
47
  // Transaction Serialization & Digest
47
- export { serializeTransaction, computeTransactionDigest, } from './wasm-sync.js';
48
+ export { serializeTransaction, computeTransactionDigest, } from './wasm-async.js';
48
49
  // Transaction deserialization (byte-exact inverse of the TS serializer)
49
50
  export { deserializeTransaction } from './transaction.js';
50
51
  // Verification
51
- export { timingSafeEqual, createChallenge, validateChallenge, } from './wasm-sync.js';
52
+ export { timingSafeEqual, createChallenge, validateChallenge, } from './wasm-async.js';
52
53
  // ---------------------------------------------------------------------------
53
54
  // TypeScript-only modules (no crypto — keep as-is)
54
55
  // ---------------------------------------------------------------------------
55
56
  // Script helpers (for address derivation)
56
57
  export { scriptFromWotsPk } from './script.js';
57
58
  // Base32 Encoding (Minima-compatible) — re-export from WASM
58
- export { makeMxAddress as encodeMx, parseMxAddress as decodeMx } from './wasm-sync.js';
59
+ export { makeMxAddress as encodeMx, parseMxAddress as decodeMx } from './wasm-async.js';
59
60
  /** Convert an Mx (radix-32) or hex Minima address to lowercase hex. */
60
61
  export function mxToHex(address) {
61
62
  const upper = address.startsWith('0x') || address.startsWith('0X') ? address.slice(2) : address;
@@ -67,6 +68,7 @@ export function mxToHex(address) {
67
68
  export * from './mmr.js';
68
69
  // Script Types, Witness Serializer, Contract Helpers
69
70
  export * from './scripts/index.js';
71
+ export { toNodeScript } from './scripts/canonical.js';
70
72
  // Address Derivation (original)
71
73
  export { scriptToAddress, addressToRoot } from './derive.js';
72
74
  // BIP39 — re-export word list and legacy helpers from JS
@@ -77,6 +79,8 @@ export { MiniNumber } from './MiniNumber.js';
77
79
  export { parseDecimalToMiniNumber, serializeCoin, serializeTransaction as serializeTransactionObject, computeTokenId, serializeTokenDescriptor, createDefaultTransaction, buildMinimaCoin, } from './transaction.js';
78
80
  // High-level Verification API (convenience functions for integrators)
79
81
  export { verifySignature, verifySignatureDetailed, verifyTreeSignatureDetailed, deriveAddressFromPublicKey, normalizeHex, } from './verify.js';
82
+ // Deterministic address derivation (CAN-005)
83
+ export { deriveDeterministicAddress, deriveUnifiedAddress, deriveAddress, verifyDeterministicAddress, } from './address-derivation.js';
80
84
  // Streamable primitives (low-level serialization building blocks)
81
85
  export { writeMiniByte, writeMMREntryNumber, writeSignature, writeSignatureProof, concat, bigIntToByteArray, } from './Streamable.js';
82
86
  // Java-Compatible Serialization Helpers (non-crypto)
@@ -85,7 +89,8 @@ export { serializeMiniNumber, serializeMiniData, hashAllObjects, deriveChildTree
85
89
  export { TreeKey, TreeKeyNode, serializeTreeSignature, deserializeTreeSignature, getRootPublicKey, DEFAULT_KEYS_PER_LEVEL, DEFAULT_LEVELS, createUnifiedChildTreeKeyAsync, createPerAddressTreeKey, createPerAddressTreeKeyAsync, setTreeKeyLogger, disableTreeKeyLogger, } from './treekey.js';
86
90
  export { F, hex, fromHex, setWotsLogger, disableWotsLogger, u16be, u32be, assert32, h, prfChainSeed, toWinternitzDigits, baseWWithChecksum, wotsSignLegacy, } from './wots.js';
87
91
  // Canonical helpers (deterministic JSON + hashing)
88
- export { toHex, canonicalJson, hashCanonical } from './canonical.js';
92
+ export { toHex, canonicalJson } from './canonical.js';
93
+ export { hashCanonical } from './canonical-hash.js';
89
94
  // Byte/string utilities
90
95
  export { utf8ToBytes, bytesToUtf8 } from './utils.js';
91
96
  // Constants
@@ -12,7 +12,7 @@
12
12
  * NOTE: This module provides number-based wrappers for backward compatibility.
13
13
  * The canonical implementations are in Streamable.ts which uses bigint for precision.
14
14
  */
15
- import { sha3_256 } from './wasm-sync.js';
15
+ import { sha3_256 } from './wasm-async.js';
16
16
  import { writeMiniNumber as streamableWriteMiniNumber, writeMiniData as streamableWriteMiniData, writeHashToStream as streamableWriteHashToStream, bigIntToByteArray } from './Streamable.js';
17
17
  /**
18
18
  * Serialize a number in MiniNumber format (Java compatible)
package/dist/legacy.d.ts CHANGED
@@ -1,12 +1,21 @@
1
1
  /**
2
- * Legacy JS implementations — backward compatibility.
2
+ * Legacy JS crypto kernels — **deprecated (RFC-031 P4), frozen**.
3
3
  *
4
- * These are the original TypeScript implementations preserved for
5
- * environments where WASM is not available. The main entry point
6
- * (`@totemsdk/core`) now delegates to WASM by default.
4
+ * @deprecated The pure-JS kernels are scheduled for removal (RFC-031 P5). Use
5
+ * the WASM surface instead:
6
+ * - `@totemsdk/core` / `@totemsdk/core/wasm` — synchronous WASM (bundler loader required)
7
+ * - `@totemsdk/core/wasm-async` — async-init WASM (portable to edge/Workers)
7
8
  *
8
- * Import legacy implementations directly:
9
- * import { wotsSign } from '@totemsdk/core/legacy';
9
+ * This entry stays only as a migration bridge for environments that cannot run
10
+ * WASM yet; it is **frozen** (no new kernels are added here) and will be deleted
11
+ * in a major release. Exports are `legacy`-prefixed where they collide with the
12
+ * WASM names (`legacyWotsSign`, …).
13
+ *
14
+ * // before
15
+ * import { legacyWotsSign } from '@totemsdk/core/legacy';
16
+ * // after
17
+ * import { init, wotsSign } from '@totemsdk/core/wasm-async';
18
+ * await init();
10
19
  */
11
20
  export { F, hex, fromHex, u16be, u32be, assert32, h, prfChainSeed, toWinternitzDigits, baseWWithChecksum, derivePKdigest as legacyDerivePKdigest, wotsKeypairFromSeed as legacyWotsKeypairFromSeed, wotsSign as legacyWotsSign, wotsSignLegacy, wotsPkFromSig as legacyWotsPkFromSig, wotsVerify as legacyWotsVerify, wotsVerifyDigest as legacyWotsVerifyDigest, wotsPublicKeyFromSeed as legacyWotsPublicKeyFromSeed, type WotsKeypair, type WotsSignature, } from './wots.js';
12
21
  export { TreeKey, TreeKeyNode, verifyTreeSignature as legacyVerifyTreeSignature, serializeTreeSignature, deserializeTreeSignature, getRootPublicKey, DEFAULT_KEYS_PER_LEVEL, DEFAULT_LEVELS, createUnifiedChildTreeKey as legacyCreateUnifiedChildTreeKey, createUnifiedChildTreeKeyAsync, createUnifiedRootTreeKey as legacyCreateUnifiedRootTreeKey, deriveUnifiedAddressPublicKey as legacyDeriveUnifiedAddressPublicKey, createPerAddressTreeKey, createPerAddressTreeKeyAsync, type KeyGenProgress, type ProgressCallback, type SignatureProof, type TreeSignature, } from './treekey.js';
package/dist/legacy.js CHANGED
@@ -1,12 +1,21 @@
1
1
  /**
2
- * Legacy JS implementations — backward compatibility.
2
+ * Legacy JS crypto kernels — **deprecated (RFC-031 P4), frozen**.
3
3
  *
4
- * These are the original TypeScript implementations preserved for
5
- * environments where WASM is not available. The main entry point
6
- * (`@totemsdk/core`) now delegates to WASM by default.
4
+ * @deprecated The pure-JS kernels are scheduled for removal (RFC-031 P5). Use
5
+ * the WASM surface instead:
6
+ * - `@totemsdk/core` / `@totemsdk/core/wasm` — synchronous WASM (bundler loader required)
7
+ * - `@totemsdk/core/wasm-async` — async-init WASM (portable to edge/Workers)
7
8
  *
8
- * Import legacy implementations directly:
9
- * import { wotsSign } from '@totemsdk/core/legacy';
9
+ * This entry stays only as a migration bridge for environments that cannot run
10
+ * WASM yet; it is **frozen** (no new kernels are added here) and will be deleted
11
+ * in a major release. Exports are `legacy`-prefixed where they collide with the
12
+ * WASM names (`legacyWotsSign`, …).
13
+ *
14
+ * // before
15
+ * import { legacyWotsSign } from '@totemsdk/core/legacy';
16
+ * // after
17
+ * import { init, wotsSign } from '@totemsdk/core/wasm-async';
18
+ * await init();
10
19
  */
11
20
  // WOTS — unique exports
12
21
  export { F, hex, fromHex, u16be, u32be, assert32, h, prfChainSeed, toWinternitzDigits, baseWWithChecksum, derivePKdigest as legacyDerivePKdigest, wotsKeypairFromSeed as legacyWotsKeypairFromSeed, wotsSign as legacyWotsSign, wotsSignLegacy, wotsPkFromSig as legacyWotsPkFromSig, wotsVerify as legacyWotsVerify, wotsVerifyDigest as legacyWotsVerifyDigest, wotsPublicKeyFromSeed as legacyWotsPublicKeyFromSeed, } from './wots.js';
package/dist/minima32.js CHANGED
@@ -39,7 +39,7 @@ export function decodeMxRadix32Frame(mx) {
39
39
  }
40
40
  return bigIntToBytes(x);
41
41
  }
42
- import { sha3_256 as nobleSha3 } from './wasm-sync.js';
42
+ import { sha3_256 as nobleSha3 } from './wasm-async.js';
43
43
  /** Encode raw 32 bytes to Mx address with frame and checksum */
44
44
  export function makeMxAddress(root32) {
45
45
  if (root32.length !== 32) {
package/dist/mmr.d.ts CHANGED
@@ -16,6 +16,28 @@ export type Bytes = Uint8Array;
16
16
  export declare function mmrLeafExact(script: string): Bytes;
17
17
  /** In a single-leaf MMR the root equals the leaf commitment. */
18
18
  export declare function mmrRootFromSingleLeaf(script: string): Bytes;
19
+ /**
20
+ * Build the serialized Minima `ScriptProof` bytes for a single-leaf MMR.
21
+ *
22
+ * Mirrors the node's `ScriptProof(const std::string& zScript)` constructor
23
+ * (org/minima/objects/script_proof.cpp): the script is added as the sole leaf
24
+ * of a fresh MMR with sum value ZERO, so the proof chain is empty and the
25
+ * resulting address is the leaf commitment itself:
26
+ *
27
+ * address = sha3( MiniNumber.ZERO || MiniString(script) || MiniNumber.ZERO )
28
+ * = mmrLeafExact(script)
29
+ *
30
+ * This is exactly how the node derives `Address(script)`, so a witness carrying
31
+ * this proof satisfies `Witness::getScript(input.getAddress())` for every input
32
+ * paying to that script. Without it the node rejects the TxPoW with
33
+ * "Script Missing from TxPoW for address <addr>".
34
+ *
35
+ * Wire format (`ScriptProof::writeDataStream`):
36
+ * MiniString(script) || MMRProof(blockTime = 0, chunks = [])
37
+ *
38
+ * @param script - The Minima (KISSVM) script whose address the proof attests.
39
+ */
40
+ export declare function buildScriptProof(script: string): Bytes;
19
41
  /**
20
42
  * MMRData structure matching Minima's MMRData.java
21
43
  * Contains hash and value (for sum tree functionality)
package/dist/mmr.js CHANGED
@@ -1,9 +1,12 @@
1
1
  // packages/core/src/mmr.ts
2
2
  // Full MMR implementation matching Minima's MMR.java, MMRData.java, and TreeKeyNode.java
3
- import { sha3_256 as nobleSha3 } from './wasm-sync.js';
3
+ import { sha3_256 as nobleSha3 } from './wasm-async.js';
4
4
  import { serializeMiniNumber, serializeMiniData, javaHashAllObjects } from "./javaStreamables.js";
5
5
  // Import canonical wire serialization from Streamable.ts (single source of truth)
6
- import { writeMMRProof } from "./Streamable.js";
6
+ import { writeMMRProof, writeMiniString } from "./Streamable.js";
7
+ // Canonicalise to the exact script the node will receive, so the proof's
8
+ // computed address matches `computeScriptAddress` (which canonicalises too).
9
+ import { toNodeScript } from "./scripts/canonical.js";
7
10
  // Re-export for API compatibility (existing code imports from mmr.ts)
8
11
  // Using a wrapper function for better compatibility with dynamic imports
9
12
  export function serializeMMRProof(proof, blockTime = 0n) {
@@ -69,6 +72,35 @@ export function mmrLeafExact(script) {
69
72
  export function mmrRootFromSingleLeaf(script) {
70
73
  return mmrLeafExact(script);
71
74
  }
75
+ /**
76
+ * Build the serialized Minima `ScriptProof` bytes for a single-leaf MMR.
77
+ *
78
+ * Mirrors the node's `ScriptProof(const std::string& zScript)` constructor
79
+ * (org/minima/objects/script_proof.cpp): the script is added as the sole leaf
80
+ * of a fresh MMR with sum value ZERO, so the proof chain is empty and the
81
+ * resulting address is the leaf commitment itself:
82
+ *
83
+ * address = sha3( MiniNumber.ZERO || MiniString(script) || MiniNumber.ZERO )
84
+ * = mmrLeafExact(script)
85
+ *
86
+ * This is exactly how the node derives `Address(script)`, so a witness carrying
87
+ * this proof satisfies `Witness::getScript(input.getAddress())` for every input
88
+ * paying to that script. Without it the node rejects the TxPoW with
89
+ * "Script Missing from TxPoW for address <addr>".
90
+ *
91
+ * Wire format (`ScriptProof::writeDataStream`):
92
+ * MiniString(script) || MMRProof(blockTime = 0, chunks = [])
93
+ *
94
+ * @param script - The Minima (KISSVM) script whose address the proof attests.
95
+ */
96
+ export function buildScriptProof(script) {
97
+ // The node derives the proof's address as
98
+ // sha3( MiniNumber.ZERO || MiniString(script) || MiniNumber.ZERO )
99
+ // so the script bytes here must be exactly the canonical script whose address
100
+ // was used for the coin (see computeScriptAddress).
101
+ const canonical = toNodeScript(script);
102
+ return concat(writeMiniString(canonical), serializeMMRProof({ chunks: [] }, 0n));
103
+ }
72
104
  /**
73
105
  * Create MMRData leaf node matching Minima's MMRData.CreateMMRDataLeafNode
74
106
  *
@@ -0,0 +1,20 @@
1
+ /**
2
+ * `toNodeScript` — canonicalize a KISSVM script to the syntax the Minima **node**
3
+ * tokenizer accepts (RFC-048 §3.1 L4 finding; audit
4
+ * `docs/audits/kissvm-node-validity-l4-2026-10.md`).
5
+ *
6
+ * The node tokenizer requires:
7
+ * - user variable names `^[a-z]+$` (lowercase letters only — no digits/underscores/uppercase),
8
+ * - hex literals `^0x[0-9a-fA-F]+$` (lowercase `0x` prefix),
9
+ * - arithmetic via the `+` / `-` operators (`ADD`/`SUB` are not node functions).
10
+ *
11
+ * This is a token-level rewrite: commands, functions, operators, globals (`@…`), hex
12
+ * literals, numbers and `[…]` string literals are preserved; only **user identifiers**
13
+ * are rewritten to lowercase letters (with deterministic de-collision), `0X`→`0x`, and
14
+ * `ADD`/`SUB`→`+`/`-`. It is idempotent.
15
+ *
16
+ * Semantics are unchanged: the SDK evaluators normalize `+`→ADD and `-`→SUB (and vice
17
+ * versa), so a canonical script behaves identically to its source.
18
+ */
19
+ /** Canonicalize a KISSVM script to node-accepted syntax. Idempotent. */
20
+ export declare function toNodeScript(script: string): string;
@@ -0,0 +1,96 @@
1
+ /**
2
+ * `toNodeScript` — canonicalize a KISSVM script to the syntax the Minima **node**
3
+ * tokenizer accepts (RFC-048 §3.1 L4 finding; audit
4
+ * `docs/audits/kissvm-node-validity-l4-2026-10.md`).
5
+ *
6
+ * The node tokenizer requires:
7
+ * - user variable names `^[a-z]+$` (lowercase letters only — no digits/underscores/uppercase),
8
+ * - hex literals `^0x[0-9a-fA-F]+$` (lowercase `0x` prefix),
9
+ * - arithmetic via the `+` / `-` operators (`ADD`/`SUB` are not node functions).
10
+ *
11
+ * This is a token-level rewrite: commands, functions, operators, globals (`@…`), hex
12
+ * literals, numbers and `[…]` string literals are preserved; only **user identifiers**
13
+ * are rewritten to lowercase letters (with deterministic de-collision), `0X`→`0x`, and
14
+ * `ADD`/`SUB`→`+`/`-`. It is idempotent.
15
+ *
16
+ * Semantics are unchanged: the SDK evaluators normalize `+`→ADD and `-`→SUB (and vice
17
+ * versa), so a canonical script behaves identically to its source.
18
+ */
19
+ const KEYWORDS = new Set([
20
+ 'LET', 'IF', 'THEN', 'ELSE', 'ELSEIF', 'ENDIF', 'RETURN', 'ASSERT', 'EXEC', 'MAST',
21
+ 'WHILE', 'DO', 'ENDWHILE', 'FOR', 'TO', 'BY', 'ENDFOR', 'FOREACH', 'IN', 'SWITCH',
22
+ 'CASE', 'DEFAULT', 'ENDSWITCH', 'FUNC', 'ENDFUNC', 'TRUE', 'FALSE', 'STORE', 'WITH', 'FUNCTION', 'RETURN',
23
+ ]);
24
+ // Word operators kept as-is (ADD/SUB are handled separately → +/−).
25
+ const OPS = new Set([
26
+ 'GT', 'LT', 'EQ', 'GTE', 'LTE', 'NEQ', 'AND', 'OR', 'XOR', 'NAND', 'NOR', 'NXOR',
27
+ 'NOT', 'NEG', 'MUL', 'DIV', 'MOD', 'LSHIFT', 'RSHIFT', 'BITAND', 'BITOR', 'BITXOR', 'BITNOT',
28
+ ]);
29
+ const FUNCTIONS = new Set([
30
+ 'SHA3', 'SHA2', 'HASH', 'PROOF', 'SIGNEDBY', 'MULTISIG', 'CHECKSIG', 'VERIFYOUT', 'VERIFYIN',
31
+ 'GETOUTADDR', 'GETOUTAMT', 'GETOUTTOK', 'GETOUTKEEPSTATE', 'GETINADDR', 'GETINAMT', 'GETINID',
32
+ 'GETINTOK', 'STATE', 'PREVSTATE', 'SAMESTATE', 'SAMECOINS', 'COINAGE', 'COINDATA', 'NUMBER',
33
+ 'HEX', 'STRING', 'ASCII', 'UTF8', 'BOOL', 'CONCAT', 'LEN', 'REV', 'SUBSET', 'SETLEN',
34
+ 'SUBSTR', 'REPLACE', 'REPLACEFIRST', 'OVERWRITE', 'ABS', 'CEIL', 'FLOOR', 'MAX', 'MIN',
35
+ 'DEC', 'INC', 'SIGDIG', 'POW', 'SQRT', 'BITSET', 'BITGET', 'BITCOUNT', 'ADDRESS', 'EXISTS',
36
+ 'GET', 'SUMINPUTS', 'SUMOUTPUTS', 'CHECKSIG',
37
+ ]);
38
+ function classify(id) {
39
+ const up = id.toUpperCase();
40
+ if (up === 'ADD')
41
+ return { kind: 'keep', out: '+' };
42
+ if (up === 'SUB')
43
+ return { kind: 'keep', out: '-' };
44
+ if (KEYWORDS.has(up) || OPS.has(up) || FUNCTIONS.has(up))
45
+ return { kind: 'keep', out: up };
46
+ return { kind: 'var' };
47
+ }
48
+ /** a, b, …, z, aa, ab, … */
49
+ function letters(n) {
50
+ let s = '';
51
+ n += 1;
52
+ while (n > 0) {
53
+ const r = (n - 1) % 26;
54
+ s = String.fromCharCode(97 + r) + s;
55
+ n = Math.floor((n - 1) / 26);
56
+ }
57
+ return s;
58
+ }
59
+ const TOKEN = /(\[[^\]]*\]|0[xX][0-9a-fA-F]+|@[A-Za-z][A-Za-z0-9]*|[A-Za-z_][A-Za-z0-9_]*)/g;
60
+ /** Canonicalize a KISSVM script to node-accepted syntax. Idempotent. */
61
+ export function toNodeScript(script) {
62
+ // The node tokenizer has no comment syntax; strip `//` line comments.
63
+ script = script.replace(/\/\/[^\n]*/g, '');
64
+ const varMap = new Map();
65
+ const used = new Set();
66
+ // First pass: assign canonical names to user variables (in first-occurrence order).
67
+ let m;
68
+ const re1 = new RegExp(TOKEN.source, 'g');
69
+ while ((m = re1.exec(script))) {
70
+ const tok = m[0];
71
+ if (tok[0] === '[' || tok.startsWith('0x') || tok.startsWith('0X') || tok[0] === '@')
72
+ continue;
73
+ if (classify(tok).kind !== 'var' || varMap.has(tok))
74
+ continue;
75
+ const base = tok.toLowerCase().replace(/[^a-z]/g, '') || 'v';
76
+ let cand = base;
77
+ let i = 0;
78
+ while (used.has(cand))
79
+ cand = base + letters(i++);
80
+ used.add(cand);
81
+ varMap.set(tok, cand);
82
+ }
83
+ // Second pass: rewrite.
84
+ return script.replace(TOKEN, (tok) => {
85
+ if (tok[0] === '[')
86
+ return tok;
87
+ if (tok.startsWith('0x') || tok.startsWith('0X'))
88
+ return '0x' + tok.slice(2);
89
+ if (tok[0] === '@')
90
+ return '@' + tok.slice(1).toUpperCase();
91
+ const c = classify(tok);
92
+ if (c.kind === 'keep')
93
+ return c.out;
94
+ return varMap.get(tok) ?? tok;
95
+ });
96
+ }
@@ -13,10 +13,10 @@
13
13
  * Each helper validates inputs and builds the appropriate ScriptDescriptor
14
14
  * for use with the EnhancedTransactionBuilder.
15
15
  */
16
- import { sha3_256 } from '../wasm-sync.js';
17
- import { createHash, randomBytes } from 'node:crypto';
16
+ import { sha3_256 } from '../wasm-async.js';
17
+ import { sha256 as nobleSha256 } from '@noble/hashes/sha256.js';
18
18
  function sha256(data) {
19
- return new Uint8Array(createHash('sha256').update(data).digest());
19
+ return nobleSha256(data);
20
20
  }
21
21
  import { createTimelockDescriptor, createHTLCDescriptor, createMASTDescriptor, createExchangeDescriptor, createFlashCashDescriptor, createSlowCashDescriptor } from './types.js';
22
22
  function kissHex(hex) {
@@ -79,7 +79,7 @@ export class HTLCHelper {
79
79
  * Generate a random preimage and its hash.
80
80
  */
81
81
  static generateSecret() {
82
- const preimageBytes = randomBytes(32);
82
+ const preimageBytes = globalThis.crypto.getRandomValues(new Uint8Array(32));
83
83
  const preimage = bytesToHex(preimageBytes);
84
84
  const hashBytes = sha3_256(preimageBytes);
85
85
  const hash = bytesToHex(hashBytes);
@@ -1,4 +1,5 @@
1
1
  export * from './types.js';
2
2
  export * from './dapp-types.js';
3
- export { encodeMiniNumber, encodeMiniData, encodeMiniString, serializeMMRProofChunk, serializeScriptProofWithProof, STATETYPE_HEX, STATETYPE_NUMBER, STATETYPE_STRING, STATETYPE_BOOL, encodeStateValue, serializeStateVariables, buildScriptProofFromDescriptor, deduplicateScriptDescriptors, serializeExtraScripts, aggregateSignatures, validateExternalSignature, computeScriptAddress, } from './witness-serializer.js';
3
+ export { encodeMiniNumber, encodeMiniData, encodeMiniString, serializeMMRProofChunk, serializeScriptProofWithProof, STATETYPE_HEX, STATETYPE_NUMBER, STATETYPE_STRING, STATETYPE_BOOL, encodeStateValue, serializeStateVariables, buildScriptProofFromDescriptor, deduplicateScriptDescriptors, serializeExtraScripts, aggregateSignatures, validateExternalSignature, computeScriptAddress, wotsAddressData, } from './witness-serializer.js';
4
4
  export * from './contract-helpers.js';
5
+ export { toNodeScript } from "./canonical.js";
@@ -1,4 +1,5 @@
1
1
  export * from './types.js';
2
2
  export * from './dapp-types.js';
3
- export { encodeMiniNumber, encodeMiniData, encodeMiniString, serializeMMRProofChunk, serializeScriptProofWithProof, STATETYPE_HEX, STATETYPE_NUMBER, STATETYPE_STRING, STATETYPE_BOOL, encodeStateValue, serializeStateVariables, buildScriptProofFromDescriptor, deduplicateScriptDescriptors, serializeExtraScripts, aggregateSignatures, validateExternalSignature, computeScriptAddress, } from './witness-serializer.js';
3
+ export { encodeMiniNumber, encodeMiniData, encodeMiniString, serializeMMRProofChunk, serializeScriptProofWithProof, STATETYPE_HEX, STATETYPE_NUMBER, STATETYPE_STRING, STATETYPE_BOOL, encodeStateValue, serializeStateVariables, buildScriptProofFromDescriptor, deduplicateScriptDescriptors, serializeExtraScripts, aggregateSignatures, validateExternalSignature, computeScriptAddress, wotsAddressData, } from './witness-serializer.js';
4
4
  export * from './contract-helpers.js';
5
+ export { toNodeScript } from "./canonical.js";
@@ -25,5 +25,24 @@ export declare function aggregateSignatures(totemSignature: {
25
25
  signature: Uint8Array;
26
26
  }, externalSignatures: ExternalSignature[], transactionDigest: Uint8Array): Uint8Array[];
27
27
  export declare function validateExternalSignature(signature: ExternalSignature, transactionDigest: Uint8Array): boolean;
28
+ /**
29
+ * Derive a Minima script address exactly as the node does
30
+ * (`Address::Address(script)` / `ScriptProof::calculateAddress`):
31
+ *
32
+ * address = sha3( MiniNumber.ZERO || MiniString(script) || MiniNumber.ZERO )
33
+ *
34
+ * The script is first canonicalised (`toNodeScript`) so the address is over the
35
+ * same bytes the node will execute and that `buildScriptProof` attests. The
36
+ * previous implementation hashed `sha3(upper(script))`, which is not a Minima
37
+ * script address — coins sent to it could never be spent by that script
38
+ * ("Script Missing from TxPoW for address …").
39
+ */
40
+ /**
41
+ * Address data (hex) of a WOTS public-key digest's single-key script
42
+ * (`RETURN SIGNEDBY(0x<pk>)`). This is the value a `VERIFYOUT` compares against
43
+ * (the node compares the output coin's *address data*), distinct from the WOTS
44
+ * public key used by `SIGNEDBY`.
45
+ */
46
+ export declare function wotsAddressData(publicKeyDigest: string): string;
28
47
  export declare function computeScriptAddress(script: string): string;
29
48
  export { concat };
@@ -1,6 +1,6 @@
1
- import { sha3_256 } from '../wasm-sync.js';
1
+ import { toNodeScript } from './canonical.js';
2
2
  import { wotsVerifyDigest } from '../wots.js';
3
- import { serializeMMRProof } from '../mmr.js';
3
+ import { serializeMMRProof, mmrRootFromSingleLeaf } from '../mmr.js';
4
4
  import { mxToHex } from '../minima32.js';
5
5
  function hexToBytes(hex) {
6
6
  const cleanHex = hex.startsWith('0x') ? hex.slice(2) : hex;
@@ -302,10 +302,29 @@ export function validateExternalSignature(signature, transactionDigest) {
302
302
  return false;
303
303
  }
304
304
  }
305
+ /**
306
+ * Derive a Minima script address exactly as the node does
307
+ * (`Address::Address(script)` / `ScriptProof::calculateAddress`):
308
+ *
309
+ * address = sha3( MiniNumber.ZERO || MiniString(script) || MiniNumber.ZERO )
310
+ *
311
+ * The script is first canonicalised (`toNodeScript`) so the address is over the
312
+ * same bytes the node will execute and that `buildScriptProof` attests. The
313
+ * previous implementation hashed `sha3(upper(script))`, which is not a Minima
314
+ * script address — coins sent to it could never be spent by that script
315
+ * ("Script Missing from TxPoW for address …").
316
+ */
317
+ /**
318
+ * Address data (hex) of a WOTS public-key digest's single-key script
319
+ * (`RETURN SIGNEDBY(0x<pk>)`). This is the value a `VERIFYOUT` compares against
320
+ * (the node compares the output coin's *address data*), distinct from the WOTS
321
+ * public key used by `SIGNEDBY`.
322
+ */
323
+ export function wotsAddressData(publicKeyDigest) {
324
+ const raw = publicKeyDigest.replace(/^0x/i, '').toUpperCase();
325
+ return computeScriptAddress(`RETURN SIGNEDBY(0x${raw})`);
326
+ }
305
327
  export function computeScriptAddress(script) {
306
- const cleanScript = script.trim().toUpperCase();
307
- const scriptBytes = new TextEncoder().encode(cleanScript);
308
- const hashBytes = sha3_256(scriptBytes);
309
- return bytesToHex(hashBytes);
328
+ return bytesToHex(mmrRootFromSingleLeaf(toNodeScript(script)));
310
329
  }
311
330
  export { concat };
@@ -10,7 +10,7 @@
10
10
  * precomputeTransactionCoinID() to set output coin IDs. Without this, the signed
11
11
  * digest won't match what the Minima node verifies, causing allsignaturesvalid=false.
12
12
  */
13
- import { sha3_256 } from './wasm-sync.js';
13
+ import { sha3_256 } from './wasm-async.js';
14
14
  import { writeMiniNumber, writeMiniData, writeHashToStream, writeMiniByte, writeMMREntryNumber, concat, hexToBytes, } from './Streamable.js';
15
15
  const ZERO_TXPOWID = new Uint8Array([0x00]);
16
16
  const STATETYPE_HEX = 1;
package/dist/verify.js CHANGED
@@ -1,4 +1,4 @@
1
- import { sha3_256 } from './wasm-sync.js';
1
+ import { sha3_256 } from './wasm-async.js';
2
2
  import { deserializeTreeSignature } from './treekey.js';
3
3
  import { scriptToAddress } from './derive.js';
4
4
  import { scriptFromWotsPk } from './script.js';