This Python code simulates a simple Proof of Work by finding a nonce that makes the hash start with '00'. What will it print?
import hashlib def proof_of_work(data): nonce = 0 while True: text = f'{data}{nonce}' hash_result = hashlib.sha256(text.encode()).hexdigest() if hash_result.startswith('00'): return nonce nonce += 1 nonce_found = proof_of_work('blockchain') print(nonce_found)
Try running the code or understand that the nonce is the smallest number making the hash start with '00'.
The code increments nonce until the SHA-256 hash of 'blockchain' plus nonce starts with '00'. The first such nonce is 523.
In blockchain, which consensus mechanism relies on a fixed group of trusted validators voting to agree on the next block?
Think about consensus designed for permissioned blockchains with known validators.
PBFT uses a fixed set of validators who vote to reach consensus, suitable for permissioned blockchains.
Consider this Python code that selects a validator weighted by stake. What error will it raise when run?
import random validators = {'Alice': 50, 'Bob': 30, 'Charlie': 20} weights = list(validators.values()) selected = random.choices(list(validators.keys()), weights=weights, k=1) print(selected[0]) # Now test with an empty validators dict validators = {} weights = list(validators.values()) selected = random.choices(list(validators.keys()), weights=weights, k=1) print(selected[0])
What happens if you try to pick weighted choices from an empty list?
random.choices raises ValueError if weights are empty or all zero, which happens when validators dict is empty.
Among these consensus methods, which one is known for low energy use and selects block creators based on how many tokens they own?
Think about the method that replaces mining with stake-based selection.
Proof of Stake uses token ownership to select validators, avoiding energy-heavy mining.
This Python code simulates adding blocks with a simple consensus check. How many blocks will the blockchain contain at the end?
blockchain = ['Genesis'] class Block: def __init__(self, data, prev_hash): self.data = data self.prev_hash = prev_hash def hash(self): return hash((self.data, self.prev_hash)) # Simulate adding blocks only if prev_hash matches last block's hash for i in range(1, 6): last_block = blockchain[-1] last_hash = hash(last_block) if isinstance(last_block, str) else last_block.hash() new_block = Block(f'Data {i}', last_hash) # Consensus check: accept block only if prev_hash matches last_hash if new_block.prev_hash == last_hash: blockchain.append(new_block) print(len(blockchain))
Count the genesis block plus all accepted blocks.
The genesis block is first. Each new block's prev_hash matches last block's hash, so all 5 blocks are added. Total length is 6.