Wednesday, 31 July 2019

How to create a Blockchain ecosystem?


    The blockchain technology is permanently evolving. It allows users to create an immutable and reliable system for recording any kinds of transactions or information. There are some key pillars to sustain the value of this technology. Those are,
   * Cryptographic Hash
   * Blockchain Validation or Mining
   * Immutable Ledger
   * Consensus Protocol
   * P2P Network
      Before we start creating the blockchain, you need to install the Flask which is the web framework to build the web application that contains the blockchain using the server. So, type the command 'pip install Flask==0.12.2" in the Anaconda prompt. The anaconda prompt is equivalent to the command-line interface in windows. Also, you need to install Postman which is the HTTP client of a user-friendly interface to interact with the blockchain. Most importantly, we will use the Get request in Postman.
      Building the blockchain has two parts. First, we need to build the architecture of the blockchain. You can display the blockchain using the Postman user-friendly functions. Then, we need to add new blocks in the blockchain. So, you need to import the libraries like DateTime which is used for the exact date of the block created and mined. The hashlib used to hash the block for the hash function. and the JSON function will be used to encode the block before hashed up. Finally, from the flask library, we will import the flask class. The jsonify will return the messages in postman when we interact with the blockchain. When we make the request to blockchain to display the whole blockchain, the jsonify will be used to display the responsive request of an index of a new block, proof of the new block, previous hash and the message that the block has been mined.
Creating the Blockchain:
         Start to build a blockchain with the class and name of the class. Inside the class, define all the components of the blockchain that includes the genesis block, chain, init function, create_block function that adds a new block which will be used to mine later on. Then, we need to add the tools to make the blockchain is solid that can not be hacked or broken. So, It is to start with init method that contains self variable and initializes the blockchain. The first block of the blockchain is the genesis block. The create block function in init function has two arguments such as proof (=1) and the link to the previous block(previous_hash = '0'). The SHA256 function in the hashlib library accepts only the string so put the previous_hash value in string format. This will also be used to append the mined block in the blockchain.

Block Structure:
                  The create_block() function will create the block and add to the blockchain. So, it has arguments of self, proof, and previous_hash.  What it has to do is to define the new block to be mined. So, create the variable with a dictionary that will define each block in the blockchain with its 4 essential keys. Those are the index of the block, timestamp, the proof of the block and previous hash. Once, you have the block, you need to append to the chain, So, simply take the list and use the append function this block. The get_previous_block() function will be used to get the last block of the current chain and returns at any time. So, it just returns self.chain[-1]. The chain-1is the last block of the chain.
Proof Of Work: 
          Next function is proof_of_work() which the miners will execute and find the proof. Proof of work is the number or piece of data the miners have to find in order to find a new block. When the miners solve the problem and find potential proof_of_work, then other miners need to verify indeed the first miner solved the problem. This needs to be implemented in this function. The miners need to consider previous proof to find the new proof once we defined the problem. Here, we make the blockchain with a simple proof of work with 4 leading zeros.
     First, the hash operation will generate the 64 characters using the SHA256 in hashlib function. The second part of the problem is to check the first 4 characters of the hash operations are 4 zeros. If the first 4 characters are 4 leading zeros, the miner wins and the proof will be set to true and the new_proof will be returned. If the miner loses, the new_proof will be incremented by 1 for the next check. Finally, The new_proof will return the cryptographic hash to mine new block. 
     The hash() function will hash each block so that we have more structured code. So, it will take the block as input and return the SHA256 cryptographic hash of the block which is exactly the hash_operation.

Validating the Block:
              At any time, we must able to validate the block or a chain of a block is valid in terms of integrity. The blocks need to be validated when we receive a new block from other nodes and must decide whether to accept or not. So, we must check the blocks in the blockchain has the correct proof of work that means the cryptographic hash starts with 4 leading zeros in our example. The second thing is the previous hash of each block is equal to the hash of the previous_block. By checking these 2 things, we have a valid blockchain.  
         The Is_chain_valid() function will check the whole chain of the blockchain is valid. This will return true if everything is correct in the blockchain meaning each block is the valid proof of work.  So, take the chain and iterate to check for each block of the chain. Also, We will check that the previous_hash of the current block is equal to the hash of the previous block. The second check is that the proof of each block is valid. It means that the cryptographic hash_operation must start with 4 leading zeros for each of the block. 

Blockchain Mining: 
    The Flask based web application helps to interact with blockchain by making get requests in our Postman user-friendly interface. There are 4 things you need to do in blockchain mining. Those are
   * Creating the Web Application
   * Creating the Blockchain object
   * Mining a New Block
   * Getting the Full Blockchain
           The Flask quickstart guide has all the information to start using the flask. The first step when using the flask is to create a web application. So, you need to create the object app from the flask class which is already imported from the python library. Remember, when you mine a block and want to display in postman, you need to use @app.route() function that has the requests. We have 2 requests that are mine_block() and get_chain().
          Now, we need to mine a new block by making a new request that we have in flask based web application. The mine_block() function will need to solve the proof of work problem and the keys required to create the block are index, timestamp, proof, and previous_hash. The response variable contains all the information about the block with messages. Lastly, you need to return this response to the user-friendly display of postman. We use the jsonify to return the response in JSON format with the status code of 200 which is a standard response for successful HTTP requests. This is the first function will interact with the blockchain.
        The second get request is the full blockchain to be displayed in the user interface of postman.  So, the response variable contains what will be displayed when we send the get request. Basically, it contains two keys which are chain key and the value of the key is the chain of our blockchain. This will display the whole chain. The second variable is the length of the blockchain which will count the whole block. Now, you can return the response in JSON format with HTTP status code of 200.

BlockChain Creation Demo: 

               Now, we are ready to run the code of the Blockchain implementation from our flask app. In the postman, we will test 2 requests. We start with the get_chain request to test the genesis block is created with the proof of 1 and previous_hash of 0 and we mine as many blocks as we want and get_chain for the actual state of the chain. So, run the app with the single line of code that has the arguments of host and port. The flask quickstart guide provides information about the host of  '' will make the server publically available for a port no 5000. So, start to run the application at the right folder in anaconda prompt. Once the server is running, jump into postman. Then,simply make the get request and request url . The flask url( and add the get_chain request which will create the genesis block.

           Now, you can mine for new blocks by mine_block() function. As you can see the index: 2 or second block is created. We have the previous hash and the proof. The solution to our problem is a cryptographic hash of square of the new proof minus square of the one starting with 4 leading zeros which is 533 and we have the timestamp of the block mined. Now, we request the get_chain which will give the whole blockchain. The length of the chain will be displayed at the end of the chain.

        Finally, it is to check if the blockchain is valid or not. So, it is new a get request with the name of is_valid. Now, the Is_valid() function is ready to execute this request in postman. We will use is_chain_valid method to return true or false when the blockchain is valid or not. If it is true, it will display everything is alright else it will display as we have the problem in the blockchain.


Monday, 15 July 2019

What are the basic things to know in Python Programming?


     Python is a high-level programming language that are easy to write programs and faster than different languages. If you want to compare C and Python to write the code, the 10 pages in C language will take one or 2 pages in Python. Python languages are used when you really need something done fast. It is a scripting language that allows you to do simple tasks for you. There is something called idle which is similar to a command shell, you can give simple instructions and test programs. Python professionally can be used for back-end development to analyze data and parse data when you have a huge pile of data. There are libraries to extract the things that you need from the file of data. Python3 is widely used on the server side and for scripting. It includes various testing, building, monitoring frameworks, scientific apps etc., It is widely used as an embedded language.
      If you have a newer version, feel free to download the stable release to work perfectly in Python3 website, and not in Python2. Follow the actual process of installation and later on, you can add the Python3 to the desktop directory by adding executable of this program. The interactive development environment used to help with the errors in coding. It simply executes a single line at a time.

Python Programming: We are going to use the idle and write the program in the idle notepad shell.
So, just click on the file, it will open new file same as the idle window and run the program from there. You can try out the programs from the idle and start programming by converting int, string and redesigned_string etc., Importing the module is important in python because it allows importing different python programs into our own program which allows using different functions, methods from that specific programs. In order to access the specific functions on the library like os, random, subprocess etc., you need to specify the name of the library with dot and specify the name of the function For ex, To import the library called os,  just type the command of import os and execute as os.system('mkdir test'). Finally, Go to the python.exe directory in terminal and run the command >> python.exe which will create test directory.

Defining the Functions in Python: The functions will be used once you need to cover a large part of the programs that will actually repeat itself throughout the code itself. So, you want to create a function that will do that certain part. You can actually call that function every time you need it without coding the same. Basically, the function called print and what you specified in between the brackets are parameters of that function. We can write our own printing function like my_print and in the brackets specify what you want to print. In order to define the function in specific name, use def and type the name of the function. For ex, def my_print(string) : print(string). So, this will define our own functions.
             Sometimes, you actually want to return something from the function. For ex, if we want to
pick the random integer between 1 and 5 and print the different statement for each number that the actual random library picks. We can do that in the function and print the actual string. Let's open the new file and start coding by importing the random and create a random number using the random library from the range of 1 to 4. With randint function, the random number will take the value between 1 and 4 depending on what the program picks. Then we create the pick variables that will call this function and store its value of the outcome to the pick variable and then print the pick variable. So, when you run the module the output will be generated from the random library generated number and printed out while returning from the function.

Python Lists, Tuples, and Dictionary: Lists can store multiple values in a specific array. The syntax for lists in python is square brackets.  Lists are used to store different types of element that belongs to the same group. It has the following properties,
  1.  It can store string, boolean, float, and numbers in one list. Also, you can store the list elements into a certain variable and will print out the list that we specified. Remember, the actual counting starts from zero and does not start counting from 1.
 2. You can concat(+ in print) the element in the list. For ex, print( 'This is a ' + stationary_item[2]). It will print the 3rd element in the list with concated  message.
 3. The list can also have multiple symptoms of  an element that is going to be an entire different list. For ex, list = [[1,2,3,4], ['salt','pepper','water','milk']]. Here, the first list contains the number and the second list has the kitchen items. Suppose, if you want to select the pepper, just type the command of print(list[1][1]). This will print pepper.
Tuples: Some of the things that are actually similar to lists are called tuples. If you want to print the letters in the variables, you can specify the element position or use the for loop to retrieve all the letters in the variable. For ex, >>animal = "Rabbit", in order to print the letters in the variable of animal, type the command "for letter in animal : print(letter)". This will print R, a, b, b, i, t.
Dictionary in python is a collection of many values just like the list. In the dictionary, we have two separate types of values. Those are keys and values that are separated by two dots. The syntax for opening the dictionary is curly brackets{} that have key: values. For >> number_list = {'five':5, 'four':4,'two':2}. So, if you want access five, just type number_list['five'] which will print the value 5.

 Files in Python:  We need to import the os, subprocess or other libraries for accessing the files. It
has the functions of getcwd(), chdir() etc for handling the directories. The function mkdir will help you to create the folder in a specific directory. You can also look at different functions in the OS library like os.path.dirname, os.path.getsize, os.path.basename and check whether a certain file exists or if it is direct etc.,
      To open certain files in python, we need to use command open with the arguments of filename and mode of opening the file(W, R, A). The W mode is for writing, A for appending and R for reading the file. For ex,  fn = open('file.txt', r) then function will help to read the contents in the file. If you want to open the file in write mode, and use the write command for overwriting into the file. If you don't want to delete the contents in the file and simply want to add something, the A option will help to append the string into the file. Finally, if you just want to read the text from the file, use the option 'rt'. This will display the text in string format.

Object-Oriented Programming: The first thing, you encounter the OOPs is class. The class is a user-defined prototype for an object that defines a set of attributes characterized of any class. Basically, the class has data members, variables, and instance variables. Also, it has methods or function. The class variables are shared by all instances of the class. Class variables are defined within a class are coded at the beginning of the class. An instance is an individual object of a certain class. The inheritance transfer the characteristic of a class to other class that is derived from it. Data member holds the data associated with a class and its object. The object is the unique instance of that data structure that is defined by the class. 
             Let us create the class defined to our employees of the existing company and have the
variable that will count the number of employees and will set to zero at the beginning. We have the init function which is called the class constructor or initialization method that
python calls when you create the new instance of the class. Basically, this method will take all the variables that are going to be part of the employees. The python will take the self argument to list for you. So you don't need to include it when you call the methods. The actual variables of name, email, age, are three different values of the employees. This class actually used on certain employee count and increase the employee count by one. So, this function should be in the class.
    Now, create the actual method that will take the self argument because it belongs to the class and print the total employee number. The third function will display the information about the specific employees. Now, we can create instances of a class or add the person to the employee class. In order to add it to an actual class, we need to specify employee of their details of name, email, and age. This will create instances of the employee class.

Interacting with HTTP: There are two different modules(lib, libtool) handle HTTP related operations. But, We need to write lot of codes to make simple HTTP request. There is an third party library known as request is available and the developers prefer to use instead of lib library. It does not Pre-installed in Python, So, you need  a "pip install request" in your Pyhton Scripts directory. Once you performed this command, you can go back to the idle and type import requests. then, we use get request to retrieve data from any destination. Suppose, we want to retrieve the contents of the home page and print out the html data, you need to include html page link inside the get command and print the contents of that page.

The post requests are opposite of get requests. Basically, it means of sending data to a server as opposed to retrieving it. We are going to pass it in the data parameter and perform it on the website. In the idle, import requests library , then we need to create the payload which is our data currently and pass the username and password. Now, we need to create the post request and specify the link in the brackets and specify data equals to payload. If print in the text format of the url, you can see the username and password are passed to the form. You can also send the files through post request.

Monday, 1 July 2019

ads.txt, pub-3390807332255810, DIRECT, f08c47fec0942fa0