A Blockchain-Powered Smart-Lock

Securely open/close your front door with a smart contract

Ever wondered why many consider blockchain to be a game-changer in the IoT space? This example describes how to build a very simple smart-lock powered by a Blockchain smart contract to make some considerations around this topic.

The hardware

We will use a very basic solenoid-based electric lock, that requires a dc 12V input to switch in the “open” state, while a mechanical spring will push it in “closed” state when not powered. A Raspberry Pi Zero is more than enough to run the small script that monitors the blockchain and it’s small enough to fit into an hypothetical SmartLock case of a decent size. Finally the 12V power supply to power the lock and a relay board to switch it on and off complete the hardware specs for this simple project.

The blockchain

We will use the IoTeX Blockchain for the smart contract infrastructure: it has some nice characteristics and features that are very desired in an IoT project, let's see some of them:

  • It's extremely fast, with an amazing 5-second transaction confirmation time it's perfect for devices automation
  • In features instant finality of transactions: once a transaction is confirmed in a block, the confirmation is 100% final (i.e. no need to wait for more blocks to increase the confidence of the confirmation against possible blockchain forks), which is totally required if we are operating on real-world devices (if you are doing home-sharing, you don't want to open your front door based on a transaction that you will later discover it was not included in the blockchain, right?)
  • It provides smart contracts: well, IoT is all about automation of devices, and orchestration of “things” in real world scenarios that will possibly also involve deposits and payments, all based on some more or less complex logic, so this is a pretty obvious requirement! Good that we ca use Solidity, too.
  • It's extremely secure: IoTeX has proven itself to be one of the most secure networks in the blockchain space. Ever since the bootstrap of the first MainNet Alpha release in April 2018 the network has never experienced any downtime, or any relevant issue. To date, the network is running smoothly on MainNet v1.1.1, it's backed by over 60 worldwide block producers, and is actively developed with many innovations tailor fit for the IoT (both software and hardware!).

Benefits of Smart Contracts

Why would we use a smart contract for our smart-lock? Well, we want to remotely operate our SmartLock, so one option we have is to open our network to external incoming connections and talk directly to our SmartLock: this option poses huge security concerns that are not easy to tackle without professional knowledge and a solid security policy (read “money”), especially if we are going to scale. A more reasonable alternative is to use an intermediate server in the cloud to hold the status of the lock that we will actually modify, while it is monitored by the SmartLock to execute the request. This option sounds much better as the security is managed by the cloud service provider, but it poses another types of concerns: their security is probably much stronger than what we can do, but they are also the target of 99% of all serious hackings, so the risk is still high. Additionally, our business (the service availability and the data) are in the hands of a third party, in the best scenario it could have downtime’s, in the worst one it could sell our data, or close our account for whatever reason. And it has a cost of course.

What about the blockchain? You may think that for such a simple application there could be not much benefits in using a smart contract, yet even though the code that we will use is as simple as one line of code: State = not State; to toggle the Lock, solely because it's executed ina blockchain contract it changes everythin. Le’s what it provides us:

CloudService: We can use the blockchain as a cloud server to remotely access our home device: so no need to open our home network to the outside world.

Security: Only the owner of the blockchain account (i.e. the wallet) that deployed the smart contract is the one allowed to execute it and to operate the smart lock, which means that our system is as secure as a blockchain account, and no successful attempts of cracking a blockchain wallet have been reported to date — that's pretty important if you are driving the lock of your front door, isn't it?!

Uptime: Relying on a blockchain we achieve a theoretical 100% uptime: even comparing to the best professional cloud service, a well designed blockchain counts on a worldwide decentralized network of numerous independent servers, and can be considered immune to hardware failures and almost immune to attacks.

Censorship-free/tamper-proof: Because our blockchain is permission-less and decentralized, there is no service provider (or hacker!) here that can decide to close your account, stop your service, or somehow tamper with your code altering the behavior.

Time get our hands dirty and start building our Smart Lock!

1. Configure the Raspberry Pi Zero W

Let's start from the Raspberry Pi Zero W that will directly drive the smart-lock through the integrated digital I/O: we will install the Raspberry OS Lite Image and configure the I/O pins.

1. Insert your Micro-SD card into the slot of your computer

2. Use the Raspberry Imager tool and select Raspberry Pi OS (Other) > Raspberry Pi OS Lite (32bit) and flash it to your card

3. Extract and insert again your micro-sd card, open the folder /boot on the card, create and save an empty file named ssh to enable ssh connection to your Raspberry

4. Create a wpa_supplicant.conf file and paste the following code, replacing the placeholders with your wifi network name and password:

# Replace with your ISO country code, e.g. US, IT, GB, AU, etc... country=YOUR_2_CHARACTERS_COUNTRY_CODEnetwork={       # Set your wifi network name - 5Ghz network are not supported!       ssid="YOUR_NETWORK_NAME"       # Set your wifi password here       psk="YOUR_NETWORK_PASSWORD"       key_mgmt=WPA-PSK    }ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdevupdate_config=1

5. Save the file and put the micro-sd card into the Raspberry card slot, connect the power to the Raspberry and turn it on

6. Login into the Raspberry with:

ssh [email protected] # use "raspberry" as a password!

if this doesn't work, then you will be required to access your router web interface and look for the list of connect wifi clients, locate “raspberrypi” in the list, take note of it's IP address and replace raspberry.local with the IP address in the ssh command above (also you should make sure that it will be always assigned the same ip by the router – check out this video as an example).

7. Before going on it's recommended to run sudo apt-get update and sudo apt-get upgrade to ensure your Pi system is up to date.

Install required packages and clone the iotexlab/iotex-arm GitHub repository from IoTeXLab Delegate:

sudo apt install git python3-gpiozero -ygit clone https://github.com/iotexlab/iotex-arm.git

8. Configure the GPIO on the raspberry: the following script will basically enable GPIO 14 (corresponding to pin 8 on the Raspberry) and configure it as an output pin:

sudo su~/iotex-arm/smartlock/configureGpioexit

2. Hardware configuration

We will only use pins 4, 6 and 8 on the Raspberry pi to drive the Relay module that in turn will enable/disable the smart-lock:

1. Use the female-to-female wires to connect the Raspberry to the relay: depending on your relay board the position of pins may vary slightly

Raspberry pin 4 (5V) -> Relay pin 1 - VCC
Raspberry pin 
6 (GND)-> Relay pin 4 - GND
Raspberry pin 
8 (5V) -> Relay pin 3 - IN1

2. Connect the relay output to the lock power supply. Basically you want to “cut” the ground wire from the 12V power-supply and put the relay in the middle of the power line. Eventually, here are is how the final wiring looks like:

3. You can test that everything works by sending 0 or 1 to the GPIO 14 and you should see the lock open/close (or close/open depending if you wired it on the NO or NC output of the relay):

echo 1 > /sys/class/gpio/gpio14/valueecho 0 > /sys/class/gpio/gpio14/value

3. Create the smart contract

As anticipated, we will use a smart contract to keep and toggle the state of our smart-lock: to do that we will need a blockchain account:

1. Download the official ioPay wallet for the IoTeX Blockchain, we need the desktop app: iopay.iotex.io/desktop, launch the app and create a new account. In the network dropdown menu select “Testnet“:

2. Go to https://faucet.iotex.io and input your newly created wallet address to obtain some IOTX tokens to be used for our transactions on the IoTeX TestNet:

3. Open the IoTeX Web Studio at ide.iotex.io and paste the smart contract code: it's very simple and self-explicative!

4. In the Studio IDE, click the “Compile” button[1], after compilation click the [ABI] button to copy the contract ABI, and put the content of the clipboard in the ~/abi.json file.

Then select “Deploy via ioPay” in the Environment field[2], notice that your ioPay account is showed in [3] (that will be the owner of the contract!), make sure the “SimpleDoorLock” contract is selected in the deployment section[4] and click the “Deploy Contract” button[5]:

5. At this point ioPay will pop up with a request for signing the transaction: sign it and wait for it to be confirmed by the blockchain: make sure that the TestNet network is selected and that you have some IOTX balance or your transaction will be rejected:

6. Go back to IoTeX Studio: notice that your contact is now listed under the “Deployed Contracts” section and you can also test the functions[1]. Now head to the log panel and take note (copy) the blockchain address that has been assigned to your contract[2]:

Please, leave the Studio open, as we will use it later to interact with the contract.

4. Monitoring scripts

The only step left is to monitor the status of the smart-lock from our Raspberry Pi and drive the lock accordingly. We will keep this simple, and just use the IoTeX ioctl command line client: you find a binary built for the Rpi Zero included in the IoTeXLab repository that you cloned above, let's copy it in our ~/bin directory that should include it in the path:

cp iotex-arm/bin/ioctl-armv6l bin/ioctl

Configure ioctl to interact with a IoTeX Blockchain Gateway: we will use the public TestNet gateway provided by the IoTeX Team

ioctl config set endpoint api.testnet.iotex.one:443# Test it by querying some TestNet infoioctl config set endpoint api.testnet.iotex.one:443

Now lets create our checkState script that will monitor the contract and drive the lock accordingly (paste the code from the attachment):

nano ~/bin/checkState # Paste the code of the checkState script and savechmod +x ~/bin/checkState./checkState

5. Test the project!

For this project we will just test by going back to the IoTeX Studio IDE and use the UI to interact with the contract:

1. Make sure your ioPay wallet is open and unlocked on your contract owner account

2. In IoTeX Studio IDE, in the â€śDeployed Contracts” section expand the SimpleDoorLock contract, and try the toggle function, wait a few second and check your SmartLock!

6. Questions

For any questions, feel free to contact me in the IoTeX Developer Telegram Group (@zimne).

Stay tuned for more advanced block creation tutorials!


pragma solidity ^0.5.0;

// Import the "Ownable" interface from OpenZeppelin, that implements
// the "onlyOwner" modifier we use to make sure only the contract
// owner can operate the smart-lock
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/ownership/Ownable.sol";

 * @title Simple Smart-Lock
 * @dev Very simple smart contract to manage the state of a smart-lock
contract SimpleDoorLock is Ownable {

    // Keeps the status of the smart-lock: true = door is locked!
    bool public State;
     * For safety, let's initialize the state to false (lock is open)
    constructor () public { State = false;  }
     * Toggles the state of the door lock, 
     * only the contract owner account can call this function!
    function toggle() public onlyOwner() { State = !State; }

Source: A Blockchain-Powered Smart-Lock

About The Author

Muhammad Bilal

I am highly skilled and motivated individual with a Master's degree in Computer Science. I have extensive experience in technical writing and a deep understanding of SEO practices.

Scroll to Top