<?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 Vinayak Singh on Medium]]></title>
        <description><![CDATA[Stories by Vinayak Singh on Medium]]></description>
        <link>https://medium.com/@vinayak-singh?source=rss-cabb56682624------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yHgSYRNb_-hyFzcF</url>
            <title>Stories by Vinayak Singh on Medium</title>
            <link>https://medium.com/@vinayak-singh?source=rss-cabb56682624------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 19:23:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vinayak-singh/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[Virtual Machines vs Containers]]></title>
            <link>https://medium.com/@vinayak-singh/virtual-machines-vs-containers-933f345046d4?source=rss-cabb56682624------2</link>
            <guid isPermaLink="false">https://medium.com/p/933f345046d4</guid>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[virtualization]]></category>
            <category><![CDATA[virtual-machine]]></category>
            <dc:creator><![CDATA[Vinayak Singh]]></dc:creator>
            <pubDate>Mon, 27 May 2024 00:35:40 GMT</pubDate>
            <atom:updated>2024-05-27T00:35:40.468Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jt_YYkAzmXmbV4a0Ag_8HQ.jpeg" /></figure><h4>What are these, and how do they differ?</h4><p>Containers and Virtual Machines are technologies that free your applications from IT infrastructure resources, make the application independent from the hardware. However, containerization and virtualization achieve the common goal in different ways. While containerization makes your application portable so that the same code can run on any machine, virtualization is more of imitating a physical machine, virtually. You can have multiple virtual machines, each having an individual operating system, on the same host OS.</p><h3>Virtualization</h3><p>Virtualization is creating a software-based version of something, which can be a computer, networking, storage, application, or much more. It is made possible by a software called <strong>hypervisor</strong>. Hypervisor is a software that runs on a physical server or a host. A hypervisor allocates and manages the resources present in the physical server to the virtual environment. This way, certain resources are utilized to create and run each newly created secondary ‘virtual’ computer inside the actual computer.</p><blockquote>Think of an actual big hall having walls on every side. Instead of using the hall as a whole, you decide to divide this hall into smaller rooms dedicated for a specific thing each. So, you’re the hypervisor as you’re allocating space, and each little room resembles an independent virtual machine. Why did you do this? Maybe to better utilize the resources (in this case, the space in the room), or even rent up each part to a different person and gain revenue out of it. There can be multiple reasons, this is just an example, and I hope this helps you imagine what virtualization is.</blockquote><p>There are two types of hypervisors-</p><ol><li><strong>Type 1/Bare metal hypervisors<br></strong> A type 1 Hypervisor is installed right onto the physical hardware and manages guest operating systems. Usually seen in server-based environments, these are the most secure and most-used Hypervisors. Some examples are KVM, Microsoft Hyper-V, and VMware vSphere.</li><li><strong>Type 2/Hosted hypervisors<br></strong>Type 2 Hypervisors are installed on top of the host operating system. It works by taking up resources from the host OS and then running on the hardware present. It’s better suited for end-user virtualization, where a user wants to run multiple OSes on a personal computer. Some examples of such software are VMware workstation and Oracle VirtualBox.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*kOCd6mo0vwNmpIZpKM6UjA.png" /></figure><p>One key difference between the two types of hypervisors is that hosted hypervisors have greater latency than bare metal hypervisors. This seems logical too, since Type1 hypervisors have direct access to all the hardware resources, whereas hosted hypervisors communicate with the host operating system to manage the resources present on the computer.</p><h3>Virtual Machines (VMs)</h3><p>Virtual Machines, as the name suggests, are computing environments that function as isolated systems with their own CPU, memory, storage, and network interface. It mimics a physical computer. Software called hypervisors is used to manage VMs and allocate resources to each VM from the physical hardware known as the ‘host machine’. This way, a virtual machine is also called a guest machine, a virtual server with the operating system running on a VM known as a guest OS. The host machine runs the host operating system.</p><p>Virtual Machines achieve hardware virtualization. The Hypervisor creates these virtualized instances of all the components that make up a physical machine — processors, RAM, storage, and network instances.</p><h4>Pros of Virtual Machines</h4><ol><li><strong>Better security due to isolation of processes<br></strong> Hypervisors achieve complete isolation between the virtual machines as the physical server resources are distributed among the VMs created, and each VM works independently, not even knowing about the existence of other virtual servers. Even if a single VM dies or gets attacked by an external party, it won’t affect the other machines. You can also create snapshots of the VMs at any point so that they can be restored to that state.</li><li><strong>Interactive development<br></strong> Containers are configured using static definitions and contain only the needed static configurations and dependencies defined in them. However, virtual machines once set up act as barebones computers and you can manually install software based on the requirements.</li><li><strong>Reduced costs and time<br></strong>Since you can install multiple operating systems on a single server by running VMs, you can save costs on setting up new physical servers and also save the time needed to spin up new VMs by using snapshots and meet demands.</li></ol><h4>Cons of Virtual Machines</h4><ol><li><strong>Iteration Speeds</strong><br>Setting up a virtual machine is like setting up a physical computer, which is a time-consuming process. Any modifications to an existing VM will require a complete regeneration of the environment which reduces the overall efficiency of development.</li><li><strong>Storage Size</strong><br>Virtual Machines are full-stack systems that contain details about every physical component allocated to it, along with the drivers, and operating system details. This causes the image to be of several GBs of size. This can lead to disk space shortage issues on the virtual machine host server.</li><li><strong>Single point of failure<br></strong> By relying on a single physical machine, it increases the risk of SPOF.</li><li><strong>Larger time to market<br></strong>Updating existing VMs is the same as updating an operating system on computers, and it’s a tedious time time-consuming process. Changing the VM configurations is the same case — you need to re-run the validations and regenerate the environment. Plus, all this is a manual process. This ultimately increases the time it takes for an application to be live.</li></ol><p>This is virtualization at its core. You can create multiple Virtual Machines from a hypervisor, each having a different operating system of its own, each running its processes independently from one another. These VMs are highly portable, which means moving a VM from one hypervisor to another is very easy by creating images for the VM and importing them to the new hypervisor. A VM can be defined in a single data file, which can be moved from one computer to another, opened in anyone and still expected to work the same.</p><h3>Containers and Containerization</h3><p>At the top level, both Virtual machines and containers aim at isolating applications so that they can run in multiple environments. However, it’s <strong>the way</strong> both achieve this common goal. While virtual machines aim to emulate an entire machine down to the hardware resources, containers work at the software layer above the operating system. What does this mean? Let’s find out.</p><h4>Containers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*D6uTZgW7cNQYA-YcdxCFzg.png" /></figure><p>Containers describe a lightweight approach to virtualization — you don’t need to spin up an entire virtual system. Instead, it packages up all the necessary code files, runtime libraries, and dependencies into a single image that can run using software known as a container engine. Docker is the most famous example of a container engine.</p><p>Instead of achieving hardware-level virtualization, containers achieve OS virtualization. Software developers create and deploy <em>container images</em> — files containing the necessary information to run the application. Container images are read-only and cannot be altered by the computer system. Multiple containers can run on the same machine and share the OS kernel with other containers, each running as an isolated process in the user’s space.</p><blockquote>To deploy your application using containers, you just need to package the application code and dependencies into a container image. Use a container engine like docker to load the image into any machine, bring up your application container and it’s done. Your application should be up and running without depending on the underlying infrastructure.</blockquote><p>Hence, containers are fast, small, and portable since they don’t need to carry a guest OS in every instance and can leverage resources from the host operating system.</p><h4>Pros of Containers</h4><ol><li><strong>Lightweight<br></strong> Containers share the underlying machine OS kernel. That eliminates the need for a dedicated OS instance per application, reducing the container image file size by a lot compared to the virtual machine image size.</li><li><strong>Portability<br></strong>Since Containers do not depend on the hardware capabilities of a machine, the same container file, after carefully writing down all the needed dependencies and libraries, can be run on any machine without any need to reconfigure them based on the host operating system.</li><li><strong>Faster development cycles<br></strong>Modifying the dependencies and libraries in the container image files is achievable by changing only a few lines of code. Redeployment of containers with updated configuration is faster than redeployment of complete operating systems in VMs.</li><li><strong>Support for modern development architecture<br></strong>Since containers are highly portable, consistent across multiple systems, of small size, and their deployment is faster, containers are an ideal fit for modern development and application patterns — such as microservices, DevOps, and serverless — built using regular code deployments in small increments.</li></ol><h4>Cons of Containers</h4><ol><li><strong>Reduced security due to poor isolation<br></strong>Containers perform what is known as process isolation. Containers at the very base use the same operating system resources. Therefore, the utilization of resources needs monitoring so that the host machine is not limited due to the overutilization of resources by specific containers. It is possible that an exploit in one container could break out of the container and affect the shared hardware.</li></ol><h3>Difference between VMs and Containers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bw0gWcxXBntrmU3RWYpWHA.png" /><figcaption>Visualization of differences between Virtual Machines and Containers</figcaption></figure><ol><li>Virtual Machines use hypervisors as the underlying technology but containers use a container engine (Docker) to manage the virtualization of applications.</li><li>As containers share the OS Kernel, they don’t need to run a separate OS instance of itself, and all overheads related to managing physical components aren’t there. In virtual machines, the hypervisor needs to manage the performance overhead caused by emulating hardware components. Containers are hence more efficient. Also, VMs can run on any operating system, while containers run on the same operating system.</li><li>VMs require ample storage to manage the operating system, drivers, and libraries. This not only takes more space but also is a slower process since we’re emulating the entire OS boot-up process. However, containers only package necessary code files and dependencies needed to run a process within the same OS kernel as that of the host machine. Container files are usually of size in MBs, while the VM images go into GBs because they hold the details of every encapsulation — the hardware resource allocations, OS, networking, etc. Hence, application sharing is faster for containers than VMs.</li><li>As discussed above, VMs achieve complete isolation between the different processes and hence, they offer better security and isolation than that offered by containers. Since containers do not isolate processes to such an extent, the chances of exposing other components during external attacks are comparatively higher.</li><li>In terms of Software development life cycles, containers offer faster deployment speeds and lower upgrade times. All the container configurations come inside the base file (Dockerfile). If you need to update/upgrade the operating system it’s based on, you provide the latest build of the OS image and rebuild the container with this new image. You need to modify any other dependency in a container — you just need to edit the container image base file and redeploy the container. This clearly shows containers offer faster build times to test and release features frequently.</li></ol><blockquote>In our laptops and devices, different processes work under the same environment (operating system). They can talk to each other, and see the resources being utilized by other components. The same process is done by containers, however, keeping isolation in mind. All the containers share the same OS Kernel, but each container, appears they have its copy of the operating system with only the code, libraries, and dependencies defined in the image present. That’s it. Similarly, other containers are running, and they don’t know about each other.</blockquote><h3>Hybrid use of Virtual Machines and containers</h3><p>It is entirely possible to use virtual machines and containers together although the practical use-cases may be limited. A virtual machine can be created that emulates a unique hardware configuration. An operating system can then be installed within this virtual machine’s hardware. Once the virtual machine is functional and boots the operating system, a container runtime can be installed on the operating system. At this point we have a functional computational system with emulated hardware that we can install containers on.</p><p>However, its worth mentioning that majority times, your requirements will be fulfilled by either one of the two, and you will not need to bring up containers inside a virtual machine. The key to deciding between containers or virtual machines for your virtualization needs is understanding your resource needs and the trade-offs you’re willing to make.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*l8fFzrppYLhLHtBbymDDNg.png" /><figcaption>Using containers inside virtual machines hosted on a hypervisor</figcaption></figure><h3>Conclusion</h3><p>That was it for this blog describing virtual machines and containers. Hope you had a wonderful time reading this stuff.</p><p>Happy Learning!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=933f345046d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How does a GraphQL server work?]]></title>
            <link>https://medium.com/@vinayak-singh/how-does-a-graphql-server-work-9ee353bb7e4c?source=rss-cabb56682624------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ee353bb7e4c</guid>
            <category><![CDATA[graphql-resolver]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[graphql-vs-rest]]></category>
            <category><![CDATA[graphql-apollo-server]]></category>
            <category><![CDATA[apollo-client]]></category>
            <dc:creator><![CDATA[Vinayak Singh]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 21:34:43 GMT</pubDate>
            <atom:updated>2024-04-10T11:45:16.217Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QpQWyvjir5hUUZrh.jpeg" /></figure><h4>Is it any different than a normal server, and if it is, how??</h4><p>Popularly known as the client-server model, the client requests for data over the network to the server, and it is the server’s responsibility to verify defined rules and then send an acknowledgement along with the data requested. Building a simple server using Node.js is simple — you can utilize the built-in modules like http, https or even popular frameworks like express.</p><p>With GraphQL, we can write really descriptive, easy-to-read queries that ask for everything that we want in one go. But in order to receive such queries, a server needs to understand GraphQL first and then interpret it. Even though our requests have a slightly different format, this mechanism turns out to be the similar to a typical <em>web server</em>: listening to the incoming HTTP requests and having all instructions necessary to figure out how to fulfill them.</p><p>A GraphQL server can also be built from scratch, but fortunately there are a lot of libraries present that can handle all the weightlifting for us. Apollo Server is one such open-source server library.</p><h3>Building Blocks of GraphQL</h3><h4><strong>Schema</strong></h4><p>If you’ve read this <a href="https://medium.com/@vinayak-singh/graphql-core-concepts-7be2c93b5cd9">blog </a>of mine, you’ll remember what a schema is. For a quick recap, a schema is like a blueprint of the application, that describes all the different types defined, and their properties (known as fields). Think of a GraphQL Schema as an actual graph — each node being a <strong>type </strong>having different fields inside, and these nodes and connected to each other, forming relations among themselves.</p><p>Consider three different types ‘Game’, ‘Review’ and ‘Author’. These different types can have relationships among them (for example, a game can have multiple reviews, with each review having its own author). The Schema documents all these connections and individual characteristics of an object — the fields. Furthermore, the schema does data validations. If the request asks for any <strong>undefined type</strong> or a <strong>field, </strong>it’ll simply throw an error. The schema helps enforce that requests can only ask about the types and fields that we’ve previously defined.</p><p>When a request passes the checkpoint (that is, it contains only <em>valid</em> types and fields according to the schema), it proceeds to the next layer of our server: <strong>the resolver functions</strong>.</p><h4><strong>Resolver Functions</strong></h4><p>Taking forward the previous example of games and reviews, a REST API will have to fetch games separately, and then the associated reviews, and filter them to return only specific fields requested by the client. So the question arises — how can a GraphQL server resolve data from multiple sources all at once, where a REST API might require multiple calls to different endpoints?</p><p>GraphQL clients like Apollo handle the internal mechanism of mapping types to the fields, and also returning only the fields specified in the query themselves. Using resolver functions, the data related to each type and field can be queried irrespective of the data source, i.e. Resolver functions have the access to every connected database, APIs and even JSON files.</p><p>In JavaScript, a basic resolver functions might look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*gfAAuj4ErkGRkIwGukbJOQ.png" /><figcaption>Example for resolver functions being passed to the ApolloServer object</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*zQnh5kjOPPF3KtDRkxAFfg.png" /><figcaption>Example query</figcaption></figure><p>The Apollo Server handles the fields returned by the server, while the developer only needs to link the queries defined in the Schema with appropriate data source. Also, any variables being passed as an argument can be handled by Apollo Server, provided the syntax rules are being followed properly by the user.</p><p>Here is the server response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HIxvX4YxC1YvGxcKLniI7Q.png" /></figure><p>Resolver functions provide flexibility to the GraphQL servers as no matter what the query looks like, it’ll adjust itself to return the response as needed. We can mix and match the things we ask for, which gives us the precision to ask for exactly the data we need on a page-by-page or component-by-component basis. It all depends on what we want to do with the data!</p><p>Also, Resolvers have a special function when it comes to authorization and authentication. Since it is within these resolver functions where the data is resolved for response, we can apply some rules to check who is allowed to have the data. Resolvers have access to a lot of the information that comes in as a request to our server, which enables them to make decisions about what they return on a request-by-request basis.</p><p><strong>But one question arises. If the resolver functions need to access data source frequently, is the entire data stored in the GraphQL server, or we can create connections between the database and the Apollo Server?</strong></p><p>One of GraphQL’s greatest strengths is its ability to grab, collect, and serve up data from a variety of sources. As a result, the only thing needed is to tell our server all the database connections and external APIs it has to fetch data from — like a manual or instruction booklet for each place our GraphQL server will ask for data.</p><p>To do this, we can configure <em>data sources</em> which I’ll demonstrate in another blog where we’ll be setting up an entire application using Apollo Server and GraphQL. These <em>data source</em> configurations contain the properties, details and logic (rules) for accessing the data.</p><p>So, how we configure each data source depends on what it is and the kind of data it serves up: if we’re connecting to a database, our configuration could include the connection details required to make contact with the data, along with some helper functions that abstract away heavier, more error-prone database syntax. If we’re reaching out to another API, such as a REST API, our data source configuration might look more like a series of methods that we can call to request data at particular REST endpoints.</p><p>Once the configurations are made, the server has everything it needs to receive requests, do data validations via the schema, delegate them to the resolver functions, and let them do their job fulfilling the data. This is because as soon as data sources are configured on the server, resolver functions get the power to connect to databases, make additional HTTP calls, and retrieve the data they’re responsible for. When all of the data is collected, the server packages it together and sends it back to the client that sent the request.</p><h3>Finally, GraphQL server at a glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*ghxwBdFHIjXt55HdzpngHw.png" /></figure><p>This is how a graphQL server behaves, at the most basic level. You send a descriptive request, and it does data validations based on the defined schema. Afterwards, the schema drills it down for various resolver functions and connect to a variety of data sources to gather all the requested data.</p><p>This structure benefits both the frontend and backend — different teams can work simultaneously based on the defined schema, and the backend team can update the schema, add or remove resolver functions as per the software requirements and manage external data sources efficiently.</p><p>In the upcoming blogs, we’ll quickly setup a working application that connects our GraphQL server to an actual MongoDB database through Apollo Server and mongoose. If you liked this blog, do follow me for more interesting topics I write about.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ee353bb7e4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST vs SOAP]]></title>
            <link>https://medium.com/@vinayak-singh/rest-vs-soap-8ce0f50e916c?source=rss-cabb56682624------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ce0f50e916c</guid>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[soap-api]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Vinayak Singh]]></dc:creator>
            <pubDate>Tue, 16 Jan 2024 21:53:29 GMT</pubDate>
            <atom:updated>2024-04-12T11:41:38.767Z</atom:updated>
            <content:encoded><![CDATA[<h4>A comprehensive guide between the two API architectural patterns, their differences and use cases</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gxs2Hn2KeDG2UN_C6gv3Q.jpeg" /></figure><h3>Introduction</h3><p>Every API has a defined set of rules that should be followed by the developers while developing their software. These rules govern how the API implementation should be done, and how APIs should be used. These rules are termed as API protocols. <strong>API Protocols define the accepted commands, data types, and formats to be used, along with a lot of other things.</strong></p><p>SOAP, which stands for Simple Object Access Protocol, is the oldest API protocol being used in web services to facilitate communication between applications. On the other hand, REST (Representational State Transfer) is more of an architectural style of designing networking applications. It is not a protocol, but rather a set of principles.</p><p>While SOAP focuses on a rigid, structured way of sending and receiving messages, REST is more focused on the statelessness and simplicity of the interface. We’ll explore more as we discuss the two below.</p><h4>Something that you should know before going forward</h4><h3>Service Definition</h3><blockquote>In the context of web services, how does an application know what requests to send, what should be the correct format of the messages received, and where to send it?</blockquote><p><strong>All of these things are defined in the Service Definition of the web service.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*OpBbE04wKrtReIkHiKxaGQ.png" /></figure><p>Here, <strong>Format</strong> specifies whether the web service uses JSON or XML as the main format for the messages. <strong>Structure</strong> defines the way the web service must send the request, or the way data will be received from the external ‘<strong>endpoint</strong>’ — point of communication with the external application.</p><h3>Simple Object Access Protocol</h3><p>SOAP specifies that a rigid messaging structure should be followed in requests and responses. It is <strong>older, established, </strong>and<strong> dependable</strong> — but it can be slower than competing architectural styles like REST. Why are we saying it is <strong>dependable</strong> is something you’ll understand in a few minutes.</p><p>A SOAP request/response has this basic structure:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*6xoseoc4Lqyz9iJ7LJr1hw.png" /><figcaption>In SOAP, an envelope always wraps the header and body of the message to be sent.</figcaption></figure><p>SOAP was primarily developed to enable businesses to move data across the corporate networks. While it has matured as the internet and web developed, it is very different from REST from the perspective of web services. In easier terms, SOAP focuses more on the <strong>messages </strong>whereas REST focuses more on defining APIs as resources to be utilized in multiple locations.</p><p>SOAP uses XML as the data format for messages being sent and received by the API client. <strong>It uses standardized contracts such as Web Service Definition Language (WSDL) to specify the functionalities of an API.</strong></p><p>The WSDL strictly provides the following four dimensions to the API protocol:-</p><ul><li><strong>Endpoint</strong>: Defining where the service is exposed.</li><li><strong>Encoding</strong>: Rules for expressing the type of data. All the operations (Get data, add new data, etc.) are specified here.</li><li><strong>Requests</strong>: How each SOAP API Request is structured.</li><li><strong>Responses</strong>: How each SOAP API response is structured.</li></ul><h4>SOAP API Example</h4><p>An example would be the ISBN Book Validation Service, which provides validations using a simple URL</p><ul><li><a href="http://webservices.daehosting.com/services/isbnservice.wso">http://webservices.daehosting.com/services/isbnservice.wso</a></li></ul><p>This service uses a POST HTTP method to pass the following structured snippet of XML to the service using the body of the HTTP request. It provides a structured request for the server to process and return a response:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;soap:Envelope xmlns:soap=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;&gt;<br> &lt;soap:Body&gt;<br>  &lt;IsValidISBN10 xmlns=&quot;http://webservices.daehosting.com/ISBN&quot;&gt;<br>   &lt;sISBN&gt;0-19-852663-6&lt;/sISBN&gt;<br>  &lt;/IsValidISBN10&gt;<br> &lt;/soap:Body&gt;<br>&lt;/soap:Envelope&gt;</pre><p>It returns the following XML response confirming the validity of the ISBN:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;soap:Envelope xmlns:soap=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;&gt;<br>  &lt;soap:Body&gt;<br>    &lt;m:IsValidISBN10Response xmlns:m=&quot;http://webservices.daehosting.com/ISBN&quot;&gt;<br>         &lt;m:IsValidISBN10Result&gt;true&lt;/m:IsValidISBN10Result&gt;<br>      &lt;/m:IsValidISBN10Response&gt;<br>   &lt;/soap:Body&gt;<br>&lt;/soap:Envelope&gt;</pre><p>This ISBN validation service uses a standardized SOAP envelope to pass a structured message as part of the request, resulting in a standardized response sent in the same way. The SOAP response structure makes it easy for developers to understand and put to work in their applications and integrations.</p><blockquote>While this particular use case is specific to validating ISBNs for books, SOAP APIs can be applied to making any data, content, media, and algorithms available between systems, and within applications. SOAP essentially provides an industrial-grade format for automating how different business messages communicate across daily operations.</blockquote><h4>Benefits of SOAP APIs</h4><p>SOAP has its advantages against REST, and some of these are as follows:</p><ul><li><strong>Extensibility</strong> — Since SOAP is based on XML to a large extent, it can be easily extended by simply adding custom XML header elements.</li><li><strong>Strongly Typed and Better Security — </strong>SOAP is very secure because of its use of WSDL which specifies strict structure and formatting. This helps improve data validation, detect errors, and reduce the potential for communication errors. Hence, it is perfect for systems that handle sensitive data, such as financial services and online banking applications.</li><li><strong>In-built support for error handling </strong>— SOAP has a fault element</li><li><strong>Support for multiple protocols </strong>— Unlike REST which is mainly based on HTTP for communication, SOAP is not dependent on any specific protocol and can even use the features provided by SMTP, or Message Queues (MQs).</li></ul><h4>Disadvantages of SOAP APIs</h4><p>In some situations, SOAP does shine. But it has its drawbacks like</p><ul><li><strong>Slower than REST </strong>— SOAP messages can be quite large due to their verbose XML-based structure, which can lead to greater bandwidth usage and slower performance.</li><li><strong>Does not support Caching</strong></li><li><strong>Complex</strong> —It’s less adaptable than REST because of its strongly typed nature. Whereas, REST might provide an easier approach.</li></ul><h4>Use Cases of SOAP APIs</h4><p>Some of the most common use cases for SOAP APIs include:</p><ul><li><strong>Bank Transfers: </strong>Because of the heightened security features of SOAP, it’s the preferred option</li><li><strong>Booking flights</strong></li><li><strong>Billing services</strong></li><li><strong>Navigation companies</strong></li></ul><h3>Representational State transfer</h3><p>While SOAP primarily uses HTTP for message transfer over the network, REST utilizes HTTP in a much better and more robust manner. It stands for Representational State Transfer and is an architectural style that’s better for applications with CRUD operations <strong>(Create, Read, Update, </strong>and<strong> Delete)</strong>.</p><p>APIs that are designed keeping REST in mind, are known as RESTful APIs. All of these APIs have the following features more or less:</p><ul><li><strong>Statelessness</strong>: The server does need not to store any information about the client’s state. Rather than storing session information, a client should provide all the necessary details in its request.</li><li><strong>Separation of concerns</strong>: The client and server should be properly decoupled from each other, which allows each one to evolve independently.</li><li><strong>Layered architecture</strong>: Software architecture should be split into layers with their distinct purpose, which helps keep the system modular and maintainable.</li><li><strong>Cache support</strong>: Responses can be cached on the client to improve an application’s performance and remove the need to re-process repeated requests.</li><li><strong>Consistent interface</strong>: HTTP methods like GET, POST, and DELETE help make interactions between clients and servers simple and consistent.</li><li><strong>Emphasis on resources</strong>: RESTful APIs are resource-based, rather than method-based or function-based like SOAP. A resource can be an object, entity, or data within a system. Resources are uniquely identified using a Uniform Resource Identifier (URI), and HTTP methods are used to perform CRUD operations (create, read, update, delete) on them.</li><li><strong>Support for standard media types</strong>: Resources are represented using standard media types, such as JSON, XML, or plain text. Clients can request servers to deliver a response in their preferred media type.</li></ul><h4>REST API Example</h4><p>Click on this link to open up the public API that Github provides:</p><ul><li><a href="https://api.github.com/users/github">https://api.github.com/users/github</a></li></ul><p>This REST-based API can be requested to get the following data from any HTTP client, for example <strong>curl:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*b1N3VM5cCbfc5EkSy6uNDA.png" /></figure><p>Note that this public API endpoint is actually of the format api.github.com/users/{github_user_name}, where the Github user name is an optional parameter. And it returns JSON object as a response.</p><p>For more details about the public Github API, <a href="https://docs.github.com/en/rest/about-the-rest-api">click here</a>.</p><h4>Benefits of REST APIs</h4><p>REST provides a straightforward solution for a seamless connection between the server and the client. If the rules are followed as they are, it provides a lot of advantages like</p><ul><li><strong>Scalability</strong> — In today’s time where the online presence of devices and people is increasing every moment, REST provides the ease of scaling the systems depending upon the traffic without affecting the state of the already established network. Horizontal scaling, or adding more servers is easier without the fear of losing session states.</li><li><strong>Flexible with the universal conventions</strong> — REST applies no rigidity over which format to follow, and how a request should look strictly. Having a consistent interface also improves interoperability and makes it easier for various systems to communicate with one another.</li><li><strong>Interoperability</strong> — Any client that supports HTTP protocol, can make use of REST APIs irrespective of the programming language.</li><li><strong>Improved performance </strong>— Since REST APIs support caching and use lesser bandwidth compared to SOAP, RESTful communication ultimately has lesser latency and in turn, a better user experience.</li></ul><h4>Disadvantages of REST APIs</h4><p>Using REST does come at its costs. Here are some of the disadvantages of REST, primarily because of the flexibility it offers:</p><ul><li><strong>Overfetching and Underfetching </strong>—A response can contain more data than you need or require further requests to access all of the data. To solve this specific problem of REST APIs, Facebook’s (now Meta) famous solution is <a href="https://medium.com/@vinayak-singh/graphql-an-introduction-10618e69073d">GraphQL</a>.</li><li><strong>Versioning — </strong>API versioning is the practice of creating multiple versions of an API to accommodate changes or updates without disrupting consumers. To prevent compatibility issues, APIs are often versioned. However, old endpoints remain active, which leads to an increase in workload, as multiple APIs are maintained.</li><li><strong>Maintaining consistency at the endpoint </strong>— As the application exposes multiple endpoints to accomodate all the complex operations it solves, it becomes tedious to keep everything at bay and maintain a record of all the exposed endpoints.</li><li><strong>Less Secure than SOAP — </strong>Even though RESTful APIs provide a simpler way to access and manipulate your application, security issues can still happen. For example, a client can send thousands of requests every second and crash your server (lack of rate limiting). Other REST API security challenges include:</li><li>Lack of proper authentication</li><li>Absence of rate limiting and throttling</li><li>Failure to encrypt payload data</li><li>Incorrect implementation of HTTPS</li><li>Weak API keys that are easily compromised.</li></ul><h4>Use Cases of REST APIs</h4><p>Here are some of the use cases of REST APIs.</p><ul><li>Because of the stateless nature of REST, the dilemma of affecting the entire application by making certain changes is gone. This is the main reason why <strong>Cloud Applications</strong> prefer REST. If something fails, stateless components can smoothly redeploy and scale to accommodate load changes. These Cloud Service Providers also prefer REST for their <strong>Cloud Services</strong> like document sharing, storage, finance and accounting, inventory control, and many more.</li><li><strong>Web Services</strong> — Due to the advent of so many technologies that aim to surpass the drawbacks or failures of others, having a common protocol of communication that is not dependent on the client is a boon. Since REST is not tied to client-side technology, these APIs can be accessible from a client-side web project, an iOS app, an IoT device, or even a (now dead..) Windows Phone. One can design the infrastructure of its application without worrying about a definite client-side stack.</li></ul><h3>Conclusion</h3><p>REST and SOAP both have unique benefits and drawbacks that affect their suitability for various use cases.</p><p>Software development often involves developers choosing among the available options before diving straight into coding. It’s important to understand the advantages and disadvantages of every option that you have.</p><p>SOAP is all about adhering to its rigid structure. Although it’s the older protocol and its popularity has been waning in recent times, it does offer some benefits over REST, and therefore, depending upon the use cases of your application, you should always give it a thought.</p><p>Feel free to share your thoughts in the comments, and do clap and support me by clicking on the image below if you like my writing :)</p><figure><a href="https://www.buymeacoffee.com/singhvinayak"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCQqlZr6doDP-cszzpaSpw.png" /></a></figure><p>Happy Learning ✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ce0f50e916c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL Core Concepts]]></title>
            <link>https://medium.com/@vinayak-singh/graphql-core-concepts-7be2c93b5cd9?source=rss-cabb56682624------2</link>
            <guid isPermaLink="false">https://medium.com/p/7be2c93b5cd9</guid>
            <category><![CDATA[graphql-mutations]]></category>
            <category><![CDATA[graphql-schema]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[graphql-vs-rest]]></category>
            <category><![CDATA[graphql-subscriptions]]></category>
            <dc:creator><![CDATA[Vinayak Singh]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 18:07:46 GMT</pubDate>
            <atom:updated>2023-12-17T18:10:23.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b4eimn9tDHyCGnw-XYNDsw.jpeg" /></figure><h4>A glimpse of the building blocks of GraphQL</h4><p>We know that underfetching and overfetching issues might arise while using RESTful APIs. This ultimately reduces both the client-side experience as the multiple requests needed will lead to slow data processing and transmission between the client and the server. Also, it leads to slower product iterations since the front-end code and the back-end code need to be in sync with the data being requested and transferred between the two.</p><p>During product development, the API endpoints are structured the way the client wants the data to be visible on his screen. Though it seems handy to design the APIs based on the requirements, it has its drawbacks. With every change in the UI, there is a high risk that the back-end code needs to be modified to provide more or less data than before. This ultimately kills productivity and leads to a slower product lifecycle. With GraphQL, however, changes on the client side can be made without any extra work needed on the server side.</p><p>Another major benefit of using GraphQL is its type system. It defines the capabilities of the API, or should I say, it defines the type of data being returned by the API endpoint. All the types that are exposed in the API are written down in the schema using GraphQL Schema Definition Language (SDL). Once the schema is defined, the teams working on the front end and back end can work independently without further communication since both of them are aware of the exact data needed to be sent over the network.</p><p>To understand more of this, we’ll go through all the important concepts like <strong>schema</strong>, <strong>queries</strong>, <strong>mutations</strong>, and <strong>subscriptions</strong> one by one.</p><h3>Schema Definition Language (SDL)</h3><p>GraphQL has its type system that is used to define the schema of an API. The syntax for writing schema is known as the Schema Definition Language (SDL).</p><p>If you’ve read <a href="https://medium.com/@vinayak-singh/graphql-an-introduction-10618e69073d">my other blog</a> where I introduced GraphQL, you might remember the blogging platform example. And if you’re new, imagine a blogging platform where your home screen displays the titles of all your posts and the names of the last three people who followed you. So, this application will have a specific syntax to fetch different ‘types’ of data. Here, type is synonymous with different tables from where the data is fetched.</p><p>We have two types, Person and Post, defined in the following manner.</p><pre>type Person {<br>  name: String!<br>  age: Int!<br>  posts: [Post!]!<br>  address: String<br>  followers: [Person!]<br>  following: [Person!]<br>}</pre><pre>type Post {<br>  title: String!<br>  author: Person!<br>}</pre><p>In programming dogma, types resemble the classes and each new record of such types is just an object in disguise.</p><p>The Person type has five fields and Post has only two fields as of now. (note that this is for understanding purposes only). The Person type has fields name, age, address, posts, followers, and following with types String, Integer, String, an array of Posts, and the last two being array for Persons respectively. Similarly, Post has two fields title and author with types String and Person respectively.</p><p>For those of you familiar with the concept of relationships in database management, relationships can be formed between the different types in GraphQL. Here we have established a one-to-many relationship between the two types. A person can have multiple posts, and therefore, it’s stored in the form of an array. Just like any other programming language out there, this is nothing fancy with GraphQL.</p><blockquote>Notice the exclamation mark. It means that it is a required field, and therefore can’t be left empty. For the fields that are optional to a type, it can be defined without the exclamation mark.</blockquote><h3>Queries</h3><p>The REST APIs have a defined structure. Though new API endpoints can be written to support custom client needs like the one described above, it leads to the creation of new endpoints that might not be used at multiple places in the application, and therefore, not an efficient way of development. So, if our blogging platform were to use REST APIs only to get the required data, it’d have to make three separate API calls.</p><p>· /api/users/&lt;id&gt;</p><p>· /api/users/&lt;id&gt;/posts</p><p>· /api/users/&lt;id&gt;/followers</p><p>With GraphQL, everything becomes different and much more efficient. Instead of having multiple endpoints that return fixed data structures, GraphQL typically exposes a single endpoint that returns data with a dynamic structure, based on the requirement. It is completely flexible and lets the client decide instead what is needed, and what is not.</p><p><strong>This also means that the client needs to send additional data, to tell the server its data needs. This information is called a query in GraphQL.</strong></p><p>To fetch all persons present in the database, the query will look something like this:</p><pre>{<br>  allPersons {<br>    name<br>    age<br>    posts {<br>      title<br>    }<br>  }<br>}</pre><p>Therefore, for own blogging platform example, the GraphQL query will look like this:</p><pre>{<br>   Person(id: “xyz”) {<br>    name<br>    posts {<br>     title<br>    }<br>    followers(last: 3) {<br>     name<br>    }<br>  }<br>}</pre><p>This query will go to the GraphQL server and instruct it in the following way — fetch the record of type Person whose id is <strong>xyz</strong> (parameters and arguments can be sent this way to specify a specific record or a specific number of records) and <strong>return only its name, the title of all the posts under it, and only the names of latest three people that have followed</strong> this specific person.</p><p>No client-side filtering is needed when data can be received this way. And since the data requirements are written on the query, any update in the client requirements can be simply updated on the query, instead of writing new logic on the backend side.</p><blockquote>In GraphQL, each <em>field</em> can have zero or more arguments, depending upon the schema specification. That’s why in the above written query, we are passing an argument to fetch defined number of followers. What this does, is use the value passed to it, place it in the function fetching the records, and return only the requested data.</blockquote><p><strong>This is how data is fetched using queries. But what about updating the data that’s already present in the databases, or adding new records to the database?</strong></p><p><strong>This is where mutations come into play.</strong></p><h3>Mutations</h3><p>The RESTful APIs utilize HTTP verbs to perform CRUD (Create Read Update Delete) operations. While the <strong>read operation (GET) is made possible through the use of queries in GraphQL</strong>, the rest <strong>three operations (POST, PUT, DELETE) are carried out through mutations</strong>.</p><p>In GraphQL, 3 kinds of mutations are present:</p><ol><li><strong>Creating</strong> new data</li><li><strong>Updating</strong> existing data</li><li><strong>Deleting</strong> existing data</li></ol><p>While their syntactical structure is the same as writing queries, one should always keep in mind to start with the keyword “mutation” when writing mutations. Here’s an example to create a new Person:</p><pre>mutation {<br> createPerson(name: “Vinayak Singh”, age: 21) {<br>   name<br>   age<br>  }<br>}</pre><p>Like writing queries, we specify the root field in mutations — here it is <strong>createPerson</strong>. It takes two arguments to specify the new person’s name and age.</p><p><strong>The lines below specify the fields to be returned as part of server response. The server response for the above mutation will look like this:-</strong></p><pre>&quot;createPerson&quot;: {<br>  &quot;name&quot;: &quot;Bob&quot;,<br>  &quot;age&quot;: 36,<br>}</pre><p>Databases store different records with something to differentiate each record or identify each record uniquely. We call them IDs.</p><blockquote>In the case of relational databases, we have a primary key that’s distinctive for each record.</blockquote><p>Same is the case with GraphQL. GraphQL types have unique IDs associated with them that are generated by the server when new objects are created. Therefore, our existing Person and Post types will look like this:</p><pre>type Person {<br>  id: ID!<br>  name: String!<br>  age: Int!<br>  posts: [Post!]!<br>  address: String<br>  followers: [Person!]<br>  following: [Person!]<br>}</pre><p>Hence, if we want the server to return the unique ID of the newly created object in its response, the mutation will instead look like this :</p><pre>mutation {<br>  createPerson(name: &quot;Vinayak Singh&quot;, age: 21) {<br>    id<br>  }<br>}</pre><blockquote>According to official GraphQL documentation, it’s not preferred to use any object type for the input fields in mutations functions. Instead, an “input” type should be defined that will be passed to the mutations. More details can be <a href="https://graphql.org/graphql-js/mutations-and-input-types/">read here</a></blockquote><h3>Subscriptions</h3><p>Another important requirement for many applications today is to have a <em>real-time</em> connection to the server to get immediately informed about important events. For this use case, GraphQL offers the concept of <em>subscriptions</em>.</p><p>When a client <em>subscribes</em> to an event, it will initiate and hold a steady connection to the server. Whenever that event happens, the server pushes the corresponding data to the client. Unlike queries and mutations that follow a typical “<em>request-response</em>-cycle”, subscriptions represent a <em>stream</em> of data sent over to the client.</p><p>Subscriptions are written using the same syntax as queries and mutations. Here’s an example where we subscribe to events happening on the Person type:</p><pre>subscription {<br>  newPerson {<br>    name<br>    age<br>  }<br>}</pre><p>After a client sent this subscription to a server, a connection is opened between them. Then, whenever a new mutation is performed that creates a new Person, the server sends the information about this person over to the client:</p><pre>{<br>  &quot;newPerson&quot;: {<br>    &quot;name&quot;: &quot;Alice&quot;,<br>    &quot;age&quot;: 23<br>  }<br>}</pre><h3>Defining a Schema</h3><p>After learning about queries, mutations, and subscriptions, we can finally write down a complete schema. <strong>The schema is the most important thing in GraphQL as it mentions the exact client requirements to the server. It can be called the contract between the client and the server.</strong></p><p>The schema is a collection of all other GraphQL types, written in a specific syntax. There are root types here also that we need to write, like this</p><pre>type Query { ... }<br>type Mutation { ... }<br>type Subscription { ... }</pre><p>To enable the allPersons and Person queries we wrote above, they have to be mentioned here inside the Query root type</p><pre>type Query {<br> allPersons: [Person!]!<br> person ( id: ID! ): Person!<br>}</pre><p>Similarly, the mutations and subscriptions will look like this</p><pre>type Mutation {<br> createPerson(name: String!, age: Int!): Person!<br>}<br>type Subscription {<br>  newPerson: Person!<br>}</pre><p>This is it for this blog post. I hope this was informative. In the upcoming blogs, we’ll dive deeper into GraphQL and work on a GraphQL project using Node.js and Prisma ORM.</p><p>Happy Coding!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7be2c93b5cd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is an API? Its types and protocols used]]></title>
            <link>https://medium.com/@vinayak-singh/what-is-an-api-its-types-and-protocols-used-bfaad3fa8e77?source=rss-cabb56682624------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfaad3fa8e77</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Vinayak Singh]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 20:56:19 GMT</pubDate>
            <atom:updated>2023-11-12T20:58:03.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*AQzsgSb23Hg-caTvYJmomQ.png" /></figure><h3>Introduction</h3><p>Imagine you’ve gone with your family to a restaurant for dinner. All of you want to have your favorite delicacies in front of you. The kitchen’s there, the utensils are there. But does the place’s management allow anyone to straightaway go into the kitchen and use it? No right! Instead, a waiter comes up to your table, takes the order request, goes to the chef and gets back to your table with the order after some time.</p><p>The restaurant management wouldn’t allow people who are not authorized to access certain places (in this case, the kitchen). Here, the waiter acts as an interface between you and the restaurant. It is the exact task of an API in software development.</p><p><strong>An API, or Application Programming Interface, allows unrelated software products to integrate and interoperate with other software services and data. It acts as an intermediary layer that processes data transfers between systems, letting companies open their application data and functionality to external third-party developers, business partners, and internal departments within themselves.</strong></p><p><em>The user interacts with the system through the user interfaces. Similarly, an API exists for the software to interact with each other, such as executing instructions, fetching data from servers, etc.</em></p><h3>How an API works</h3><p>A simple way to understand how APIs work is to look at an example like third-party payment processing. Let’s say a user is ordering a product on an e-commerce website. On the mode of payment selection page, a prompt appears saying “Pay with Paytm” or some other third-party system like PayPal, etc. This function is now API-dependent.</p><p>When the buyer clicks the payment button, an API call is made to retrieve the user’s information. This request is processed on the payment services’ end via the API’s URI (uniform resource identifier) to validate this request.</p><p>The third-party system validates and performs all the checks on the user’s account level without displaying any information on the screen. Afterwards, the server sends the response back to the initial requesting application, here the e-commerce platform.</p><p>While the data transfer depends on the type of service, protocols, and formats used for the requests and responses that happen through the API, there is no visibility on the user interface, and all a user sees is a seamless connection between different services that appear to be working as one.</p><h3>API or Web Service — confused between the two?</h3><p>According to W3C, Web service is a software system designed to support interoperable machine-to-machine interaction over the internet. Wait a second, this does sound a lot like API, right?</p><p>While the two terms are used interchangeably, there is a slight difference between them. Web services are a type of API that are accessible through the network. <strong><em>All web services are APIs, but not all APIs are web services.</em></strong></p><ul><li>The difference between an API and a web service is that API allows two-way communication and web services (through web applications) are just a way for users to interact through a web browser. A web service may have an API to complete the requests.</li><li>Webservices are used for REST, SOAP, and XML RPC protocol-based communication, while APIs can be used for any mode of communication.</li><li>Another considerable difference between the two is the format they support. <strong>Webservices only support HTTP protocol and XML message exchange format for requests and responses, whereas APIs support both XML and JSON message exchange formats along with both HTTP/HTTPS protocols for communication.</strong></li></ul><h3>Types of APIs</h3><p>By “type”, we mean the scope of use of the API. There are four different types of APIs used in web services:</p><ol><li><strong>Public APIs<br></strong>Also called open or external API, public APIs are those that are made available to be used by any other developer/business. Such APIs usually have low to moderate authorization and authentication. While many of the open APIs are free to use, certain publicly available APIs do charge money on the basis of their usage, and might apply rate limits as well.</li><li><strong>Partner APIs<br></strong>Partner APIs are made to handle business-to-business activities and are made selectively available to developers outside the parent organization. These APIs impose stronger rules and guidelines around authorization, authentication and security. A business organization might share its customer data with external parties through such partner APIs having dedicated rules defined. No other API is used.</li><li><strong>Private APIs<br></strong>Private APIs are used within the organization, like between the HR department and the payroll team. These are made to connect the internal systems and data in the business. Usually, since there is no connection with the outer world, such APIs might opt for weak or no security at all. This, however is changing and companies are imposing strong security to match the regulatory compliance demands.</li><li><strong>Composite APIs<br></strong>Composite APIs combine multiple API requests into one call to form a solution for a complex problem. This saves data and makes the application efficient by reducing the number of API calls the system makes.</li></ol><blockquote>GraphQL can be said to an example of composite APIs, as it consolidates all queries to a single endpoint and returns precisely what the client requests to avoid over and under fetching. Though the developer has to tightly bound the requesting payload, it reduces the number of API calls and thus, makes the system faster.</blockquote><h3>API Protocols</h3><blockquote>Every API has a defined set of rules and techniques that should be followed by the developers to incorporate them in their software. These rules govern how the API implementation should be done, and how APIs should be used. These rules are termed as API protocols. <strong>API Protocols define the accepted commands, data types and formats to be used, along with a lot of other things.</strong></blockquote><p>Popular API Formats being used are –</p><h4>SOAP</h4><p>SOAP stands for <strong>Simple Object Access Protocol</strong>. It’s being still used even though it was started in 1998. In SOAP, we use XML as the only message exchange format for both requests and responses. SOAP is highly structured in nature and requires a standard format for all XML requests and responses.</p><h4>REST</h4><p>It stands for Representational State Transfer. REST is more of an ‘<strong><em>architectural approach</em></strong>’ for designing APIs. It’s stateless in nature, and therefore does not enforce messages to be in a specific format like SOAP does. <br> A REST API endpoint is a URL that utilizes HTTP verbs to execute <strong>CRUD (Create Read Update Delete)</strong> operations over the resources. These HTTP verbs are GET, POST, PATCH, PUT and DELETE. It focuses on providing resources from the server to the clients.</p><h4>RPC</h4><blockquote>To understand RPC, it is like you are working on a program, and upon running a certain function, it triggers a function call to be executed that is running on another computer connected to yours through network. The other computer receives your request, processes it, and returns the response to your system to be used for further processing.</blockquote><blockquote>For a common person’s understanding, lets say you are working in your office and want to have cookies made by your mother specifically. What you do is email her asking her to send a box of your favorite cookies. This is an example of RPC. Of course not anyone can do a RPC. There are rules for authorization and authentication. In this scenario, someone from the family only will call for the delicious cookies :)</blockquote><p>Remote procedure call (RPC) is an <strong>Inter-process communication</strong> technology that allows a computer program to cause a subroutine or procedure to execute in another address space (commonly on another computer on a shared network) without the programmer explicitly coding the details for this remote interaction. RPC is more powerful than REST, but at the same time, harder to use.</p><h4>XML-RPC</h4><p>The XML-RPC protocol relies on a specific XML format to receive data. Being older than even SOAP, it’s lightweight, simpler and requires much less bandwidth.</p><h4>JSON-RPC</h4><p>As the name suggests, it relies on JSON format to receive data.</p><h4>gRPC</h4><p>Developed initially by Google and then open sourced, gRPC is a high-performance open source RPC framework.<br> Unlike above protocols, gRPC lets developers define their own custom functions to enable inter-service communication as required. gRPC uses HTTP as its transport layer and provides additional facilities such as authentication features, timeouts, flow control, etc. Data is sent in protocol buffers (called <em>protobuffs</em>), a language and platform independent mechanism which defines how data can be structured in a simpler intuitive way.<br> Protobuffs begin with defining the service first, followed by defining the data structures the service will use. This is compiled by the compiler protoc, which now creates an entire class furnished with your defined data types along with basic set methods in the development language you’re working on. Now, this class can be used to implement the detailed workings of the API.</p><h4>GraphQL</h4><p>Developed by Facebook (now Meta), GraphQL is a query language for your API, where you define the format in which you want the data. It is a strongly typed query language that queries data from the server, in the exact format specified by the developer in the request.</p><p>That’s it for this blog. In the upcoming blogs, we’ll be discussing about the differences between REST and SOAP to more extent. And then, understanding GraphQL basics, how to use GraphQL and we’ll be working on setting up a project utilizing GraphQL, Postgres and JavaScript.</p><p>Thanks for reading. If you liked it, your feedback is truly appreciated.</p><p>For more content, do check my other blogs!! ✌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfaad3fa8e77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL: An Introduction]]></title>
            <link>https://medium.com/@vinayak-singh/graphql-an-introduction-10618e69073d?source=rss-cabb56682624------2</link>
            <guid isPermaLink="false">https://medium.com/p/10618e69073d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[graphql-vs-rest]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Vinayak Singh]]></dc:creator>
            <pubDate>Thu, 28 Sep 2023 12:11:36 GMT</pubDate>
            <atom:updated>2023-09-28T12:11:36.008Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVAsp6NPXTZqYuRrPM14gQ.png" /><figcaption>image from <a href="https://www.howtographql.com/">howtographQL</a></figcaption></figure><p>GraphQL is a query language for your API, where you define the format in which you want the data. It isn’t tied to any specific database or storage engine and is instead backed by your own existing code and data.</p><p>GraphQL is an alternate way to write API requests that is more efficient, flexible, and powerful. Developed and later open sourced by Meta (formerly Facebook) initially as an internal tool for their native mobile applications, it was first made public at <a href="https://www.youtube.com/watch?v=9sc8Pyc51uU">React.js Conference 2015</a>.</p><blockquote>It enables <em>declarative data fetching</em> where a client can specify exactly what data it needs from an API. Instead of multiple endpoints that return fixed data structures, a GraphQL server only exposes a single endpoint and responds with precisely the data a client asked for.</blockquote><p>Hold on, before learning what is GraphQL, let’s dive a little deeper into APIs and how they work.</p><h3><strong>Application Programmable Interfaces (APIs)</strong></h3><p>Most applications need to fetch data from a server which fetches that data from one or more databases. The server exposes certain API endpoints which the client application listens to, and renders data for the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAuo-q9_ql5FYyOMmdubZw.png" /><figcaption>Server responds to the client via the API endpoints over the internet</figcaption></figure><p>Consider yourself working on a to-do application that has the feature to maintain your calendar planner with meeting records and other important events. You need reminders for it on a regular basis, and also you need to have them synchronized with the main calendar application that you preferably use (on multiple devices maybe?). Do you create an entire calendar application first to do so? No, right? I mean, if you think you should first create a calendar application first, please wait. <br> <br> Instead, you use Google Calendar, or through Outlook. They provide dedicated services for people to use and interact with the calendar application. In this way, you are utilizing an external system into your own application and requesting some data to be stored and received. This is how microservice architecture behaves, where the APIs serve as the components making this communication possible between different systems.</p><blockquote>An API is a software that can be utilized by other software to communicate with other software or even hardware. It acts as a bridge between different software and devices.</blockquote><p><strong><em>GraphQL is often confused with being a database technology. This is a misconception, GraphQL is a query language for APIs — not databases. In that sense it’s database agnostic and effectively can be used in any context where an API is used.</em></strong></p><p>For understanding the different types of APIs and the different protocols used, we’ll discuss them in upcoming blogs.</p><h3>Features of GraphQL</h3><p>GraphQL is a query language. In a broad sense, GraphQL is a syntax developers can use to ask for specific data and return that data from multiple sources. Yes, you don’t use GraphQL to query a particular type of data store (such as a MySQL database). Instead, we can use GraphQL to query data from any number of different sources.</p><p>It’s importance is listed down in the following list.</p><ul><li><strong>One request, many resources</strong>: Compared to REST where you need to make multiple network calls to each endpoint, with GraphQL you can query all your resources with one call.</li><li><strong>Exact data fetching</strong>: GraphQL minimizes the amount of data transferred across the wire by being selective about the data depending on the client application’s needs. Thus, a mobile client with a small screen can fetch less information. In this way, GraphQL solves problems like Overfetching or Underfetching.</li><li><strong>Strongly typed</strong>: Every query, input, and response objects have a type. On web browsers, JavaScript’s lack of type became a weakness that many tools tried to compensate (Dart from Google, TypeScript from Microsoft). GraphQL allows you to share types between the backend and frontend.</li><li><strong>Better tooling and developer experience: </strong>Introspective server can be queried for the types it supports, allowing API explorer, editor warnings and auto-completion. We don’t have to rely on backend developers to document their APIs anymore. You can just explore endpoints and get the data you want.</li></ul><blockquote>The designers of the schema already know what the schema looks like but how can clients discover what is accessible through a GraphQL API? We can ask GraphQL for this information by querying the ‘<em>__schema</em>’ meta-field, which is always available on the root type of a Query per the spec.</blockquote><ul><li><strong>Version free:</strong> The shape of the data returned is determined entirely by the client’s query, so servers became simpler. When you’re adding new product features, additional fields can be added to the server side, leaving existing clients unaffected. This ultimately leads to faster development cycles and product iterations.</li></ul><h3>A real world example — Blogging Platform</h3><p>To show how is GraphQL different from REST when it comes to fetching data from an API, let’s consider a simple example scenario: a blogging application.<br>The app needs to display the titles of the posts of a specific user. The same screen also displays the names of the last 3 followers of that user. How would that situation be solved with REST and GraphQL?</p><h4>Data fetching with REST vs GraphQL</h4><p>With a REST API, we’ll probably gather data through multiple endpoints. These endpoints could be</p><ul><li><strong>/users/&lt;id&gt;</strong> <strong>—</strong> to fetch the initial users data</li><li><strong>/users/&lt;id&gt;/posts — </strong>to fetch all the posts of the user</li><li><strong>/users/&lt;id&gt;/followers — </strong>to fetch list of followers of the user</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CGw4dP39knujQHlh.png" /><figcaption>With REST, we will have to make three requests to different endpoints to get the required data. Also, there will be a problem of overfetching as excess data will be received than what is needed. So the data has to be formatted on the client-side before it can be rendered.</figcaption></figure><p>In GraphQL, a single query will be sent to the GraphQL server that specifies the exact data requirements. The server sends back the response with the desired data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pxDu6XlqY1reQr67.png" /><figcaption>Client can specify exactly the data it needs in the query. And the server responds in the exact format as the nested query.</figcaption></figure><p>Through this example, we can clearly see that this query only fetches the user’s name, the last three followers and the title of the posts written by the user. This makes the system very efficient, as the response is very lightweight when compared to the REST API response, and the client can render the data faster.</p><h4>Coming later:</h4><ul><li>Types of APIs and its Protocols</li><li>REST vs GraphQL — their differences and how to choose between the two?</li><li>GraphQL Core Concepts</li></ul><p>If you feel the above blog was helpful, do follow me or drop a comment!!</p><p>Happy Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10618e69073d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Merkle Tree in Blockchain]]></title>
            <link>https://blog.blockmagnates.com/merkle-tree-in-blockchain-b581e4c48bfe?source=rss-cabb56682624------2</link>
            <guid isPermaLink="false">https://medium.com/p/b581e4c48bfe</guid>
            <category><![CDATA[merkle-tree]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Vinayak Singh]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 12:56:47 GMT</pubDate>
            <atom:updated>2023-06-19T11:53:05.321Z</atom:updated>
            <content:encoded><![CDATA[<p>Merkle Tree is a type of data structure that’s used to keep track of the transactions and their authenticity. It allows us to verify efficiently that the data belongs in the larger set of data. Also known as “binary hash tree”, Merkle Tree are named after Ralph Merkle, who proposed the term in a 1987 paper titled “A Digital Signature Based on a Conventional Encryption Function”.</p><h3>What is a Merkle Tree?</h3><p><strong><em>Merkle tree</em></strong><em> is a </em><a href="https://en.wikipedia.org/wiki/Tree_(data_structure)"><em>tree</em></a><em> in which every leaf node is labelled with the hash of a data block and every non-leaf node is labelled with the </em><a href="https://en.wikipedia.org/wiki/Cryptographic_hash_function"><em>cryptographic hash</em></a><em> of the labels of its child nodes. It’s primary purpose is to prove the consistency of data.</em></p><p>To give a better understanding, consider the following tree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*CTIq49cqG1A1joLlqOAEsQ.jpeg" /><figcaption>Example of a Merkle Tree</figcaption></figure><p>Here, “Txn _” refers to a transaction and “H” refers to a hash. This image showcases 8 transactions labelled from A to H inside a block. Note that this image is only for understanding purpose, and a real block contains on an average, 2000–3000 transactions (or even more, depending on the block size).</p><blockquote>A hash function is a mathematical function that takes an input (usually a large value in size) and converts it into a new output value, usually smaller in size.</blockquote><p>And for those of you who aren’t familiar with tree data structure, think of this tree as a real Tree, but inverted. The root is the top, with the leaves occupying the bottom-most level. In the above Merkle Tree, hashes on the bottom row are referred to as “leaves”, intermediate hashes as “branches”, and the hash value at the top as the “root”.</p><p>So, the image above has <em>eight leaf nodes </em>which hold the hashed values of individual transaction data. And the above non-leaf nodes contain the cryptographic hashes of the combined values of respective child nodes.</p><h3>How is a Merkle Tree constructed?</h3><p>The following steps are followed to construct a merkle tree in blockchain blocks.</p><ul><li>The transaction data is hashed. Each of this hash forms the leaf node in our tree.</li><li>These hash values are paired together. In case there is odd number of transactions present in the block, the last transaction is doubled, hashed and paired with itself. So if there were 7 transactions (A to G), the tree will look something like this</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*V3YU352N8d9Xwkc-5JiqCQ.png" /><figcaption>Merkle Tree with odd number of transactions</figcaption></figure><ul><li>Combine the two hash values paired above. Now apply the same hash function to generate a new hash from the combined value. This will form the parent node for the paired nodes.</li><li>Repeat the above step until only a single node is left in the tree. This node is known as the Merkle Root Hash. It’s a very special hash value, whose importance will be discussed below.</li></ul><h3>But why use a Merkle Tree?</h3><p>Consider three peers in a large blockchain network- Alice, Bob and Charlie. To verify whose chain is correct, one solution is that every node sends its own chain to other two nodes, they compare each transaction, and come to conclusion after verification is done. Nothing seems to be of problem, right?</p><blockquote>A peer is simply a node/device running the blockchain software. In networking, peer refers to any device that participates (connects) in the network.</blockquote><p><strong>But what happens when the number of transactions increase exponentially, and let’s say the number of nodes in the network increase from 3 to 30k?</strong></p><p>This solution will work properly when the number of transactions are quite less. But as soon as the transactions increase, and the peers increase, it’ll result in a steep increase in the cost to verify all the transactions. The transactions will be constantly moving to-and-fro the network. Not only will this increase the computations happening per second, but more resources will also be wasted on this task.</p><h4>Simplified Verification</h4><p>Merkle Trees provide a very efficient solution for this problem. Every block in a blockchain stores a set of transactions inside itself. To verify the given data set with the original set of transaction data, the system does not compare each transaction detail every time. Instead, every transaction is hashed and a pair of transaction is concatenated together. This step is done repeatedly, until a single hash value is achieved. This allows you to verify the correctness of all the transactions present in the blockchain network without having to download the entire blockchain onto your system.</p><blockquote>One important aspect of the Root Hash value is the fact that it is stored inside the <strong>block header</strong> of a block. The unique block identifier, called the block hash, is calculated by hashing the entire block header (including the Merkle root hash) using a specific cryptographic hash function. <br><strong>This block hash will be stored inside the block header of the block mined after it.</strong> For example, the block hash of <a href="https://www.blockchain.com/explorer/blocks/btc/793253">bitcoin block number 793253</a> is 00000000000000000001371ae2b3e60147ccaa8b207a35082e693164b76811a4.</blockquote><p><strong>Instead of keeping all transactions, a user only needs to keep a copy of the block headers of the longest proof-of-work chain</strong>, which he can get by querying network nodes until he’s convinced he has the longest chain, and obtain the Merkle branch linking the transaction to the block it’s timestamped in. He can’t check the transaction for himself, but by linking it to a place in the chain, he can see that a network node has accepted it, and blocks added after it further confirm the network has accepted it. This confirms that the reaction is verified, and therefore, correct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*p3nQKxSfJ3D2tSXt4ESZkA.png" /><figcaption>Example of the longest POW Chain in bitcoin</figcaption></figure><p>This way of verification is reliable as long as the network is controlled by honest nodes. If the network is overpowered by an attacker (famously known as the 51% attack), this simplified method can be fooled by the attacker. But don’t worry, it is <strong>very difficult to be done</strong> and the amount needed to be invested to carry out such an attack is so huge that it’s better to be on the legitimate side of the network.</p><h4>Reclaiming Disk Space</h4><p>Once the latest transaction is buried under enough blocks, the spent transactions before it can be discarded to save disk space. To facilitate this without breaking the block’s hash, transactions are hashed in a Merkle Tree, with only the root included in the block’s hash. Old blocks can then be compacted by stubbing off branches of the tree. The interior hashes do not need to be stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qnkTKYQANyCepWkSOZqNWg.png" /><figcaption>Same block, before and after stubbing the older transaction data</figcaption></figure><p>Since Hash01 is created using Hash0 and Hash1 which, in turn, are created from their respective transactions, the nodes below Hash01 can be removed to save some extra space.</p><h3>Searching for a transaction in Merkle Tree</h3><p>Merkle trees allow searching for a particular data item without having to traverse the entire tree, and gives accurate result even if the tree has some missing data. This means they can be used to check for inconsistencies in all kinds of distributed systems!</p><blockquote>For Blockchain, storing transactions as Merkle Trees allows us to look at a block and verify that a transaction was part of it by only having part of the data set!</blockquote><p>Consider the previous example. Suppose we need to check whether <em>Transaction E </em>is included in the list. The only data we have is the root hash <strong>H(ABCDEFGH) </strong>and <strong>H(E)</strong>, the hash value of “<strong>Txn E</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*TbHHHM53yQ9WxaMBPOENlw.jpeg" /><figcaption>Finding if E is part of the Merkle root</figcaption></figure><p>In order to find if there is some data in the blockchain named “<strong>Txn E”, </strong>we’ll need a few more components that contribute in forming the hash. We don’t need lots of transaction data. Instead, some hash values are needed so that new hash values can be formed to reach the single root value.</p><p>If you look at the above figure closely, you’ll see that we need something related to <strong>F</strong>, but do you think we need the entire transaction named “<strong>Txn F”</strong>? No, we don’t. We only need the hash H(F) to form the parent hash H(EF). Similarly, we don’t need all the other transactions. In this tree, the other two requirements are <strong>H(GH) </strong>and<strong> H(ABCD)</strong>. Using these two hashes in the same manner, and hashing again gives us the final hash value. Now compare it with the original Merkle Root hash.</p><p>If it matches, voila!!! the transaction has been verified to be in the block. Else, there is something wrong and the blockchain doesn’t have any such transaction.</p><pre>E = hash of transaction &#39;E&#39;                        &lt;- derived from Txn E<br>F = given, hash of unknown transaction &#39;F&#39;<br>GH = given, parent hash of two unknwon transaction hashes H(G) and H(F)<br>ABCD = given, grandparent hash of multiple unknown transaction hashes<br><br>EF = Hash(E+F)<br>EFGH = Hash(EF+GH) = Hash(Hash(E+F) + GH)<br><br>Hash(ABCDEFGH) = Hash(Hash(EFGH)+Hash(ABCD)) = Hash(Hash(Hash(E+F)+GH)+ABCD)<br><br>Hash(Hash(Hash(E + F) + GH) + ABCD) = Hash(ABCDEFGH)  &lt;- merkle root hash</pre><blockquote>The Merkle path for Txn E will be H(F), H(GH) and H(ABCD). It means that we only need the hash values F, GH and ABCD to prove E is in the tree.</blockquote><h4>Another scenario….</h4><p>Let’s say inside this Merkle tree of a specific block, we replace E with M. That is, the root value is H(ABCDMFGH). As soon as the mismatch is found, it denotes that the list of transactions does not include our transaction labelled E. Since the block holds a completely different transaction list, the node that holds this altered block is removed from the network.</p><p><strong>If anyone tries to alter data at one location, the transaction hash value will change</strong>, leading to a change in the root hash. This ultimately changes the block header and making it invalid. The network node detecting this invalid block can raise alerts. <br>Thus,<strong> other nodes in the network can detect this inconsistency based on the mismatch in the root hash, prompting their software to download the full block and alerted transactions to confirm the inconsistency. </strong><br>This prevents the 51% attack referred to in this article previously.</p><h4>Conclusion</h4><p>The savings offered by the use of Merkle trees become important in the longer chains of the blockchain network. Since the <strong>time complexity to search in a binary tree is O(log(n)) </strong>(where n being the number of nodes in the tree), it offers efficient utilization both in terms of storage and time. They store hash values of data that require lesser storage space. You can easily search for data by producing the Merkle path, rather than searching in the entire tree. Merkle tree efficiency also depends upon the selection of hash functions.</p><p>Hope you enjoyed reading this article. Follow for more related content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b581e4c48bfe" width="1" height="1" alt=""><hr><p><a href="https://blog.blockmagnates.com/merkle-tree-in-blockchain-b581e4c48bfe">Merkle Tree in Blockchain</a> was originally published in <a href="https://blog.blockmagnates.com/">Block Magnates</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Blocks in Blockchain?]]></title>
            <link>https://medium.com/@vinayak-singh/what-are-blocks-in-blockchain-f73835d197ba?source=rss-cabb56682624------2</link>
            <guid isPermaLink="false">https://medium.com/p/f73835d197ba</guid>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[bitcoin-mining]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Vinayak Singh]]></dc:creator>
            <pubDate>Mon, 29 May 2023 16:17:39 GMT</pubDate>
            <atom:updated>2023-05-29T16:17:39.214Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Blockchain, as the name suggests, is a chain of blocks containing some information. These blocks are containers holding a record of transactions on the blockchain. In Bitcoin’s case, the transactions are primarily transfers of bitcoins. However on some blockchains, they can also contain a variety of other information, even code of computer programs. One example of such programs can be smart contracts.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESzybud4T6OiUxynKT1r0g.jpeg" /></figure><p>To provide a better perspective, let’s take a real-life scenario. Suppose Alice wants to transfer 0.50 BTC (bitcoin) to Bob. On the blockchain network, there has to be some place where the transaction information can be stored. This place is called a <strong>block</strong> in blockchain. Before going ahead, what does this transaction look like? How are the two different people able to transact exactly?</p><h3>What is a transaction in blockchain?</h3><p>People have their bank accounts where they can hold money. Even if you have cash, you generally carry it in your wallets, purses or any bag. It provides security and a sense of ownership, right? And well it makes carrying money easier. For cryptocurrencies as well, you have digital wallets. People can open their own wallets, with addresses that act as unique identifiers for each specific wallet.</p><p>To perform a transaction, Alice opens her wallet, inputs Bob’s wallet address or if possible, scans Bob’s QR code. Input the amount she wants to transfer and selects Send to authorize the payment. Within a few seconds, Bob sees the transaction on his wallet, completing the transaction.</p><p>In simple terms, a transaction tells the network that the owner of a certain number of digital currency has authorized the transfer of some of this currency to another owner. Transactions are like a double-entry bookkeeping ledger. That is, it contains one or more inputs (debits against an account) and on the other side, “outputs” which are the credits added to the receiving account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*gSF6gE-sVlPnjNKF.png" /><figcaption>Transaction as Double-Entry Bookkeeping</figcaption></figure><blockquote>Note that during these transactions, the output amount always adds up to value slightly less than the input amounts. <strong>This difference between the debit amount and the credit amount is known as ‘gas fee’ or ‘transaction fee’.</strong> It’s a small price paid to the miner, or let’s say to the person who does the proof of work and adds this transaction onto the blockchain ledger (which is not an easy task).</blockquote><p>To see how a real life transaction that gets stored in a block after it gets added to the ledger, here it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myhZaqXyRslqh2sR2J1K3Q.png" /><figcaption>Example of a Bitcoin transaction</figcaption></figure><p>As it shows, the block number 277,316 has its hash ID. An amount of 0.1 BTC is transferred from 1 wallet to 2 different wallets. Notice the difference between output value and input value. This is because of the transaction fee of 0.0005 BTC that is spent to support the network. Another thing to point out is that the size of this block is 258 bytes. Then there are other parameters written that can be studied below: <a href="https://www.blockchain.com/explorer/transactions/btc/0627052b6f28912f2703066a912ea577f2ce4da4caa5a5fbd8a57286c345c2f2">https://www.blockchain.com/explorer/transactions/btc/0627052b6f28912f2703066a912ea577f2ce4da4caa5a5fbd8a57286c345c2f2</a></p><h3>How does a block work in blockchain?</h3><p>A blockchain network deals with tremendous activity, and maintaining each and every transaction is not so straightforward. A single block can only store a certain number of transactions that depends on a lot of factors, like the type of blockchain protocol it is based on, block size and the transaction size.</p><blockquote>In Bitcoin, for example, the block size is limited to 1 megabyte (MB). The size of each transaction can vary, but on average, a Bitcoin transaction is around 250–300 bytes. Given the block size limit of 1 MB, this means that a single block can store approximately 3,000 to 4,000 transactions.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Y-cKanQnpGXcZNXO.png" /></figure><blockquote><strong>The Genesis block is the very first block added to the blockchain network.</strong></blockquote><p>When a certain number of transactions are completed, they are compiled into a new block and this new block is ready to be added onto the ledger. This new block holds certain elements, which are</p><ul><li><strong>Magic number</strong>: A number containing specific values that identify that block as part of a particular cryptocurrency’s network. For example, this 4 byte field contains the value 0xD9B4BEF9 signifying that the block belongs to the bitcoin blockchain network</li><li><strong>Blocksize</strong>: Another 4 Byte field that sets the size limit on the block so that only a specific amount of information can be written in it.</li><li><strong>Block header</strong>: Second most important element of a block. It contains information about the block and the data contained inside it.</li><li><strong>Transaction counter</strong>: A number that represents how many transactions are stored in the block.</li><li><strong>Transactions</strong>: A list of all of the transactions within a block.</li></ul><h3>Structure of a Block</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*O3e1vKtvncfxyudBNr9WWw.png" /><figcaption>Components of a block</figcaption></figure><p>The transactions element is the greatest element, simply because it holds the data of multiple transactions in it. After it is the Block header. It holds the following elements:</p><ul><li><strong>Version</strong>: This field stores the version number of the blockchain protocol (cryptocurrency in general terms) the block belongs to.</li><li><strong>Previous block hash</strong>: Contains a hash (encrypted number) of the previous block’s header.</li><li><strong>Merkle root hash</strong>: It stores the merkle tree root’s hash of the current block. It is a special data structure similar to binary trees that is made up of hashes of the transaction data stored in the block. <br>Since transaction data is immutable, merkle root hash allows faster and easier verification of any transaction over the internet.</li><li><strong>Time</strong>: It stores the timestamp when the block was added in the blockchain ledger after successful mining and verification.</li><li><strong>Target Bits</strong>: Also known as the difficulty target or difficulty bits, targer bits are a value stored in the block header of a blockchain block. This value represents the level of difficulty required for miners to find a valid block hash. The new block’s hash should be less than or equal to the difficulty bits.<br>The target bits value is periodically adjusted based on the network’s hash rate and the desired block creation rate. By controlling the target bits, blockchain networks can regulate the rate of block creation, ensure the consistency of the block time, and maintain the security and stability of the blockchain.</li><li><strong>Nonce</strong>: The encrypted number that a miner must solve to verify the block and close it. It is the only alterable field in the block header. The miners collect the set of transaction data, combine it with the other elements of the block header (previous block’s hash, timestamp) to create the block data. Now they combine this block data with the nonce, hash it using any defined hash function (SHA-256 in case of bitcoin) and validate against the criteria set by protocol target bits. For example, the resulting hash should have specific number of zeroes in the starting, or be less than the numeric threshold. If it doesn’t validate, the nonce is adjusted and all the steps are repeated.</li></ul><p>The miners race against each other to solve this mathematical puzzle using the blockchain client they are using. Basically it’s just a software that does this work and uses electricity. Let’s say a certain miner is the first person to find the solution that gets accepted. He then broadcasts the block with all the transactions to the other nodes (miners, participants) present on the network. These nodes verify the cryptographic proof and the transactions present in the block. Only after the majority of the nodes have verified the block, it gets added to the network, and now the miners start to solve the next puzzle after including this newly found block’s hash into their calculations.</p><h3>Block Time</h3><p>The average time taken by the Blockchain network to generate a new block of transactions and add it to its ledger is called the block time. Certain Blockchains can create new blocks within a few seconds, while others take few minutes. For instance, the block time for Ethereum Blockchain is between 14 and 15 seconds, while the block time for bitcoin Blockchain is around 10 minutes. In cryptocurrency, a shorter block time means faster transactions.</p><h3>Important things to remember about block creation and new transactions</h3><p>You might think that since the addition of new blocks can take upto several minutes, new transactions are held in the pool of transactions. Let’s take the previous example of Alice and Bob. Does the transfer of 0.5 BTC take 10 minutes before the updated amount reflects in Bob’s wallet? <br>No, it doesn’t exactly work that way.</p><p>While it’s true that the average time for a new block to be added to the Bitcoin blockchain is approximately 10 minutes, the transaction verification process can occur before a block is added. When Alice initiates the transaction, it is broadcasted to the network and added to the transaction pool, also known as the mempool.</p><p>While confirmations ensure the transaction has been accepted by the whole network, such a delay is unnecessary for transactions of very small value. A merchant may accept a valid small-value transaction with no confirmations, with no more risk than a credit card payment made without ID or a signature, like merchants routinely accept today.</p><p>Miners, who are responsible for creating new blocks, select transactions from the mempool to include in the next block they mine. Miners tend to prioritize transactions with higher fees, so including an appropriate transaction fee can help expedite the confirmation process. Once a miner successfully mines a block and includes this Alice-Bob Transaction, it basically means that the transaction seems correct according to the account statements of both the accounts and is verified once. Now the block is propagated to the network. Other nodes in the network start validating the block, which includes verifying the included transactions.</p><p>Nodes follow the consensus rules and perform their own verification process to ensure the block’s validity. Once a node validates the block, it can consider the transactions within the block as confirmed, including Alice’s transaction.</p><p>At this stage, Bob can receive a transaction confirmation indicating that his transaction has been included in a block. The confirmation typically provides a level of assurance that the transaction is considered valid and will be included in the blockchain.</p><p>In summary, while complete verification from the entire blockchain network takes time, transaction confirmations can be sent to Bob once his transaction is included in a block and validated by a sufficient number of nodes.</p><blockquote>So, while a transaction may not be immediately included in a block, it can still be verified and completed before the block is added. Transaction confirmation time depends on factors such as transaction fees, network congestion, and the priority assigned to the transaction by the miner. Hence, it’s possible for a transaction to wait in the mempool for some time before being included in a block.</blockquote><h3>In Conclusion</h3><p>Blocks are the basic constructs of blockchain. Each block contains a set of transactions, metadata, and mining information. The above article covered details of a block in blockchain technology.</p><p>Hope you enjoyed and learned something new reading this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f73835d197ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart Contracts in Blockchain]]></title>
            <link>https://medium.com/@vinayak-singh/smart-contracts-in-blockchain-58538d0b3dca?source=rss-cabb56682624------2</link>
            <guid isPermaLink="false">https://medium.com/p/58538d0b3dca</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <dc:creator><![CDATA[Vinayak Singh]]></dc:creator>
            <pubDate>Fri, 21 Apr 2023 19:13:21 GMT</pubDate>
            <atom:updated>2023-04-21T19:13:21.058Z</atom:updated>
            <content:encoded><![CDATA[<h4>How smart contracts revolutionised the way of handling contracts digitally and efficiently</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*kpk7SDoQGPhr9CaZ7z-0_Q.jpeg" /></figure><p>Simply put, Smart Contracts are “<strong>digital programs stored on blockchains that run when certain specified conditions are met</strong>”. But let’s discuss it properly.</p><p>Smart contracts are just <strong>like usual contracts that will let you exchange assets</strong> (property, money, shares) or anything valuable <strong>securely </strong>and<strong> transparently</strong>, but <strong>digitally</strong>. Smart contracts involve contracts being converted into code which allows computers to store files that run on a blockchain (think of it as an advanced database system where data or transactions are stored on a network of computers). These contracts can be set to automatically put into effect when certain terms and conditions are met.</p><p>To give you real-world example instead, suppose you want to buy a car from another person. In such a scenario, the bank acts as the intermediary entity. If you have sufficient money in your account, then only you can buy the car of your choice. Here, the seller trusts you with the fact that you have required amount of legitimately earned money, while you trust the dealer with all the specifications of the car, and upon payment you’ll get your car delivered to your address. <strong>With the use of smart contracts in blockchain, all these problems are solved</strong>. Based on the transaction, the contract gets setup, and the <strong>assets </strong>that are going<strong> to be exchanged are tokenized</strong>. All the terms and conditions are mentioned specifically and upon the meeting of these conditions only, the transaction takes place. In this system, <strong>instead of any middle entity, the smart contract is evaluated by all the participating nodes in the blockchain</strong>, therefore reducing the chances of failure/fraud entirely.</p><blockquote>Smart Contracts are like vending machines — you choose a product, pay the specified amount for it, and only when the machine receives the money you get your product. If you don’t select a product or pay enough money, the machine won’t give out your product.</blockquote><h3><strong>How smart contracts work?</strong></h3><p>Smart contracts work on the simple rule of “if/when..., then …” statements that are written in the form of code that runs on the blockchain. A network of computers (each having equal importance) executes the actions specified in the smart contract when the written conditions are met. These actions may involve the release of payment only when the assets are received, vehicle registration, stock trading, supply chain management etc.</p><p>Whatever the action is, it gets updated in the blockchain and <strong>only the parties that have been given the permission to view can see the results</strong>.</p><p>The <strong>terms in the smart contract</strong> that are programmed by a developer <strong>include not only the terms of the trade between the parties</strong> (“if/when… then…” rules), <strong>but also the terms to resolve any disputes that might occur, how their data will be represented</strong> on the blockchain.</p><h3>Workflow of a smart contract</h3><p>First, the developer writes the code to setup the contract between the parties. He mentions the <strong>parties</strong> that are allowed to view the transaction at every stage, <strong>terms and conditions</strong> associated with the transaction and the <strong>assets</strong> being traded. This digital contract gets uploaded onto a blockchain and every node present in the blockchain receives the contract. Each individual on this decentralized network now stores the code and evaluates the terms of the contract. Here, a <strong>trigger event</strong>, such as the receipt of a payment or the fulfillment of a specific action, <strong>occurs by an externally owned account, activating the smart contract</strong>.</p><p>Upon activation, the <strong>contract automatically executes its terms</strong>, which may involve transfer of assets or ownership/ release of funds, or any other action specified in the code. In case the preconditions are not met, the smart contract will not execute and an error will be raised.</p><p>After execution, the network validates the outcome of the transaction by consensus of all participating machines to maintain trust and security in the system. The <strong>outcome of the execution gets recorded and stored on the blockchain and is public for anyone to verify the transaction</strong>.</p><h3>Benefits of using smart contracts</h3><p>Smart contracts are very powerful and there is a big increase in the public interest over the last few years. It is because of the following reasons:-</p><ul><li><strong>Savings —</strong> The use of smart contracts removes the requirements of intermediaries as a whole, and therefore, removes the time delays and cost of operations associated with such processes.</li><li><strong>Speed, Efficiency and accuracy —</strong> Once a condition is met, the contract is executed immediately. Because smart contracts are digital and automated, there’s no paperwork to process and no time spent reconciling errors that often result from manually filling in documents. To get an idea of this, consider an example of supply chain where the goods need to be inspected by a human-monitored system. Upon getting desired results only is the payment transferred for the goods. Now this entire process can be automated using smart contracts, therefore, reducing overall time of manufacture of the goods. Otherwise, the supply chain gets disrupted and ultimately, the prices of goods increase that causes an economical pressure on the consumers.</li><li><strong>Security — </strong>Blockchain transaction records are encrypted using complex hashing algorithms, which makes them very hard to hack. Also, each block/record is connected to the previous record on a distributed ledger; hackers would have to alter the entire chain to change a single record, which as expected, is very difficult to perform. In other words, blockchains are immutable and any transaction that gets stored on the ledger once cannot be altered again.<br>Then, each individual system on the decentralized network holds all the records. This prevents any person from trying to inject false records for malicious intent. Consensus is maintained in the network and any chain that holds false/altered records gets removed the network entirely.<br> Lastly, smart contracts have increased security provisions because it is the code that executes these contracts, meaning no human error is possible.</li><li><strong>Trust and transparency</strong> <strong>— </strong>Without the involvement of any third party, there’s no need to question whether information has been altered for personal benefit. And since these encrypted records of transactions are shared across the decentralized network, transparency is maintained while keeping track of original transactions.</li></ul><h3>Uses of Smart Contracts</h3><p>Smart Contracts are being incorporated in various domains because of the advantage it offers over the orthodox ways of carrying out transactions. Some examples are</p><ol><li><strong>Trading — </strong>The traditional trading financial activities always required a broker or a middleman. This made the whole process lengthy and a little costly. Smart Contracts have made international trade easier make international trades easier, faster and it ensures all the processes are automated without the need of any third parties. This increases transparency and reduces chances of frauds.</li><li><strong>Supply Chain Management —</strong> One of the potential uses of smart contracts is supply chain management. Blockchains that support smart contracts store records for all the processes starting from collection of raw materials to delivery of the final product. They record every detail of the entire process along with the concerned persons.<br> Smart Contracts can utilize use of IoT sensers to track the latest update of a product at each step of its transportation between places, or let me put it this way, at each point between its delivery from manufacturing plant to the supplier. In this way, history of lost/stolen goods along with items that are late in delivery are recorded with their exact location as well. <br> Moreover, every concerned person will be able to check if there is any failure of any stakeholder to fulfil the terms and conditions of the contracts. The smart contract is making the whole supply chain transparent to its relevant parties. Thus, they are making the supply chain industry advanced and improved.</li><li><strong>Mortgage System —</strong> At the time of making any mortgage agreement, there must be an estimation of the information about the credit, earnings, expenditures, and some other important information. All these things make the procedure complicated, costly, and lengthy.<br> With the smart contract technology, all the procedures for getting a mortgage will be so easy, cheap and fast. This technology will handle all the stuff automatically with great care. There will be no confusion, no problem, no extra charge, and no complication with a lot of papers.<br> More importantly, all these procedures will be transparent to all the members of the concerned parties. This technology will connect the interested parties to complete the deal by signing off the agreement which is entirely digital and error free. Both the interested parties will know for what they are signing.</li><li><strong>Decentralized Finance or deFi — </strong>It’s based on the premise of the real-world trading system. Here, users can create their accounts and get their ‘wallet’. Smart Contracts allow these transactions, and a user can lend their digital currency, get a loan, trade or even safe for the future. All of this happens through special applications known as decentralized applications (dApps). A very big example of this is the advent of NFTs or non-Fungible tokens.<br> Suppose you purchase an in-game item (lets say a costume for your character/ skins for your weapons or vehicles). Now this item is purchased using currency of real-world value. But there’s no real-world worth of such in-game things. So, using digital tokens, what can be done is tokenize the item and associate this token with your special wallet account. And you can trade this in-game item with another player on your choice. By doing this you can add real world value to an item that was previously present only within the game and you possibly couldn’t do anything except seeing it within the game.</li><li><strong>Voting System — </strong>The existing system of voting in different countries requires a lot of manpower to setup booths and then the counting of so many votes is very difficult. And then the fact that there can be human errors, miscalculations or even tampering of votes (rigged voting systems, fraudulent EVMs) shows how complex this system is. Smart Contracts offer solutions for all these problems. After fulfilling conditions required to be eligible to vote, a person can easily hop onto the voting blockchain system and vote for the candidate of his choice. And this system cannot be altered by any third-party while being transparent to the entire system (therefore preserving the privacy of each voter).</li><li><strong>Insurance Claims — </strong>The existing system of insurance claims is a very tiring process that is complicated and irritating for both the parties. No one’s at fault because it requires so many formalities and paperwork and completing this is a long process for a human. Therefore, this is a great application of smart contracts.<br> Smart contracts can streamline and automate the entire process. It will recognize any condition and state the claim automatically itself. Thus, it will manage the rest of the process without any error.</li></ol><p>To sum everything up, smart contracts offer an efficient and smooth way to create and execute agreements across many different industries with the aim to automate processes and allow their business to be done more securely and efficiently, both time-wise and money-wise.</p><p>Smart Contracts also shine as being another application of the world-changing blockchain technology, and is only expected to increase the possibilities as time goes on.</p><p>To learn more on smart contracts, I’m linking this page from ethereum.org itself.</p><p><a href="https://ethereum.org/en/smart-contracts/">Smart contracts: What are the and benefits</a></p><p>Happy Learning!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58538d0b3dca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction To Blockchain]]></title>
            <link>https://medium.com/@vinayak-singh/introduction-to-blockchain-a9df685b0174?source=rss-cabb56682624------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9df685b0174</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <dc:creator><![CDATA[Vinayak Singh]]></dc:creator>
            <pubDate>Sun, 05 Mar 2023 17:17:49 GMT</pubDate>
            <atom:updated>2023-05-29T12:52:46.822Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kbu7gaCW6S0SAbQl" /></figure><p>A beginner’s guide to Blockchain, what it is and how it works.</p><p>Imagine yourself at a hypermarket buying fruits and vegetables and there are different QRs for each shelf. On scanning the QR, you are provided with every detail about the item, ranging from the place where it was grown, picked, cleaned, distributed and then finally transported to the shop.</p><p>What if you can trace and track the exact time and position during its entire duration of its transportation (means and how long it took at every step)? <em>Keeping a manual record surely seems a very cumbersome process in today’s world of technology.</em></p><p><strong>So the question arises — is there a technology that can help record information at every step and make that information available to everyone?</strong></p><p>In simple terms, blockchain is the exact thing.</p><h3>What is Blockchain?</h3><p>The definition of blockchain can be given as <em>a peer-to-peer, immutable, decentralized ledger system that allows peers to transact between them without any centralized authority. To make it decentralized, each peer carries a copy of the ledger.</em></p><p>But let me explain these terms one by one.</p><ol><li><strong>peer -to-peer</strong> -&gt; A peer is simply any connected device on the network. Hence, peer-to-peer refers to the distributed application architecture that partitions tasks or workloads between peers. Peers are equally privileged, equipotent participants in the network. They are said to form a peer-to-peer network of nodes.</li><li><strong>Immutable</strong> -&gt; Every time a new block gets added to the existing chain, its newly generated hash is dependent on the data of the previous blocks along with the data of the new block. Assume there is a chain of 5 blocks, and you want to update the 2nd block (first block after the genesis block). And you’re successful doing so. But now the hashed value is changed. And to keep the chain, you’ll need to update the hash of the 3rd block, and so on… I think you know where we are going through this. In this way, new blocks of transactions can only be added at the end, and the existing blocks can never be changed without alarming the entire network that there is someone trying to alter the data for his/her personal gains.</li><li><strong>Decentralized</strong> -&gt; There is no central entity governing over the entire system. Instead, all the nodes collectively (or, the majority of the nodes) govern each and every transaction taking place in the blockchain</li><li><strong>Ledger</strong> -&gt; A ledger is a book or collection of accounts in which account transactions are recorded such as payments, supply chain details, medical records, real-estate contracts and others as required.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*UvNEQBBANOcpbwKkT_xqLg.png" /><figcaption>original blockchain</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*e-EZe7f7g0DcnVsI7Yc4lA.png" /><figcaption>on trying to update the 2nd block, the chain breaks.</figcaption></figure><h3>But why is there the need of a decentralized system?</h3><p>The existing infrasctructure of any form of transaction requires a third party(<em>which can be a bank or any other governing institution, or even a person who can act as a guarantor</em>). <strong>This system depends on the fundamental concept of trust</strong>. The buyer has to trust the seller that upon payment, seller will provide him the required item of the desired quality. And in reverse, the seller has to keep faith in the buyer that he’s paying in real currency and there’ll be no problem ahead. And I’m not writing down all the other issues that can arise in a transaction like this. Then include the <strong>expenses for the third party, cost of mediations plus the increase in time</strong> required for a single transaction to complete properly, without any fraud.</p><p>By using a digital decentralized system instead, the electronic payment is <strong>based on cryptographic proof</strong> instead of trust where the transaction will only move forward after both the parties fulfill desired requirements. <strong>Transactions that are computationally impractical to reverse would protect sellers from fraud</strong>, and routine escrow mechanisms could easily be implemented to protect buyers. <strong>We can maintain a computational proof of the chronological order of transactions</strong>. The system is secure as long as honest nodes collectively control more CPU power than any cooperating group of attacker nodes which we’ll cover later in this article.</p><h3><strong><em>And how is a Blockchain ledger different from a database?</em></strong></h3><p><strong><em>Are the two not used for same purpose — saving, organizing in a structured manner, maintaining, and controlling data/information?</em></strong></p><p>Both blockchain and databases record transactions, but the<strong> database is a centralized entity </strong>and, therefore,<strong> </strong>behaves like a<strong> single point of failure(SPoF). </strong>In contrast, the<strong> Blockchain </strong>is<strong> decentralized.</strong></p><p><strong>Every node in the blockchain network collectively takes part in the consensus algorithm using Proof-of-Work.</strong></p><p><strong>Databases are owned by a central authority</strong>(for example a company, or a government institution), which <strong>controls access</strong> by granting different roles to different users. In contrast to this, <strong>Blockchain is a peer-to-peer network where each node can connect with every other node, and blocks in a chain are connected cryptographically</strong>.</p><h3>Use-Cases of Blockchain Technology</h3><h4>Supply chain management</h4><p>With blockchain, supply chain companies can document production updates to a single shared ledger, which provides complete data visibility and a single source of truth. Because transactions are always time-stamped and up to date, companies can query a product’s status and location at any point in time. This helps to combat issues like counterfeit goods, compliance violations, delays, and waste. In addition, immediate action can be taken during emergencies (e.g., in the case of product recalls), and regulatory compliance is ensured by the ledger audit trail. Moreover, by combining blockchain with smart technology like Internet of Things, supply chains can automate tracking the conditions of production, transportation, and quality control. Companies can also choose to share track and trace data with their customers as a way to verify product authenticity and ethical supply chain practices.</p><h4>Healthcare</h4><p>In this field, blockchain can bring revolutionary changes. The Blockchain <strong>makes</strong> <strong>the</strong> <strong>entire prescription process transparent</strong>, from manufacturing to pharmacy shelves. Congestion, freight direction, and speed may all be tracked using IoT and Blockchain. It offers the chance to schedule acquisitions efficiently to <strong>prevent disruptions and shortages</strong> in clinics, pharmacies, and other medical facilities with a given medication. The deployment of digital frameworks built on Blockchain would help ensure that the logistics data avoid uncontrolled adjustments. <strong>It increases trust and prevents the illicit handling of records, payments, and medication themselves</strong> by various people interested in purchasing drugs. The technology can <strong>effectively</strong> <strong>improve the condition of patients while at a competitive cost retaining the funds</strong>. It eliminates all obstacles and barriers in multi-level authentication. Because Blockchain can preserve an incorruptible, decentralised, and transparent log of all patient data, it is ripe for security applications. Furthermore, while Blockchain is visible, it is also private, hiding any individual’s identity behind complicated and secure algorithms that can preserve the sensitivity of medical data. Thanks to the technology’s decentralised structure, patients, doctors, and healthcare providers can all share the same information swiftly and safely.</p><p>With blockchain, supply chain companies can document production updates to a single shared ledger, which <strong>provides complete data visibility and a single source of truth</strong>. <strong>Because transactions are always time-stamped and up to date, companies can query a product’s status and location at any point in time.</strong> This helps to combat issues like counterfeit goods, compliance violations, delays, and waste. In addition, <strong>immediate action can be taken during emergencies</strong> (e.g., in the case of product recalls), and regulatory compliance is ensured by the ledger audit trail. Moreover, <strong>by combining blockchain with smart technology like Internet of Things, supply chains can automate tracking the conditions of production, transportation, and quality control</strong>. Companies can also choose to share track and trace data with their customers as a way to verify product authenticity and ethical supply chain practices.</p><h4>Smart Contracts</h4><p>Contracts regulate most aspects of our professional and personal lives, and they are essential to the functioning of modern society. Make these contracts <strong>smart </strong>by incorporating technology and voila!!! You’ve a plethora of new fields to use blockchain in.</p><p>Smart contracts are computer programs or protocols for automated transactions that are stored on a blockchain and run in response to meeting certain conditions. In other words, smart contracts automate the execution of agreements so that all participants can ascertain the outcome as soon as possible without the involvement of an intermediary or time delay. These agreements can be of any domain, let’s say, in real estate. With this sort of tech in place, a property transaction that once involved nearly endless paperwork can now take place digitally between the buyer and seller. That transaction has greater transparency and security than was previously possible.</p><p>This was just a single example. Smart Contracts are a very important application of blockchain tech.</p><h4>Real Estate</h4><p>Using smart contracts to reduce the paperwork and fasten the entire process is a very important use case of blockchain in this domain. Along with that, blockchain prevents potential frauds. Another great thing going around these days is known as <em>Metaverse</em>. With blockchain, something called tokenization of the real properties is possible. This allows people to transact on real piece of legally approved land without much hassle.</p><p>Then there is increased transparency as the entire history of the land is available on the digital ledger. This allows more accurate tracking of consumer and owner histories across borders and banks. It lessens the possibility of default. Big data real estate players can now better analyze information and make data-driven decisions.</p><p>Another very big use case is fractional investment and ownership. It is made possible by digitally reproducing any asset, lowering the cost of transactions, and making them accessible worldwide. Purchasing real estate requires significant investment, especially given the steady rise in property prices. Through the blockchain, investors can pool their resources and buy their share of a property they could not purchase independently.</p><p>Furthermore, shared ownership enables investors to sell their ownership stake whenever they want. It also allows them to avoid self-management of real estate: its maintenance or lease, which often requires considerable effort.</p><h4><strong>Money Transfer from anywhere to anywhere on the globe</strong></h4><p>The global money transfer is time-consuming, error-prone, costly, and subjected to money laundering. The secure, immutable, decentralized, and transparency feature of Blockchain helps solve money transfer issues without any intermediary.</p><h3>Other Important Terminologies</h3><h4>Nonce</h4><p>It stands for <strong>number used only once</strong> . In finance and cryptography, a nonce refers to a randomly generated number, and it is used to verify transactions or perform security checks.</p><blockquote>The captchas we often find on websites are very much nonces (with letters included) as they are used just once. In a much simpler case, even the OTPs sent to verify transactions are nonces that have the singular use of verifying something for a limited period of time.</blockquote><p>Within several proof-of-work blockchains, including Bitcoin, a nonce is a random 32-bit number that miners use as a base for their hash calculations. Bitcoin miners must attempt to guess a valid nonce (i.e., that starts with a certain number of zeros). The right to add the following block to the blockchain is provided to the first miner to find a nonce that produces a valid block hash during a competition to mine a new block. This miner is also compensated for doing so. <strong>The valid nonce is known as Golden Nonce</strong>.</p><p>Calculating the nonce might seem as an easy task, but it isn’t. Infact, it is quite challenging to estimate the <strong>random 32-bit</strong> string through trial and error. <strong>A nonce can have more than 4 billion possibilities</strong>. Miners must determine the correct nonce and add it to the current header’s hash before rehashing the value and comparing it to the target hash. Miners can obtain rewards for the block when the calculated hash value satisfies the conditions.</p><h4>Node</h4><p>A Node in a blockchain can be any electronic device that is part of a peer-to-peer network and maintain its own copy of the blockchain.</p><h4>Hash</h4><p>A hash is simply a mathematical function using which we can encrypt data. The generated hashes are of fixed length and cannot be reverse-engineered to generate the original hidden data (they work one-way). The same data will always give the same hashed value.</p><p>Hashes are used in several parts of a blockchain system. Each block header contains the previous block’s hash, which ensures that nothing has been tampered with as new blocks are added. Cryptocurrency blockchains use hashes to secure information and make the ledger immutable. This makes hashes the backbone of the blockchain.</p><h4><strong>SHA-256</strong></h4><p><strong>SHA-256 is a cryptographic algorithm that accepts input of any length, scrambles the data deterministically, and returns a hash that is 256 bits or 64 characters long. </strong>SHA-256 hashing algorithm ensures the input can never be derived from the output, making it very secure. It is a part of the SHA 2 family of algorithms, where SHA stands for Secure Hash Algorithm. The significance of the 256 in the name stands for the final hash digest value, i.e. irrespective of the size of plaintext/cleartext, the hash value will always be 256 bits.</p><h4>Mining</h4><blockquote>It’s similar to gold-mining, but here things are done digitally.</blockquote><p>It is the process of validating and recording new transactions on a blockchain performed by Miners for which they have a special mining software.</p><p>By convention, when a new coin (cryptocurrency) is circulated by the creator, he creates the special transaction known as the genesis block for that coin. This adds value for nodes to support the network and make the initial circulation of the coins possible. This steady addition of a constant amount of new coins is analogous to the gold miners who use resources to bring more gold in circulation.</p><h4>Merkle Tree</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*P5fVf-AvMoiFyuk4X1Ch6A.jpeg" /></figure><p>Merkle trees, also known as Binary hash trees, are a type of data structure in computer science. In bitcoin and other cryptocurrencies, they’re used to encrypt blockchain data more efficiently and securely.</p><p>It’s a mathematical data structure made up of hashes of various data blocks that summarize all the transactions in a block. It also enables quick and secure content verification across big datasets and verifies the consistency and content of the data.</p><p><strong>Merkle tree summarizes all the transactions in a block by producing a digital fingerprint of the entire set of transactions.</strong> Merkle tree is <strong>created by repeatedly hashing a pair of transactions from the bottom</strong> until we have only one hash, referred to as <strong>Root Hash or Merkle Root</strong>.</p><blockquote>It is possible to verify payments without running a full network node. A user only needs to keep a copy of the block headers of the longest proof-of-work chain, which he can get by querying network nodes until he’s convinced he has the longest chain, and obtain the Merkle branch linking the transaction to the block it’s timestamped in. He can’t check the transaction for himself, but by linking it to a place in the chain, he can see that a network node has accepted it, and blocks added after it further confirm the network has accepted it.</blockquote><h3>What is a Block?</h3><blockquote>A single chain can be viewed as a linked List, where each node of the chain points to the node before it.</blockquote><p>A Block in a Blockchain record transaction or transactions to organize, monitor, and control information for informed decision making.</p><p>Every time a new transaction occurs on the blockchain, a record of that transaction is added as a new block to the chain. The new block is added to every participant’s node ledger only after applying a consensus algorithm like proof of work to validate the transaction. A block in the chain is immutable. It can never be updated and only be appended to the end of the chain.</p><blockquote><strong><em>The Genesis block is the very first block added to the blockchain</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XzUqNJHpVQPZTORYS1Qlg.jpeg" /></figure><p>The overall structure of a Bitcoin block always includes the following elements:</p><ul><li><strong>Magic number</strong>: This 4-byte field always contains the value 0xD9B4BEF9, which indicates that the file format adheres to a data structure that corresponds to the Bitcoin network.</li><li><strong>Blocksize</strong>: This 4-byte field sets a cap on the amount of data that can be contained in a block. The Bitcoin block size is limited to one megabyte (MB).</li><li><strong>Block header</strong>: This 80-byte field consists of six individual components, discussed in more detail below.</li><li><strong>Transaction counter</strong>: This field can range in size from one to nine bytes and is a positive integer that represents the number of transactions contained in the Bitcoin block.</li><li><strong>Transactions</strong>: This variable size field contains the list of all transactions contained in the block and is typically filled with enough transactions to fill the 1MB Bitcoin block size limit.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*M7M2SlYxmF1cMUO29kXNXw.png" /><figcaption>Block in a blockchain</figcaption></figure><p>The block header and the transaction data represent the two main categories of data in any given block — though these two sections are further broken down into individual components.</p><blockquote><strong>The Block consists of a Block header containing metadata and Transaction stored in the block using Merkle Tree.</strong></blockquote><p>The block header contains 80 bytes of cryptographically verifiable information:</p><ul><li><strong>Version</strong>: This 4-byte field indicates the version number of the Bitcoin protocol being used, and typically contains the value “1.”</li><li><strong>hashPrevBlock</strong>: This 32-byte field contains a 256-bit hash of the previous block header.</li><li><strong>hashMerkleRoot</strong>: This 32-byte field contains a 256-bit hash of the root of the Merkle tree of all the transactions in the current block.</li><li><strong>Timestamp</strong>: This 4-byte field contains a timestamp of the current block that is used to situate it chronologically in the blockchain.</li><li><strong>Target Bits</strong>: This 4-byte field contains the target difficulty of the current Bitcoin block which determines how difficult the target hash will be to find. It regulates the speed at which new blocks are added to the blockchain and are adjusted roughly every 2016 block. Higher difficulty in generating the nonce represents a lower target value.</li></ul><blockquote>How this number 2016 came? As the average duration of mining 1 bitcoin is 10 minutes, the target difficulty gets regulated after every 2 weeks <br>( 2*7*24*60 minutes/10 minutes per block= 2016 blocks)</blockquote><ul><li><strong>Nonce</strong>: This 4-byte field contains a 32-bit number that a miner must alter in order to correctly solve the computational puzzle for the current block.</li></ul><p>A block hash is like a reference number for a block in the blockchain. This reference number needs to meet certain requirements, i.e., it needs to begin with a specific number of zeroes. Bitcoin miners perform a maddening number of hash functions with many different nonce values until a valid output is produced.</p><p>Bitcoin miners compete to solve a computationally-intensive Proof-of-Work (PoW) puzzle. The puzzle requires taking all of the network’s transactions as well as information from the previous block (i.e. its block header), and “hashing” them using the SHA-256 algorithm. The first miner to complete this puzzle is allowed to create a new block, and receives a reward of newly minted BTC in return.</p><blockquote>This reward is equal to the difference between the hashed value and the predetermined target hash.</blockquote><h3>Types Of Blockchain</h3><ul><li><strong>Public blockchain.</strong><br>A public, or permission-less, blockchain network is one where anyone can participate without restrictions. Most types of cryptocurrencies run on a public blockchain that is governed by rules or consensus algorithms. Examples of public blockchain architecture include bitcoin, Litecoin, and Ethereum.</li><li><strong>Permissioned or private blockchain</strong><br>A private, or permissioned, blockchain allows organizations to set controls on who can access blockchain data. Only users who are granted permissions can access specific sets of data. Oracle Blockchain Platform is a permissioned blockchain.</li><li><strong>Federated or consortium blockchain.</strong><br>A blockchain network where the consensus process (mining process) is closely controlled by a preselected set of nodes or by a preselected number of stakeholders. It combines the best features of both public and private blockchain. It is also heavily controlled and is best suited for enterprise blockchains.</li></ul><h3>Consensus Methods in Blockchain</h3><h4>A brief about the notable methods being used presently</h4><blockquote>Cryptocurrencies, blockchains, and distributed ledgers benefit from their use because the consensus mechanism replaces much slower human verifiers and auditing.</blockquote><p>In order to achieve distributed agreement about the ledger’s state among the nodes regarding a transaction’s validity and foolproof-ness, blockchain uses certain programs known as consensus.</p><p>For example, Bitcoin blockchain uses a mechanism called Proof-of-Work (PoW), which requires computational power to solve an encrypted puzzle, called the hash. By solving, what the miner actually does is find a suitable nonce that can be added to the hash of the most recent block to create a number equal to or lesser than the present target hash. After the hash is solved by one miner (or a group working together), Bitcoin’s PoW requires that every node on the network verifies the data that has been changed by checking:</p><ul><li>The data structure</li><li>The block header hash</li><li>The block timestamp</li><li>The block size</li><li>The first transaction</li></ul><p>It then completes a long transaction verification checklist. This verification takes much less time than the process of solving the hash, which is called mining, and is orders of magnitude less time-consuming than human verification.</p><h4>Proof of Work (PoW)</h4><p>The proof of work (PoW) is a common consensus algorithm used by the most popular cryptocurrency networks like Bitcoin and Litecoin. It requires a participant node to prove that the work done and submitted by them qualifies them to receive the right to add new transactions to the blockchain. However, this mechanism has received a lot of criticism lately due to high energy consumption and long processing times.</p><blockquote>Proof-of-Work (PoW) blockchains are among the first, yet still most secure decentralized systems out there.</blockquote><p>But Still, it is securing the world’s biggest cryptocurrency, Bitcoin (BTC), and its network, which makes PoW a fascinating feat of technology.</p><h4>Proof of Stake (PoS)</h4><p>The Proof of Stake (PoS) is another common consensus algorithm that evolved as a low-cost, low-energy consuming alternative to the PoW algorithm. It involves allocating responsibility in maintaining the public ledger to a participant node in proportion to the number of virtual currency tokens held. This is done by the coin owners who offer their coins as collateral — staking — for the chance to validate blocks and then become validators.</p><blockquote>To become a validator, a coin owner must “stake” a specific amount of coins. For instance, Ethereum requires 32 ETH to be staked before a user can become a validator. Blocks are validated by more than one validator, and when a specific number of the validators verify that the block is accurate, it is finalized and closed.</blockquote><p>PoS is designed to overcome the drawbacks of PoW- it improves the scalability of PoW, reduces network congestion and overcomes environmental sustainability concerns.</p><p>However, this has the drawback that it incentivizes hoarding instead of spending.</p><blockquote><em>The first cryptocurrency to adopt the PoS method was Peercoin.</em></blockquote><p>While PoW and PoS are by far the most prevalent in the domain of blockchain, there are other consensus algorithms like <strong>Proof of Capacity (PoC)</strong> which allow sharing of memory space of the contributing nodes on the blockchain network. The more memory or hard disk space a node has, the more rights it is granted for maintaining the public ledger. <strong>Proof of Activity (PoA)</strong>, used on the Decred blockchain, is a hybrid that makes use of aspects of both PoW and PoS. <strong>Proof of Burn (PoB)</strong> requires transactors to send small amounts of cryptocurrency to inaccessible wallet addresses, in effect “burning” them out of existence.</p><blockquote>Proof of Capacity(PoC) is like Proof of Stake(PoS), but in PoS preference of next validator is given to the node having a greater stake and in PoC, it’s given to the node having more memory/hard disk space.</blockquote><h3>Possible Weaknesses of Blockchain</h3><ul><li>V<strong>ery high energy consumption to solve the cryptographic challenge in order to add a new block to the blockchain.</strong> What crypto miners do, is take the hash of the most recent block’s header contents, add a random number (nonce), and hash it again. <strong>The goal of each miner is to get a hash value that’s less than or equal to a predefined target hash.</strong> In bitcoin, presently the 64-byte hash values start with 19 zeroes. The lesser the target value, the more difficult it is to find a suitable nonce (and ultimately, the block hash for a new valid block).<br>To find such a number from trillions of possibilities, special computer rigs are needed with Graphics Processing Units (GPUs) or even Application Specific Integrated Circuits (ASICs) to solve these computations. All of this requires <strong>initial investment of a lot of money in order to create the smallest of profits by mining</strong>, and therefore, cryptocurrency mining is just not for everyone.</li><li><strong>The 51% Attack </strong>is an attack on the blockchain orchestrated when a group of miners on the blockchain network control more than 50% of the network’s hash rate or computing power to prevent new transactions from gaining confirmations, or ability to invalidate transactions that introduce double spend. While it’s very difficult for an attacker to overtake majority of the honest nodes, it’s still considered a potential weakness.</li></ul><blockquote>Consider this, you have 1 BTC which you give to your friend Jack by signing and sending it to his wallet. Now you sign the same transaction again and send it to your another friend Paul. This is double spending.</blockquote><ul><li><strong>Double-spending</strong> is yet another problem with the current blockchain technology. While double spending is impossible with physical currency (if you buy a bottle of wine with money, then you can’t use the same currency note to get another bottle of whiskey. It’s just not possbile with fiat currencies). <br>For someone to double spend, <strong>a secret block has to be mined that outpaces the creation of the real blockchain</strong>. Theu would then need to introduce that chain to the network before it caught up and in this way, the person who did this can give themselves back any cryptocurrency they had spent and use it again.<br>To prevent double-spending the blockchain network deploys different consensus algorithms including Proof-of-Stake, Proof-of-Work, and so on. <strong>Double spending is only possible on networks with a vulnerability to the 51% attack.</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9df685b0174" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>