Contracts and Trust

Two nights ago, I was convinced to watch 50 Shades of Grey. Not the whole movie, thank god, just the contract negotiation scene.

I don’t get it, I said. Two adults are about to engage in sexual relations. Why do they need a contract? Don’t they trust each other? And if they don’t trust each other, why don’t they walk away?

The same question applies to pre-nups. Or even the institution of marriage! Unless one party poses a significant flight risk, why would willing participants need a legal contract to compel each other to stay?

To better understand this, let’s start with a simpler contract.

Loan contracts.

Suppose you apply for a mortgage with the best of intentions. The loan is approved thanks to your impeccable credit score and 10% down. It’s a large mortgage, but your salary is five times the monthly payment so you should pay it off no problem.

Fast-forward half a decade. The housing market has collapsed, your dog needs kidney dialysis, and to top it all off, a robot just took your job.

How motivated are you to continue paying that mortgage?

While you may be a trustworthy individual at time of loan application, it’s future-you that can’t be trusted. As long as the cost of defaulting on the contract (loss of home equity) is greater than the opportunity cost of mortgage payments, repayment can be coerced.

funny-wedding-cake-topper-remarkable-and-no-running-again-funny-wedding-cake-toppers-rwdreview-com

Much like a consumer loan agreement, marriage is an institution founded on mistrust. Sure, things are going great right now, but it is a cruel fact of nature that most humans do not age well.

What will compel you to stick around after she doubles in size and succumbs to the effects of gravity? And what happens after you become a balding couch ornament with the gut of a ruminant?

This is why marriage contracts were invented. Conjugal bliss can exist when both parties follow similar rates of decay, but this symmetry is rare. Discord arises when one party decays more rapidly than the other. Or, worse, when one party’s income substantially increases.

If the cost of terminating the marriage is less than the opportunity cost of remaining in the contract, it is inevitable that the contract will be breached. The key to a successful marriage is to ensure a sufficiently high cost of termination for both parties. Like, always keep a few thermonuclear warheads up your sleeve.

Back to 50 Shades.

If I understand correctly, the entire movie is about the process of contract negotiation. Christian Grey needs to protect himself from legal recourse if Ana decides to sue him for excessive shenanigans.

As a result, they arrive at an overly complex agreement detailing every possible activity or instrument that could possibly be employed. There’s an easier way.

Christian and Ana’s many pages of complexity can be reduced to a simple smart contract. Here’s how it works:

Each participant puts a valuable consideration (say, 10 ether) into escrow. The participants wear GPS tracking devices that continuously relay their location coordinates to the contract.

Just like in the movie, Ana has two safe words, yellow and red. After the first safe word is invoked, Christian has 10 minutes to move at least 1000 feet away from Ana. If the second safe word is invoked, and the contract detects that Christian is still within the stay-away radius, Ana gets all the money. If Christian is outside the radius and the red safe word is invoked, then Ana is being dishonest about her safety and Christian gets all the money.

Here’s a template, now all they have to do is put it on the blockchain.

import "math.sol";

contract FiftyShades {
    address dominant;     // contract participants
    address submissive;

    uint public value;    // deposit value
    uint public distance; // distance between dom and submissive

    int subCoordX;  // cartesian coordinates 
    int subCoordY;  // of participants
    int domCoordX;
    int domCoordY;

    // contract state. 
    // Green = no safe words yet.
    // Yellow = first safe word, Red = second safe word
    enum State { Dormant, Green, Yellow, Red }
    State public state;

    // when was first safe word used?
    uint public yellowStartTime;

    // submissive creates the contract
    function FiftyShades(int subCoordX_, int subCoordY_) {
        submissive = msg.sender;
        value = msg.value;      // submit deposit
        subCoordX = subCoordX_; // initialize location
        subCoordY = subCoordY_;
        state = State.Dormant;
    }

    // contract becomes active when dominant submits deposit
    function addDeposit(int domCoordX_, int domCoordY_) {
        // require an equal contribution
        if (msg.value < value) throw;

        dominant = msg.sender;
        domCoordX = domCoordX_; // init location
        domCoordY = domCoordY_;
        // deposits received, ready to go
        state = State.Green;
    }

    modifier onlySubmissive() {
        if (msg.sender != submissive) throw;
        _
    }

    modifier onlyDominant() {
        if (msg.sender != dominant) throw;
        _
    }

    modifier inState(State _state) {
        if (state != _state) throw;
        _
    }

    event aborted();  // cancel contract
    event yellowState();  // first safe word used
    event redState();     // second safe word used
    event falseAlarm();

    /// First Safe word used by submissive
    /// After first safe word, the dominant has 10 minutes
    /// to move at least 1000 feet away from the submissive
    function safeWordYellow(int subCoordX_, int subCoordY_)
        onlySubmissive
        inState(State.Green)
    {
        yellowState();
        subCoordX = subCoordX_;  // record location
        subCoordY = subCoordY_;
        yellowStartTime = now;   // record start time
        state = State.Yellow;
    }

    /// Second safe word used by submissive
    function safeWordRed(int subCoordX_, int subCoordY_)
        onlySubmissive
        inState(State.Yellow)
    {
        // has enough time elapsed?
        if (now >= yellowStart + 10 minutes) {
            state = State.Red;
            // TODO: check submissive's movement since last safe word
            // Ensure that submissive is not chasing after dominant
            subCoordX = subCoordX_;
            subCoordY = subCoordY_;

            // calculate distance beteen dominant and submissive
            distance = calcDistance();
            // is the dominant outside of the stay-away distance?
            if (distance < 1000) {
                paySubmissive();  // no: pay submissive 
            } else {
                payDominant();    // yes: submissive misused the safe word
            }
        }
    }

    function paySubmissive()
        inState(State.Red)
    {
        redState();
        suicide(submissive); // kill contract, everything goes to submissive
    }
    function payDominant()
        inState(State.Red)
    {
        falseAlarm();
        suicide(dominant); // kill contract, everything goes to dominant
    }
    /// Can only be called by the submissive
    /// before dominant deposit
    function abort()
        onlySubmissive
        inState(State.Dormant)
    {
        aborted();
        suicide(submissive); // kill contract, return initial deposit to submissive
    }

    function updateDomLocation(int domCoordX_, int domCoordY_)
        onlyDominant
    {
        domCoordX = domCoordX_;
        domCoordY = domCoordY_;
    }

    function updateSubLocation(int subCoordX_, int subCoordY_)
        onlySubmissive
    {
        subCoordX = subCoordX_;
        subCoordY = subCoordY_;
    }

    //pythagorean distance
    function calcDistance() returns (uint d) {
        int x = subCoordX - domCoordX;
        int y = subCoordY - domCoordY;
        int dist = Math.sqrt(x*x - y*y)
        return dist;
    }

    /// TODO: use Haversine distance, add trig fxns to Math lib

    function() {
        throw;
    }
}

For comparison, here is the 10-page entanglement the characters used in the movie.

Obfuscated Obfuscation

klout (1)

Remember Klout? Didn’t think so.

Klout was a social network that assigned you a score between 1 and 100 depending on what it thought you were worth as a human being.

For a while, American Airlines offered VIP lounge access to people with Klout scores above 55. One of my classmates was an intern at Klout, so I asked him to insert a few lines of server code for me:

if( username==”elaine” ) { 
     kloutScore = 60;
}


I’ll get fired,
he said.

Of course, you can’t put it in there just like that. It has to be nonobvious. Like this:

private String o = “656c61696e65”;
private StringBuilder O = new StringBuilder(username);
for( int j=0; j<o.length()-1; j+=2 ){	  
    String l = o.substring(i, (i+2));
    int i = Integer.parseInt(l, 16);
    if( O.charAt(j/2)!=(char)i ) {
        break;
    } else {
        kloutScore+=10;
    }
}

The two code examples achieve the same function. The difference is, the first one is inadmissibly honest in its intentions. The second is a code-reviewer’s nightmare.

Instead of building a stronger lock, hide the front door.

Software obfuscation was originally used to protect proprietary software from reverse engineers looking to bypass copy protection. If the debugger output is tortuous enough, maybe the engineer will get frustrated and go watch porn instead.

A simple transformation to source code can leave it logically opaque while functionally the same. For example:

AND EAX, 0x40    ;mask all but the 6th bit 
CMP EAX, 0x40    ;check if that bit was set

is logically equivalent to:

PUSH EAX 
XOR [ESP], 0xFFFFFFFF 
AND [ESP], 0x40 
POP EAX 
CMP EAX, 0

These methods worked against not just DRM-crackers, but company competitors seeking access to intellectual property. The cat-and-mouse game of software protection gave rise to a whole industry of obfuscation tools designed to chew up a program source file and spit out a snake pit.

Of course, as soon as reverse engineers encountered obfuscated code, they started building deobfuscation tools.

Thus came the impetus to obfuscate the obfuscation.

If you don’t want anyone to break your lock, convince them there is no lock.

Good obfuscation does not look obfuscated. For example, a programmer could hide her intentions by using machine instructions with hidden side effects [1]. Some innocuous string operations:

XCHG EAX, ESI   ;swap two registers
LODS            ;store the value pointed to by ESI
XCHG EAX, ESI   ;swap registers back

This result of those instructions is:

INC EAX

The LODS instruction has the side effect that it increments ESI to the next address after storing the value, because it works on continuous blocks of memory.

obfuscated code

Obfuscated obfuscation is even easier in high-level languages. The Underhanded C Contest is an annual challenge to write honest-looking code that secretly performs a nefarious function.

Common tactics include triggering an arithmetic overflow, pointer overwrites, and bad hash values. As a result, the code ends up doing the opposite of what a user might expect from a visual inspection.

Last year’s winning entry put this line in a single header file:

typedef double float_t; /* Desired precision for floating-point vectors */

By default, float_t is defined as single precision in math.h. The above file overrides the typedef as double precision. By #include-ing this header file in some C files but not others, the programmer passes an array of 8-byte numbers into a function that expects an array of 4-byte numbers. C interprets each 8-byte number as two 4-byte numbers, leading to an array where every other value is 0.

Submissions to the Underhanded C Contest would never pass formal verification, let alone a basic systems test. Far more interesting is the Underhanded Crypto Contest, which challenges programmers to submit cryptography implementations with hidden backdoors.

This one implements Stern’s zero-knowledge identification protocol [2], a scheme based on error-correcting codes where the public key is a parity check matrix and the cryptogram is a noisy codeword. The private key is the unencoded word. A backdoor was inserted by allowing an arithmetic overflow in part of the verification, making it possible for an attacker to pass off an incorrect key. (Note: My interpretation is grossly simplified and possibly flawed.)

I think the moral of the story is, try not to piss off your software engineers. If that can’t be avoided, confine them to a safe language like Ada.

References:
1. S. Schrittwieser, et al. Covert Computation — Hiding code in code through compile-time obfuscation. Computers & Security 42, 2014.
2. J. Stern. A new identification scheme based on syndrome decoding. CRYPTO, Volume 773, 1993.

Reverse-Engineering Software Copy Protection

Commercial software often comes saddled with undesirable features. Microsoft Office, for example, has an annoying pop-up screen that prevents me from using the software unless I first purchase a “product key” to “activate” it.

Microsoft’s copy protection is a self-enforcing contract: In order to gain access to the software, I must pay $149.99 for a license. Licensing is administered by the product key, which activates the software.

A contract is only as good as its enforceability, and commercial copy-protection has long been terrible at self-enforcement.

Disk_II

In early days, distributors copy-protected their disks by introducing intentional bad sectors [1]. The floppy disk’s boot loader would look for errors upon execution, and only load the software if the intentional errors occurred. Copied disks didn’t have bad sectors, so they couldn’t generate the expected errors.

This stopped piracy for about five minutes, or however long it took to delete three lines from the boot loader.

tetris box

In the 80s, game publishers brought copy protection into the physical world: At runtime, the program would ask a question whose answer could only be found in the game manual. If answered incorrectly, the software would terminate.

Boxed versions of Tetris came with a book of information about the fifteen Soviet Republics (Tetris was developed at the Academy of Sciences of the USSR). I didn’t own this manual because my dog ate it. As a result, I spent hours at the library memorizing Soviet trivia in order to play my stupid Tetris game.

От каждого по способностям, каждому по потребностям
The answer is От каждого по способностям, каждому по потребностям!

There were better workarounds.

Software-liberators armed with debuggers could view machine instructions as the program was running. When the copy-protection popped up, the user would identify the offending lines and edit them out of the program. This is called a crack.

Example:

CMP  WORD PTR [A720], 1C20  ;compare location A720 (user’s response) with hardcoded passphrase
JNZ  kill_function           ;if Z flag not set, CMP failed. Quit. 
CALL continue_playing        ;otherwise, continue

Replace the second line with a NOP and it’s fixed.

There were many variations on this scheme: Free trials that expire after 30 days, mail-order activation codes, serial numbers based on device IDs. These protections all relied on a checkpoint, followed by a conditional jump. The checkpoints were trivial in the face of a debugger.

A lock does no more than keep an honest man, honest.

Protectionists realized that it was impossible to guarantee digital rights security for software running on an untrusted machine. Still, they hoped to at least increase the cost and inconvenience of breaking copy protection.

They wrote software that could detect if it was running in a debugger; they added code checksums to detect alterations; they planted copy-protection subroutines in multiple locations.

Unfortunately, they overestimated the value of time to Eastern Europeans making fifty kopeks a day. The net result was that proprietary software became buggier and more bloated for legitimate users, while only nominally slowing the freedom-fighters.

dc-Cover-qf1kifq9vq6bbheeh5of1qfh70-20160426004906.Medi

You know how doctors warn against the unnecessary use of antibiotics because it leads to an increase in drug-resistant bacteria? Decades of broken software security trained reverse-engineers to identify flaws in the toughest protection schemes. Many then applied these skillz to creating malware, the malicious code that resulted in multiple breaches at the US Federal Reserve and disappeared $81 million from Bangladesh’s central bank.

As for large software vendors, they found that the most effective copy protection is still best-enforced in the physical world: Lawsuits.

There are some transactions software can’t enforce. For everything else, there’s the blockchain.

Screen Shot 2016-06-06 at 8.34.54 PM

References:
1. Pournelle, Jerry. Zenith Z-100, Epson QX-10, Software Licensing, and the Software Piracy Problem. BYTE, June 1983.
2. +HCU (High Cracking University) Academy of Reverse Engineering –Fravia+ (the definitive cracking guide of the 90s)

See Also:
Obfuscated Obfuscation

Podcast Transcript: Tim Ferriss and Marc Andreessen

The Tim Ferriss podcast with Marc Andreessen is very good. Andreessen compares himself to Warren Buffett as a value investor, except that Andreessen bets on legacy industries getting disrupted, and Buffett bets that they don’t.

I generated a transcript for those who hate podcasts. Also, for those who complain that Marc Andreessen has a squeaky voice that only a dog can understand.

Source: Marc Andreessen — Lessons, Predictions, and Recommendations from an Icon –The Tim Ferriss Show

Can I Take Medication that was Prescribed for a Dog?

My friend George was visiting from Pyongyang when he suffered a minor hangnail. Unfortunately, it soon became infected and turned into something not-so-minor.

It was gonna be another two weeks before he could return to the land of universal health care, so he had no choice but to submit to the indignity of the American health care system. He went to the MinuteClinic at CVS.

MinuteClinic is a walk-in medical clinic designed to substitute the services of a primary care provider. Just like at a family doctor’s office, George spent two hours waiting, ten minutes with a nurse practitioner, and $127 for the ordeal ($99 for the visit, $28 for prescription antibiotics).

MinuteClinic-7

After he left, George did a Google search on his medication: Cephalexin. Much to his dismay, it was available online, for cheaper, and without a doctor visit or prescription. From an animal supply store!

Elaine, he said. You’re sort of a doctor — Is it safe for me to take animal medication that I get off the internet?

I’m not really a doctor, but I do watch a lot of medical shows on Netflix. That must count for something, so let’s take a look.

Hit up American Pharoah for the good stuff.

Five seconds into my review of animal med suppliers, I was distracted by all the fun stuff available for racehorses.

American-Pharoah-a4-721-800x461

Myo-inositol trispyrophosphate (ITPP) stands out due to its cult popularity in nootropic and health-hacking forums. It’s used to increase the oxygen-releasing capacity of red blood cells, increasing the stamina of racehorses. Lance Armstrong doesn’t need a prescription for this dopant!

Xylazine is a horse sedative. It’s also a recreational drug that’s frequently cut with cocaine and heroin to create speedballs.

Clenbuterol is an amphetamine that celebrities use for rapid weight loss. It’s also illegal in the US, unless you’re a horse.

All of these drugs are available online, without prescription.

Pet meds are cheaper than prescription human meds.

Insurance companies are pretty good at insulating their customers from actual drug prices. Uninsured customers account for only 8.5% of prescriptions dispensed nationwide. As a result, pharmacies mark retail prices to whatever they like.

Pets, on the other hand, don’t always have health insurance. Their human owners are more motivated to shop around, or maybe replace the animal with a new one and hope the kids don’t notice. This forces animal drug manufacturers to be a little more competitive with their pricing.

For example, a 30-day supply of 10 mg Fluoxetine, aka Prozac, is $20 at my local CVS. Prozac for dogs is $2.70 for an equivalent strength and supply. Amlodipine, a blood pressure medication, is $34 for humans, $5.40 for dogs. Humulin N (insulin): $435.20 for people, $149.99 for dogs. Minocycline (antibiotic): $108 for people, $6.60 for dogs. Epinephrine: $430 for people, $17.98 for dogs.

cute-dog-11

So I can take animal drugs?

What’s the difference between animal meds and human meds?

Animal drugs often start off as human medications, because human drug research commands more money. But before a human drug can be marketed for animals, it has to go through an FDA approval process.

Both animal and human approval processes require safety and efficacy assessments consisting of lab and clinical studies. I understand how clinical trials might work for obvious indications like bacterial infection or hypertension, but how do you evaluate the efficacy of Dog Prozac? What about side effects? How do you ask a dog if he feels dizzy or has a headache? Or whether he notices an increase in suicidal thoughts?

Unless the drug is destined for mass administration in livestock, it doesn’t make sense for a manufacturer to invest millions towards FDA approval. Certainly no veterinarian would bother prescribing Prozac or insulin to a food-producing animal.

So none of the animal drugs I mentioned here are FDA-approved for their respective species. That’s okay, because veterinarians can prescribe FDA-approved human drugs for “extralabel use”:

Actual use or intended use of a drug in an animal in a manner that is not in accordance with the approved labeling. This includes, but is not limited to, use in species not listed in the labeling, use for indications not listed in the labeling, use at dosage levels, frequencies, or routes of administration other than those stated in the labeling, and deviation from labeled withdrawal time based on these different uses. (21 CFR 530.3(a))

The main restriction is that the drug manufacturer can’t market the drugs for animal uses.

Let’s look at those dog meds again.

Doggie minocycline is manufactured by Actavis, a pharmaceutical company that also makes human minocycline. Dog Prozac is made by Par Pharmaceutical, which also supplies a generic for humans. The dog version of Humulin N is manufactured by Elanco Animal Health… a division of Eli Lilly, which still holds a patent on Humulin N for people.

Same drugs, same manufacturers, different FDA approval status. Next time I need a prescription, I’ll go to the vet and pretend I’m a dog.

I AM NOT A MEDICAL DOCTOR AND NONE OF THIS IS MEDICAL ADVICE.

See Also:
This Post Brought to You by Your Insurance Provider