Skip to content

Instantly share code, notes, and snippets.

@torkelrogstad
Created June 12, 2019 11:17
Show Gist options
  • Save torkelrogstad/a39178af39795a87865c3bb89b3be063 to your computer and use it in GitHub Desktop.
Save torkelrogstad/a39178af39795a87865c3bb89b3be063 to your computer and use it in GitHub Desktop.
import scodec.bits._
import org.bitcoins.core.crypto._
import org.bitcoins.core.hd._
// the length of the entropy bit vector determine
// how long our phrase ends up being
// 256 bits of entropy results in 24 words
val entropy: BitVector = MnemonicCode.getEntropy256Bits
// entropy: BitVector = BitVector(256 bits, 0xdf78bf273bc6fa221e1d807e389818b9e9a5f19d20328bef2bf35db8714cffe6)
val mnemonicCode = MnemonicCode.fromEntropy(entropy)
// mnemonicCode: MnemonicCode = MnemonicCodeImpl(Vector(term, shine, six, jealous, hurry, baby, journey, quote, lawsuit, shadow, alert, inherit, olympic, web, innocent, alien, message, junk, wolf, rocket, mandate, please, zebra, solution))
mnemonicCode.words // the phrase the user should write down
// res0: Vector[String] = Vector(term, shine, six, jealous, hurry, baby, journey, quote, lawsuit, shadow, alert, inherit, olympic, web, innocent, alien, message, junk, wolf, rocket, mandate, please, zebra, solution) // the phrase the user should write down
// the password argument is an optional, extra security
// measure. all MnemonicCode instances will give you a
// valid BIP39 seed, but different passwords will give
// you different seeds. So you could have as many wallets
// from the same seed as you'd like, by simply giving them
// different passwords.
val bip39Seed = BIP39Seed.fromMnemonic(mnemonicCode,
password = "secret password")
// bip39Seed: BIP39Seed = BIP39SeedImpl(ByteVector(64 bytes, 0x754c023772d101d4ed0b626ad84468d825f22c09e8d2d9d31d6e096f40376613729e9433d2b21fd55c1d5cd911c309105c4f3472e03094a743bebd7f1aacb3c6))
val xpriv = ExtPrivateKey.fromBIP39Seed(ExtKeyVersion.SegWitMainNetPriv,
bip39Seed)
// xpriv: ExtPrivateKey = zprvAWgYBBk7JR8Gj133sPAyfw4GYa2cKkxQNj17W2b1JPkJF7bVEQsxrnRSxqN1e9cn8WZvESTVLPxzqpGAn3PMMLhyDFUzMUeB5K2YjxdUsWN
val xpub = xpriv.extPublicKey
// xpub: ExtPublicKey = zpub6jftahH18ngZwV7WyQhz35116bs6jDgFjwviJQzcrjHH7uvdmxCDQajvp7fxrgSutirVic7LV4sb1jrtxbx8NfswD2tUxXww54h53wVijyz
// you can now use the generated xpriv to derive further
// private or public keys
// this can be done with BIP89 paths (called SegWitHDPath in bitcoin-s)
val segwitPath = SegWitHDPath.fromString("m/84'/0'/0'/0/0")
// segwitPath: SegWitHDPath = m/84'/0'/0'/0/0
// alternatively:
val otherSegwitPath =
SegWitHDPath(HDCoinType.Bitcoin,
accountIndex = 0,
HDChainType.External,
addressIndex = 0)
// otherSegwitPath: SegWitHDPath = m/84'/0'/0'/0/0
segwitPath == otherSegwitPath
// res1: Boolean = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment