@interchainjs/auth
Version:
Authentication for web3 accounts
70 lines (69 loc) • 2.98 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PrivateKey = void 0;
const utils_1 = require("@interchainjs/utils");
const crypto_1 = require("@interchainjs/crypto");
const algorithms_1 = require("../config/algorithms");
const public_key_1 = require("./public-key");
// Helper function to convert HD path to Slip10 format
function hdPathToSlip10(hdPath) {
const parts = hdPath.split('/').slice(1); // Remove 'm'
return parts.map(part => {
const isHardened = part.endsWith("'");
const index = parseInt(isHardened ? part.slice(0, -1) : part, 10);
return isHardened ? crypto_1.Slip10RawIndex.hardened(index) : crypto_1.Slip10RawIndex.normal(index);
});
}
class PrivateKey {
value;
config;
hdPath;
_algo;
constructor(value, config, hdPath) {
this.value = value;
this.config = config;
this.hdPath = hdPath;
// Resolve algo once during construction
this._algo = (0, algorithms_1.resolveAlgo)(config.algo);
}
toPublicKey(config) {
// Only compression can be configured, algorithm is inherited
const compressed = config?.compressed ?? true; // default to compressed
const keyPair = this._algo.makeKeypair(this.value.value);
const pubKeyBytes = compressed
? this._algo.compress(keyPair.pubkey)
: keyPair.pubkey;
return new public_key_1.PublicKey(utils_1.BaseCryptoBytes.from(pubKeyBytes), this.config.algo, // Pass the same algorithm
compressed);
}
async sign(data) {
// Note: The caller is responsible for hashing the data if needed
// This allows flexibility for different signing schemes
const signature = await this._algo.sign(data, this.value.value);
return utils_1.BaseCryptoBytes.from(signature);
}
toHex() {
return this.value.toHex();
}
toBase64() {
return this.value.toBase64();
}
static async fromMnemonic(mnemonic, hdPaths, config) {
const mnemonicObj = new crypto_1.EnglishMnemonic(mnemonic);
const seed = await crypto_1.Bip39.mnemonicToSeed(mnemonicObj, config.passphrase || '');
return hdPaths.map(hdPath => {
// Determine curve based on algorithm
const algo = (0, algorithms_1.resolveAlgo)(config.algo);
const curve = algo.name === 'ed25519' ? crypto_1.Slip10Curve.Ed25519 : crypto_1.Slip10Curve.Secp256k1;
const slip10Result = crypto_1.Slip10.derivePath(curve, seed, hdPathToSlip10(hdPath.toString()));
return new PrivateKey(utils_1.BaseCryptoBytes.from(slip10Result.privkey), config, hdPath);
});
}
static fromBytes(bytes, config, hdPath) {
return new PrivateKey(bytes, config, hdPath);
}
static fromHex(hex, config, hdPath) {
return PrivateKey.fromBytes(utils_1.BaseCryptoBytes.fromHex(hex), config, hdPath);
}
}
exports.PrivateKey = PrivateKey;