@ton-keychain/core
Version:
SDK for creating multi account mnemonics
165 lines (160 loc) • 6.09 kB
JavaScript
// src/ton-keychain-root.ts
import { getSecureRandomNumber, hmac_sha512, mnemonicValidate, pbkdf2_sha512 } from "@ton/crypto";
import { wordlist } from "@scure/bip39/wordlists/english";
// src/utils.ts
import * as crypto from "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
import { mnemonicToPrivateKey } from "@ton/crypto";
import { mnemonicToEntropy } from "@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([
mnemonicToPrivateKey(mnemonics),
mnemonicToEntropy(mnemonics)
]);
return new _KeychainTonAccount(
mnemonics,
keypair.secretKey.toString("hex"),
keypair.publicKey.toString("hex"),
entropy
);
}
};
// src/ton-keychain-root.ts
import { bytesToMnemonics, mnemonicToEntropy as mnemonicToEntropy2 } from "@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 getSecureRandomNumber(0, wordlist.length);
_mnemonicArray.push(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 hmac_sha512("TON Keychain", mnemonic.join(" "));
const result = await 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 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 mnemonicToEntropy2(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 mnemonicToEntropy2(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 hmac_sha512(hmacData, entropy);
const iterationSeed = iterationEntropy.subarray(
0,
KeychainTonAccount.MNEMONICS_WORDS_NUMBER * 11 / 8
);
const mnemonics = bytesToMnemonics(
iterationSeed,
KeychainTonAccount.MNEMONICS_WORDS_NUMBER
);
if (await 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 hmac_sha512(hmacData, entropy);
const iterationSeed = iterationEntropy.subarray(
0,
KeychainTonAccount.MNEMONICS_WORDS_NUMBER * 11 / 8
);
const mnemonics = 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);
}
export {
KeychainTonAccount,
TonKeychainRoot,
getNthAccountTon
};