BCT Unit-2
BCT Unit-2
BCT Unit-2
1.Public Blockchain
Public Blockchain, as the name suggests, is public. A public blockchain is completely decentralized and does not have
a single entity that controls the network.
In this type of Blockchain, anyone with an internet connection can join the network and participate in reading, writing,
or auditing within the Blockchain. Hence anyone can review anything at a given point of time on a public blockchain
as long as they are connected to the network. Any node can also choose to leave the network and rejoin and still get
the chain of data, since the time they left.
Public blockchain can also be called Permissionless Blockchain because it allows any user to create a personal address
and join the blockchain network, i.e., become a ‘node’ of the network. Also, the public blockchains do not restrict the
rights of the nodes on the blockchain network.
Another critical point to remember is that these types of Blockchain are more transparent and secure than
permissioned blockchains because there are many nodes to validate transactions. Thus, it would be difficult for bad
actors to collude on the network. Also, it is not possible to modify or alter the data once it has been validated on the
Blockchain.
(i) To be part of a public blockchain, one needs to download the code without needing any permission from anyone
and start running a public node on their local device. Once this is done, he can then validate transactions in the
network, thus participating in the consensus process — the process for determining what blocks can be added to the
Blockchain.
(ii) Anyone in the world can send transactions through the network and can expect them to be included in the
Blockchain if they are valid.
(iii) In a public blockchain, anyone in the world can access and read Blockchain transactions using a block explorer,
which is a program or a website that allows a user to search and navigate the blocks of a Blockchain, their contents,
and relevant details.
(iv) Speed of transactions in the public blockchain is slower than in the case of private blockchain.
Examples: To date, public blockchains are primarily used for exchanging and mining cryptocurrency. A few examples
of cryptocurrency public blockchain platforms include Bitcoin, Ethereum, Litecoin, etc. Ethereum is actually the most
popular public blockchain at present.
Limitations:
One may face some challenges while using a public blockchain. For instance,
(i) Difficult Fraud Tracking: The transactions on the public blockchain can be done anonymously or pseudo
anonymously and are not tied directly to the real identity of the user. These transactions are linked to an account
address comprised solely of numbers and letters. With no real-world identity attached to this address, it is impossible
to track the transaction’s originator. It raises a very critical concern, what if activities like fraud, hacking, or money
laundering take place in this type of Blockchain. How will the guilty party or person be tracked and punished?
(ii) Lack of governance and regulations: The public blockchain being completely open and decentralized makes it
susceptible to a lack of proper regulation and governance by an authorized body. Thus, there is no safe upgrade path
for any protocols, and there is no one who can be held responsible for setting and maintaining the network standards.
It is definitely good to keep the development of Blockchain technology as decentralized as possible; however, we still
need some organization that can look after its features, upgrades, and code of conduct. For instance, if a developer
designs a new standard or protocol but gets busy and forgets to respond, then the progress on that protocol halts
regardless of how valuable that protocol is for everybody. You cannot hold anyone responsible for maintaining the
network standard, thus making the entire system dicey and skeptical. Therefore there is a need for leadership that
needs to look after all these aspects. Additionally, the public blockchains are not suitable for use in any internal system
and for projects that have strict criteria to follow.
(iii) Slow speed and massive consumption of energy: Another critical area of concern while using public blockchain
technology is its speed and the energy it consumes. Public blockchains are slow because it takes time for the network
to reach a consensus. For instance, public blockchains like bitcoin manage to process seven transactions per second
compared to Visa, which can do 1700 transactions per second. Also, public blockchains like Bitcoin rely on a
consensus mechanism- Proof of Work to validate transactions and add new blocks of transactions to the network. In
this process, a lot of energy gets consumed while solving complex mathematical problems to validate the transactions
and create a block. As per the studies published in June 2017, each bitcoin transaction consumes 80,000 times more
electricity than a Visa credit card transaction. But various other consensus mechanisms have been proposed, like Proof
of Stake, which uses far less electricity.
2.Private Blockchain
The second type of blockchain is Private Blockchain, where the network participants have control over who can join
the network and who can participate in the consensus process. This is in contrast to public blockchain which is open
for anyone to participate in the network.
In a private blockchain, access to the blockchain is limited to selected participants for example, those participants
within an organization. Access controls in the network will vary for every participant, and the Regulatory Authority or
central organization would decide on various activities inside the network starting from joining the network until
executing any of the functionalities in this closed network.
In this platform, the digital identities of the participants need to be managed and monitored by the Regulatory
Authority. Therefore, it is not necessarily decentralized even among its members but is a centralized system that uses
distributed ledger technology.
However, private blockchain offers several advantages over public blockchain:
(i) In the case of the public blockchain, the credentials of nodes are not known; therefore, nobody can decipher who
these validators are, which increases the risk of malicious activities. But in the case of a private blockchain, the
credentials of participating nodes are present on the blockchain; therefore, it is much easier to track where the fraud
happened.
(ii) Additionally, since private blockchains are generally smaller than public blockchains and have far fewer
participants, therefore it takes less time for the network to reach a consensus. As a result, more transactions can take
place. Private blockchains can process thousands of transactions per second. Also, they take up a lot less energy and
power to validate transactions. On the contrary public blockchain networks, which usually have thousands of
computers to verify transactions, consume tons of energy.
(iii) Private blockchain provides exciting opportunities for businesses to leverage trustless and transparent activities
for internal and business-to-business use cases. For instance, banks and financial institutions can use private
blockchain as they are regulated entities that cannot operate over open protocols or public blockchain without
performing due diligence of the parties involved in the transaction. Additionally, with the advent of smart contracts,
this technology could eventually replace many centralized businesses.
Limitations:
There are certain challenges associated with the private blockchain. For instance,
(i) Centralization of private blockchain is one of its biggest disadvantages. Blockchain was built to avoid
centralization, and private blockchain inherently becomes centralized due to its private network.
(ii) The second disadvantage of using private blockchain is trust. The credibility of a private blockchain network relies
on the credibility of the authorized nodes. They need to be trustworthy as they are verifying and validating
transactions.
(iii) Security is another concern while using a private blockchain. With fewer nodes, it is easier for malicious hackers
to gain control of the network. Thus, compared to the public blockchain, a private blockchain is far more at risk of
being hacked or having data manipulated.
• Like a consortium blockchain, a hybrid blockchain has the privacy benefits of a permissioned blockchain.
• But, unlike a consortium blockchain with multiple participants collectively helping to maintain the network, a
hybrid blockchain can have a single entity network administrator.
Mining Pools:
The miner who discovers a solution to the puzzle first receives the mining rewards, and the probability that a
participant will be the one to discover the solution is equal to the proportion of the total mining power on the network.
Participants with a small percentage of the mining power stand a very small chance of discovering the next block on
their own. For instance, a mining card that one could purchase for a couple of thousand dollars would represent less
than 0.001% of the network’s mining power. With such a small chance at finding the next block, it could be a long
time before that miner finds a block, and the difficulty going up makes things even worse. The miner may never
recoup their investment. The answer to this problem is mining pools.
To find such a hash value, we have to get a fast mining rig with high computation power, or we have to join a mining
pool — a group of coin miners who combine their computing power and split the mined Bitcoin. A disproportionately
large number of blocks are mined by pools rather than by individual miners and the reward will be shared by all the
miners involved in the pool.
1.Smart Contracts:
Smart contracts are self-executing contracts with the terms of the agreement between buyer and seller being directly
written into lines of code. Smart contracts are a key innovation in blockchain technology, enabling the automation of
complex processes. Smart contracts have the potential to transform many industries, including financial services, real
estate, and supply chain management.
2.Scalability
• Scalability refers to the ability of a system to handle increasing amounts of work without impacting
performance.
• Scalability is a significant challenge for blockchain technology, which currently struggles with slow
transaction processing and high fees.
• Several solutions are being developed to address scalability, including sharding, layer 2 solutions, and
blockchain interoperability.
3.Interoperability
• Interoperability refers to the ability of different blockchain networks to communicate and work together
seamlessly.
• Interoperability is critical for the widespread adoption of blockchain technology.
• Several projects are underway to develop interoperability solutions, including Polkadot, Cosmos, and Ark.
4.Privacy
• Privacy is a critical concern for many blockchain use cases, particularly those involving sensitive data.
• Several privacy-focused blockchain projects, such as Monero and Zcash, have emerged to address this issue.
• Privacy-enhancing technologies, such as zero-knowledge proofs, are also being developed to improve privacy
on public blockchains.
5.Governance
• Governance refers to the systems and processes in place to manage and regulate a blockchain network.
• Effective governance is essential for the ongoing success of blockchain projects.
• Several governance models exist, including on-chain governance, off-chain governance, and hybrid models.
6.Sustainability:
• Sustainability refers to the ability of a blockchain network to operate over the long term.
• Blockchain networks require significant computing power and energy consumption, which can be a barrier to
sustainability.
• Several projects are exploring alternative consensus mechanisms, such as proof of stake, to improve
sustainability.
Some of the use cases are
1. Financial Services
2. Supply chain Management
3. Health Care
4. Identity Management
5. Voting Systems
1.Financial Services
• Blockchain technology has the potential to transform the financial services industry by enabling faster, more
secure, and more efficient transactions.
• Use cases for blockchain in financial services include cross-border payments, trade finance, and digital
identity.
• Several blockchain projects are focused on financial services, including Ripple, Stellar, and Corda.
2.Supply Chain Management
• Blockchain technology can improve supply chain management by increasing transparency and traceability,
reducing fraud and counterfeiting, and improving efficiency.
• Use cases for blockchain in supply chain management include tracking the origin and movement of goods,
verifying product authenticity, and reducing waste.
• Several blockchain projects are focused on supply chain management, including VeChain, Waltonchain, and
Ambrosus.
3.Healthcare
• Blockchain technology has the potential to transform the healthcare industry by improving patient data
management, reducing fraud, and increasing transparency.
• Use cases for blockchain in healthcare include patient data management, clinical trials, and drug supply chain
management.
• Several blockchain projects are focused on healthcare, including MedRec, Medicalchain, and FarmaTrust.
4.Identity Management
• Blockchain technology can improve identity management by reducing fraud, increasing security, and
improving privacy.
• Use cases for blockchain in identity management include digital identity, KYC/ AML compliance, and secure
authentication.
• Several blockchain projects are focused on identity management, including Civic, uPort, and SelfKey.
5.Voting Systems
• Blockchain technology can improve voting systems by increasing transparency, reducing fraud, and
improving accuracy.
• Use cases for blockchain in voting systems include online voting, secure and anonymous voting, and election
auditing.
• Several blockchain projects are focused on voting systems, including Follow My Vote, Agora, and Horizon
State.
2.4: Digital Identity Verification
Identity verification is the concept of proving that an identity is a real one. It’s about proving a person is who
they say they are and that it’s a real person behind the actions. In most places around the world, identity
verification uses data such as name, DOB and address to prove an identity is real.
Digital identity verification is the process of proving that an identity is real without ever having to meet
someone face-to-face. It confirms that a person is who they say they are and that the personal information
they have provided isn’t fake or stolen (identity fraud). Digital identity verification also helps ensure that it
is actually a person behind the screen and not fake identities — now much more easily created with the rise
of criminal technology.
Digital Identity Verification works by comparing the data that a person sends ( e.g., document such as a
passport or biometric data such as a picture of their face ) against a verified data set which can include
government records, credit references or even mobile data.
Digital identity verification speeds up the verification process, which is necessary for the fast pace of a
digital world in which the majority of our transactions take place online.
Customers nowadays expect and demand to be able to sign up for a product or service quickly and start
using it immediately. Delivering a smooth customer experience, however, has to be balanced with a secure
identity verification process that ensures a business is safeguarded and individuals are protected from
identity fraud. With so much of life now online, there is more data than ever before that can be misused if
not protected, so the identity verification process is crucial.
There are six common ways to verify someone’s identity online.
1. Biometric verification: This method uses unique biological traits of an individual, such as your
fingerprint, iris or face recognition. Certain smartphones use fingerprint or face recognition to verify
your identity.
2. Document verification: This method uses government-issued identification documents. These can be
passports, driver’s licenses or national identity cards.
3. Knowledge-based verification: By requesting information that only the person should know, such as
their mother’s maiden name, or addresses where they’ve lived, the system verifies a person’s identity.
4. Device authentication: This method involves verifying the device, such as a phone or computer, used
by the individual. Verification comes through the IP address or browser fingerprint.
5. Email verification: This one is prevalent due to emails’ broad acceptance across users. A system uses
personal credentials to set up the email account to verify the user for email verification.
6. Phone verification: Another typical verification process usually occurs in three steps. The customer
creates an account with their phone number and then the user receives a one-time passcode via an
SMS or phone call. Finally, the user submits the one-time passcode to obtain verification.
Digital Identity Verification can be done by Blockchain where we can control our identity without
depending on any central authority like UIDAI (Universal IDentification Authority of India) assigns a 12
bit unique number called Aadhar and controls one’s identity.
OneName, BitID, and BitHandle are examples of blockchain-based digital identity services.
OneName is decentralized digital identity verification system that runs on Namecoin protocol. OneName
helps solve the problem that 27- through 34-character Bitcoin addresses are cumbersome for human users.
Some other Bitcoin wallet services and exchanges, like Coinbase, have allowed Bitcoin to be sent to email
addresses for some time. The OneName service is a more secure solution.
With OneName, users can set up a more practical name (like a social media handle) to use for Bitcoin
transactions.
After a user is registered with OneName, performing bitcoin transactions is as easy as adding a plus sign to
your username (for example, +DeMirage99). OneName is an open source protocol built on the Namecoin
protocol that allows digital identity verification, rather than allowing centralized social media sites like
Facebook, LinkedIn, and Twitter to be the de facto identity verification platform, given that many websites
have opted to authenticate users with social media APIs.
BitID protocol allows users to login to websites with their Bitcoin address. Instead of “Login with
Facebook,” you can “Connect with Bitcoin” (your Bitcoin address). BitID is a decentralized authentication
protocol that takes advantage of Bitcoin wallets as a form of identification and QR codes for service or
platform access points.
BitID takes an already-verified identity that has been created by one online service, like a bank or bitcoin
exchange, and creates an ‘identity token’.
That token consists of two things: an actual Bitcoin address derived from the domain where the identity was
created, and eight bytes of code to signify what ID documents were used to verify it. The token is then
recorded on the blockchain.
This identity token can then be used by any other service using the BitID protocol. Anyone who wants to
verify that identity — another service or an individual — can simply scan a QR code to check that the
identity token exists.
Unlike other similar services, no detailed or identifying information is stored on the blockchain. BitID does
not require any permission to use, is completely decentralized, and protects users’ privacy from data mining
and theft.
Another proposed digital identity verification business is Bithandle, which was developed as a hackathon
project.
Bithandle offers short-handle registration, verification,and ecommerce service. As with Onename and BitID,
users can register an easy-to use handle — for instance, “Coinmaster” — that is linked to a wallet address
via a public or private real-life identity check and a Bitcoin blockchain transaction.
The service offers ongoing real-time digital identity verification and one-click auto-enabled ecommerce per
“Login with Bitcoin” website access.
An obvious problem with the mainstream adoption of Bitcoin is the unwieldy 32-character Bitcoin address,
or QR code, needed to send and receive funds.
Instead, Bithandle gives users the ability to link a short handle to a Bitcoin address, which is confirmed
initially with real-life identity and looked up in the blockchain on demand at any future moment.
Specifically, how Bithandle works is that in the digital identity registration process, participants register a
Bitcoin username, an easy-to-use handle that can then be used to “Login with Bitcoin” to websites. As
mentioned, this is similar to the ability to access websites by “Login with Facebook” or “Login with
Twitter” but automatically connects to a user’s Bitcoin address for proof of identity. When a user sets up a
Bithandle, his real-life identity is confirmed with Facebook, Twitter, LinkedIn, or other services, and this can
be posted publicly (like OneName) or not (as OneName does not allow), with the user’s Bithandle.
Later, for real-time digital identity verification, “Logging in with Bitcoin” means that a Bithandle is already
connected to a Bitcoin address, which securely facilitates ecommerce without the user having to register an
account and provide personal identity and financial details.
Bithandle thus helps streamline user interactions with websites in several ways.
1. First, websites do not have to maintain user account registries (“honeypot” risks for hacking).
2. Second, every user “Logging in with Bitcoin” is automatically enabled for one-click ecommerce
purchases.
3. Third, the Bithandle service can provide real-time blockchain lookups to confirm user digital identity
at any future time on demand — for example, to reauthorize a user for subsequent purchases.
Attestation Services:
Attestation services (declaring something to be true, such as asset ownership) are referred to as digital art. Attestation
services relies on the blockchain functionality of hashing and timestamping.
Proof of Existence:
One of the first services to offer blockchain attestation is Proof of Existence.
Proof of Existence demonstrates document ownership without revealing the information it contains, and it provides
proof that a document was authored at a particular time. With this tool, the blockchain can be used to prove the
existence and exact contents of a document or other digital asset at a certain time.
Attorneys, clients, and public administrators could use the Proof of Existence blockchain functionality to prove the
existence of many documents including wills, deeds, powers of attorney, health caredirectives, promissory notes, the
satisfaction of a promissory note, and so on without disclosing the contents of the document.
With the blockchain timestamp feature, users can prove that a document (like a will) they will be presenting to a court
in the future is the same unaltered document that was presented to the blockchain at a prior point in time.
Benefits:
1.Original documents are not stored on the blockchain, just their hash is stored, which is accessible by private key.
2. Whenever a proof of existence needs to be confirmed, the hash does not need to (and cannot) translate back into the
document. The document can be verified as unchanged, if the recomputed hash is the same as the original hash
registered in the blockchain.
Limitations:
There are some limitations to hashing-plus-timestamping blockchain attestation services.
1. a blockchain is not required for timestamping, because other third-party services provide this for free, whereas a
small transaction fee (to compensate miners) is required to post a digital asset attestation to the blockchain.
2. blockchain transaction confirmations are not immediate; the time the document was added to the blockchain is
recorded, not when the document was submitted.
3. timestamping does not prove ownership.
4. the hash might be less secure when you’re hashing very large documents (an 8-GB genome file, for example)
compared to small documents (a standard IOU contract)
Virtual Notary:
Virtual Notary is another project that similarly conceptualizes the need and fulfillment of blockchain attestation
services.
Like Proof of Existence, Virtual Notary does not store files but instead provides a certificate that attests to the file’s
contents at the moment of submission.
The service provides a certificate virtual notary-type service for many different “file types” such as documents, web
pages, Twitter feeds, stock prices, exchange rates, weather conditions, DNS entries, emailaddress verifications,
university affiliations, real estate values, statements and contracts,and random-number drawing.
Files can be in any format, including Microsoft Word, PDF, JPG, PNG, TXT, and PPT (Microsoft PowerPoint). The
site generates a certificate that can be downloaded from the site, and also offers the other side of the service —
examining existing certificates.
Virtual Notary’s aim is to provide a digital, neutral, dispassionate witness for recording online facts and conveying
them to third parties in a trustworthy manner.
Two other blockchain timestamp projects are Bitnotar and Chronobit. Two other virtual notary projects are Blocksign
and btcluck.
A similar blockchain-based project for contract signing is Pavilion.io, which provides the service much cheaper than
Adobe EchoSign or DocuSign; contracts are free to send and only one mBTC to sign.
Monegraph:
One digital-art protection project built and intended as a proof of concept using the blockchain ledger Bitcoin is
Monegraph,
Using this (currently free) application, individuals can facilitate the monetization of their online graphics — digital
media they have already created and posted on the Web — by registering their assets. Just as Bitcoin verifies currency
ownership, Monegraph verifies property ownership;
This an example of the smart property application of the blockchain. Monegraph could be a complementary service or
feature for stock photo image and graphic repository websites like Shutterstock or Getty Images, possibly adding
future functionality related to image use enforcement and tracking.
Working of Monegraph:
Monegraph works in a two-step process using Twitter, Namecoin, and Monegraph. Namecoin is used because it is an
altcoin that can be used to verify DNS registrations in an automated, decentralized way; any similar DNS confirmation
service could be used.
1. To stake the claim, the user goes to http://www.monegraph.com/, gives it permission to sign into Twitter account
(via the standardized Twitter API OAuth token),
2. supply the URL of the graphic, upon which Monegraph automatically tweets a link to that image in the correct
format.
3. To record the title, after Monegraph tweets the link to the image, it provides a block of code for the user to copy and
paste into the Namecoin client.
4. The user initiates a new transaction in the Namecoin wallet and adds the block of code as the key and value in the
Namecoin transaction (you can see the transaction here: http://bit.ly/monegraph_verification).
5. Only one copy of a digital image can ever have a valid Monegraph signature. Monegraph images are just ordinary
image files, so they can be duplicated and distributed like any other images, but only the original file will pass
validation against the Monegraph system.
Ascribe:
A related digital art and copyright protection project is Ascribe, which is aimed at providing an underlying
infrastructure for IP registry.
The company is building an “ownership layer” for digital property in the form of a service to register and transfer
copyright. Although existing copyright law offers creators protection against infringement and the right to
commercialize, there is no simple, global interface to register, license, and transfer copyright.
Working of Ascribe:
1. The Ascribe service registers a digital work with the service hashes and timestamping it onto the blockchain. An
earlier step in the registration process uses machine learning to detect and resolve any prior-art challenges.
2. Ownership rights can then be transferred, which enables secondary markets for digital IP.
The service handles digital fine art, photos, logos, music, books, blog posts, tweets, 3D CAD files, and more. Users
need no prior knowledge of the intricacies of the blockchain, copyright law, or machine learning to benefit from the
service.
The bulk of Ascribe’s users are marketplaces and white-label web services that use Ascribe in the background, though
individual users can use the site directly, as well.
Click on Open Chrome Web Store. In search the store type metamask wallet and click on it. The following will get
displayed.
Now agree the terms and click on create a new wallet, and then I agree.
then it will reveal and when you click on next, it will ask to confirm recovery phrase
Smart contracts are the self-executing programs that are stored on Blockchain and run when predefined conditions are
met.
Smart contracts automatically execute transactions if certain conditions are met without requiring the help of a third
party to manage or approve the transaction.
For example, there is a deal that is made with two friends Alice and Bob. Alice lend 1000rs from Bob and has
promised to return in the next month. They have created a smart contract to automate the return of the payment.
So, the next month, 1000rs will be automatically get deducted from the Alice account and it will be paid to Bob. None
of them have to interfere in the returning process. It will be done automatically.
Let us consider another scenario, in which Dave is the owner of the car and he wants to sell it. So, he creates a smart
contract. With his private key, he signs and deploy it in the network which is broadcasted to every peer in the network.
Then this car along with the key will be put in the smart garage. The details will be shared with the network, where
every peer in the network will know that the owner is Dave.
Now Claire login to the system with her private key. She accesses the smart contract to pay the money. Now the
money will be received by the signified person of the contract, the owner name will be changed from Dave to Claire
and is broadcasted to the network, so that evry node will know the current owner is Claire.
Softwares to be installed:
2. Add chrome extension Metamask wallet — It is a free and secure browser extension that allows web applications to read
and interact with the ethereum blockchain.
3. Install node.js (LTS version) — node.js is javascript but on server side. It is used as development tool for blockchain.
When you install node.js, it comes with npm (node package manager) which allows you to easily install tool frameworks
and libraries from the command line. Go to run->cmd->node -v displays node.js version
4. Install Truffle — Truffle is a framework for writing smart contract, tests them and deploy them. It mainly target the
solidity programming language which is the most popular programming language for smart contract. Truffle is mostly
used for the ethereum blockchain. Truffle has a built-in compiler for solidity and also has a built-in development
blockchain called Ganache.
$truffle version
5. Install Ganache — Click on QuickStart Ethereum (Launching Blockchain network). If you save this random name will
be generated for workspace rather than Quickstart.
6.
This is test network. Check the port in RPC Server configuration., which is usually 7545.
Gas will be calculated based on transaction request. Based on GAs, transaction fee will be charged. In real-time scenario,
it might take 15–20 min for mining process.
By clicking on the blocks, we can see that there is block0 which is called genesis block and it is empty because of no
transactions made. By clicking on block 0, we can see a unique hash value.
To connect with full node which is Blockchain server, we need a half node called cryptowallet.
Once metamask wallet is created, click on extensions symbol on top right corner and pin metamask.
click on it to open. Once opened, click on down arrow symbol beside ethereum mainnet.
Import an account from Ganache and make transactions between Account1 and Account2:
Now click on send to make transactions and then transfer between my accounts
click on Account1
We can see the change here, 10ETH in Account1 and remaining amount in Account2. In account2 it is 89.99… rather
than being 90, because a fraction of amount will be deducted for miner fee.
Now goto ganache and click on Blocks on top row. Now you can see that Block 1 has been added tothe blockchain
File Explorer — This is an option available on Remix IDE to handle various files associated to a Smart Contract.
When accessed for the first time, the IDE will pre-generate files and directories.
Step1:
To create a new Solidity file, Right-click the “contracts” directory and click on “New File”. Then, enter the filename,
say “demo.sol”.
Step2: Writing the Smart Contract
//SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
contract demo
{
string _msg; //state variable
//reading data
function takeInput(string memory a) public
{
_msg=a;
}
//displaying data
function giveOutput() public view returns(string memory)
{
return (_msg);
}
}
SPDX-License-Identifier is a license Identifier syntax. It is the essential statement in any solidity smart contract because
without it, smart contract will likely throw an error.
//SPDX-License-Identifier: MIT
In Solidity, we need to declare the language version to be used for the compiler. This can be done by using
the pragma keyword.
This line of code tells the compiler to use solidity version 0.8.18. We can also input a range of versions to be used.
This will tell the compiler to use version 0.4.0 as the minimum and 0.9.0 as the maximum.
Defining Contract
Defining a contract in Solidity is similar to defining a class in other programming languages. To define a contract we
can use the contract keyword followed by the name of our contract.
Let’s add variables inside our contract. Solidity’s Data Types can be found here. Here, we are using string to store the
message in the Smart Contract.
To declare a variable in Solidity, we first write the data type and then the variable name. Optionally, we can add an
access modifier such as private and public before the variable name.
Create a function
To create a function, the structure of functions in solidity is
When a compilation for a Solidity file succeeds, Remix creates three JSON files for each compiled contract.
Then we can click on the Ethereum logo to view the Deploy and Run Transactions Tab. In this tab, we can choose the
environment where our smart contract will be deployed, Use the generated accounts which contain test Ethers, Set the
gas limit for transactions, Set the amount of ether to be transferred for the transaction, Set the contract to be used, and
then click on Deploy button.
After the contract is deployed. We can interact with the contract in the Deployed Contracts Section.
Now enter a input string and click on takeInput button. And then click on giveOutput button to see the output.
2.7: Blockchain Environment- Migrate a smart contract into Ganache using Truffle
Build a smart contract
Step 1: With Ganache running behind, open new terminal, and run the commands below:
$ cd Desktop
$ mkdir DemoSmartContract
$ cd DemoSmartContract
$ truffle init
1. /contracts: store original codes of the smart contract. We will place our demo.sol file here.
2. /migrations: deploy the smart contract in the “contracts” folder.
3. /test: test codes for your smart contract, support both JavaScript and Solidity.
4. truffle-config.js: configuration document for windows user.
Oen VS Code editor and open folder on desktop with name “DemoSmartContract”.
//SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
contract demo
{
string _msg; //state variable
//reading data
function takeInput(string memory a) public
{
_msg=a;
}
//displaying data
function giveOutput() public view returns(string memory)
{
return (_msg);
}
}
$ truffle compile
This compiles the original code into Ethereum bytecode. If everything goes well, it will create .json file
under build/contracts folder. This json document is called as “artifact”. It contains abi (application byte code) which is
used to deploy smart contract — can see in line no.3. We can also see byte code and deployed byte code at lines 33–34.
$ truffle migrate
While migrating using truffle on Ganache, a block will be created.
Before migrating, only block0 exists in Ganache. After migration, block1 is created.
On clicking transaction
Block will be holding tranction data which is in encrypted form. To connect with contract, we need and contract
address.