2019-06-11 14:55:59 +02:00
|
|
|
---
|
|
|
|
id: addresses
|
2020-03-13 09:54:07 -05:00
|
|
|
title: Generating Addresses
|
2019-06-11 14:55:59 +02:00
|
|
|
---
|
|
|
|
|
|
|
|
Almost all Bitcoin applications need to generate addresses
|
|
|
|
for their users somehow. There's a lot going on in getting
|
|
|
|
a correct bitcoin address, but our APIs make it possible to
|
|
|
|
to get started with all types of addresses in a matter of
|
|
|
|
minutes.
|
|
|
|
|
|
|
|
## Generating SegWit (bech32) addresses
|
|
|
|
|
|
|
|
Generating native SegWit addresses in the bech32 format
|
|
|
|
is something that all Bitcoin applications should enable,
|
|
|
|
as it makes the transaction fees less expensive, and also
|
|
|
|
makes the addresses more readable by humans. However, it
|
|
|
|
has seen slower than necessary adoption. With Bitcoin-S
|
|
|
|
you can generate bech32 addresses in four(!) lines of code
|
|
|
|
(not counting comments and imports), so now there's no
|
|
|
|
reason to keep using legacy transaction formats.
|
|
|
|
|
2020-03-10 12:49:22 -05:00
|
|
|
```scala mdoc:invisible
|
2020-04-30 11:34:53 -06:00
|
|
|
import org.bitcoins.core.{protocol, config}
|
2019-06-11 14:55:59 +02:00
|
|
|
import config.TestNet3
|
2020-04-30 11:34:53 -06:00
|
|
|
import org.bitcoins.crypto.ECPrivateKey
|
2019-06-11 14:55:59 +02:00
|
|
|
|
|
|
|
import protocol._
|
|
|
|
import protocol.script._
|
2020-03-10 12:49:22 -05:00
|
|
|
import org.bitcoins.core.protocol.P2PKHAddress
|
|
|
|
```
|
|
|
|
|
|
|
|
```scala mdoc:to-string
|
2019-06-11 14:55:59 +02:00
|
|
|
|
|
|
|
// this generates a random private key
|
|
|
|
val privkey = ECPrivateKey()
|
|
|
|
val pubkey = privkey.publicKey
|
|
|
|
|
|
|
|
val segwitAddress = {
|
|
|
|
// see https://bitcoin.org/en/glossary/pubkey-script
|
|
|
|
// for reading resources on the details of scriptPubKeys
|
|
|
|
// pay-to-witness-pubkey-hash scriptPubKey V0
|
|
|
|
val scriptPubKey = P2WPKHWitnessSPKV0(pubkey)
|
|
|
|
Bech32Address(scriptPubKey, TestNet3)
|
|
|
|
}
|
2020-03-10 12:49:22 -05:00
|
|
|
|
|
|
|
println(segwitAddress.toString)
|
2019-06-11 14:55:59 +02:00
|
|
|
```
|
|
|
|
|
|
|
|
## Generating legacy (base58) addresses
|
|
|
|
|
|
|
|
If you need to generate legacy addresses for backwards
|
|
|
|
compatability reasons, that's also a walk in the park.
|
|
|
|
Take a look:
|
|
|
|
|
|
|
|
```scala mdoc:to-string
|
|
|
|
|
|
|
|
// we're reusing the same private/public key pair
|
|
|
|
// from before. don't do this in an actual application!
|
|
|
|
val legacyAddress = P2PKHAddress(pubkey, TestNet3)
|
2020-03-10 12:49:22 -05:00
|
|
|
|
|
|
|
println(legacyAddress.toString)
|
2019-06-11 14:55:59 +02:00
|
|
|
```
|