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

B07 · IoT dApp workflow and event evidence

Ask Dr. Mohammad · B07 →

Connect an off-chain sensor payload to a contract invocation, receipt, event and subsequent verification.

Design experiment & verify evidence →
B07 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Blockchain foundationsB07 · IoT dApp workflow and event evidence

Before you start

Learning outcome: Connect an off-chain sensor payload to a contract invocation, receipt, event and subsequent verification.

Use fictional values only. Browser models work offline; actual Solidity compilation and Remix VM require the external Remix IDE and initial compiler download. No real funds or private credentials.

Recommended predecessors: B06

Predict: Write down the expected positive and negative outcomes in the notebook before proceeding.
B07 · Academic orientation

Scope and objectives

Scope of the experiment

Connect an off-chain sensor payload to a contract invocation, receipt, event and subsequent verification.

The focus of this experiment is to trace an IoT dApp request, transaction and emitted event. Students then distinguish transaction submission from confirmed state changes, and reconcile application evidence with receipt and contract state. 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

  • Trace an IoT dApp request, transaction and emitted event.
  • Distinguish transaction submission from confirmed state changes.
  • Reconcile application evidence with receipt and contract state.
  • Identify the configured inputs (Transaction / indexer condition; Submitted sequence; Previous on-chain sequence; Fictional telemetry) 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 trace an IoT dApp request, transaction and emitted event, distinguish transaction submission from confirmed state changes, and reconcile application evidence with receipt and contract state.

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 reconcile application evidence with receipt and contract state. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to B08 · Gas, scalability and experimental design.

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

Scientific architecture · IoT dApp transaction and receipt reconciliation

dApp receipt reconciliation — Sensor/client; Wallet & local EVM; Application ledger; Construct transaction / 0>1; Submit and execute / 1>1; Receipt & logs / 1>0; Reconcile event ID / 0>2
Scientific concept map: IoT sensor — Telemetry; dApp client — Construct transaction; Local EVM — Execute contract; Receipt — Status and event; Reconcile — Compare expected state.

Scientific foundations and analytical reasoning

A dApp links an off-chain record to a signed transaction, receipt, event and state verification. Transaction inclusion is not synonymous with success.

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 · Application transaction evidence

An IoT dApp serializes a reading, constructs a transaction, obtains a signature and waits for a receipt. Inclusion, execution success and finality differ. Event indexing can be delayed; reconcile an event's transaction identity with receipt and current state.

Worked example and engineering interpretation

A transaction hash may exist while the transaction is pending. An included transaction with failure status did not perform its intended state update. Verify the receipt and compare its event commitment with the local record before reporting success.

Engineering principles · additional worked teaching example

A transaction hash identifies a submitted transaction, receipt status indicates execution, and event logs identify emitted records. An indexer may lag behind the chain; absence from a local dashboard does not establish transaction failure.

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 B07 · IoT dApp workflow and event evidence

Connect an off-chain sensor payload to a contract invocation, receipt, event and subsequent verification.

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: Connect an off-chain sensor payload to a contract invocation, receipt, event and subsequent verification.

  1. Send sequence 2 after 1. Inspect submission, accepted receipt and indexed event.
  2. Select missing receipt. Contract state advances but indexer remains at 1.
  3. Choose revert; verify no committed event or sequence advance.
  4. Inject a duplicate event and deduplicate by transaction/log identity.

Reference check: An accepted reading above 8°C raises the declared teaching-policy warning. Offline delivery does not create a commitment. Altered bytes do not match an accepted digest.

Model boundary: 8°C is a teaching threshold, not a universal food-safety standard. Hashes cannot establish actual temperature or physical custody.

Independent task and submission evidence

2. Select missing receipt. Contract state advances but indexer remains at 1. 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: Transaction / indexer condition = none; Submitted sequence = 2; Previous on-chain sequence = 1; Fictional telemetry = temperature=25. In the classroom model, On-chain sequence = 2; Indexed sequence = 2; Indexed events = 1; Reconciled = Yes. A UI receipt failure is not evidence that the contract reverted. Deterministic dApp workflow, not actual EVM.

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.

Concept animation · message sequence

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.

B07 · IoT dApp workflow and event evidence: message sequenceGatewayContractReceiptIndexerSubmit seq 2CommittedEvent reconciled

Step 1 of 3 · Submit seq 2

Submit seq 2

1. Gateway → Contract
Submit seq 2

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

Recall the concept before revealing its explanation.

0 / 3 revealed
B07 · 01 / 08What is a dApp?Reveal explanation
Engineering explanation

An application using smart contracts through a client interface.

B07 · 02 / 08Why distinguish receipt from event?Reveal explanation
Engineering explanation

A receipt indicates transaction execution status; logs provide emitted event data, not independent sensor truth.

B07 · 03 / 08Why use local chains first?Reveal explanation
Engineering explanation

They provide controlled, low-risk conditions with test accounts and no real assets.

B07 · 04 / 08Why reconcile event logs with contract state?Reveal explanation
Engineering reasoning

Events describe execution records; reading contract state verifies the persistent result and detects indexing discrepancies.

B07 · 05 / 08Why distinguish a model receipt from an EVM receipt?Reveal explanation
Engineering reasoning

A model is a teaching calculation; actual receipts require contract execution in the selected EVM environment.

B07 · 06 / 08An IoT dApp submits a contract operation. Select every technically valid statement. A. Inspect transaction receipt status. B. Check the expected event and contract state against the intended payload. C. A transaction hash alone establishes successful execution. D. An event from a different contract proves the intended state changed.Reveal explanation
Applied scenario

Correct: A. Inspect transaction receipt status.; B. Check the expected event and contract state against the intended payload.

B07 · 07 / 08How do you carry out 4. Verify receipts and limitations?Reveal explanation
Implementation recall

Inspect evidence JSON, contract tests and transaction hashes. Compare to manual Remix B06.

B07 · 08 / 08For B07 · IoT dApp workflow and event evidence, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Extract blockchain-toolkit.zip; open a terminal in its blockchain folder (verify package.json, contracts/ and evm-test.cjs exist). Node.js 20+ and npm required, internet for first install. Run node --version, npm --version, npm install, npm ls --depth=0, then npm test. Require exit 0, evm-evidence.json and gas-trials.csv. Archive both before rerunning. If DNS, compiler, contract or transaction error occurs, stop and record it; no real accounts or funds. The optional runner is a local programmatic dApp client, not a browser dApp or public blockchain.

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
Simulation task

Connect an off-chain sensor payload to a contract invocation, receipt, event and subsequent verification.

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 workbenchB07 · 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.

Loading executable simulation…

B07 · 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

B07 · 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
B07 · IoT dApp workflow and event evidence

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: Model tested; actual local EVM runner pending dependency installation.

Extract blockchain-toolkit.zip; open a terminal in its blockchain folder (verify package.json, contracts/ and evm-test.cjs exist). Node.js 20+ and npm required, internet for first install. Run node --version, npm --version, npm install, npm ls --depth=0, then npm test. Require exit 0, evm-evidence.json and gas-trials.csv. Archive both before rerunning. If DNS, compiler, contract or transaction error occurs, stop and record it; no real accounts or funds. The optional runner is a local programmatic dApp client, not a browser dApp or public blockchain.

Optional local EVM route: extract the Blockchain toolkit in Windows, copy its blockchain folder into the Ubuntu home directory (open it with explorer.exe . from Ubuntu). In Ubuntu Bash, enter cd ~/blockchain. Verify node --version shows 20 or later and npm --version succeeds; install Node.js through an approved distribution method first if unavailable. Use Bash for the command blocks. The Remix VM alternative does not require installing Node.js.

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

For prior sequence 1 and submitted 2, draw each stage and identify required fields tying event and payload together.

02 · Compare or justify using evidence

Compare successful receipt, revert and missing event in the indexer. Explain why independent state reconciliation is necessary.

03 · Troubleshooting

Troubleshooting · Independent work

Receipt status success and event exists on chain but dashboard shows older sequence. Give two checks before resubmitting.

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 · B07-01

Use the reference configuration (Transaction / indexer condition = none; Submitted sequence = 2; Previous on-chain sequence = 1; Fictional telemetry = temperature=25), but change Submitted sequence = 4. The model reports On-chain sequence = 4. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · B07-02

Two model observations of On-chain sequence are 2 (reference) and 4 (changed condition). Compute signed change and, when the reference is nonzero, percentage change. Explain why units matter.

Intermediate · Interpret a technical trace

Independent theoretical exercise · B07-03

For Previous on-chain sequence = 3, the model supplies this excerpt from dApp lifecycle: Stage · Observation Gateway · 3ad08815cc298024402a45e89c9e4737b6926d7dd49bb3fb92e902362541cfc2 Submission · Created Contract · Reverted Receipt · Reverted Event · None observed Count rows whose Observation value is exactly “Reverted”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · B07-04

An observation is On-chain sequence = 3. Candidate A uses Transaction / indexer condition = none; Submitted sequence = 2; Previous on-chain sequence = 1; Fictional telemetry = temperature=25. Candidate B changes the listed settings (Previous on-chain sequence = 3) 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 · B07-05

A student configures Transaction / indexer condition = missing receipt while preserving all other reference settings, but copies the reference report of Indexed sequence = 2. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · B07-06

Design a controlled comparison for B07 · IoT dApp workflow and event evidence using reference Transaction / indexer condition = none; Submitted sequence = 2; Previous on-chain sequence = 1; Fictional telemetry = temperature=25 and test Submitted sequence = 4. Specify the changed setting(s), measured metric On-chain sequence, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Separate transaction submission, receipt and event indexer state in an IoT dApp.

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.

Transaction / indexer conditionnone
Submitted sequence2
Previous on-chain sequence1
Fictional telemetrytemperature=25

2 · Perform the investigation in order

  1. Send sequence 2 after 1. Inspect submission, accepted receipt and indexed event.
  2. Select missing receipt. Contract state advances but indexer remains at 1.
  3. Choose revert; verify no committed event or sequence advance.
  4. Inject a duplicate event and deduplicate by transaction/log identity.
  5. Run the actual local EVM integration from the bundled dApp toolkit; reconcile receipt and contract state rather than assuming UI success.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Successful dAppUse reference inputs aboveOn-chain sequence: 2; Indexed sequence: 2Record actual result
Missing receiptTransaction / indexer condition = missing receiptOn-chain sequence: 2; Indexed sequence: 1Record actual result
RevertTransaction / indexer condition = revertOn-chain sequence: 1Record actual result
Duplicate logTransaction / indexer condition = duplicate eventIndexed events: 1Record actual result

4 · Analyze and report

Distinguish submission, inclusion, successful execution and indexed evidence.

Required evidence: Receipt and indexer reconciliation table.

Model boundary: Deterministic dApp workflow, not actual EVM.

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
Successful dAppUse reference inputs aboveRecord actual outcome and units
Missing receiptTransaction / indexer condition = missing receiptRecord actual outcome and units
RevertTransaction / indexer condition = revertRecord actual outcome and units
Duplicate logTransaction / indexer condition = duplicate eventRecord 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…

Independent implementation sequence

  1. 1. Explore the model dApp
  2. 2. Prepare optional actual local dApp
  3. 3. Run real EVM integration
  4. 4. Verify receipts and limitations

Complete practical procedure

Open Remix IDE ↗ · Official deployment guide

1. Explore the model dApp

Authorize sensor as owner, submit sequence 1 as sensor, then verify the matching digest.

✓ Expected: The model shows an accepted transaction, sequence and commitment. It is not an EVM receipt.

2. Prepare optional actual local dApp

Install Node.js 20+ from its official distribution. Open a terminal in the extracted blockchain directory and run npm install.

✓ Expected: Pinned direct dependencies install. Initial network access required; do not use production credentials.

3. Run real EVM integration

Run npm test. Review the source evm-test.cjs, which compiles, deploys and invokes contracts through ethers and an in-process Ganache provider.

✓ Expected: If execution succeeds, evm-evidence.json and gas-trials.csv are created; controls pass. If compilation or install fails, record the actual error, not a fabricated result.

4. Verify receipts and limitations

Inspect evidence JSON, contract tests and transaction hashes. Compare to manual Remix B06.

✓ Expected: A local actual EVM result is distinct from the browser model and public Ethereum. Archive files before rerunning.
Node.js terminal · blockchain directory
node --version
npm --version
ls package.json evm-test.cjs
npm install && npm ls --depth=0
✓ Expected: required dependencies install without errors. Internet required.
Node.js terminal
npm test
✓ Expected: all assertions pass and two result files are created; archive existing results before repeating.

Experimental notebook

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

Source & scientific method

The optional runner is a programmatic local dApp client. It does not expose an RPC listener. No public testnet is needed for core learning. Public testnet extension: use Sepolia only with instructor-approved test accounts and test ETH; confirm chain ID 11155111, repeat deployment, record actual receipts; never use mainnet.

TelemetryAnchor.sol

Download source file
Solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
/// @notice Store only a digest and monotonic sequence, never raw private telemetry.
/// A commitment proves equality with supplied bytes, not truth of sensor measurements.
contract TelemetryAnchor {
    address public immutable owner;
    mapping(address => bool) public active;
    mapping(address => uint64) public lastSequence;
    mapping(address => bytes32) public lastDigest;
    event DeviceStatus(address indexed device, bool enabled);
    event Anchored(address indexed device, uint64 sequence, bytes32 digest);
    error NotOwner();
    error InvalidDevice();
    error Unauthorized();
    error InvalidSequence();
    error EmptyDigest();
    constructor() { owner = msg.sender; }
    function setDevice(address device, bool enabled) external {
        if (msg.sender != owner) revert NotOwner();
        if (device == address(0)) revert InvalidDevice();
        active[device] = enabled;
        emit DeviceStatus(device, enabled);
    }
    function anchor(uint64 sequence, bytes32 digest) external {
        if (!active[msg.sender]) revert Unauthorized();
        if (sequence <= lastSequence[msg.sender]) revert InvalidSequence();
        if (digest == bytes32(0)) revert EmptyDigest();
        lastSequence[msg.sender] = sequence;
        lastDigest[msg.sender] = digest;
        emit Anchored(msg.sender, sequence, digest);
    }
    function verifyLatest(address device, uint64 sequence, bytes32 digest) external view returns (bool) {
        return sequence != 0 && lastSequence[device] == sequence && lastDigest[device] == digest;
    }
}

evm-test.cjs

Download source file
Javascript
/* Optional real local EVM verification. No network listener, wallet or real funds. */
const fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict'),solc=require('solc'),ganache=require('ganache');
const {BrowserProvider,ContractFactory,sha256,toUtf8Bytes,ZeroHash,id}=require('ethers');
for(const n of ['evm-evidence.json','gas-trials.csv'])if(fs.existsSync(path.join(__dirname,n)))throw Error('Archive existing '+n+' before rerunning.');
const sourceDir=path.join(__dirname,'contracts');
const sources=Object.fromEntries(fs.readdirSync(sourceDir).filter(x=>x.endsWith('.sol')).map(n=>[n,{content:fs.readFileSync(path.join(sourceDir,n),'utf8')}]))
const settings={evmVersion:'shanghai',optimizer:{enabled:false,runs:200},outputSelection:{'*':{'*':['abi','evm.bytecode.object']}}};
const compiled=JSON.parse(solc.compile(JSON.stringify({language:'Solidity',sources,settings})));const errors=(compiled.errors||[]).filter(x=>x.severity==='error');if(errors.length)throw Error(errors.map(x=>x.formattedMessage).join('\n'));
(async()=>{const raw=ganache.provider({logging:{quiet:true},chain:{hardfork:'shanghai',chainId:1337},wallet:{totalAccounts:3}});try{const p=new BrowserProvider(raw),owner=await p.getSigner(0),sensor=await p.getSigner(1),other=await p.getSigner(2),addr=await sensor.getAddress();let checks=[];
async function deploy(name){let a=compiled.contracts[name+'.sol'][name];let c=await new ContractFactory(a.abi,a.evm.bytecode.object,owner).deploy();await c.waitForDeployment();return c}
async function check(name,fn){await fn();checks.push({name,pass:true})}
async function rejected(contract, errorName, simulate, submit){
 const selector=id(errorName+'()').slice(0,10).toLowerCase();
 // Confirm the precise custom error via eth_call before sending a transaction.
 // Do not accept generic transport failures as a passing negative control.
 await assert.rejects(simulate,e=>{
   const d=e.data??e.info?.error?.data?.result??e.info?.error?.data;
   return typeof d==='string'&&d.toLowerCase().startsWith(selector);
 });
 const tx=await submit();
 await assert.rejects(()=>tx.wait(),e=>e.receipt?.status===0);
}
const c=await deploy('Counter');await check('Counter starts at zero',async()=>assert.equal(await c.count(),0n));await check('Increment',async()=>{await(await c.increment()).wait();assert.equal(await c.count(),1n)});await check('Reset',async()=>{await(await c.reset()).wait();assert.equal(await c.count(),0n)});
const r=await deploy('DeviceRegistry');await check('Owner registers',async()=>{await(await r.setDevice(addr,true)).wait();assert.equal(await r.active(addr),true)});await check('Non-owner denied',async()=>rejected(r,'NotOwner',()=>r.connect(other).setDevice.staticCall(addr,false),()=>r.connect(other).setDevice(addr,false,{gasLimit:200000})));await check('Owner revokes',async()=>{await(await r.setDevice(addr,false)).wait();assert.equal(await r.active(addr),false)});
const t=await deploy('TelemetryAnchor');let digest=sha256(toUtf8Bytes('demo:25.0'));await check('Unregistered denied',async()=>rejected(t,'Unauthorized',()=>t.connect(sensor).anchor.staticCall(1,digest),()=>t.connect(sensor).anchor(1,digest,{gasLimit:200000})));await(await t.setDevice(addr,true)).wait();await check('Valid commitment and match',async()=>{await(await t.connect(sensor).anchor(1,digest)).wait();assert.equal(await t.verifyLatest(addr,1,digest),true)});await check('Replay denied',async()=>rejected(t,'InvalidSequence',()=>t.connect(sensor).anchor.staticCall(1,digest),()=>t.connect(sensor).anchor(1,digest,{gasLimit:200000})));await check('Modified bytes mismatch',async()=>assert.equal(await t.verifyLatest(addr,1,sha256(toUtf8Bytes('demo:99.0'))),false));await check('Empty digest denied',async()=>rejected(t,'EmptyDigest',()=>t.connect(sensor).anchor.staticCall(2,ZeroHash),()=>t.connect(sensor).anchor(2,ZeroHash,{gasLimit:200000})));await check('Revoked writer denied',async()=>{await(await t.setDevice(addr,false)).wait();await rejected(t,'Unauthorized',()=>t.connect(sensor).anchor.staticCall(2,digest),()=>t.connect(sensor).anchor(2,digest,{gasLimit:200000}))});await check('Re-enable preserves sequence',async()=>{await(await t.setDevice(addr,true)).wait();await rejected(t,'InvalidSequence',()=>t.connect(sensor).anchor.staticCall(1,digest),()=>t.connect(sensor).anchor(1,digest,{gasLimit:200000}));await(await t.connect(sensor).anchor(2,digest)).wait();assert.equal(await t.lastSequence(addr),2n)});
let trials=[];for(let size of [32,128,512,1024])for(let trial=1;trial<=3;trial++){let g=await deploy('GasStudy'),h=await deploy('GasStudy'),data=Buffer.alloc(size,trial),hex='0x'+data.toString('hex'),digest=sha256(data);let a=await(await g.storeRaw(hex)).wait(),b=await(await h.storeDigest(digest)).wait();assert.equal(a.status,1);assert.equal(b.status,1);assert.equal(await g.rawDemo(),hex);assert.equal(await h.commitment(),digest);trials.push({size,trial,rawGas:Number(a.gasUsed),digestGas:Number(b.gasUsed),rawTx:a.hash,digestTx:b.hash})}
const report={provenance:'actual local Ganache EVM execution (not public Ethereum)',compiler:solc.version(),settings,checks,trials};fs.writeFileSync(path.join(__dirname,'evm-evidence.json'),JSON.stringify(report,null,2),{flag:'wx'});fs.writeFileSync(path.join(__dirname,'gas-trials.csv'),'size,trial,rawGas,digestGas,rawTx,digestTx\n'+trials.map(x=>Object.values(x).join(',')).join('\n')+'\n',{flag:'wx'});console.log(JSON.stringify(report,null,2));}finally{await raw.disconnect()}})().catch(e=>{console.error(e);process.exitCode=1});

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

B07 · 9 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: 8°C is a teaching threshold, not a universal food-safety standard. Hashes cannot establish actual temperature or physical custody. Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.

01Instructions · Markdown
# B07 · B07 · IoT dApp workflow and event evidence **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## 1. Scientific objective Separate transaction submission, receipt and event indexer state in an IoT dApp. Complete the analytical worksheet in the portal first. Record your predictions before running this notebook. This notebook is a bounded local computational investigation; use the portal’s separate WSL, hardware or Remix procedure for real interfaces.
02Instructions · Markdown
## Experiment-specific preparation Connect an off-chain sensor payload to a contract invocation, receipt, event and subsequent verification. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Send sequence 2 after 1. Inspect submission, accepted receipt and indexed event. 2. Select missing receipt. Contract state advances but indexer remains at 1. 3. Choose revert; verify no committed event or sequence advance. 4. Inject a duplicate event and deduplicate by transaction/log identity. 5. Run the actual local EVM integration from the bundled dApp toolkit; reconcile receipt and contract state rather than assuming UI success. **Evidence:** An accepted reading above 8°C raises the declared teaching-policy warning. Offline delivery does not create a commitment. Altered bytes do not match an accepted digest. **Boundary:** 8°C is a teaching threshold, not a universal food-safety standard. Hashes cannot establish actual temperature or physical custody.
03Instructions · Markdown
## 2. Reference configuration and investigation 1. Send sequence 2 after 1. Inspect submission, accepted receipt and indexed event. 2. Select missing receipt. Contract state advances but indexer remains at 1. 3. Choose revert; verify no committed event or sequence advance. 4. Inject a duplicate event and deduplicate by transaction/log identity. 5. Run the actual local EVM integration from the bundled dApp toolkit; reconcile receipt and contract state rather than assuming UI success. Run cells in order; do not substitute model results for physical measurements.
04Instructions · Markdown
## 3. Represent receipt and indexer state separately.
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# B07 | Code cell 01 | B07 · IoT dApp workflow and event evidence
# Purpose: 3. Represent receipt and indexer state separately.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Define the reusable operation process; keep its logic separate from the trial.
def process(seq, receipt, event, old_state=1, old_index=1):
    state=seq if receipt=="success" and seq>old_state else old_state
    index=state if event and receipt=="success" else old_index
    return state,index
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert process(2,"success",True)==(2,2)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert process(2,"success",False)==(2,1)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert process(2,"reverted",False)==(1,1)
Ask Dr. Mohammad about this cell
06Instructions · Markdown
## 4. Reconcile missing events and ignore duplicates. This is not a deployed EVM.
07Python · executable cell
PYTHON · Code cell
# =====================================================================
# B07 | Code cell 02 | B07 · IoT dApp workflow and event evidence
# Purpose: 4. Reconcile missing events and ignore duplicates. This is not a deployed EVM.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Set (state, index) for the next computation or reference condition.
state,index=process(2,"success",False)
# Set index for the next computation or reference condition.
index=state # independent authorized state query in model
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert (state,index)==(2,2)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert process(2,"success",True,state,index)==(2,2)
Ask Dr. Mohammad about this cell
08Instructions · Markdown
## Experimental analysis and submission 1. Record the reference input, predicted output and actual result. 2. Modify one independent variable and run the relevant cells again. 3. Explain the result using the theory and identify model limitations. 4. Save the notebook with outputs and retain the separate theoretical worksheet. **Your derivation and conclusion:** (Complete independently.)
09Instructions · 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. Select missing receipt. Contract state advances but indexer remains at 1. 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.