Raspberry Pi Counts Down to the Last Bitcoin

Even though it might appear to be pretend Internet money, by design, there are a finite number of Bitcoins available. In the same way that the limited amount of gold on the planet and the effort required to extract it from the ground keeps prices high, the scarcity of Bitcoin is intended to make sure it remains valuable. As of right now, over 80% of all the Bitcoins that will ever exist have already been put into circulation. That sounds like a lot, but it’s expected to take another 100+ years to free up the remaining ones, so we’ve still got a way to go.

Even though his device will probably no longer exist when the final Bitcoin hits the pool, [Jonty] has built a ticker that will count down as the final coins get mined from the digital ground. The countdown function is of course a bit tongue-in-cheek, but the gadget also shows slightly more pertinent information such as the current Bitcoin value, so you can always remember what a huge mistake it was not to invest while they were still worth pennies.

On the hardware side, this is a pretty simple project. The enclosure is laser cut 5 mm MDF, and it holds a Raspberry Pi 3, a MAX7219 32×8 LED dot matrix display, and a 10 mm white LED with accompanying resistor. The white LED is placed behind an acrylic diffuser to give the Bitcoin logo on the side of the display a soft pleasing glow when the device is powered up. There are no buttons or other controls on the ticker, once the software has been configured it just gets plugged in and away it goes.

As for the software, it takes the form of a Python script [Jonty] has created which uses Requests and Beautiful Soup to scrape the relevant data from bitcoinblockhalf.com. The script supports pulling any of the 19 variables listed on the site and displaying it on the LED matrix, which range from the truly nerdy stats like daily block generation to legitimately useful data points that anyone with some Bitcoin in their digital wallets might like to have ticking away on their desks.

The first decade of Bitcoin has been a pretty wild ride, not only monetarily, but in the wide array of hardware now involved in cryptocurrency mining and trading. From Bitcoin traffic lights to custom-made mining rigs that are today more useful as space heaters, it takes a lot of hardware to support these virtual coins.

Continue reading “Raspberry Pi Counts Down to the Last Bitcoin”

Now That’s What I Call Crypto: 10 Years of The Best of Bitcoin

On January 3rd, 2009, the Genesis Block was created. This was the first entry on the Bitcoin blockchain. Because of the nature of Bitcoin, all transactions lead back to this block. This is where Bitcoin began, almost exactly ten years ago.

The Genesis Block was created by Satoshi, a person or persons we know nothing about. In the decade since, we’ve seen the astonishing rise and meteoric descent of Bitcoin, and then it happened again after the bubble was re-inflated.

Due to the nature of Bitcoins, blockchains, and ledgers, the entire history of Bitcoin has been recorded. Every coin spent and every satoshi scrupled has been recorded for all to see. It’s time for a retrospective, and not just because I wanted to see some art based on the covers of Now That’s What I Call Music albums. No, ten years is a lot of stories to tell.

Continue reading “Now That’s What I Call Crypto: 10 Years of The Best of Bitcoin”

What Can The Blockchain Do For You?

Imagine you’re a general, camped outside a fortified city with your army. Your army isn’t strong enough to take the city without help. But you do have help: camped on other hills outside this city are a half dozen more generals, with their armies ready to attack. Attacking one army at a time will fail; taking this city will require at least three or four armies, and an uncoordinated attack will leave thousands dead outside the city gates. How do you coordinate an attack with the other generals? Now, how do you coordinate your attack if one of those other generals is Benedict Arnold? What happens when one of the generals is working with the enemy?

This situation is a slight rephrasing of the Byzantine Generals Problem, first presented in the ACM Transactions on Programming Languages and Systems in 1982. It’s related to the Two Generals Problem formulated a decade prior. These are the analogies we use when we talk about trust over a communications channel, how hard it is to transmit knowledge, and how to form a consensus around imperfect facts.

This problem was upended in late 2008 when Satoshi Nakamoto, a person or group of people, published a white paper on the ‘block chain’. This was the solution to double-spending in digital currency. Think of it as having a digital thing that only one person could own. As a test of this block chain technology, Bitcoin was launched at the beginning of 2009. Things got more annoying from there.

Now, blockchain is at the top of the hype cycle. Every industry is looking at blockchain tech to figure out how it will work for them. Kodak launched their own blockchain, there are proposals to use the blockchain in drones and 3D printers. Medical records could be stored on the blockchain, HIPAA be damned, and there’s a blockchain phone, for reasons. This doesn’t even cover the massive amount of speculation in Bitcoin itself; thousands of other cryptocurrencies have also sprung up, and people are losing money.

The blockchain is a confusing thing, with hashes and Merkle trees and timestamps. Everyone is left asking themselves, what does the blockchain actually do? Is there an independent body out there that will tell me what the blockchain is good for, and when I should use it? You’re in luck: NIST, the National Institute of Standards and Technology released their report on blockchain technology (PDF). Is blockchain magic? No, no it is not, and it probably shouldn’t be used for anything other than a currency.

Continue reading “What Can The Blockchain Do For You?”

RGB Sensor’s New Job: Cryptocurrency Trade Advisor

[XenonJohn] dabbles in cryptocurrency trading, and when he saw an opportunity to buy an RGB color sensor, his immediate thought — which he admitted to us would probably not be the immediate thought of most normal people — was that he could point it to his laptop screen and have it analyze the ratio of green (buy) orders to red (sell) orders being made for crypto trading. In theory, if at a given moment there are more people looking to buy than there are people looking to sell, the value of a commodity could be expected to go up slightly in the short-term. The reverse is true if a lot of sell orders coming in relative to buy orders. Having this information and possibly acting on it could be useful, but then again it might not. Either way, as far as out-of-left-field project ideas go, promoting an RGB color sensor to Cryptocurrency Trading Advisor is a pretty good one.

Since the RGB sensor only sees what is directly in front of it, [XenonJohn] assembled a sort of simple light guide. By enclosing the area of the screen that contains orders in foil-lined cardboard, the sensor can get a general approximation of the amount of red (sell orders) versus green (buy orders). The data gets read by an Arduino which does a simple analysis and sends alerts when a threshold is crossed. He dubbed it the Crypto-Eye, and a video demo is embedded below.

Continue reading “RGB Sensor’s New Job: Cryptocurrency Trade Advisor”

Hackaday Links: June 3, 2018

All the Radio Shacks are dead. adioS, or something. But wait, what’s this? There are new Radio Shacks opening. Here’s one in Idaho, and here’s another in Claremore, Oklahoma. This isn’t like the ‘Blockbuster Video in Nome, Alaska’ that clings on by virtue of being so remote; Claremore isn’t that far from Tulsa, and the one in Idaho is in a town with a population of 50,000. Are these corporate stores, or are they the (cool) independent Radio Shacks? Are there component drawers? Anyone want to take a field trip and report?

A few years ago, [cnxsoft] bought a Sonoff WiFi switch to control a well pump. Despite this being a way to control the flow of massive amounts of water with an Internet of Things thing, we’re still rocking it antediluvian style, and for the most part this WiFi-connected relay worked well. Until it didn’t. For the past few days, the switch wouldn’t connect to the network, so [cnxsoft] cracked it open to figure out why. There was one burnt component, and more than one electrocuted insect. Apparently, an ant bridged two pins, was shortly electrocuted, and toasted a resistor. It’s a bug, a real bug, in an Internet of Things thing.

eInk is coming to license plates? Apparently. Since an eInk license plate already includes some electronics, it wouldn’t be much to add some tracking hardware for a surveillance state.

Hold up, it’s a press release about crypto hardware. No, not that crypto, the other crypto. Asus has announced a new motherboard that is capable of supporting twenty graphics cards. This isn’t a six-foot-wide motherboard; it’s designed especially for coin mining, and for that, the graphics cards really only need a PCIe x1 connection. The real trick here is not using PCIe headers, and instead piping everything over vertical-mount USB ports. Yes, this is a slight cabling nightmare. So, you still think the early 80s with fluorinert waterfalls and Blinkenlights that played Game of Life was the pinnacle of style in computer hardware? No, this is it right here.

Here’s a book you should readIgnition!: An Informal History of Liquid Rocket Propellants by John Drury Clark is a fantastic book about how modern liquid rocket fuel came to be. Want to know why 60s cartoons and spy movies always referenced a ‘secret rocket fuel formula’ when kerosene and liquid oxygen work just fine? This is that. Back when we covered it, the book, used, on Amazon, cost $500. It’s now in print again and priced reasonably. It’s on the Inc. 9 Powerful Books Elon Musk Recommends list, so you know it’s good. Thanks, [Ben] for sending this one in on the tip line.

Simple Ethereum Vending Machines with NodeMCU

Recently, we covered how to use the Etherscan API to query data (a wallet balance) from the Ethereum blockchain with NodeMCU. It’s a very useful method for retrieving information from a blockchain on embedded systems where storage and memory are an issue.

It has some limitations though. Most notably, it’s polling the API at some interval to retrieve information whether it has changed or not. I would like to be able to receive data more efficiently than this, and quickly enough to make simple vending machines possible. While we’ve seen videos of Bitcoin-based Red Bull vending machines before, they required an NFC card to use.

If we could receive information about Ethereum transactions quickly and reliably enough, we could build a similar vending machine without requiring an NFC card as an intermediary. Simply send to an address via some method, and receive goods!

It turns out we can do exactly that with NodeMCU using WebSocket. Like HTTP, WebSocket is a communications protocol that uses TCP connections (typically over port 80), but it allows full-duplex communication. In other words, you can establish a connection to a server, and send/receive messages without needing to poll the server.

As in the previous example, we’ll use a NodeMCU running Lua. You may wish to refer to it for compile options and information about the screen, which will be the same in this case. Unlike the previous article, you will not need an API key from Etherscan to use this service (not yet, anyway). As usual, we’ll start off by connecting to WiFi:

station_cfg.ssid="Your SSID"
station_cfg.pwd="Your Password"

Connecting to a server with WebSockets is easy, but since we’re not using HTTP, we’ll have to remove the https:// and replace that with ws://. (Note: not wss:// because we’ve not enabled encryption yet.)


Next, we need to report back when the connection is established as the trigger to run additional code. It will return an error code if the connection fails to be established. Handling these error codes in a sensible way is an excellent feature, but we’ll handle that later:

ws:on("connection", function(ws)
    print('got ws connection')

Now, we need to extend the above to subscribe to an Eth address, and add some new code to do something when a transaction occurs. Note that the API requires that you subscribe to an address within 60 seconds of connecting. It also states that you have to send a ping event to the server every 20 seconds to keep the connection alive, so we’ll need to set a recurring timer for that.

If you’re using ESPlorer, you can send the ping request manually by entering =ws:send('{"event": "ping"}') and pressing Send. This is a useful way to test the connection status.

The address I used seems to have frequent transactions so is reasonable for testing. Be advised though that sitting and waiting for a transaction to happen to test the code creates a slow development cycle so some patience is necessary here.

ws = websocket.createClient()
ws:on("connection", function(ws)
    print('got ws connection')
    ws:send('{"event": "txlist", "address": "0x2a65aca4d5fc5b5c859090a6c34d164135398226"}')

ws:on("receive", function(_, msg, opcode)
    print('got message:', msg, opcode)

You should see something like what follows below. The first message is a simple confirmation of connection, the second confirms your subscription to an address, and the third is what you get sent when a transaction occurs. You can subscribe to up to 30 addresses with a single connected device! Note that the data is all in JSON format, which is something we’ll take advantage of later.

got message: {"event":"welcome"} 1
got message: {"event":"subscribe-txlist", "status":"1", "message":"OK, 0x2a65aca4d5fc5b5c859090a6c34d164135398226"} 1
got message: {"event":"txlist","address":"0x2a65aca4d5fc5b5c859090a6c34d164135398226","result":[{"blockNumber":"5532531","timeStamp":"1525098009","hash":"0xe5ec497cb5b38811e8bf5db67a056a2bdd4aa9b68df5c8e8225cb300cbcfa413","nonce":"3363391","blockHash":"0xf446f77d92ed29c221e8451b8048113969ed305a7dd49177e10b422e8e2c4bda","transactionIndex":"172","from":"0x2a65aca4d5fc5b5c859090a6c34d164135398226","to":"0xec5fdfba35c01c6ad7a00085e70e8f30cd121597","value":"24418350000000000","gas":"50000","gasPrice":"4000000000","input":"0x","contractAddress":"","cumulativeGasUsed":"7896403","gasUsed":"21000","confirmations":"1"}]} 1

That’s quite a mess of transaction data, and unfortunately the datum of interest is in the ‘result’ field – which is nested JSON. In the last article, we converted simple JSON to a Lua table using the excellent sjson module. We’ll do the same here after verifying the message type is a transaction (txlist).

ws:on("receive", function(_, msg, opcode)
    print('got message:', msg, opcode)
    ok, ethdata = pcall(sjson.decode, msg)
    if ok then
        msgtype = (ethdata["event"])
        if msgtype == "txlist" then

The NodeMCU documentation specifically notes that nested JSON can cause out-of-memory errors. For that reason we use pcall (protected call) to contain any such errors when decoding our JSON message. Next, we extract the contents of the ‘value’ field, nested within the ‘result’ field:

if msgtype == "txlist" then
    wei = ethdata.result[1].value
    print (wei)
    eth = wei/1000000000000000000
    print (eth)

It took me a few hours to figure out how to deal with nested tables, but in the end it was actually quite clean and easy — I was just being dense. Now, we need to add a basic provision to handle errors when the websocket is closed:

ws:on("close", function(_, status)
    print('connection closed', status)
    ws = nil -- required to Lua gc the websocket client
    tmr.alarm(0,4000,tmr.ALARM_SINGLE,transact) -- This reconnects after 4 seconds

To wrap it all up, we encase the code in a couple of functions — first, one to establish a connection, subscribe to the right address, and notify when there is a transaction. Next we need one to display the amount of Eth transferred. Finally, we need a ‘ping’ function to call every 20 seconds or less to keep the connection alive. Overall this turned out to be more robust than expected and has yet to encounter an error. Check out the full code listing here. Note that I’ve also added a little code above to interface with a 128×32 OLED screen, the same one we used previously.

Now that it works, let’s consider im/practical applications. It’s a neat way to display Ethereum transactions in real-time, say if you do livestreaming and accept Eth donations and want them to trigger something fancy. Or, you could make a somewhat insecure vending machine. Clearly, getting a secure WebSocket up and running is the next order of business.

You could also set a timer where the length depends on the amount of Eth received. This would allow for things like public advertisements that go away for a while if someone pays a fee. (Please don’t do this!) Maybe a conference room for rent with the power controlled this way? Hackerspace membership payment? An electric bicycle that charges you for power used?

In any case, it’s not legal to use cryptocurrency as a form of payment in my country so I can’t implement any of the above examples at this time. If you’ve got a better application, please share it in the comments!

Accessing Blockchain on ESP8266 Using the NodeMCU Board

Blockchains claim to be public, distributed, effectively immutable ledgers. Unfortunately, they also tend to get a little bit huge – presently the Bitcoin blockchain is 194GB and Ethereum weighs in at 444GB. That poses quite an inconvenience for me, as I was looking at making some fun ‘Ethereum blockchain aware’ gadgets and that’s several orders of magnitude too much data to deal with on a microcontroller, not to mention the bandwidth cost if using 3G.

Having imagined a thin device that I could integrate into my mobile phone cover (or perhaps… a wallet?) dealing with the whole blockchain was clearly not a possibility. I could use a VPS or router to efficiently download the necessary data and respond to queries, but even that seemed like a lot of overhead, so I investigated available APIs.

As it turns out, several blockchain explorers offer APIs that do what I want. My efforts get an ESP8266 involved with the blockchain began with two of the available APIs: Ethplorer and Etherscan.

Continue reading “Accessing Blockchain on ESP8266 Using the NodeMCU Board”