Students can build a tiny, entirely offline blockchain model in Python to learn hashing, linked records, tamper detection and testing without using Bitcoin, cryptocurrency exchanges, real wallet keys or money. The project needs only Python’s standard library, fictional classroom points and an adult-approved local computer. It demonstrates how a change to an earlier record can break a later cryptographic link—and also reveals why a simple hash chain is not a secure public blockchain.
For Singapore parents and teachers, the learning objective is not to create a coin or prepare children to trade. It is to improve structured reasoning, programming, Mathematics, cybersecurity awareness and evidence checking. The National Institute of Standards and Technology describes blockchains as distributed, tamper-evident ledgers; Bitcoin adds transaction validation, digital signatures, proof-of-work and independent nodes. Our local program deliberately omits those mechanisms so students can see both the principle and the limitations clearly.
- Create blocks that contain fictional records, a previous-block fingerprint and a calculated SHA-256 digest.
- Run a local program and interpret three outputs: a valid chain, detected alteration and a deliberately rebuilt but unauthenticated chain.
- Understand hashing versus encryption, validation versus consensus, and public keys versus ordinary passwords.
- Test invalid amounts, duplicate spending, missing authorisation and conflicting copies using safe extensions.
- Keep real private keys, cryptocurrency, online services and student personal data completely outside the exercise.
- Finish with a written explanation of what the model demonstrates and why it is not Bitcoin or a real security product.
What students are building
Imagine a school activity ledger showing imaginary points held by Classmate A and Classmate B. The starting record says A has eight and B has two. Later records describe fictional transfers: A gives B three points, then B returns one. Students want to know whether a record written earlier was changed without detection. They will store those records in blocks, link each block to the previous block’s digest and run a validator to check for mismatches.
The program runs on one computer and does not connect to any cryptocurrency network. It does not generate an address, build a spendable wallet, mine Bitcoin, contact a server or store actual money. That is intentional. It keeps the exercise small enough to understand while preventing a classroom lesson from becoming an invitation to open an exchange account or handle financial credentials.
Why learn a hash before learning a blockchain?
A cryptographic hash function converts input data into a fixed-length digest. SHA-256 produces a 256-bit output, often displayed as 64 hexadecimal characters. If an input changes, its digest will almost certainly be different, and a good cryptographic hash is designed to make useful collisions computationally infeasible. The digest is not an encrypted copy of the original data, and it does not serve as a secret password.
Students can think of a digest as a carefully designed fingerprint. However, a fingerprint is not a person’s legal identity and cannot guarantee that the statement being fingerprinted is true. In our project, SHA-256 helps show that a record changed compared with the digest stored before. It does not prove who made the record or prevent a person with full access to the file from rewriting every digest.
Why use Python’s standard library?
Python includes a hashlib module supporting SHA-256 and a json module that can convert simple data structures into a consistent text representation. These are normal parts of Python. For the exercise, students do not need to download a cryptocurrency package, connect an API, install a browser wallet or enter payment details. A familiar local programming environment is enough.
We use json.dumps with sorted keys and compact separators to make the data representation more predictable. Hashing depends on exact bytes. If two computers serialise logically similar data in different orders or formats, their digests can differ. In a real protocol, canonical encoding rules must be specified with much greater care. Our miniature program has a clearly defined data format for the narrow records it handles.
Five fields in a toy block
- Index: the position of the block in our classroom list, starting with zero.
- Previous: the digest recorded for the preceding block, or a special marker for the first block.
- Records: invented classroom activity statements that the block contains.
- Digest: the SHA-256 result for the index, previous value and records.
- Position in the list: where the block actually sits in the local chain being checked.
The first record is sometimes described as the genesis block in blockchain terminology. In this model it simply uses the text GENESIS as a starting marker. Real Bitcoin’s genesis block and block headers have specific consensus rules, transaction structures and cryptographic commitments. Our fictional label has no connection to Bitcoin mainnet.
Step 1: choose fictional data, not real financial information
A school project should use the simple names A and B rather than a student’s real name, school number, bank identifier or wallet address. Write START A=8 B=2 to describe imaginary points. Add A to B: three points as a later classroom transaction, then B to A: one point. Those statements are strings describing examples; they are not valid financial instructions or actual signatures.
Before writing code, ask students to calculate the intended balances. From A=8 and B=2, a transfer of three from A to B gives A=5 and B=5. A subsequent transfer of one from B to A gives A=6 and B=4. The total remains ten. This arithmetic matters because detecting file tampering is different from verifying that a financial transfer is valid. Our first program focuses on the former.
Step 2: run this tested, offline Python example
Copy the following example into a local Python file or a controlled classroom environment. It uses only hashlib and json. It intentionally demonstrates how a person who controls every stored block can recompute digests and make a modified local chain pass basic integrity checks. It therefore must never be used for actual financial records, payments, security logs or cryptocurrency transactions.
import hashlib
import json
def digest(index, previous, records):
payload = {"index": index, "previous": previous, "records": records}
raw = json.dumps(payload, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def make_block(index, previous, records):
return {"index": index, "previous": previous,
"records": records.copy(),
"digest": digest(index, previous, records)}
def valid(chain):
for position, block in enumerate(chain):
expected_previous = "GENESIS" if position == 0 else chain[position-1]["digest"]
if block["index"] != position or block["previous"] != expected_previous:
return False
if block["digest"] != digest(block["index"], block["previous"], block["records"]):
return False
return True
chain = [make_block(0, "GENESIS", ["START A=8 B=2"])]
chain.append(make_block(1, chain[-1]["digest"], ["A -> B: 3 points"]))
chain.append(make_block(2, chain[-1]["digest"], ["B -> A: 1 point"]))
print("Original:", valid(chain))
chain[1]["records"][0] = "A -> B: 8 points"
print("Changed record:", valid(chain))
chain[1]["digest"] = digest(chain[1]["index"], chain[1]["previous"], chain[1]["records"])
chain[2]["previous"] = chain[1]["digest"]
chain[2]["digest"] = digest(chain[2]["index"], chain[2]["previous"], chain[2]["records"])
print("Rebuilt unauthenticated chain:", valid(chain))
What the program prints and why
The expected output is: Original: True; Changed record: False; Rebuilt unauthenticated chain: True. The original sequence passes because each block’s content matches its digest and each block points to its predecessor. When the program changes the content of block one from a three-point transfer to an eight-point transfer, the stored digest no longer matches the calculated digest, so the validator reports False.
The last result is the most important lesson. The example deliberately recomputes block one’s digest, updates block two’s previous pointer and recomputes block two’s digest. With no independent copy, digital signature, proof-of-work or consensus rule, the rewritten local chain passes its own basic integrity checks. It looks internally consistent even though its history has been changed. This is why simply connecting SHA-256 hashes is not sufficient to create a secure public blockchain.
Test the arithmetic independently
Our code stores records as human-readable strings. It does not parse the amount three, update balances or reject spending more points than a person has. A student could enter A gives B one million points, and the hash chain could still be internally consistent. The validator would say nothing about whether the spending was authorised or logically possible. That is not a software bug within the narrow demonstration; it is an intentionally missing validation requirement.
To add balance checking later, students should design a separate function that receives a starting balance, sender, recipient and amount, then rejects transactions when the amount is negative, zero, non-numeric or more than the available points. It must also establish what counts as an authorised request. A boolean value typed by a user is not a cryptographic signature, so even a well-organised classroom validator is not equivalent to Bitcoin.
Change detection is not the same as truth
A blockchain-like digest can show that the stored representation changed after a digest was calculated. It cannot determine whether the original statement was truthful. If a student entered the wrong amount at the beginning, the digest faithfully protects a false value. If the name of a book’s borrower was recorded incorrectly, the hash can be correct while the data is wrong. This distinction is important in inventory, medical records, supply chains and education systems.
Give students a deliberately false statement, such as ‘A has 500 points’ when the agreed class starting balance is eight. The record can be hashed correctly. Ask whether the digest proves the large balance is genuine. The right answer is no. The program only computes a relationship between data and fingerprint. Trustworthy input requires rules, independent evidence and sometimes human review.
Step 3: design tests before adding features
Testing means deliberately asking the program to handle cases that may fail, not just watching it succeed once. Students should write expected outcomes on paper before running new versions. For instance, a missing previous digest should be rejected; an altered record should fail the hash check; a block with the wrong index should fail; and a valid unchanged local sequence should pass.
One helpful extension is to design a function that compares the same chain saved in two different copies. If one copy changes, students can detect disagreement. But then they must ask how the system decides which copy is authoritative. A majority vote can help illustrate disagreement, yet a real open blockchain does not simply accept the most popular file. Consensus has precise rules and assumptions.
Testing checklist for a fictional point ledger
- Accept an authorised transfer of three points from A=8 to B=2.
- Reject a transfer of nine points when A has only eight.
- Reject a transfer with a zero or negative amount.
- Reject a repeat of the same spent classroom voucher.
- Reject a transfer attempted by a role that lacks authority.
- Detect a modified record whose stored digest was not updated.
- Detect an incorrect predecessor link.
- Detect a block whose index does not match its expected position.
- Notice that recomputing every digest on one private copy can make its altered history appear locally valid.
- Document every case and explain which rule caused acceptance or rejection.
This checklist is a test plan rather than a ready-made secure payment engine. Testing a toy program should never be presented as evidence that a public cryptocurrency is safe to use or that a new token has investment value. The goal is to teach how software can fail and why claims about security need precise evidence.
Why digital signatures are missing
A cryptographic hash detects relationships among bytes, but it does not prove that an authorised party approved a proposed change. Public-key digital signatures can provide verification that someone controlling a relevant private key signed specific data. Bitcoin uses appropriate signatures and script conditions to authorise spending under its rules. Our demonstration has no private keys, no public keys and no actual signature verification.
That omission is useful for teaching. Ask students what would happen if anyone could append a line saying ‘A paid B’ even without A’s permission. A perfectly linked digest would not solve the authorisation problem. Then introduce the conceptual idea of a signature: a separate check on who may spend, without publishing the secret key itself. Do not require pupils to generate real wallet keys or recovery phrases to study this relationship.
Why consensus is missing
Our program lives on a single computer and verifies only its own list. Bitcoin full nodes independently check blocks and transactions under shared protocol rules. Participants may temporarily see competing valid blocks, and proof-of-work contributes to how the network selects a valid accumulated-work history. These properties make rewriting established public records more costly than rewriting a private toy file.
A classroom can illustrate this by giving four groups separate copies of the ledger. Group A secretly changes block one, while the other groups preserve the original. Each group compares records and asks why they disagree. Then discuss whether having three matching sheets makes the content factually true. The class should distinguish consistency, validation and consensus rather than collapsing all three into a simple show of hands.
Proof-of-work is not just solving a puzzle
In Bitcoin, proof-of-work relates to finding block headers whose hashes satisfy network difficulty requirements. The work helps make replacing an established chain costly under the protocol’s assumptions. Miners still have to produce otherwise valid blocks that independent nodes accept. A valid proof-of-work hash does not authorise a double spend or override transaction rules.
A classroom might use a paper puzzle to represent costly block creation, but this can exaggerate the similarity with mining. Our Python example intentionally does not mine, target difficulty, perform block-header encoding or enforce any consensus rules. There is no reason for students to install mining software, rent computing power or consume energy for a real cryptocurrency. Discussing the architecture is enough.
Why a strong hash is still not a complete security system
SHA-256 can be suitable for cryptographic uses, but using it in a program does not automatically make the overall program secure. Security depends on what data are hashed, how that data are encoded, what assumptions the validator makes, who can change stored files, which identities can authorise actions and how copies are compared. Our final True result proves precisely this point: a secure primitive can be placed inside an insecure architecture.
Students should learn to identify the threat model. Are we trying to detect a classmate editing a page without updating the fingerprint? Are we trying to prevent the file owner from rewriting all records? Are we trying to coordinate unrelated participants who do not trust one administrator? These are different problems. An answer suited to one may not solve another. The best project reports explain their threat assumptions explicitly.
What hashing is not: passwords and encryption
Hashing produces a digest; encryption is designed to allow authorised recovery of information using appropriate keys. A hash is not a reversible container for storing secret data. A normal password should not be handled by simply publishing its SHA-256 result in a blockchain exercise, because passwords require specialised credential storage approaches and protection from guessing attacks. This project should not store any real passwords at all.
A child may ask whether a recovery phrase can be safely entered into the program because it only calculates a digest. The answer is no. Do not test with wallet recovery words, bank passcodes, school credentials or personal documents. Fictional class-point records are sufficient. Security learning should start with minimizing sensitive data and preventing unnecessary exposure.
A project is not a token launch
Creating a data structure named blockchain does not issue Bitcoin, create a tradeable asset or establish legal rights. Real cryptocurrency systems require defined consensus rules, signatures, network operation, economics and much more. An application may use a blockchain-like audit log without any token. Students should learn to resist the assumption that every interesting computer science exercise should become a coin that people can buy.
A developer can learn about cryptography and distributed systems while choosing never to own a cryptocurrency. From a parent’s perspective, that is often the ideal division of labour: support curiosity and technical skill, but protect household finances and the child’s privacy. A no-money project is not a watered-down lesson; it is an appropriate way to isolate the important engineering ideas.
Compare a hash chain with a database audit log
A conventional database can store records with user permissions, backups, timestamps and audit logs. A simple hash chain can improve the ability to detect some kinds of accidental or unauthorised changes, but it does not automatically improve database correctness, access control or backup reliability. Real financial and educational systems need appropriate correction procedures and legal governance. An append-only design may be inappropriate where privacy law or educational practice requires updates or deletions.
A student should ask whether the project truly needs independent participants maintaining a common history. If a single school librarian is already responsible for book lending, a central system with clear corrections may be simpler and better. If several independent institutions need shared verification, the analysis becomes more complicated. The right technology follows from the requirements, not from the appeal of a fashionable label.
Project extension: permission and authorisation tests
Design a function on paper called transfer_points. It receives sender, recipient, positive amount and a clearly fictional authorisation indicator. It verifies that the sender is known, the amount is positive, the recipient exists and the source has enough points. If any condition fails, the function must reject the request without changing the balances. This introduces input validation and state consistency before cryptography.
Next create two cases: a valid three-point transfer and a nine-point overspend when A has eight. Explain why the second is invalid even if the string representing it can be hashed correctly. Students who understand this separation are ready to discuss Bitcoin’s unspent outputs and prevention of double spending without needing a payment account.
Project extension: replay and duplicate records
A duplicate-spending problem occurs when the same limited resource is purportedly used twice. In the classroom, issue each student a fictional voucher with a unique identifier. When a voucher is spent, mark the identifier as consumed. A second attempt to use that identifier should be rejected by the validation rules. The student must explain why ordinary balance arithmetic may be insufficient if concurrent transactions are allowed.
A real Bitcoin network uses an unspent transaction output model, in which earlier outputs are consumed by a valid new transaction and cannot also be validly consumed by another confirmed transaction in the same chain history. Our fictional vouchers approximate this concept but do not reproduce Bitcoin’s actual serialisation, scripting or consensus implementation.
Project extension: conflicting copies
Have four students maintain separate versions of the same fictional ledger. Let two copies contain block 1A and two contain a different block 1B. Both may have internally valid hashes. Ask the group to document where the histories diverge. Then require a written rule about what evidence a participant needs to decide which version to trust. The exercise should reveal that agreement among copies is a coordination problem, not only a hashing problem.
Do not claim that all nodes automatically agree or that a simple majority decides every public blockchain dispute. Different systems use different protocols and threats. Bitcoin’s proof-of-work chain selection has specific validation and accumulated-work rules. Other systems, including those using proof-of-stake, use alternative mechanisms. Students should compare the principles without making the classroom vote into a false model of real consensus.
Project extension: build a visual diagram
Draw three boxes labelled Block 0, Block 1 and Block 2. Write the stored records inside each. Use an arrow from Block 1 to Block 0’s digest and from Block 2 to Block 1’s digest. Place a checkmark beside each block whose recalculated digest matches. Now show a red modification inside Block 1 and trace which checks fail. The visual should include a note: ‘A person who controls all stored blocks can recompute our toy chain; this is not a secure network.’
This diagram can be added to a science fair board or school report without any screenshot of a live wallet, exchange or mining program. Accuracy matters more than decoration. In the caption, the student should clearly distinguish the illustrative SHA-256 digest from Bitcoin’s detailed block-header hash and Merkle-root commitments.
Extension for upper-secondary Mathematics
Discuss the hexadecimal representation of SHA-256. Each hexadecimal digit represents four binary bits, so 64 hexadecimal digits represent 256 bits. Students can calculate 16 raised to the power 64 as another way to express the number of possible 256-bit outputs. The space is enormous, but that is not proof that collisions are mathematically impossible. Cryptographic security relies on the computational difficulty of finding useful collisions or preimages under specified assumptions.
Next ask why modifying a small amount of data can change a digest extensively. Students can experiment by hashing strings such as CLASS A and Class A and comparing outputs, while noting that the result is deterministic. The goal is not to discover a secret pattern in each output but to understand why exact data encoding matters and why a hash does not preserve a simple readable summary.
Extension for Computing: canonical encoding
In our code, a dictionary is converted into a JSON string with keys sorted and compact separators. Why is the order important? Because hashing operates on bytes, not the human meaning of a dictionary. Two strings may describe the same object but produce different hashes if they differ in spaces, punctuation or key order. A protocol must specify how inputs are encoded so that participants calculate compatible results.
Students can compare two serialisations of the same fictional block and ask whether the resulting digests match. They can then write a simple rule about character encoding, field order and data types. This is an entry point into computer networking, file formats, reproducible computation and the dangers of ambiguous protocol specifications.
Extension for Social Studies and ethics
A shared record can be difficult to alter, yet the entry may be incorrect or unfair. Imagine recording a pupil’s disciplinary mistake in a public permanent ledger. Even if the entry were technically secure, publishing it could violate privacy, deny a fair correction process and harm a child unnecessarily. Students should be able to argue why secure record keeping must coexist with rights, governance and appropriate limits on disclosure.
A successful conclusion may be that some data should not be placed on a public blockchain at all. That is not anti-technology reasoning. It is a competent design choice. The ability to reject an unsuitable tool is part of engineering ethics and helps students evaluate other technologies, including AI systems and large data platforms.
Ten errors to watch for while teaching
- Running the code with real passwords, student names, wallet seeds or identity data.
- Treating the last True output as proof that the toy chain is tamper-proof.
- Assuming a good SHA-256 hash automatically verifies transaction authorisation.
- Confusing the record string ‘A pays B’ with an actual valid Bitcoin transaction.
- Believing a list of blocks in one file is a distributed consensus network.
- Assuming a file cannot be edited because it contains linked hashes.
- Ignoring balance checks and duplicate-spend checks because the digests are correct.
- Treating a mock boolean authorisation flag as a cryptographic signature.
- Running a live miner or deploying a token to complete a class demonstration.
- Publishing a child’s personal or financial details in a supposedly transparent ledger.
A five-day school project timeline
Day 1: Introduce record-keeping problems, shared ledgers and why each block stores the preceding digest. Complete a paper diagram with two fictional transfers. Make sure the Mathematics and starting assumptions are correct before programming.
Day 2: Install or use an approved existing local Python environment, read the code and run the example without network access. Identify the role of hashlib, json, make_block, digest and valid. Save the expected output and explain what each line means.
Day 3: Perform the tampering test, then discuss why an attacker can recompute every digest when they control the entire local file. Design additional invalid-input and authorisation tests on paper. A student who can explain why the final result is True despite altered history has grasped a key limitation.
Day 4: Add a fake point-balance validator or a peer-copy comparison, depending on ability. Never insert real credentials or data. Describe the remaining missing elements: digital signatures, independent full nodes, consensus, proof-of-work and network incentives.
Day 5: Present a two-page report and diagram. The first page explains what the project accomplishes; the second explains its limitations, possible threats and when a conventional database would be preferable. Finish with a source list from NIST, Python documentation and Bitcoin’s developer guidance.
Marking rubric for teachers
- Four marks for explaining the original shared-record problem in plain English.
- Four marks for showing correct hash-link data and reproducing the expected program output.
- Four marks for explaining what changing an earlier record does to verification.
- Four marks for explaining why recomputing hashes defeats an unauthenticated private chain.
- Four marks for separating data validation, signatures, consensus and proof-of-work.
- Four marks for identifying privacy, security and suitability limits.
- Additional credit for well-designed failure tests and a clear argument about whether blockchain is needed.
A report should not receive full credit merely for printing a long hash or using the word decentralised. It should earn marks for connecting observations with explanations. The ability to state ‘our model is insufficient for real cryptocurrency’ is an important sign of mastery.
Parent and student FAQs
Can my Primary-school child build this?
Younger pupils can use the paper version with blocks and stickers. Coding is optional and should be age-appropriate.
Do we need to buy Bitcoin?
No. Everything uses fictional class points and locally generated hashes.
Does Python contain a real SHA-256 implementation?
Yes. The standard hashlib module provides a SHA-256 interface, as explained in Python’s official documentation.
Is the example a real blockchain?
It is a local illustrative hash chain. It lacks the network, consensus, financial rules and authorisation mechanisms required for a real public cryptocurrency.
Why does the validator return True after rebuilding the changed chain?
Because the program only checks internal consistency. The person who controls the entire file can replace all the digests.
Does this prove SHA-256 is weak?
No. SHA-256 is not the failure here; the surrounding architecture has no independent protection against complete rewriting.
Can a hash tell whether the original statement is true?
No. It can commit to data but cannot establish that a real-world assertion is accurate.
Why don’t we use real wallet keys?
They are unnecessary and sensitive. Generating, sharing or using real keys would introduce avoidable risk.
Can students store school results on a public blockchain?
That is generally inappropriate for an introductory exercise and raises privacy, correction and governance concerns. Use invented records.
Can this code send real cryptocurrency?
No. It has no wallet, network interface, Bitcoin transaction format or signing operation.
What is proof-of-work?
A consensus-related mechanism requiring computational effort for eligible block creation under Bitcoin’s rules. It is not implemented here.
What is a digital signature?
A cryptographic authorisation mechanism, distinct from hashing data for an integrity check. Our toy program does not implement one.
What happens if a block has a wrong index?
The validator returns False, because the stored index does not match the expected list position.
What happens if an invalid point transfer is recorded?
The current program may still see an internally consistent chain; a separate transaction-validation layer is required.
Is a database automatically less secure than a blockchain?
No. Appropriate database permissions, backups and audit logs can better suit many ordinary school applications.
Does a hash chain stop administrators from changing records?
Not by itself, as the last True output demonstrates. A privileged editor can recompute local hashes when no independent anchor or consensus protects the history.
Is this project useful for future cybersecurity study?
Yes. It introduces exact data representation, threat models, testing, trust assumptions and cryptographic components without financial exposure.
What should a parent look for in the final report?
Accurate explanation of the three outputs, a clear list of missing real-world safeguards and a thoughtful safety and privacy section.
A home discussion that builds genuine understanding
Ask your child, ‘Which output surprised you most?’ Many students expect the altered chain to stay invalid forever. The last result teaches them that an attacker with complete control over one local copy can repair internal consistency after rewriting history. Ask what kind of external evidence or shared protocol could change that situation. Older learners may describe independent participants, chain-selection rules and costly replacement of established records.
Then ask why software developers should demonstrate failures rather than only show successful examples. A program that works in one scenario can still be unsafe under different assumptions. It is better to understand the limits early than to promote untested code as an investment, payment or identity product. This lesson transfers to AI tools, social-media claims and everyday digital security.
Sources and verified documentation
- NIST — Blockchain, explanation of shared, tamper-evident and tamper-resistant ledgers.
- NIST — Blockchain Technology Overview, research publication summary and technical scope.
- Python Documentation — hashlib, SHA-256 and digest interfaces.
- Python Documentation — json, stable encoding options and sorting keys.
- Bitcoin Developer Guide — Block Chain, block headers, proof-of-work, forks and transaction commitments.
- Bitcoin.org — How Bitcoin Works, digital signatures and network verification.
- MoneySense — Risks of Digital Tokens, Singapore consumer risk warning.
Further eduKateSG learning
- Build a Classroom Blockchain With Paper, Hashes and Shared Records.
- Read Transactions, Fees and Confirmations on a Block Explorer.
- Smart Contracts, NFTs and Asset Tokenisation Explained.
- Parent Safety Guide to Scams, Privacy and Responsible Learning.
Reviewed 20 November 2026. The Python example was checked using the standard library and is educational only. It is not secure for real-world audit logs or money; it deliberately allows rebuilding an unauthenticated chain. Never use student personal data, wallet keys, actual cryptocurrency or live payments in this exercise.