Skip to content

Commit

Permalink
Revert "Updates bitcoin_transfer/spend_your_coin.md"
Browse files Browse the repository at this point in the history
This reverts commit 5c6fccd.
  • Loading branch information
hypergori committed Jan 31, 2017
1 parent 5c6fccd commit 1e684b5
Showing 1 changed file with 51 additions and 64 deletions.
115 changes: 51 additions & 64 deletions bitcoin_transfer/spend_your_coin.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
## Spend your coin {#spend-your-coin}

So now that you know what a **bitcoin address**, a **ScriptPubKey**, a **private key**, and a **miner** are you will make your first **transaction** by hand.
So now that you know what a **bitcoin address**, a **ScriptPubKey**, a **private key**, and a **miner** are you will make your first **transaction** by hand.

As you proceed through this lesson you will add code line by line as it is presented to build a method that will leave feedback for the book in a Twitter style message.
As you proceed through this lesson you will add code line by line as it is presented to build a method that will leave feedback for the book in a Twitter style message.

Let’s start by looking at the **transaction** that contains the **TxOut** that you want to spend as we did previously:
Let’s start by looking at the **transaction** that contains the **TxOut** that you want to spend as we did previously:

Create a new **Console Project** \(>.net45\) and install **QBitNinja.Client** NuGet.
Create a new **Console Project** (>.net45) and install **QBitNinja.Client** NuGet.

Have you already generated and noted a private key to yourself? Have you already get the corresponding bitcoin address and sent some funds there? If not, don't worry, I quickly reiterate how you can do it:
Have you already generated and noted a private key to yourself? Have you already get the corresponding bitcoin address and sent some funds there? If not, don't worry, I quickly reiterate how you can do it:

```cs
var network = Network.Main;
Expand All @@ -19,39 +19,37 @@ var address = bitcoinPrivateKey.GetAddress();

Console.WriteLine(bitcoinPrivateKey);
Console.WriteLine(address);
```
```

Note the **bitcoinPrivateKey**, the **address**, send some coins there and note the transaction id \(you can find it \(probably\) in your wallet software or with a blockexplorer, like [blockchain.info](http://blockchain.info/)\).
Note the **bitcoinPrivateKey**, the **address**, send some coins there and note the transaction id (you can find it (probably) in your wallet software or with a blockexplorer, like [blockchain.info](http://blockchain.info/)).

Import your private key:
Import your private key:

```cs
var bitcoinPrivateKey = new
BitcoinSecret("cSZjE4aJNPpBtU6xvJ6J4iBzDgTmzTjbq8w2kqnYvAprBCyTsG4x");
var network = bitcoinPrivateKey.Network;
var address = bitcoinPrivateKey.GetAddress();

Console.WriteLine(network); // Main
Console.WriteLine(bitcoinPrivateKey); // cSZjE4aJNPpBtU6xvJ6J4iBzDgTmzTjbq8w2kqnYvAprBCyTsG4x
Console.WriteLine(address); // mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv
```

And finally get the transaction info:
```

And finally get the transaction info:
```cs
var client = new QBitNinjaClient(network);
var transactionId = uint256.Parse("e44587cf08b4f03b0e8b4ae7562217796ec47b8c91666681d71329b764add2e3");
var transactionResponse = client.GetTransaction(transactionId).Result;

Console.WriteLine(transactionResponse.TransactionId); // e44587cf08b4f03b0e8b4ae7562217796ec47b8c91666681d71329b764add2e3
Console.WriteLine(transactionResponse.Block.Confirmations);
```
```

Now we have every information for creating our transactions. The main questions are: **from where, to where and how much?**

### From where?

In our case, we want to spend the second outpoint. Here's how we have figured this out:

In our case, we want to spend the second outpoint. Here's how we have figured this out:
```cs
var receivedCoins = transactionResponse.ReceivedCoins;
OutPoint outPointToSpend = null;
Expand All @@ -65,7 +63,7 @@ foreach (var coin in receivedCoins)
if(outPointToSpend == null)
throw new Exception("TxOut doesn't contain our ScriptPubKey");
Console.WriteLine("We want to spend {0}. outpoint:", outPointToSpend.N + 1);
```
```

For the payment you will need to reference this outpoint in the transaction. You create a transaction as follows:

Expand All @@ -75,35 +73,31 @@ transaction.Inputs.Add(new TxIn()
{
PrevOut = outPointToSpend
});
```
```

### To where?

Do you remember the main questions? **From where, to where and how much?**
Constructing **TxIn** and adding to the transaction was the answer the "from where" question.
Constructing **TxOut** and adding to the transaction is the answer for the remaining ones.
Constructing **TxOut** and adding to the transaction is the answer for the remaining ones.

The donation address of this book is: [1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB](https://blockchain.info/address/1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB)
This money goes into my "Coffee and Sushi Wallet" that will keep me fed and compliant while writing the rest of the book.
If you succeed to complete this challange you will be able to find your contribution among **Hall of the Makers** on [http://n.bitcoin.ninja/](http://n.bitcoin.ninja/) \(ordered by generosity\).

If you succeed to complete this challange you will be able to find your contribution among **Hall of the Makers** on http://n.bitcoin.ninja/ (ordered by generosity).
```cs
var hallOfTheMakersAddress = new BitcoinPubKeyAddress("1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB");
```

```
If you are working on the testnet, send the testnet coins to any testnet address.

```cs
var hallOfTheMakersAddress = BitcoinAddress.Create("mzp4No5cmCXjZUpf112B1XWsvWBfws5bbB");
```
```

### How much?

If you want to send **0.5 BTC** from a **transaction input** with **1 BTC** you actually have to spend all!
If you want to send **0.5 BTC** from a **transaction input** with **1 BTC** you actually have to spend all!
As the diagram shows below, your **transaction output** specifies **0.5** BTC to Hall of The Makers and **0.4999** back to you.
What happens to the remaining **0.0001 BTC**? This is the miner fee in order to incentivize them to add this transaction into their next block.

![](../assets/SpendTx.png)
![](../assets/SpendTx.png)

```cs
TxOut hallOfTheMakersTxOut = new TxOut()
Expand All @@ -120,10 +114,10 @@ TxOut changeBackTxOut = new TxOut()

transaction.Outputs.Add(hallOfTheMakersTxOut);
transaction.Outputs.Add(changeBackTxOut);
```
```

We can do some finetuning here.
You can check the address on a blockexplorer I am working with on this whole chapter example \(I am working on the testnet\): [http://tbtc.blockr.io/address/info/mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv](http://tbtc.blockr.io/address/info/mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv)
You can check the address on a blockexplorer I am working with on this whole chapter example (I am working on the testnet): http://tbtc.blockr.io/address/info/mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv

```cs
// How much you want to TO
Expand All @@ -139,8 +133,7 @@ var txInAmount = receivedCoins[(int) outPointToSpend.N].TxOut.Amount;
Money changeBackAmount = txInAmount - hallOfTheMakersAmount - minerFee;
```

Let's add our calculated values to our TxOuts:

Let's add our calculated values to our TxOuts:
```cs
TxOut hallOfTheMakersTxOut = new TxOut()
{
Expand All @@ -153,19 +146,18 @@ TxOut changeBackTxOut = new TxOut()
Value = changeBackAmount,
ScriptPubKey = bitcoinPrivateKey.ScriptPubKey
};
```

And add them to our transaction:
```

And add them to our transaction:
```cs
transaction.Outputs.Add(hallOfTheMakersTxOut);
transaction.Outputs.Add(changeBackTxOut);
```
```

### Message on The Blockchain

Now add your feedback! This must be less than 40 bytes, or it will crash the application.
This feedback, along with your transaction will appear \(after transaction is confirmed\) in the [Hall of The Makers](http://n.bitcoin.ninja/).
This feedback, along with your transaction will appear (after transaction is confirmed) in the [Hall of The Makers](http://n.bitcoin.ninja/).

```cs
var message = "nopara73 loves NBitcoin!";
Expand All @@ -175,10 +167,10 @@ transaction.Outputs.Add(new TxOut()
Value = Money.Zero,
ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes)
});
```
```

To sum up take a look at my whole transaction before signing:
I have 3 **TxOut**, 2 with **value**, 1 without **value** \(with the message\). You can notice the differences between the **scriptPubKey**s of the "normal" **TxOut**s and the **scriptPubKey** of the **TxOut** with the message:
I have 3 **TxOut**, 2 with **value**, 1 without **value** (with the message). You can notice the differences between the **scriptPubKey**s of the "normal" **TxOut**s and the **scriptPubKey** of the **TxOut** with the message:

```json
{
Expand Down Expand Up @@ -212,44 +204,41 @@ I have 3 **TxOut**, 2 with **value**, 1 without **value** \(with the message\).
}
]
}
```
```

Take a closer look at **TxIn**. We have **prev\_out** and **scriptSig** there.
**Exercise:** try to figure out what will be and how to get the **scriptSig** in our code before you read further!
Take a closer look at **TxIn**. We have **prev_out** and **scriptSig** there.
**Exercise:** try to figure out what will be and how to get the **scriptSig** in our code before you read further!

Let's check out the **hash** of **prev\_out** in a blockexplorer: [http://tbtc.blockr.io/tx/info/e44587cf08b4f03b0e8b4ae7562217796ec47b8c91666681d71329b764add2e3](http://tbtc.blockr.io/tx/info/e44587cf08b4f03b0e8b4ae7562217796ec47b8c91666681d71329b764add2e3)
In **prev\_out** **n** is 1. Since we are indexing from 0, this means I want to spend the second output of the transaction.
In the blockexplorer we can see the corresponding address is `mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv` and I can get the scriptSig from the address like this:
Let's check out the **hash** of **prev_out** in a blockexplorer: http://tbtc.blockr.io/tx/info/e44587cf08b4f03b0e8b4ae7562217796ec47b8c91666681d71329b764add2e3
In **prev_out** **n** is 1. Since we are indexing from 0, this means I want to spend the second output of the transaction.
In the blockexplorer we can see the corresponding address is ```mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv``` and I can get the scriptSig from the address like this:

```cs
var address = BitcoinAddress.Create("mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv");
transaction.Inputs[0].ScriptSig = address.ScriptPubKey;
```
```

### Sign your transaction

Now that we have created the transaction, we must sign it. In other words, you will have to prove that you own the TxOut that you referenced in the input.
Now that we have created the transaction, we must sign it. In other words, you will have to prove that you own the TxOut that you referenced in the input.

Signing can be [complicated](https://en.bitcoin.it/w/images/en/7/70/Bitcoin_OpCheckSig_InDetail.png), but we’ll make it simple.

First let's revisit the **scriptSig** of **in**, how we can get it from code. Remember, we copypasted the address above from a blockexplorer, now let's get it from our QBitNinja transactionResponse:
First let's revisit the **scriptSig** of **in**, how we can get it from code. Remember, we copypasted the address above from a blockexplorer, now let's get it from our QBitNinja transactionResponse:

```cs
transaction.Inputs[0].ScriptSig = bitcoinPrivateKey.ScriptPubKey;
```
```

Then you need to give your private key for signing:
Then you need to give your private key for signing:

```cs
transaction.Sign(bitcoinPrivateKey, false);
```
```

### Propagate your transactions

Congratulations, you have signed your first transaction! Your transaction is ready to roll! All that is left is to propagate it to the network so the miners can see it.

#### With QBitNinja:

Congratulations, you have signed your first transaction! Your transaction is ready to roll! All that is left is to propagate it to the network so the miners can see it.
#### With QBitNinja:
```cs
BroadcastResponse broadcastResponse = client.Broadcast(transaction).Result;

Expand All @@ -263,9 +252,9 @@ else
Console.WriteLine("Success! You can check out the hash of the transaciton in any block explorer:");
Console.WriteLine(transaction.GetHash());
}
```
```

#### With your own Bitcoin Core:
#### With your own Bitcoin Core:

```cs
using (var node = Node.ConnectToLocal(network)) //Connect to the node
Expand All @@ -277,15 +266,13 @@ using (var node = Node.ConnectToLocal(network)) //Connect to the node
node.SendMessage(new TxPayload(transaction));
Thread.Sleep(500); //Wait a bit
}
```
```

The **using** code block will take care of closing the connection to the node. That's it!

You can also connect directly to the Bitcoin network, however I advise you to connect to your own trusted node \(faster and easier\)

## Need more practice?

You can also connect directly to the Bitcoin network, however I advise you to connect to your own trusted node (faster and easier)

## Need more practice?
Youtube: [How to make your first transaction with NBitcoin](https://www.youtube.com/watch?v=X4ZwRWIF49w)
CodeProject: [Create a Bitcoin transaction by hand.](http://www.codeproject.com/Articles/1151054/Create-a-Bitcoin-transaction-by-hand)
CodeProject: [DotNetWallet - Build your own Bitcoin wallet in C\#](https://www.codeproject.com/script/Articles/ArticleVersion.aspx?waid=214550&aid=1115639)

CodeProject: [DotNetWallet - Build your own Bitcoin wallet in C#](https://www.codeproject.com/script/Articles/ArticleVersion.aspx?waid=214550&aid=1115639)

0 comments on commit 1e684b5

Please sign in to comment.