<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Juhi Tiwari on Medium]]></title>
        <description><![CDATA[Stories by Juhi Tiwari on Medium]]></description>
        <link>https://medium.com/@tjuhi.321?source=rss-55f88c4a6f15------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JGOeOpoZM_nU3qVuzmZmWQ.jpeg</url>
            <title>Stories by Juhi Tiwari on Medium</title>
            <link>https://medium.com/@tjuhi.321?source=rss-55f88c4a6f15------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:56:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tjuhi.321/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Join the Dark Side — Implementing Dark Mode in React Native]]></title>
            <link>https://medium.com/tech-iiitg/join-the-dark-side-implementing-dark-mode-in-react-native-49b0a32e57f7?source=rss-55f88c4a6f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/49b0a32e57f7</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[dark-theme]]></category>
            <dc:creator><![CDATA[Juhi Tiwari]]></dc:creator>
            <pubDate>Thu, 03 Sep 2020 06:24:49 GMT</pubDate>
            <atom:updated>2020-09-03T06:35:29.663Z</atom:updated>
            <content:encoded><![CDATA[<h3>Join the Dark Side — Implementing Dark Mode in React Native</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QDQvlCg420lzRElCK4AYhw.png" /></figure><p>Adding support for dark and light themes in mobile applications can enhance the user experience by a manifold. From YouTube to Whatsapp, Instagram, Telegram, or Slack, many famous apps have extended the dark mode support to their platforms. And even if you prefer to remain in the light, one can easily leverage the dark mode support for various users in a few easy steps. Since the YouTube app looks a lot better in dark mode, let us implement dark mode by building a very basic clone of the app wherein we will mainly focus on toggling between dark and light themes.</p><p>The basic UI skeleton for the app, before we move ahead would look like as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUNt_fg0iw3sXYydG8INSQ.jpeg" /></figure><p>We have a custom header with the YouTube logo and some other icons, one of which (the theme toggling icon) will do our magic. A simple bottom tag navigator is also present similar to the app, with the active tab highlighted with red color. You can find the UI starter code required for this project <a href="https://github.com/juhitiwari/DarkThemeYoutubeStarter">here</a></p><p>A dark mode version of the app would look like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpWYeDkg4R0e4ivsdPEXAg.jpeg" /></figure><p>Notice how the icon color changes to white and the active tab is also shown in white in contrast to red as in the light mode.</p><p>We can implement dark mode via a couple of options such as <em>react-navigation</em>, <em>styled-components,</em> or the <em>react-native-appearance</em>. In this particular app, we will be using <em>Themes</em> under <em>React Navigation</em>. You can find the documentation <a href="https://reactnavigation.org/docs/themes/">here</a>.</p><p>We are provided with <em>DefaultTheme</em> and <em>DarkTheme</em> built in to React Navigation as well as an option of customizing these themes. In your App.js or wherever the entry point of your app is import the following:</p><pre>import {DefaultTheme,DarkTheme} from &#39;@react-navigation/native&#39;</pre><p>We can wrap the entry point of the app with the themes:</p><pre>&lt;NavigationContainer theme={DarkTheme}&gt;<br>      &lt;Stack.Navigator headerMode=&quot;none&quot;&gt;<br>      &lt;Stack.Screen name=&quot;home&quot; component={Home} /&gt;<br>      &lt;/Stack.Navigator&gt;<br>&lt;/NavigationContainer&gt;</pre><p>However, this alone will have no effect on our custom components like the header or the bottom navigator. We can customize them by changing the theme prop dynamically.</p><p>We customize both our themes: <em>DarkTheme</em> and the <em>DefaultTheme</em> as new JS objects in our <em>App.js</em>. In the <em>DarkTheme</em> we would like the icons and active icon to be white in color and the header background color to be gray. Similarily in the <em>DefaultTheme</em> we would like the icons to be black and the active icon to be red. The header&#39;s background would be white. Thus we add these colors to the colors property for both of our themes.</p><pre>const myDarkTheme={<br>  ...DarkTheme,<br>  colors:{<br>    ...DarkTheme.colors,<br>    headerColor:&quot;#404040&quot;,<br>    iconColor:&quot;white&quot;,<br>    activeTabColor:&quot;white&quot;<br>  }<br>}<br><br>const myDefaultTheme={<br>  ...DefaultTheme,<br>  colors:{<br>    ...DefaultTheme.colors,<br>    headerColor:&quot;white&quot;,<br>    iconColor:&quot;black&quot;,<br>    activeTabColor:&quot;red&quot;<br>  }<br>}</pre><p>To use our customized themes in components rendered inside the navigation container (such as other screens like Search, Explore, Notifications, or your custom header), we can use the hook: <em>useTheme</em>. Import the hook in your component as follows:</p><pre>import {useTheme} from &#39;@react-navigation/native&#39;</pre><p>The hook returns the theme object, whose property can now be accessed and used in our components.</p><p>So in our custom header get the theme object from the hook as follows:</p><pre>export default function Header(){<br>    const {colors}=useTheme()<br>    /* your logic goes here */<br>}</pre><p>Now we defined header color and icon colors in our customized themes in App.js. These properties can be accessed as <em>colors.headerColor</em> and <em>colors.iconColor</em> as follows:</p><pre>export default function Header(){<br>    const {colors}=useTheme()<br>    return (<br>      &lt;View style={[styles.header,{backgroundColor:colors.headerColor}]}&gt;<br>        &lt;View style={{flexDirection:&#39;row&#39;,margin:5}}&gt;<br>            &lt;Entypo<br>            name=&quot;youtube&quot;<br>            size={32}<br>            color=&quot;red&quot;<br>            style={{marginLeft:20}}/&gt;<br>            &lt;Text style={[styles.headerText, <br>              {color:colors.iconColor}]}&gt;YouTube&lt;/Text&gt; <br>        /* Rest of the icons go here */<br>        &lt;/View&gt;<br>}</pre><p>The view with the header style has been given a background color as specified by the theme. The logo text “YouTube” too will have a font color as specified by the theme. For the other icons in our header, a similar process can be followed where the icons will have a color specified by <em>colors.iconColor</em></p><p>We can also customize the icon colors and text colors in the bottom tab navigator.</p><pre>&lt;Tabs.Navigator<br>    screenOptions={({ route }) =&gt; ({ <br><br>      //accessing the icon colors from tabBarOptions<br><br>      tabBarIcon: ({ color }) =&gt; {<br>        let iconName;<br><br>        //determining which icon to be used for each tab<br><br>        if (route.name === &#39;Home&#39;) {<br>          iconName = &#39;home&#39;;<br>        } else if (route.name === &#39;Explore&#39;) {<br>          iconName = &#39;explore&#39;;<br>        }else if(route.name === &#39;Subscriptions&#39;){<br>          iconName = &#39;subscriptions&#39;<br>        }<br>        else if(route.name === &#39;Notifications&#39;){<br>          iconName = &#39;notifications&#39;<br>        }<br>        else if(route.name === &#39;Library&#39;){<br>          iconName = &#39;video-library&#39;<br>        }<br>        <br>        //returning icons for each tab with the specified color<br><br>        return &lt;MaterialIcons name={iconName} size={20} <br>          color={color} /&gt;;<br>      },<br>    })}<br>    tabBarOptions={{<br><br>      //specifying the active tab color from our colors object returned from useTheme hook<br><br>      activeTintColor:colors.activeTabColor,<br>      inactiveTintColor: &#39;gray&#39;,<br>    }}&gt;</pre><p>And that’s it! Using a similar process you can customize other screens in your app as well. For example, you might want to change the text color as white when in dark mode and to black when in light mode. And it will be exactly similar to what we have done till now.</p><p>Now the only thing left it to toggle between the modes. Right now whatever theme the <em>NavigationContainer</em> is using, the corresponding customized theme is being used across the app. From our original UI mockup, we have a button in the header (our theme icon) which will help us toggle between the themes. Since we need to use this theme value across various screens in the app we will have to make use of <em>Redux</em>.</p><p>Create a folder for our reducers in the <em>src</em> directory, inside which create a reducer file <em>themeReducer.js</em> and declare as follows:</p><pre>const initialState=false<br>export const themeReducer=(state=initialState,action)=&gt;{<br>    switch(action.type){<br>        case &#39;toggle_theme&#39;:<br>            return action.payload<br>        default:<br>            return state<br>    }   <br>}</pre><p>Let’s use this reducer by creating a store folder store in<em> src</em> directory, under which create a file <em>Index.js</em></p><pre>import { createStore, combineReducers } from &quot;redux&quot;;<br>import { themeReducer } from &quot;../reducers/themeReducer&quot;;<br>const store=createStore(<br>    combineReducers({<br>          myDarkMode:themeReducer<br><br>    })<br><br>)<br>export default store</pre><p>This is the central state of all our data.</p><p>Use this in App.js as follows:</p><pre>import store from &#39;./src/store&#39;<br>/* all your themes and logic goes here */<br><br>export default ()=&gt;{<br>  return(<br>      <br>     // make the redux store available to the Navigation Component<br><br>     &lt;Provider store={store}&gt;<br>     &lt;Navigation/&gt;<br>     &lt;/Provider&gt;<br>  )<br>}<br><br>export function Navigation(){<br><br>  //useSelector is the hook to access redux store&#39;s state, access whether dark mode is enabled or not<br><br>  let currentTheme=useSelector(state=&gt;{<br>    return state.myDarkMode<br>  })<br>  return(<br>    &lt;Provider store={store}&gt;<br><br>    // if the current theme is enabled, use the customized dark theme else the default theme<br><br>    &lt;NavigationContainer theme={currentTheme?myDarkTheme:myDefaultTheme}&gt;<br>      &lt;Stack.Navigator headerMode=&quot;none&quot;&gt;<br>      &lt;Stack.Screen name=&quot;home&quot; component={Home} /&gt;<br>      &lt;/Stack.Navigator&gt;<br>    &lt;/NavigationContainer&gt;<br>    &lt;/Provider&gt;<br>  )<br>}</pre><p>That is how we access the current theme and share it across various screens. Now the last thing left is to modify the redux state i.e. enable toggling.</p><p>For this, inside the <em>header.js</em> file, use the hooks <em>useDispatch</em> and <em>useSelector</em> as follows:</p><pre>import { useSelector, useDispatch } from &#39;react-redux&#39;;<br><br>export default function Header(){<br><br>    // accessing the current theme<br><br>    const dispatch=useDispatch()<br>    const currentTheme=useSelector(state=&gt;{<br>        return state.myDarkMode<br>    })<br><br>/* your logic goes here */<br><br>   // the icon which has to toggle the theme, in the onPress handler call the toggle_theme action type and the payload to be the opposite of the current theme i.e. if the current theme is dark mode (value true) make it false ( which is default theme).<br>   <br>   &lt;MaterialCommunityIcons<br>            name=&quot;theme-light-dark&quot;<br>            size={24}<br>            color={mycolor}<br>            onPress= <br> {()=&gt;dispatch({type:&#39;add_theme&#39;,payload:!currentTheme})}/&gt;</pre><p>And that&#39;s it! We have successfully implemented the support of toggling between dark and light modes in our react native app!</p><p>Find the complete code <a href="https://github.com/juhitiwari/DarkThemeYoutube">here</a>.</p><p>Apart from React Navigation, here’s another <a href="https://medium.com/crowdbotics/how-to-add-support-for-dark-and-light-themes-in-react-native-8aa5ef5054e9">read</a> for implementing dark mode using react-native-appearance.</p><p>For more such interesting concepts and food for your tech driven curiosity visit <a href="https://www.smartscribs.com/">SmartScribs</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49b0a32e57f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-iiitg/join-the-dark-side-implementing-dark-mode-in-react-native-49b0a32e57f7">Join the Dark Side — Implementing Dark Mode in React Native</a> was originally published in <a href="https://medium.com/tech-iiitg">tech@iiit-gwalior</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your first Cryptocurrency!]]></title>
            <link>https://medium.com/tech-iiitg/make-your-first-cryptocurrency-2b7154493a3c?source=rss-55f88c4a6f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b7154493a3c</guid>
            <category><![CDATA[crptocurrency]]></category>
            <category><![CDATA[bitcoin-mining]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Juhi Tiwari]]></dc:creator>
            <pubDate>Tue, 21 Apr 2020 11:38:05 GMT</pubDate>
            <atom:updated>2020-04-21T11:38:05.663Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/735/0*kFg6zoWUzJpLdoWz.jpg" /></figure><p>This tutorial is in continuation with the previous blog on making your own blockchain <a href="https://medium.com/tech-iiitg/make-your-first-blockchain-58c83c647ba2">here</a>. Make sure to go through this very clearly as we would be using the code to make our very own cryptocurrency.</p><p>We know that the core idea behing blockchains is to decentralize the data. Everyone knows everything and everyone monitors that the data isn’t tampered. This very crux can be used to implement blockchains in cryptocurrency, thus eliminating the needs of any third party intermediaries such as bank. Nodes or people would be connected to each other in a Peer to Peer fashion and transactions can be directly associated with them with each transaction being a part of a block in a blockchain. Thanks to the hashing, the data integrity will be maintained.</p><p>If we look at the cryptocurrency technology stack, we find that it has three layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*uxVmHYXtKnkVyEv8." /></figure><p>Layer 3: It corresponds to the technology that is used in our cryptocurrency i.e. Blockchains, the implementation behind the making of our currency. This we have already covered in our previous tutorial.</p><p>Layer 2: It corresponds to the protocol or the rules that define how transactions are to be done. Bitcoin, Ethereum, Neo, Ripple all these are protocols. Every protocol has a coin associated with it. We are going to work on this layer in this blog.</p><p>Layer 1: It corresponds to any digital asset that was created using Blockchains. We would be focussing on this in coming blogs and see how they rely on one more popular term Smart Contracts.</p><p>So now let’s get our hands dirty! We will be making our own cryptocurrency, wherein we would be executing transactions, sending coins to our friends, and also maintain consensus. Let’s take a moment to understand consensus. We know that the idea behind our currency is that all our friends (or nodes) are connected to each other directly and transactions will take place without any intervention of any bank. Now if in a group of 4 friends 2 of them transfer each other coins, adding transaction to the chain, the other 2 should know about this, meaning that their chain should also be up to date. That is how we say that everyone knows everything. This updation of the chain across all the nodes connected is known as consensus.</p><p>Moving on to coding, make sure the previous code is running. After all our currency is nothing but just another blockchain. So your blockchain should be working. We would be adding the extra code in that.</p><p>Import some extra libraries</p><pre>import requests<br>from uuid import uuid4<br>from urllib.parse import urlparse</pre><p>These will be helpful in estabilishing consensus and making our transactions more distributed.</p><p>We now make some changes in the init function of our blockchain class, where we will be adding to more variables: a list of transactions to hold the transactions made and a set of nodes to keep record od the nodes connected in our distributed network.</p><pre>def __init__(self):<br>        self.chain = []<br>        self.transactions=[]<br>        self.create_block(proof = 1, previous_hash = &#39;0&#39;)<br>        self.nodes=set()</pre><p>Similarily in your create_block function, add transactions to our dictionary. We also empty our transaction list before appending our block to the chain, so that duplicate transactions do not occur in more than one block.</p><pre>def create_block(self, proof, previous_hash):<br>        block = {&#39;index&#39;: len(self.chain) + 1,<br>                 &#39;timestamp&#39;: str(datetime.datetime.now()),<br>                 &#39;proof&#39;: proof,<br>                 &#39;previous_hash&#39;: previous_hash,<br>                 &#39;transactions&#39;:self.transactions}<br>        self.transactions=[]<br>        self.chain.append(block)<br>        return block</pre><p>Now let us make a new function add_transactions that will be responsible for appending sender, receiver and the amount transferred in a dictionary format to the list transaction. The function will return the index of the next block, the block in which the transaction should be added.</p><pre>def add_transactions(self,sender,receiver,amount):<br>        self.transactions.append({&#39;sender&#39;:sender,<br>                                  &#39;receiver&#39;:receiver,<br>                                  &#39;amount&#39;:amount})<br>        previous_block=self.get_previous_block()<br>        return previous_block[&#39;index&#39;]+1</pre><p>We also make a quick function that connects nodes in our network. This is where our urlparse library comes into use. We pass the complete url of the node, out of which we are only interested in the ip address and the port, which can be retrieved via the netloc. For eg, if you pass ‘<a href="http://www.cwi.nl/%7Eguido/Python.html&#39;">http://www.cwi.nl:80/%7Eguido/Python.html&#39;</a> to urlparse the results will be:</p><pre>o = urlparse(&#39;<a href="http://www.cwi.nl/%7Eguido/Python.html&#39;">http://www.cwi.nl:80/%7Eguido/Python.html&#39;</a>)</pre><pre>ParseResult(scheme=&#39;http&#39;, netloc=&#39;<a href="http://www.cwi.nl:80&#39;">www.cwi.nl:80&#39;</a>, path=&#39;/%7Eguido/Python.html&#39;,<br>            params=&#39;&#39;, query=&#39;&#39;, fragment=&#39;&#39;)</pre><p>Here we need just the netloc portion of the result.</p><pre>def add_node(self, address):<br>        parsed_url=urlparse(address)<br>        self.nodes.add(parsed_url.netloc)</pre><p>We now move onto estabilishing the consensus. Once a transaction has taken place among some nodes, all the nodes should be updated i.e each one of them should have the longest chain. How do we do this? We can ask for the current chain from each of our nodes in the network and check if any of the nodes have a chain that is less than the length of the largest chain. If there is, it means there were some transactions in some nodes and the chain needs to be updated. So we parse over our set of nodes and with the help of the requests library we send a request to each of them to get their chains. Remember we did implement this in last blog via our flask app with the function get_chain which returned the chain and its length. We then check this length with the maximum length and update accordingly. Our longest chain initially is none and the maximum length is the length of the current chain.</p><pre>def replace_chain(self):<br>        network=self.nodes<br>        longest_chain=None<br>        max_length=len(self.chain)<br>        for nodes in network:<br>            response=requests.get(f&#39;<a href="http://{node}/get_chain&#39;">http://{node}/get_chain&#39;</a>)<br>            if response.status_code==200:<br>                length=response.json()[&#39;length&#39;]<br>                chain=response.json()[&#39;chain&#39;]<br>            if len(chain)&gt;max_length and self.is_chain_valid(chain):<br>                max_length=length<br>                longest_chain=chain<br>        if longest_chain:<br>                self.chain=longest_chain                <br>                return True<br>        return False</pre><p>That’s all the changes we need to make in our class. We now move on to mining the blockchain and working with the flask app.</p><p>Now everytime, a block is mined, we want the miner to get a reward of may be 10 coins. So the receiver would be the miner, the sender would be our node and amount would be 10. We make use of the uuid4 library, which assigns a unique uuid to a node. We also want to remove the ‘-’, from our uuid.</p><pre>app = Flask(__name__)<br>    <br>node_address=str(uuid4()).replace(&#39;-&#39;,&#39;&#39;)</pre><p>We change our existing mine_block function so that we can have our list transactions in the response and also a transaction of 10 coins for the block has been mined.</p><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/mine_block&#39;, methods = [&#39;GET&#39;])<br>def mine_block():<br>    previous_block = blockchain.get_previous_block()<br>    previous_proof = previous_block[&#39;proof&#39;]<br>    proof = blockchain.proof_of_work(previous_proof)<br>    previous_hash = blockchain.hash(previous_block)<br>    blockchain.add_transactions(sender=node_address,receiver=&#39;Juhi&#39;,amount=10)<br>    block = blockchain.create_block(proof, previous_hash)<br>    <br>    response = {&#39;message&#39;: &#39;Mission Accomplished!&#39;,<br>                &#39;index&#39;: block[&#39;index&#39;],<br>                &#39;timestamp&#39;: block[&#39;timestamp&#39;],<br>                &#39;proof&#39;: block[&#39;proof&#39;],<br>                &#39;previous_hash&#39;: block[&#39;previous_hash&#39;],<br>                &#39;transactions&#39;: block[&#39;transactions&#39;]<br>                }<br>    return jsonify(response), 200</pre><p>We also add an add_transaction function which will take a JSON in the body section. This JSON will contain the sender, receiver and the amount involved in transaction and using our class function add_transactions it returns the block in which the transaction has been appended.</p><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/add_transaction&#39;, methods = [&#39;POST&#39;])<br>def add_transaction():<br>    json=request.get_json()<br>    transaction_keys=[&#39;sender&#39;,&#39;receiver&#39;,&#39;amount&#39;]<br>    if not all (key in json for key in transaction_keys):<br>        return &#39;elements of transaction missing&#39;,400<br>    index=blockchain.add_transactions(json[&#39;sender&#39;],json[&#39;receiver&#39;],json[&#39;amount&#39;])<br>    response={&#39;message&#39;:f&#39;transaction added in the block {index}&#39;}<br>    return jsonify(response),201</pre><p>We create a connect_node function that again takes a JSON in the body section. This JSON has all the nodes that needs to be connected in the network. With the help of the add_node fucntion we add all the nodes in the JSON.</p><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/connect_node&#39;, methods = [&#39;POST&#39;])<br>def connect_node():<br>    json=request.get_json()<br>    nodes=json.get(&#39;node&#39;)<br>    if nodes is None:<br>        return &#39;no node&#39;,400<br>    for node in nodes:<br>        blockchain.add_node(node)<br>    response={&#39;message&#39;:&#39;all nodes connected with following nodes:&#39;,<br>              &#39;nodes&#39;:list(blockchain.nodes)}<br>    return response,201</pre><p>We now quickly add a function replace_chain for handling consenus and updating the largest chain to all the nodes.</p><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/replace_chain&#39;, methods = [&#39;GET&#39;])<br>def replace_chain():<br>    is_chain_replaced = blockchain.replace_chain()<br>    if is_chain_replaced:   <br>        response = {&#39;message&#39;: &#39;nodes updated.&#39;,<br>                    &#39;new_chain&#39;:blockchain.chain}<br>    else:<br>        response = {&#39;message&#39;: &#39;already largest chain&#39;,<br>                    &#39;new_chain&#39;:blockchain.chain}<br>    return jsonify(response), 200</pre><p>Now go ahead and copy the entire code in 3 different files to create three different nodes. Make sure to change the ports in the line app.run(host = ‘0.0.0.0’, port = 5001) with 5001, 5002 and 5003, making 3 different nodes to work with in our network. And that’s it! Run these 3 different python scripts in 3 different consoles.</p><p>Let’s head over to Postman and begin the action! Run the 3 node address in 3 different tabs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p7gssmJi3Upj00-h.png" /></figure><p>Now connect these nodes to each other. For every node do a POST request and supply a JSON of all the the other nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*plqSOAgoqB_eiDp-.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W3gpWPuf9p5Dx20h.png" /></figure><p>Now let’s mine a block and see what happens. On mining a block I transferred 10 coins to Jaroli Sir. Thank me later Sir!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S_QFZgZujeWdA2hy.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5h3JIPxrrPatT3z7.png" /></figure><p>To add a transaction, we give a JSON containing the sender, receiver and amount. The transaction will be added to the block after I mine the blocks.</p><p>However, if you now see the chains in other nodes through get_chain, it will still show the old nodes and not these new transactions. To get all the nodes updated we perform our replace_chain function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yUP_4vaaANCEy56BM7f8ZA.png" /></figure><p>And that’s how all the nodes will now get to the transactions.</p><p>In a practical scenario, we wont be listing sender or a receiver in plain names, instead we will be using their public keys. This is something we will leave for our next tutorial. Also a brownie task for you can be instead of copy pasting the code in n scripts to make n nodes, can we make use of a graph?</p><p>Happy blockchaining!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b7154493a3c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-iiitg/make-your-first-cryptocurrency-2b7154493a3c">Make your first Cryptocurrency!</a> was originally published in <a href="https://medium.com/tech-iiitg">tech@iiit-gwalior</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your first Blockchain!]]></title>
            <link>https://medium.com/tech-iiitg/make-your-first-blockchain-58c83c647ba2?source=rss-55f88c4a6f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/58c83c647ba2</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Juhi Tiwari]]></dc:creator>
            <pubDate>Tue, 21 Apr 2020 11:14:31 GMT</pubDate>
            <atom:updated>2020-04-21T11:14:31.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*oEuVbGpwml1NkMft.jpg" /></figure><p>This tutorial is in continuation with a previous blog <a href="https://medium.com/tech-iiitg/blockchains-a-sneak-peak-into-the-ds-49a836862089">here</a> where you can get an idea of what Blockchains are. We now move on to make our very own simple blockchain using Python. We would be demonstrating it by making a web app on Flask. But before we move on to the code let’s get some basics covered! The whole code would be divided into two steps :</p><p><strong>1. Create a Blockchain : </strong>We would be making blocks that can be added in our chain. Every block would be having its on index number, a timestamp telling us the time at which it is created, the hash of the previous block of the chain and a nonce or the proof of work. To know what a nonce is we shall first understand our second part of the code.</p><p><strong>2. Mining a Blockchain :</strong> This is the part where we will be mining, creating our web app and display our blockchain. Now what is mining? Apart from your usual fields in a blockchain like data, hash, index etc. We have an extra field as well known as nonce aka “number used only once”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/0*Ad3CltwajZrzwkkI" /></figure><p>The nonce is under our control meaning the other fields cannot be changed by us, but we can change the value of nonce. All these fields together can computer the hash for the block. Since we can change the value of the nonce, we can change the hash of the block.</p><p>Now, after a certain fixed time, a minimum value for the hashes is set. Only the hashes below this target value are considered valid. A very important thing in this is the number of leading zeroes in the hash value. With every leading zero the hash value decreases.</p><p>And that’s where we are presented with a super geeky puzzle: find a nonce that can generate a valid hash and then only your block will be added into the chain. This is mining and if you are in the race of solving this problem you are a miner. The more miners, the lower target hash, the more difficulty. In Bitcoin, the difficulty is as such that only one new block is added in 10 minutes.</p><figure><img alt="Image result for blockchain target hash" src="https://cdn-images-1.medium.com/proxy/1*Tj9EVp6RL3qNvjj5yD0BVw.png" /></figure><p>So let’s get our hands dirty now!</p><p>We need to import flask (for our web app), hashlib (to generate our sha256 hash), json(to send our response in JSON format and datetime( to get the current time).</p><pre>from flask import Flask,jsonify<br>import json<br>import datetime<br>import hashlib</pre><p>We will be now building our blockchain and for that we would be creating its class. This will help us in making as many instances of a blockchain as we want.</p><p>Our blockchain will be initialized with our Genesis Block whose previous hash will be zero as there are no blocks before that. Also we can initialize our nonce for this block with any number, we choose 1. We also make an empty chain.</p><p>We will be creating a function create_block which will be responsible for making a new block in our chain.</p><pre>class blockchain:<br>#creating an empty chain at the first instance<br>#making our genesis block<br>   def __init__(self):<br>     self.chain=[]<br>     self.create_block(nonce=1,previous_hash=&#39;0&#39;)<br>#our block will be in the form of a dictionary with an index number, timestamp, nonce(which we will be getting on solving our cryptography puzzle and the hash of the previous block (which we will be providing)<br>#we also append this block in our chain and return our block<br>   def create_block(self,nonce,previous_hash):<br>     block={&#39;index&#39;:len(self.chain)+1,<br>    &#39;timestamp&#39;:str(datetime.datetime.now()),<br>    &#39;nonce’:nonce,<br>    &#39;previous_hash&#39;:previous_hash}<br>    self.chain.append(block)<br>    return block</pre><p>We now make a function that can generate a hash for our block</p><pre>def hash(self,block):<br>  encoded_block=json.dumps(block,sort_keys=True).encode()<br>  return hashlib.sha256(encoded_block).hexdigest()</pre><p>To provide the nonce for our block in our create_block function, we now make another function nonce that checks if our hash value is below our targeted value, if it is so it will return this nonce to us.</p><p>In this function, we solve our puzzle by calculating the difference between squares of the nonce of the previous block and our new nonce. We then check if the hash for this has 4 leading zeroes (we have defined that the target hash has 4 leading zeroes, any hash greater than this is invalid), if yes we return that nonce (yaay you solved the puzzle!). You can come up with any other expression, the only trick is that it shouldn’t be symmetrical.</p><pre>def nonce(self,prev_nonce):<br>  new_nonce=1<br>  check_nonce=False<br>  while check_nonce is False:<br>  hash_operation=hashlib.sha256(str(new_nonce**2-prev_nonce**2).encode()).hexdigest()<br>  if hash_operation[:4]==&#39;0000&#39;:<br>    check_nonce=True<br>  else:<br>    new_nonce+=1<br>  return new_ nonce</pre><p>We can also write a quick function for getting the previous block:</p><pre>def get_prev_block(self):<br>  return self.chain[-1]</pre><p>Create a web app</p><pre>app=Flask(__name__)</pre><p>Make your blockchain</p><pre>blockchain=blockchain()</pre><p>At this instance we have our genesis block and an empty chain</p><p>Now let’s mine our first block:</p><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/mine_block&#39;,methods=[&#39;GET&#39;])<br>def mine_block():<br>  prev_block=blockchain.get_prev_block()<br>  prev_nonce=prev_block[&#39;nonce&#39;]<br>  nonce=blockchain.nonce(prev_nonce)<br>  prev_hash=blockchain.hash(prev_block)<br>  block=blockchain.create_block(nonce,prev_hash)<br>  response={&#39;message&#39;:&#39;mission accomplished&#39;,<br>  &#39;index&#39;:block[&#39;index&#39;],<br>  &#39;timestamp&#39;:block[&#39;timestamp&#39;],<br>  &#39;nonce&#39;:block[&#39;nonce&#39;],<br>  &#39;prev_hash&#39;:block[&#39;previous_hash&#39;]}<br>  return jsonify(response),200</pre><p>Using our get_prev_block() function, we get the last block i.e. right now our previous block is genesis block. Thus, prev_nonce contains a value of 1. And with this value we can now easily solve our puzzle using our nonce function and get a nonce value for our block that will make our hash valid. We can also calculate the hash of our genesis block. With these two values we are ready to create our block. We can store our response in the form of a dictionary and then return this in JSON format.</p><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/get_chain&#39;,methods=[&#39;GET&#39;])<br>def get_chain():<br>  response={&#39;chain&#39;:blockchain.chain,<br>  &#39;length&#39;:len(blockchain.chain)}<br>  return jsonify(response),200</pre><p>This will simply return our complete blockchain and will also show us the length of our blockchain.</p><p>Finally run your app and let the magic begin!</p><pre>app.run(host=&#39;0.0.0.0&#39;,port=5000)</pre><p>You can quickly visualise your blockchain on Postman celebrate your first blockchain!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7XLDzmzpgAMgNMJF.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l4PUjifKBHAXGWek.png" /></figure><p>This is a very basic blockchain and in the coming posts we would be playing with them and making our own cryptocurrencies. Any suggestions or doubts are welcomed. Until then happy blockchaining!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58c83c647ba2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-iiitg/make-your-first-blockchain-58c83c647ba2">Make your first Blockchain!</a> was originally published in <a href="https://medium.com/tech-iiitg">tech@iiit-gwalior</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>