Beginning Bitcoin – Sending Funds From Your Wallet

Overview

Getting started with Bitcoin isn’t as intimidating as it would seem. In another tutorial, we discussed how to get started with a mobile wallet, using Bitcoin.com’s app or the Coinomi wallet. We learned how to install the wallet, safely back up our funds using the seed phrase, and get an address for loading up funds.

But the real use of Bitcoin isn’t simply funding a wallet and watching the price bounce up and down. Cryptocurrencies are currencies after all, so they can be spent! Sending Bitcoin is fairly straightforward, but it’s a bit of a different mechanism than using a credit card online. Let’s learn how to send funds to someone else using the Bitcoin.com mobile wallet, and learn about what makes these transactions different that traditional online payments.

Creating Cryptocurrency Transactions

Sending funds with the Bitcoin.com wallet

Let’s donate a dollar to our friends at Eat BCH using the Bitcoin.com wallet. To do this, first open up the wallet with some funds in it, and click on the Send button. You’ll see this screen with options to enter a Bitcoin Cash address manually (or copy/paste), or to scan a QR code. I find that scanning a QR code is often the easiest way to get an address, and Eat BCH has one on the website.

It’s always a good idea to double check the address that actually ends up in the transaction preview. Make sure you didn’t accidentally copy/paste an incorrect address, or scan the wrong QR code. It happens, and there’s also malware out there that has fudged copy/pasted addresses.

Just take a second to make sure you have the destination you actually want. There are no do-overs with cryptocurrency transactions – once they are sent there is no reversal!

Once everything is verified, slide the Bitcoin logo at the bottom to send. Your transaction will be created, and is on it’s way.

Bitcoin vs. Traditional Online Payments

It’s simple to create Bitcoin, Ethereum, and other cryptocurrency transactions with a nice wallet user interface. But these transactions work a bit different than traditional monetary transfers, and it’s good to understand how they work at a high level.

The major difference between a cryptocurrency transaction and a traditional credit card/debit card payment is the mechanism. Traditional credit card payments are pull transactions. You give a merchant your credit card information, which is private information you are entrusting to them. They use that number to request funds be pulled from your account, via the Visa/Mastercard/etc. network.

Bitcoin transactions are push transactions. Instead of giving away private information, the merchant has to give you their public address that you push funds to in a transaction. You’re in charge of the sending, and no private information is every exchanged.

The true beauty of this system is the increased security you get with this model! You can publish a Bitcoin transaction on a billboard and everything is safe. Try putting your credit card number in a public space and see how long it takes to have major problems!

Bitcoin Transactions – Simple and Secure!

All you need to send money is a wallet with a network connection, some cryptocurrency of your choice, and a recipient address. With a modern mobile wallet, this process is a simple as scanning a QR code and hitting send. Thanks to Bitcoin’s security model, you don’t have to trust an intermediary like a payment company to process the transaction – it’s entirely peer-to-peer. And even more novel and important, there’s no need for anyone to reveal private numbers.

If you haven’t already, try sending your first transaction! Grab some Bitcoin or Bitcoin Cash, or maybe some Litecoin. Use a few dollars to introduce a friend to cryptocurrency, buy something fun, or donate to a good cause. Adoption is important, and it’s easy!

Learn Hashing, Binary, and Proof-of-Work with MicroProver (Code Companion #2)

Note: This article focuses on the development of MicroProver. See my slides for the full BTC2019 talk

Overview

Proof-of-work is a Bitcoin and blockchain topic of vital importance, as it allows transactions to occur without trusting an intermediary. However, understanding this concept also requires some computer science background. One needs to know about hashing algorithms, binary numbers, and a bit of probability to “get” proof-of-work.

I wanted to do a better job of explaining the concept of proof-of-work to individuals without a computer science background – so I came up with the idea of visualizing hashing and binary numbers with a cool little microcontroller I received at PyCon 2019. This code companion will dive into the development of MicroProver, and how I turned this project into a session at the 2019 Blockchain Training Conference!

MicroProver (running on the Adafruit Circuit Playground Express) displays a final “block hash”

How MicroProver Works

Toy Hashing Algorithm

The first thing needed to make simulated proof-of-work operate is a hashing algorithm. Bitcoin uses the cryptographically secure SHA-256 for its mining operations, among other things. However, these cryptographic algorithms are not readily available on microcontroller platforms such as the Circuit Playground. It took extensive effort to get cryptographic primitives working for my offline address generation project, and required a more powerful line of processor than the CPX’s M0.

However, for the purposes of this project, a cryptographically secure hash algorithm is not needed! This project is designed for visualization and learning, and has no security requirements. So in order to create the 8 bit hashes I wanted, I simply used the simplest form of hash function one might use for creating a basic hash table. All of the code in this article can be found in src/core/MicroProver.py

    # Settings for "cryptography"
    self.HASH_MOD = 256

...

    # Return a really simple 8 bit hash
    # This is for educational purposes, so we don't need a
    # cryptographically secure hash, we just need one that works
    def hash_8bit(self, data):
        hash8 = data % self.HASH_MOD

        return hash8

For an 8 bit hash, we use the 8 bit number space that contains 256 total possible numbers (0-255). This algorithm takes the modulus of the data and 256, giving us a reasonable hash for our purposes.

Binary Representation

The other important concept needed to address proof-of-work is understanding binary numbers. In daily life, most of us are used to base 10, and working in other bases is a rather foreign concept. In order to make this easier to understanding in the context of proof-of-work, I decided to use the built in CPX LED lights, with red representing 0 and green representing 1.

The code takes the data (the hash output) and converts it from a raw number to an array of binary values, either True/False (used by the LED function) or 1/0 for string representation. The data is turned into binary using a technique called bitmasking, where one single bit of a byte is isolated using the & binary operator.

    # Convert a byte of data (8 bit hash, etc.) into
    # an array of bits represented by True (1) and False (0)
    # (with default mode bool)
    # Specify optional mode "bit" for 0/1 representation
    def byte_to_bitarr(self, byte, mode="bool"):

        # Define some bitmasks for each spot in the byte
        # We'll create the array using bitmasking
        masks = [ 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 ]
        byte = int(byte)

        bitarr = []
        for i in range(0, 8):
            if mode == "bit":
                masked = byte & masks[i]
                bit = "1" if masked > 0 else "0"
            else:
                bit = bool(byte & masks[i])
            bitarr.append(bit)

        return bitarr

The LED display function then takes that array and lights up individual LEDs on the board to represent each bit:

    # This function displays an LED representation of a byte
    # It lights up 8 LEDs on the Playground Express board
    # Green represents a 1 bit
    # Red represents a 0 bit
    def display_byte_led(self, byte):

        bitarr = self.byte_to_bitarr(byte)
        for i in range(0, 8):
            if bitarr[i]:
                color = self.GREEN
            else:
                color = self.RED

            # Load the pixels from 1 - 9 so they
            # fill evenly on each side of the board
            cpx.pixels[i + 1] = color
        cpx.pixels.show()

Tying It Together for Proof-of-Work

Using these nifty little hash concepts, binary operators, and LEDs, it becomes bit easier to visualize the binary number comparisons needed by proof of work. Proof-of-work requires comparing a hash output to a difficulty target, and both can be thought of as binary numbers. For this toy visualization, we use small 8 bit numbers.

For example, say we have a difficulty target of 00100000. This value (32 in decimal) has two leading zeroes represented as an 8 bit, unsigned integer. Therefore, the final hash output must have at least 3 leading zeroes to be less than the target. For example, 00010100 is a valid block hash. Because the probability of finding this “block hash” decreases as the difficulty target decreases numerically, we “proved work” by doing a lot of guesses to get a solution.

In MicroProver, the user gets to program the difficulty level from 1-7, with the level being the number of leading zeroes in the target. This way, it is easy for the user to visualize the algorithm as attempts and the final solution are displayed on the board. They can look for the red “leading zeroes” as the algorithm works, and get a better feel for how difficulty affects the computing power/time needed to prove work.

Extra Visual Help – Data Visualization Script

As an addition to the board itself, I created a data visualization script in src/dataviz/graph_pow.py. This script takes an optional log generated by the CPX simulation and graphs targets/vs. attempts, breaking down how difficulty affects the probability of finding a solution:

Proof of Work difficulty target vs attempts to find a solution. It’s probability!

Proof-of-Work, Made Accessible

When I got the Circuit Playground, I knew I had to use it to create an interesting chaintuts project! After getting oriented with programming basic utilities on the board, I decided its features would be great for an educational assistant.

Fortunately, I have had the opportunity to take this project further and teach at the 2019 Blockchain Training Conference in Denver, CO! For this session, I’ll be breaking down proof-of-work and using MicroProver for interactive simulations and data visualization.

By using LEDs to visualize hashing, binary numbers, and a bit of probability, we can make understanding this critical blockchain security topic more accessible to those without a computer science background. And the more folks that understand decentralization and trustless software, the more we can drive adoption of these technologies.

Offline Address Generation with uBitAddr (Code Companion #1)

This is a new series I’m introducing called “Code Companion”. These articles and videos highlight code projects of mine that are related to Bitcoin & cryptocurrencies. These projects can be helpful in understanding technical blockchain concepts. Explore and enjoy!

Overview

One of the most secure ways to store Bitcoin and other cryptocurrencies for the long term is to use was is called cold storage. This means storing the private keys that secure your funds in some manner that doesn’t allow access by a networked computer. A popular method of implementing cold storage is to use a technology that long predates computing and the Bitcoin network – paper. A paper wallet is simply a Bitcoin address and it’s private key written down on paper, usually in an exportable format such as WIF (Wallet Import Format).

An even more secure way to approach offline storage is to generate the private key and address offline. Generating and storing keys offline protects the owner from malware that might snoop the keys and send them off to a thief.

My project uBitAddr (pronounced MicroBitAddr) allows the generation of private keys and addresses completely offline using Adafruit M4 microprocessors wired up to an LCD screen or mini thermal receipt printer.

ubitaddr_display
uBitAddr running on the Adafruit ItsyBitsy M4 with a character LCD & backpack as the output
uBitAddr running on the Adafruit Grand Central M4 with a mini thermal receipt printer as the output

How uBitAddr Works

Custom CircuitPython Module

The first big challenge in this project was getting access to the required cryptographic primitives on a microcontroller platform. Generating a basic Bitcoin address requires elliptic curve cryptography (secp256k1 specifically), and two different hashing algorithms (SHA-256 and RIPEMD160). Good implementations of these algorithms are widely available on desktop PC’s and mobile phones for a variety of programming languages, but aren’t readily available for microprocessors like this.

I needed to get access to good cryptographic implementations to make this work! Since I wanted to do the bulk of coding in CircuitPython, I could have found pure-Python implementations of these algorithms. However, I felt this was resource inefficient and wouldn’t work on all but the most robust boards. Instead, I opted to write custom extension for CircuitPython itself using this guide from Dave Astels and some help from ladyada and Dan on Github. – thanks everyone!

For my project, I needed to use the M4 line of microcontrollers from Adafruit (using the Atmel Samd51 processor). I needed to use a processor at least this powerful to fit the compiled CircuitPython distribution, as the M0’s are simply too small to support these cryptographic algorithms. Fortunately, my goal of supporting a few different controllers and not just one big powerful one still worked out – the M4 line features a bunch of different shapes and sizes, from the ItsyBitsy to the Grand Central!

For cryptographic primitives, I ended up porting over code from the popular open-source hardware wallet Trezor. The Trezor crypto libraries had everything I needed to do efficient elliptic curve crypto and hashing, and even base58 encoding for the final address and WIF private key. This code is designed to be efficient and lightweight for embedded platforms. A big thanks to Trezor’s contributors for this code!

In terms of the my implementation, the most important code in this extension is features in src/module/shared-module/bitaddr/__init__.c. This code follows several steps to generate an address and exportable private key from start to finish:

  • Take entropy from the Python side (could be any good source, that’s up to the module user)
  • Hash the entropy and generate the raw private key
  • Calculate the uncompressed public key from the private key
  • Use the Bitcoin base58 check algorithm to hash and encode the address from the public key
  • Use the WIF algorithm to encode an exportable private key

As of this writing, that function looks like this. I try to keep projects moving forward so this may change slightly in the future:

 // Define functions that implement the Python API
void shared_modules_bitaddr_get_address_privkey(unsigned char* address, unsigned char* privkey, const char* entropy_privkey, const char* entropy_ecdsa)
{
	// Init the random32 for rand.h and ecdsa.h functions
	// The random function is only needed for curve_to_jacobian - needs a random k value
	// It will only be called once for address generation, so we'll use true entropy
	// To "seed" random32's PRNG without causing problems
	unsigned char seed_entropy[SHA256_DIGEST_LENGTH];
	sha256_Raw((uint8_t*) entropy_ecdsa, strlen(entropy_ecdsa), (uint8_t*) seed_entropy);
	init_random32(seed_entropy);


	// Generate the private key from some entropy
	// Then generate the public key from the private key
	unsigned char privkey_raw[SHA256_DIGEST_LENGTH];
	privkey_from_entropy(entropy_privkey, privkey_raw);

	unsigned char pubkey[PUBKEY_65_LENGTH];
	pubkey_from_privkey(privkey_raw, pubkey);

	// Generate the address from the public key
	// This address will use the legacy base58check encoding valid
	// in both BTC and BCH
	address_from_pubkey(pubkey, address);

	// Convert the private key to WIF format for export
	privkey_wif_from_raw(privkey_raw, privkey);
}

The next major component of this is creating a binding to the Python side in src/module/shared-bindings/bitaddr/__init__.c. This is a bit more complicated but the general idea is to take two sources of entropy (randomness) from the module user for the private key and ECDSA k value. I did this to allow flexibility – the module user can use a built in CRNG, accelerometer, diceware, etc. to generate randomness as they choose. Right now the Python code I wrote uses the convenient CRNG built in to all M4 boards.

Next, the C function shared_modules_bitaddr_get_address_privkey from shared-module/__init__.c is called. The return values (passed in to the function as pointers) are placed in a Python tuple and returned to the caller on the Python side.

//| .. function:: get_address
//|
//|   Returns a Bitcoin or Bitcoin Cash Legacy Address
//|
const size_t ADDRESS_STR_LENGTH = 40;
const size_t PRIVKEY_STR_LENGTH = 70;

STATIC mp_obj_t bitaddr_get_address(mp_obj_t entropy_privkey, mp_obj_t entropy_ecdsa) {

	// Convert entropy args needed for secure address generation
	const char* entropy_privkey_char = mp_obj_str_get_str(entropy_privkey);
	const char* entropy_ecdsa_char = mp_obj_str_get_str(entropy_ecdsa);

	// Create an address cstring long enough to fit any Bitcoin address
	unsigned char address[ADDRESS_STR_LENGTH];
	unsigned char privkey[PRIVKEY_STR_LENGTH];
 	shared_modules_bitaddr_get_address_privkey(address, privkey, entropy_privkey_char, entropy_ecdsa_char);

    	// make the return value
    	mp_obj_tuple_t *addr_key= MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL));
    	addr_key -> items[0] = mp_obj_new_str((char*) address, ADDRESS_STR_LENGTH);
    	addr_key -> items[1] = mp_obj_new_str((char*) privkey, PRIVKEY_STR_LENGTH);

	return addr_key;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(bitaddr_get_address_obj, bitaddr_get_address);

Finally, I built this for at least a few of the boards I wanted to support. I tested this code on an ItsyBitsy M4 and Grand Central M4, but it should also work on the Metro M4 or other releases. They’re all the same processor and seem to all have built in cryptographic number generation. So cool!

The Core CircuitPython Code

Thanks to this module, generating an address on the Python side ends up super simple! I generate a new address and private key on demand by specifying some entropy from the built in CRNG and store the results from the returned tuple:

    # Get entropy based on the desired source
    def get_entropy_str(self):

        if self.entropy_source == self.ENTROPY_CRNG:
            return str(os.urandom(32))
        else:
            raise Exception("No sufficient entropy source specified")

    # Generate address and private key
    def generate_address_privkey(self):

        address, privkey = bitaddr.get_address(self.get_entropy_str(), self.get_entropy_str())

        return (address, privkey)

In the future it may be possible to get entropy from another source – like an accelerometer wired to the board, or a keypad input for diceware key generation.

Wiring up Outputs

The final step was to offer a few options for viewing the generated address and private key. I have an option for serial import, so it’s of course possible to send your address and private key directly to a computer. However, since the whole purpose of this project is offline generation and storage, it’s obvious I needed some offline output options! I opted for character LCD display and thermal printing.

The first option is wiring up a thermal receipt printer. This uses an Adafruit mini printer that costs about $60, and it’s so cool to play with. To use this peripheral, I had to wire it to an external power source that came with the kit. The printer was then wired to ground and serial tx on the processor.

    # Print a paper wallet with the thermal receipt printer
    def print_address_privkey(self, address, privkey, print_privkey=True):

        # Intialize the printer
        uart = busio.UART(board.TX, board.RX, baudrate=19200)
        ThermalPrinter = adafruit_thermal_printer.get_printer_class(2.69)
        printer = ThermalPrinter(uart)

        printer.bold = True

        # Warm up and wait so we get the best print quality
        printer.warm_up()
        time.sleep(2)

        # Print the address information
        printer.feed(3)
        printer.print("Address:")
        printer.print(address)

        if print_privkey:
            printer.feed(3)
            printer.print("Private Key (WIF):")
            printer.print(privkey)

        printer.feed(3)

The next option (slightly more complex, actually) is the character LCD display. For this, I got to solder for the first time since high school! Thankfully my friend and engineer Nathan Schomer taught me well back in the day. I soldered the I2C backpack to the character LCD, and wired it to scl and sda on the board for data. Power requires either 5v or USB depending on the board, and a ground.

    # Prepare the data for display on the character screen
    def prep_data(self, data, colmax):

        prepped_data = ""
        for i in range(0, len(data)):
            if i != 0 and i % colmax == 0:
                prepped_data = prepped_data + "\n"

            if data[i] in self.BASE58_ALPHABET:
                prepped_data = prepped_data + data[i]

        return prepped_data

    # Display the address or private key on a character LCD
    def display_address_privkey(self, address, privkey):

        # Initialize the board
        i2c = busio.I2C(board.SCL, board.SDA)
        cols = 20
        rows = 4
        lcd = character_lcd.Character_LCD_I2C(i2c, cols, rows)
        lcd.backlight = True

        # Prep the address and display, wait N seconds,
        # then display the private key
        while True:
            lcd.clear()
            address = self.prep_data(address, cols)
            lcd.message = "Address:\n" + address

            time.sleep(self.DISPLAY_INTERVAL)

            lcd.clear()
            privkey = self.prep_data(privkey, cols)
            lcd.message = "Private Key (WIF):\n" + privkey

            time.sleep(self.DISPLAY_INTERVAL)
The thermal printer wired up to the ItsyBitsy M4
The character LCD wired up to the Grand Central M4.

Easy Offline Address Generation with uBitAddr

I was extremely excited to get this project working from start to finish, as it was certainly a challenge. Now that it’s done, it’s easy to generate addresses completely offline and keep them secure. All I have to do is boot up a board with an output, and make sure the key and address are safely written down and backed up.

This project has plenty of interesting potential features as well – as I improve on it I can add things like different entropy sources, persistent storage of keys/addresses on the board or a micro SD, different outputs, newer address formats, and more.

I encourage you all to go out and try building things like these as well! Try running your own uBitAddr setup if you have some knowledge of microcontrollers, or get started with your own address generation software built on a platform you’re familiar with. If you’ve never used an Arduino or CircuitPython controller before, try making something fun – they are more accessible than you think. Happy tinkering!

Token-Ize Me – The Basics of ERC20 Tokens

Overview

One of the most interesting and powerful capabilities of the Ethereum network is the ability to create new currencies that operate on top of the base network. By using smart contracts, it’s possible to create a currency called a token without having to fork an existing currency’s code and create a new decentralized network. Coins such as Litecoin follow the latter approach – Litecoin exists as its own network that runs on a modified version of Bitcoin’s code. However, tokens such as 0x (ZRX), Basic Attention Token (BAT), and Paxos (PAX) exist by leveraging the existing Ethereum network’s smart contract capability.

However, there are so many tokens out there that it would be nearly impossible for wallet creators and exchanges to keep up with each individual token’s smart contract API. In order to make it easier to create and support Ethereum tokens, the ERC20 standard was introduced. This standard specifies a common set of smart contract functions and events for a token. Let’s take a look at this standard smart contract interface and how it works.

ERC20 Contracts

The Standard Contract Format

The ERC20 standard defines a set of functions and events that a token smart contract should define. The functions are:

function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);

There are two events associated with the contract as well:

event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens

The list of required fields is fairly simple, but let’s break down more how a contract like this works and summarize what each function does.

Token Contract Creation

Any time a smart contract is deployed on the Ethereum network, it becomes a permanent part of the blockchain that others can interact with by sending a transaction to the contract address with a function call in the data section of the transaction.

When a fixed-supply token contract is created (a common and simple type of token), the first thing it does is assign the total supply balance to the contract address owner, so the total amount of tokens is accounted for. Different types of tokens might allow a mining process where when a new Ethereum block is found, that miner also gets some of the tokens. But we’re focused on simple fixed-supply contracts here, so assume when the contract is created the owner of the Ethereum contract address now owns the full supply of this token.

At any time, another user can see the total supply of tokens by creating a tx that calls totalSupply, and balances can be checked by calling balanceOf with an address.

Token Transactions

There are now two types of token transactions our smart contract interface allows. The first is pretty simple: it’s the transfer functionality from the contract address owner to another recepient. Ethereum tokens use Ethereum addresses for sending and receiving, so it’s simple in that regard. So to do a transfer, the owner creates a transaction on Ethereum that calls the transfer function, specifying an amount and the new owner.

The second type of transfer is a little more interesting and complex. The ERC20 standard allows a withdrawal type mechanism. First, the contract address owner must call approve in a transaction, specifying a new address that is allowed to withdraw and what the maximum withdrawal amount is. Then, the withdrawal address owner can call allowance to see their “account balance” and use transferFrom to withdraw from the approved account to a new address.

Finally, most contracts will emit an event on Transfer or Approval so that other contracts can listen and do something when the event is fired off. For example, we may have a contract that waits for approval to conduct a withdrawal of a token.

Tokens Made Simple

There’s a lot going on when it comes to understanding Ethereum smart contract execution, but thankfully the ERC20 interface can be understood at a high level by discussing the basic functionality of each defined function and event.

With ERC20, we can create a token, and easily retrieve the total supply or an address balance. We can do a simple transfer out of an address we own, or approve withdrawals by another account that will transfer from the approved account. Finally, other contracts can listen for approval and transfer events so they can do something interesting.

For further reading, the Ethereum Wiki has a section on the ERC20 standard with a code example that may be useful. There are tons of tokens out there you may be interested in exploring as well.

Beginning Bitcoin – Getting Started with Mobile Wallets

Overview

For someone that’s completely new to the concept of digital money, all the information out there can get a tad overwhelming. Fortunately, getting a practical start in using cryptocurrencies is actually fairly trivial with modern mobile wallets!

Installing a proper wallet is the first step in a safe and successful journey into the crypto space. We want a wallet that makes it easy to send and receive funds (has a nice user interface) and where you control your own funds (by owning the private keys). Both of these wallets allow you full control over your own funds – there is no institution like an exchange holding your money for you like a bank. It’s yours, like digital cash! In order to securely back up your money, each wallet generates a 12-24 word “seed” that you need to write down somewhere in the event you lose your phone or something of that nature.

In this tutorial, we’ll learn to install two easy to use and secure multi-asset wallets developed by Bitcoin.com and Coinomi. Both of these allow the user to send and receive multiple cryptocurrencies, so it’s easy for a beginner to dabble in a few currencies that interest them.

Wallet Install Walkthroughs

The Bitcoin.com Wallet

The first wallet we’ll take a look at is the Bitcoin.com wallet. This application is available on Android and iOS, as well as desktop platforms. I find it easy to use on a mobile phone for portable payments. This wallet supports both Bitcoin Cash (BCH) and Bitcoin Core (BTC). It’s also compatible with a payment protocol known as BIP70 used by the popular payment processor Bitpay, so it’s easy to buy things with this wallet through retailers like Newegg and service providers like AT&T.

Let’s walk through how to set up this wallet so you can start sending and receiving funds securely.

  • First, install the application on your phone through the Google Play store or the App Store.
  • Open up the application – you’ll see a screen that says “Creating wallet” while your initial seed is generated
  • Next, you’ll see a screen telling you that your wallets are ready to go! Tap on either your BCH or BTC wallet – it doesn’t matter which as both will share the same backup phrase.
  • When you open up your wallet, go to the settings (the cog icon at the top) and click on the “backup” option.
  • Next, write down the backup phrase shown on the screen and store it somewhere safe. This phrase is absolutely secret and should never be shared with anyone. It’s used to generate all of the keys that unlock your money for spending. Also, don’t use or write down the phrase shown in this tutorial. Anyone can see it, so anyone could spend money sent to this example wallet.
  • Now verify it on the next screen, and your wallet is ready to use!
  • To receive BCH or BTC from someone, or send it to your wallet from an exchange, click on “receive” and one of your addresses will be shown in text and QR code format. This address is public (used to send you money) and can be given away freely. Just don’t use the example one shown here, because it belongs to the (not so) secret backup phrase shown above.

The Coinomi Wallet

The Coinomi wallet is another easy to use and secure mobile wallet for Android or iOS. This wallet is built with security in mind according to the Coinomi website, and supports hundreds of cryptocurrencies including Bitcoin, Bitcoin Cash, Litecoin, and Ethereum.

  • Just like with the Bitcoin.com wallet, start by actually installing the application via the Google Play store or the App Store.
  • When you first open up the app, it will ask you if you’d like to create or restore a wallet. We’ll select “create” here.
  • Next, the wallet will generate and display a 24 word “seed” phrase that allows you to easily back up your wallet. Write this down and store it somewhere safe. Again, do not share this with anyone. It’s the secret key that’s used to unlock all of your funds when you want to spend them. And again, don’t use the specific phrase shown below. Anyone that’s read this tutorial could steal your money if you did!
  • Next, select the currencies you want to use. You can add and remove currencies any time, and all of them will use the same backup phrase you wrote down in the last step to generate keys and addresses. One backup, many wallets!
  • Now you can open up the wallet created for any currency you’d like to use, and your address will be shown in text and QR format. There’s a couple of different address formats these days – usually “compatibility” is a good bet if you’re not sure. Again, don’t send any funds to the address shown here.

Getting Started with Crypto – It’s That Easy!

Using either of these mobile wallets is a great way to get started using cryptocurrencies like Bitcoin, Bitcoin Cash, Litecoin, and Ethereum. These mobile wallets are available on the most popular mobile platforms, and can be installed by simply visiting the right app store.

Setup is easy and secure, as both wallets use BIP39 mnemonics to generate your addresses. All you have to do is write down this phrase in a safe place and your wallet can always be restored if you have a problem. More importantly, the funds you send to these wallets are truly yours; they’re not held by an exchange.

And as we’ve seen here, these wallets are pretty easy to use! Just a few set up steps and you’re ready to send and receive magic internet money yourself.

Super Segwit Scripts

Overview

Segregated Witness, better known as segwit, is a soft-fork change to the core Bitcoin (BTC) protocol implemented to provide one possible scaling solution as well as other benefits. First, the use of segwit decreases the size of transactions (sort of) and provides a new way for the Bitcoin network to scale without a hard-fork block size increase. As well, segwit fixes transaction malleability, a long known problem that allows the transaction ID hash to change without changing the meaning (value transfers, etc.) of a transaction. Finally, segwit helps to decrease the amount of data nodes need to store in memory by making UTXOs much smaller.

There’s a lot to segwit, and each of these points can be a lengthy technical discussion. However, it can be easier to understand these benefits of segwit by understanding how these transactions compare internally to normal P2PKH transactions.

Transaction Scripts: Segwit vs. Normal

Reviewing Legacy Transaction Scripts

First, let’s review how scripts work generally and how they are used to construct transactions in Bitcoin. We’ll take a look at the normal or legacy Pay-To-Public-Key-Hash transaction type, one of the most common on the Bitcoin network.

When a user receives some Bitcoin at their address, what they really receive is a new “Unspent Transaction Output” or UTXO that is associated with their address. This UTXO specifies a locking script – a condition that must be programatically satisfied in order to spend that Bitcoin in a future transaction.

When the user wants to send funds to someone else, their wallet constructs a transaction with an unlocking script that satisfies the locking script set on the UTXO. This script essentially proves that the user owns the Bitcoin to the rest of network and allows the funds to be spent.

For a typical P2PHK transaction, the locking script set by the UTXO looks like this:

OP_DUP OP_HASH160 <Public Key Hash> OP_EQUALVERIFY OP_CHECKSIG

The unlocking script the wallet will use to spend the funds looks like this:

<Signature> <Public Key>

Any node on the network that validates transactions will execute the scripts and verify the sender is indeed the rightful owner of the funds.

Segwit Transaction Scripts

Now that we’ve reviewed traditional P2PKH scripts and validation, it’s actually fairly simple to understand how segwit scripts operate. There are two big differences: the locking script uses a different format, and the location of the witness or unlocking script is outside of the transaction input!

First, let’s look at the locking script placed on an output sent to a segwit-compatible address:

<version> <pubkeyhash>

The segwit locking script simply pushes a version number (for example, OP_0 to the stack, followed by the public key hash. This serves two important purposes. Similar to a P2PKH transaction, it provides the hash of the address owner’s public key. But more interestingly, this functionally lets nodes that are not running a segwit implementation see the UTXO as “anyone can spend”, making the transaction backwards-compatible on the network.

The normal unlocking script would be in the scriptSig, but for segwit transactions, this field is actually left empty! Instead, an entirely new data structure called the witness is used. The witness contains the same data as a normal P2PKH scriptSig would though, so it’s pretty easy for us to understand:

<Signature> <Public Key>

The segwit BIP (Bitcoin Improvement Proposal) states that this script will be verified by simply checking the signature:

The signature is verified as

    <signature> <pubkey> CHECKSIG

Segwit Scripts – Same Idea, Different Data

Although segwit in its entirety is a complex topic, it’s fairly trivial to understand the difference in how scripts are implemented and how the corresponding transactions are validated. With every Bitcoin transaction, a user owns some UTXOs with a locking condition placed on them. When this user wants to spend some Bitcoin, they create a new transaction with a signature that satisfies that script, “unlocking” the currency by proving they are the rightful owner.

With P2PKH legacy transactions, this is done with a signature in the scriptSig field. With segwit, this unlocking signature is moved to a separate (“segregated”) data structure called the witness. The internal mechanisms of the Bitcoin implementation validates the signature with an OP_CHECKSIG similar to a normal transaction. And interestingly, the original locking condition allows backwards compatibility with old nodes on the network.

Inside Ethereum Transactions

Overview

Much like Bitcoin, Ethereum is a wildly popular cryptocurrency that allows its users to exchange value on a global, decentralized, censorship resistant platform. However, Ethereum goes beyond the capabilities of Bitcoin by adding a far more versatile scripting platform for the creation of “smart contracts” or “decentralized applications”.

In order to facilitate this, the Ethereum blockchain uses a different model for tracking ownership of funds than the Bitcoin blockchain. Bitcoin, Bitcoin Cash, Litecoin, and other popular currencies are UTXO based blockchains. Ethereum, however, uses an account based model. Let’s take a closer look at Ethereum’s model for dealing with address balances and transactions.

The Ethereum Model

UTXOs vs. Accounts

On the Bitcoin blockchain, exchanges between addresses are facilitated by consuming and creating “Unspent Transaction Outputs”, or UTXOs. When someone creates a transaction to send value to another address, their wallet looks for enough UTXOs to use an inputs for the transaction. Each UTXO used must be consumed in full, much like a dollar bill or cent coin in fiat money. The transaction is then constructed with outputs (new UTXOs) owned by the recipient. If there’s extra money that had to be consumed from input UTXOs, the user’s wallet will send change back to itself in the form of an output.

It’s just like going to the store and buying a $15 item with a $20 bill – you give the cashier the $20 and they give you $5 back in change. This UTXO model behaves remarkably similar to physical cash.

Ethereum, however, uses an account-based model that behaves much more like a traditional bank account. Each address is considered an “account”, and each transaction marks a change in state on that account. When an Ethereum transaction is created, the input account has a negative change in value (a withdrawal). The output account receives a positive change in value (a deposit). There’s no bills exchanged here, there’s simply an electronically recorded change in the state of the account’s balance.

Types of Ethereum Accounts and Transactions

The reason Ethereum uses an account model becomes more clear considering its more advanced scripting capabilities than Bitcoin. There are two different types of accounts in Ethereum: Externally Owned Accounts and Contract Accounts.

Contract accounts are created when a new smart contract is deployed on the network – these accounts are only controlled by the code of that contract. EOA accounts are the accounts we are focused on for understanding value transfers between individuals – when you give someone your Ethereum address or send to someone else’s, you’re dealing with Externally owned accounts.

This leads us to the few types of transactions in Ethereum. There’s transactions that deploy smart contracts by providing the contracts code to the network. There’s transactions that send messages to contracts in order to trigger execution. And finally, there are simple value-transfer transactions conducted between externally owned accounts. Again we are focused here on this type of transaction.

Inside an Ethereum Transaction

Now, let’s look a bit deeper at the transaction internals in order to fully understand how an Ethereum transfer works. Here’s an example of a simple value transfer between to addresses. I’ve simplified and reformatted this data grabbed from a block explorer API to make it easy to understand:

{ "transaction_id": "7959c9b9c9f0e949e6fa175d8b15d3bb464d31659f8c607d43b59c96e9bffe47",
  "total": 0.17703882,
  "fees": 0.00042000,
  "gas_limit": 21000,
  "gas_price": 0.00000002,
  "from": "fd7079c59b403759264d477c7b71105be0319de8"
  "to" : "e7e485512e0c2b7b21f7bad2d43fb83bce2886e4"
  "nonce": 0
}

Let’s discuss each piece individually:

  • Transaction ID – A hash of the transaction data that uniquely identifies the tx on the blockchain
  • Total – The amount of Ether transacted in total
  • Fees – Ether paid to the miner to incentivize the inclusion of the transaction in a block
  • Gas limit – Gas is a unit that describes the cost of each computational step when executing a transaction/contract. Each computation requires a certain amount of gas to execute, and this is the maximum amount of gas the transaction creator is willing to pay.
  • Gas price – The price per computation (like dollars per gallon of real-life gasoline)
  • From – The account sending the Ether, whose account balance will be reduced
  • To – The account receiving the Ether, whose account balance will be increased
  • Nonce – A value that increases for every transaction the sender completes from their account. It’s used to help track state over time and prevent double spends from an account.

Ethereum Transactions – Like Your Bank Account!

All in all, this model seems a bit simpler to understand than the BTC/BCH/LTC UTXO model, but it also facilitates more complex blockchain use since accounts can be used for everything from basic transfers to contract deployment and execution.

When Ethereum transactions are executed on the blockchain, what you’re really seeing is a change in the state of the address (account). The sending account has its balance reduced, and the receiving account has its balance increased, just like a bank transfer.

Other transaction components like fees and gas are also fairly intuitive – these are a premium paid by the sender to allow their transaction to be included in a block, and a premium paid for the privilege of using the miner’s computational power. Unlike a traditional bank, this system allows account transfers in a manner that doesn’t require any trust!

Wrong Address Woes – What Happens if You Send BCH to a BTC address (and vice versa)

Overview

In the early days of the Bitcoin Cash hard fork, several users encountered a very serious problem with their transactions. In what might be a simple misreading of an address or confusion over the distinction between these two currencies, users were sending their funds to addresses on the wrong blockchain.

Users found out that this was a simple mistake to make. Bitcoin and Bitcoin Cash share the same address space – so an address that’s valid on one is also valid on the other. And at the time, there was no formatting distinction between the two either. So all it took was accidentally copying an address that someone intended to be user for BTC, and suddenly a user was sending their BCH into the void (or so it seemed). The reverse could be true as well, with BTC (Bitcoin) being sent to an address intended to be used for Bitcoin Cash.

Let’s take a look a what actually happens when this mistake is made, and what some solutions to the problem are.

A Deeper Look at BTC/BCH Addresses

The Address Space and Private Keys

When looking at this problem, it is important to understand why Bitcoin and Bitcoin Cash addresses were easily confused, and why this problem would occur in the first place.

Bitcoin addresses are derived from 256 bit private keys using elliptic curve cryptography, coupled with some extra steps that make addresses easy to verify and encoding that makes them easier to deal with. When a Bitcoin address is generated, a random 256 bit number is generated. The public key is then derived using an elliptic curve algorithm (specifically secp256k1). The public key is hashed twice, once with SHA256 and then once with RIPEMD160. Finally, a version prefix and checksum are added and the whole address is encoded in base58.

Both Bitcoin and Bitcoin Cash used the exact same mechanism for generating addresses from the same exact pool of private keys. This offers up some good news with regards to dealing with this problem!

Cross-Chain Address Ownership

So if the mechanism for generating addresses is the same in BCH and BTC, then that means that the owner of a BTC address is also the owner of the exact same address on the BCH chain! The private key that the address was generated from proves ownership of the coins, and so the owner of the address will own coins sent to that address on either chain.

“Cross-Chain” Transaction Scenarios and Solutions

User sends BCH funds to their own BTC address

Let’s take a closer look at what happens when a user accidentally sends Bitcoin Cash to their own Bitcoin address. It is common for users to send their own funds between different wallets, like purchasing on an exchange with a custodial system and sending funds to a wallet where they control the private keys.

When the user broadcasts this transaction, it is processed entirely by the Bitcoin Cash network. Even though this user’s address came from their Bitcoin (BTC) wallet, nothing happens on the Bitcoin chain because these are two entirely different systems.

However, the BCH had to go somewhere! It may seem that it has been lost, but in reality it is now owned by the user’s address on the Bitcoin Cash blockchain.

It is likely that our friend is panicking because they don’t see the funds showing up in their Bitcoin Cash (BCH) wallet like they intended. However, they do own the money and just need to claim it!

Since the address spaces are the same between chains, our user has the private key that controls this Bitcoin Cash. All they need to do is export the private key from their Bitcoin wallet and import it into their Bitcoin Cash wallet, and the wallet will now recognize the funds as part of their BCH balance.

Further Complications

Thankfully in this situation, the mistake is a simple fix. The user controls the private key for the address they mistakenly sent their funds to, and so they have retained control of the funds the entire time. However, if a user sends funds to someone else’s BTC address, they will have to explain this process to the (hopefully known) recipient and hope they will be generous enough to send the BCH funds back to our friend. If the owner of the address cannot be contacted in the real world, our friend is entirely out of luck.

The activation of segwit (segregated witness) on the Bitcoin (BTC) network further complicates things. The above process only holds true for simple P2PKH transactions. If Bitcoin Cash is sent to a Segwit BTC address, the funds cannot be recovered on the BCH blockchain because these address types are not supported on the network

The CashAddr Format

Thankfully, the developers in the Bitcoin Cash ecosystem have created a new address format unique to BCH that is easily distinguishable from legacy Bitcoin addresses. A base58check encoded BTC address (non-segwit) looks like this:

1LxWuAJLENgSpQic736V3ZxmRVJp44uGZV

Whereas a base32 CashAddr BCH address looks like this:

qrnzx44wf8swjl2v9c36jcmch7a4yefkav0z4rxm8g

It is now much harder to make the same mistakes when dealing with addresses thanks to this format

Wrong Address? Not All Hope Is Lost!

Once we understand that Bitcoin and Bitcoin Cash share the same address space (and therefore private key space), it is a bit less scary to deal with this problem of “cross-chain” transactions. No transaction is really cross chain, it is simply sent to the mistaken address on the chain you sent it from. So, if you control the private keys for an address on one chain, you can easily claim funds you mistakenly sent to that address on the other. If you send BCH to your BTC address, you simply need to import that private key in your BCH wallet to claim the funds.

There are complications due to segwit and further problems for addresses our user doesn’t own. These are a reminder to always exercise caution when creating cryptocurrency transactions, as mistakes are often costly and irreversible. However, new formats like CashAddr have made these mistakes harder to make, so hopefully you never have a need to recover funds in the first place!