Skip to content

Instantly share code, notes, and snippets.

@cgcardona
Last active July 12, 2022 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgcardona/35ebfe93a26d76add577927564969f8f to your computer and use it in GitHub Desktop.
Save cgcardona/35ebfe93a26d76add577927564969f8f to your computer and use it in GitHub Desktop.
Hierarchical deterministic keypairs and bech32 addresses for the X-Chain and P-Chain on the Avalanche Primary Network
// imports
import {
KeyChain as AVMKeyChain,
KeyPair as AVMKeyPair,
} from "avalanche/dist/apis/avm"
import {
KeyChain as PlatformVMKeyChain,
KeyPair as PlatformVMKeyPair
} from "avalanche/dist/apis/platformvm"
import { Buffer } from 'buffer/'
import * as bip39 from "bip39"
import HDKey from 'hdkey'
// the goods
const main = async (): Promise<any> => {
const AVAX_ACCOUNT_PATH: string = `m/44'/9000'/0'`
const mnemonic: string = bip39.generateMnemonic(256)
console.log(`Mnemonic: ${mnemonic}`)
const seed: globalThis.Buffer = bip39.mnemonicToSeedSync(mnemonic)
const hdkey: HDKey = HDKey.fromMasterSeed(seed)
let derivationPath: string = `${AVAX_ACCOUNT_PATH}/0`
console.log("X ADDRESSES")
for (let i: number = 0; i < 5; i++) {
let key: HDKey = hdkey.derive(`${derivationPath}/${i}`) as HDKey
let keychain: AVMKeyChain = new AVMKeyChain("avax", 'X')
let pkHex: string = key.privateKey.toString('hex')
let pkBuf: Buffer = new Buffer(pkHex, 'hex')
let addr: AVMKeyPair = keychain.importKey(pkBuf)
console.log(`${i} Address: ${addr.getAddressString()}`)
console.log(`${i} Public Key: ${key.publicKey.toString('hex')}`)
console.log(`${i} Private Key: ${key.privateKey.toString('hex')}`)
console.log("--")
}
console.log("+++++++++++++++++++++++++++++++++++")
console.log("P ADDRESSES")
for (let i: number = 0; i < 5; i++) {
let key = hdkey.derive(`${derivationPath}/${i}`) as HDKey
let keychain: PlatformVMKeyChain = new PlatformVMKeyChain('avax', 'P')
let pkHex: string = key.privateKey.toString('hex')
let pkBuf: Buffer = new Buffer(pkHex, 'hex')
let addr: PlatformVMKeyPair = keychain.importKey(pkBuf)
console.log(`${i} Address: ${addr.getAddressString()}`)
console.log(`${i} Public Key: ${key.publicKey.toString('hex')}`)
console.log(`${i} Private Key: ${key.privateKey.toString('hex')}`)
console.log("--")
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment