Blockchain Tutorial: Write a message to the Bitcoin Blockchain

March 21, 2016 0 Comments tutorial, blockchain

Blockchain Tutorial: Write a message to the Bitcoin Blockchain


Blockchain Tutorial: Send data to the Blockchain with Javascript

Today, we're going to write a very simple script that we will use to write a letter on the Blockchain. Bitpay open-sourced their Bitcore library, and that's what we'll be using today. If you aren't familiar with how to get NodeJS up and running on your machine, you should check out this tutorial:

http://howtonode.org/how-to-install-nodejs

This Blockchain tutorial will use a Bitpay Javascript library that will allow us to interact and make Bitcoin transactions without downloading the full Blockchain which can take days to download.

Digital ink and the World Wide Spreadsheet

Think of Bitcoin and the Blockchain like the new paper and pen. In order to write on the "paper" (Blockchain) you need ink. And the "ink" in this analogy are the Bitcoin you use to create transactions. The data that we write inside a transaction are called a "OP_Return". An OP_Return is a opcode, and the message you write inside is like writing a message in digital ink on a world wide spreadsheet.
OP_Returns are limited to 40 characters. That's little less than a 1/3 of a Tweet! Still, with 40 characters, you can store some interesting data. Think of apps that can show chain of custody, proof of purchase, or new ways of digitally notarizing documents or inventions.
When you create a transaction on the Blockchain, it's broadcast across thousands of computers across the world running the Bitcoin software, so the OP_Returns in those transactions are also distributed across the network in a few seconds. Once the data is written, it's impossible to alter it.
This changes the way we can create apps, because we can be sure that after the transaction has been created, it hasn't been altered in any way. Also, data can be verified by anyone with access to the Blockchain. All they need is the right transaction ID.

So, let's get started! In this example, we'll show how to write a short message the Blockchain.

Bitpay open-sourced their "Bitcore" project, which allows us to explore the Blockchain and create Bitcoin transactions.
First open up the command line and create a folder for our Blockchain tutorial:

~ mkdir 'HelloWorld'

Now, let's go into that folder we just created:

~ cd HelloWorld

We're going to need two libraries for this tutorial, "bitcore" and "bitcore-explorers", we can install them both with one command:

sudo npm install bitcore@0.13.0 && sudo npm install bitcore-explorers

Nice! We're on our way. To make sure it got installed correctly, you can enter "ls" (shorthand for "list") in the command line. You should see one folder, called node_modules.

➜ HelloWorld ls

node_modules
Ok let's open up a text editor and start coding. Create a new file called "HelloWorld.js". Then, we need to tell our script to grab the Bitcore modules we got from NPM above:

var bitcore = require('bitcore');
var explorers = require('bitcore-explorers');

Ok, our script knows about Bitcore, so let's initiate the bitcore-explorers library by calling a function called Insight():

var insight = new explorers.Insight();

Create a Bitcoin Wallet

So the goal here is to send a small amount of Bitcoin from one address to another. That means we'll need two things; a Bitcoin recipient address, and a Bitcoin address the we have full control over.
The first part is easy, we can send money to any Bitcoin address we want. The second part is a little more tricky, and I'll do my best to explain how a Bitcoin address is created.
Bitcoin is based on private and public keys. You create your public key by creating a SHA-256 hash of your private key. So, how do you create a private key?
There are many ways to do it, but for simplicity we'll generate a practice wallet using RushWallet.com. This is not a recommended solution for storing Bitcoin long-term, but for this tutorial, it's the perfect tool. Follow these steps:
Go to RushWallet.com
Create Wallet by moving mouse around on the screen.
After your wallet is created, you will see your public address under the text "Your Bitcoin Address". Copy that and store it in our HelloWorld.js file as the variable "publicAddress".
On RushWallet.com click the settings icon (second to last button on the right) and select the "Export Keys" link. Then copy your private key into our HelloWorld.js script as the variable "privateKey".

That's all you need to do to continue to the next step. Your script should now look like this:

var bitcore = require('bitcore');
var explorers = require('bitcore-explorers');
var insight = new explorers.Insight();

var publicAddress = '1DuFRRFEJvchWpTQiDqMk3DW3mP9XZ3UTa';
var privateKey = '5KG7bZhGX5jaCD46cxbN1tX6nq1zSa4gAZ4baKmw277RKGbH3qc'

For this example we'll send the Bitcoin to this address 1HLoD9E4SDFFPDiYfNYnkBLQ85Y51J3Zb1, which is Satoshi's first Bitcoin wallet. Create a variable called "bitcoinRecipient" and set it equal to this address or any other address you'd like.
We have to set two more variables before we get to the fun stuff, and they're pretty easy. The first is the miner fee, which is the price we pay to send the transaction to the Blockchain. If Bitcoin and the Blockchain are pen and paper, the miner's fee is the stamp that let's us send a letter to our friends.

var minerFee = 667;

(The minimum amount to pay is 667 satoshis, and that's what we'll use in this example. The higher the miner's fee, the faster it will get broadcast around the Blockchain. 100,000,000 satoshis == 1 Bitcoin)
Next, we'll write our message to the Blockchain:

var blockchainMessage = 'Hello Satoshi!';

Check Bitcoin Address Info
Send a penny to your test address, and let's check out the balance of our public address:

var bitcore = require('bitcore');
var explorers = require('bitcore-explorers');
var insight = new explorers.Insight();

var publicAddress = '18JYiBktnAzbS2sEZSrdKgSEFwLjXvW9Uy';
var privateKey = '5HxKWX4pkze3AiB4yWrdZKMYrf9hWYdAVp3TnkpYMiGbxnLuLWN'

insight.getUnspentUtxos(publicAddress, function (error, utxos) {
console.log('utxos' + ' :' + JSON.stringify(utxos, undefined, 2));
});

You should see something similar to this response:

utxos :[
    {
    "address": "18JYiBktnAzbS2sEZSrdKgSEFwLjXvW9Uy",
    "txid": "6c2e97cd10906ad89fdd10c1f068fc20ecc709a9dcc152dab1d7a2c7118a4158",
    "vout": 1,
    "scriptPubKey": "76a914501a6c0e1e7030100a9a3cdc14b906760fc45bb388ac",
    "amount": 0.000042
    }
]

When we look up an addresses UXTO's (Unspent Transaction Outputs), we're can see how much Bitcoin are in this wallet. This next snippet of code checks if our wallet has enough Satoshis to cover the miner's fee:

if (bitcore.Unit.fromBTC(utxos[0].toObject().amount).toSatoshis() - minerFee > minerFee)     {
    console.log("We've got enough Satoshis!");
}

If you get an error message, that means your wallet doesn't have enough to cover the miner's transaction fee. If this happens to you, send a few more cents to the address.
If you got the console message above, that means we can sign and broadcast the transaction.

Signing and Broadcasting Transactions

Sending Bitcoin from point A to point B, at a very high level, is like signing a digital check. Only your "autograph", which is a number generated by a combination of your private key and past UXTO's can send money from a Bitcoin address.
This digital check can be written out to any Bitcoin address, and the OP_Return field will act like a memo on the check would, a quick note attached to the transaction. Side note: All of Satoshi's wallets combined most likely have hundreds of millions of dollars in them, and they're all secured by a long string of numbers and letters. Pretty cool!
Once the transaction is signed, we need to tell the Blockchain about it. Bitcore is doing most of the heavy lifting here, but behind the scenes what's happening is the transaction is being verified by the latest version of the spreadsheet, ensuring that you're sending money you actually control. Once verified, the miners will record your transaction, and it will be publicly view it on the Blockchain, along with anyone, or anything in the world.
Here's the code snippet that signs and broadcasts the transaction. We'll use some of the variables we created earlier to do this:

// Sign the transaction with a combo of your private key, the address you want to pay, and your last UXTO.

insight.getUnspentUtxos(publicAddress, function (error, utxos) {
console.log('utxos' + ' :' + JSON.stringify(utxos, undefined, 2));
if(utxos.length == 0) {
    console.log("Not enough Satoshis to cover the miner fee.");
    return
} else if (bitcore.Unit.fromBTC(utxos[0].toObject().amount).toSatoshis() - minerFee > minerFee)     {
    console.log("We've got enough Satoshis!");

    var transaction = new bitcore.Transaction()
        .from(utxos[0]) // using the last UXTO to sign the next transaction
        .to(bitcoinRecipient, 4200 - minerFee) // Send 4200 Satoshi's
        .addData(blockchainMessage) // Our message to Satoshi
        .sign(privateKey); // Last step for the digital autograph

    console.log('transaction_hex: ' + transaction.checkedSerialize());

    insight.broadcast(transaction, function (error, body) {
        if (error) {
            console.log('Error in broadcast: ' + error);
        }
        else {
            console.log("Success! Here's our Transaction ID: " + body);
            console.log('http://explorer.chain.com/transactions/' + body + "#!transaction-op-return")
        }
    });
  }
});

After you add that to your script, open up your terminal and type:

node HelloWorld.js

If you get an error, make sure you're in the correct folder!
Assuming you had enough cash in your wallet to cover the miner fee, you should get a console message with a URL to check your message on the Blockchain. We're using http://explorer.chain.com/ to search, but any other Bitcoin search engine will work too.
Check out an example here:
https://live.blockcypher.com/btc/tx/c6aabd49ea7f06a02a9100feea037b752b46539d784ae3d0a288ab45aec4ec9c/

Here's the full script:

var bitcore = require('bitcore');
var explorers = require('bitcore-explorers');
var insight = new explorers.Insight();

var publicAddress = '1DuFRRFEJvchWpTQiDqMk3DW3mP9XZ3UTa';
var privateKey = '5KG7bZhGX5jaCD46cxbN1tX6nq1zSa4gAZ4baKmw277RKGbH3qc'

var bitcoinRecipient = '3BuMGCRby5xeu2tB8p4iok8pAmw9abHWoA'

var minerFee = 667;
var blockchainMessage = 'Hello Satoshi!';

insight.getUnspentUtxos(publicAddress, function (error, utxos) {
console.log('utxos' + ' :' + JSON.stringify(utxos, undefined, 2));
if(utxos.length == 0) {
    console.log("Not enough Satoshis to cover the miner fee.");
    return
}
else if (bitcore.Unit.fromBTC(utxos[0].toObject().amount).toSatoshis() - minerFee > minerFee)     {
    console.log("We've got enough Satoshis!");
    var transaction = new bitcore.Transaction()
        .from(utxos[0]) // using the last UXTO to sign the next transaction
        .to(bitcoinRecipient, 4200 - minerFee) // Send 4200 Satoshi's
        .addData(blockchainMessage) // Our message to Satoshi
        .sign(privateKey); // Last step for the digital autograph
    console.log('transaction_hex: ' + transaction.checkedSerialize());
    insight.broadcast(transaction, function (error, body) {
        if (error) {
            console.log('Error in broadcast: ' + error);
        }
        else {
            console.log("Success! Here's our Transaction ID: " + body);
            console.log('http://explorer.chain.com/transactions/' + body + "#!transaction-op-return")
        }
    });
   }
});

(How you should feel after sending your first message to the Blockchain.)

Conclusion

Congratulations, you've written your first transaction on the Blockchain! After completing this Blockchain tutorial, it will remain there forever, like the first footprints on the moon. I'm sure Satoshi will be happy when your letter is read, and I hope you will continue on your journey in the Blockchain. There is still a lot to learn about this subject, so I hope you'll check out the other tutorials here and around the web.

The Self-driving taxis, digital democracies and food-delivery drones of the future could benefit from a network that can read, trust and more importantly react to changes on the Blockchain. It's up to you to make experiences that are worth taking the jump into this new world, so get out there and make it happen! Don't worry this is just the beginning - we got another Bitcoin Blockchain tutorial in the lab, and we'll keep releasing a new one every week, so check back soon.

See you on the Blockchain,

Mike G

(P.S If you have an idea for a Blockchain tutorial, leave a comment below and I'll look into it!)

1NmMKNHtj5ct3zKBuCr6MTjgKkVmPk2Xnp is where you can send a few Satoshis if you want to supoort Blockchain Pie!

Blockchain Tutorial: Write a message to the Bitcoin Blockchain


Tag cloud