Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Distributed Ledger StudioBlockchain for IoTExperimentsWorkspaces
ENGINEERING WORKSPACE
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
BLOCKCHAIN FOR IOT
Blockchain for IoT

B02 · Merkle trees and inclusion proofs

Ask Dr. Mohammad · B02 →

Construct a four-leaf Merkle tree and verify inclusion against a trusted root.

Design experiment & verify evidence →
B02 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Blockchain foundationsB02 · Merkle trees and inclusion proofs

Before you start

Learning outcome: Construct a four-leaf Merkle tree and verify inclusion against a trusted root.

Use the offline browser model with fictional values. Web Crypto must be available for actual SHA-256. If unavailable, start the local website server and open localhost. No wallet or blockchain network is required.

Recommended predecessors: B01

Predict: Write down the expected positive and negative outcomes in the notebook before proceeding.

Related course access: IoT Security and Privacy — same laboratory, notebook and completion record.

B02 · Academic orientation

Scope and objectives

Scope of the experiment

Calculate and independently verify a four-leaf binary Merkle tree.

The focus of this experiment is to construct ordered Merkle parent hashes and inclusion paths. Students then trace sibling selection and root recomputation, and verify accepted and rejected proofs against a trusted root. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.

Learning objectives

  • Construct ordered Merkle parent hashes and inclusion paths.
  • Trace sibling selection and root recomputation.
  • Verify accepted and rejected proofs against a trusted root.
  • Identify the configured inputs (Leaf 0; Leaf 1; Leaf 2; Leaf 3; Selected index) and record the corresponding observed outputs with units where applicable.
  • Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.

Expected learning outcomes

On completion, students can construct ordered Merkle parent hashes and inclusion paths, trace sibling selection and root recomputation, and verify accepted and rejected proofs against a trusted root.

Required deliverables

Submit the derivation or state trace for the named operation, the exact reference and changed configurations, the associated simulator or practical evidence, and a short validation statement addressing verify accepted and rejected proofs against a trusted root. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to B03 · Distributed agreement and finality.

Environment and experimental methodology

The listed browser model and experiment-specific local Python, Solidity or EVM workflow, where provided. Do not treat a model as a deployed ledger.

Begin with a manual prediction, record the baseline, change one independent condition at a time, and compare the resulting trace or measurements with the original prediction. Record observations and uncertainty separately from reference values. Follow the experiment’s specific procedure, safety limits, and acceptance checks.

Understand the experiment

Merkle tree · ordered inclusion proof

Four leaves · highlight the proof of transaction T3 (zero-based index 2)
Four leaves · highlight the proof of transaction T3 (zero-based index 2)

Scientific architecture · Four-leaf proof packet verifier

Scientific concept map: Four records — Leaf data; Leaf hashes — H(A)…H(D); Parent hashes — Ordered concatenation; Merkle root — Commitment; Proof — Sibling path verification.
Scientific concept map: Four records — Leaf data; Leaf hashes — H(A)…H(D); Parent hashes — Ordered concatenation; Merkle root — Commitment; Proof — Sibling path verification.

Scientific foundations and analytical reasoning

A Merkle root recursively commits ordered leaf hashes. Inclusion verification needs sibling values, orientation and a trusted root.

Before operating the equipment or executing the program, derive the expected outcome using the required theoretical work in Experiment. Use the diagram to identify the variables and system boundaries.

Scientific theory · Merkle tree construction

A Merkle tree combines ordered child hashes into parent hashes until a root remains. The serialization and odd-leaf rule must be consistent across producer and verifier. A proof contains siblings and their orientation, requiring only logarithmic path length in a balanced tree.

Worked example and engineering interpretation

For four leaves A,B,C,D, root=H(H(H(A) ∥ H(B)) ∥ H(H(C) ∥ H(D))). A proof for B includes H(A) on the left and the C/D parent on the right. Swapping the order changes the computed root under the same encoding.

Engineering principles · additional worked teaching example

For a balanced binary Merkle tree, each proof level contributes one sibling hash. Eight leaves need three siblings; a proof for index 3 starts with leaf2 on left. Ordered concatenation matters.

From theory to experiment

Predict the reference result before operating the workbench; check the actual intermediate state, units and constraints. The existing simulation, implementation and procedure below are distinct sources of evidence.

How to investigate B02 · Merkle trees and inclusion proofs

Construct a four-leaf Merkle tree and verify inclusion against a trusted root.

Analytical investigation means collecting an observation, identifying the mechanism, using a calculation or state trace to explain it, and checking your conclusion against evidence. Controlled comparison means changing one independent variable, holding the remaining relevant conditions constant, and measuring a dependent variable against a baseline. Experimental validation means comparing a predicted result to a reproducible observation or assertion; agreement inside a model does not certify hardware. Evidence-based reasoning connects a specific observation to a theoretical rule and states uncertainty, not merely an opinion. Performance characterization records a named metric and its units across conditions; sensitivity analysis changes one parameter across several values. A threat assessment links an asset, threat, consequence and evidence to a mitigation.

Experiment-specific guided practice

Objective: Construct a four-leaf Merkle tree and verify inclusion against a trusted root.

  1. Use leaves T1–T4 and verify T1 at index zero. Inspect seven computed digests and two siblings.
  2. Change candidate only. The trusted root stays fixed.
  3. Select index 3 and T4. Compare sibling sides.
  4. Modify proof order or sibling digest and inspect the failing computed root.

Reference check: Four leaves require 7 digests and 2 proof siblings; eight require 15 digests and 3 siblings. Modified candidate fails against the original root.

Model boundary: Domain-separated UTF-8 encoding matches the existing teaching labs; not Bitcoin double-SHA256 byte serialization or Ethereum Keccak. Inclusion does not establish finality or source truth.

Independent task and submission evidence

2. Change candidate only. The trusted root stays fixed. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.

Before execution write the independent variable and its levels, dependent observation with units where applicable, baseline, controlled variables, measurement method and expected result. For a state machine use state/event/output rather than inventing a numeric metric. Record failures and repeat the baseline. A weak conclusion is “it works”; a supported conclusion names the changed setting, observed value/state, corresponding rule and one limitation.

TrialChanged settingFixed settingsPredicted resultActual observation / unitsEvidence / uncertainty
A: baselineReferenceRecordPredictRecordRecord
B: one changeRecordSame as APredictRecordRecord
A: repeatRestoreSame as APredictRecordRecord

Completion: submit the filled table, relevant simulator screenshot or terminal/notebook output, reasoning with units/assumptions, and one limitation. Preserve the independent assessment questions; this guide does not fill their answers.

Worked engineering reasoning and boundary conditions

Engineering reference configuration: Leaf 0 = T1; Leaf 1 = T2; Leaf 2 = T3; Leaf 3 = T4; Selected index = 0; Candidate value = T1; Proof fault = none. In the classroom model, Valid inclusion = Yes; Sibling count = 2; Proof bytes = 64 B. Inclusion is verified against the fixed root from the four original leaves. Actual SHA-256 with the domain-separated course encoding.

Use the diagram to follow the calculation or state progression. Keep the teaching configuration separate from the independent exercise values; compare observations with the actual model and implementation.

Mathematical representation and interpretation

Merkle parent construction

The child digests are concatenated in the defined order using the same byte representation; membership depends on the independently trusted root.

\[h_{i,j}=H(h_i\parallel h_j)\]

Concept animation · independent state notebook

Explore the teaching example independently of the simulator. Each step reveals an operation, data relationship or calculated state. The Simulation view has separate editable inputs.

B02 · Merkle trees and inclusion proofs: independent state notebook123Tree level 0Node 05007e18fe7ee36c0a92636757635b432fde39d91bc…Node 1fe7e75c1572c03c58331fc8aa03d5731199605a63e…Node 250de762b8fd96e8569a78309bf140d660cb5abe719…Node 3f9f9a347a66a8b7fa96b148ea420c8ce38d978dfcd…

Step 1 of 3 · Tree level 0

Tree level 0

phase
Tree level 0
Node 0
5007e18fe7ee36c0a92636757635b432fde39d91bc46c0a3118ba68f44addace
Node 1
fe7e75c1572c03c58331fc8aa03d5731199605a63eccf186a4fcdf28e02964ba
Node 2
50de762b8fd96e8569a78309bf140d660cb5abe719615cd93bd9d2c025f1d957
Node 3
f9f9a347a66a8b7fa96b148ea420c8ce38d978dfcded7e6b6c509b83a94da624

Teaching example only; inspect live calculations or real practical evidence separately.

Recall the concept before revealing its explanation.

0 / 3 revealed
B02 · 01 / 08What is a Merkle root?Reveal explanation
Engineering explanation

A digest summarizing a tree of ordered leaves.

B02 · 02 / 08What is an inclusion proof?Reveal explanation
Engineering explanation

A sequence of sibling digests and their left/right positions.

B02 · 03 / 08Does inclusion establish a true sensor reading?Reveal explanation
Engineering explanation

No. It proves consistency with the selected commitment, not truth of measurements.

B02 · 04 / 08Why must a proof include sibling order?Reveal explanation
Engineering reasoning

Hash(left + right) differs from hash(right + left); the proof must reconstruct the correct path.

B02 · 05 / 08What does inclusion under a trusted root prove?Reveal explanation
Engineering reasoning

The supplied leaf belongs to the committed tree under that root and hashing rule; it does not prove truth of the underlying sensor observation.

B02 · 06 / 08An inclusion proof is checked. Select every technically valid statement. A. Hash siblings in the specified order. B. Compare the result against an independently trusted root. C. A candidate-supplied root alone establishes membership in the trusted tree. D. Swapping left and right is always immaterial.Reveal explanation
Applied scenario

Correct: A. Hash siblings in the specified order.; B. Compare the result against an independently trusted root.

B02 · 07 / 08How do you carry out 3. Check another leaf?Reveal explanation
Implementation recall

Select leaf 2, enter sample-C and Verify selected proof.

B02 · 08 / 08For B02 · Merkle trees and inclusion proofs, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Build once, retain root. Leaf 0 sample-A must verify, sample-X must fail; select leaf 2 and type sample-C to verify against the unchanged root. Do not rebuild after changing candidate because that changes the reference. This is a domain-separated binary teaching tree, not an Ethereum trie.

Shared research workbenches · network designer & advanced studies
Concurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery research
Loading experiment-specific apparatus…
Previous model / additional reference tools

Loading executable simulation…

Simulation task

Construct a four-leaf Merkle tree and verify inclusion against a trusted root.

Explore the model using its own controls. Record a prediction before changing a condition. Compare the reference with a changed condition, then use the Experiment tab for the procedure, acceptance criteria and notebook. Model outputs and physical observations must remain separate.

Interactive engineering workbenchB02 · Existing model

Interactive simulation

The model is an independent teaching abstraction, not Solidity execution or Ethereum consensus. SHA-256 uses actual browser cryptography when available.

B02 · Model-linked instrumentation

Visual observation lens

Back to controls ↑

Browser ledger / digest abstraction; not EVM transaction execution.

Loading instrument…

Awaiting model display.

Experimental instrumentation · A/B

Compare two model conditions

Capture a baseline, change one experimental condition, run the model if required and capture the comparison. Snapshots contain visible controls and display text, not physical sensor readings. Review before exporting.

Open simulation view
Baseline A
Not captured
Comparison B
Not captured

Capture a baseline to begin.

Evidence portfolio →
V19.0 · Contextual AI workspace

Ask your engineering assistants

B02 · current context

Ask Dr. Mohammad locally, or prepare an experiment-aware prompt for ChatGPT, Gemini or Claude. The external providers open in their own tabs; nothing is automatically submitted.

Dr. Mohammad · offline
Dr. Mohammad

Offline curriculum-grounded assistance.

Open local tutor
B02 · Merkle trees and inclusion proofs

Public course objective, displayed commands, source excerpts and procedure. Private assessment content is not collected.

Prepare a contextual AI prompt

0 characters

Common secret and email patterns are redacted on preparation; this is not a comprehensive privacy filter. Review the entire editable prompt, including student work and unpublished research, before sharing. The providers apply their own accounts, privacy settings and limits.

Prepare → review → copy & open your selected provider → paste and submit there.

Run & verify — acceptance checklist

Build verification: Actual SHA-256 Merkle proofs tested.

Build once, retain root. Leaf 0 sample-A must verify, sample-X must fail; select leaf 2 and type sample-C to verify against the unchanged root. Do not rebuild after changing candidate because that changes the reference. This is a domain-separated binary teaching tree, not an Ethereum trie.

Record the actual output, source (mock/model or physical), and any error. A missing tool, timeout or untested external service is not a pass.

Complete lab-by-lab verification report →Open automated verification center → Ask Engineering Copilot →

Independent theoretical exercises

Before the simulation or practical, solve both experiment-specific tasks. List the given inputs, show the intermediate calculation or state trace, identify the expected observation, and state a limitation. Show formulas and intermediate calculations where relevant, or draw the requested state/sequence diagram. These are independent classroom fixtures; where they differ from the reference configuration below, do not treat them as measured values. Compare your predictions with the corresponding experiment afterwards.

01 · Predict and derive using the given inputs

Draw a four-leaf tree for T1…T4, write parent hash expressions and derive the ordered proof for leaf index 0 and 2.

02 · Compare or justify using evidence

Predict verification after changing T1 or swapping sibling order. Calculate proof length for 4 and 8 leaves.

03 · Proof tracing

Proof tracing · Independent work

For four leaves, write the proof for leaf1 and the root reconstruction expression using h0,h1,h2,h3.

Work is saved locally when browser storage is available. Export it for submission; no remote upload or automatic grade is assigned.

Expanded independent theoretical exercise bank

Progress from calculation and interpretation to diagnosis and controlled engineering design. Complete the questions without opening the simulation first; show intermediate steps.

Intermediate · Explain a changed-input result

Independent theoretical exercise · B02-01

Use the reference configuration (Leaf 0 = T1; Leaf 1 = T2; Leaf 2 = T3; Leaf 3 = T4; Selected index = 0; Candidate value = T1; Proof fault = none), but change Selected index = 2. The model reports Valid inclusion = No. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Interpret a state transition

Independent theoretical exercise · B02-02

The reference model reports Valid inclusion: Yes. Under Selected index = 2 it reports No. Explain which configured condition changed and what the two outputs establish, and what they do not establish.

Intermediate · Interpret a technical trace

Independent theoretical exercise · B02-03

For Proof fault = wrong order, the model supplies this excerpt from Node calculation: Node · Input · SHA-256 L1 · leaf:"T1" · 5007e18fe7ee36c0a92636757635b432fde39d91bc46c0a3118ba68f44addace L2 · leaf:"T2" · fe7e75c1572c03c58331fc8aa03d5731199605a63eccf186a4fcdf28e02964ba L3 · leaf:"T3" · 50de762b8fd96e8569a78309bf140d660cb5abe719615cd93bd9d2c025f1d957 L4 · leaf:"T4" · f9f9a347a66a8b7fa96b148ea420c8ce38d978dfcded7e6b6c509b83a94da624 H1.1 · node:5007e18fe7ee36c0a92636757635b432fde39d91bc46c0a3118ba68f44addacefe7e75c1572c03c… · f120b2acb5b3c7259422689fc72779eb1c95e09ea6cbdc9338935b2908d1b7c9 Count rows whose Input value is exactly “leaf:"T1"”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · B02-04

An observation is Valid inclusion = No. Candidate A uses Leaf 0 = T1; Leaf 1 = T2; Leaf 2 = T3; Leaf 3 = T4; Selected index = 0; Candidate value = T1; Proof fault = none. Candidate B changes the listed settings (Proof fault = wrong order) and keeps the remaining settings fixed. Which is consistent with the observation? If both can explain it, say what additional evidence is required.

Advanced · Diagnose a reported mismatch

Independent theoretical exercise · B02-05

A student configures Candidate value = T1 altered while preserving all other reference settings, but copies the reference report of Valid inclusion = Yes. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · B02-06

Design a controlled comparison for B02 · Merkle trees and inclusion proofs using reference Leaf 0 = T1; Leaf 1 = T2; Leaf 2 = T3; Leaf 3 = T4; Selected index = 0; Candidate value = T1; Proof fault = none and test Selected index = 2. Specify the changed setting(s), measured metric Valid inclusion, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Calculate and independently verify a four-leaf binary Merkle tree.

1 · Reference workbench configuration

Use the named reference workbench and its reference inputs. Additional live instruments may have different controls; use the matching instrument. Record virtual and practical results separately.

Leaf 0T1
Leaf 1T2
Leaf 2T3
Leaf 3T4
Selected index0
Candidate valueT1
Proof faultnone

2 · Perform the investigation in order

  1. Use leaves T1–T4 and verify T1 at index zero. Inspect seven computed digests and two siblings.
  2. Change candidate only. The trusted root stays fixed.
  3. Select index 3 and T4. Compare sibling sides.
  4. Modify proof order or sibling digest and inspect the failing computed root.
  5. Verify the exact leaf and internal inputs independently with the local reference toolkit.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Valid proofUse reference inputs aboveValid inclusion: Yes; Sibling count: 2Record actual result
Changed recordCandidate value = T1 alteredValid inclusion: NoRecord actual result
Different leafSelected index = 3; Candidate value = T4Valid inclusion: YesRecord actual result
Changed siblingProof fault = modified siblingValid inclusion: NoRecord actual result

4 · Analyze and report

Explain why the proof must preserve child order and why a proof is smaller than the full leaf set.

Required evidence: Tree and proof packet with exact hash inputs.

Model boundary: Actual SHA-256 with the domain-separated course encoding.

Controlled investigation · reproducible evidence

Method. Use the existing reference workbench configuration and the named controlled changes below. A controlled variable stays fixed while the independent variable is intentionally changed; the dependent variable is the resulting observed output. First predict each trial from the Concepts page. Run the baseline, then change only the specified setting and record the outcome. For deterministic traces one execution per case and a repeated verification are sufficient; for timing or stochastic measurements repeat at least five times, recording each run, median and range. Reset to the reference state between independent comparisons.

TrialIndependent changeDependent observation
Valid proofUse reference inputs aboveRecord actual outcome and units
Changed recordCandidate value = T1 alteredRecord actual outcome and units
Different leafSelected index = 3; Candidate value = T4Record actual outcome and units
Changed siblingProof fault = modified siblingRecord actual outcome and units

Evidence: attach the completed comparison table, one trace or screenshot per condition, and actual practical terminal/hardware evidence where applicable. Explain any prediction mismatch and distinguish modeled behavior from measured results.

Loading laboratory-specific procedure…

Python / Google Colab notebook

Original module reference toolkit; genuine SHA-256 and bounded search. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

  1. 1. Construct the tree
  2. 2. Test a changed record
  3. 3. Check another leaf

Complete practical procedure

1. Construct the tree

Select leaf 0 and Build four-leaf tree.

✓ Expected: A root, two branch digests and four leaf digests appear. The selected proof verifies.

2. Test a changed record

Replace the candidate with sample-X, then Verify selected proof.

✓ Expected: valid is false.

3. Check another leaf

Select leaf 2, enter sample-C and Verify selected proof.

✓ Expected: valid is true with a different sibling path. Keep the same trusted root.

Experimental notebook

Record your own results. Values are not prefilled or independently verified.

Source & scientific method

Leaf and internal node encodings are domain-separated. This is a binary teaching tree, not an Ethereum Merkle Patricia trie.

Toolkit instructions and references · Download complete blockchain toolkit

Verification, troubleshooting and reflection

Compare each observation with its expected result. If a check fails, identify whether the issue is the environment, contract selection, caller identity, sequence, byte encoding or model setup. Do not infer success from a timeout or a missing receipt. In Remix inspect the compiler errors and revert message; do not bypass the negative control.

Reset the browser model for a fresh run. Resetting Remix VM removes its deployed state. Keep screenshots and receipts before reset. For actual EVM execution, save compiler/fork/settings and transaction receipts. Explain limitations and propose one additional independent test.

Python / Google Colab laboratory

B02 · 8 notebook cells · 2 executable Python cells

Complete the theoretical investigation first. Run the cells in order, record actual outputs and compare against your prediction.

How to execute

  1. Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
  2. Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
  3. Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.

Execution scope: Domain-separated UTF-8 encoding matches the existing teaching labs; not Bitcoin double-SHA256 byte serialization or Ethereum Keccak. Inclusion does not establish finality or source truth. Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.

01Instructions · Markdown
# B02 · B02 · Merkle trees and inclusion proofs **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Construct a four-leaf Merkle tree and verify inclusion against a trusted root. ## How to run 1. Download this notebook from the laboratory page. Open Google Colab → File → Upload notebook. 2. Select a Python CPU runtime. Run cells from top to bottom using Shift+Enter, or Runtime → Run all. 3. Read the printed observations and assertions. Change one parameter at a time and rerun the relevant cell. 4. Save your own outputs and compare them to the portal Experiment tab. **Execution boundary:** Original module reference toolkit; genuine SHA-256 and bounded search. Do not run the hardware or service commands in Colab. No real credentials are needed. The notebook is self-contained.
02Instructions · Markdown
## Experiment-specific preparation Construct a four-leaf Merkle tree and verify inclusion against a trusted root. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Use leaves T1–T4 and verify T1 at index zero. Inspect seven computed digests and two siblings. 2. Change candidate only. The trusted root stays fixed. 3. Select index 3 and T4. Compare sibling sides. 4. Modify proof order or sibling digest and inspect the failing computed root. 5. Verify the exact leaf and internal inputs independently with the local reference toolkit. **Evidence:** Four leaves require 7 digests and 2 proof siblings; eight require 15 digests and 3 siblings. Modified candidate fails against the original root. **Boundary:** Domain-separated UTF-8 encoding matches the existing teaching labs; not Bitcoin double-SHA256 byte serialization or Ethereum Keccak. Inclusion does not establish finality or source truth.
03Instructions · Markdown
## 1. Objectives and reference condition - Reproduce the specific computational mechanism in this laboratory. - Inspect the output, compare the reference condition with a changed or rejected condition where implemented, and explain any discrepancy. - Distinguish actual local Python execution from mock, physical and external-service observations. ## 2. Environment check
04Python · executable cell
PYTHON · Code cell
# =====================================================================
# B02 | Code cell 01 | B02 · Merkle trees and inclusion proofs
# Purpose: 1. Objectives and reference condition - Reproduce the specific computational mechanism in this laboratory. - Inspect the output, compare the reference condition with a changed or rejected condition where implem
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import sys
print("Python",sys.version.split()[0])
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert sys.version_info >= (3,10)
Ask Dr. Mohammad about this cell
05Instructions · Markdown
## 3. Implementation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
06Python · executable cell
PYTHON · Code cell
# =====================================================================
# B02 | Code cell 02 | B02 · Merkle trees and inclusion proofs
# Purpose: implement only the mechanism named in this laboratory.
# Inputs: the explicit fictional fixture and reference parameters below.
# Output: printed observations and assertions for the controlled trial.
# =====================================================================
import hashlib,json
def serialize(obj):
    return json.dumps(obj, ensure_ascii=False, separators=(',', ':'))

def sha(text):
    return hashlib.sha256(text.encode('utf-8')).hexdigest()

def tree(values):
    if len(values) not in (4,8): raise ValueError('Use 4 or 8 leaves')
    levels = [[sha('leaf:' + serialize(v)) for v in values]]
    while len(levels[-1]) > 1:
        a=levels[-1]; levels.append([sha('node:' + a[i] + a[i+1]) for i in range(0,len(a),2)])
    return levels

def prove(levels,index,candidate):
    current=sha('leaf:'+serialize(candidate)); steps=[dict(input='leaf:'+serialize(candidate),digest=current)]
    for row in levels[:-1]:
        sibling=row[index^1]; text='node:'+(sibling+current if index&1 else current+sibling);current=sha(text)
        steps.append(dict(input=text,digest=current,sibling=sibling,side='left' if index&1 else 'right'));index//=2
    return dict(valid=current==levels[-1][0],steps=steps,computedRoot=current,trustedRoot=levels[-1][0])
values=[f'sensor-{i+1}:temp={25+i}' for i in range(8)]
levels=tree(values);proof=prove(levels,0,values[0]);tampered=prove(levels,0,'changed')
print('root',levels[-1][0],'proof',proof,'tampered valid',tampered['valid'])
assert proof['valid'] and not tampered['valid']
Ask Dr. Mohammad about this cell
07Instructions · Markdown
## 4. Results and analysis Record the actual output and whether the assertions pass. Identify a parameter to vary, state your prediction, repeat the reference calculation, then explain the changed result. | Trial | Configuration | Observation | Interpretation | |---|---|---|---| | A | Reference | | | | B | One controlled change | | | | C | Reference repeat | | | **Limitations:** Original module reference toolkit; genuine SHA-256 and bounded search. Notebook success does not certify external equipment or services.
08Instructions · Markdown
## Guided reasoning and evidence A controlled comparison changes one independent input while keeping the other relevant inputs fixed; the dependent variable is the recorded output. Use this lab’s reference condition above. **Independent task:** 2. Change candidate only. The trusted root stays fixed. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat. | Trial | Input/configuration | Prediction | Observation | Evidence / limitation | |---|---|---|---|---| | A | Reference | | | | | B | Changed input | | | | | A repeat | Reference | | | | A conclusion is supported only when it cites the recorded values or observed states and explains them with the experiment theory.