@ton-keychain/core
Version:
SDK for creating multi account mnemonics
204 lines (197 loc) • 8.01 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
KeychainTonAccount: () => KeychainTonAccount,
TonKeychainRoot: () => TonKeychainRoot,
getNthAccountTon: () => getNthAccountTon
});
module.exports = __toCommonJS(src_exports);
// src/ton-keychain-root.ts
var import_crypto2 = require("@ton/crypto");
var import_english = require("@scure/bip39/wordlists/english");
// src/utils.ts
var crypto = __toESM(require("crypto"));
async function hmac_sha256(key, data) {
let keyBuffer = typeof key === "string" ? Buffer.from(key, "utf-8") : key;
let dataBuffer = typeof data === "string" ? Buffer.from(data, "utf-8") : data;
return crypto.createHmac("sha256", keyBuffer).update(dataBuffer).digest();
}
// src/keychain-ton-account.ts
var import_crypto = require("@ton/crypto");
var import_mnemonic = require("@ton/crypto/dist/mnemonic/mnemonic");
var KeychainTonAccount = class _KeychainTonAccount {
constructor(mnemonics, privateKey, publicKey, entropy) {
this.mnemonics = mnemonics;
this.privateKey = privateKey;
this.publicKey = publicKey;
this.entropy = entropy;
}
static MNEMONICS_WORDS_NUMBER = 24;
static async fromMnemonic(mnemonics) {
const [keypair, entropy] = await Promise.all([
(0, import_crypto.mnemonicToPrivateKey)(mnemonics),
(0, import_mnemonic.mnemonicToEntropy)(mnemonics)
]);
return new _KeychainTonAccount(
mnemonics,
keypair.secretKey.toString("hex"),
keypair.publicKey.toString("hex"),
entropy
);
}
};
// src/ton-keychain-root.ts
var import_mnemonic2 = require("@ton/crypto/dist/mnemonic/mnemonic");
var TonKeychainRoot = class _TonKeychainRoot {
constructor(mnemonic, id) {
this.mnemonic = mnemonic;
this.id = id;
}
static ID_PREFIX = 19629;
// base64 "TK" + 1101 constant
static async generate(wordsCount = 24) {
let mnemonicArray = [];
for (let i = 0; i < 4294967295; i++) {
const _mnemonicArray = [];
for (let i2 = 0; i2 < wordsCount; i2++) {
let ind = await (0, import_crypto2.getSecureRandomNumber)(0, import_english.wordlist.length);
_mnemonicArray.push(import_english.wordlist[ind]);
}
if (await this.isValidMnemonic(_mnemonicArray)) {
mnemonicArray = _mnemonicArray;
break;
}
}
if (!mnemonicArray) {
throw new Error("Root mnemonics was not found in 2^32 iterations");
}
return this.fromMnemonic(mnemonicArray);
}
static async fromMnemonic(mnemonic, options) {
const isValid = options?.allowLegacyMnemonic ? await this.isValidMnemonicLegacy(mnemonic) : await this.isValidMnemonic(mnemonic);
if (!isValid) {
throw new Error("Mnemonic is not compatible with Tonkeeper Root account recovery");
}
const id = await this.calculateId(mnemonic);
return new _TonKeychainRoot(mnemonic, id);
}
/**
* @description DANGER
* Should only be used to process legacy already created mnemonics
* @param mnemonic
*/
static async isValidMnemonicLegacy(mnemonic) {
const mnemonicHash = await (0, import_crypto2.hmac_sha512)("TON Keychain", mnemonic.join(" "));
const result = await (0, import_crypto2.pbkdf2_sha512)(mnemonicHash, "TON Keychain Version", 1, 64);
return result[0] === 0;
}
static async isValidMnemonic(mnemonic) {
const isLegacyValid = await this.isValidMnemonicLegacy(mnemonic);
if (!isLegacyValid) {
return false;
}
const isTonCompatible = await (0, import_crypto2.mnemonicValidate)(mnemonic);
return !isTonCompatible;
}
static async calculateId(mnemonic) {
const id = await hmac_sha256("Keychain ID", mnemonic.join(" "));
const prefix = Buffer.alloc(2);
prefix.writeUint16BE(this.ID_PREFIX);
return Buffer.concat([prefix, id.subarray(0, 16)]).toString("base64").replaceAll("+", "-").replaceAll("/", "_");
}
ACCOUNT_LABEL = (n) => `account:${n}`;
SUB_ROOT_ACCOUNT_LABEL = (n) => `keychain:${n}`;
getTonAccount = async (index) => {
const rootEntropy = await (0, import_mnemonic2.mnemonicToEntropy)(this.mnemonic);
const childEntropy = await hmac_sha256(this.ACCOUNT_LABEL(index), rootEntropy);
const { mnemonics } = await this.entropyToTonCompatibleSeed(childEntropy);
return KeychainTonAccount.fromMnemonic(mnemonics);
};
getSubRootAccount = async (index) => {
const rootEntropy = await (0, import_mnemonic2.mnemonicToEntropy)(this.mnemonic);
const childEntropy = await hmac_sha256(this.SUB_ROOT_ACCOUNT_LABEL(index), rootEntropy);
const { mnemonics } = await this.entropyToRootCompatibleSeed(childEntropy);
return _TonKeychainRoot.fromMnemonic(mnemonics);
};
async entropyToTonCompatibleSeed(entropy) {
const SEQNO_SIZE_BYTES = 4;
const maxSeqno = 4294967295;
for (let i = 0; i < maxSeqno; i++) {
const hmacData = Buffer.alloc(SEQNO_SIZE_BYTES);
hmacData.writeUint32BE(i);
const iterationEntropy = await (0, import_crypto2.hmac_sha512)(hmacData, entropy);
const iterationSeed = iterationEntropy.subarray(
0,
KeychainTonAccount.MNEMONICS_WORDS_NUMBER * 11 / 8
);
const mnemonics = (0, import_mnemonic2.bytesToMnemonics)(
iterationSeed,
KeychainTonAccount.MNEMONICS_WORDS_NUMBER
);
if (await (0, import_crypto2.mnemonicValidate)(mnemonics)) {
return { seed: iterationSeed, mnemonics };
}
}
throw new Error("Ton mnemonics was not found in 2^32 iterations");
}
async entropyToRootCompatibleSeed(entropy) {
const SEQNO_SIZE_BYTES = 4;
const maxSeqno = 4294967295;
for (let i = 0; i < maxSeqno; i++) {
const hmacData = Buffer.alloc(SEQNO_SIZE_BYTES);
hmacData.writeUint32BE(i);
const iterationEntropy = await (0, import_crypto2.hmac_sha512)(hmacData, entropy);
const iterationSeed = iterationEntropy.subarray(
0,
KeychainTonAccount.MNEMONICS_WORDS_NUMBER * 11 / 8
);
const mnemonics = (0, import_mnemonic2.bytesToMnemonics)(
iterationSeed,
KeychainTonAccount.MNEMONICS_WORDS_NUMBER
);
if (await _TonKeychainRoot.isValidMnemonic(mnemonics)) {
return { seed: iterationSeed, mnemonics };
}
}
throw new Error("Ton mnemonics was not found in 2^32 iterations");
}
};
// src/index.ts
async function getNthAccountTon(rootMnemonic, childIndex) {
const root = await TonKeychainRoot.fromMnemonic(rootMnemonic);
return root.getTonAccount(childIndex);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
KeychainTonAccount,
TonKeychainRoot,
getNthAccountTon
});