Addresses

It is important to note that Bitcoin Addresses are a wallet concern. Wallets use Bitcoin Addresses as a “user-friendly” means of obtaining public key hashes from wallet users. I.e. the addresses we create never end up inside bitcoin Transactions. Addresses are envelopes for public-key-hashes. Public key hashes do appear in bitcoin transactions.

Since an address contains the hash of a public key, it stands to reason that we can obtain an address directly from a public key.

Obtaining an Address


//create a random private key
import org.twostack.bitcoin4j.ECKey
import org.twostack.bitcoin4j.PublicKey
import org.twostack.bitcoin4j.address.LegacyAddress


//creates random private key and public keys (generates random point on elliptic curve)
val ecKey = ECKey()


//create a PublicKey to wrap the ECKey
val publicKey = PublicKey(ecKey)

//create an address from the public key
val address = LegacyAddress.fromKey(NetworkAddressType.MAIN_PKH, publicKey)

Serialising Addresses

The generally accepted format for sharing Addresses publicly, is in their base58-encoded form. It typically looks like this:

//example base58-encoded address : 2NB72XtkjpnATMggui83aEtPawyyKvnbX2o
  • Construct an Address from base58 encoding

      import org.twostack.bitcoin4j.address.LegacyAddress
    
      val addrString = "2NB72XtkjpnATMggui83aEtPawyyKvnbX2o"
    
      //if you don't specify network type, the framework will
      //detect the network type from the base58 string.
      val address1 = LegacyAddress.fromBase58(null, addrString);
    
      //override the network type of the base58 string
      val address2 = LegacyAddress.fromBase58(NetworkAddressType.TEST_PKH, addrString);
    
  • Serialise an Address to base58 encoding

      import org.twostack.bitcoin4j.ECKey
      import org.twostack.bitcoin4j.PublicKey
      import org.twostack.bitcoin4j.address.LegacyAddress
    
    
      //creates random private key and public keys (generates random point on elliptic curve)
      val ecKey = ECKey()
    
      //create a PublicKey to wrap the ECKey
      val publicKey = PublicKey(ecKey)
    
      //create an address from the public key
      val address = LegacyAddress.fromKey(NetworkAddressType.MAIN_PKH, publicKey)
    
      //do base58 encoding
      val base58Encoding: String = address.toBase58()
    
On this page