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!

Full Node Friends – Understanding and Running A Fully Validating Wallet

Overview

In previous tutorials, we’ve discussed the basic differences between a full node wallet and an SPV or Simplified Payment Verification wallet. Now let’s take a further look into why full nodes are important to cryptocurrency networks, and how you can get started running one!

Why Full Nodes?

Full nodes, along with mining nodes form the backbone of cryptocurrency and smart contract networks like Bitcoin and Ethereum. These wallets have several important characteristics that help secure these networks and ensure they remain decentralized. This is not to detract from the importance of SPV wallets for adoption and convenient day-to-day use! Simplified wallets allow users to quickly and efficiently onboard to the world of crypto, but those aren’t the focus of this discussion.

So what makes full nodes so special and important for Bitcoin and other decentralized forms of money? The first critical characteristic of full nodes is that these wallets store the entire blockchain. Unlike SPV wallets which only store data relevant to the wallet user’s addresses, full node wallets download and process the whole blockchain database. There are some special methods the software uses to prune out unnecessary data, but at a high level we can say that these wallets store every transaction ever recorded in the history of Bitcoin, Litecoin, etc.

Now why is this data-intensive act of storing the whole blockchain necessary and valuable? It’s important because full nodes validate every single transaction in the blockchain. And in doing so, they ensure everyone is following the rules! By processing all the transactions up to and including the current block, wallets ensure that transactions are cryptographically sound, and therefore no one is trying to falsify ownership of any currency. If a single transaction in the history is off, the cryptography won’t be correct and the node will not recognize this fake version of the blockchain.

By rejecting bad blocks, full nodes help tell other parties on the network that something is up…and other nodes in turn will not allow shenanigans to occur. Bitcoin and other digital currencies are decentralized because anyone on the network can run a fully validating node and help make sure everyone is following the rules. If someone tries to fake a transaction (give themselves more money, re-spend money they’ve already spent, etc.), nodes on the network will refuse to accept this false version of history. And if nodes reject the malicious transaction, the bad actor effectively can’t spend that money!

Full nodes are just like cashiers who are trained to recognize counterfeit $100 bills. The know what a fake bill looks like, and they won’t let you spend it. But taking the analogy a bit further, a full node is a cashier that won’t take your fake money and also tells everyone else around them that your money is no good.

How to Run A Full Node

General Setup

Fortunately, running a full node is extremely easy. All you need is a computer with a decent internet connection, plenty of hard drive space, and the right software.

Almost all cryptocurrencies list their full node implementations as top recommended wallets. For example, bitcoin.org recommends running the Bitcoin Core client for Bitcoin (BTC).

Once you download and install the full node, you’ll need to wait for the initial download of the blockchain to complete. This does require some patience, as the most popular cryptocurrency blockchains exceed 100 GB in size at the time of this writing. On a 250Mbps connection, my node was able to sync the Bitcoin Cash blockchain overnight.

Once this initial sync is complete, your node will continually download and broadcast blockchain data and validate that all of the consensus rules of the currency are being followed!

Bitcoin Cash Nodes

For Bitcoin Cash (BCH), I’m trying out the Bitcoin ABC implementation. I installed this via the Ubuntu package manager aptitutde:

sudo add-apt-repository ppa:bitcoin-abc/ppa
sudo apt-get update
sudo apt-get install bitcoind bitcoin-qt

Once installed, simply open up the Bitcoin ABC software and follow some initial setup prompts. None are technical or complicated. Again, the blockchain will take some time to sync but your full node is up and doing its thing!

Ethereum Full Nodes

For the smart contract network Ethereum, geth is the client of choice. geth is just as simple to install, but is a bit less user friendly in terms of interface. The quickest way to start it is to run via the command line. To install:

sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo add-apt-repository -y ppa:ethereum/ethereum-dev
sudo apt-get update
sudo apt-get install ethereum

And to start the client:

geth account new
geth

Be a Full Node Friend

Fully validating nodes are an important part of cryptocurrency networks. They help keep these digital currencies secure and decentralized by ensuring that all transactions on the network follow the rules. No one can falsify transactions with thousands of full nodes watching, and because anyone can help ensure the rules are being followed, there is no need for central authorities to maintain trust.

And thankfully, running a full node is pretty easy to do. If you have the resources and desire, consider being a “full node friend” on the currency network of your choice – you’ll be keeping digital money secure for everyone!

Don’t Just Hodl, Spedn! – Cool Ways to Use Your Cryptocurrency

Overview

The “hodl” meme in the cryptocurrency world has gotten out of hand. With dreams of lambos abound, it seems everyone is just sitting around with fat crypto wallets waiting for the next big jump in price.

Now, there is absolutely nothing wrong with savings. I wouldn’t tell you to spend all your fiat either, and it’s always great to have money set aside for the future. But when it comes to cryptocurrencies, we’re doing the community a disservice by focusing too much on the price.

Bitcoin and all of its descendents are meant to be digital cash! We’re in the era of the most fascinating way to exchange value ever created, so let’s not sit on our crypto-assets like they’re a couple of boring old gold bars.

Why Spend Cryptocurrencies?

So why should you spend some of your digital assets? I always go back to the unique properties of cryptocurrencies that make them so interesting in the first place. Currencies like Bitcoin Cash, Litecoin, Ethereum, and (to some extent) the original Bitcoin Core chain are:

  • Secure
    • Crypto transactions are push transactions, so you never have to reveal personal information to a merchant like you do with a credit card.
  • Global and decentralized
    • These networks run worldwide without borders. Purchase goods, donate, and share with anyone anywhere without asking anyone’s permission
  • Low barrier
    • There is no KYC requirements, no paperwork, no approvals – download the wallet software and you now have a bank in your hands
  • Low fee
    • With the exception of the Bitcoin Core chain, you can send anyone any amount of money for a penny or less. And your fee isn’t going to a middleman, it’s going to support the network!

The Fun Part – How to Spend Cryptocurrencies

Purchasing Goods and Services

There are tons of merchants that will accept the most popular cryptocurrencies, especially online. I’ve bought several interesting items with various digital currencies – A JavaScript reference book for my shelf, T-shirts that share my love of Bitcoin, and even special apparel for Brazilian Jiu Jitsu.

Check out websites like Accept Bitcoin Cash or SpendBitcoins for ideas on where you can trade digital money for real-world goods.

Donate to your Favorite Organizations

Cryptocurrencies are great for donations as they make it so easy to send money quickly. Just snap a picture of a QR code address and your charitable contribution is on its way.

I’m a big fan of free and open source software, so I’ve sent tips to other developers and software projects I find useful.

Share it with Friends

Once again, the barrier to entry for digital currencies is low. Do you have crypto-curious friends? Have them download your favorite mobile wallets and send them a dollar or too. It’s simple and you may make a new crypto enthusiast for life!

After my recent lecture at Saint Vincent College, I was able to send a dollar a piece to several students by just instructing them to download a BCH wallet and snapping a picture of their QR code addresses. Crypto sharing is caring.

Spedning is Fun!

Sure, it’s easy to acquire cryptocurrencies and forget about them, stashing funds for a rainy day or big price spike. But the beauty of Bitcoin and its peers is the ability to exchange money in a way we’ve never done before. Adoption will be key for the future of digital money, and it’s quite easy and fun to participate in the economy.

Hodl some, spedn some. The crypto community thanks you.

Understanding Address Balances for UTXO Blockchains

Overview

When you open your Bitcoin, Bitcoin Cash, or Litecoin wallet, you’ll see a balance just like you do when you open your bank app. At the end of the day, you just want to know how much currency you own, right?

You may be curious, however, how your total balance is calculated in the world of cryptocurrencies. With your local bank, a centralized authority (the bank itself) keeps track of the state of your account as one unit. The bank tracks deposits and withdrawals, and keeps a running tally of your available balance for you.

The Bitcoin blockchain, however, does things a little differently. This blockchain (and the BCH and LTC blockchains, to name a few others) use a concept called the UTXO to deal with available balances. If that sounds completely foreign, don’t fret. It turns out UTXO-based chains function quite like the physical cash in your wallet!

UTXOs explained

What is a UTXO?

An unspent transaction output, commonly referred to as a UTXO is a chunk of cryptocurrency that is owned by a user’s wallet and available for the user to spend. More specifically, a UTXO is owned by a particular address in the user’s wallet, and therefore the associated private key.

A raw UTXO looks something like this when pulled from a block explorer API:


{
"txid": "2e2a921b819c261822dfa0931523a54b0c8900182c20d4be25ff333982a8f76a",
"amount": 0.10401187,
"confirmations": 306
}

This UTXO is pulled from the bitcoin.com REST API, with some bits of data removed for simplification. If you want to try querying this yourself, you can opening this API call in your browser.

Deciphering UTXO data

Now let’s look a little closer at this UTXO. The first data field that we see is the txid, which is a long string of data that looks meaningless. This data is the hash of the transaction that created this UTXO. In other words, this particular transaction sent money to this address.

The second item is fairly self explanatory: this is the Bitcoin amount sent to the address in this UTXO.

Finally, the number of confirmations indicates how many times a new block has been added on top of the block containing this transaction. The more confirmations, the more “sure” we can be that this transaction is a permanent part of blockchain history and owned by the address.

How do UTXO’s function?

UTXOs function in a way that is remarkably similar to physical cash. Think of a UTXO like a five dollar bill in your wallet.

A UTXO is a bill available for you to spend in a future Bitcoin transaction. Let’s say your grandma sent you $5 in a card for Christmas. You now have $5 in your wallet ready to use when you go to the store.

Much like dollar bills, UTXOs must be spent entirely in a new transaction. If you go to the store to buy a bag of chips and a drink for $2.50, you cannot tear the $5 bill in half and give it to the cashier, can you? You give the person the entire bill, and get $2.50 back in change.

Bitcoin UTXOs function in the exact same way in a transaction. If you have a UTXO your address owns for 0.1 Bitcoin and you want to send your friend 0.05 Bitcoin, your wallet will create a transaction that sends their address 0.05 BTC in a new UTXO, and sends 0.05 back to your address in change!

UTXO’s and Your Wallet Balance

Now that we understand how UTXOs work, understanding how your wallet tracks your balance is pretty straightforward! Your wallet contains a bunch of private keys and a bunch of addresses derived from those keys. Each address can have a bunch of UTXOs associated with that address, and your wallet balance is the sum total of all those UTXOs. It’s that simple. Just like you may have some 1’s, 5’s, and 20’s in your physical wallet, your Bitcoin wallet can have a bunch of UTXOs in any denomination of Bitcoin.

When you go to send Bitcoin to another user, your wallet bundles up as many UTXOs as it needs to create a transaction in that amount and uses them as “inputs” for that transaction. Unlike physical cash, however, your wallet can turn your $5 and $10 UTXOs in to a fresh $20 bill.

What’s in your (Bitcoin) wallet? UTXOs of course!

Again, UTXOs are the dollar bills of the Bitcoin world. Blockchains based on this model include popular digital currencies such as Bitcoin Core, Bitcoin Cash, and Litecoin. Other popular currencies such as Ethereum use an account based model that functions more like a traditional bank account, tracking inputs, outputs, and balances as state changes over time. The good news is, understanding the slightly more complex UTXO model is fairly trivial with a good analogy, and this model functions like the cash we use every day.

If you have a Bitcoin Cash address, you can try viewing your UTXO “dollar bills” yourself using a project I created for this purpose. This project features an API that digests raw blockchain data and outputs an easy to understand format so you can learn these concepts. On top of the API, there’s a nice and simple React frontend that formats the data in a table. The code is available on Github, and if you visit https://jmcintyre.net/sites/myaddrbal_client/ you can try it for yourself! Here’s an example with one of my BCH addresses used above:

Happy crypto learning!

(Bitcoin) Script Kiddies – Understanding Basic Transaction Scripts

Overview

In the Bitcoin world, money is not just digital – money is programmable! When transactions between users on the network are created and broadcast, miners and nodes independently verify that these transactions are valid. But this verification is not just checking some basic data points – it involves the execution of special scripts specified in the transaction parameters.

Script Basics

The Bitcoin Scripting Language

Before we can understand how basic Bitcoin scripts operate, we need to know a little bit about the scripting language itself. Unlike common scripting languages such as Python and Bash, the Bitcoin scripting language is quite limited and fairly simple in its execution. “Script” is stack based, meaning data is stored on an execution stack and script operators “push” and “pop” data from this stack. As well, Script is not Turing complete. There are no functions for looping or jumping around in the order of script execution. Operations are completely linear from the beginning of execution to the end. This keeps scripts secure, as it is not possible to tie up machines executing the scripts with an infinite loop.

Some operators are general, but most are specific to the cryptography of Bitcoin. Operators such as OP_ADD, OP_SUB, OP_DUP are pretty self explanatory – they make it possible to add, subtract, or duplicate data on the stack. Operators such as OP_HASH160 are more specific to the way Bitcoin operates – this operator takes the top item on the stack, hashes it using SHA-256 and then RIPEMD160, and finally pushes the result back on to the stack.

Common Bitcoin Script Mechanics

Pay to Public Key Hash (P2PKH) Script Basics

Finally, we need to understand a bit about how scripts are formed by discussing the basics of transactions. When a user “receives” Bitcoin in a transaction, they don’t just have a “bank account” balance on the blockchain. Rather, the blockchain stores what are called unspent transaction outputs associated with a user’s address. These outputs specify a locking condition that must be satisfied in a script when the user tries to spend that output in a future transaction. When the user creates a new transaction with that UTXO, they specify an unlocking script that satisfies that locking script

The most common form of script on the Bitcoin network is called Pay to Public Key Hash. With this type of script, the locking script requires that the user provide their public key and a digital signature formed with transaction data and their private key. This public key and digital signature will “satisfy” the locking script. When this unlocking script is combined with the UTXO locking script and executed, the final result on the Script stack should be true, meaning that the user can spend the Bitcoin.

P2PKH Formation

For a P2PKH script, the locking script specified by an unspent transaction output looks like this:

OP_DUP OP_HASH160 <Public Key Hash> OP_EQUALVERIFY OP_CHECKSIG

The unlocking script provides the user’s signature and public key in order

<Signature> <Public Key>

In order to verify that the user owns the Bitcoin they wish to spend, a node verifying this transaction will append the locking script to the unlocking script and then execute it:

<Signature> <Public Key> >OP_DUP OP_HASH160 <Public Key Hash> OP_EQUALVERIFY OP_CHECKSIG

Script Execution

Now let’s walk through how this P2PKH script executes.

<Signature> <Public Key> OP_DUP OP_HASH160 <Public Key Hash> OP_EQUALVERIFY OP_CHECKSIG

First, the signature and public key specified by the unlocking script are pushed on to the stack:

STACK: <Signature> <Public Key>

Next, OP_DUP pushes a copy of the top item on to the stack:

STACK: <Signature> <Public Key> <Public Key>

OP_HASH160 will pop the top stack item and hash it using SHA-256, and then RIPEMD160. Once the hashing operations are complete, the result is pushed on to the stack:

STACK: <Signature> <Public Key> <Public Key Hash>

The user’s public key hash (a data item) specified by the locking script is pushed on to the stack:

STACK: <Signature> <Public Key> <Public Key Hash> <Public Key Hash>

OP_EQUALVERIFY now pops the top two stack items and checks that they are equal. If they are equal, execution continues. If the comparison fails, script execution exits with a failure.

STACK: <Signature> <Public Key>

OP_CHECKSIG now verifies that the signature is valid against the public key specified. An elliptic curve digital signature is created using a private key and a specific message, and any user with that message and public key can verify that the signature is valid without knowing the private key! Note that the message is not a part of the script, but is garnered from the overall transaction data. If the signature is valid, OP_CHECKSIG pushes true on to the stack.

STACK: true

Any Bitcoin script that ends with just true on the stack indicates a valid transaction. The user that created this transaction to spend some currency is in fact the rightful owner of the unspent output they want to use.

Bitcoin Scripts – Simple But Powerful

For someone with programming experience and some computer science background, Bitcoin scripts are generally straightforward to understand since the language is limited and Turing incomplete. Understanding P2PKH scripts requires just a working knowledge of stack data structures and commonly used cryptographic algorithms, but no higher level programming constructs. Now you know what goes on when you send your friend some money from your Bitcoin wallet!

However, the beauty of programmable money is the power to create transactions beyond the normal flow of “Alice sends Bob some cash”. Script opens up the possibility of things like multi-signature transactions, time locked spending, and more!