## bitcoin protocol: transaction encoding

4

I am writing a program (in golang) to mine bitcoins. Supposing I have this dummy transaction, how may I encode it so it can be used in the block im trying to mine?

Also, supposing I have a block header as below:

// binary header data encoded as a hex string:

000000000000000003e6d3647001d1f455d585cdd3c298093902fe52ea4529ba01000030cd0594ebccfe15b205125165cc3b66986ed5b2a311cd8805000000000000000037022f7a3b9a2b199d53fbf1552be32c141892319966c3ef999d348d74cfb5827f476357a09b0518ae5ae1c1

// original header data that has been encoded to build the above header:

Version: 01000030

prev_block: cd0594ebccfe15b205125165cc3b66986ed5b2a311cd88050000000000000000

Merkle root: 37022f7a3b9a2b199d53fbf1552be32c141892319966c3ef999d348d74cfb582

Timestamp: 7f476357

nbits: a09b0518

Nonce: ae5ae1c1

computed_hash: 000000000000000003e6d3647001d1f455d585cdd3c298093902fe52ea4529ba

How may I add our dummy transaction to the given header (suppose the header already have the merkle root in it)? What if I wish to add multiple transactions like our dummy transaction data to our block header ?

2

Feb2018: This is a very generic question of an older request, I answer it anyhow, maybe someone will be searching for this info, just like I was doing :-)

The main point is, that the transaction is not part of the block header. The block starts with a blocksize number of 4 bytes, a block header of 80 bytes, and a transaction counter (var_int, 1-9 Bytes). Then follows all the transactions in the block. The block header starts with a 4 bytes version field, followed by the previous block hash (32 bytes) and the merkle tree (32bytes). This is followed by three fields of 4 bytes each: difficulty, timestamp, and nonce.

In your example, the block should be composed this way:

Block size: 00000264 (612 Bytes)

Version: 01000030

prev_block: cd0594ebccfe15b205125165cc3b66986ed5b2a311cd88050000000000000000

Merkle root: 37022f7a3b9a2b199d53fbf1552be32c141892319966c3ef999d348d74cfb582

Timestamp: 7f476357

nbits: a09b0518

Nonce: ae5ae1c1

tx counter: 2

Without the first field, this is a length of 612 bytes, which must be converted into a 4 bytes, which is placed at the beginning of the block. So the full block would be:

<block size>

01000030

cd0594ebccfe15b205125165cc3b66986ed5b2a311cd88050000000000000000

<merkle tree>

7f476357

a09b0518

ae5ae1c1

2

<coinbase ... >