Random Thoughts

Measured waveforms, mel spectrograms, and pitch tracks for three vocal prayer recordings
Sacred Resonance

Can devotional sounds from different traditions share measurable acoustic patterns? That question led to Sacred Resonance, a small Python experiment comparing three vocal recordings: one associated with Hinduism, one with Christianity, and one with Islam.

The result is an exploratory comparison of three performances. It does not establish a common sacred frequency, and it cannot tell us what an entire religious tradition sounds like. It does show how a few sound measurements can make a listening question more precise.

Starting with three recordings

The project began with a broader collection idea covering chants and prayers across the three traditions. Narrowed the working experiment to three input files so that the measurements and their limitations would be easier to inspect. The three recordings selected for this run are:

  • Hinduism: Gayatri Mantra
  • Christianity: Abunbshmayo
  • Islam: Azan

The plots and tables retain the labels Hinduism, Christianity, and Islam so they match the script’s output.

Those labels identify the supplied recordings; they are not categories the software learned to recognize. The analysis does not inspect a file’s religious meaning or verify the identity of its chant.

What was measured

The script loads each file as a mono signal at 22,050 samples per second and trims leading and trailing silence. It then analyzes the full remaining recording. These files have different lengths; this run does not use matched 60-second excerpts.

  • Waveform: how the recorded signal changes over time.
  • Pitch: an estimate of the voice’s fundamental frequency where tracking is reliable.
  • Mel spectrogram: how energy is distributed across frequency bands over time.
  • Energy and spectral shape: signal strength, the balance of lower and higher frequencies, and detected changes in the sound.

Python, librosa, NumPy, and matplotlib provide the processing and plots. Unreliable pitch estimates remain missing.The script does not replace them with zero or invent a pitch value to complete a table.

Actual analysis: Hindu recording has a narrow estimated pitch track, Christian recording has sparse pitch estimates, and Islamic recording has a more variable pitch track
Actual output from the current three-file run. Rows show the supplied Hindu, Christian, and Islamic recordings. Columns show waveform, mel spectrogram, and estimated pitch. Each row has its own time and waveform scales; spectrogram colours are relative to that recording’s maximum.

What the current run found

Measurements after trimming edge silence
Recording labelDurationMedian estimated pitch
Hinduism204.90 seconds143.41 Hz
Christianity79.67 secondsNot reliably estimated
Islam182.97 seconds285.17 Hz

The Hindu recording had a narrow estimated pitch range of about one semitone. The Islamic recording showed a wider range of about seven semitones. These ranges describe the central 90 percent of valid pitch estimates, rather than every sound in the files.

Reliable pitch was available for only about 31 percent of frames in the Hindu recording and 27 percent in the Islamic recording. The Christian recording reached about 4.9 percent, below the script’s minimum coverage threshold, so its pitch summary was withheld. That is a limit of this measurement on this file, not an absence of pitch in Christian prayer.

The Christian recording also had a higher spectral centroid, meaning its measured energy was weighted toward higher frequencies. Microphone response, consonants, accompaniment, and recording conditions can affect that value.

Which recordings were closest?

For one comparison, the script averages each recording’s energy across 64 mel-frequency bands, normalizes that profile, and calculates cosine similarity between profiles. Higher values mean a closer broad spectral shape under this particular calculation.

Broad spectral-profile cosine similarity
Pair of recording labelsSimilarity
Hinduism – Christianity0.64
Christianity – Islam0.60
Hinduism – Islam0.45

The Hindu and Christian files were closest by this metric. A score of 0.64 does not mean “64 percent the same,” and it does not show that the prayers share a melody or meaning. Averaging a spectrum discards the order of sounds, phrases, and pauses.

Try the analysis yourself

The code, three input recordings, and results are available in the Sacred Resonance GitHub repository.

What I take from this experiment

There are measurable similarities and differences between these recordings. We have not established a shared acoustic signature across religions. With one file per tradition, singer, language, melody, room, microphone, production, and tradition are mixed together in the observations.

The next step is to repeat this comparison under controlled conditions, with multiple independent recordings and a broader range of religious sounds. The analysis should also extend beyond the features examined here. Perhaps a shared pattern will emerge. After all, every sound in this study ultimately comes from human beings.

AI and direct machine code generation
AI and Direct Machine Code Generation

The question

When we write a program today, there are usually several layers between our program and the CPU. This experiment started with a simple question: if AI understands the program and the target CPU, can it generate the machine code directly instead of going through all those layers?

A quick look at the usual approach

Consider a Java program. We normally write Java source code, which is compiled into Java bytecode. The Java Virtual Machine (JVM) runs that bytecode. While the program is running, the JVM can identify code that is being used frequently and compile it into native machine code for the actual CPU.

So the simplified path looks like this:

  • Java source code
  • Java bytecode
  • JVM
  • native machine code
  • CPU

The important point is that Java does eventually get down to machine code. The extra layers provide useful things such as portability and runtime optimization.

What is JIT?

JIT means Just-In-Time compilation. Instead of compiling everything to CPU-specific machine code before the program starts, the JVM can compile selected parts while the program is running.

This is useful because the JVM can observe what the program actually does. Code that is used very frequently can receive more optimization effort, while code that is rarely used may not need that work.

What is C2?

C2 is the name of one of the optimizing compilers inside the HotSpot JVM, which is the JVM implementation used by OpenJDK and commonly used for Java applications.

We do not need to understand the internal details of C2 for this experiment. At a high level, C2 takes frequently executed Java code, applies various optimizations, and produces native machine instructions for the CPU.

Our experiment

We wanted to see what happens if we skip the normal route and generate machine code directly.

We used AI to construct a minimal Windows 64-bit executable containing raw x86-64 instruction bytes. The final executable did not need an assembler or a C compiler to produce those instructions. Python was used only to construct the executable file and place the machine-code bytes and data inside it.

The program itself was deliberately simple. It calculated a dot product:

sum = A[0]*B[0] + A[1]*B[1] + ... + A[n-1]*B[n-1]

For the clean benchmark, the calculation used 100,000 elements and was repeated 10,000 times. That gave 1 billion multiply/add iterations in total.

Benchmark detail Value
Target Windows x86-64
Elements 100,000
Repetitions 10,000
Total multiply/add iterations 1,000,000,000
Expected dot product 29,050,000
Expected total checksum 290,500,000,000
Direct machine-code core 81 bytes

The result

The direct machine-code executable ran successfully on Windows and produced the expected result.

The core machine-code sequence generated for the calculation was only 81 bytes.

What did Java do?

We also looked at what HotSpot was doing with the equivalent Java program. The JVM compilation log showed C2 compiling our JavaBenchmark.work() method.

The log showed two relevant stages: an optimization of code while it was already running, called an OSR (On-Stack Replacement) compilation, followed by a normal C2 compilation.

The final C2 compilation reported 288 bytes of main native code. Looking at the generated instructions, we could see the expected low-level operations: loading array values, converting them to the required integer size, multiplying them, adding the results, and controlling the loop.

In other words, the JVM eventually produced real x86-64 machine code that was doing the same kind of work as our directly generated machine code.

What happened during the JIT transition?

We also ran a separate experiment specifically to observe the transition from initial execution to JIT-compiled execution. Instead of one very large measurement, the benchmark divided the work into 200 smaller invocations in the same JVM. Each invocation performed 10,000 multiply/add operations.

The timing pattern showed the behavior we were looking for: the early invocations took more time, while later invocations settled into a lower and more stable range. This is consistent with the JVM spending time profiling and compiling frequently executed code before the optimized version is used for subsequent executions.

The compilation log independently confirmed this transition. HotSpot reported an OSR C2 compilation of JavaBenchmark.work(), followed by a normal C2 compilation. The later compiled code was therefore not just an interpretation of the original bytecode; the JVM had generated native x86-64 instructions for the method.

This experiment is useful for understanding JIT overhead, but its timings should not be treated as a universal measurement of Java startup or performance. The exact transition point depends on the JVM, workload, hardware, and runtime conditions.

The timings we observed

We also measured the programs. The numbers below are useful as experimental data, but they should not be interpreted as a definitive Java-versus-native performance comparison. The native executable was measured externally as a separate process, while the Java timings were measured inside the same JVM process. Java can also spend time doing JIT compilation while it runs.

Implementation Measurement Duration
Native raw machine code External process timing 569.9437 ms
Java Run 1 344.429 ms
Java Run 2 344.125 ms
Java Run 3 341.650 ms
Java Run 4 345.005 ms
Java Run 5 340.381 ms
Java Run 6 353.870 ms
Java Run 7 349.026 ms
Java Minimum 340.381 ms
Java Median 344.429 ms
Java Average 345.498 ms

The important lesson from these timings is not that one implementation was faster. The experiment did not control all of the factors needed for that conclusion. The useful result is that both approaches successfully performed the same large calculation, while Java was also able to turn the hot Java method into native machine code during execution.

So why have all those layers?

The experiment might make it tempting to ask why we need bytecode and a JVM at all if we can generate machine code directly. The answer is that the extra layers solve real problems.

  • Portability: the same Java bytecode can be used on different CPU architectures.
  • Runtime optimization: the JVM can observe how the program is actually being used.
  • Runtime services: the JVM provides many facilities around memory management, safety, loading code, and execution.

Direct machine code gives up some of those benefits unless we build equivalent capabilities somewhere else.

Where AI changes the picture

Traditionally, portability meant that humans could write one program and use a common intermediate representation across different machines. The compiler and runtime handled the differences between CPUs.

AI introduces another possible model. Instead of keeping exactly the same compiled representation for every machine, we could give AI the program specification and the target architecture and ask it to generate an implementation specifically for that machine.

  • Traditional idea: write once → portable representation → run on many machines.
  • Possible AI-assisted idea: specify once → generate code for each target machine.

This does not automatically make direct machine-code generation better. It simply changes where the work is done. The compiler and runtime currently perform a large amount of that work; an AI-based system could potentially perform some of it before the program is deployed.

What did this experiment actually prove?

  • AI can generate a working Windows executable containing raw x86-64 machine-code bytes.
  • The final executable can run without an assembler or C compiler being used to produce those machine-code instructions.
  • A JVM such as HotSpot can itself generate native machine code from Java code while the program is running.
  • The machine code generated by C2 has the expected low-level structure for the calculation we tested.
  • Direct generation is therefore technically possible, but this experiment does not establish that it is generally faster or better than Java/JIT.

Conclusion

The interesting part of this experiment is not that we replaced Java with 81 bytes of machine code. The interesting part is that we saw, in a small and understandable example, that the path from a program description to CPU instructions is not fixed.

Today, compilers and runtimes perform much of the work of translating and optimizing programs. If AI becomes capable of reliably understanding a program, its constraints, and the target CPU, it may be possible to move some of that work into AI-assisted code generation and produce target-specific machine code directly.

This experiment is only a small proof of concept, but it demonstrates that the idea is technically possible and gives us a concrete starting point for thinking about what AI-generated software could look like beyond today's traditional compilation pipeline.

https://github.com/nenukc/ai-machinecode

Breath — Currency of Life
Breath — Currency of Life

Rethinking Effort and Human Life

“A being is born alone and dies alone.” — Garuda Purana

Yet humans have always organized themselves into groups. From tribes to kingdoms, from empires to modern nation-states, societies formed for protection, cooperation, and survival. Over time these structures evolved into complex hierarchies and systems of thought—political ideologies, economic models, and countless “isms” attempting to define how humans should live together.

Despite centuries of experimentation, we still struggle with a fundamental question: does society exist to serve the individual, or does the individual exist to serve society? At the root of this tension lies a deeper problem. Humanity has never agreed on a universal and natural way to measure human effort.

In early societies, effort was exchanged through barter. Later came currencies made of metals, paper money backed by institutions, and eventually digital balances recorded in financial systems. All of these are attempts to measure and exchange effort. Yet they remain abstractions—symbols that stand in place of real human life.

Yet the rhythm of human life itself has never changed. Life unfolds moment by moment, breath by breath. Every action—thinking, speaking, building, creating—draws from the same underlying rhythm of existence.

What if the most honest unit of human effort was not gold, paper, or digital numbers—but breath itself?

Breath as the Fundamental Unit of Life

Breath is the most immediate expression of life. Every human shares it. Every moment of activity consumes it. Unlike money, breath cannot be stored indefinitely or accumulated beyond the limits of life itself.

Ancient Indian traditions observed that a healthy human breathes roughly 21,600 times in a day. Over a theoretical lifespan of 120 years, this corresponds to approximately 946 million breaths in a lifetime.

Unit Relation Approximate Time
1 Prāṇa One breath cycle ~4 seconds
6 Prāṇa 1 Vināḍī(Pala) ~24 seconds
60 Vināḍī 1 Nāḍī(Ghati) ~24 minutes
60 Nāḍī 1 Day–Night ~24 hours

In this view, time itself unfolds through breath and life becomes the gradual expenditure of these breaths.

Breath and Free Will

Most biological processes operate beyond conscious control. The heart beats, blood circulates, and cells regenerate automatically. Breath is unique because it lies at the intersection of automatic life processes and conscious control.

Life provides the breaths.
Time counts them.
But the mind decides how they are spent.

Breath as Currency

If breath represents life expenditure, it can also serve as a natural unit for measuring human effort.

In a breath-based economy each individual maintains a breath account. When a person needs work done, they describe the task and the skills required. Workers perform the task, and the breaths expended during the work become the payment request. These breaths are transferred from the employer’s account to the worker’s account.

  • Employers prefer workers who complete tasks with fewer breaths.
  • Workers improve their skills to perform tasks more efficiently.
  • Reputation becomes the primary driver of opportunity.

Entry Support and Collective Accounts

Young individuals entering the workforce may lack experience or reputation. Governments or communities can provide limited incentive breaths so that new participants remain competitive.

Unlike modern fiat systems, no authority can create breaths arbitrarily. Every breath distributed by governments must come from a collective account funded by real contributions from society.

Environmental Implications

Environmental damage increases the effort required to sustain life. If polluted cities require more breaths to clean streets, filter water, or maintain infrastructure, society must expend more life energy.

In this framework protecting nature becomes economically rational because it reduces the breaths required for survival.

Nations and Cooperation

When measured in breaths, large-scale conflicts such as wars become visibly irrational. War consumes enormous human life energy and requires even more breaths for reconstruction.

International cooperation therefore becomes the more efficient path for human civilization.

Common Questions

Is breathing rate too variable to measure effort?

Actual breaths expended during a task are measured. Over time large datasets allow governments to maintain baseline breath estimates for common tasks.

Can people game the system by breathing more?

Workers who artificially inflate breath expenditure become inefficient and lose future work opportunities as employers prefer more efficient individuals.

What happens to breaths after death?

Remaining breaths return to the collective system pool. They are not inherited, preventing generational accumulation of wealth.

What about thinking jobs vs physical jobs?

All work consumes breaths. Education and training themselves require large breath investments, allowing skilled individuals to perform specialized work efficiently.

Are loans possible?

Traditional loans are avoided. Breaths represent life expenditure and should not be borrowed from the future.

How are job expectations estimated?

Governments can maintain baseline breath estimates for common tasks to guide employers when requesting work.

Can accounts go negative?

No. Overdrafts are not allowed. Work must be backed by an existing breath balance.

Conclusion

Human societies have long searched for systems that measure effort and organize collective life. Most rely on abstractions increasingly detached from the reality they represent.

Breath returns us to that reality.

Every action consumes a portion of our finite life. If effort and value are understood through breaths spent, our priorities may gradually shift toward balance, cooperation, and meaningful contribution.

Between birth and death lies only a finite number of breaths.
How we spend them ultimately defines both our lives and the societies we build.

Stock market prediction illustration
Stock Market Trend Prediction

Prediction of stock market trends has been an area of great interest both to researchers attempting to uncover the information hidden in the stock market data and for those who wish to profit by trading stocks. The extremely nonlinear nature of the stock market data makes it very difficult to design a system that can predict the future direction of the stock market with sufficient accuracy. News contents are one of the most important factors that have influence on the market. Considering the news impact in analyzing the stock market behavior, leads to more precise predictions and as a result more profitable trades.

This work done as part of my M.Tech project work in 2011, presents a data mining based stock market trend prediction system, which produces stock market forecasts. The proposed system is a hybrid of Support Vector Machine (SVM) based News article Classification and Exponential Moving Average (EMA). The uniqueness of the proposed system lies in the use of News Article terms and Technical analysis indicators like EMA to predict the directional movement of Stock Market in the near future. The prediction generated by this system will aid short term traders in decision making.

Sensex Prediction High Level Design

Sensex prediction system diagram

Detailed documentation and Code is available on Github. As the solution involves web scraping from multiple sources, some of the target URLs and page composition has changed over the last decade. So expect run time errors. I removed most of the hardcoded values, nevertheless this would give a basic idea of news sentiment analysis and stock market trends using AI, many years back. Don't expect much accuracy in the predictions, it's a work in progress.

https://github.com/nenukc/SensexPrediction

EVM process illustration
EVM – Critical Analysis

TRANSPARENCY IN THE INDIAN ELECTRONIC VOTING MACHINES (EVM) PROCESS: A CRITICAL ANALYSIS

EVM - Known Technical Limits

  • 16 candidates per Balloting unit.
  • 24 Balloting units can be connected to a control unit (M3).
  • Max. candidates using EVM’s – 384 (16 × 24).
  • Max. votes per EVM (M3) – 2000.
  • Average slips per VVPAT roll – 1500.
  • Time VVPAT slip is displayed – 7 seconds.
  • Max votes per minute – 5.

EVM Process Stages

First Level Check & Mock Poll – 1 (Polling Day -120): Initial functional checks and random verification of EVMs.

EVM – 1 vote against 16 candidates and cleared for each EVM, additionally 5% of EVMs are verified. (Random manual selection) - 1% -1200 votes, 2% - 1000 votes, 2% - 500 votes. VVPAT – 96 vote slips in each VVPAT. (6 Votes per contestant)

First Randomization (P-21): Allocation of EVMs across assembly constituencies.

Second Randomization (P-14): Allocation of EVMs to polling stations within a constituency.

Candidate Setting & Mock Poll – 2 (P-14): Assignment of candidates to EVM buttons.

EVM – 1 vote against each EVM, 1000 votes on 5% of EVMs. (i.e. 50% of EVM capacity) VVPAT – 1 vote slip per VVPAT.

Polling Day & Mock Poll – 3 (P-0): Final functional check before polling begins.

EVM – 50 votes per EVM, VVPAT – 50 vote slips.

Polling & Counting: Voting and tallying results.

Retention Process: Data retention for post-election audits.

Notes

Process

  • EVM Stock changes happen at central level.
  • EVM warehouses are at District level, so set of EVMs to be used at a district level is already known after FLC i.e. 120 days prior to Poll Day.
  • FLC related register will be given to all National and state level recognised political parties. Serial number of the control unit related seal number is also recorded.
  • Engineers who do FLC will be randomized at state level, to reduce possibility of manipulation by engineers.
  • First randomisation is between Assembly constituencies and Second randomisation is between polling stations within an assembly constituency.
  • Preparation of ballot paper on EVM is known as candidate set.
  • Candidate names are arranged in alphabetical order within three categories – recognised national and state parties, unrecognised but registered parties, independent candidates and lastly NOTA. Some of the seats candidates are already known among the political parties, exposing EVM button positions even before P-14th day.
  • After 2nd Randomization i.e. 14 days prior to the polling day, exact EVM and button associated with a particular candidate is available.
  • Mandatory check of VVPAT is for ONE polling station only, Supreme court increased it to 5 random polling stations per Assembly, political parties are requesting for 50% polling stations to be considered.
  • VVPAT check request can be placed but RO will decide if it is required based on vote margin, VVPAT or EVM complaints.
  • Random VVPAT polling station selection is made by RO using draw of lots.
  • Paper slips have precedence over EVM count.
  • Data is stored for 45 days after the result is declared.
  • All EVMs are protected after classification into category A, B, C and D. Category A - is polled and worked, B is polled but stopped working, C - Not polled not working, D - Reserve.
  • Yellow colour sticker is used on training EVMs. Green will be used for voting EVMs.

People

ECI > State level CEO > District Election Officer > Returning Officer > Presiding Officer > Polling Officers

Independent Observers

Central Police Force forms the innermost security perimeter and State armed police force forms the outer perimeter around the strong rooms.

Technology

  • Software is converted to machine code and then given to foreign industries to provide the microchips. Each microchip has an identification number and a digital signature of the manufacturer so that chips cannot be changed.
  • Symbol loading units (SLU) are used for loading party symbols to VVPAT. These devices are with district election officer on the poll day to avoid any manipulation.
  • ETS – Old EVM tracking software, has all the FLC details of EVMs.
  • EMS – EVM management system has web and android interface, multiple individuals from CEO have access to this software.
  • EVM randomization happens using EMS software not manually, random function used is unknown.
  • Even though VVPAT is in the middle of BU and CU, a signal confirming the vote goes back to BU from CU, so VVPAT if manipulated during symbol loading has to handle both directions of information flow.

Issues Addressed

  1. Can a voter place a sticker and another voter remove it after an hour? Presiding officer does random checks and will be spotted in VVPAT by voter.
  2. Dynamic coding of key press feature in EVM to handle man-in-the-middle issues.
  3. FLC related 5% EVMs are picked up randomly by political party representatives. Can malicious code activate after the max vote check say after 1200? Till 2019, 1200 votes per booth limit would have handled this issue, ECI later increased the limit to 1500 but did not increase the corresponding mock testing size resulting in a gap. This 1200 number has been arrived at taking into account 5 votes max per minute limit on an EVM and average polling hours.
  4. Introduction of VVPAT has reduced the possibility of EVM manipulation to a large extent but introduced its own gaps because of symbol loading in the process.
  5. Can same set of EVMs and VVPATs be replaced after polling? Highly unlikely due to signature-based seals.

Open Queries

  1. Why only representatives of recognised political parties for FLC? How will ECI ensure existing political parties will not gang up against a new party?
  2. Why is there a delay and inaccuracy in acquiring the poll percentage, considering that ‘Total’ button would give an accurate number quickly compared to pre-EVM era.
  3. An EVM can poll max of 5 votes per minute, so 300 votes per hour, how can the poll percentage increase all of a sudden in the last few hours?
  4. What are the distribution statistics related to M3 and M2 EVMs in recent elections?
  5. How will one ensure that VVPAT printer is not maintaining a printer queue and prints the slips later?
  6. Why VVPATs are not uniquely identifiable in the ETS/EMS software? Why 0 to all VVPATs?
  7. Why would VVPAT go into error mode when used under direct sunlight or bright lights? Why thermal printing was opted for VVPAT?
  8. Why is the testing of VVPAT at dispersal strictly prohibited under "any circumstances" – what could be the logic behind this strict note in the ECI manual?
  9. If EVMs need to be replaced, only 1 vote is checked not minimum 50, this is a point for exploitation. How many EVMs have been replaced in each election from each booth? Is the data openly available? Did the political parties accept the data ECI published?
  10. Only 96 votes are tested in FLC for VVPATs out of 1500 per VVPAT roll. Why such a low number?
  11. How can ECI rule out malicious code injection at coding level? How will ECI gain voter confidence on this risk with closed source code?
  12. What kind of manipulation possibility was handled by placing the symbol loading units with DEO on polling day?

Suggestions

  1. Guiding motto for ECI should be to gain the trust of the voter, this can only be achieved by being transparent at every step and by being open for discussion on the process.
  2. Focus should be on reliability of the system and not on speed and practicality.
  3. Software used should be open source, including the random function used in EMS software for EVM randomisation.
  4. Using chemicals, heat and light in the VVPAT system increases the complexity of identifying any exploitation points.
  5. Candidate setting could be done after 2nd randomisation instead of 1st. Candidate list order has to be randomised for each polling station i.e. Candidate setting has to be at polling station level.
  6. All documentation should be available to the public on time. Hard copies should be sent to all the participating political parties.
  7. Account of votes register and incidents related documents should be made public to ensure polling agents have not colluded.
  8. Webcam feed data should be preserved for legal scrutiny during conflict resolution.
  9. Voting pattern data from the control unit should be preserved for legal scrutiny during conflict resolution.
  10. All vendors involved in hardware and software should be made public both domestic and foreign.
  11. An EVM test centre should be available to the public in the national capital to test out the EVMs.
  12. There should be no separate battery to power the VVPAT, it should derive power from control unit so that printer queues related risk doesn’t arise.
  13. When a voter registers a protest of mismatch regarding VVPAT, very next vote should not be used to confirm the behaviour as malicious code logic might not repeat immediately.
  14. Malicious code can trigger at any point of time, so during FLC, 1500 votes (max. per booth) should be tested and matched with VVPAT slip count.
  15. Number of times result fetched should be displayed on counting day, this is to ensure no one has accessed the counts after polling day.
  16. VVPATs should be placed in a separate room with reverse of security layers to that of control unit.
  17. CAG should conduct an audit of each election and share its findings.

Conclusion

Any system’s reliability depends on the people involved, process maturity and technology. Regarding EVM, manipulation is quite possible with the current setup. Closed software, hidden device architecture and lack of transparency in documentation, inaccessibility of EVMs for testing purpose all add to loss of trust.

One possible imaginative scenario on how EVM could be manipulated is given below.

Malicious code section (inserted in software or software pointer to a chip that holds the malicious code) + trigger through input buttons on CU or BU (secret knock) + chemical paper, thermal printing and VVPAT light.

While developing the EVM software or hardware itself, malicious code might have been inserted that can be triggered using buttons on the control unit or Balloting unit, say a combination press of keys on BU, or on pressing “clear” n times or on pressing total and ballot button n number of times etc. Another way could be sequence-based triggering using a set of voters, say 6 voters press NOTA button one after the other triggering the malicious code. These combinations are so huge that they can never be tested exhaustively. Once the malicious code section is triggered, it can do multiple things, add votes to one party every 10 votes or so etc., the same malicious code might be sending a signal to the VVPAT as well suggesting to heat the thermal printing paper “differently”. As the paper in thermal printing uses chemicals and heat, the light in VVPAT might help in displaying the right party at that moment to the voter but later can change to the desired party. Also, care might have been taken to ensure this doesn’t happen at the very start of the VVPAT roll to overcome mock checks.

Entire process spans multiple technical disciplines including computer science, electronics, chemistry requiring multiple individual experts to identify any loop holes, ruling out any single voter to raise a flag. Considering the lack of transparency and the complexity involved, the existing process has to be changed significantly or scrapped entirely to gain the trust of the voter. Entire election process not only has to be transparent but it should also appear to be transparent to an average voter.

Bitcoin Lottery Mining
Bitcoin Lottery Mining

In continuation of the theoretical analysis of Bitcoin design in my earlier post, below is a practical attempt at Bitcoin mining using random values on a single thread with a not-so-fast Python code (to prevent overheating the laptop). Consider this as Bitcoin lottery mining.

Block Header Variables and Mining Process

Before diving into the code, let us understand the block header variables that can be altered to achieve the required difficulty level of the output hash.

A Bitcoin block header is 80 bytes (640 bits) in size and consists of the following fields:

Bitcoin block header illustration

The output hash of the above inputs exists in a 2^256 possibilities space, which is immense compared to the nonce space (2^32) that miners generally iterate over to find a valid hash under the difficulty target.

Statistical Analysis of Random Mining

Below graphs suggest the uniform distribution of nonce values and output hash values, ruling out any pattern analysis or heuristics. In fact, randomness is inherent in SHA-256, and Bitcoin employs double hashing (SHA256d) at multiple points in its design.

Statistical graphs placeholder

Statistical Values over 1000 Blocks

  • Nonce Distribution: Mean: 2,081,172,767.407 Standard Deviation: 1,208,351,280.655
  • Hash Distribution: Mean: 6.605958045090711e+63 Standard Deviation: 4.681072803036996e+63

Merkle Root Calculation

The Merkle root is crucial to the block hash and is computed as follows:

  1. Collect the Transaction Hashes – Start with the hashes of all transactions in the block. Each transaction is typically hashed using SHA-256 twice (SHA256d) in Bitcoin.
  2. Pair Up Hashes – If there is an even number of hashes, group them into pairs. If there is an odd number, duplicate the last one to maintain pairing.
  3. Hash Each Pair – Concatenate each pair of hashes. Hash the concatenated result using SHA-256 twice (SHA256d).
  4. Repeat Until One Hash Remains – The new hashes form the next level of the Merkle tree. Repeat steps 2 and 3 until only one hash remains—this is the Merkle root.

Note: The coinbase transaction is custom-built by the miner and is not part of the block header. However, since it is the first transaction in the block, any changes to it affect the Merkle root, making it a variable in the block hash generation algorithm.

Avalanche Effect of SHA-256

SHA-256 exhibits an avalanche effect—any small change in input drastically changes the output. Example:


Nonce: 728825053 → Hash: 8861458f8b7ac539f0b8e0a0276cfe5601e3223a815232c3d691e9a65e1b9aef
Nonce: 728825054 → Hash: 000000000000000000027755490437d3e7670033bdca1b1417a23fbe57691a07 (valid block)
Nonce: 728825055 → Hash: a397f41ba66e9fe46f2305670d904a2e94932fccba2a1e45ac121f6275ae27a6
    

Repository and Setup Instructions

  • GitHub Repository: Bitcoin Random Mining
  • Install Bitcoin Core: Download Here
  • Pruning Setup: Set prune block size to 1 GB
  • UTXO set size: ~11GB as of March 14, 2025
  • Total space recommendation: At least 20GB
  • If running a full node, it requires 650GB+, Refer below screenshot.
Bitcoin Core pruning placeholder
Placeholder for pruning and setup screenshot

Pruning and RPC setup

Note: Ensure you regularly sync the blockchain when using pruning, else wallet will not be accessible till the entire blockchain is downloaded again.

https://github.com/nenukc/bitcoin-random-mining

Bitcoin wiring diagram
Understanding Bitcoin Design

Introduction to Bitcoin

A digital currency is a form of money that exists purely in an electronic form, Bitcoin is one such digital currency that relies on a peer-to-peer (P2P) network to maintain its ledger. This decentralized design enables bitcoin to address the double-spending problem of digital currencies, without requiring a financial institution as an intermediary.

Bitcoin transactions are basically string entries recorded into blocks, which are then linked together to form the blockchain. Imagine transactions as entries in the ledger page, block as the page and block chain as the ledger book. Multiple copies of this blockchain are maintained across the network, providing security and redundancy.

Basic Bitcoin Concepts

  • Blockchain – A public digital ledger recording transactions.
  • Satoshi – The smallest unit of bitcoin (1 Bitcoin = 100,000,000 Satoshis’).
  • UTXO (Unspent Transaction Output) – Represents the remaining balance from a transaction.
  • Mempool – A memory location were all the unverified transactions are stored.
  • PoW – Proof of Work – Backbone of Bitcoin design ensuring fairness using gaming theory.

Bitcoin Design Assumptions

Bitcoin's security is built on the assumption that at least 51% of nodes in the network remain honest, preventing fraudulent modifications to the blockchain. The credibility of Bitcoin incentivizes participants to act honestly, as trust in the network directly affects Bitcoin’s value.

Bitcoin Transaction Process

Transaction Flow

  1. A user initiates a Bitcoin transaction, which updates the blockchain ledger.
  2. The sender’s private key is used to authorize the transaction by signing the UTXOs.
  3. The receiver’s public key hash is used as the destination address.
  4. The transaction is broadcasted to the network and enters the Mempool.
  5. Miners validate the transaction, include it in a block, and add the block to the blockchain.
Bitcoin flow diagram

Transaction Components

Each Bitcoin transaction contains specific fields:

  • Version: Specifies the transaction format.
  • Inputs: References previous UTXOs, including:

TXID: Transaction ID of the previous transaction, this is how transactions are linked to one another across blocks, forming a trail of transfer of ownership of bitcoin from the point it was mined.

Output Index: Position of the UTXO in the previous transaction, this is required as a single transaction can have more than one output.

ScriptSig: Contains the sender’s digital signature and public key, this enables the miners to validate the transaction. They use to the public key on the transaction fields and compare it with the digital signature to validate the sender’s ability to initiate the transaction.

Sequence: Used for time-locked transactions or Replace-By-Fee (RBF).

  • Outputs: Specifies new UTXOs created, including:

Value: Amount of Bitcoin being sent.

ScriptPubKey: Locking script containing the recipient’s address.

Locktime: Specifies the earliest time a transaction can be included in a block.

{
  "txid": "42e1436a6ec1a65c783a3b02eafa352302f4415c14602f26daa4f8181a02eccc",
  "size": 194,
  "version": 2,
  "locktime": 0,
  "fee": 5000,
  "inputs": [
    {
      "coinbase": false,
      "txid": "f29a6c29de88ec043eddef6d65f7e7ef6e778f2d90741b2e018a6e69caceedb9",
      "output": 69,
      "sigscript": "",
      "sequence": 4294967293,
      "pkscript": "0014f8c6f40fccbfabfd6ae8f19c25d28ec889c2fda5",
      "value": 21747,
      "address": "bc1qlrr0gr7vh74l66hg7xwzt55wezyu9ld9whrksw",
      "witness": [
        "30440220406af6acbfba91e82fa34c40e1d4e58fd0aed4e83be41c4bc16694728e073e55022045624e44867b6b77c9b70456085b3e6ecf4ba171f2d6c92ef2087b78cf00a6ff01",
        "03b8fc5c116bd5a1ae4135c45c8e19749d5fd9134e5bbafa8bed67ba44aeaf05c4"
      ]
    }
  ],
  "outputs": [
    {
      "address": "1Ny9toPUCkeidGzHBSjq1NJ9GzwS1UWybB",
      "pkscript": "76a914f0f95be137ece93262b4e24ee1313748300226dd88ac",
      "value": 16747,
      "spent": false,
      "spender": null
    }
  ],
  "block": {
    "height": 884415,
    "position": 2
  },
  "deleted": false,
  "time": 1739938867,
  "rbf": false,
  "weight": 449
}

*Above transaction is in JSON format for readability, Bitcoin uses Serialized binary in Hex format.*

UTXO Selection Algorithms in Wallets

Bitcoin wallets use different coin selection algorithms to choose UTXOs efficiently

  • Largest First: Uses the largest UTXO first, reducing future transaction sizes.
  • Smallest First: Uses the smallest UTXOs first, avoiding dust buildup.
  • Best Fit (Least Change): Selects UTXOs that minimize leftover change.
  • Knapsack Solver: Optimizes selection to match transaction value.

Transaction Verification

Submitted Transactions are verified by full nodes, after which they are included into the Mempool.

Verification involves checking if the sender has sufficient balance in terms of UTXO, if the digital signature provided is valid (Public key of the sender is used), transaction doesn’t result in double-spending.

Miners select verified transactions, prioritizing those with higher fees per byte instead of higher value, as there is a 1 MB block size limitation. Miners try to fit in as many transactions as possible in 1MB that would generate the highest amount of transaction fee per block.

Miners compete to find a valid hash by adjusting the nonce meeting the difficulty requirement. (Proof-of-Work)

The first miner to solve the Proof-of-Work (PoW) puzzle adds the block to the blockchain.

The miner is rewarded with new Bitcoins (block reward) and transaction fees of all transactions included in the block.

If two miners create blocks simultaneously, the longest chain is chosen.

This process of adding a new block to the block chain is known as mining as it results in new bitcoins.

Proof of Work (PoW) Mechanism

  • PoW ensures decentralization and fair competition among miners, also PoW is an NP problem based on computational science making it easy to verify the hash but difficult to solve for a hash.
  • Bitcoin software adjusts the difficulty after every 2016 blocks (~2 weeks) based on the hash rate availability i.e. how quickly or slowly these 2016 blocks were mined.
Bitcoin related diagram
  • After picking up validated transactions from the Mempool, Miners must find a hash value below a set difficulty target for the block header. This is done by tweaking nonce, timestamps, Coinbase transaction details and sometimes even the selected transaction list itself.
  • Block reward halves every ~4 years, ensuring a total supply cap of 21 million BTC after which the incentive for adding blocks would just be the Transaction fees.
  • Nonce is a 32-bit number (4.3 billion+ possible values) used to tweak the hash output. Since multiple nonce values can be valid at any difficulty level, miners iterate through different values to find a valid hash. This iterative process ensures fair competition and prevents attackers from rewriting blocks too quickly.

Bitcoin Trivia

  • Genesis block – The first block in Bitcoin’s blockchain.
  • Pizza day – First real world bitcoin transaction happened when a programmer paid 10000 bitcoins for two pizza’s worth 41$ on 22-May-2010, this day is celebrated as the Bitcoin Pizza day every year.
  • Transaction confirmation depth – Number of blocks added after the transaction has been verified to the block chain. 6 confirmations is the standard for large transactions, this is known as the Gold standard. 12-24 confirmations is generally used for Institutional transfers and cold storage providers and exchanges like Coinbase look for 100+ confirmations.

Attacks and Network Stability

  • Transaction Starvation Attack - Malicious actors spam transactions with high fees to delay low-fee transactions discouraging wide spread use of bitcoin. Circular transactions could be used for this purpose by corporates or governments that would like to discourage use of anonymous and independent financial systems like the Bitcoin.
  • The 51% Attack and Security – Malicious actors try to modify confirmed blocks by creating a longer block chain than the honest miner’s chain by achieving 50%+ of the available hash rate. As bitcoin nodes follow the longest chain rule whenever a fork happens, the altered attackers block chain becomes the legitimate one. This would result in double spending and blocking of other transactions from being confirmed destroying the trust in Bitcoin system. Though theoretically possible, it is highly impractical for the following reasons

High computational costs make it economically irrational. The attacker has a short window of opportunity to alter multiple blocks and also solve the Proof of work considering an average block generation time of 10 mins.

A successful attack reduces trust in Bitcoin, devaluing the attacker’s own holdings thus discouraging malicious intent.

Honest miners have strong incentives to control majority of the total hash rate available through fair competition resulting in block and transaction fee rewards.

Mining feasibility

Considering the huge computational requirement for mining, for most users, the only remotely feasible way of successfully mining using personal computers, is by using random values and not by brute forcing all possible values. Users can run process daemons randomly varying few possible values of the nonce and other block variables during the short interval available before a new block gets added to the block chain. Normal users can never compete with the mining pools that use dedicated hardware in an iterative way. Users can try their luck by running a full node on a normal machine, periodically fetching the Mempool transactions, trying out few random values and directly submitting to the network if ever a valid hash is generated within small window of opportunity. As on 25-02-2025 the size of a full node is about 640 GB and is increasing about 16% per year.

The other way to involve in mining is by investing into ASIC miners like Ant miner S19 XP which consume about 3.2 kW of electricity. In India, Himachal Pradesh seems to be a relatively suitable location for mining rigs due to its cold climate, low electricity costs and fair internet availability. One might be able to generate about 30,000/- rupees per month by joining a mining pool.

Final Thoughts

Bitcoin is a fusion of cryptography, economics, and decentralization, ensuring security and transparency in financial transactions. Its limited supply, strong security model, and decentralized nature make it a revolutionary financial system that brings control back to the people.

In the short term Bitcoin seems to be a promising alternative to the existing financial system but as every Technology, it too has to adapt to the emerging challenges to maintain its relevance in the long term.

One of the challenges it would face is the impact of quantum computing on cryptography which is a key component of the overall Bitcoin design. Bitcoin may adapt to this challenge by implementing Quantum-resistant cryptography but it would again have to deal with tradeoff related to decentralization as quantum computers might be out of reach for normal users.

Another challenge is its ability to keep miners interested even after all the bitcoins have been mined using just the transactional fee as an incentive. Without the block rewards, Bitcoin may end up as a settlement layer instead of a popular transactional network or it could even end up like Gold as a storage currency.

Bitcoin's long-term success will depend on its ability to evolve through solutions like regional network layers and Lightning Network offloading, preserving its core principles while adapting to technological advancements.

Reference

https://bitcoin.org/bitcoin.pdf