The most expensive version of Conway's Game of Life - running on the Ethereum Blockchain

Overview

GameOfLife

The most expensive implementation of Conway's Game of Life ever - over $2,000 per step! (Probably the slowest too!)

Conway's Game of Life running as a smart contract on the Ethereum Blockchain.

This application would be able to run 'forever' - so long as there was some funds in an Ethereum account that could be used to run each 'step'.

However, the cost of Ethereum (and therefore 'gas') used to run smart contracts is so high that it would cost (in March 2021) over $80 just to register the smart contract, and to run a single 'step' of the game would cost over $2,000! No doubt that the code could be made more efficient and consume less resources, but hey that's just too much work for a concept app, so I have simply registered the contract on the Kovan test network instead, and use some 'fake' Ethereum to run the system. The app is the same, but it just points to the 'Kovan' test network instead of the Ethereum mainnet.

You can see it in action here

The application consists of three parts:

  • Front end Javascript application using the p5js library which runs in your browser
  • A Python Flask app implemented as a google cloud function
  • An Ethereum smart contract written in Solidity which runs on the (Kovan) Ethereum blockchain

p5js - client application

There are just three files in the app: a very simple index.html to host the javascript application in sketch.js along with a simple style.css stylesheet. When started, the app requests the 32x32 grid from the blockchain (via the flask app). Nothing will happen until you press the start button. Once this is pressed the app will request a new step on a timed basis (about one per minute). This will continue until the stop button is pressed. There are a couple of other buttons that will create a random selection on the screen, clear the screen, and add a few gliders. You can also use the mouse to select/deselect individual cells.

Python Flask google cloud function

This started as a bog standard Flask application, but I converted it into a google cloud function to avoid the hassle of having to host it somewhere. Most of the functionality here could have also been included in the browser-based javascript application, but because of my greater familiarity with python and my uncertainty about how to secure the private key needed to sign the solidity transactions I left it running on the server side. The main.py needs some environment variables for it to work. These are configured as part of the deployment script when pushing the flask app to the google cloud service:

gcloud functions deploy gameoflife \
--runtime python38 \
--trigger-http \
--allow-unauthenticated \
--env-vars-file env.yaml
env.yaml:
---
network_name: Kovan
HTTPProvider: 'https://kovan.infura.io/v3/PUT-YOUR-INFURA-KEY-HERE'
contract_address: '0x51B92cef4C0847EF552e4129a28d817c26a4A053'
private_key: 'PUT-THE-PRIVATE-KEY-OF-YOUR-ACCOUNT-HERE'
chain_id: '42'

Ethereum smart contract

The smart contract was written in Solidity. I used VS Code with a solidity extension that highlighted any syntax errors. The testing of the contract was done with the Truffle/Ganache suite of applications, and to get it onto the blockchain I simply used the remix online tool with the metamask browser extension.

I decided that a 32 x 32 cell structure would be big enough the showcase how the game works. In order to reduce the size requirements of data to be stored on the block chain, I used an array of 4 x 256 bit unsigned integers and used this as a bit field. There are three entry points in the contract (apart from the constructor): setCells(), getCells() and step()

Step

The step function mainly consists of loop iterating through the cells, creating/removing cells according to the rules of the game. I didn't make much effort to reduce the amount of work done in order to run a single cell, so I did run foul of one specific issue - the amount of gas consumed. At times it would exceed the limits of even the test networks, and so I ignored some of the cells on the edge of the whole cell universe. It would then take about 11M gas to process it, which is just below the 12M limit for the Kovan network.

for (int16 row=4; row<rows-4; row++) {
    for (int16 col=4; col<cols-4; col++) {
                
        int16 pos = (col + row*cols);
        int count = 0;

        // count_neighbours - count the number of cells that are direct neighbours   
        count += get(pos - cols - 1);  //(row-1,col-1); 
        count += get(pos - cols);      //(row-1,col  );
        count += get(pos - cols + 1);  //row-1,col+1);
        
        count += get(pos - 1); //(row,col-1);
        count += get(pos + 1); //(row,col+1);
        
        count += get(pos + cols -1); //(row+1,col-1);
        count += get(pos + cols); //(row+1,col  );
        count += get(pos + cols + 1); //(row+1,col+1);
                
        // if current cell is alive
        if (get(pos) == 1) {
            if (count > 3) {
                set(pos,0);
            } else if (count == 2 || count == 3) {
                set(pos,1);
            } else if (count < 2) {
                set(pos,0);
            }
        } else { // dead cell
            if (count == 3) {
                set(pos,1);
            }
        }
    }
}

and the get and set functions are implemented as bit twiddlers.

    function set(int16 pos, int8 value) internal {
        // the linear array is held in 4 x 256 unsigned integers 
        uint32 i = uint32(pos) / 256;
        uint32 j = uint32(pos) % 256;
        // if value is 1 then set the j-th bit
        if (value>0){
            newcells[i] |= (1 << j);  // set this bit
        } else {
            newcells[i] &= ~(1 << j);  // turn off this bit
        }   
    }
    function get(int32 pos) view internal returns (int) {

        if (pos<0) {
            pos += rows*cols;
        } 
        if (pos >= rows*cols) {
            pos -= rows*cols;
        }
        // make sure pos always is a valid value
        pos = pos % int32(rows*cols);
        // the linear array is held in 4 x 256 unsigned integers
        uint32 i = uint32(pos) / 256;
        uint32 j = uint32(pos) % 256;
        // if the j-th bit set?
        if ((cells[i] >> j) & 0x01 == 1 ) {
            return 1;
        } else {
            return 0;
        }
    }
Twitter FakeNFT With Python

This project is a server that fetches your Twitter profile picture and applies the hexagonal transparency mask displayed on the profiles of users who have an NFT profile picture.

Mathis HAMMEL 29 Apr 23, 2022
SpautiNoFay - A simple and beautiful music player created with Python

SpautiNoFay A simple and beautiful music player created with Python Why SpautiNo

8 Jan 19, 2022
Cloudshell-sandbox-reporter - Helper modules and classes for writing to Cloudshell sandbox console

Cloudshell Sandbox Reporter This project provides utility classes for formatting

QualiLab 2 Sep 07, 2022
Awslogs - AWS CloudWatch logs for Humans™

awslogs awslogs is a simple command line tool for querying groups, streams and events from Amazon CloudWatch logs. One of the most powerful features i

Jorge Bastida 4.5k Dec 30, 2022
A telegram bot that can upload telegram media files to anonfiles.com and give you direct download link

✯ AnonFilesBot ✯ Telegram Files to AnonFiles Upload Bot It will Also Give Direct Download Link Process : Fork This Repositry And Simply Cick On Heroku

Avishkar Patil 38 Dec 30, 2022
First Party data integration solution built for marketing teams to enable audience and conversion onboarding into Google Marketing products (Google Ads, Campaign Manager, Google Analytics).

Megalista Sample integration code for onboarding offline/CRM data from BigQuery as custom audiences or offline conversions in Google Ads, Google Analy

Google 76 Dec 29, 2022
✨ A Telegram mirror/leech bot By SparkXcloud Group ✨

SparkXcloud-Gdrive-MirrorBot SparkXcloud-Gdrive-MirrorBot is a multipurpose Telegram Bot writen in Python for mirroring files on the Internet to our b

119 Oct 23, 2022
python based bot Sends notification to your telegram whenever a new video is released on a youtube channel!

YTnotifier python based bot Sends notification to your telegram whenever a new video is released on a youtube channel! REQUIREMENTS telethon python-de

Mohamed Rizad 6 Jul 23, 2022
"Nesse projeto criei uma automação para abrir as tarefas no Jira em massa pegando de uma determinada fila do Zendesk."

automacao-Zendesk "Nesse projeto criei uma automação para abrir as tarefas no Jira em massa pegando de uma determinada fila do Zendesk." en-us "In thi

tokoyamy 1 Dec 20, 2021
A Discord bot to play bluffing games like Dobbins or Bobbins

Usage: pip install -r requirements.txt python3 bot.py DISCORD_BOT_TOKEN Gameplay: All commands are case-insensitive, with trailing punctuation and spa

4 May 27, 2022
A Telegram Bot to prevent Night Spams

NightModeBot A Telegram Bot to lock group in night to prevent night spam Setps To Use - Put Variables Correctly. - Add Bot to your group and make admi

ReeshuXD 10 Oct 21, 2022
If you are in allot of groups or channel and you would like to leave them at once use this

Telegram-auto-leave-groups If you are in allot of groups or channel and you would like to leave them at once use this USER GUIDE 👣 Insert your telegr

Julius Njoroge 4 Jan 03, 2023
Script Crack Facebook, and Instagram 🚶‍♂

in-mbf Script Crack Facebook, and Instagram 🚶‍♂ Bukti Install Script $ pkg update && pkg upgrade $ pkg install git $ pkg install python2 $ pip2 insta

Yumasaa 5 Dec 27, 2021
This is an implementation example of a bot that periodically sends predictions to the alphasea-agent.

alphasea-example-model alphasea-example-modelは、 alphasea-agent に対して毎ラウンド、予測を投稿するプログラムです。 Numeraiのexample modelに相当します。 準備 alphasea-example-modelの動作には、

AlphaSea 11 Jul 28, 2022
Prisma Cloud utility scripts, and a Python SDK for Prisma Cloud APIs.

pcs-toolbox Prisma Cloud utility scripts, and a Python SDK for Prisma Cloud APIs. Table of Contents Support Setup Configuration Script Usage CSPM Scri

Palo Alto Networks 34 Dec 15, 2022
domhttpx is a google search engine dorker with HTTP toolkit built with python, can make it easier for you to find many URLs/IPs at once with fast time.

domhttpx is a google search engine dorker with HTTP toolkit built with python, can make it easier for you to find many URLs/IPs at once with fast time

Naufal Ardhani 59 Dec 04, 2022
使用appium进行抖音粉丝的自动化获取

DYfans 使用appium进行抖音粉丝的自动化获取 工具: appium appium inspector Fiddler 夜神模拟器或者安卓手机 mitmdump mitmproxy 推荐使用安卓5.0夜神模拟器 库: appium selenium json 环境: jdk 安卓sdk 安卓

kaba 0 Mar 25, 2022
Hydro Quebec API wrapper.

HydroQC Hydro Quebec API wrapper. This is a package to access some functionalities of Hydro Quebec API that are not documented. Documentation https://

Olivier BEAU 9 Dec 02, 2022
• Create Your Own YouTube Info Api.

youtube_data_api • Create Your Own YouTube Info Api. Deploy How to Use https://{ Heroku App Name }.herokuapp.com/api?link={YouTube link} In local Host

lokaman chendekar 12 Oct 02, 2022
Pydf: A modular Telegram Bot which provides Pdf Tools using PyPdf2

pyDF-Bot 🌍 Pydf - Pyrogram Document File Bot, a modular Telegram Bot which prov

HyDrix 2 Feb 18, 2022