Kin Android development tutorial — part 7 — Setting up the app backend for earns

Luc Hendriks
Sep 19, 2019 · 13 min read

Welcome to part 7 of the Android development tutorial series! The goal of this part is to set up the backend that sits between the app and the Kin blockchain to secure your earns (and later spends). As a reminder, the infrastructure of the app-to-Kin communication is laid out in part 4. Here’s a visual example of the infrastructure we’re building:

Infrastructure for secure earns

We already covered how to set up the “Kin blockchain” portion of the earn flow in part 6. In this tutorial series, we communicate with the Kin blockchain using the Kin bootstrap server. The backend in the figure above represents the layer between the app and bootstrap server we built in the previous part. It is responsible for validating the earn requests which prevent someone from stealing all your Kin. To prevent confusion, I refer to the following:

  • Kin backend: This is the Kin bootstrap server we already set up in a previous part.
  • App backend: This is the backend that sits between the app and the Kin blockchain to do the verification of earn requests.
  • Backend: The Kin backend and the app backend together. They are separate web servers listening on different ports, but sit on the same instance.

In this part we are going to build the app backend, which together with the Kin backend finishes up the backend for earning Kin.

Setting up the app backend

The easiest way to set up a backend server is to set up two servers. However, we only have one free server from AWS. The method we will use here allows us to continue using one server to handle both the Kin backend logic and the app backend logic. Keep in mind that the app backend and Kin backend functionalities are completely independent and can run on different servers.

The first thing we need to do is set up another web server on the instance we created in the last part. The Kin backend, which runs in Docker, is a web server that listens to requests on port 8000. The new server we are going to create will run on port 8001. This way, by sending requests to port 8000 or 8001, we can differentiate between the Kin backend and the app backend.

Only the app backend can communicate with the Kin backend. If the app itself would directly communicate with the Kin backend, one would be able to circumvent the verification. This means the app will always send requests to port 8001 (where the app backend listens to), and the app backend will send requests to port 8000 (where the Kin backend listens to). The app will never send requests to port 8000 directly, because it would bypass the security of the app backend. Therefore, we can close off port 8000 from the outside world. This works, because the app backend can send requests to the Kin backend locally.

To set up the web server, first log in to the AWS console, and open up port 8001 on the security group, while closing port 8000 (reminder: EC2 dashboard -> Security Groups [under Networking & Security]). If you did this correctly, the security group settings should look something like this:

Security group settings. Yes, I was too lazy to block SSH access to only my ip address.

You can try to navigate to your server using http://SERVER-IP:8001, but it won’t work. That’s because there is nothing listening to port 8001 on the server (only on port 8000, but that’s blocked off now, so that also doesn’t work anymore — try it!).

Setting up a web server

We need something that listens to port 8001. The programming language the web server is going to be built in is Python. So please make sure Python is installed (it should be) by typing “python” in the console (first SSH into the server of course with your pem key). If you see something like this, you know it works:

To exit the Python console, press CTRL+D (Windows) or CMD+D (Mac).

Python has a very easy-to-use web server package called Flask. Install it by typing:

When it’s done installing, we can set up a simple web server. Create a new folder and create a file in it:

Paste this code in the file you just created:

And save and exit (CTRL+O, ENTER, and then CTRL+X).

Now start the web server using the following command:

This will start the web server that listens to port 8001. Open your browser and navigate to http://SERVER-IP:8001. You should see “Hello world” popping up! Congrats! You have set up the web server. Please take a moment to review the code above.

Verify the earn request

A valid earn request following the graph at the top of this post should be a request with the following information:

  • The ID of the user that does the earn request (which is attached to a Kin address on the backend)
  • How much Kin should be earned

The verification handles a few things:

  • An ID cannot earn more than once per 2 minutes (for the sake of this tutorial — a day is too long for debugging obviously)
  • An earn cannot be more than 100 Kin
  • An earn cannot be less than 1 Kin

First, we need to determine what an earn request looks like. For now, let’s use the following structure:

This means the server located at SERVER-IP listens on port 8001 to requests to the “/earn” endpoint with an “id” and an “amount” query string parameter.

In Flask this is very easy to set up. First, close the server (CTRL-C) and change the file to the following:

Please take a moment to read the above code. It’s changed a bit so it now listens to the “/earn” endpoint instead of just “/”. Next, we take the ID and amount parameters from the URL and put them in the ID and amount variables. Then, we print some text to convince ourself that it works. Save the file and start the server again. Then make the following request:

It should say “Hello someid. You requested an earn of 12 Kin.”

Now we can build the first two verification checks: That the amount is between 1 and 100 Kin:

Note the pieces of code in bold. The amount is now cast to an integer (a number), and then we make sure if the amount is smaller than 1 or bigger than 100. It will print out what is wrong, or “Request is OK” if it is correct. Run the server and play around with the amount parameter to make sure the code is working correctly.

Creating the user “database”

The final check, making sure a user can only earn once every 2 minutes, is a bit trickier. We first need to have a mapping from ID to Kin address. But to have the mapping we also need to have a way to get the ID + Kin address into our app backend. The ID here corresponds to the device ID of the phone, and the Kin address of the address that is created on the phone as well. When the app is launched for the first time, the device ID + Kin address combination needs to be sent to the backend once. Then the backend can save this combination in a database which can be referenced in a future earn request.

Handling databases is out-of-scope for this tutorial series, but I highly recommend using a MySQL database for storing this kind of data. Here is a nice tutorial on MySQL in Python. For now, we are going to use the file system as sort of a mini-database to learn how backends work. Create a folder called “users” inside the “app” folder you just created.

Then, we need to create a “registration” endpoint: A place where the Android app can send the device ID and Kin address, so the backend can associate the ID with the Kin address.

What the following additions to the server code does, is provide another endpoint “/register”, that register the user by saving a file to the users folder. The file name is the device_id and the contents of the file constitutes two lines: The Kin address and a zero. This represents a timestamp. We can update the timestamp after every earn to check if the earn is valid. But as there have been no earns yet, this value is 0.

Please note that this is will get you on your feet, but if your app is ready for production you should still go for something like a MySQL database with all the necessary security precautions. This is really meant to get you thinking about backends and how they work; it is not the most secure way to handle this. I’m not going to handle the following cases, but please be aware that you should build to handle these things once your app is ready to go into production.

  • What if one device ID is registered multiple times?
    The timestamp will be reset and the Kin address overwritten (you can try it). This leads to a way to bypass the two-minute verification. You should first check if the record exists, and do not overwrite the file if the user is already registered.
  • What if someone puts actual Python code as a device ID? An attacker might make a request like “/register?device_id=some_id&kin_address=ACTUAL_PYTHON_CODE”. Because the file is saved to the disk with the Python code in it, everyone can put actual code on your server. If they find a way to execute it as well, your server is compromised (meaning: they can do everything you can).

Even if you are going to use a database, you still need to be aware of SQL injections and XSS attacks. Please don’t underestimate this part of backend development! Building an app requires a full stack, either learn client and server development yourself, or focus on just one and hire someone for the other part.

Verify the two-minute window

Now that we’ve save the Kin address and last earn time per device ID, we can make the final verification and the actual earn request. First, the verification:

Take a look at the bold part. Several things are happening here. First, it tries to open the file with the requested ID as filename. If it doesn’t exist, we return “User does not exist”. If it does exist, read the file and extract the Kin address and the last earn time (which is set to 0 when registering, and will be updated to the current timestamp after an earn is completed — in the next part). If the last earn time took place less than 120 seconds ago, we return an error saying the last user earn was less than two minutes ago.

If those two checks pass, we again return “Request is OK”. All backend verification from the image at the beginning of this post is now done. We are now ready to finally make the actual earn.

Send the earn request

To send the earn request, we need to send a request to our Kin backend, which is running on the same server as this backend code. Because of that, we can send a request to “localhost”, which means “the current machine”, on port 8000 (where the Kin backend is listening).

The Kin backend has an endpoint called “pay” and we can do a POST request to this to do the earn. The POST request accepts 3 parameters in JSON format. This is an example request:

To be able to send requests, we need another Python package called requests (Flask is all about receiving requests, not sending them). So in your server, install that package with the following command:

Chances are it’s already installed, then nothing happens. The following code performs the actual earn request:

The bold code imports requests and then sends the request to earn. For this to work, the address in the user file needs to be an actual working address. So either use one that you already have, create a new one using part 5 of the tutorial series, or just pick a random address on the testnet block explorer (it’s testnet, you can just throw around test Kin to other people). Register a user with that address using the register endpoint and then submit a request to http://SERVER-IP:8001/earn?id=SOME-ID&amount=10. It should return the transaction hash; in my case:

Now check the transaction out on the blockchain explorer! If all went well, you can search for the transaction and it should pop up :) Congratulations! You have created a backend that can handle earns!

However, we need to add one last thing: The last earn time has not yet been updated. We created the two-minute check, but did not update the code to actually save the last earn time after the earn is completed, so it is always valid (you can just keep refreshing the earn request).

The actual code to update the last earn time is actually quite easy. We just overwrite the file with the same address and the current time. Python’s time() function returns the number of seconds that have passed since 1 January 1970 (called the UNIX timestamp), so we don’t have to deal with timezones and other annoying date properties (like the fact that not every month has the same amount of days).

Now try to refresh the request page. It will work again, but now the timestamp will be set to the current date. If you refresh once again, you will get the error message that you need to wait a bit. Wait for two minutes, refresh again, and it should work.

Wrapup

Phew! That is everything we need to create a relatively secure backend that accepts earns, verifies if the earn is valid, sends the earn request to the Kin backend, and returns the transaction hash. We are now ready to integrate this earn into the Android app.

Please keep in mind that this is a very minimal, bare-bones backend that relies on the filesystem as a makeshift database. For demonstration purposes this is fine, as you really understand what a backend does this way. However, actual production apps require an actual database with the necessary security precautions. As you might have noticed through my blog post series, there are already numerous places where one could try to steal all your Kin or access you server. By thinking like this, you can eliminate most security flaws.

Kin Blog

Kin is money. Earn, spend, and transfer value across an ecosystem of apps and services. Get paid for developing engaging user experiences with Kin.

Luc Hendriks

Written by

I like to think about the future

Kin Blog

Kin Blog

Kin is money. Earn, spend, and transfer value across an ecosystem of apps and services. Get paid for developing engaging user experiences with Kin.

More From Medium

More on Kin from Kin Blog

Kevin R Ricoy
Mar 27 · 5 min read

123

More on Kin from Kin Blog

More on Kin from Kin Blog

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade