Bitcoin Script Engineering part II

11 min readApr 12, 2020


The goal of this article is an introduction to the original Bitcoin capability of smart-contract creation. Namely, Bitcoin with an original set of opcodes of its native language called script and original protocol that was designed and set in stone by its creator over a decade ago.

Moreover, in the light of plentiful negation of Bitcoin completeness through recent years, the article is engaged with so called stateful smart-contracts which preserve state during their execution from one transaction to another. A past claim of Bitcoin inability to create such stateful contracts actually was what induced and justified the existence of “alternative” platforms.

For demonstrating the above capability a first financial instrument contract was created, described below in this article. This contract will provide an initial basis for creation of further various financial instrument projects such as futures, insurance policies and other diverse derivatives and hedging contracts.

This is purely L1 contract, meaning its data and code reside and preserve its state exceptionally in spendable transaction outputs being executed from one hop to another, no off-chain calculations and unspendable (so-called OP_RETURN) transactions outputs are used for state-preserving implementation.

1. Prerequisites:

My previous project was “Dead Man’s Switch” (aka “Last Will”), which was the first stateful Bitcoin-script (L1) smart contract ever written with an original-only set of script opcodes, thanks to the Genesis upgrade that made it possible.

If you haven’t read it yet and are not familiar with the way Bitcoin smart contracts work, I suggest you pause and do some catch up reading to close the knowledge gap before moving on:

2. The Oracle

2.1 Intro:

The oracle is a source of real world data that may be fed into Bitcoin smart-contracts.

They are a way to incorporate external information, which may be easily cryptographically verified inside the contracts.

An Oracle’s reputation is its most important thing, incorrect data written once to a publicly open ledger will irreversibly damage it once and forever.

But even so, there are ways to achieve better oracle security by coordinating inside the smart contract:

  • more than one independent oracle inputs
  • m out of n’ determining data accuracy
  • more complicated threshold oracle systems described here

Another security improvement could be adding escrow amount in case of his failure to perform and eventually — law accountability through its real-world identity.

Now for our specific case, let’s define an “open usage” kind of oracles, meaning their data is open free to public use by whoever needs it, without the oracle itself even knowing who the users are.

In this case it just publishes the data periodically on the Bitcoin global ledger and it is a user responsibility to collect and include it in a smart-contract which explicitly demands this data provably signed by a specific one, several or ‘m out of n’ oracles for its successful execution.

2.2 Rabin signatures

Rabin signatures applicability for Bitcoin was explained some time ago by Owen Vaughan (Director of Research, nChain) and recently implemented by sCrypt Inc. I will just put couple of excerpts here:

It is an alternative digital signature algorithm (DSA) to ECDSA used in Bitcoin. The security of Rabin signatures depends on the fact that calculating a modular square-root is as hard as integer factorization”.

“A Rabin signature has the beautiful asymmetry that signature generation is computationally expensive, but signature verification is computationally cheap. This property renders it extremely amenable to an on-chain implementation, where only signature verification is needed.”

So the idea for ‘open usage’ of a trusted oracle would be just — each time it publishes the data, to put next to it his Rabin signature and corresponding public key. The public key should be widely known and used for validation by any party utilizing the data (which has enough trust for this specific oracle).

2.3 Meet the oracle:

Now, let me introduce to you our ‘open usage’ oracle. It actually was created half year ago:

Autonomous weather station which is a Raspberry Pi computer with a Sense HAT attached to it that has a temperature and humidity sensors collecting data to be sent time-stamped straight to the Bitcoin¹ ledger. And like one smart guy said once:

So, yes, in the way we use it, it actually enables us to have a self-contained project from hardware up to the contract written onto the global ledger.

And finally it has another very important historical property — it also sends along with this data a BSV-USD exchange rate (Bittrex), which makes this contract a real world application, doing all its payments and calculation in USD.
This is how oracle’s output looks on the ledger:

3. The contract:

One of the most straightforward use-cases for our oracle would be a contract made between a farmer and some counterparty, since the farmer’s crop is highly susceptible to extreme weather conditions like frost or drought, in other words a “Weather Derivative”.

“A weather derivative is a financial instrument used by companies or individuals to hedge against the risk of weather-related losses. The seller of a weather derivative agrees to bear the risk of disasters in return for a premium. If no damages occur before the expiration of the contract, the seller will make a profit. In the event of unexpected or adverse weather, the buyer of the derivative claims the agreed amount.

It is estimated that nearly 20% of the U.S. economy is directly affected by the weather, and the profitability and revenues of virtually every industry — agriculture, energy, entertainment, construction, travel, and others — depend to a great extent on the vagaries of temperature, rainfall, and storms. ” — James Chen, Ivestopedia

  • Agriculture, tourism and travel, and energy are just a few of the sectors of the economy that can be negatively impacted by extreme or inclement weather.
  • To mitigate the risks emerging out of damaging weather factors, weather derivatives have gained tremendous popularity.
  • These are financial instruments that work like insurance, paying out contract holders if weather events occur or if losses are incurred due to certain weather-related events.

Terms of the contract:

The simplest yet reasonable terms for such a contract to be implemented can be:

  1. Farmer paying regular payments to the counterparty in regular predetermined intervals
  2. The counterparty covers the farmer’s loss, in case extreme weather conditions occur

Since the Bitcoin-USD exchange rate is still prone to significant volatility (due to the lack of liquidity and market nascence stemming from limited real usage) the amount of Bitcoin locked in the contract should always significantly exceed the amount that may be claimed by the farmer at any moment of contract duration. Meaning, it is the counterparty’s obligation to maintain sufficient collateral. Simplest suggestion to achieve this would be to determine soft and hard thresholds, in other words:

3. The counterparty must have an ability to add funds (in Bitcoin) to already previously locked ones when the rate descends.

4. Crossing down the soft threshold would be considered a soft-violation and result in the counterparty paying a fine to the farmer instead of him paying his regular payment.

5. Crossing down the hard threshold would be considered a final contract violation by the counterparty and the farmer could take all the remaining locked funds.

So simply put, the contract may be violated by both sides: either by the farmer — if he stops paying regularly, or by the counterparty itself if it doesn’t maintain the amount of funds in smart TX output covering with a vengeance the agreed possible claim amount according to current exchange rate.

4 Script Engineering:

4.1 State machine:

While each subsequent state is determined by the final date the farmer has to make his payment by (also called a cancellation date), there are 3 kinds of states in this machine:

4.2 Structures and actions:

At this section I presume that the reader is already familiar with all the stateful contracts material and examples from preceding prerequisite articles.

To implement this state machine it took:

  • 6 different types of TX structures
  • With 5 different types of scriptSigs (from now and on called unlocking scripts), each exerting (the term spending becomes irrelevant here) its specific action on the contract (scriptPubkey, from now and on sometimes called locking script), and each differently structured.

Let us look at them closer one by one:

I will omit mentioning the step of validating access to TX fields from within script execution (which enables making it stateful), since it’s the first thing all of them are doing.

Posting the contract:

This transaction is spending a preceding simple P2PKH* UTXO that belongs to a counterparty while just publishing the contract in its locking script to the global Bitcoin ledger.

Farmer’s regular periodic payment:

TX structure:

Unlocking script exerts the following actions (example of detailed technical description):

1. Parse next smart locking script into cancellation time field and the remainder, then validate:

  • next cancellation time exceeds previous by exactly predetermined payment period
  • the rest of the next script (code part and constants) stays identical

2. Check validity of oracle’s output (namely, Rabin signature authentication and Rabin public key belongs to the oracle written in the contract), then validate:

  • The weather conditions are not extreme (temperature and humidity)
  • Oracle’s time-stamp is within the range of last two cancellation times

3. Third output, validate:

  • It is P2PKH to predefined counterparty PKH (raw address)
  • Payment amount is correct according to exchange rate in oracle’s output

4. To avoid funds leakage to miners — validate smart input amount is equal to smart output’s one

5. Validate the amount locked in the contract exceeds soft-threshold according to exchange rate in oracle’s output

6. Farmer’s ECDSA signature verification

Counterparty paying fine to farmer:

TX structure:

This TX outputs structure is the same as in preceding one (distinction is made only by internal condition cases). Only the payment target in the third output is swapped to any address farmer provides. Payment amount is the fine defined (certain percentage of the whole payout) in the contract and calculated according to exchange rate in oracle’s output

Counterparty adding collateral to previously locked amount:

TX structure:

Locking script being executed validates the next script (both code and data parts) stays identical to previous one and the funds in the contract were increased.

Again — new output created on the ledger, but the state stays the same.

Extreme weather conditions — farmer’s claim is triggered and paid out:

TX structure:

The script validates one of the extreme weather conditions:

  • Frost — temperature below lower threshold
  • Drought — temperature above upper threshold and humidity below its lower threshold

As well as correct payment amounts and destinations for both parties.

Farmer stopped paying — the contract is cancelled:

TX structure:

Validates through nLocktime that the contract is not valid anymore

**Using nLocktime field in this way is explained in detail in previous article ‘Dead man’s switch’ (coming soon)

Funds locked in the contract are less (in USD) than amount farmer can claim:

TX structure:

In addition to farmer’s ECDSA signature verification, validates that oracle’s time-stamp is within the range of the last two cancellation times and the amount in smart input is less than potential payout (that might be claimed) according to oracle’s exchange rate.

4.3 Optimization and Cost:

As you might have guessed, optimized production software wasn’t the goal of this project, yet even without any optimizations, even the biggest transactions don’t exceed a few cents of cost.

Miners fees per byte are expected to go down as Bitcoin becomes broadly used.

Even if its price rises significantly in the future, I would not expect prices for these kinds of contracts to go higher than this range.

5. Wherever you are at:

This contract is a minimal yet sufficient example from which many other instruments may be built with insignificant code modifications.

Multiple oracles with various types of data, as well as multiple kinds of payouts by single counterparty each for different higher-probability events or/and even multiple counterparties: all may be coordinated in single smart-contract which is just an upgraded modification based on such a template.

Among other things, counterparty in his turn can disperse his risk further and hedge with similar contract based on this template against exchange rate decline.

Existence of USD-pegged token would simplify significantly implementation of these kinds of contracts, but lack of it is not an obstacle as you have just been demonstrated.

All this has become possible now when we have just had the Genesis upgrade — removing all limits from Bitcoin without changing its original rules of the game …

I guess we have had enough now to demonstrate to those really interested that:

Everything people are/were ever trying to achieve on “alternative” non-scalable projects — can be done on original Bitcoin¹!

On original Bitcoin, with original set of script opcodes, with original version 0.1 protocol that should have never been modified by the words of its creator himself:

“The nature of Bitcoin is such that once version 0.1 was released, the core design was set in stone for the rest of its lifetime.” — Satoshi Nakamoto,, 2010

Without any “improvements”² that some people have been trying to introduce for the last decade, which eventually have had only one outcome — made the perfect thing broken.

Bitcoin era begins now …

Come from wherever you are at … let us make Bitcoin shine, as it originally was meant to!


I would like to thank:

  • Phoenix for coming up with, discussing and reviewing the whole idea!
  • Avi Wolicki for creating and providing me with this autonomous weather station that definitely inspires many other projects.
  • And of course, my script comrade — Xiaohui Liu, for providing on-demand all necessary tools I needed during my projects. As well as Yiqiang Wang for building the IDE.

¹currently Bitcoin SV

²Bitcoin protocol changes (bug fixes are not implied here)

*PKH — Public Key Hash, P2PKH — UTXO type of “Pay To Public Key Hash”