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

B08 · Gas, scalability and experimental design

Ask Dr. Mohammad · B08 →

Compare raw storage and digest storage using actual transaction gas, and distinguish bytes from gas.

Design experiment & verify evidence →
B08 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Blockchain foundationsB08 · Gas, scalability and experimental design

Before you start

Learning outcome: Compare raw storage and digest storage using actual transaction gas, and distinguish bytes from gas.

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

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

Scope and objectives

Scope of the experiment

Compare raw storage and digest storage using actual transaction gas, and distinguish bytes from gas.

The focus of this experiment is to compare transaction cost, batching and scalability under matched trials. Students then calculate per-record resource metrics from actual or stated data, and document execution assumptions and avoid fabricated gas measurements. 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

  • Compare transaction cost, batching and scalability under matched trials.
  • Calculate per-record resource metrics from actual or stated data.
  • Document execution assumptions and avoid fabricated gas measurements.
  • Identify the configured inputs (Records per batch; Raw bytes per record; Assumed base gas per tx; Assumed extra anchor gas; Gas price (gwei)) 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 compare transaction cost, batching and scalability under matched trials, calculate per-record resource metrics from actual or stated data, and document execution assumptions and avoid fabricated gas measurements.

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 document execution assumptions and avoid fabricated gas measurements. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to B09 · Blockchain privacy and secure IoT 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 · Gas and batch payload budget

Batch gas budget — Fixed transaction overhead / G0; Per-report work / g; Batch n reports / G0+n·g; Capacity / floor(budget / batch gas); Trade-off / overhead vs waiting time
Scientific concept map: Payload — Bytes / batch size; Transaction — Fixed and variable costs; Gas model — Execution budget; Block capacity — Finite limit; Trade-off — Gas per report.

Scientific foundations and analytical reasoning

Byte counts are not gas measurements; transaction execution and storage affect cost. Batching can amortize fixed overhead.

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 · Scalability and gas methodology

Gas measures execution resource units under a specific virtual machine and protocol rules. Fees depend on gas used and effective gas price. Payload bytes and transaction count are not direct gas measurements. Batching can amortize fixed transaction costs while increasing per-batch work and delay.

Worked example and engineering interpretation

For 100 samples grouped into batches of 10, ten transactions are needed rather than 100 individually. This is a transaction-count prediction, not a measured gas reduction. Run the same local contract and inputs for both strategies and record actual receipt gas usage.

Engineering principles · additional worked teaching example

For N records and batch B, anchors=ceil(N/B); modeled cost is anchors×(base gas+anchor gas) if each anchor costs the same. 33 records batched 16 use 3 anchors, not 2.

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 B08 · Gas, scalability and experimental design

Compare raw storage and digest storage using actual transaction gas, and distinguish bytes from gas.

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: Compare raw storage and digest storage using actual transaction gas, and distinguish bytes from gas.

  1. Use 16 records × 64 B; calculate 1024 raw bytes, 512 per-record digest bytes and 32 root bytes.
  2. Enter configured base gas 21,000 and anchor gas 20,000. Calculate the teaching gas budget for 16 separate anchors versus one batch root.
  3. Repeat with one record and 32 records. Explain why payload byte count and gas cost are not equivalent.
  4. Run the provided local EVM controlled gas experiment or Remix receipts and record actual gas separately.

Reference check: Read-only local call does not pay a transaction fee. Failed included transactions can consume gas without committing contract state.

Model boundary: Fixed illustrative gas costs, not measured EVM gas. Use actual receipts in Remix for precise costs.

Independent task and submission evidence

2. Enter configured base gas 21,000 and anchor gas 20,000. Calculate the teaching gas budget for 16 separate anchors versus one batch root. 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: Records per batch = 16; Raw bytes per record = 64; Assumed base gas per tx = 21000; Assumed extra anchor gas = 20000; Gas price (gwei) = 20. In the classroom model, Raw bytes = 1024 B; Digest bytes = 512 B; Root bytes = 32 B; Modeled gas saved = 615000. The actual gas schedule depends on contract execution and transaction data. Payload-only byte accounting and configured gas assumptions, not EVM gas measurement.

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 · quantity comparison

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.

B08 · Gas, scalability and experimental design: quantity comparisonRaw1024 Individual digests512 Batch root32

Step 1 of 3 · Raw

Raw

Raw
1024

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

Recall the concept before revealing its explanation.

0 / 3 revealed
B08 · 01 / 08Are bytes equal to gas?Reveal explanation
Engineering explanation

No. Gas also depends on execution, storage transitions and calldata encoding.

B08 · 02 / 08Why deploy fresh contracts for trials?Reveal explanation
Engineering explanation

Storage cost depends on prior state. Fresh deployment controls the zero-to-nonzero transition.

B08 · 03 / 08Does host timing measure network finality?Reveal explanation
Engineering explanation

No. Public network latency includes inclusion and confirmation behavior.

B08 · 04 / 08Why does a 32-byte Merkle root not mean a batch transaction costs only 32 bytes?Reveal explanation
Engineering reasoning

Transaction overhead, ABI encoding, proofs and other fields are additional; the model's byte budget is not a gas measurement.

B08 · 05 / 08Why hold record size fixed when varying count?Reveal explanation
Engineering reasoning

It isolates the effect of batch size on payload volume or measured transaction cost.

B08 · 06 / 08Two Solidity storage approaches are compared. Select every technically valid statement. A. Measure actual transaction gas under controlled conditions. B. Payload bytes and gas are different units. C. One byte always costs exactly one gas for any operation. D. An estimated byte reduction proves an equal gas reduction.Reveal explanation
Applied scenario

Correct: A. Measure actual transaction gas under controlled conditions.; B. Payload bytes and gas are different units.

B08 · 07 / 08How do you carry out 4. Analyze?Reveal explanation
Implementation recall

Compute mean and range per condition, plot rawGas and digestGas versus bytes; distinguish deterministic gas from randomized network delay.

B08 · 08 / 08For B08 · Gas, scalability and experimental design, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Use B07 runner or Remix. Control compiler 0.8.28, optimizer off, Shanghai fork. Use separate freshly deployed GasStudy instances for raw and digest conditions; same account, VALUE 0, nonzero payload sizes 32/128/512/1024 bytes, three pairs per size. Use matching SHA-256 digest of exact bytes. Record actual receipt gasUsed (not gas limit/estimate) and verify stored values. Exclude deployment gas. Compare 12 pairs and report mean/range; no fabricated gas numbers. Browser byte comparison is not gas.

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

Compare raw storage and digest storage using actual transaction gas, and distinguish bytes from gas.

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 workbenchB08 · 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…

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

B08 · 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
B08 · Gas, scalability and experimental design

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: Byte-accounting model tested; actual receipt-gas experiments pending.

Use B07 runner or Remix. Control compiler 0.8.28, optimizer off, Shanghai fork. Use separate freshly deployed GasStudy instances for raw and digest conditions; same account, VALUE 0, nonzero payload sizes 32/128/512/1024 bytes, three pairs per size. Use matching SHA-256 digest of exact bytes. Record actual receipt gasUsed (not gas limit/estimate) and verify stored values. Exclude deployment gas. Compare 12 pairs and report mean/range; no fabricated gas numbers. Browser byte comparison is not gas.

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 16 records of 64 bytes, calculate raw payload bytes and savings with one 32-byte commitment.

02 · Compare or justify using evidence

Under teaching assumptions base 21000 and extra 20000 gas per anchor, compute single batch versus 16 separate anchors and costs at 20 gwei. Label as model, not EVM measurements.

03 · Calculation

Calculation · Independent work

For 50 records, base 21000 and extra 18000 gas per anchor, compare batch size10 and25. State what is excluded.

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

Use the reference configuration (Records per batch = 16; Raw bytes per record = 64; Assumed base gas per tx = 21000; Assumed extra anchor gas = 20000; Gas price (gwei) = 20), but change Records per batch = 18. The model reports Raw bytes = 1152 B. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · B08-02

Two model observations of Raw bytes are 1024 B (reference) and 1152 B (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 · B08-03

For Raw bytes per record = 66, the model supplies this excerpt from Commitment alternatives: Mode · Payload bytes · Transactions · Configured gas · Fee gwei Raw payload · 1056 · 16 · Not estimated · — Separate hashes · 512 · 16 · 656000 · 13120000 Batch root · 32 · 1 · 41000 · 820000 Compute the range (maximum minus minimum) of the Payload bytes column in these rows. Identify the maximum observation. Do not extrapolate beyond these rows.

Advanced · Reverse reasoning

Independent theoretical exercise · B08-04

An observation is Raw bytes = 1056 B. Candidate A uses Records per batch = 16; Raw bytes per record = 64; Assumed base gas per tx = 21000; Assumed extra anchor gas = 20000; Gas price (gwei) = 20. Candidate B changes the listed settings (Raw bytes per record = 66) 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 · B08-05

A student configures Assumed base gas per tx = 21002 while preserving all other reference settings, but copies the reference report of Modeled gas saved = 615000. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · B08-06

Design a controlled comparison for B08 · Gas, scalability and experimental design using reference Records per batch = 16; Raw bytes per record = 64; Assumed base gas per tx = 21000; Assumed extra anchor gas = 20000; Gas price (gwei) = 20 and test Records per batch = 18. Specify the changed setting(s), measured metric Raw bytes, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Quantify the tradeoff of batching commitments versus per-record transactions.

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.

Records per batch16
Raw bytes per record64
Assumed base gas per tx21000
Assumed extra anchor gas20000
Gas price (gwei)20

2 · Perform the investigation in order

  1. Use 16 records × 64 B; calculate 1024 raw bytes, 512 per-record digest bytes and 32 root bytes.
  2. Enter configured base gas 21,000 and anchor gas 20,000. Calculate the teaching gas budget for 16 separate anchors versus one batch root.
  3. Repeat with one record and 32 records. Explain why payload byte count and gas cost are not equivalent.
  4. Run the provided local EVM controlled gas experiment or Remix receipts and record actual gas separately.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Sixteen samplesUse reference inputs aboveRaw bytes: 1024; Digest bytes: 512; Root bytes: 32Record actual result
Single recordRecords per batch = 1Digest bytes: 32; Root bytes: 32Record actual result
Thirty-two recordsRecords per batch = 32Raw bytes: 2048; Root bytes: 32Record actual result

4 · Analyze and report

Discuss proof overhead, off-chain availability and batching delay.

Required evidence: Size and cost table with measured receipt values if available.

Model boundary: Payload-only byte accounting and configured gas assumptions, not EVM gas measurement.

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
Sixteen samplesUse reference inputs aboveRecord actual outcome and units
Single recordRecords per batch = 1Record actual outcome and units
Thirty-two recordsRecords per batch = 32Record 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. Predict data volume
  2. 2. Run a controlled EVM study
  3. 3. Manual Remix alternative
  4. 4. Analyze

Complete practical procedure

Open Remix IDE ↗ · Official deployment guide

1. Predict data volume

Select 128 bytes and 16 records in the model and Compare byte counts.

✓ Expected: Raw 2048 bytes, one hash each 512 bytes, one batch root 32 bytes. This excludes metadata, proofs and transaction overhead.

2. Run a controlled EVM study

Use npm test from B07 in a fresh results folder (move existing JSON/CSV first). The runner creates fresh GasStudy instances at 32,128,512,1024 bytes, three repetitions per size.

✓ Expected: Twelve paired raw/digest gas observations are recorded if actual execution succeeds.

3. Manual Remix alternative

Compile GasStudy.sol with B04 settings. For each payload size, deploy two fresh instances; call storeRaw with nonzero bytes of that size on the first, and storeDigest with the matching SHA-256 digest on the second. Repeat three times, save gas used from receipts.

✓ Expected: Each successful receipt has gas used. Deployment gas is excluded. Do not compare different forks or storage states without noting them.

4. Analyze

Compute mean and range per condition, plot rawGas and digestGas versus bytes; distinguish deterministic gas from randomized network delay.

✓ Expected: Conclude only from actual receipt data. Report optimizer, compiler, fork, source hashes and limitations.
Node.js terminal · blockchain directory
npm install
✓ 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

Gas study is not an energy or cost benchmark. Raw data is fictional and bounded to 1024 bytes. The browser calculator never predicts gas values.

GasStudy.sol

Download source file
Solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
/// @notice Gas study: compares bounded public storage to a fixed-size digest.
contract GasStudy {
    bytes public rawDemo;
    bytes32 public commitment;
    error TooLarge();
    function storeRaw(bytes calldata data) external {
        if (data.length > 1024) revert TooLarge();
        rawDemo = data;
    }
    function storeDigest(bytes32 digest) external { commitment = 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

B08 · 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: Fixed illustrative gas costs, not measured EVM gas. Use actual receipts in Remix for precise costs. Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.

01Instructions · Markdown
# B08 · B08 · Gas, scalability and experimental design **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## 1. Scientific objective Quantify the tradeoff of batching commitments versus per-record transactions. 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 Compare raw storage and digest storage using actual transaction gas, and distinguish bytes from gas. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Use 16 records × 64 B; calculate 1024 raw bytes, 512 per-record digest bytes and 32 root bytes. 2. Enter configured base gas 21,000 and anchor gas 20,000. Calculate the teaching gas budget for 16 separate anchors versus one batch root. 3. Repeat with one record and 32 records. Explain why payload byte count and gas cost are not equivalent. 4. Run the provided local EVM controlled gas experiment or Remix receipts and record actual gas separately. **Evidence:** Read-only local call does not pay a transaction fee. Failed included transactions can consume gas without committing contract state. **Boundary:** Fixed illustrative gas costs, not measured EVM gas. Use actual receipts in Remix for precise costs.
03Instructions · Markdown
## 2. Reference configuration and investigation 1. Use 16 records × 64 B; calculate 1024 raw bytes, 512 per-record digest bytes and 32 root bytes. 2. Enter configured base gas 21,000 and anchor gas 20,000. Calculate the teaching gas budget for 16 separate anchors versus one batch root. 3. Repeat with one record and 32 records. Explain why payload byte count and gas cost are not equivalent. 4. Run the provided local EVM controlled gas experiment or Remix receipts and record actual gas separately. Run cells in order; do not substitute model results for physical measurements.
04Instructions · Markdown
## 3. Compare raw records, digest bytes and a root commitment.
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# B08 | Code cell 01 | B08 · Gas, scalability and experimental design
# Purpose: 3. Compare raw records, digest bytes and a root commitment.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Set records for the next computation or reference condition.
records=16; size=64
# Set raw for the next computation or reference condition.
raw=records*size; digests=records*32; root=32
print(raw,digests,root)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert (raw,digests,root)==(1024,512,32)
Ask Dr. Mohammad about this cell
06Instructions · Markdown
## 4. Change the assumed transaction count and gas budget. These are assumed costs, not measured EVM gas.
07Python · executable cell
PYTHON · Code cell
# =====================================================================
# B08 | Code cell 02 | B08 · Gas, scalability and experimental design
# Purpose: 4. Change the assumed transaction count and gas budget. These are assumed costs, not measured EVM gas.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Set base for the next computation or reference condition.
base=21000; anchor=20000
# Repeat the same operation for each configured input so observations are comparable.
for count in (1,4,16,32):
    print(count,"separate",count*(base+anchor),"batch",base+anchor)
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. Enter configured base gas 21,000 and anchor gas 20,000. Calculate the teaching gas budget for 16 separate anchors versus one batch root. 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.