Photo by Jan Antonin Kolar on Unsplash

Files in the Blockchain

These days I am practicing programming smart contracts in Solidity using TDD. There are several projects I am working on: some DeFi projects, a programmatic faucet, user login and onboarding, personal notes, some games. One of the projects already has something to show: I have been able to upload (image) files to RSK’s testnet.

One comment: a blockchain is not the more appropriate place to save files, at least an Ethereum-like. The upload of a file could cost many millions of gas units. And the retrieval is not the fastest. But I wanted to explore some Solidity code, and also, do an experiment with web application.

Show Me The Code

The main contract I’m using is ChunkedFile.sol. It can contains an array of chunks. Each chunk is a bytes array. The owner of the contract can upload a file, putting chunks into this smart contract. The chunks can be retrieved by anyone, one by one.

The internal state is very simple:

contract ChunkedFile {
address public owner;

bytes[] public chunks;

There are functions for put and get chunks:

function get(uint nchunk) public view returns (bytes memory) {
return chunks[nchunk];
function put(uint nchunk, bytes memory content) public onlyOwner {
if (nchunk == chunks.length)
chunks[nchunk] = content;

Uploading and Downloading Files

Having defined the host and some user with balance, you can upload a file (I recommend to use a file with size less than 20K) using a chunk size of 4096 bytes:

node deploy myuser file1 ChunkedFile
node upload myuser file1 <localfilepath> 4096

To download the file, execute

node download myuser file1 <localfilepath>

Viewing Files

One of my watercolor painting practice, now immortalized in the blockchain

Next Steps

  • Deploy the sample dapp to a hosting service (maybe vercel)
  • Use of directories
  • Add properties to files and directories

I had a lot of fun with this project!

Angel “Java” Lopez

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store