IAT 1 Question Bank
On this page
CMC742 IAT-1 — Exam-Ready Answers
Each answer is structured for a 10-mark response. Bitcoin-specific rules are labelled as such; other blockchains may use different data structures, permissions, or consensus mechanisms.
Module I
1. Define blockchain. Explain any four key characteristics of blockchain technology.
A blockchain is a distributed, replicated, append-only ledger in which transactions or state updates are grouped into blocks, blocks are cryptographically linked, and participating nodes use a consensus protocol to agree on the accepted history. It is a system comprising data, networking, validation, consensus, and application layers—not merely a list of hashes or a database. Bitcoin is one application of blockchain technology, not a synonym for blockchain.
Key characteristics
- Distributed replication: Multiple nodes maintain copies of the ledger and independently verify new records. There is no necessary single master database. Replication improves availability and lets participants audit the same history, although a full node need not store every type of data in every protocol.
- Decentralisation and shared control: In a public permissionless chain, no single organisation decides unilaterally which valid transactions become final; protocol rules and distributed participants do. In a private chain, decentralisation is weaker and control is assigned to an organisation or consortium.
- Cryptographic linkage and tamper-evidence: A block contains a cryptographic commitment to its predecessor. In Bitcoin, the header contains the previous block-header hash and the Merkle root of transactions. Changing an old transaction changes the Merkle root and block hash, breaking the next block’s reference.
- Consensus and ordering: Nodes may receive transactions in different orders. Consensus rules determine which valid block/history is accepted and how conflicting transactions are resolved. Bitcoin uses cumulative Proof-of-Work; permissioned networks may use voting or BFT protocols.
- Append-only, auditable history: Accepted records are normally appended rather than edited in place. “Immutable” means alteration is detectable or economically/organisationally difficult; it does not mean a physical byte can never be changed or that a recorded fact is necessarily true.
- Transparency and verifiability: On a public chain, transaction data and proofs can usually be inspected and independently checked. This is normally pseudonymous rather than anonymous: addresses are visible even if real names are not.
- Programmability: Smart-contract platforms allow deterministic programs to update shared state when specified conditions are met. This adds automation but also introduces code, oracle, gas, and bug risks.
- Incentive/security mechanism: Public networks attach influence to a scarce resource such as computation or stake, and may reward valid participation with fees or protocol rewards. This prevents cheap creation of identities from becoming voting power (Sybil resistance).
Flow:
signed transaction → peer-to-peer broadcast → node validation
→ candidate block → consensus → replicated ledger
The appropriate definition depends on the trust model. A company’s hash-linked audit file may be tamper-evident, but without replicated participants and a protocol for agreement it is not automatically a decentralised blockchain. The CMC742 reference material and Bitcoin whitepaper describe the ledger, peer-to-peer, hashing, and consensus foundations.
2. Explain the role of cryptographic hash functions in blockchain. Illustrate your answer with a suitable example.
A cryptographic hash function H maps an arbitrary-length input to a fixed-length digest:
H : {0,1}* → {0,1}^n
For example, SHA-256 always produces 256 bits (32 bytes, conventionally written as 64 hexadecimal characters). SHA256("hello") is:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
A secure hash is designed to have:
- Preimage resistance: given
y, it is infeasible to findxsuch thatH(x)=y; - Second-preimage resistance: given
x, it is infeasible to find a differentx'with the same hash; and - Collision resistance: it is infeasible to find any two different inputs with the same hash.
A collision is mathematically possible because many inputs map to a finite output space; security means that finding a useful collision is computationally infeasible. A small input change normally causes a large, unpredictable output change, called the avalanche effect.
Roles in blockchain
- Block linking: Bitcoin computes the block identifier as double SHA-256 of its 80-byte header. The next block stores that hash as
prev_block, forming a tamper-evident chain. - Transaction identification: A transaction hash/txid provides a compact identifier for a serialised transaction.
- Merkle commitment: Transaction hashes are combined into a Merkle tree; the single root is placed in the block header. A changed transaction changes its leaf, all ancestors, and the root.
- Proof-of-Work: Bitcoin miners repeatedly hash candidate headers until the numerical hash is below the current target:
SHA256d(header) ≤ target. Finding is difficult; checking is quick. - Commitment/integrity: A hash can commit to data without revealing it in advance, but hashing is not encryption and does not authenticate a sender. Digital signatures authenticate key control; consensus orders valid transactions.
Example: Suppose a block contains transaction T. A miner computes:
m = MerkleRoot(T, other transactions)
h = SHA256(SHA256(version || prev_hash || m || time || bits || nonce))
If an attacker changes T to T', then normally H(T') ≠ H(T), so m changes and the block hash h changes. The next block still contains the old h in its previous-hash field, so nodes detect the break. To conceal the edit in Bitcoin, the attacker must find a valid alternative header and redo the work for the altered block and its descendants. SHA-256 is specified by NIST FIPS 180-4; Bitcoin’s double hashing is a protocol convention, not a universal blockchain requirement.
3. Construct a Merkle Tree for the given four transactions T1, T2, T3 and T4 using suitable hash values, and explain how the Merkle Root is generated.
Let H(x) denote the hash operation; for Bitcoin use H(x)=SHA256d(x), while a classroom example may use any collision-resistant hash. First hash each transaction to create the leaves:
h1 = H(T1) h2 = H(T2) h3 = H(T3) h4 = H(T4)
Pair adjacent leaves and hash their concatenations:
h12 = H(h1 || h2)
h34 = H(h3 || h4)
Finally hash the two parent nodes:
MerkleRoot = H(h12 || h34)
Tree diagram
Merkle Root
R = H(h12 || h34)
/ \
h12 = H(h1 || h2) h34 = H(h3 || h4)
/ \ / \
h1=H(T1) h2=H(T2) h3=H(T3) h4=H(T4)
Worked numerical example: using the ASCII strings T1, T2, T3, and T4 and Bitcoin-style double-SHA-256 (displayed in hexadecimal):
h1 = dcd82e14263c812e22e8d34cd8879250544eb04737e30cbbef293162c461c338
h2 = dcd81cedc1471e7c8ca8ac50beb1a678bc07509ebb6d78f4a41a0193455217a3
h3 = 824d27add2f491ae3d740bf39863099361f138a338b56bc193ab4ded0fd1d25f
h4 = b85d6ac1e13e72d7baf0c9119d349c88a9c31413750731a9826442b109eb3d5d
h12 = 768efea1673a6b9772fc158331525009473c69734939bcca22db6138c7dca322
h34 = b8a8b4d155432ec970f7e01466a43f1a05d3924c689c8913a49a5fbd10b1d0f9
R = bbe4c9a7f6e2a7773b9ee98698419e7bc132702133553ce6627264fde9984cde
Here h12 = H(h1 || h2), h34 = H(h3 || h4), and R = H(h12 || h34), where || means byte concatenation. The root is stored in the block header. It commits to all four transactions and their order. If T3 changes to T3', then h3 changes, then h34 changes, then R changes; the old header’s root no longer matches the block body.
For an odd number of leaves, Bitcoin duplicates the final hash at that level before pairing, e.g. H(h3 || h3). This is Bitcoin-specific; other protocols can use promotion, a different tree, or another odd-leaf rule. Bitcoin’s developer reference also explains Merkle branches: to prove inclusion of T3, a verifier needs h4 and h12, plus left/right positions:
p34 = H(h3 || h4)
R = H(h12 || p34)
Thus verification requires only O(log n) sibling hashes rather than the full block. A Merkle proof proves inclusion in the committed tree; it does not alone prove that the transaction is valid, final, or on the canonical chain.
4. Draw and explain the structure of a blockchain block. Describe the purpose of each field present in the block header.
A generic block has a header containing metadata/commitments and a body containing transactions or state updates. The exact layout is protocol-specific. The following is the Bitcoin block structure:
┌──────────────────────────────────────────────────────┐
│ Block header (Bitcoin: 80 bytes) │
│ version | previous block hash | Merkle root │
│ timestamp | nBits/target | nonce │
├──────────────────────────────────────────────────────┤
│ Block body │
│ transaction count | coinbase transaction | Tx2 ... │
└──────────────────────────────────────────────────────┘
| Header field | Bitcoin size | Purpose |
|---|---|---|
version | 4 bytes | Signals the block/protocol version and version-dependent validation rules. |
previous block hash | 32 bytes | Cryptographic link to the preceding block header. The genesis block has a protocol-defined special value. |
Merkle root | 32 bytes | Single commitment to the block’s transaction hashes and order. |
timestamp | 4 bytes | Approximate block time, subject to Bitcoin’s consensus timestamp rules; it is not a universally trusted wall clock. |
nBits | 4 bytes | Compact encoding of the PoW target. Nodes decode it and check that the header hash is at or below that target. |
nonce | 4 bytes | Search counter varied by miners while trying to satisfy PoW. When its range is exhausted, miners change extra-nonce/coinbase data or other permitted fields. |
The body contains the transactions. In Bitcoin the coinbase transaction is first and creates the miner’s permitted subsidy plus collected fees; ordinary transactions consume and create UTXOs. The Bitcoin block-chain reference specifies the Bitcoin header fields; Ethereum and permissioned chains have different headers and state commitments.
Validation flow
receive block → check format, parent, timestamp and target
→ recompute Merkle root
→ validate every transaction and UTXO/signature rule
→ verify PoW → apply chain-selection/finality rule
The block hash is not the Merkle root: in Bitcoin it is SHA256d(header). If a transaction is changed, its txid and the Merkle root change; therefore the block hash changes. The child block’s previous-hash field then fails unless the attacker recomputes the child and every later block. A valid PoW header is necessary but not sufficient: nodes still reject invalid transactions.
5. Differentiate between Public, Private and Consortium blockchains based on any six suitable parameters.
The three types differ mainly in membership, permissions, governance, and trust assumptions. “Public/private” should not be confused with “all data public/secret”; read and write permissions can be designed separately.
| Parameter | Public blockchain | Private blockchain | Consortium blockchain |
|---|---|---|---|
| Control | Distributed; no single operator is intended to control the ledger | One organisation controls membership and rules | Several organisations jointly govern it |
| Membership | Generally open/permissionless | Invitation or administrator approval | Vetted member organisations |
| Read access | Usually open and independently auditable | Restricted or role-based | Usually restricted to consortium members, with possible public proofs |
| Transaction submission | Generally anyone with a valid account/transaction | Authorised users | Authorised users from member organisations |
| Validation/order | Protocol-selected miners/validators; Sybil resistance is required | Selected nodes or administrator | Selected member validators/orderers under a quorum policy |
| Consensus | Often PoW or PoS | Often Raft, PBFT, PoA, or another permissioned method | Often BFT, Raft, IBFT, or policy-based ordering |
| Trust model | Trust is shifted from an intermediary to public rules, cryptography, and economic assumptions | Trust remains concentrated in the operator | Trust is shared among known members; no single member should dominate |
| Performance/cost | Usually lower throughput and greater latency/resource cost in open adversarial settings | High throughput and low latency are easier to achieve | Intermediate; faster than many public chains but coordination is required |
| Privacy | Transparent by default; pseudonymous and sometimes privacy-enhanced | Stronger access control and confidentiality | Selective disclosure/channels can protect member data |
| Governance | Open and often difficult to change; forks may occur | Central administrator can upgrade/censor/reconfigure | Consortium agreement defines membership, upgrades, disputes, and quorum |
| Examples/use | Bitcoin/Ethereum; public payments or public proofs | Internal audit, one company’s records | Inter-bank settlement, supply-chain, shared certificates |
A public chain maximises openness and public verifiability but pays for open membership. A private chain is suitable where one legitimate authority already exists; it provides auditability but not the same trustlessness. A consortium is appropriate when several institutions need a common record and do not want one institution to own it. Hyperledger Fabric’s ordering documentation illustrates the permissioned ordering/validation distinction.
6. Explain the working of a blockchain consensus protocol. Discuss how consensus ensures data integrity and prevents unauthorized modification of blocks.
Consensus is the protocol process by which distributed nodes agree on a valid state/history, transaction order, and next block despite delays, failures, and possibly malicious nodes. It must provide safety (honest nodes do not accept conflicting final histories), liveness/progress (the network can continue under stated conditions), validity, and a rule for resolving competing proposals.
Generic operation
1. A user signs a transaction with a private key.
2. Peers broadcast and independently validate its format, signature and state rules.
3. A proposer/miner/validator assembles valid transactions into a candidate block.
4. The consensus mechanism selects or approves a candidate.
5. Nodes verify the block, append it if valid, and relay/store it.
6. Later blocks or a quorum increase finality/confidence.
Example: Bitcoin’s Nakamoto Proof-of-Work
- A miner forms a header and searches for
SHA256d(header) ≤ target. - The first valid candidate is broadcast.
- Nodes check the PoW, previous-block hash, Merkle root, transactions, signatures, and UTXO rules.
- If two valid blocks compete, nodes follow the valid chain with the greatest cumulative work; the losing branch becomes stale if it is not extended.
- Rewriting an old block changes its Merkle root and hash, invalidates its child link, and requires redoing the work for the altered block and its descendants and catching up with honest work.
How unauthorised modification is resisted
- Digital signatures: only a holder of the relevant private key can normally authorise a spend; a hash alone cannot prove authorship.
- Hash links: an edited block no longer matches its child’s
previous hash. - Merkle root: an edited transaction no longer matches the header’s transaction commitment.
- Independent validation: nodes reject malformed blocks, invalid signatures, double spends, over-creation, or invalid smart-contract state transitions even if a proposer created a valid-looking header.
- Sybil resistance: PoW makes influence proportional to costly hashpower; PoS uses economically committed stake; permissioned BFT uses authenticated members and quorum votes.
- Finality/confidence: BFT quorum commits can be deterministic under their assumptions; Bitcoin confirmations are probabilistic and become harder to reverse as cumulative work grows.
Consensus does not guarantee that data describes reality: it can agree on a false oracle reading, nor does it make a 51% attacker able to forge another user’s signature or make invalid transactions valid. It protects the accepted protocol history under its threat model. The Bitcoin whitepaper explains the PoW chain-selection and double-spending model; PBFT illustrates a permissioned Byzantine-quorum approach.
7. Analyze the process of adding a new block to a blockchain network. Explain the role of hashing, previous block hash and consensus during this process.
The following is the Bitcoin-style flow; a permissioned chain may replace mining with endorsement/orderer voting.
wallet signs Tx
↓
P2P broadcast → nodes check signature, UTXO, fee, script → mempool
↓
miner selects transactions + coinbase
↓
construct Merkle tree and candidate header
↓
PoW search: vary nonce/extraNonce until hash ≤ target
↓
broadcast block → every node validates independently
↓
accepted on best valid chain → relay/store → confirmations grow
Step 1 — Transaction collection and validation. Nodes receive signed transactions and check syntax, signatures/scripts, referenced outputs, absence of double spend, amounts, and policy/consensus rules. Valid but unconfirmed transactions are held in a mempool.
Step 2 — Candidate block. The miner selects transactions, constructs a coinbase transaction, places transactions in an order, and computes their txids and Merkle root. The candidate header contains version, the hash of the current chain tip, the Merkle root, timestamp, encoded target, and nonce.
Step 3 — Hashing and PoW. The miner computes SHA256d(header) repeatedly. Hashing gives a compact fingerprint: changing any transaction changes the Merkle root and therefore every candidate header hash. PoW requires the numerical hash to be below the target, making block production costly but verification easy.
Step 4 — Broadcast and independent checks. A successful miner broadcasts the full block. Nodes verify:
- the parent is known/valid and the previous-hash field matches;
- the timestamp and target are acceptable;
- the header hash satisfies PoW;
- recomputed Merkle root equals the header’s root;
- every transaction is valid, including signatures, UTXO spending, fees, and coinbase rules; and
- the block follows the consensus/chain-selection rule.
Step 5 — Append and confirmation. Valid nodes append the block to their current best chain and relay it. If competing valid blocks exist, the consensus rule selects a branch. In Bitcoin, later blocks add cumulative work and make a reversal increasingly unlikely.
The previous block hash provides ordering and tamper evidence; the hash/Merkle root commits to content; consensus decides which valid candidate becomes shared history. None alone is sufficient: a hash does not validate transactions, and consensus cannot legitimise a block that violates the protocol. See the Bitcoin developer mining guide.
8. Analyze any four major limitations and challenges of blockchain technology and discuss their impact on practical applications.
- Scalability, throughput and latency: Every validating node may need to receive, verify, and store replicated data. Larger blocks or more complex execution can raise throughput but increase bandwidth, storage, and hardware requirements, excluding smaller nodes and reducing decentralisation. Applications requiring instant, high-volume payments may need batching, channels, rollups, sharding, or a permissioned design.
- Energy and resource consumption: Bitcoin PoW deliberately spends electricity and hardware to make attacks expensive. This can create environmental, operating-cost, and geographic-concentration concerns. PoS or permissioned consensus reduces continuous hash racing but introduces stake, governance, or membership assumptions; changing consensus is a trade-off, not a free solution.
- Privacy and data permanence: Public ledgers are transparent and address reuse/link analysis can reveal behaviour. Sensitive personal data is difficult to delete once replicated, while storing only a hash does not eliminate metadata or the need to protect the original. Use data minimisation, encryption/access control, off-chain storage, selective disclosure, and store hashes rather than raw personal data where appropriate.
- Security and key management: A private-key theft, smart-contract bug, oracle manipulation, or majority-resource attack can cause losses. Blockchain validation can preserve an incorrect input; immutability makes recovery difficult. Mitigations include hardware/MPC or multisignature custody, audits, formal analysis, least privilege, pause/upgrades with governance, rate limits, monitoring, and tested recovery procedures.
- Governance and legal uncertainty: Protocol upgrades, disputed transactions, membership, liability, identity, tax, and data-protection obligations still need human institutions. Decentralised governance can lead to forks and slow decisions; permissioned governance can be more efficient but reintroduces trusted administrators.
- Storage and operational cost: A growing replicated history requires disk, backups, indexing, and node maintenance. Pruning, archival separation, off-chain data, and compact proofs reduce costs but may weaken independent verification or availability.
- Oracle/real-world truth problem: Consensus proves what was submitted, not whether a sensor, person, shipment, or price report was true. Use multiple independent oracle sources, signed attestations, dispute windows, collateral/slashing, and human/legal escape paths.
The practical impact is that blockchain is most justified where several parties need a shared, auditable record but do not want one party to control it. For a single trusted organisation’s fast private data, a conventional database is often cheaper and simpler. The CMC742 reference discusses the same limitations; Ethereum’s scalability documentation illustrates current mitigation directions.
9. Evaluate the suitability of Public, Private and Consortium blockchains for an e-governance application. Justify your choice.
Consider an e-governance system for certificates, land records, licences, or welfare transactions. The design must provide auditability, authorised issuance, citizen verification, privacy, revocation, availability, and legal accountability.
| Option | Strengths for e-governance | Weaknesses/risks |
|---|---|---|
| Public | Maximum independent auditability; citizens and journalists can verify proofs; resilient against one department rewriting history; useful for anchoring document hashes. | Public personal data is a privacy risk; fees/latency and throughput may be unsuitable; irreversible mistakes and key loss are difficult; the government still has to attest that the original fact is true. |
| Private | Fast, inexpensive, confidential, easy role-based access, and simple administrative accountability. | A department/operator can censor or rewrite records or control upgrades; citizens and other departments must trust that authority; compromise of the operator is a single-point risk. |
| Consortium | Several departments, universities, courts, auditors, and authorised service providers jointly validate; no single department owns the history; permissioned identities support privacy, compliance, and deterministic finality. | Requires governance, membership, quorum, dispute and upgrade rules; colluding members can still censor; onboarding and interoperability are non-trivial. |
Recommended design: a permissioned consortium blockchain with optional public anchoring.
- Members: issuing departments, accredited institutions, independent auditor/ombudsman, and perhaps a records authority.
- Citizens and employers receive read/verification access through a portal, but raw personal data is kept off-chain.
- The chain stores a document hash, issuer ID, issue time, version, status/revocation reference, and a URI or encrypted pointer—not the full certificate or sensitive identity data.
- A quorum of independent member nodes endorses and orders issuance/revocation. Role-based access and encryption protect private details.
- Periodically publish a consortium Merkle root or state digest to a public chain for an extra external timestamp/anti-rewrite anchor.
Decision: a public chain alone maximises transparency but conflicts with privacy and government control; a private chain is efficient but merely replaces the public trust problem with one department; consortium gives shared institutional accountability with controlled disclosure. Public anchoring adds independently verifiable evidence without placing citizens’ data on a public ledger. Governance must define who may issue/revoke, how disputes are handled, how keys are recovered, retention/deletion rules, audits, and what legally constitutes a final record.
10. Design a blockchain-based solution for a certificate verification system. Clearly identify the participants, type of blockchain, block contents and transaction flow.
Objective: allow an employer or citizen to verify that a certificate was issued by an authorised institution and has not been altered or revoked, without putting personal data in plaintext on a public ledger.
Participants
- Issuer: university/board/government department that creates and signs the certificate.
- Consortium validators/orderers: issuer organisations, accreditation authority, examination board, and independent auditor.
- Holder: student/citizen who receives the certificate and controls disclosure.
- Verifier: employer, another university, or government service that checks a presented certificate.
- Identity/authorisation service: registers institutions and maps permissioned keys to organisations.
- Off-chain storage: encrypted document store/IPFS-like content-addressed storage, with the holder or authorised custodian controlling access.
Type and trust model: a permissioned consortium blockchain. Validators are known and authenticated; endorsement/quorum rules prevent one institution from silently changing history. Do not store the full certificate, Aadhaar/PAN-like data, or other sensitive personal data on a public chain. A public hash anchor may be added periodically.
On-chain certificate record
certificateId = unique identifier
subjectCommitment = hash(blinded subject identifier)
documentHash = hash(canonical certificate bytes)
issuerId, issuerKeyVersion
qualification, issueTimestamp, expiry (if applicable)
status = VALID | REVOKED | SUPERSEDED
revocationReason/reference, schemaVersion
metadataURI = encrypted/off-chain pointer (optional)
issuerSignature / transaction signature
The hash must be computed over a canonical representation so whitespace or field-order differences do not create false mismatches. The chain stores proof and status; encrypted document content stays off-chain.
Issuance flow
institution authenticates student/result
↓
create canonical certificate + encrypt/store document off-chain
↓
compute documentHash and subject commitment
↓
issuer signs IssueCertificate(certificateId, hash, metadata)
↓
endorsing consortium nodes check issuer role and uniqueness
↓
orderer/quorum puts transaction in a block
↓
peers validate, commit, and emit CertificateIssued
↓
holder receives document/credential and verification link
Verification flow
- Holder presents the certificate or a verifiable credential and proof of consent.
- Verifier computes the canonical document hash (or requests a holder-provided proof) and queries the consortium portal/ledger.
- The system checks that
certificateId,documentHash, issuer signature, issuer authorisation, status, and expiry match. VALIDplus matching hash means the record was issued by the registered issuer and the presented bytes match the committed document. It does not prove that the issuer’s original academic decision was morally/correctly made.- If the certificate is revoked, the verifier receives status and reason according to policy; no old block is edited.
Revocation: issuer submits a signed RevokeCertificate transaction referencing the original ID. Validators check issuer authority, append the status change, and emit an event. Privacy: use encryption, selective disclosure/zero-knowledge proofs where feasible, minimal on-chain identifiers, key rotation, and access logs. Security: multisignature issuer keys, HSMs, audit logs, duplicate-ID protection, backups, and a documented governance/recovery procedure are essential.
Module II
11. Explain the concepts of Bitcoin, Altcoin, and Tokens with suitable examples.
| Concept | Definition | Example and technical distinction |
|---|---|---|
| Bitcoin | A decentralised cryptocurrency protocol/network and its native asset BTC. It maintains a public UTXO ledger and uses Proof-of-Work for ordering. | A BTC payment consumes Bitcoin UTXOs and pays Bitcoin-network fees. Bitcoin is an application of blockchain technology, not the definition of blockchain. |
| Altcoin | “Alternative coin”: broadly, a coin other than Bitcoin that has its own independent blockchain and protocol. It may modify monetary policy, block time, privacy, scripting, or consensus. | Litecoin or Monero are examples of independent networks; ETH is the native coin of Ethereum. A Bitcoin-derived network is still a separate coin if its network and ledger operate independently. |
| Token | An application-level digital asset created on an existing blockchain, usually by a smart contract. It uses the host chain for transaction ordering and security rather than bootstrapping its own consensus network. | An ERC-20 token deployed on Ethereum has balances and transfer rules in a contract; it is not ETH and does not have its own miners/validators. |
Coin versus token: a coin is native to its own ledger and often pays that network’s fees; a token is issued on a host chain and normally pays fees in the host coin. A token can represent utility, governance, a claim, an identity credential, or an investment-like right.
Bitcoin flow:
Bitcoin wallet signs input references → Bitcoin nodes validate UTXOs
→ PoW miners order transactions
→ BTC outputs become spendable
Token flow:
user calls token contract → Ethereum transaction pays gas in ETH
→ contract updates balances mapping
→ token transfer event is emitted
An altcoin is not merely another name for a token: the former has an independent base chain; the latter is hosted on another chain. A project’s claim that a token is a “utility token” does not by itself settle its legal classification; that depends on rights, facts, and jurisdiction. See the CMC742 reference material and Ethereum account/transaction documentation.
12. Differentiate between Utility Tokens and Security Tokens with suitable examples.
A utility token is designed primarily to provide access to, or use within, a product, service, network, or application. A security token represents an investment-like financial interest such as equity, profit share, debt, or a claim whose value depends substantially on the efforts of an issuer/project team. The label chosen by the issuer is not conclusive; legal classification is jurisdiction- and fact-dependent.
| Parameter | Utility token | Security token |
|---|---|---|
| Primary purpose | Access, usage, payment for a service, or application function | Investment, ownership, debt, revenue/profit share, or financial claim |
| Holder expectation | Use the network/product; price speculation may still exist | Expectation of financial return or appreciation from an enterprise/managerial effort |
| Issuer relationship | May be decentralised or service-provider based | Usually an identifiable issuer/promoter and regulated offering obligations may apply |
| Example | A storage-application token redeemable for storage capacity | A token representing a proportional share of rental income or company equity |
| Transfer/rights | Defined by application contract; may provide access/governance | Defined by offering terms and applicable securities/company law |
| Main risks | Contract failure, illiquidity, service not delivered, misleading utility claims | Investment loss, issuer failure, fraud, disclosure/compliance and transfer restrictions |
| Typical compliance concern | Consumer protection, AML/tax, platform rules | Registration/exemption, disclosures, KYC/AML, investor restrictions and reporting |
Example comparison:
STORAGEgives a user one month of decentralised storage when redeemed through an application. That is a utility use, although it is not automatically legally exempt.RENTentitles a holder to 1% of an apartment project’s rental profits. It is an investment-like claim and is likely to receive security-token treatment in many legal analyses.
Both can be implemented as smart-contract tokens, but code does not determine legal rights by itself. A sound design documents the asset’s rights, restricts transfers where law requires, performs legal analysis, protects investors/consumers, and clearly separates marketing promises from on-chain enforcement. For a legal definition, consult the relevant regulator; for example, the U.S. SEC digital-asset framework uses investment-contract analysis rather than relying only on the word “utility.”
13. Explain the working of Hot Wallets and Cold Wallets. State two advantages and two limitations of each.
A wallet is a key-management tool, not a container holding physical coins. The blockchain records spendable outputs or account state; the wallet stores/derives keys, shows balances, constructs transactions, and signs with the private key.
public address → receive funds / identify destination
private key → sign authorisation to spend
seed phrase → recover the wallet's derived keys
Hot wallet
A hot wallet is connected to the internet or readily accessible by an online device: mobile, desktop, browser, exchange account, or software wallet.
Working: the wallet derives or imports keys, queries the chain, creates a transaction, signs it locally or through a custodian, and broadcasts it through a connected node/service.
Advantages
- Convenience and speed: suitable for frequent payments, trading, and DApp interaction.
- Easy access/integration: works with phones, browsers, exchanges, QR codes, and online applications; backups and recovery can be simpler if managed correctly.
Limitations
- Greater online attack surface: malware, phishing, malicious browser extensions, remote compromise, SIM/social engineering, and exchange breaches can expose keys or authorise transactions.
- Custody/operational risk: a custodial hot wallet requires trust in the provider; an incorrect address or leaked key usually cannot be reversed by a bank. Online service downtime and fees are additional concerns.
Cold wallet
A cold wallet keeps signing keys offline except during deliberate signing: hardware wallet, properly stored offline device, or paper/air-gapped backup.
Working: the online computer prepares an unsigned transaction, the offline device displays/verifies its details and signs it, and only the signed transaction is returned for broadcast. The private key need not leave the device.
Advantages
- Reduced remote exposure: malware cannot normally read a well-protected offline key during ordinary online use.
- Good long-term custody: balances can be separated from everyday spending and hardware wallets can require PIN/physical confirmation.
Limitations
- Less convenient: signing, firmware updates, address checking, and recovery take more time; it is unsuitable for every small payment.
- Physical/recovery risk: loss, theft, fire, damage, counterfeit hardware, a malicious initial setup, or a lost seed phrase can cause permanent loss. Cold does not mean immune to phishing or human error.
Hot/cold and custodial/non-custodial are separate axes: an exchange is usually hot and custodial; a hardware device is usually cold and non-custodial only if the user generated and protects the seed. Keep only a working balance hot, verify addresses on the trusted device screen, and never disclose a seed/private key. See Ethereum’s account documentation and the CMC742 wallet note/reference.
14. Explain the lifecycle of a blockchain transaction from its initiation until it is confirmed in the blockchain.
A transaction is a signed request for a valid state change. The exact fields differ by chain; the following applies to a Bitcoin-style payment and, with account-model substitutions, to smart-contract chains.
user intent
↓
wallet selects inputs / builds call
↓
private-key signature
↓
P2P broadcast
↓
node validation + mempool
↓
miner/validator includes in candidate block
↓
consensus accepts block
↓
block replicated; confirmations/finality increase
- Initiation: the sender chooses a recipient, amount, fee and (for Bitcoin) UTXOs; a smart-contract user chooses
to, calldata, value, nonce, gas limit and fee. - Construction: the wallet serialises inputs/outputs or call data. Bitcoin’s input total must cover outputs plus fee; a change output may be created.
- Signing: the private key signs the transaction. Nodes can verify the signature using public information. The signature proves key control, not that funds exist or that the transaction is accepted.
- Broadcast: the wallet sends the signed transaction to a node; peers gossip it through the network.
- Validation: each node checks syntax, size, signature/script, nonce/UTXO existence and unspent status, amounts, fees, contract rules, and policy. Invalid transactions are rejected; valid unconfirmed transactions enter a mempool. Different nodes may temporarily hold different mempools.
- Selection/proposal: a miner or validator selects transactions, usually considering fee rate, constructs a candidate block, and adds the required commitments.
- Consensus: PoW miners find a target-valid header, PoS validators propose/attest, or permissioned validators endorse/order. Other nodes validate the block independently.
- Inclusion/confirmation: once the block is accepted on the chain, the transaction has one confirmation. A Bitcoin transaction gets additional confirmations as later blocks build on it; a BFT chain may provide deterministic finality after a quorum commit.
- State update: consumed Bitcoin UTXOs become spent and new outputs appear; an account/smart-contract chain updates balances/storage and may emit logs/events.
A conflicting unconfirmed transaction can briefly exist, but only one spend of the same UTXO can survive a valid Bitcoin history. “Confirmed” is not identical to “irreversible”: PoW confirmation gives increasing probabilistic confidence, while finality semantics depend on the protocol. The Bitcoin transaction guide and Ethereum transaction guide give protocol-specific details.
15. Explain the UTXO model used in Bitcoin with a suitable example.
UTXO means Unspent Transaction Output. Bitcoin does not maintain a single mutable balance field for each user. A transaction consumes previous outputs and creates new outputs. Each output contains a value and a locking script/condition; it remains a UTXO until a later valid transaction spends it. A wallet balance is the sum of UTXOs controlled by its keys.
Transaction form
inputs: references to previous txid:output-index + unlocking witness/script
outputs: amount + locking script/address
fee = sum(inputs) − sum(outputs)
Worked example: Alice controls two UTXOs:
UTXO A = 2.00 BTC
UTXO B = 2.00 BTC
She wants to pay Bob 3.00 BTC and chooses a 0.01 BTC fee.
Inputs: A + B = 4.00 BTC
Outputs: Bob = 3.00 BTC
Alice change = 0.99 BTC
Fee: 4.00 − 3.00 − 0.99 = 0.01 BTC
The wallet signs the inputs with the private key satisfying their locking conditions. Once confirmed, A and B are consumed and cannot be spent again. Bob owns a new 3 BTC UTXO; Alice owns a new 0.99 BTC change UTXO. The fee is the difference not assigned to an output and is available to the miner under Bitcoin’s rules.
Properties
- UTXOs are discrete “digital notes”; coin selection may combine many inputs.
- There may be multiple outputs, recipients, and change outputs.
- Every input must reference an existing, unspent output and satisfy its script/witness.
- A transaction with inputs less than outputs is invalid; the difference between inputs and outputs is the fee.
- A UTXO is not a wallet, address, or balance; it is one spendable output.
Lifecycle:
old output created → remains unspent → referenced as input
→ validation succeeds → marked spent
→ new outputs become UTXOs
This model makes ownership history explicit and lets nodes detect reuse. Bitcoin’s developer transaction guide defines inputs, outputs, UTXOs, scripts, and fees.
16. Analyze how the UTXO model prevents the double-spending problem in Bitcoin.
Double spending is an attempt to use the same digital value twice—for example, to spend one 5 BTC UTXO both to a shop and to the attacker’s own address.
T1: UTXO-5 → Shop 4.9 BTC + change
T2: UTXO-5 → Attacker 5 BTC
The UTXO model prevents ordinary double spending through the following checks:
- Unique outpoint: each output is identified by
(previous transaction hash, output index). A node maintains a UTXO set and knows whether that outpoint is unspent. - Input validation: a transaction input must point to an existing UTXO and satisfy its locking script/signature. A missing or already-spent outpoint is invalid.
- Atomic state transition: when a transaction is accepted into a block, its inputs are removed from the UTXO set and its outputs are added. The same UTXO cannot remain available to two accepted transactions in one valid state.
- Mempool conflict handling: two conflicting transactions may reach different nodes or appear briefly in mempools. Nodes generally keep/relay one according to policy, but mempool acceptance is not final ownership.
- Consensus ordering: if competing valid spends exist, the consensus-selected block/history determines which one is accepted. The other becomes invalid because its input is now spent.
- Proof-of-Work and confirmations: in Bitcoin, changing the winning transaction after inclusion requires rewriting its block and subsequent PoW. More confirmations increase the cost/probability barrier, though they do not create instant mathematical finality.
- Signatures: only the private-key holder can normally create a valid spend of the UTXO. This prevents unauthorised spending but is different from the “one outpoint cannot be consumed twice” rule.
Example: Alice broadcasts T1 and T2 spending the same 5 BTC UTXO. Both may have valid signatures because Alice signed both, but they conflict. If a miner includes T1 first and the network accepts it, the UTXO is removed; T2 fails the UTXO-existence/unspent check. If T2 wins first, T1 fails instead.
Limits: accepting an unconfirmed transaction exposes a merchant to race attacks; a miner or majority of hashpower may reorganise recent history; a signature does not guarantee settlement. Thus UTXO validation prevents two spends from coexisting in one accepted history, while consensus and confirmations protect the ordering of that history. See the Bitcoin double-spending/transaction explanation and whitepaper.
17. Explain the working of the Proof-of-Work (PoW) consensus mechanism. Discuss its advantages and limitations.
Proof-of-Work is a Sybil-resistant consensus mechanism in which miners spend computation searching for a value that makes a block-header hash satisfy a target. In Bitcoin:
SHA256d(block_header) ≤ target
Working
- Full nodes validate transactions and relay them to a mempool.
- A miner selects transactions, creates the coinbase reward transaction, computes the Merkle root, and builds a header containing the previous hash, time,
nBitstarget, and nonce. - The miner varies the nonce and, when necessary, extraNonce/transaction data, hashing repeatedly.
- Since hash outputs behave unpredictably, a smaller target means fewer acceptable outputs and a lower probability per attempt.
- A miner finding a valid header broadcasts the block and proof.
- Other nodes verify the hash, target, parent, Merkle root, transactions, signatures, UTXOs, and coinbase rules. A valid hash does not make invalid transactions acceptable.
- If multiple valid blocks compete, Bitcoin nodes follow the valid chain with the greatest cumulative work. Later blocks add confirmations.
Advantages
- Open-membership Sybil resistance: influence depends on costly hashpower, not the number of cheap identities.
- Simple verification: one hash and a target check are cheap for every node.
- Permissionless participation: no central validator registry is required.
- History-rewrite cost: an attacker must redo the altered block’s work and catch up with honest miners; a majority hash-rate attacker can nevertheless reorganise/censor within protocol limits.
- Battle-tested probabilistic settlement: honest miners are incentivised by block subsidy and fees.
Limitations
- Energy and hardware consumption: continuous hash racing consumes electricity and specialised equipment.
- Probabilistic finality/latency: users wait for confirmations; short forks and reorganisations are possible.
- Hashpower concentration: ASIC economics, electricity prices, geography, and pools can centralise influence.
- 51% risk: majority hashpower can censor or reorder/reverse recent transactions and double-spend its own funds, but cannot forge another user’s signature or create arbitrary valid coins.
- Throughput cost: all full nodes must verify and store blocks; raising limits can reduce node participation.
PoW therefore trades energy and time for open, economically weighted consensus. Proof-of-Stake, Proof-of-Burn, and PoET are alternative mechanisms, not simultaneous components of Bitcoin. See the Bitcoin mining guide and whitepaper §4.
18. Analyze the role of a miner in the Bitcoin blockchain. Explain the steps involved in mining a new block.
A Bitcoin miner performs two related roles: it assembles a candidate block from valid transactions and performs the PoW search that gives the block a chance to be accepted. A miner is not a central authority: full nodes independently reject invalid transactions or blocks.
Mining lifecycle
hardware/software/network setup
↓
receive and validate mempool transactions
↓
select transactions by validity, fee rate and block space
↓
create coinbase + Merkle root + header
↓
nonce/extraNonce/timestamp search
↓
valid hash found? ──no──> change search data and repeat
│ yes
↓
broadcast block → nodes verify → reward if accepted
- Connect and receive data: mining software obtains the current chain tip, target, transactions, and pool work if pool mining.
- Select transactions: check signatures/scripts, UTXOs, fees, dependencies, and block-size/weight limits. High-fee transactions may be preferred, but validity comes first.
- Create coinbase transaction: include the permitted subsidy and transaction fees, paying the miner/pool address; include an extraNonce if needed.
- Build the Merkle tree: hash transaction IDs pairwise to obtain the Merkle root.
- Construct the 80-byte header: set version, previous block hash, Merkle root, timestamp, compact target (
nBits), and nonce. - Perform PoW: calculate double SHA-256 for many nonce values. If all 32-bit nonce values are exhausted, modify the coinbase extraNonce, which changes the Merkle root and supplies a new search space.
- Broadcast: when
hash ≤ target, send the full block and proof to peers promptly; another miner may find a competing block meanwhile. - Network verification: nodes check the parent, target, PoW, Merkle root, all transactions, coinbase amount, and consensus rules.
- Reward/continue: if the block is accepted on the best chain, the miner earns the subsidy and fees subject to maturity/protocol rules; it then starts building on the new tip. If stale or invalid, it receives no valid block reward and must change work.
Pool miners submit easier-target shares to demonstrate contributed work; only a share meeting the network target is a valid Bitcoin block. Hardware ranges from CPU/GPU to FPGA/ASIC, but profitability depends on difficulty, hash rate, electricity, fees, reward, price, uptime, and pool terms. The Bitcoin mining guide describes candidate construction, shares, and block propagation.
19. Evaluate the impact of mining difficulty on Bitcoin mining and network security.
Bitcoin’s PoW rule uses a numeric target rather than a fixed number of human-readable zeros:
valid if H(block header) ≤ target
Difficulty is a relative measure of target hardness. A lower target means fewer acceptable hashes, lower probability per attempt, and greater expected work. It must be distinguished from:
- hash rate: attempts per second across miners;
- target: the threshold a hash must meet;
- difficulty: relative hardness compared with a reference target; and
- block interval: time between accepted blocks.
Effect on miners
- If network hash rate rises while the target is unchanged, blocks are found faster and each miner’s expected share of blocks falls unless it adds hashpower.
- At higher difficulty, the expected number of hashes and electricity/time per block rise. Inefficient miners may become unprofitable; specialised hardware and cheap electricity gain an advantage.
- If hash rate falls, blocks initially become slower and fee confirmation delays increase.
Retargeting: Bitcoin adjusts the target every 2,016 blocks (subject to protocol limits), using the time taken by the previous adjustment period, aiming for approximately the intended ten-minute average interval. It does not make a hash function “smarter”; it changes the acceptance threshold.
Security effects
- Higher difficulty raises attack cost: an attacker must perform more work to create an alternative chain and overtake honest cumulative work.
- Predictable issuance/settlement: retargeting stabilises block production and therefore the approximate schedule of rewards and confirmations.
- Hash-rate security is dynamic: difficulty alone does not guarantee safety. If the honest network hash rate falls, an attacker may need less absolute hardware to obtain a majority; if hash rate rises, a fixed attacker may represent a smaller fraction.
- Centralisation pressure: high difficulty increases capital, power, cooling, and ASIC requirements, encouraging pools and industrial farms. Pool concentration may threaten censorship resistance even without a successful majority attack.
- Temporary effects: after a sudden hash-rate increase or decrease, blocks can be temporarily faster/slower until the next adjustment; outages can reduce security and delay transactions.
Thus difficulty is both a liveness control and a security/economic barrier. It creates no protection if nodes fail to validate transactions, and a 51% hash-rate attacker can still reorganise recent history within the limits of valid rules. See Bitcoin’s developer block-chain guide and mining guide.
20. Explain the concept of mining pools. Compare any two mining pool reward distribution methods.
A mining pool coordinates many miners. The pool operator supplies candidate work, usually with a target easier than Bitcoin’s network target, and miners return shares. A share proves that a miner performed measurable work and lets the pool estimate each participant’s contribution. Occasionally a share also satisfies the network target; then it is a valid block, which the pool broadcasts. The pool receives the block subsidy and fees and distributes proceeds according to its method, less fees.
Pool flow
pool creates work → miners hash and submit shares
→ pool measures each miner's work
→ one share may meet network target
→ pool broadcasts block
→ reward distributed by scheme
Compare PPS and PPLNS:
| Feature | PPS — Pay Per Share | PPLNS — Pay Per Last N Shares |
|---|---|---|
| Payment basis | Fixed expected value for every accepted share | Share of an actual pool reward based on the last N eligible shares when a block is found |
| Timing/variance | Frequent and relatively predictable; paid even during a short unlucky period | More variable; no block means no block payout and the rolling window affects the amount |
| Luck risk | Pool operator bears most short-term block-finding variance | Miner bears more pool-luck variance |
| Fees/transaction fees | Often higher pool fee; basic PPS may pay expected subsidy but not all transaction-fee value | Based on actual block proceeds according to the pool’s policy; fee treatment must be checked |
| Incentive | Stable cash flow, but operator must price risk | Rewards continued contribution and can reduce pool-hopping incentives; joining/leaving affects the N window |
Illustrative formulae
PPS payment ≈ accepted shares × expected value/share − pool fee
PPLNS payment ≈ (miner shares in last N / total eligible shares in last N)
× actual block proceeds − pool fee
PPS reduces income variance but exposes miners to operator solvency, fee, and share-accounting risk. PPLNS can produce better alignment with actual pool revenue but requires continuous participation and tolerating variance. Neither changes Bitcoin’s PoW or creates extra network hashpower; a large pool can, however, create centralisation/governance risk. FPPS is a related method that adds an estimated transaction-fee component to PPS. The Bitcoin mining guide explains shares; the f2pool payout comparison gives current practical definitions. Always inspect a pool’s exact fee, stale-share, payout-threshold, and fee-treatment rules.
Module III
21. Explain the concept of a Smart Contract. Discuss its characteristics and applications in blockchain.
A smart contract is a program deployed on a blockchain that stores state and executes deterministic rules when called by a transaction or another contract. It is not necessarily a complete legal contract; it is machine-executable logic that can automate specified conditions and state transitions.
specification → Solidity/code → compile/deploy → contract address
↓
transaction/input → deterministic execution
↓
state update + logs/asset transfer
Characteristics
- Deterministic: honest nodes execute the same bytecode and inputs to obtain the same result.
- Self-executing within scope: once the trigger and preconditions are satisfied, the programmed action occurs without a clerk manually applying it.
- Persistent state: variables such as balances, ownership, votes, or order status remain at the contract address.
- Transparent/auditable: public-chain code, transactions, state changes, and events can be inspected, subject to privacy design.
- Tamper-resistant: a deployed contract cannot ordinarily be edited by an arbitrary user; upgradeability requires explicit proxy/governance design.
- Atomic: a transaction either commits its valid state changes or reverts them when an error occurs (subject to external effects/log semantics).
- Gas/resource bounded: EVM execution consumes gas; unbounded loops and expensive storage can make calls fail or cause denial of service.
- Key/permission controlled:
msg.sender, signatures, roles, and modifiers determine who may invoke operations. - Oracle-dependent for external facts: code cannot directly know weather, delivery, identity, or a market price; an oracle supplies data and creates a trust boundary.
Applications
- token issuance, transfers, and NFTs;
- escrow, payments, lending, decentralised exchanges and insurance;
- DAOs for proposals, voting, and treasury control;
- supply-chain events and provenance;
- certificates/credentials and document notarisation;
- IoT devices that act on sensor conditions;
- smart legal/automated agreements and royalty distribution.
A DApp is larger than a contract: it combines a front end, wallet, one or more contracts, and possibly off-chain services. A contract can execute bad logic perfectly if input or specification is wrong. Other limitations include bugs, key loss, privacy, legal enforceability, scalability, and irreversible state. Ethereum’s smart-contract documentation and the CMC742 reference material provide the platform context.
22. Explain the different types of Smart Contracts with suitable examples.
Smart-contract types can be classified by what they automate and how much of the surrounding application/legal process is on-chain.
- Smart legal contracts: A legally recognised agreement is represented partly in natural language and partly in code. Code automates objectively checkable terms, while legal text handles identity, exceptions, remedies, and jurisdiction. Example: an escrow contract releases payment after an authorised inspection oracle confirms delivery, while a legal agreement handles disputes and fraud.
- Decentralised applications (DApps): An end-to-end application combines a blockchain contract backend with a user interface, wallet, and possibly off-chain indexing/storage. Example: a token exchange front end calls liquidity-pool contracts; the contract holds rules and assets, while the UI presents quotes and signs transactions.
- Decentralised autonomous organisations (DAOs): Contracts implement proposals, voting, treasury rules, membership or delegation. Stakeholders govern according to programmed quorum and execution conditions rather than one central administrator. Example: a DAO proposal reaches quorum and transfers funds from a multisignature/governance treasury.
- Smart-contracting devices / IoT contracts: A physical device or sensor submits authenticated data and triggers a coded action. Example: a cold-chain sensor reports a temperature breach and the contract flags a shipment or pauses payment. The sensor/oracle remains a trust dependency.
- Financial/asset contracts: Code manages tokens, escrow, lending, swaps, derivatives, royalties, or insurance. Example: an ERC-20 token contract maps addresses to balances and emits
Transferevents; a lending contract records collateral and repayment. - Record and verification contracts: A contract stores hashes, ownership, status, or revocation records while the actual document remains off-chain. Example: a university publishes a certificate hash and later appends a signed revocation status.
These categories overlap: a DAO is a DApp, and a DApp may contain token, legal, financial, and oracle contracts. The essential distinction is the application role, not a different EVM execution model. A contract is deterministic only over the data supplied to it; software oracles, hardware sensors, inbound/outbound oracles, and consensus oracles connect it to the external world but add trust and failure surfaces. Ethereum smart contracts and the supplied CMC742 reference describe the contract, DApp, DAO, and oracle categories.
23. Draw and explain the structure of a Smart Contract. Describe the purpose of each component.
A current Solidity contract can be represented as follows:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "./IERC20.sol"; // optional dependency
contract Example is Ownable { // name + inheritance
using SafeLib for uint256; // optional library attachment
uint256 private value; // persistent state
mapping(address => bool) public approved;
error NotApproved(address caller); // custom error
event ValueChanged(address indexed by, uint256 value); // log
modifier onlyApproved() { // reusable precondition
if (!approved[msg.sender]) revert NotApproved(msg.sender);
_;
}
constructor(uint256 initialValue) Ownable(msg.sender) {
value = initialValue; // one-time deployment setup
}
function setValue(uint256 next) external onlyApproved {
value = next; // state-changing behaviour
emit ValueChanged(msg.sender, next);
}
function getValue() external view returns (uint256) {
return value; // read-only behaviour
}
receive() external payable {} // plain Ether transfer
fallback() external payable {} // unknown calldata/no match
}
Components
- SPDX licence and
pragma: records licensing and constrains compiler compatibility. It is not a runtime security control. - Imports: bring interfaces, libraries, or inherited code into the compilation unit.
- Contract declaration/name: defines the deployable type and may list base contracts/interfaces after
is. - State variables: persistent storage at the contract address; public variables generate getter functions, while
privatemeans source-level access restriction—not secrecy on a public chain. - Structs/enums/arrays/mappings: define structured persistent data collections.
- Events: transaction logs for off-chain applications/indexers. They are not a replacement for state needed by contract logic.
- Errors: custom, ABI-visible failure types; modern Solidity custom errors are often cheaper than long revert strings.
- Modifiers: reusable checks or pre/post logic;
_inserts the protected function body. - Constructor: runs once during deployment to initialise state and configure inherited constructors; it is not callable afterwards.
- Functions: executable interface. Visibility controls who can call; mutability (
view,pure,payable) restricts read/write/value behaviour. receiveandfallback:receivehandles empty-calldata Ether transfers;fallbackhandles unmatched function selectors and may be payable. They should be minimal and deliberate.- Libraries/interfaces: libraries provide reusable code; interfaces describe callable function signatures and support decoupled contracts.
Deployment relationship
Solidity source → compiler → ABI + creation/runtime bytecode
→ deployment transaction + gas → contract address/state
→ client uses ABI + address for calls/transactions
The Solidity contract-structure documentation and types/contracts documentation define the current syntax. A contract’s exact components vary, but state, behaviour, access control, events/errors, construction, and Ether-entry points are the main structural units.
24. Explain the different approaches used for Smart Contract development. Discuss the advantages of any one approach.
Smart-contract development can be approached as a spectrum according to how the agreement is specified, executed, and connected to external systems.
- Code-only / fully automated approach: Conditions, state transitions, permissions, and outcomes are expressed directly in Solidity/EVM code. Example: an ERC-20 transfer checks balances and updates mappings without a human administrator.
- Natural-language plus code (hybrid/legal) approach: Natural-language terms define the broader legal agreement; code automates only precise, objective clauses. Oracles, authorised roles, and dispute/upgrade procedures handle facts the chain cannot observe. Example: code releases escrow after a signed delivery attestation, while the legal agreement defines fraud and court remedies.
- Template/formal-specification-first approach: Start with a state machine, invariants, threat model, permissions, and formal properties; derive code from the reviewed specification and verify it with static analysis, tests, symbolic execution, or formal methods. This is useful for high-value contracts.
- Framework/library/composable approach: Build from audited interfaces, standard libraries, access-control modules, and established patterns (for example ERC interfaces), rather than writing every primitive from scratch. Dependencies still require version and security review.
- Prototype → testnet → audited deployment approach: Develop in Remix/local chains, test happy and failure paths, fuzz and analyse, deploy to a test network, conduct an audit/bug bounty, then deploy an immutable or governed production version. This is a lifecycle approach and should accompany the code/legal choices above.
Advantages of the hybrid legal-plus-code approach
- It automates the deterministic, high-volume part while retaining human/legal remedies for ambiguous or real-world conditions.
- It acknowledges the oracle problem instead of pretending sensor/data input is automatically true.
- It can specify identity, jurisdiction, dispute resolution, emergency pause, revocation, and upgrade governance outside the rigid execution path.
- It reduces the risk that a small coding ambiguity becomes an irreversible economic result.
- It is practical for supply chain, insurance, property, and certificates where some facts are off-chain.
Example:
legal agreement: seller must deliver conforming goods by date D
code: escrow funds + state machine + release/refund transitions
oracle: authenticated inspection result
exception: dispute window → human/arbitrator decision
The disadvantage is complexity: two representations can diverge, and the oracle/arbitrator becomes a trust boundary. Code-only may be simpler and more deterministic for purely digital assets, but it cannot express every legal or physical-world fact. Good development therefore starts from a precise specification and threat model, uses minimal code, tests failure cases, and makes any trust/upgrade path explicit. See Ethereum smart-contract development and Solidity security considerations.
25. Explain the limitations of Smart Contracts and suggest suitable measures to overcome any two limitations.
Major limitations
- Code bugs and irreversible execution: A deployed bug can lock or transfer assets; immutable code will faithfully execute wrong logic.
- Oracle/input problem: A contract cannot directly observe physical delivery, weather, identity, or off-chain prices. It can reach consensus on false data.
- Scalability and gas: Every node re-executes state-changing code; storage and loops consume gas, and unbounded loops can fail or cause denial of service.
- Privacy: Public contract state and call data can reveal balances, votes, business relationships, or personal information.
privateSolidity visibility does not make blockchain storage secret. - Legal/enforcement limits: Code cannot by itself identify a real person, seize a physical asset, resolve ambiguity, or guarantee a court will enforce the result.
- Key and access-control risk: A stolen owner/admin key can invoke privileged functions; lost keys may make recovery impossible.
- Upgrade/governance dilemma: Immutable contracts are hard to fix; upgradeable proxies add admin trust, storage-layout and governance risks.
- Determinism and composability risk: External calls, reentrancy, gas changes, and dependencies can cause unexpected behaviour; all nodes must reach the same result.
Measures for limitation 1 — bugs/irreversibility
- Use a small, modular design and established audited standards/libraries.
- Apply checks-effects-interactions, least-privilege roles, reentrancy guards where needed, and custom errors.
- Perform unit/integration/fuzz/property testing, static analysis, symbolic/formal verification for critical invariants, independent audit, and bug bounty.
- Add a narrowly scoped pause/emergency response, timelocked governance, rate limits, and multisignature administration. Document whether and how upgrades are possible; do not call a privileged upgrade “immutable.”
Measures for limitation 2 — oracle/input risk
- Use multiple independent authenticated data sources and an aggregation/median rule instead of one feed.
- Require signed attestations, freshness/nonce checks, bounds, collateral/slashing, and a dispute/challenge window.
- Record provenance and oracle version on-chain; define fallback/manual arbitration for exceptional cases.
- Keep sensitive/raw data off-chain and commit only a hash or verifiable proof.
Measures for scalability/privacy (alternatives)
- Bound loops, paginate work, batch transactions, avoid unnecessary storage, use layer-2/rollups/channels or a permissioned chain where appropriate.
- Store only hashes/commitments, encrypt off-chain data, use selective disclosure/zero-knowledge proofs, and minimise public metadata.
No measure removes the underlying trade-off: a pause key, oracle committee, or upgrade admin adds trust. The correct answer is therefore a documented threat model that states what is automated, who can intervene, and what is deliberately kept off-chain. See Solidity security considerations.
26. Explain the role of functions, visibility specifiers, and state mutability qualifiers in Solidity with suitable examples.
A function is executable contract behaviour. It may read state, change state, receive Ether, call other contracts, emit events, and return values. A function declaration has the form:
function name(uint x)
external
view
returns (uint)
{
return x;
}
Visibility specifiers
| Specifier | Callable from | Typical use |
|---|---|---|
external | External message calls; external interface | Public API functions; parameters can use calldata efficiently |
public | External callers and internal calls | General interface when both call styles are required |
internal | This contract and derived contracts | Reusable implementation helpers |
private | This contract only; not derived contracts | Local implementation helper |
Visibility is an access/interface rule, not confidentiality. Even a private state variable is observable in public-chain storage; it merely prevents Solidity-level direct access.
State mutability qualifiers
| Qualifier | Permitted behaviour | Example |
|---|---|---|
view | Reads state but must not modify it | function balance() external view returns (uint) |
pure | Reads neither state nor blockchain context; computes from arguments/literals | function add(uint a,uint b) external pure returns(uint) |
payable | Permits Ether to accompany the call | function deposit() external payable |
| omitted/nonpayable | Default; rejects unexpected Ether and may change state | function set(uint x) external |
Current Solidity example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Qualifiers {
uint256 private count;
address public immutable owner;
constructor() {
owner = msg.sender;
}
function increment() external {
count += 1; // state-changing transaction
}
function getCount() external view returns (uint256) {
return count; // read-only call
}
function add(uint256 a, uint256 b)
external pure returns (uint256)
{
return a + b;
}
function deposit() external payable {
// msg.value is the Ether sent with this call
}
function ownerOnly() external view returns (address) {
return owner;
}
}
msg.sender is the immediate caller; msg.value is the wei sent. A view read made directly through an RPC node normally does not create a state-changing transaction, whereas increment and deposit require a signed transaction and gas. payable allows value; it does not require a nonzero value. Use modifiers or explicit checks for access control:
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
The Solidity functions documentation and state mutability documentation define current visibility and qualifier behaviour.
27. Differentiate between address and address payable in Solidity. Illustrate their usage with suitable examples.
Both are 20-byte Ethereum address types, but they express different intent and permitted Ether operations.
| Type | Meaning/use |
|---|---|
address | Identifies an account or contract and supports address information such as balance; use where no direct Ether transfer is required. |
address payable | An address explicitly permitted by the type system to receive Ether through payable transfer operations such as call{value: ...}. |
A plain address can be explicitly converted to payable with payable(a) when the programmer has established that sending Ether is intended. A payable address can be assigned to an ordinary address.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Payments {
address public treasury; // identity/administrative reference
address payable public recipient; // intended Ether destination
constructor(address payable initialRecipient) {
treasury = msg.sender;
recipient = initialRecipient;
}
function setRecipient(address payable next) external {
require(msg.sender == treasury, "not treasury");
recipient = next;
}
function sendEther(uint256 amount) external {
require(msg.sender == treasury, "not treasury");
require(address(this).balance >= amount, "insufficient balance");
(bool ok, ) = recipient.call{value: amount}("");
require(ok, "transfer failed");
}
function sendTo(address destination, uint256 amount) external {
// Explicit conversion documents that Ether transfer is intended.
address payable to = payable(destination);
(bool ok, ) = to.call{value: amount}("");
require(ok, "transfer failed");
}
receive() external payable {}
}
call is commonly preferred over transfer/send because the 2300-gas stipend assumptions behind those older operations can make legitimate recipients fail after gas-cost changes. A low-level call returns (success, returndata), so the contract must check success and consider reentrancy: use checks-effects-interactions, a reentrancy guard, pull payments, or another appropriate design. address payable does not verify that a recipient is honest or that a contract has a payable receive/fallback; a transfer can still fail.
A contract address is not automatically a user identity, and type conversion does not grant permission. The Solidity address-type documentation specifies the current distinction and payable(addr) conversion.
28. Explain the use of arrays, structures (struct), and mappings in Solidity. Illustrate each with a suitable example.
These are Solidity reference types used to model collections and records. Their data location (storage, memory, or calldata) matters for arrays/structs and for gas/copy semantics.
Arrays
An array is an ordered, zero-indexed collection. T[k] is fixed-size; T[] is dynamic.
uint256[3] public fixedScores;
uint256[] public scores;
function addScore(uint256 score) external {
scores.push(score); // dynamic storage array
}
function removeLast() external {
require(scores.length > 0, "empty");
scores.pop();
}
Fixed arrays have a compile-time length; dynamic storage arrays can grow/shrink with suitable operations. delete scores[i] resets an element to its default value but does not necessarily close the gap or reduce length. Arrays are useful when order/enumeration is required, but large loops can exceed the gas limit.
Structs
A struct defines a custom record grouping related fields:
struct Student {
string name;
uint256 rollNo;
bool active;
}
Student[] public students;
function addStudent(string calldata name, uint256 rollNo) external {
students.push(Student({name: name, rollNo: rollNo, active: true}));
}
Structs improve domain modelling and keep fields together. They do not automatically enforce business rules; functions must validate updates.
Mappings
A mapping is a key-to-value association:
mapping(address => uint256) public balanceOf;
mapping(address => bool) public hasVoted;
mapping(uint256 => Student) private byRoll;
balanceOf[a] and hasVoted[a] provide direct lookup. An unmapped key returns the value type’s default (0, false, or an empty value), so a separate existence flag may be necessary. Mappings are storage-only, have no length, and cannot be enumerated; keep an array of keys/records when iteration is needed.
Combined voting model
struct Candidate { string name; uint256 votes; }
Candidate[] public candidates;
mapping(address => bool) public hasVoted;
function vote(uint256 index) external {
require(index < candidates.length, "bad index");
require(!hasVoted[msg.sender], "already voted");
hasVoted[msg.sender] = true;
candidates[index].votes += 1;
}
The array lists candidates in order, the struct groups name/count, and the mapping provides efficient per-address eligibility. A mapping alone could not tell a client all candidate keys; an array alone would make duplicate-voter lookup inefficient. The Solidity reference types documentation covers data locations, arrays, structs, and mappings.
29. Analyze the role of inheritance and error handling mechanisms in Solidity. Explain how they improve the reliability of smart contracts.
Inheritance
Inheritance lets a derived contract reuse and extend state/functions from a base contract. It supports modular access control, common interfaces, reusable standards, and polymorphism.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
abstract contract Ownable {
address public owner;
error NotOwner(address caller);
constructor() { owner = msg.sender; }
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwner(msg.sender);
_;
}
function label() public pure virtual returns (string memory) {
return "base";
}
}
contract Registry is Ownable {
mapping(bytes32 => string) public records;
function set(bytes32 id, string calldata value) external onlyOwner {
records[id] = value;
}
function label() public pure override returns (string memory) {
return "registry";
}
}
virtual permits overriding and override makes the override explicit. Solidity supports multiple inheritance with a linearisation order, so base order and constructor execution must be understood. Interfaces provide function signatures without implementation; libraries package reusable code. Inheritance improves reliability when audited, minimal, well-tested modules centralise a rule (for example ownership) and prevent inconsistent copies. It harms reliability when a developer inherits an unsuitable contract, misunderstands storage/layout/initialisers, or adds unnecessary complexity; inspect all dependencies.
Error handling
Errors prevent invalid state transitions and make failure explicit:
require(condition, "message"): caller-controlled preconditions, permissions, input ranges, balances, deadlines. If false, execution reverts.revert CustomError(args): explicit branch failure; custom errors are ABI-visible and generally cheaper than long strings.assert(condition): internal invariant that should never fail; not ordinary user input validation.- Custom errors: typed failure data, e.g.
error Unauthorized(address caller);. try/catch: external contract calls/creation can be wrapped so a caller contract can handle failure; it does not make an unsafe external call safe.- Events: emit successful state-change history for off-chain observers, but do not replace state or error checks.
error InvalidAmount(uint256 amount);
error NotEnough(uint256 available, uint256 requested);
function withdraw(uint256 amount) external {
if (amount == 0) revert InvalidAmount(amount);
uint256 available = balances[msg.sender];
if (available < amount) revert NotEnough(available, amount);
balances[msg.sender] = available - amount; // effects first
(bool ok, ) = payable(msg.sender).call{value: amount}("");
require(ok, "payment failed");
}
When a checked failure occurs, the call’s state changes are reverted, protecting atomicity; gas may still be consumed for work performed. Correct errors improve reliability by rejecting invalid inputs, enforcing permissions, preserving invariants, and making client failures diagnosable. They do not fix bugs in unchecked arithmetic/logic, external reentrancy, bad oracles, compromised keys, or incorrect requirements.
Combined reliability practices: use least-privilege inheritance, explicit virtual/override, audited dependencies, checks-effects-interactions, reentrancy protection where needed, custom errors, bounded loops, tests/fuzzing/formal checks, and independent audits. See Solidity inheritance and Solidity error handling.
30. Design the logic of a blockchain-based Voting Smart Contract. Identify the essential state variables, functions, and mappings required for its implementation. (Flowchart or pseudocode may be used instead of Solidity code.)
Assumptions for an educational contract: one vote per registered address, public/non-secret ballots, a fixed voting period, and a trusted administrator who registers candidates/voters. This is not a national-election design: an address is not a verified person, and public-chain votes are observable.
State model
struct Candidate {
string name;
uint256 voteCount;
}
Candidate[] public candidates; // enumerate candidates
mapping(address => bool) public isRegistered;
mapping(address => bool) public hasVoted; // prevent repeat address vote
mapping(address => uint256) public choice; // optional audit of choice
address public admin;
uint256 public startTime;
uint256 public endTime;
bool public finalised;
uint256 public winningCandidate;
Optional variables include mapping(address => uint256) votingPower, role sets, proposal ID, quorum, a commitment hash for a commit-reveal ballot, a revocation/eligibility snapshot, and an event sequence number. Do not store unnecessary personal data on-chain.
Essential functions
constructor(candidates, start, end): set admin, validate time interval, add initial candidates.registerVoter(address voter): admin-only; setisRegistered[voter] = truebefore voting starts.addCandidate(string name): admin-only and before voting starts; append a candidate.open/closeor time checks: enforcestartTime ≤ block.timestamp < endTime; never rely on a user-supplied time.vote(uint256 candidateId): check phase, registration, not already voted, valid candidate, and optional voting power; mark voter before incrementing; increment count; emitVoteCast.getCandidate(uint256 id)/candidateCount():viewfunctions for clients.finalise(): after deadline and once only; compute winner under an explicit tie rule; setfinalised; emitElectionFinalised.winner(): return final result, or compute/read stored result.pause/emergency(optional): multisignature/admin-controlled emergency response with a documented policy.
Pseudocode
DEPLOY:
require(admin != zero)
require(start < end)
candidates = supplied list
phase = SETUP
REGISTER(voter) [admin only, before start]:
require(voter != zero)
require(now < start)
isRegistered[voter] = true
VOTE(candidateId) [transaction]:
require(now >= start && now < end)
require(isRegistered[msg.sender])
require(!hasVoted[msg.sender])
require(0 <= candidateId < candidates.length)
hasVoted[msg.sender] = true // effects before external calls
choice[msg.sender] = candidateId // optional public audit
candidates[candidateId].voteCount += 1
emit VoteCast(msg.sender, candidateId)
FINALISE:
require(now >= end)
require(!finalised)
winner = first candidate with maximum voteCount
// or set TIE state if the maximum is not unique
finalised = true
emit ElectionFinalised(winner)
READ:
return candidates, counts, finalised, winner
Flowchart
Start
↓
Is call after start and before end? ──No──> Reject
↓ Yes
Is voter registered? ──No──> Reject
↓ Yes
Has voter already voted? ──Yes──> Reject
↓ No
Is candidate ID valid? ──No──> Reject
↓ Yes
mark hasVoted → increment candidate → emit event → success
↓
After end: finalise once → determine tie/winner → publish result
Security and design justification: use role-based access/multisignature admin keys, a voter-registration audit, explicit phase/deadline and tie rules, checks-effects-interactions, custom errors, bounded winner calculation, and tests for duplicate/invalid/late votes. An open public chain needs Sybil resistance or verified eligibility; otherwise one person can create many addresses. A public transparent ballot is not secret. For a secret ballot, use commit-reveal (voter commits hash(choice || salt) then reveals) or a privacy-preserving credential/zero-knowledge design; commit-reveal must handle non-reveal incentives and does not by itself prove one person has one identity. A production election also needs legal authority, accessibility, coercion resistance, audits, key recovery, and a trustworthy registration process.
The core mapping/struct/array design follows the Solidity data-type documentation and the voting case-study logic in the CMC742 reference material.
Sources
- CMC742 supplied Blockchain reference material
- S. Nakamoto, Bitcoin: A Peer-to-Peer Electronic Cash System
- Bitcoin Developer Guide — Transactions
- Bitcoin Developer Guide — Block Chain
- Bitcoin Developer Guide — Mining
- Ethereum developer documentation — Accounts, Transactions, and Smart contracts
- Solidity documentation — Types and reference types
- Solidity documentation — Contracts, functions and inheritance
- Solidity documentation — Security considerations
- Hyperledger Fabric — Ordering service
- Castro and Liskov, Practical Byzantine Fault Tolerance
- f2pool — PPS, PPLNS and FPPS payout schemes
- U.S. SEC — Framework for “Investment Contract” Analysis of Digital Assets