Speculative Attack on Blockchain Based Cryptocurrency

Since the recent Bitcoin hype, I’ve been thinking about different types of cryptocurrencies, their design, usage etc. I came up with an idea how to severely impact some blockchain based cryptocurrency’s public perception, and in the result, it’s trading price. Let me just disclose that this is just speculation on my part, I don’t have a will nor means to do this, and I’m definitively not the first person who figured this out, so this might be a kind of “warning” when you see something like this happening.

But first, let’s focus how typical blockchain cryptocurrency (Bitcoin included) works. I’m not going to go into details here if you want to see a great technical explanation check out this great presentation:

You can also check this great live demo

I’ll focus on important features that allow this kind of “attack” and I will explain this using Bitcoin as an example. Basically, blockchain is a publicly available ledger which contains all the Bitcoins ever created and all the transaction records. As I’m writing this it amassed to roughly 150 gigabytes of data. All the Bitcoins are assigned to “wallets”, which are pairs of public and private cryptographic keys. The public key is stored in the ledger (when the first token transfer to this wallet happens), while the private key is stored by the owner in a secure manner. The private key allows transferring Bitcoins to another wallet.

This is really that simple. There is no overseer, all the system “cares” is that the owner has a private key to the wallet. This has several implications:

  • The system relies 100% on secure cryptography.
  • If the owner somehow loses the private key (it is destroyed, lost, forgotten etc) the Bitcoins are lost, forever. There is no way to get those bitcoins back.
  • If someone else gets access to the owner’s private key, this person can transfer Bitcoins within a matter of minutes. The only way to protect the Bitcoins when the key was compromised is to transfer them faster than the thief to another, non-compromised wallet. After stealing the money there is no way to get them back (there is no regulatory body, no customer support to call).
  • If the owner sends money by accident/to a wrong recipient, there is no way to reverse that transaction.
  • All the wallets with money on them are available to view for anyone on the Internet because the ledger is public. You can see all the Bitcoin transactions on a particular wallet.

The first implication is crucial. The only reason cryptocurrencies hold value is the fact they’re are secure. If you undermine this perception, the value will go down.

Now let’s think how secure they are? The correct answer is - we don’t know for sure. Let’s look at Bitcoin’s protocol: it is based on SHA-256 hash function, which, ironically, was introduced by the NSA. There is no mathematical proof this algorithm is secure. We only know that no one (at least in the open) was able to crack it in a practical manner. Both SHA-1 and MD5 has been broken roughly ~15 years after being introduced. The crypto behind ZCash, zn-SNARKs was introduced in 2012 so it is really new. You can say the same about CryptoNote used in Bytecoin and Monero. I also encourage you to read this article about IOTA. Keep also in mind the rapid development of quantum computing in the recent years. If someone will tell you those cryptocurrencies are 100% hack-proof, they are lying. Maybe they are but we just don’t know that right now. Also, Bitcoin protocol has been hacked before. The CVE-2010-5139 vulnerability in 2010 allowed the creation of over 184 billion bitcoins. The blockchain had to be forked to fix that screwup. So there are precedences.

There are also now HUGE incentives to find vulnerabilities, as David Schwartz (Chief Cryptographer ad Ripple) said: “What we have now is a multi-billion dollar bug bounty program”.

The FUD attack

Let’s talk about the theoretical “attack”. To pull this off the attackers would need some hefty amount of money “parked” in targeted cryptocurrency, IMO at least 1M$. The particular crypto price doesn’t matter. All that matters is the “real” money involved (USD, EUR, GBP, RMB etc) to scare other current and potential investors. Keep in mind this money doesn’t have to be wasted and can be recovered after the stunt. In an ideal case, this would be some “old money”, i.e. money lying on particular wallets for a while (not transferred there just before the stunt). The attackers would then “fake” their tokens were stolen. It could be accomplished by just transferring the money to some fresh wallets. Those wallets would, of course, belong to attackers, but there is no way to check and prove that.

After transferring the tokens, the “attackers” would go public with this fake information in a coordinated manner. Preferably to different language speaking communities. One person would talk about it on some English speaking crypto forum. The other would go to Russian one, another would post on Chinese social media etc. This is a classic FUD campaign. Those people can show their account being wiped as a proof, since as I mentioned, all the transactions are publicly available. If I were the “attacker” I would do some wallet-juggling, in the end transfer the money to couple of particular wallets and then to some more private cryptocurrency (like ZCash) so it could never be traced.

This would probably get some media attention, since it has a big “click-generating” potential: cryptocurrencies and people loosing their live savings due to some mysterious hacker. The problem is, due to most of the cryptocurrencies nature, there is no credible way to disprove this as a hoax. The particular cryptocurrency community/maintainers couldn’t do much. They can’t tell if the protocol is being compromised, they could just assure that nothing suspicious was found. To be honest after seeing this kind of news, as a holder of particular cryptocurrency I would be at least little afraid of loosing all my money.

Testing Room and LiveData with Kotlin

In this post, I’ll show how to unit test Google’s Room persistence library with LiveData in Android project written in Kotlin. You can find the project’s code on my GitHub.

The app is just storing user’s name in our Room database. The View is observing LiveData retrieved from the database by the ViewModel.

The database is empty and when we tap “SHOW LOG” it is displaying “null”:

Room and LiveData testing first screenshot

After adding the user, the UI is refreshed and the “SHOW LOG” is displaying our new user:

Room and LiveData testing second screenshot

Lets take a closer look how this functionality is implemented. First we have our User object:

It contains a mutable field userName.

Then we have our UserDao class which is a Data Access Object:

It is a Java class. The reason for that is Android Studio is not yet (at the time of writing this blogpost) code highlighting and completion for Room SQL queries in Kotlin. There are 3 standard SQL methods (insert, delete and update) but also two more interesting: getUser() and getUserAsLiveData(). The latter is returning User object wrapped inside a LiveData. I’ll explain that later in this post.

Then we have our database:

It contains one entity (User) and one Dao (UserDao). The companion object is just a quick way to have an instance of our database as a singleton. In production, you probably should use some dependency injections framework (such as Dagger 2) to provide your database instances. The rest of the code is pretty straightforward.

Now, let’s switch to the unit testing part. First, we need to create our database for testing purposes. Let’s use an abstract class here for code reusability:

For testing purposes, we’re using Room’s inMemoryDatabaseBuilder. It will create a non-persistent instance of our database, which will be discarded after the test ends.

Then we create our UserDaoTest class by extending abstract DbTest class. Don’t forget to use the open modifier and annotate the class with @RunWith(AndroidJUnit4::class).

Testing inserting and deleting user is pretty straightforward:

Room’s “in memory” database allows main thread operations so we can just call appDatabase.userDao().user to retrieve the User object. The problem arises when we want to call getUserAsLiveData() method. This method returns LiveData object. Room calculates the value wrapped in LiveData lazily, only when there is an observer. Fortunately using Kotlin’s extension functions we can solve this problem in elegant way.

Let’s provide a LiveData extension that will observe the value stored in LiveData, blocks the thread and returns the value:

Now we can use that in our test case:

First we call val userWrappedInLiveData = appDatabase.userDao().userAsLiveData which returns LiveData object. Then we apply our extension function to get User object: val userFromDb = userWrappedInLiveData.getValueBlocking(). As we can see, all three tests are passing:

Tests results

Best Summary of Android Architecture Components

During 2017s Google Developer Days Europe Florina Muntenescu gave this great talk explaining Android Architecture Components. It is only 15 minutes long (last 5 minutes are about new android.support.v7.recyclerview.extensions) and addresses all the issues I encountered using it in a very clear way. Highly recommended watch.

Running TensorFlow on Android Things

In May of 2017 Google announced its TensorFlow library’s version dedicated for mobile devices, back then called TensorFlow Lite. Later they rebranded it as TensorFlow Mobile. Google used a process called Quantization, which is basically a way to represent neural network’s structure using lower than 32bit floating point computer formats. In the case of TensorFlow Mobile, the 8bit fixed point format is being used.

The whole point of this library is to use it on low-power devices with limited storage since “traditional” deep neural nets can be both huge in size (hundreds of megabytes) and very demanding in computationally (which requires powerful hardware and a lot of energy).

I decided to give it a try on my Raspberry Pi 3 board running Android Things developer preview 4.1. The code I used and the schematics are available on my GitHub. The network used is pre trained Google Inception model.

Here is the setup I used. The camera is an old 5-megapixel module from 2013. The picture quality isn’t too great by today’s standards. I used slightly modified soldering gripper as a makeshift tripod.

Architecture sample app first screenshot Quick and dirty setup

TensorFlow first prediction It recognizes the conch shell with 51% certainty

Schematics of the project:


Here are some other examples of the network at work:

Coffee mug example

Orange example

Of course, the network isn’t perfect:

Egg example

The whole app’s size is ~70MB. Keep in mind all the app’s work is done offline, contained in a tiny RP3 body. It takes under one second to do the inference on the picture. I think future looks particularly promising with the advances in hardware (new cheaper and more powerful IoT platforms) and machine learning algorithms.

Android Architecture Components With Kotlin - Lifecycle

Google recently released its official guide to the Android app architecture with a bunch of libraries called Architecture Components. This looks very promising since Android has been missing a standard way of implementing some kind of clean architecture. There were many unofficial ways to implement MVP and MVVM patterns, from which I had a chance to use a couple, including Mosby.

The problem was lack of standards. When I switched a project I had to learn completely new MVP/MVC/MVVM implementation which did exactly the same thing I was used to, just in a different way. I always thought it would be nice if Google provided some “official” support for app architecture which the industry could adopt.

In this post, I’m going to explore the ViewModel, LifecycleOwner, and LiveData from the Architecture Components Library. All the code here is of course Kotlin.

The code for this tutorial is available here. The sample app requires Android Studio 3.0, at the time of writing this post I used Android Studio 3.0 Canary 5. If you want to use Canary version of Android Studio along your stable version on the same machine, check out this video. I will update the GitHub repository to more stable versions of Android Studio 3.0 when available.

As an example, I created a simple app which contains Activity and two Fragments. The app is showing two Fragments connected to shared Activity. The first Fragment is displaying simple countdown timer, the second Fragment has all the controls:

Architecture sample app first screenshot

When you tap “START” the app starts the counter:

Architecture sample app second screenshot

The state of the counter is preserved during orientation change, when the shared Activity is being recreated:

Architecture sample app third screenshot

You can also stop the timer or log the timer state.

App’s architecture explained

First, we need to import the required library. To do this we add the dependency to the apps build.gradle file in dependencies section:

// Android Architecture Components

compile "android.arch.lifecycle:extensions:$arch_version"

where '$arch_version' is the library’s version. Google is currently providing Architecture Components as a separate library but after reaching v1.0 it will be part of the support libraries.

Our shared Activity extends LifecycleActivity() from the library.

Our app’s business logic is located in SharedViewModel class, which extends ViewModel class. Its purpose is to “store and manage UI-related data so that the data survives configuration changes such as screen rotations”. The business logic here is a simple countdown timer. We store the formatted time String as MutableLiveData, an Architecture Components holder which stores data that can be observed. The difference between LiveData is that it exposes setters. Note that we also use a TimerStateModel object (custom Kotlin Data class) which also survives orientation change:

In FirstFragment we make the formattedTime observed. First we create timeObserver which updates our tvTimer TextView every time the mFormattedTime in our SharedViewModel is getting changed. We are obtaining instance of our SharedViewModel (see code line 10 below) and then we subscribe to the observer (code line 13). The activity cast as LifecycleOwner which we pass to the observe method is Kotlin’s convenience method to get our SharedActivity instance. We are accessing formattedTime via our public getter.

In the SecondFragment in onViewCreated method first we obtain an instance of our SharedViewModel and then we set all the appropriate onClickListeners (code lines 7-9).

In this simple example we delegated all of the business logic to a ViewModel. Our fragments are only responsible for observing the data changes (using convenience of LiveData) and responding for user input. Everything is managed by the Architecture Components library so there is very little boilerplate. Also, it reduces the possibility of shooting ourselves in the foot by mismanaging app state, which in my experience is one of the most common bugs every Android developer experiences.

If you want to do some further reading about Architecture Components I recommend those excellent articles:

Exploring the new Android Architecture Components library by Joe Birch


Styling Android articles