Tuesday, October 7, 2014

Turning the abstract concrete

One of the more subtle properties of Bitcoin that I find very endearing is that it has taken what has long been in the realm of the abstract (numbers) and has made them something very concrete.

Here is an example: "I have 12."  That statement is nonsensical.  It must be put into context for it to make sense.  12 must be qualified.  12 is an abstract concept and cannot stand alone.

Put it into the realm of Bitcoin and 12 becomes a very concrete and discrete thing.  12 is my private key.  It exists in a very real and discrete space.  The address 1LWsLyY2j2mPtYcG9yG2bDFwTWryiJL6sp is derived from that key and can be assigned bitcoin.  If you take 12 out of its home and context and put it anywhere else in the world it will retain all of its former properties.  No matter what else, 12 is the key to sign transactions at that address.

I am fully aware that discrete mathematics has been around for a long time and has dealt with these concepts.  It is one of the building blocks of cryptography which is in turn one of the building blocks of Bitcoin.  It is just that for me, Bitcoin is one of the best examples of translating the abstract concept of numbers into a concrete object.

Wednesday, April 16, 2014

What could/should a GovCoin look like

I will start by saying that I am not advocating a government crypto-currency.  I also do not believe one would happen in the US because our money is privatized and implementing a crypto-currency of the land would greatly increase transparency and reduce corruption.  Enough politicians are plenty happy with the way things are because they get a cut of the pie.  But, for the sake of critical thinking, lets say that USGovCoin did exist.  What are some benefits we could get from this and what would it look like?

This coin would be minted in a proprietary process by the federal government.  A blockchain technology would be preferable to something like Open Transactions because we would then have an auditable public ledger.  The currency would be forever inflationary.  Currency minting of USGovCoin would go to a master account and every item in the budget would be designated with their own master account which would be paid out by the minting master account for the appropriate amount.  The government would never again collect taxes (but may charge transaction fees as a method of state and municipal income).  They would merely alter the mining algorithm to "print" what they needed.  Everyone would pay taxes in the form of inflation.

Here are some benefits I see to this system:
1. Government spending becomes transparent.  The public ledger allows anyone to track where the money is going and how it is being spent.  No more trillion dollars lost by the Pentagon that no one can account for coming up in the news.
2. Get rid of the IRS.  No one pays taxes so no one avoids taxes, you just lose value based on measured inflation.  Hey, that happens anyway and inflation is harder to track in this current complex system.
3. Inflation tax is tempered by the fact that foreign holders are getting "taxed" the same.  No more offshore tax havens and inflation tax is spread over a larger base than regular tax so the effects are not as heavy on any one group.
4. With an inflationary currency people will still be encouraged to invest in businesses to stop the bleeding.  You don't want your money sitting, you want it doing things for you.  I realize that people tend to invest what they have saved and inflation fights that, so this argument is mainly aimed at the "inflation is necessary" camp.

Here are some issues I see with this system:
1. Why would foreign entities treat USGovCoin as a reserve currency if they are getting taxed like US citizens?
2. Like it or not, having to pay taxes stabilizes the currency.  Businesses accept USD in part because when they pay taxes it has to be in USD.  If there was no tax then leaving USGovCoin for a crypto-currency with lower inflation and risk would seem very attractive.  If the government tries to play this game they will find themselves losing to the competition.
3. If it is a true crypto-currency, then the government would have a difficult time regulating fraud and confiscating currency after prosecuting theft.  The penal system would have to change because all thefts would become final.  You will send the rich to prison and they will leave just as rich.

Tuesday, April 15, 2014

Explaining BIP 0032 using pybitcointools

BIP 0032 is a protocol created to make Hierarchical Deterministic wallets. Most Bitcoin wallets contain a set a private keys that are all randomly generated and have no relationship to each other. Hierarchical Deterministic (HD) wallets contain private keys that are all derived from the same seed. If you can remember your seed, you can regenerate the entire wallet with all the keys. An advantage to this is that you can perform your customary best practices generating new addresses for change for each transaction and if anything happens you can tear down and build the same chain with the same generated addresses as before so you don't lose anything.

BIP 0032 does one step better though. If all you wanted was a chain of private keys that you could reproduce at a whim then why not just transform your seed for your first private key and double SHA-256 hash (the previous key + seed) or some other simple transformation that will achieve the same results (ie. a repeatable chain of private keys)?  The extra level of awesome that BIP 0032 does is that you can produce a public key to generate a public keychain that follows your private keychain.  This public key can be made public (or given to a third party) without compromising your private keys.

There are a couple examples showing why a deterministic public keychain is so important:

1. You can use it on public servers for automated point of sale.  If you want to generate a new address for each order you can use the public chain key to generate these new addresses.  If your server gets compromised, no one can steal your bitcoin because the public chain key can only generate public keys.

2. You can give the public chain key to an auditor.  Lets say you have investors and they want real time audits of your bitcoin sales.  They can give them the public chain key and they will have all the information they need to see transactions without having access to the bitcoin.


So here is how you can use BIP 0032 by utilizing pybitcointools.  Start by asking for the seed input and create from that your master private key.


#Always include pybitcointools
import sys, os
sys.path.append('pybitcointools')
import bitcoin

bip32seed = raw_input('Your secret phrase: ').strip()
masterKey = bitcoin.bip32_master_key(bip32seed)

This "masterKey" is the head of the private keychain.  Now we can start deriving other private keys at the first level of our tree.


level1Priv1 = bitcoin.bip32_ckd(masterKey, 1)
level1Priv2 = bitcoin.bip32_ckd(masterKey, 2)

Here we have derived 2 private chain keys one level down from the masterKey.  Structurally, level1Priv1 and level1Priv2 are no different from masterKey.  Because of this, each private chain key can be used to derive a whole new level of private keys.  So you can code something like this and it is perfectly valid and reproducible:


level1Priv = bitcoin.bip32_ckd(masterKey, 34)
level2Priv = bitcoin.bip32_ckd(level1Priv, 2983)
level3Priv = bitcoin.bip32_ckd(level2Priv, 7)

This would create a private chain key off the masterKey (at the 34th index) and another private chain key off of that (at the 2983rd) index and another off of that (at the 7th index) and from there you can generate a list of private keys off level3Priv at 1, 2, 3, 4, etc.

So now we have the private chain keys but what we would really like is the private key.  That is done like this:


private1 = bitcoin.bip32_extract_key(level1Priv1)

If you want to get the public key that corresponds to this private key there are 2 ways to do that.


level1Pub2 = bitcoin.bip32_privtopub(level1Priv2)
public2 = bitcoin.bip32_extract_key(level1Pub2)

-or-

masterPub = bitcoin.bip32_privtopub(masterKey)
level1Pub2 = bitcoin.bip32_ckd(masterPub, 2)
public2 = bitcoin.bip32_extract_key(level1Pub2)

Each private chain key has its public counterpart.  In the first example we take the public counterpart of the target private chain key and pull out the public key with "bip_extract_key".  In the second example we pull the public chain key from the masterKey which is just a private chain key.  From there we derived public chain key of our target through the public chain.  Note that we were targeting the private key at the 2 index so we make sure and create the public key at the 2 index as well.

These public and private derived keychains are mirrored down as many levels as you would like and across a very large number of indexes with one exception.  You can make a hardened keychain where only private keys may be derived.  This is done by creating the keys at indexes at or above 2^31 or 2147483648.  The public derivation does not work for indexes above that value.

Saturday, April 12, 2014

Multisig with pybitcointools

Multisig is all the rage these days and for good reason.  It is very useful and so much more secure.  Take, for example, a scenario where you are pooling bitcoin resources with a group of friends for investment or mining.  In a typical single signature situation there are some difficult choices to make.  Is the secret key just held by one person?  What if something happened to that one person?  Maybe everyone in the group should hold the private key.  What if someone doesn't encrypt or has their copy compromised?  What if someone is not as trustworthy as you first thought?  In comes multisignature transactions to resolve all your problems.  If someone loses a key or has it compromised the holdings are still safe and internal shenanigans requires coordinated effort.

I am going to go through with code to show you how this can all be done with pybitcointools.  For this I am going to assume that you are going to create a 2 of 3 transaction.  This means there are 3 keys and any two of them can be used to sign the transaction.

For reference, I got started here: http://bitcoinmagazine.com/11113/pybitcointools-multisig-tutorial/
I found this tutorial to be a great start but it left me with too many questions and too many unknowns.  This tutorial is MUCH more comprehensive.


1. Generate the secret keys.

Multisig addresses are made using the public keys that are generated from 3 private keys.  Because of this, each party should be responsible for generating their own key on their own machine.  Secret keys never have to be shared.  Here is the code for this:

import sys
sys.path.append('pybitcointools')
import bitcoin

secret = bitcoin.random_key()
public = bitcoin.privtopub(secret)
print "Secret: " + secret
print "Public: " + public

All the public keys should be distributed to all of the partners.  Then everyone can generate the same public multisig address with the same redemption script.  Please note that you have to agree on the order of the public keys as changing the order will alter the multisig address and the redemption script.  While the different address would certainly be problematic, the redemption script should be fine whatever the order.  I have not tested this though.  Please feel free to correct me.

In any case, here is the code for creating the address and redemption script:

//assume the same imports at the top
pub  = []

// put the public keys in this array however you would like

for x in range(0, 3)
    pub.append(raw_input("Enter a public key: "))
script = bitcoin.mk_multisig_script(pub[0], pub[1], pub[2], 2, 3)
address = bitcoin.scriptaddr(script)

print address
print script

In "mk_multisig_script" the first three values are the public keys, the next value is the number of signatures required (could be 1 or 3 instead of 2 if that is what you want), and the last value is the number of total keys being used to create this transaction.

So you send bitcoin to that address and all is right with the world, but bitcoin is not yours unless you are able to transfer it.  I will explain how to spend multisig transactions now.  This part is a bit more complicated.

The first thing you want to do is figure out how much bitcoin is available in at your address.  Pybitcointools makes that very easy with the function unspent(address).  Like so:

history = bitcoin.unspent(fromAddress)
total = bitcoin.sum(bitcoin.multiaccess(history, 'value'))

unspent(address) will return a json object with transactions that the address can still spend. This will include the transaction id, the output index of the transaction that this address can spend, and the value of the transaction.  I want to spend a bit of time on this because transaction indexes will come up again.  Remember that a transaction can have multiple inputs and multiple outputs.  Most transactions will have more than one output just because it needs to send change.  If the transaction was set up to spend to 6 different addresses of which you were only one, it is important to know that portion of the transaction you can spend is at index 2 or whatever it happens to be.  The index starts at 0 for the first output.

The next line iterates through the json object and sums the values of unspent transactions.  It is good to know how much you can spend.

The next portion of the code assumes that you have set something up to enter in the outgoing address, value you want to send, and the fee you would like to pay.  This code traverses the available transactions available to spend and selects enough value to make the transaction work.  There are certainly more efficient ways to select inputs.

totalSend = amount + fee
currentValue = 0
inputs = []
for trans in history:
 inputs.append(trans)
 currentValue += trans['value']
 if currentValue >= totalSend:
  break

inputLen = len(inputs)

Now that we have the length of the inputs for our new transaction, we can make sure that we are supplying the appropriate minimum fee.  For safety's sake we are going to assume that each input takes 400 bytes, though the truth is closer to 387.

neededFee = int(.0001 * 100000000) //unit used is satoshi
transSize = inputLen * 400 + 34 * 2 + 10 // assume change so 34x(2 outputs)

if transSize > 10000:
 while transSize > 1000:
  neededFee += int(.0001 * 100000000)
  transSize -= 1000

Ok, so now we have all of our inputs ready to make our transaction.  Since we are already making the transaction so we should also go ahead and create our signatures as well using the only private key we control.

rawTX = bitcoin.mksend(inputs, [toAddress+':'+str(amount)], fromAddress, neededFee)

mySig = []
for x in range(0,inputLen):
 mySig.append(bitcoin.multisign(rawTX, x, script, myPrivKey))

There is a lot going on here so let me break it down. mksend() is a helper function for mktx(). It takes the additional parameters of a change address and fee and generates the appropriate final output to send change back. Remember that 'amount' is an integer representing the number of satoshis being sent. In this code I am sending change back to the original multisig address. You may not want to do that. In the second portion of the code I am generating a signature for each input of this transaction. Remember that the inputs for this transaction are outputs from previous transactions. Those outputs had an index designating where to find it in that transaction. In this code 'x' is also an index but it is the input index. So the first input you use will be index 0 and the second would be index 1. The 'script' parameter is the redemption script you generated earlier. The output of this function is NOT a signed transaction. Instead it is the signature for this transaction. Once you have run this you will need to send another key holder the following pieces of data:
  • The original raw transaction
  • The redemption script
  • The signature for each input
Once another key holder has this information, they can generate their own signature(s), apply their signature(s) and your signature(s), and publish the signed transaction. That is done like this:

mySig = []
for x in range(0,inputCount):
 mySig.append(bitcoin.multisign(rawTx, x, script, myPrivKey))
 if (mySig[x] == otherSig[x]):
  print "You already signed this.  Send it to another key holder."
  sys.exit(0)
fullySignedTx = rawTx
for x in range(0,inputCount):
 fullySignedTx = bitcoin.apply_multisignatures(fullySignedTx, x, script, mySig[x], otherSig[x])

answer = raw_input("Do you want to send this transaction? (Type 'yes' default is 'no')") or "no"
if answer == 'yes':
 print bitcoin.eligius_pushtx(fullySignedTx)
 print "The transaction has been double signed and sent.  Thank you!"
else:
 print "You have not sent this transaction."

Again, a signature is being generated for the transaction with the key the new person is holding. There is a check to make sure it isn't actually the same key so that we can generate a useful message. The next step is to iterate through the inputs in the transaction and apply the signatures to each one. Please note that this does return a transaction and we would send the transaction with the first input signed to the function to have the second input signed. It does no good to sign the first input of the raw transaction and then sign the second input of the same raw (unsigned) transaction. It would return a transaction without the first input signed.

Once the signatures have been applied we are ready to broadcast the transaction to the network. Currently blockchain.info does not like multisig transactions generated like this so we have to submit it to eligius.

I hope this makes working with multisig addresses much easier and I hope that you learned something about Bitcoin transactions. If I made any mistakes or could have done something better please let me know. I like learning as well.

Friday, January 3, 2014

Open Transactions is incredibly important

I was able to attend the first Bitcoin mini-conference in Austin and to my surprised pleasure one of the speakers was FellowTraveler (Chris) who also lives here.  He works on the open source project Open Transactions which is part of the Monetas product.  In my mind this is absolutely the next generation in software tools for supporting digital currencies.

I will attempt to explain Open Transactions but I will warn you that it is a heady idea and I feel that I am only beginning to understand the full potential and implementation of it.

Open Transactions is a server model cryptographic contract clearinghouse.  Clients connect to it and can send each other encrypted messages that can take different forms from just being a memo, to being a transaction of a security, to being a security pair trade.  In layman's terms that is sending someone a message, sending someone money, or sending someone a contract to exchange one type of security (stock, bitcoin) for another type of security (stock, cash).

You might be thinking (as I did near the beginning of Chris's presentation) that this all sounds like a step backward.  And it would be if not for the next steps taken.  While the server is indeed a server, the server only acts as one signature of the contract.  The client is the first signature and the server cannot alter records sent by the client.  This is very different from current server thinking where clients are not to be trusted and the server is the master record.  Banks must have strict audits to prove that they don't just alter numbers in the system, Open Transactions is simply unable to do so in the first place.  The other step that needs to be taken for this to work is that the server needs to be part of a federated server cluster where contracts can be set up that need majority vote of the federation to occur.  For instance, instead of bitcoin being stored at one address whose key lives on one server, the bitcoin can be sent to a multi-signature address.  Now different servers controlled by different parties must sign the transaction to access the bitcoin.  You can set it up so that you need, say, 6 of the 11 signatures to make the transaction legitimate.  Now bitcoin cannot be stolen by rouge actors, bitcoin cannot be stolen from compromised servers, bitcoin cannot be lost by MIA servers.  What we see is that Open Transactions is a powerful enhancement to Bitcoin, and not something meant to replace it.

There are so many features that make Open Transactions a library that pushes the open, trust independent ideals of Bitcoin from currency into so many other venues.

Tuesday, December 17, 2013

What I should have said was "Of course"

Being an evangelist I make it a point to mention that I work with Bitcoin when getting to know anyone.  Most people have heard of it now and most people still know next to nothing about it.  I will typically get the question, "So, should I get some bitcoin?"  And for some reason I always seem to answer "Yeah, not sure about that."  Why?  Why do I do this?  Some evangelist I am.  Here is a reflection of my own failings in this arena.

Bitcoin is too expensive.  This was my personal bias merging in with my general advice.  A bitcoin was $1100 at the time.  I was not willing to buy bitcoin at that time so why should I tell other people that they should?  I think the argument is valid but I need to back it up with my reasoning on the individual situation.  I tend to assess situations, give a recommendation, and not give people background data so they can make their own decision.  I need to work on that.

You are not ready for Bitcoin.  Part of my assessment of an individual is whether I feel they can start up a client, encrypt their wallet, and backup their wallet in alternative locations.  Really the barrier right now is "are you capable of being your own bank."  That kind of responsibility is just too damn high, especially if they have to figure out how these things are accomplished and not just perform the tasks.  The last thing I want to do is recommend people get bitcoin just to have them go and lose their wallet.

No, you cannot have my bitcoin.  If setting up a scheme to protect your local wallet isn't hard enough, try explaining the hoops people have to go through to get bitcoin.  If you wanted bitcoin bad enough you would already have found out how to get them on your own.  Anything I would tell you would just confirm your bias that it is too hard to get your hands on bitcoin and you will give up before you try.  The simplest way for them to get bitcoin is to purchase them from me directly.  I may be an evangelist but I am not going to be sucked dry of my bitcoin just to proclaim the good news of Bitcoin.  Afterall, bitcoin is difficult to acquire with all the hoops you have to jump through, even for me.  And yes getting sucked dry would happen.  I have found that the hardest part of selling bitcoin is telling people that you have no more to sell them.  It is like a spigot connected to suction.  You want to let a little out but staunching the flow becomes a chore.

In short, I want to be a better evangelist.  What I should be telling people is, "Of course, I think everyone should own bitcoin.  It is still not an easy thing and you will have to work to get it, but it is rewarding."

Thursday, December 12, 2013

My thoughts on Casascius in trouble

According to the website casascius.com and a followup report by Wired the company (Casascius) was contacted by FinCen with language that made them take a step back and turn off operations for the time being.  Right now it is hard to separate speculation from actual news but I thought I would weigh in on what I have heard.

For those that don't know Casascius, they are the 800 pound gorilla in the physical bitcoin market.  They produce metal coins that are hollow in the center and cardstock with a secret key printed on it is placed into this space.  The hollow space with the printed key is then covered with a tamper evident sticker.  The result is a fancy cold storage wallet that you can give to someone else with confidence that the secret key was not accessed.  The public key (actually firstbits of the public key) are printed on the coin so that you can verify the balance of the coin.  I have some Casascius coin and I would definitely recommend them for people who like collectibles and want to introduce Bitcoin to new comers in a way that they will understand.

FinCen is the enforcement branch of the US treasury.  They deal with money laundering and other financial crimes.  Where factual reports of this case and speculation seem to blur is what exactly FinCen had a problem with regarding Casascius.  The consensus opinion seems to be that the business process Casascius uses can lend itself to money laundering so it needed to register itself with FinCen as a money transmitter and verify and keep records of its customers.  Here are the specifics to how that works.  When you order a 1 bitcoin coin from Casascius you pay Casascius 1.25 bitcoin (this is not the current rate, just an example).  You pay .05 BTC for shipping and .2 BTC for the markup and when you get your coin in the mail Casascius will send 1 BTC to the address of the coin.  The problem is that Casascius is collecting bitcoin from orders from all over the place and the 1 BTC that is going on the coin is not necessarily part of the 1.25 BTC you originally sent.  There is nothing wrong with that, it is just that FinCen wants you to be registered and follow their rules and regulations for your customers if you are doing that.

If, on the other hand, Casascius was charging .25 BTC for the coin as a blank and telling the recipient that it was up to them to charge the coin then Casascius is not transmitting money.  They are just taking payment for a product.  Whatever happens, I am very interested to see how this all pans out.