Monday, 17 September 2018

Solidity - II

After the first post on Solidity in Remix, we look at the basic types that are encountered while programming in Solidity. We will be using the online Remix IDE for all the work in this post.

Let us see the program below that shows us the default values of the basic data types:

pragma solidity ^0.4.25;

contract Types {
        bool Boolean;
        int SignedInteger;
        uint UnsignedInteger;
        address Address;
        byte Byte;
        string String;
        function getDefaultValues() public view returns (bool, int, uint, address, byte, string) {
    return (Boolean, SignedInteger, UnsignedInteger, Address, Byte, String);
        }
}

The function defaultValues() is a getter function. view is used bool is be used to define boolean variables in Solidity. int stands for signed integers of 256 bits. We can define int of 8 bits as int8 and then multiples of 8 like int16, int24 and so on till int256. uint represents unsigned integers and is of 256 bits. unit can also be represented in the same way as int: uint8, unit16, uint24, ..., unit256. address type defines an Ethereum address and is of 20 bytes. byte is byte array and is equal to bytes1. Like int, it also variants like bytes2, bytes3, and so on till bytes32. string type defines strings. Compiling the above contract in Remix gives the below result:













Running and deploying we see below result:













Note that there is no output for string data type. Now let us do a few operations on the default values:

pragma solidity ^0.4.25;

contract Types {
        bool Boolean;
        int SignedInteger;
        uint UnsignedInteger;
        address Address;
        byte Byte;
        string String;
        function changedValues() public view returns (bool,int,uint,address,byte,string) {
    return (!Boolean, SignedInteger-1, UnsignedInteger+2, Address, Byte|0x10, String);
        }
}

Running above program shows below result:


We can compare the results with the results of the earlier run and see that values of 4 variables have changed. In the last example, we show the classic overflow and underflow examples in int8:

pragma solidity ^0.4.25;

contract IntTypes {
        int8 i=1;
        int8 j=2;
        int8 k=127;
        int8 l=-128;
        int8 m=3;
        function setInt() public {
            i++;
            j--;
            k++;
            l--;
            return;
        }
        function getInt() public view returns (int8,int8,int8,int8,int8) {
        return (i, j, k, l, m++);
        }
}

Let us run the above program. When we try to deploy the program, we get two buttons called setInt and GetInt in line with the function names as shown below:











Now, click on getInt button to see default values as shown below:













Now that i, j, k, and l are in line with the values that we have set when we defined these variables. But, the ++ increment operator fails on m as it does not increment m and returns the same value that is set when it is defined. Now, click on setInt button and then getInt again to see the results below:












Note that i is incremented from 1 to 2, j is decremented from 2 to 1, k overflows and is reset to -128, l underflows and is reset to 127. The overflow and underflow occur as the range of values that int8 can take are from -128 to 127. Note again that m remains the same and is not incremented. While ++ increment operator or -- decrement operator work well within the body of the function, they do not operate on the variable in the return clause.

This concludes the second post on Solidity

Saturday, 15 September 2018

Solidity - I

I am really excited to be writing on another emerging area that has caught the imagination of many in the past decade: Blockchain. It is only appropriate at the start itself to share the link to the seminal paper on Bitcoin. Following the arrival of Bitcoin, many cryptocurrencies have been invented and there has been a lot of effort to leverage the underlying Blockchain technology for transactions. 

For this post, we look at Solidity Solidity is high-level language for implementing smart contracts in Ethereum. It has borrowed from existing languages as C++, Python, and Javascript. We will be using the online Remix IDE for all the work in this post. The reason for using this online IDE is to directly getting a hands on feel for Solidity rather than getting bogged down with the usual setting up or installation of some tools, etc.

Remix IDE can be accessed by navigating to https://remix.ethereum.org as shown below:













We will write, compile, and run smart contracts in Remix. In this post, we will run a simple smart contract and this will get us familiarized with Remix as well. There are four sections in Remix as shown below:













The blue rectangle on the left is the file browser that can be used to create files with .sol suffix that will have the smart contracts written to. The files can be called in the editor indicated by the green rectangle. To the right of the editor we can see the admin section indicated by orange border that has the following tabs: Compile, Run, Analysis, Testing, Debugger, Settings, and Support. Lastly, below the editor, we see the Remix terminal that can be used for checking transactions details and start debugging, running JavaScript scripts, and executing common command to interact with the Remix interface. Note that like the language Solidity, Remix IDE also is subject to frequent changes. All that is recorded in this post is as it exists on the date this post is written.

Let us see our first smart contract:

pragma solidity ^0.4.25;
contract greeter {
    function greet() public pure returns (string) {
        return "Hello, World!";
 }
}

Let us quickly review this code before we run in Remix IDE. The pragma directive as the first line of the smart contract specifies the version of the Solidity compiler that should be used for compiling the following smart contract. greeter is the name of the smart contract and it contains a function called greet. Functions are by default public in Solidity. pure keyword indicates that the function greet() will neither read nor modify the storage state. returns spells out the return type and it is string in this case. The next line merely returns the "Hello, World!" string. Let us run this in Remix IDE. Click on + icon in the file browser on the left top as shown below:
















In the window that comes up, enter greeter.sol as shown below:










Click on OK. Now we can enter our first smart contract in the editor as shown below:
















In the admin section, click on Start to Compile button under Compile tab. On successful compilation, a light green message with the contract name is seen as shown below:












Since this has compiled successfully, we can deploy it. Click on the Run tab. The Run details are shown:












Before deploying, make sure that the Environment is set to Javascript VM and that greeter appears in the dropdown above the Deploy button. Click on the Deploy button. Once the Deploy button is clicked, we see an entry under Deployed Contracts as shown below:













Click on the entry seen. A button called greet corresponding to the function defined in the contract is seen. Click on that to see Hello, World! as shown below:

























This concludes the first post on smart contracts in Solidity

Tuesday, 21 August 2018

Python - III

After seeing file handling in this post, and string handling in this post, we will take a look at how JSON is handled in Python in this post. For all the work in this post, like before, we will be using CLI of Python 3.7.0(the latest version of Python as of the time this blog is being written).

There are four methods that can be used for encoding and decoding JSON in Python. They are dump, dumps, load and loads. The method dump serializes an object as a JSON formatted stream and stores it as a file. Encoding into JSON will use below conversion table:












For the first example, let us consider a string called data that is encoded into JSON using dump. dump takes a few parameters that are shown in examples below.

>>> import json
>>> data = {"connection": {'Latitude': 41.556895, 'Longitude': -72.665225}, "loc": [-72.665225, 41.556895], "loc_tup": (-72.665225, 41.556895), "state": "CT", "pop": 42846, "enroute": True, "travel": None}
>>> json.dump(data, open('json_file.json','w'))  # we can create a file and write to it

Now, let us examine the file:









Note the encoding conversion of the elements from Python to JSON as per conversion table above. To read this file in prompt:

F:\PythonPrograms>type json_file.json
{"connection": {"Latitude": 41.556895, "Longitude": -72.665225}, "loc": [-72.665225, 41.556895], "loc_tup": [-72.665225, 41.556895], "state": "CT", "pop": 42846, "enroute": true, "travel": null}

To pretty print it, use below command:

F:\PythonPrograms>type json_file.json | python -m json.tool
{
    "connection": {
        "Latitude": 41.556895,
        "Longitude": -72.665225
    },
    "loc": [
        -72.665225,
        41.556895
    ],
    "loc_tup": [
        -72.665225,
        41.556895
    ],
    "state": "CT",
    "pop": 42846,
    "enroute": true,
    "travel": null
}

F:\PythonPrograms>

Instead of using dump to write the JSON to a file, we can also use StringIO() that reads and writes a string buffer:

>>> from io import StringIO
>>> io = StringIO()
>>> json.dump(data, io)
>>> io.getvalue()
'{"connection": {"Latitude": 41.556895, "Longitude": -72.665225}, "loc": [-72.665225, 41.556895], "loc_tup": [-72.665225, 41.556895], "state": "CT", "pop": 42846, "enroute": true, "travel": null}'

>>>

In the next example, we will add a few parameters. For this example, we will use another string dump_1:

data_1 = {"connection": {'Longitude': -72.665225, 'Latitude': 41.556895}, "loc": [-72.665225, 41.556895], "loc_tup": (-72.665225, 41.556895), "state": "CT", "pop": 42846, "enroute": True, "travel": None, "special": "ÃΣ"}

>>>
>>> json.dump(data_1, open('json_file_1.json','w'), ensure_ascii=True, indent=None, separators=(',', ':'), sort_keys=True)

>>>

Let us now inspect the created file using type:

F:\PythonPrograms>
F:\PythonPrograms>type json_file_1.json
{"connection":{"Latitude":41.556895,"Longitude":-72.665225},"enroute":true,"loc":[-72.665225,41.556895],"loc_tup":[-72.665225,41.556895],"pop":42846,"special":"\u00c3\u03a3","state":"CT","travel":null}

F:\PythonPrograms>

ensure_ascii=True ensures that the output is guaranteed to have all incoming non-ASCII characters escaped. See the encoding on ÃΣ. json.dump(data_1, open('json_file_1.json','w'), ensure_ascii=True, indent=None, separators=(',', ':'), sort_keys=True) removes any whitespace. Compare current type output with previous type output to see the difference. sort_keys=True sorts the keys of any dictionaries in the input. In our case, see the reordering of "connection" dictionary.

dumps is similar to dump expect that the input object is serialized to a JSON string using the same conversion table that dump uses. It also uses the same parameters as dump but here we do not specify any file name. An example is shown below:

data_1 = {"connection": {'Longitude': -72.665225, 'Latitude': 41.556895}, "loc": [-72.665225, 41.556895], "loc_tup": (-72.665225, 41.556895), "state": "CT", "pop": 42846, "enroute": True, "travel": None, "special": "ÃΣ"}

>>> json.dumps(data_1, ensure_ascii=True, indent=None, separators=(',', ':'), sort_keys=True)
'{"connection":{"Latitude":41.556895,"Longitude":-72.665225},"enroute":true,"loc":[-72.665225,41.556895],"loc_tup":[-72.665225,41.556895],"pop":42846,"special":"\\u00c3\\u03a3","state":"CT","travel":null}'

>>>

To pretty print the output, we can set indent to 4 as shown below:

>>> print(json.dumps(data_1, ensure_ascii=True, indent=4, separators=(',', ':'), sort_keys=True))
{
    "connection":{
        "Latitude":41.556895,
        "Longitude":-72.665225
    },
    "enroute":true,
    "loc":[
        -72.665225,
        41.556895
    ],
    "loc_tup":[
        -72.665225,
        41.556895
    ],
    "pop":42846,
    "special":"\u00c3\u03a3",
    "state":"CT",
    "travel":null
}
>>>

load deserializes a JSON file to a Python object according to below conversion table:














We will decode the encoded JSON file, json_file_1.json, as shown below:

>>>
>>> json.load(open('json_file_1.json'))
{'connection': {'Latitude': 41.556895, 'Longitude': -72.665225}, 'enroute': True, 'loc': [-72.665225, 41.556895], 'loc_tup': [-72.665225, 41.556895], 'pop': 42846, 'special': 'ÃΣ', 'state': 'CT', 'travel': None}
>>>

You can see the converted values.

loads is similar to load but takes encoded JSON string as shown below:

>>> data_1 = {"connection": {'Longitude': -72.665225, 'Latitude': 41.556895}, "loc": [-72.665225, 41.556895], "loc_tup": (-72.665225, 41.556895), "state": "CT", "pop": 42846, "enroute": True, "travel": None, "special": "ÃΣ"}
>>>
>>> encoded_JSON =  json.dumps(data_1, ensure_ascii=True, indent=None, separators=(',', ':'), sort_keys=True)
>>>
>>> json.loads(encoded_JSON)
{'connection': {'Latitude': 41.556895, 'Longitude': -72.665225}, 'enroute': True, 'loc': [-72.665225, 41.556895], 'loc_tup': [-72.665225, 41.556895], 'pop': 42846, 'special': 'ÃΣ', 'state': 'CT', 'travel': None}
>>>

This concludes the discussion of JSON in Python