Sunday, 11 November 2018

A step-by-step guide for deploying a simple Solidity contract on a test network

This post relates to a simple smart contract written in Solidity deployment on the Ropsten test network. It is a step-by-step deployment, giving as much detail as I could patiently gather..

METAMASK

"MetaMask is a bridge that allows you to visit the distributed web of tomorrow in your browser today. It allows you to run Ethereum dApps right in your browser without running a full Ethereum node.".
In a nutshell, it allows you to create an address and request ETH for testing. Install the extension for Chrome or Mozilla and set it up as follows. Start with the password creation (in my test I used 12345678910!)
You will now see this screenshot:
Then accept the various terms and conditions Finally, set up the secret words and back them up (spray talk duck avocado access put lens slice bench donor wise survey) - and the next screen put them back in the same order - and confirm. You will still see the following.
Now for the purpose of this exercise, select the "Ropsten Test Network" and click on "deposit" and select "Test Faucet" and click "GET ETHER" A new tab opens to https://faucet.metamask.io/ and select "reqest 1 ether from faucet" (or few times) A link like https://ropsten.etherscan.io/tx/0x2bc952af0236ef3960bdcd22b1a637f07e1369b1c0b200063c38104ab9a3611e will appear once the transaction(s) has(have) been validated and mined - you will see the number of ETH appear on your METAMASK main window for the "Ropsten Test Network"

SOLIDITY

Now on to the Solidity contract and coding/deployment/testing on the test network. Head towards https://remix.ethereum.org Under the tab 'run' select (if not already) 'environment' to be 'Injected Web' - and the test account we created should appear with the number of ETH requested by Faucet. We just need to write and deploy a contract... What about a simple contract to store the hash of a public document to validate the fact that it has not been modified?
pragma solidity ^0.4.7;

contract HashedDocsDemo {
    mapping (string => string) urlsDocHashMaps;
    
    function setHash(string url, string hash) public validStr(url) validStr(hash) {
        urlsDocHashMaps[url] = hash;
    }
    
    function checkHash(string url, string hash) public view validStr(url) validStr(hash) returns(bool) {
        string memory storedHash = urlsDocHashMaps[url];
        return keccak256(bytes(storedHash)) == keccak256(bytes(hash));
    }
    
    modifier validStr(string str) {
        bytes memory bstr = bytes(str); 
        require(bstr.length != 0, "invalid string");
        _;
    }
}
Once the contract has been pasted in the Remix IDE, go to "run" and click on deploy.
A window will popup and "click" confirm.
Another URL will be displayed (like https://ropsten.etherscan.io/tx/0xc551c6c2237c4faad697faf65bdd3d3a407914f1574b2a931871f3552154b93d) - same thing - wait for mining and effective contract deployment ("This transaction has been included into BlockNo #4400698 And will be reflected in a shortwhile")
We can finally interact with the contract - still in Remix - in the Run tab Enter any URL with any hash - then "transact" - same pop-up - confirm a new link is displayed: https://ropsten.etherscan.io/tx/0xe3c8af1e041405c53b2bf2ba300a947b3ba2a284f8f0ddce1187658f118557ce
Wait for confirmation - then you can look at the Remix ide, at the bottom, details of the transaction that went through and "decoded input" ....

Friday, 21 September 2018

Fun with Ethereum

Hi, If you want to play with Ethereum, locally, I would suggest to read the following blogs: Demystifying Ethereum Private Blockchain in less than 4 minutes! and Running a “quick” Ethereum private network for experimentation and testing
I run Ubuntu 16 it was a breeze to download the code, compile it, and run a mining node locally, as well as submitting transactions using web3.

Thursday, 21 September 2017

Monitoring, Alerts, and Google Compute

Have you ever looked for a simple, cheap and efficient solution to get alerts for a system that is not based on emails (as most of us get hundreds of those per day), or where you would need to look at a screen 24x7 to see a label color change from green to red?
I thought of using bots from Telegram to broadcast critical alerts to a Telegram group - and as I wanted to try Google Compute - to deploy the process on Google Compute Engine.
Code has been written in Kotlin

Kotlin/Telegram Code

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>morse</groupId>
    <artifactId>morse-tg</artifactId>
    <version>1.0</version>

    <properties>
        <kotlin.version>1.1.4-3</kotlin.version>
    </properties>

    <build>
        <sourceDirectory>src/main/kotlin</sourceDirectory>
        <testSourceDirectory>src/test/kotlin</testSourceDirectory>
        <plugins>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>${kotlin.version}</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>test-compile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <jvmTarget>1.8</jvmTarget>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <configuration>
                    <mainClass>morse.SupportBot</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jre8</artifactId>
            <version>${kotlin.version}</version>
        </dependency>

        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-test</artifactId>
            <version>${kotlin.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.telegram</groupId>
            <artifactId>telegrambots</artifactId>
            <version>3.3</version>
        </dependency>

    </dependencies>

</project>

kt code

package morse

import org.telegram.telegrambots.ApiContextInitializer
import org.telegram.telegrambots.TelegramBotsApi
import org.telegram.telegrambots.logging.BotLogger
import java.util.*
import java.util.logging.Level


class SupportBot : TimerTask() {
    lateinit var longPollHandler:LongPollingHandler

    override fun run() {
        longPollHandler.broadcast()
    }

    fun broadcast() {
        val timer = Timer()
        timer.schedule(this, 10_000, 60_000)
    }

    fun init() {
        BotLogger.info("SupportBot", "init()")
        ApiContextInitializer.init()

        BotLogger.setLevel(Level.ALL)

        val botAPI = TelegramBotsApi()
        BotLogger.info("SupportBot", "registering...()")

        longPollHandler = LongPollingHandler()
        botAPI.registerBot(longPollHandler)
        botAPI.registerBot(WebhookHandler())
        BotLogger.info("SupportBot", "Registered Handler")
    }

    companion object {
        @JvmStatic fun main(args: Array) {
            BotLogger.info("SupportBot", "SupportBot")

            val bot = SupportBot()
            bot.init()
            bot.broadcast()
        }
    }
}

package morse

object Cred {
    val bot = ""
    val token = ""
}

package morse

import org.telegram.telegrambots.api.methods.BotApiMethod
import org.telegram.telegrambots.api.objects.Update
import org.telegram.telegrambots.bots.TelegramWebhookBot
import java.util.*

class WebhookHandler : TelegramWebhookBot() {
    override fun getBotUsername() : String = Cred.bot

    override fun getBotToken(): String = Cred.token

    override fun getBotPath(): String = UUID.randomUUID().toString()

    override fun onWebhookUpdateReceived(update: Update?): BotApiMethod<*>? {
        return null
    }
}

package morse

import org.telegram.telegrambots.api.methods.send.SendMessage
import org.telegram.telegrambots.api.objects.Update
import org.telegram.telegrambots.bots.TelegramLongPollingBot
import org.telegram.telegrambots.logging.BotLogger
import java.util.*


class LongPollingHandler : TelegramLongPollingBot() {
    override fun getBotUsername(): String = Cred.bot

    override fun getBotToken(): String = Cred.token

    override fun onUpdateReceived(update: Update?) {
        BotLogger.info("LongPollingHandler", update.toString())
        try {
            if (update?.hasMessage()!!) {
                val message = update.message
                if (message.hasText()) {
                    val sendMessageReq = SendMessage()
                    sendMessageReq.setChatId(message.chatId)
                    sendMessageReq.text = "You just told me " + message.text
                    sendMessage(sendMessageReq)
                }
            }
        } catch (t: Throwable) {
            BotLogger.error("onUpdateReceived", t)
        }
    }

    fun broadcast() {
        BotLogger.info("LongPollingHandler", "broadcast")

        val sendMessageReq = SendMessage()
        sendMessageReq.chatId = "A negative chat it you get when added to the group"
        sendMessageReq.text = "Random message sent from Google Cloud at " + Date()
        sendMessage(sendMessageReq)
    }
}
maven was used to build, package and run this code.

Google Compute Engine

The easiest part! Nothing much to say. I went for the simple CPU/Mem option available, installed Java 8, Maven, uploaded my code, built entirely locally, and ran it via maven exec:java

Result!

Thursday, 15 December 2016

Decode Your FIX has gone SSL

https://www.fixdecoding.org/ is a web site developed by Paul and myself. Free of use :-)

Monday, 28 November 2016

Ethereum Wallet is amazingly slow to sync

Since the last hard fork, and I must say, even before that, I am struggling with the use of ethereum mist. What a nightmare, does not sync up, very slow, 27,000 blocks behind and no sync end in view...
According to the logs, worst case, it takes 40 secs to get one block, 27,000 blocks, more than 12 days! What!

Sunday, 20 November 2016

BTC to ETH

From my previous post first-experience-with-ethereum, you would have read that I was waiting for my transaction to go through to buy ETH from BTC.
I submitted the transaction on 18/11/2016 at 16:39 - it finally went through more than a day later.....

Blog Archive