Skip to content

Instantly share code, notes, and snippets.

@caike
Last active May 23, 2024 17:28
Show Gist options
  • Save caike/bb826b13bd808b4dae38db49c044b4cb to your computer and use it in GitHub Desktop.
Save caike/bb826b13bd808b4dae38db49c044b4cb to your computer and use it in GitHub Desktop.
Generate seeds, keys and addresses. Useful for quickly creating credentials for testing purposes.
// deno run --allow-env --allow-read --allow-net --allow-write credentials.ts
import { mnemonicToEntropy } from "npm:bip39";
import { Blockfrost, C, Lucid, fromHex, generateSeedPhrase } from "npm:lucid-cardano";
type Network = "mainnet" | "testnet";
const harden = (num: number): number => {
if (typeof num !== "number") throw new Error("Type number required here!");
return 0x80000000 + num;
}
const getAccountKeyFromSeed = (seed: string) => {
const entropy = mnemonicToEntropy(seed);
const rootKey = C.Bip32PrivateKey.from_bip39_entropy(
fromHex(entropy),
new Uint8Array()
);
const accountKey = rootKey.derive(harden(1852))
.derive(harden(1815))
.derive(harden(0));
return accountKey;
};
const getAddressFromSeed = (
seed: string,
network: Network = "mainnet"
): string => {
const accountKey = getAccountKeyFromSeed(seed);
const paymentKey = accountKey.derive(0).derive(0).to_raw_key();
const stakeKey = accountKey.derive(2).derive(0).to_raw_key();
const paymentKeyHash = paymentKey.to_public().hash();
const stakeKeyHash = stakeKey.to_public().hash();
return C.BaseAddress.new(
network == "mainnet" ? 1 : 0,
C.StakeCredential.from_keyhash(paymentKeyHash),
C.StakeCredential.from_keyhash(stakeKeyHash)
)
.to_address()
.to_bech32(undefined);
};
const getPrivateKeyFromSeed = (seed: string): string => {
const accountKey = getAccountKeyFromSeed(seed);
return accountKey.derive(0).derive(0).to_raw_key().to_bech32();
};
const generateCreds = async () => {
const seed = generateSeedPhrase();
console.log(seed);
const acctKey = getAccountKeyFromSeed(seed);
console.log(acctKey.to_bech32());
const pKey = getPrivateKeyFromSeed(seed);
console.log(pKey);
const address = getAddressFromSeed(seed, "testnet");
console.log(address);
await Deno.writeTextFile("./credentials.txt", seed + '\n', {
append: true,
});
await Deno.writeTextFile("./credentials.txt", acctKey.to_bech32() + '\n', {
append: true,
});
await Deno.writeTextFile("./credentials.txt", pKey + '\n', {
append: true,
});
await Deno.writeTextFile("./credentials.txt", address + '\n', {
append: true,
});
}
generateCreds();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment