Blockchain Note – BTC Transaction

Transaction in BTC

Bitcoin or similar distributed systems will have a design that is very different from the normal design:
Each node in the layout is both a client and a server.

So in the design of distributed systems, when using classes to describe objects, it is sometimes necessary to distinguish between which classes are used as clients and which classes are used as servers to receive clients. Because the client and the server are running the same set of code, but in the actual operation process, if you follow the C/S model (in fact, you should not look at it this way, you should change your thinking into the thinking of designing p2p nodes). Will see the Tx/Block produced by C and the Tx/Block received by S

Vector<CTxIn> vin;
Vector<CTxOut> vout;

These two key member variables. These two member variables represent the “income” and “expense” of bitcoin transactions, respectively. The Bitcoin transaction is not a record of the account-shaped data changes (for example, we use the bank model to describe A to B transfer 100 yuan, then the bank will record 3 records in the process of recording this transfer, these three records are connected A Transaction process: A’s account is reduced by 100 yuan, the recorded id is tid1, B’s account is added with 100 yuan, the recorded id is tid2, and a transfer record records tid1 transferred to tid2 for 100 yuan, becoming A. The account is reduced by the “relationship connection” with the increase of the B account.), but the log shape: the Tx of the bitcoin only records the “relational connection” of the transfer from A to B. This log record only includes the transfer of A to B by 100.

And here in is to record from ”who’ (currently simple to see this, the actual is not only this, the text will slowly re-interpret), out is transferred to who, and how much money is transferred is included in In Out

In storage, bitcoin uses Tx’s hash as the key and CTxIndex as the value. So we got one
CTransaction (or its subclasses) can get the TxIndex corresponding to this Tx by obtaining the local storage of the hash index of this Tx.


This class is a subclass of Tx that is used to handle the relevant processing in the Block. CMerkleTx is a related class when the miner (server) holds the Tx
It added on the basis of the original Tx
classCMerkleTx: public CTransaction{
uint256 hashBlock;
vector<uint256> vMerkleBranch;
int nIndex;
3 properties, hashBlock represents the hash of the current Tx block (as an index), vMerkleBranch is the hash value of the Tx paired in the merkle tree (this paired hash value will be explained in a later article), here is Used to verify Tx’s additional information in the block. Index represents the location of the Tx in the block.

vs Traditional Bank

According to the traditional process (online banking model), the two processes should be as follows: ps (about the concept of the central coinage node reference bitcoin white paper article)
• The originator of the transaction obtains the balance in the account of the central coinage node (such as a bank) (not required) -> the transaction initiator obtains the relevant information of the transaction recipient (such as the bank card number of the other party) -> the transaction initiator will transfer the amount And the other party’s information tells the central coin node
• The central coin node obtains the information of the initiator -> checks the originator’s account balance -> determines whether the transfer amount is below the balance -> destroys the amount of the initiator’s account that needs to be transferred (reducing the assets of the initiator’s account) -> casting to receiving The account accepts the amount of the transfer (increasing the same assets of the recipient’s account) -> destruction and casting constitute a “transaction”

In the overall process of bitcoin’s transfer, the two processes are different. The transaction initiator and the transaction recipient are in the same angle, but the role of the verification transaction is changed from the original “central coinage node” to “All miners and everyone who accepts the block containing this Tx”
• The transaction originator checks his own locally stored information (Wallet) to get the total assets he can use (not required) -> the transaction initiator gets the relevant information of the transaction recipient (bitcoin address) -> after local inspection ( Not necessarily) generating a transaction Tx and broadcasting

The miners (we) receive the transaction -> according to their own local storage information (all TxIndex) used to verify the historical transaction information corresponding to the TxIn received information, the most important two aspects
• Whether the Tx corresponding to TxIn is not spent (UTXO)
‐> If the verification is successful, put it into the memory pool and wait for it to be packed into the block.
‐> After packaging into the block, modify your local storage (TxIndex) ‐> Broadcast this block to more people
‐>(Other miners) If the block received is the longest chain–>Verify this block–>Verify the verification and save it (others’ history)->Remove the relevant Tx->interrupt in the memory pool Own packing block process -> repacking the Tx in the remaining memory pool

After the above analysis, the comparison between the traditional way and the bitcoin way can be concluded that the biggest difference is:
Where was the process of verifying the history being transferred?
Because in the correctness of the guarantee transaction process, the key point is that a transaction can be successful, depends on whether the previous transaction is correct, such as:
• In a traditional transaction, the user’s account balance is checked to be the transfer amount.
• In bitcoin, check to see if the TxIn used by Tx has been spent and is controlled by the originator of the transaction (pub key_script, sig_script pairing)
The traditional transaction and bitcoin are quite significant:
• Traditional transactions must rely on the central node. It is absolutely impossible to bypass the center to generate transactions, otherwise the transaction will not be recognized.
• The verification history of bitcoin transactions is based entirely on the history of personal storage, without exception, whether it is an individual or a miner, this is back to the questions raised in the analysis section:

How is a Tx in a distributed environment, even if the nodes are not trusted, they can still accept transactions generated by others. The answer to this question is simple:

Because nodes are not trusting each other, they trust themselves. Nodes only believe in their own history and only make judgments based on their own historical records. Then the question comes: Is your history record right or wrong? (The right or wrong here is a relative meaning, it should be said that it is consistent with most people)

This issue involves the highest principle of bitcoin, and only recognizes that the longest chain of work is the only recognized bitcoin chain.

BTC Script

So in my opinion, Bitcoin’s Script is actually:
scriptPubKey is a “problem” from the previous transaction (out)
And scriptSig is the money I want to use in the previous transaction, then I will provide my “answer” to the question you asked.
Because of the public-private key relationship, if the problem raised by scriptPubKey is a public key-related problem, it is obvious that only the person holding the private key can answer the question, so it is simplified to the “lock” and “key” just mentioned.

On the other hand, how to confirm the “answer” provided is to answer the “problem”? This means that the script needs to be verified, and the verification process only needs the scriptSig provided by txin and the scriptPubKey of the txout that the verifier himself finds from his own records. This verifier is the majority of miners.

Script is an extremely powerful place in the Bitcoin system. It is really a wave of smart contracts after this mode of operation has started. It extends the process of simply authenticating a transaction’s attribution problem from simple authentication to running scripts. Roughly speaking, it complicates a simple thing, and in fact greatly expands the meaning of “transaction”. Make transactions can contain “logic”, not just “state” Nakamoto has redefined the “transaction” by the pioneering evolution of the “transaction process” into a “question-answer” process.

Although the private key and wallet address of the bitcoin wallet are from ECDSA
The private key and the public key, however, the wallet address is not directly the public key, but the hash of the public key. Therefore, if you pay for a wallet, you don’t need the public key of the wallet; only when the wallet uses the money inside (to give money to others), you need to put your public key in the transaction. If a wallet is just collecting money, then it is safe — even if the Shor algorithm requires a public key to reverse the private key. Because the public key is not exposed, the Shor algorithm cannot be used.

Therefore, even if quantum computing breaks the asymmetric encryption algorithm, it can’t be cracked for those cold wallets that have not been used. For those who need multisig, it is similar.

If you have to crack the cold wallet, you need to reverse the wallet address to its public key, and this operation Shor can not be completed, only by other algorithms.

Because of this system, we can find that a transaction in Bitcoin is actually TxIn in the transaction. A transaction can be generated by different people to generate their own TxIn and then combine the transaction, which makes multi-party participation possible. Instead of a transaction, only two participants are input and output.


Priority = transaction amount × queue time ÷ transaction size
The transaction amount is the primary factor affecting the priority: the larger the amount, the higher the priority of the transaction – let the leader eat first. Trading gold

The accurate queuing time is the block age: the wallet initiates a transaction and immediately spreads to the entire network.
Broadcast, the block age when the miner received is 0. If the 100 blocks are still not recorded, then the block of the transaction

The transaction information size refers to the number of bytes in which the transaction information is recorded, and the unit of the byte is byte. For example, the transaction has only one
Pens come in and out, the size is about 250bytes, while some transactions have multiple input and output transaction information size is relatively large

First, pick out the top 2,000 transactions with the highest priority, but the total size of these transactions cannot exceed
Second, find a random number so that there is enough “0” before the hash of the “block + random number”.

If a simple transaction (250bytes) is 1 bitcoin (100 million Cong), wait 1 day (about 144 blocks)
It has not been recorded yet, and its priority is:
100,000,000 × 144 ÷ 250 = 57,600,000
With this number in mind, a transaction with a priority greater than 57,600,000 is called a “high priority transaction.” Even if no tip is given, the miner will store it in the first 50K bytes of the block – then your transaction is equivalent to Leaders can enter small rooms and enjoy special services.


The miners packed 2,288 transactions and found the random number (Nonce) 101544420, which was approved by the entire network miners.
So I got Transaction Fees about 8.6 coins and Block Reward.
There are 12.5 coins.
The system will put 21.1 coins into the address of the miner once, we are used to calling it Coinbase.
Coinbase is not a transaction because it has no input (see the left side of the figure: No Inputs).
Coinbase is a field structure, only those who dig out this block can fill out
Coinbase includes commissions and burrowing rewards for all transactions within the block

The attacker can take three steps:
step1: spend 3 million US dollars to buy 200 bitcoins normally, and normal packing and accounting.
Step 2: Sell these coins in the market and get $3 million in cash.
Step 3: start 51% attack, erase the second step of selling 200 coins, repackage the transaction, calculate the random number.

Transaction in Code

Transaction id

The transaction id is calculated by taking a hash from the contents of the transaction. However, the signatures of the txIds are not included in the transaction hash as the will be added later on to the transaction.
const getTransactionId=(transaction:Transaction):string=>{
   const txInContent:string=transaction.txIns
       .reduce((a, b)=>a+b,'');

   const txOutContent:string=transaction.txOuts
       .reduce((a, b)=>a+b,'');


Transaction signatures

It is important that the contents of the transaction cannot be altered, after it has been signed. As the transactions are public, anyone can access to the transactions, even before they are included in the blockchain.
When signing the transaction inputs, only the txId will be signed. If any of the contents in the transactions is modified, the txId must change, making the transaction and signature invalid.
const signTxIn=(transaction:Transaction, txInIndex:number,
                 privateKey:string, aUnspentTxOuts:UnspentTxOut[]):string=>{
   const txIn:TxIn=transaction.txIns[txInIndex];
   const dataToSign =;
   const referencedUnspentTxOut:UnspentTxOut=findUnspentTxOut(txIn.txOutId, txIn.txOutIndex, aUnspentTxOuts);
   const referencedAddress=referencedUnspentTxOut.address;
   const key=ec.keyFromPrivate(privateKey,'hex');
   const signature:string=toHexString(key.sign(dataToSign).toDER());
   return signature;

Coinbase transaction

Transaction inputs must always refer to unspent transaction outputs, but from where does the initial coins come in to the blockchain? To solve this, a special type of transaction is introduced: coinbase transaction
The coinbase transaction contains only an output, but no inputs. This means that a coinbase transaction adds new coins to circulation.
const COINBASE_AMOUNT:number=50;
The coinbase transaction is always the first transaction in the block and it is included by the miner of the block. The coinbase reward acts as an incentive for the miners: if you find the block, you are able to collect 50 coins.
We will add the block height to input of the coinbase transaction. This is to ensure that each coinbase transaction has a unique txId. Without this rule, for instance, a coinbase transaction stating “give 50 coins to address 0xabc” would always have the same txId.
const validateCoinbaseTx=(transaction:Transaction, blockIndex:number):boolean=>{
   if (getTransactionId(transaction) !== {
       console.log('invalid coinbase tx id: ' +;
       return false;

   if(transaction.txIns.length!==1) {
       console.log('one txIn must be specified in the coinbase transaction');


   if(transaction.txIns[0].txOutIndex!==blockIndex) {
       console.log('the txIn index in coinbase tx must be the block height');
       return false;

   if(transaction.txOuts.length!==1) {
       console.log('invalid number of txOuts in coinbase transaction');
       return false;

   if(transaction.txOuts[0].amount!=COINBASE_AMOUNT) {
       console.log('invalid coinbase amount in coinbase transaction');
       return false;

   return true;



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s