Block Chain Lab Manual
Block Chain Lab Manual
ENGINEERING 2024-2025
NAME OF STUDENT: Sarthak Mallick
1. Develop a Solidity-based marketplace where users can buy and sell digital goods.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Marketplace {
struct Item {
uint256 id;
string name;
address payable seller;
uint256 price;
address buyer;
bool isSold;
}
// Events
event ItemListed(uint256 id, string name, uint256 price, address seller);
event ItemPurchased(uint256 id, address buyer);
event Withdrawal(address seller, uint256 amount);
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Insurance {
// Structure for an insurance policy
struct Policy {
uint256 id;
address payable policyHolder;
uint256 premium;
uint256 coverageAmount;
bool isActive;
}
policyCount++;
policies[policyCount] = Policy({
id: policyCount,
policyHolder: payable(msg.sender),
premium: _premium,
coverageAmount: _coverageAmount,
isActive: true
});
claimCount++;
claims[claimCount] = Claim({
id: claimCount,
policyId: _policyId,
claimAmount: _claimAmount,
isSettled: false,
isApproved: false
});
claim.isSettled = true;
claim.isApproved = _approve;
if (_approve) {
Policy storage policy = policies[claim.policyId];
uint256 payoutAmount = claim.claimAmount;
policy.policyHolder.transfer(payoutAmount);
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Crowdfunding {
struct Campaign {
address payable creator;
uint256 goal;
uint256 deadline;
uint256 amountRaised;
bool isGoalMet;
mapping(address => uint256) contributions;
}
// Events
event CampaignCreated(uint256 id, address creator, uint256 goal, uint256 deadline);
event ContributionReceived(uint256 campaignId, address contributor, uint256 amount);
event GoalReached(uint256 campaignId, uint256 amountRaised);
event RefundIssued(uint256 campaignId, address contributor, uint256 amount);
// Contribute to a campaign
function contribute(uint256 _campaignId) public payable {
Campaign storage campaign = campaigns[_campaignId];
require(block.timestamp <= campaign.deadline, "Campaign is over");
require(msg.value > 0, "Contribution must be greater than zero");
campaign.contributions[msg.sender] += msg.value;
campaign.amountRaised += msg.value;
campaign.contributions[msg.sender] = 0;
payable(msg.sender).transfer(contribution);
OUTPUT
4. Build a contract for a lottery system where users can buy tickets and a winner is randomly
chosen.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Lottery {
address public manager;
address[] public players;
uint256 public ticketPrice;
bool public lotteryActive;
constructor() {
manager = msg.sender;
lotteryActive = false;
}
ticketPrice = _ticketPrice;
lotteryActive = true;
delete players; // Reset the players for a new round
emit LotteryStarted(ticketPrice);
}
players.push(msg.sender);
emit TicketPurchased(msg.sender, msg.value);
}
OUTPUT
5. Build a smart contract with a modifier to check if a function is called by the owner.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract OwnerCheck {
address public owner;
// Function to change the owner (only the current owner can do this)
function changeOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
}
OUTPUT
6. Create a smart contract for a simple auction where users can place bids.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleAuction {
address payable public auctionOwner;
uint256 public auctionEndTime;
address public highestBidder;
uint256 public highestBid;
bool public auctionEnded;
emit AuctionStarted(auctionEndTime);
}
// Place a bid
function placeBid() public payable auctionActive {
require(msg.value > highestBid, "There already is a higher bid");
// If there is a previous highest bidder, store their bid so they can withdraw it later
if (highestBid != 0) {
pendingReturns[highestBidder] += highestBid;
}
// Reset the pending return amount before transferring to avoid re-entrancy attacks
pendingReturns[msg.sender] = 0;
payable(msg.sender).transfer(amount);
// End the auction and transfer the highest bid to the auction owner
function endAuction() public onlyOwner {
require(block.timestamp >= auctionEndTime, "Auction has not ended yet"); require(!
auctionEnded, "Auction is already ended");
auctionEnded = true;
OUTPUT
7. Write a simple Solidity contract that stores a user's name
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract UserStorage {
string public userName;
OUTPUT
8. Implement Markel tree to encoded block chain data.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MerkleTree {
// State variable to store the Merkle root
bytes32 public merkleRoot;
// Function to create a Merkle root from an array of transactions (or data hashes)
function createMerkleRoot(bytes32[] memory _dataHashes) public returns (bytes32) {
require(_dataHashes.length > 0, "Data hashes array cannot be empty");
// If the array has only one element, return it as the Merkle root
if (_dataHashes.length == 1) {
merkleRoot = _dataHashes[0];
return merkleRoot;
}
// If there's an odd number of nodes, hash the last one with itself
if (length % 2 == 1) {
newLevel[newLength - 1] = hashPair(_dataHashes[length - 1], _dataHashes[length - 1]);
}
// Return whether the recalculated root matches the stored Merkle root
return hash == root;
}
}
OUTPUT
9. How to Create a Consecutive Block
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract ConsecutiveBlocks {
struct Block {
uint256 blockNumber;
bytes32 prevHash;
bytes32 blockHash;
uint256 timestamp;
string data; // This represents the data or transactions stored in the block
}
// Calculate the new block's hash based on the previous block's hash and new data
bytes32 newBlockHash = keccak256(abi.encodePacked(prevBlock.blockHash, _data,
block.timestamp));
OUTPUT
10. Write a program in Solidity Language.
OUTPUT
11. Implementation of a blockchain in C++ - Peer-to-Peer network, SHA-256.
#include <iostream>
#include <sstream>
#include <vector>
#include <ctime>
#include <string>
#include <openssl/sha.h> // SHA-256 library from OpenSSL
std::stringstream ss;
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
ss << std::hex << (int)hash[i];
}
return ss.str();
}
private:
std::vector<Block> chain; // Vector to store the blockchain
};
int main() {
// Create a new blockchain
Blockchain myBlockchain;
return 0;
}
12. Implement Diffie-Hellman Algorithm in C++.
#include <iostream>
#include <cmath> // For pow
#include <cstdlib> // For rand()
#include <ctime> // For srand()
int main() {
// 1. Publicly agreed values (prime p and base g)
long long p = 23; // A prime number
long long g = 5; // A primitive root modulo p
std::cout << "Publicly shared prime number (p): " << p << std::endl;
std::cout << "Publicly shared base (g): " << g << std::endl;
std::cout << "Party 1's secret key (a): " << a << std::endl;
std::cout << "Party 2's secret key (b): " << b << std::endl;
std::cout << "Party 1's public key (A): " << A << std::endl;
std::cout << "Party 2's public key (B): " << B << std::endl;
std::cout << "Shared secret calculated by Party 1: " << sharedSecret1 << std::endl;
std::cout << "Shared secret calculated by Party 2: " << sharedSecret2 << std::endl;
if (sharedSecret1 == sharedSecret2) {
std::cout << "Success! Both parties have the same shared secret: " << sharedSecret1 <<
std::endl;
} else {
std::cout << "Error! The shared secrets do not match." << std::endl;
}
return 0;
}
OUTPUT
13. Using RSA algorithm encrypt a text data and decrypt the same.
#include <iostream>
#include <cmath> // For pow()
#include <cstdlib> // For rand() and srand()
#include <ctime> // For time()
int main() {
// Step 1: Key generation
srand(time(0));
// n = p * q
long long n = p * q;
// Public key exponent e (choose e such that 1 < e < phi(n) and gcd(e, phi(n)) == 1)
int e = 17; // Commonly used value for e
std::cout << "Public key (e, n): (" << e << ", " << n << ")" << std::endl;
std::cout << "Private key (d, n): (" << d << ", " << n << ")" << std::endl;
// Step 2: Encryption
std::string message;
std::cout << "Enter the message to encrypt (as a number): ";
std::cin >> message;
// Step 3: Decryption
long long decryptedMessage = decrypt(ciphertext, d, n); // Decrypt the message
std::cout << "Decrypted message: " << decryptedMessage << std::endl;
return 0;
}
OUTPUT
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SupplyChain {
struct Product {
uint productId;
string name;
string manufacturer;
string currentLocation;
Status status;
address owner;
}
// State variables
mapping(uint => Product) public products;
uint public productCounter = 0;
// Events to log significant changes in product status
event ProductManufactured(uint productId, string name, string manufacturer);
event ProductShipped(uint productId, string location);
event ProductInTransit(uint productId, string location);
event ProductDelivered(uint productId, string location);
// Modifier to check that only the owner of the product can perform certain actions
modifier onlyOwner(uint _productId) {
require(products[_productId].owner == msg.sender, "Not the owner of the product");
_;
}
// Emit event
emit ProductManufactured(productCounter, _name, _manufacturer);
}
products[_productId].currentLocation = _newLocation;
products[_productId].status = Status.Shipped;
// Emit event
emit ProductShipped(_productId, _newLocation);
}
products[_productId].currentLocation = _location;
products[_productId].status = Status.InTransit;
// Emit event
emit ProductInTransit(_productId, _location);
}
products[_productId].currentLocation = _location;
products[_productId].status = Status.Delivered;
// Emit event
emit ProductDelivered(_productId, _location);
}
OUTPUT
15. Implementation of Healthcare solutions through blockchain.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Healthcare {
// State variables
mapping(address => Patient) public patients;
mapping(uint => address) public
patientById; uint public patientCount = 0;
uint public recordCount = 0;
patientCount++;
patients);
patientById[patientCount] = msg.sender;
}
// Function to authorize a doctor to access the patient's medical records
function authorizeDoctor(uint _patientId, address _doctor) public {
require(patientById[_patientId] == msg.sender, "Only the patient can authorize");
patients[msg.sender].authorizedDoctors[_doctor] = true;
}
recordCount++;
MedicalRecord memory newRecord = MedicalRecord(recordCount, _diagnosis, _treatment,
block.timestamp, msg.sender);
patients[patientById[_patientId]].medicalRecords.push(newRecord);