Lab - Simple Blockchain

docx

School

University of Pittsburgh *

*We aren’t endorsed by this school

Course

1242

Subject

Computer Science

Date

Apr 3, 2024

Type

docx

Pages

7

Uploaded by GeneralExplorationOwl33

Report
Scripting a Simple Blockchain in Python IMPORTANT NOTE: Python is very particular about spaces and indentations. Make sure you code matches EXACTLY or you will encounter errors. Before you begin, click Download to open these instructions in the desktop version of Microsoft Word . That way the indents will persist when you copy and paste the code below. Introduction In this lab, you will generate a simple blockchain. You will be given the Python commands and your goal is to document the code by describing what takes place in each step. What exactly is a blockchain? A Blockchain is a digital ledger in which transactions are recorded chronologically and publicly. In more general terms, it is a public database where new data are stored in a container called a block and are added to an immutable chain (hence blockchain) with data added in the past . In the case of Bitcoin and other cryptocurrencies, these data are groups of transactions. But the data can be of any type, such as smart contracts. Blockchain technology has given rise to new, fully digital currencies like Bitcoin and Litecoin that are not issued or managed by a central authority. This brings new freedom to individuals who believe that today’s banking systems are a scam or subject to failure. Blockchain has also revolutionized distributed computing in the form of technologies like Ethereum, which has introduced interesting concepts like smart contracts . In this lab, you will create a very simple blockchain and calculate the hash values for each block. The basic algorithm is as follows: 1. Identify and load prerequisites 2. Define the data in a block 3. Define the genesis block 4. Define subsequent blocks 5. Define a sample blockchain 6. Test the sample blockchain 7. Show more detail of each block Go to Google Colab and create a new Python script: Google Colab allows you to write an execute Python code in the cloud. Normally you would install the Python console on your local computer and work with local data, but for this exercise the cloud will work just fine.
1. Go to colab.google and create a New Notebook. Since this is likely the first time you have scripted something, we’ll start simple to make sure it works. 2. On line 1, type: print('Hello, world!') 3. Click the Run (play) button to the left of the first line of code. In a few moments, the words Hello, world! will appear below your code. 4. TAKE A SCREENSHOT (1) 5. Now we are ready to jump into the code! Click the + Code button to add a new code block below your script and continue below. Program a very simple blockchain: Now we are ready to do some scripting. In this lab, I will give you snippets of code to add to your script that follow the steps of the blockchain algorithm. You are responsible for making sure you and the next person understands what you did. Before each block of text, you will add a comment (starting with a # symbol) to explain in plain English what the script is doing.
Algorithm Step 1 – Identify and load prerequisites Before we begin, we will need a couple Python functions to define the datetime datatype and a hash calculator. Think of these as helper tools. 1. Copy and paste the following code into your Blockchain.py script after the previous code to define a block: from datetime import datetime import hashlib as hasher Algorithm Step 2 – Define the data a block We’ll start by first defining what our blocks will look like. In blockchain, each block is stored with a timestamp and, optionally, an index. Here, we’re going to store both. And to help ensure integrity throughout the blockchain, each block will have a self-identifying hash. Like Bitcoin, each block’s hash will be a cryptographic hash of the block’s index, timestamp, data, and the hash of the previous block’s hash. Oh, and the data can be anything you want. 2. Copy and paste the following code into your Blockchain.py script after the previous code to define a block: # class Block: def __init__(self, index, timestamp, data, previous_hash): self.index = index self.timestamp = timestamp self.data = data self.previous_hash = previous_hash self.hash = self.hash_block() def __str__(self): return 'Block #{}'.format(self.index) def hash_block(self): sha = hasher.sha256() seq = (str(x) for x in ( self.index, self.timestamp, self.data, self.previous_hash)) sha.update(''.join(seq).encode('utf-8')) return sha.hexdigest() The INIT function identifies the data in each block. The STR function labels the block. The hash block function joins all the block data and calculates the hash value. 3. Look for the # at the beginning of this block of code (right above class Block :) and write a comment describing what this function does. Use the # to start the comment. For example:
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
#This class defines the data to be included in a block and calculates the block’s hash value. Algorithm Step 3 – Define the genesis block Awesome! We have our block structure, but we’re creating a block chain . We need to start adding blocks to the actual chain. As I mentioned earlier, each block requires information from the previous block. But a question arises: how does the first block in the blockchain get there? Well, the first block, or genesis block, is a special block. In many cases, it’s added manually or has unique logic allowing it to be added. We’ll create a function that simply returns a genesis block to make things easy. This block is of index 0, and it has an arbitrary data value and an arbitrary value in the “previous hash” parameter. 4. Copy and paste the following code into your Blockchain.py script after the previous code to define a genesis block: # def make_genesis_block(): block = Block(index=0, timestamp=datetime.now(), data="Genesis Block", previous_hash="0") return block 5. Add a line before this block of code and write a comment describing what this function does. Use the # to start the comment. Algorithm Step 4 – Define subsequent blocks Now that we’re able to create a genesis block, we need a function that will generate succeeding blocks in the blockchain. This function will take the previous block in the chain as a parameter, create the data for the block to be generated, and return the new block with its appropriate data. When new blocks hash information from previous blocks, the integrity of the blockchain increases with each new block. If we didn’t do this, it would be easier for an outside party to “change the past” and replace our chain with an entirely new one of their own. This chain of hashes acts as cryptographic proof and helps ensure that once a block is added to the blockchain it cannot be replaced or removed. 6. Copy and paste the following code into your Blockchain.py script after the previous code to define a subsequent block: # def next_block(last_block, data=''): idx = last_block.index + 1 block = Block(index=idx, timestamp=datetime.now(), data='{}{}'.format(data, idx), previous_hash=last_block.hash)
return block 7. Add a line before this block of code and write a comment describing what this function does. Use the # to start the comment. 8. TAKE A SCREENSHOT (2) Step 5 – Define a sample blockchain That’s most of the hard work. Now, we can create our blockchain! In our case, the blockchain itself is a simple Python list. The first element of the list is the genesis block. And of course, we need to add the succeeding blocks. Because this is the tiniest blockchain, we’ll only add 20 new blocks. We can do this with a for loop. 9. Copy and paste the following code into your Blockchain.py script after the previous code to define a sample blockchain. # def sample_blockchain(): blockchain = [make_genesis_block()] prev_block = blockchain[0] num_of_blocks_to_add = 20 for i in range(0, num_of_blocks_to_add): block = next_block(prev_block, data= 'Smart contract data No. ') blockchain.append(block) prev_block = block print('{} added to blockchain'.format(block)) print('Hash: {}\n'.format(block.hash)) 10. Add a line before this block of code and write a comment describing what this function does. Use the # to start the comment. Algorithm Step 6 – Test the sample blockchain Now let’s test what we’ve made so far: 11. Copy and paste the following code into your Blockchain.py script after the previous code to create your sample blockchain: #This command generates a new blockchain sample_blockchain() 12. Go back to the sample blockchain definition code and change the number of blocks to add to any number between 50 and 100. 13. Click Run to execute your code. A list of all your blocks should appear with their corresponding hash (this is what the last print function in the sample blockchain definition did). 14. TAKE A SCREENSHOT (3)
Algorithm Step 7 – Show more detail about the blocks. We are interested in seeing the details of what is contained in each block, such as the previous hash, timestamp, and data. Go back to the code where you define the sample blockchain (def sample_blockchain()). 15. Add the following code between the last two print() commands and double-check your indents to make sure they’re in line . There should now be five total print commands. print('PrevHash: {}'.format(block.previous_hash)) print('Time: {}'.format(block.timestamp)) print('Data: {}'.format(block.data)) 16. Re-run your code. Your list should now have each block and a list of each block’s data. Does the previous hash match the hash from the previous block? 17. TAKE A SCREENSHOT (4) Now use some AI to document 18. Click the + Code button to create a new code block below your blockchain output. 19. Copy the following block of code into an AI chat bot (e.g., Colab AI, ChatGPT, Gemini, etc.) with the following prompt: Write comments to document the following code: from datetime import datetime import hashlib as hasher class Block: def __init__(self, index, timestamp, data, previous_hash): self.index = index self.timestamp = timestamp self.data = data self.previous_hash = previous_hash self.hash = self.hash_block() def __str__(self): return 'Block #{}'.format(self.index) def hash_block(self): sha = hasher.sha256() seq = (str(x) for x in ( self.index, self.timestamp, self.data, self.previous_hash)) sha.update(''.join(seq).encode('utf-8')) return sha.hexdigest() def make_genesis_block(): block = Block(index=0,
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
timestamp=datetime.now(), data="Genesis Block", previous_hash="0") return block def next_block(last_block, data=''): idx = last_block.index + 1 block = Block(index=idx, timestamp=datetime.now(), data='{}{}'.format(data, idx), previous_hash=last_block.hash) return block def sample_blockchain(): blockchain = [make_genesis_block()] prev_block = blockchain[0] num_of_blocks_to_add = 50 for i in range(0, num_of_blocks_to_add): block = next_block(prev_block, data= 'Smart contract data No. ') blockchain.append(block) prev_block = block print('{} added to blockchain'.format(block)) print('PrevHash: {}'.format(block.previous_hash)) print('Time: {}'.format(block.timestamp)) print('Data: {}'.format(block.data)) print('Hash: {}\n'.format(block.hash)) sample_blockchain() There we go! Our blockchain works. That is about all that this simple blockchain has to offer. It is missing some key functionality, but each block is dependent on the previous, so it creates a nice chain. END OF LAB Adapted from https://medium.com/crypto-currently/lets-build-the-tiniest-blockchain-e70965a248b