Blockchain study notes and summary [2]

Blockchain overview

Blockchain is the core technology of Bitcoin, which is used to record orderly and time-stamped transaction records in the Bitcoin system. It is mainly used to prevent (double spend) double flower attacks and tamper with previous transaction records.

It should be noted here that it is to prevent tampering, not to prevent changes. In fact, certain situations in the blockchain encourage changes, such as when illegal blocks are written. Since only the longest legal chain is recognized, for those blocks that are not in the longest legal chain, they are modified.

In general, the blockchain is a self-stabilizing system that does not require external forces (when most of the computing power is in the hands of good people). The entire block reflects the will of the vast majority of participants. Of course, most of these standards have different standards in different system designs. In the Bitcoin system, it is the vast majority of computing power.

It should be noted that the decentralization of Bitcoin still cannot prevent the emergence of groups. Although it is still difficult for a group to control the entire system. To prevent groups from appearing, we need to design another mechanism, which may be a mechanism similar to the few decisions in a fraud game (an anime feels good) , but in the end it seems inevitable to form a team.

In addition, the fairness pursued by Bitcoin is not absolute fairness, but a kind of linear fairness. For example, if my computing power is twice that of yours, then my income should be twice yours, and the effect cannot be amplified again, just to prevent the Matthew effect - the rich get richer and the poor get poorer.

Of course, the above paragraph is mainly my own subjective opinion, which may not be correct. The following is bitcoina summary of the relevant

Introduction to Blockchain

Each full node in Bitcoin independently stores a blockchain containing only the blocks validated by that node. When multiple nodes have the same blocks in their blockchain, they are said to have reached consensus, a logical public ledger. The validation rules these nodes follow to maintain consensus are called consensus rules . A good decentralized system should amplify the consensus rules.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-2oApcObg-1642693109129)(bitcoin.assets/en-blockchain-overview-16426818607191.svg)]

The diagram above shows a simplified version of the blockchain. A block is collected into the transaction data portion of a block. A copy of each transaction is hashed, and the hashes are paired, hashed, paired again, and hashed again until one hash remains, the Merkle Merkle treeroot of the Merkle tree Merkle root.

The Merkle root is stored in the block header. Each block also stores a hash of the previous block header, chaining the blocks together. This ensures that a transaction cannot be modified without modifying the block in which it was recorded, and all subsequent blocks.

Transactions are also chained together. Bitcoin wallet software gives the impression that bitcoins are being sent from wallet to wallet, but bitcoins are actually being transferred from one transaction to another. Each transaction spends bitcoins previously received in one or more transactions, so the input to one transaction is the output from the previous transaction.

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-g4DDmE1f-1642693109130) (https://developer.bitcoin.org/_images/en-transaction-propagation.svg )]

A single transaction can create multiple outputs, as is the case with sending to multiple addresses, but each output for a particular transaction can only be used as an input once in the blockchain. Any subsequent references are prohibited double spending - attempting to spend the same bitcoin twice.

The output and transaction identifier (TXID) is a hash of the signed transaction.

Since each output of a particular transaction can only be spent once, the outputs of all transactions contained in the blockchain can be classified as transaction outputs (UTXOs) or spent transaction outputs. In order for a payment to be valid, it can only use UTXOs as input.

Treated as a transaction fee to create a block containing that transaction For example, in the diagram above, each transaction spent 10,000 satoshi less than it received from its combined inputs, effectively paying 10,000 satoshi in transaction fees.

proof of work

The above network is jointly maintained by anonymous nodes, so Bitcoin requires each block to prove that a lot of work was put into its creation process to ensure that bad nodes who want to modify past blocks must have good nodes work harder. Want to add a new block to the blockchain.

Chaining blocks together makes it impossible to modify transactions contained in any block without modifying all subsequent blocks. This results in the cost of modifying a particular block increasing as the number of new blocks added to the blockchain increases, amplifying the effect of proof-of-work.

Proof-of-work exploits the unpredictability of cryptographic hashes. A good cryptographic hashing algorithm converts arbitrary data into a seemingly random number. If the data is modified in any way and the hash is re-run, a new seemingly random number is produced, so the data cannot be modified to make the hash number predictable.

To prove that you did some extra work to create a block, you have to create a hash of the block header that does not exceed a certain value. For example, if the maximum possible hash value is 2255, by generating a hash value less than 2255, you can prove that you tried at most two combinations. .

New blocks are only added to the blockchain when the difficulty is as challenging as the consensus protocol expects every 2,016 blocks. The network uses the timestamp stored in each block header to calculate the first and last 2,016 blocks. The number of seconds elapsed between the last block generation. An ideal value is 1,209,600 seconds (two weeks).

If it took less than two weeks to generate 2,016 blocks, the difficulty value is expected to increase proportionally (up to 300%), so if hashes are checked at the same rate, the next 2,016 blocks should take exactly two weeks to complete generate. If it takes more than two weeks to generate a block, the expected difficulty value is reduced proportionally (minimum 75%) for the same reason.

The block header provides several easily modifiable fields, such as a dedicated nonce field, so getting a new hash does not require waiting for a new transaction. In addition, only the 80-byte block header is hashed for proof-of-work, so including a large amount of transaction data in a block does not slow down the hashing process due to additional I/O, but adding additional Transaction data only needs to recalculate the ancestor hashes in the Merkle tree.

Block heights and forks

Any Bitcoin miner who successfully hashes the block header to a value below the target threshold can add the entire block to the blockchain (assuming the block is legitimate).

[External link picture transfer failed, the source site may have an anti-leech link mechanism, it is recommended to save the picture and upload it directly (img-uFrkYRK4-1642693109131)(bitcoin.assets/en-blockchain-fork-16426834035843.svg)]

Multiple blocks can have the same block height, which is common when two or more miners produce a block at roughly the same time. This creates an obvious fork in the blockchain , as shown in the diagram above.

When miners simultaneously produce blocks at the end of the blockchain, each node individually chooses which block to accept. In the absence of other considerations, as described below, nodes generally use the first block they see.

The two chains compete for the longest legal chain at the same time, and the nodes in the network choose the longest legal block they agree to dig down. In the end, the chain with the most computing power wins, and the differences are eliminated.

The block is only connected to one competing concurrently mined block. This makes that side of the fork stronger than the other. Assuming a fork contains only valid blocks, normal nodes always follow the hardest chain to recreate and discard shorter forks

Long-term forks are possible if different miners work for different purposes, such as some miners working to extend the blockchain while others try to modify transaction history through a 51% attack.

transaction data

Each block must contain one or more transactions. The first of these transactions must be a coinbase transaction, also known as a minting transaction, which should collect and spend block rewards (including the block subsidy and any transaction fees paid by transactions included in the block).

The UTXO of a coinbase transaction has a special condition that it cannot be spent (used as input) for at least 100 blocks. This temporarily prevents miners from spending transaction fees and block rewards from a block that could be rolled back after a block chain fork (and thus the coinbase transaction is broken).

Blocks are not required to contain any coinbase transactions, but miners will almost always include additional transactions to collect transaction fees.

All transactions, including coinbase transactions, are encoded into blocks in a binary raw transaction format.

Hash the raw transaction format to create a transaction identifier (txid). From these txids, a Merkle tree is built by pairing each txid with another txid and then hashing them together. If there is an odd number of txids, a txid with no siblings will be hashed with a copy of itself.

The resulting hashes are themselves each paired with the other and hashed together. Any hash that has no siblings hashes with itself. The process is repeated until only one hash remains, the Merkle root.

For example, if transactions are only joined (rather than hashed), a five-transaction Merkle tree would look like the text graph below:

       ABCDEEEE .......Merkle root
      /        \
   ABCD        EEEE
  /    \      /
 AB    CD    EE .......E is paired with itself
/  \  /  \  /
A  B  C  D  E .........Transactions

The merkle tree allows clients to verify that a transaction was included in a block by getting the merkle root from the block header and a list of intermediate hashes from the full peers. Full peers do not need to be trusted: forging block headers is costly, and intermediate hashes cannot be forged or verification will fail.

For example, to verify that transaction D was added to a block, an SPV client only needs a copy of the hash of C, AB, and EEEE in addition to the merkle root; the client does not need to know about any other transactions. If all five transactions in this block were at their maximum size, downloading the entire block would require over 500,000 bytes - but downloading the three hashes plus the block header would only require 140 bytes.

Consensus Rule Changes

To maintain consensus, all full nodes validate blocks using the same consensus rules. However, consensus rules are sometimes changed to introduce new features. When the new rules are implemented, there may be a period of time when non-upgraded nodes follow the old rules and upgraded nodes follow the new rules, resulting in two possible situations

  1. Blocks following the new consensus rules are accepted by upgraded nodes but rejected by non-upgraded nodes. For example, a new transaction feature is used in a block: upgraded nodes understand the feature and accept it, but non-upgraded nodes reject it because it violates the old rules.
  2. Blocks that violate the new consensus rules are rejected by upgraded nodes but accepted by non-upgraded nodes. For example, an abusive transaction function is used in a block: upgraded nodes reject it because it violates the new rules, but non-upgraded nodes accept it because it follows the old rules.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-DZ0865Rr-1642693109132)(bitcoin.assets/en-hard-fork-16426847269895.svg)]

In the first case, rejected by non-upgraded nodes, mining software that gets blockchain data from those non-upgraded nodes refuses to build on the same chain as mining software that gets data from upgraded nodes. This creates permanently different chains — one for non-upgraded nodes and one for upgraded nodes — known as a hard fork.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-CqeoWhCv-1642693109134)(https://developer.bitcoin.org/_images/en-soft-fork.svg )]

In the second case, the upgraded node refuses, which prevents the blockchain from permanently forking if the upgraded node controls a majority of the computing power. This is because, in this case, the non-upgraded nodes will accept all the same blocks as the upgraded nodes as valid blocks, so the upgraded node digs more computing power off the chain, and the non-upgraded nodes will eventually accept the upgraded nodes The longest chain mined is the longest legal chain . This is called a soft fork.

trade

Each transaction is composed of several parts, which can realize simple direct payments or complex transactions.

For simplicity, assume that the coinbase transaction does not exist.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-00ddyeSP-1642693109136)(bitcoin.assets/en-tx-overview-16426849841618.svg)]

The diagram above shows the main parts of a Bitcoin transaction. Every transaction has at least one input and one output. Each input spends bitcoins paid to previous outputs. Each output acts as an unspent transaction output (UTXO) waiting for an input after it is spent. When your bitcoin wallet tells you that you have a balance of 10,000 bitcoins, it actually means that you have 10,000 bitcoins in one or more UTXOs.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-NLAmQDVU-1642693109138)(bitcoin.assets/en-tx-overview-spending.svg)]

The output has an index number of where the transaction is located, and an amount in satoshis whose payment terms are pubkey scriptgiven by the script. Anyone who can satisfy the script's conditions can spend the bitcoins in this output.

Inputs use a transaction identifier (txid) and an output index number (often called the "vout" of the output vector) to identify a specific output to spend. It also has a signature script signature scriptto match against pubkey script.

The diagram below helps illustrate how these features are used by showing the workflow that Alice uses to send a transaction to Bob, and Bob uses that transaction later to spend. Both Alice and Bob will use the most common standard Pay-To-Public-Key-Hash (P2PKH) transaction type. P2PKH lets Alice spend satoshis to a typical Bitcoin address, and then lets Bob use a simple cryptographic key pair.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-0nQ2pyYu-1642693109139)(bitcoin.assets/en-creating-p2pkh-output.svg)]

Bob must first generate a private/ public key pair before Alice can create the first transaction. Bitcoin uses the Elliptic Curve Digital Signature Algorithm ( ECDSA ) and the secp256k1 curve; the secp256k1 private key is 256 bits of random data. A copy of this data is deterministically transformed into a secp256k1 public key. Because the transformation can be reliably repeated later, there is no need to store the public key.

The public key (pubkey) is then cryptographically hashed. This public key hash can also be reliably repeated later, so there is no need to store it either. The hash shortens and obfuscates the public key, making manual transcription easier and providing security against accidental problems.

Bob provides the public key hash to Alice as the payment address. These addresses are base58 encoded strings containing the address version number, hash and checksum. This address can be transmitted over any medium and can be further encoded into another format, such as a bitcoin:urlQR code included.

Once Alice has the address and decodes it back to a standard hash, she can create her first transaction. She creates a standard P2PKH transaction output containing instructions that anyone can spend that output if they can prove they control the private key corresponding to Bob's hashed public key.

Alice broadcasts the transaction and adds it to the blockchain. The bitcoin network stores it as an unspent transaction output (UTXO).

Some time later, when Bob decides to spend the UTXO, he must create an input that references the hash (txid) of the transaction Alice created to say where the bitcoin came from, and the index number she used. He must then create a signature script—a set of data parameters that satisfy the conditions Alice placed in the previous output's public key script.

Public key scripts and signature scripts combine secp256k1 public keys and signatures with conditional logic to create programmable authorization mechanisms.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-qUgJI9Qq-1642693109139)(bitcoin.assets/en-unlocking-p2pkh-output.svg)]
For P2PKH-style output, Bob's signature script will contain the following two pieces of data:

  1. His full (unhashed) public key, so the pubkey script can check that its hash is the same as the pubkey hash provided by Alice.
  2. The secp256k1 signature works by combining certain transaction data (described below) with Bob's private key using the ECDSA encryption formula. This lets the pubkey script verify that Bob possesses the private key that created the public key.

Bob's secp256k1 signature not only proves that Bob controls his private key; it also makes the non-signature script part of his transaction immutable, so Bob can propagate it through the p2p network

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Q5PlwTIN-1642693109140)(bitcoin.assets/en-signing-output-to-spend.svg)]

As shown in the figure above, the data signed by Bob includes the txid and output index of the previous transaction, the pubkey script of the previous output, the pubkey script created by Bob to let the next recipient spend the output of this transaction, and the pubkey script to be redeemed number of satoshis. Essentially, the entire transaction is signed except for the signing script, which contains the full public key and secp256k1 signature.

After putting his signature and public key into the signing script, Bob goes through the peer-to-peer network . Each node and miner independently validates the transaction before further broadcasting it or attempting to include it in a new transaction block.

P2PKH script verification

The verification process requires the evaluation of the signature script and the public key script. In the P2PKH output, the pubkey script is:

OP_DUP OP_HASH160 <PubkeyHash> OP_EQUALVERIFY OP_CHECKSIG

The spender's signature script is evaluated and prefixed at the beginning of the script. In a P2PKH transaction, the signature script contains the secp256k1 signature (sig) and the full public key (pubkey), creating the following concatenation:

<Sig> <PubKey> OP_DUP OP_HASH160 <PubkeyHash> OP_EQUALVERIFY OP_CHECKSIG

The scripting language is a Forth-like stack-based language that is deliberately designed to be stateless and not Turing-complete. Statelessness ensures that once a transaction is added to the blockchain, there is no condition to make it permanently unspendable. Turing incompleteness (specifically the lack of loops and goto) makes scripting languages ​​less flexible and more predictable, greatly simplifying the security model.

To test whether the transaction is valid, the signature script and public key script operations are executed one at a time, starting with Bob's signature script and ending with Alice's public key script. The figure below shows a standard P2PKH pubkey script in action.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-wXIJz5oK-1642693109142)(bitcoin.assets/en-p2pkh-stack.svg)]

  • The signature (from Bob's signature script) is pushed to an empty stack. Since it's just data, it does nothing but add it to the stack. The public key (also from the signing script) is pushed on top of the signature.

  • From Alice's pubkey script, OP_DUPthe operations are performed. OP_DUPPushes a copy of the data currently on top of it onto the stack—in this case, creating a copy of the public key provided by Bob.

  • What happens next OP_HASH160pushes the hash of the data currently on top of it (in this case, Bob's public key) onto the stack.

  • Alice's pubkey script then pushes the hash of the pubkey that Bob provided her in the first transaction. At this point, there are two copies of Bob's pubkey hash at the top of the stack.

  • Alice's pubkey script executes OP_EQUALVERIFY. OP_EQUALVERIFYEquivalent to execute OP_EQUALheel OP_VERIFY.

    OP_EQUAChecks the two values ​​at the top of the stack; in this case, it checks that the public key hash generated from the full public key provided by Bob is equal to the public key #1hash provided by Alice when creating the transaction. OP_EQUALPops (removes from the top of the stack) the two values ​​it compares, and replaces them with the result of the comparison: falseor true.

    OP_VERIFYCheck the value at the top of the stack. If value is false, terminate immediately and transaction validation fails. Otherwise, it will truebe popped from the stack.

  • Finally, Alice's public key script executes OP_CHECKSIG, which checks the signature provided by Bob against the now-verified public key he also provided. If the signature matches the public key and was generated using all the data required to be signed, OP_CHECKSIGa value is truepushed onto the top of the stack.

If falseis not at the top of the stack, the transaction is valid.

P2SH script

Pubkey scripts need to be created by consumers who are not interested in what the script does.

For this problem, pay-to-script-hash (P2SH) was invented to allow the payer to create a pubkey script that contains the hash of a second script, the Redeem script.

The basic P2SH workflow shown in the diagram below looks almost identical to the P2PKH workflow. Bob creates a redeem script using whatever script he wants, hashes the redeem script, and provides the redeem script hash to Alice. Alice creates a P2SH-style output containing Bob's redeem script hash.

When Bob wants to spend an output, he provides his signature along with the full (serialized) redeem script in the signing script. Make sure the hash of the redeem script is the same as the hash in signatrue, then it will process the redeem script like a pubkey script, and let Bob spend the output if the redeem script doesn't return false.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-F4DkVB7J-1642693109143)(https://developer.bitcoin.org/_images/en-unlocking-p2sh-output .svg)]

The hash of the redeem script has the same properties as the public key hash, so it can be converted to the standard Bitcoin address format with minor changes to distinguish it from the standard address. This makes collecting P2SH style addresses as easy as collecting P2PKH style addresses. The hash still hides the public key in the redeem script, so a P2SH script is as secure as a P2PKH public key hash.

standard transaction

As of Bitcoin Core 0.9, the standard pubkey script type is

  • Pay To Public Key Hash (P2PKH)
  • Pay To Script Hash (P2SH)
  • Multisig
  • Pubkey
  • Null Data

P2PKH

P2PKH is the most common form of public key scripting used to send transactions to one or more Bitcoin addresses.

Pubkey script: OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
Signature script: <sig> <pubkey>

P2SH

P2SH is used to send transactions to script hashes. Every standard public key script can be used as a P2SH redemption script, excluding P2SH itself. Starting with Bitcoin Core 0.9.2, P2SH transactions can contain any valid exchange script, making the P2SH standard more flexible and allowing experimentation with many novel and complex transaction types. The most common use of P2SH is the standard multi-signature public key script, followed by the Open Asset Protocol .

Another common redeemScript for P2SH is to store text data on the blockchain.

Pubkey script: OP_HASH160 <Hash160(redeemScript)> OP_EQUAL
Signature script: <sig> [sig] [sig...] <redeemScript>

As long as the script hash matches the redeem script, this combination of scripts looks flawless for older nodes without P2SH capabilities. But the new node will do further verification of the redemption script. They will extract the redeem script from the signature script, decode it, and execute it. Therefore, to redeem a P2SH transaction, the spender must provide a valid signature or answer in addition to a correct redeem script.

The final step is similar to the verification step in a P2PKH or P2Multisig script, where the initial part of the signature script <sig> [sig] [sig..]acts as the "signature script" in P2PKH/P2Multisig, and the redeem script acts as the "public key script".

Multisig

While there is already P2SH for multisig, this basic script can be used to require multiple signatures before a UTXO can be used.

In a multi-signature public key script called m-of-n, m is the minimum number of public keys that must match, and n is the number of public keys provided.

Due to a bug in the original Bitcoin implementation, OP_CHECKMULTISIGthe value consumed from the stack was one m more than indicated , so the list in the secp256k1 signature script must be signed with an extra OP_0.

The signing script must provide signatures in the same order that the corresponding public keys appear in the pubkey script or redeem script. See the description in "OP_CHECKMULTISIG" for details.

Pubkey script: <m> <A pubkey> [B pubkey] [C pubkey...] <n> OP_CHECKMULTISIG
Signature script: OP_0 <A sig> [B sig] [C sig...]

While it's not a separate transaction type, this is a P2SH multisig with 2-of-3:

Pubkey script: OP_HASH160 <Hash160(redeemScript)> OP_EQUAL
Redeem script: <OP_2> <A pubkey> <B pubkey> <C pubkey> <OP_3> OP_CHECKMULTISIG
Signature script: OP_0 <A sig> <C sig> <redeemScript>

Pubkey

Public key outputs are a simplified form of P2PKH public key scripts, but they are not as secure as P2PKH, so they are generally no longer used for new transactions.

Pubkey script: <pubkey> OP_CHECKSIG
Signature script: <sig>

Null Data

Null Data Adds arbitrary data to unusable pubkey scripts in the default relayed and mined transaction type Bitcoin Core 0.9.0 and later, full nodes don't have to store it in their UTXO database. It is better to use Null Data transactions instead of other transactions, because other transactions cannot be automatically deleted;

Pubkey Script: OP_RETURN <0 to 40 bytes of data>(Null data scripts cannot be spent, so there's no signature script.)

Lock time and serial number

One thing that all signature hash types sign is the locktime of the transaction. (It's called nLockTime in the Bitcoin Core source code.) The lock time represents the earliest time a transaction can be added to the blockchain.

Locktime allows signers to create time-locked transactions that only go into the future, giving signers the opportunity to change their minds.

If any signer changes their mind, they can create a new non-locking time transaction. The new transaction will use the same inputs as the lock and time transactions. If a new transaction is added to the blockchain before the timelock expires, because the inputs are the same, this will cause the timelocked transaction to conflict with the new transaction, thereby canceling the transaction.

transaction fees and

Transactions pay fees based on the total byte size of signed transactions. The fee per byte is calculated based on the current space demand for mined blocks, and the fee rises as demand increases. Transaction fees are given to Bitcoin miners, so ultimately it is up to each miner to choose the lowest transaction fee they will accept.

Since each transaction costs unspent transaction outputs (UTXO), and since a UTXO can only be spent once, the full value of the UTXO must be spent or given to miners in its entirety as transaction fees. Very few people will have a UTXO that exactly matches the amount they want to pay, so most transactions include change outputs.

It is theoretically possible to reuse the same P2PKH public key hash or P2SH script hash as used in the UTXO, but for security it is common to change the output to send to a new P2PKH or P2SH address.

avoid key reuse

In a transaction, the spender and receiver each reveal to the other any public keys or addresses used in the transaction. This allows any one person to use the public blockchain to track past and future transactions involving the same public key or address of another person.

If the same public key is reused frequently, as happens when people use a Bitcoin address (hashed public key) as a static payment address, others can easily track that person's receiving and spending habits, including when they are at a known address How many bitcoins are controlled in .

Even better, using a new public key when accepting payments or creating change outputs can be combined with other techniques discussed later (such as CoinJoin or merge avoidance), making blockchain alone a way to reliably track users become extremely difficult

Transaction Malleability

Transaction malleability opens the door to denial of service attacks. The signing script contains a secp256k1 signature, which cannot be signed by itself, allowing an attacker to make non-functional modifications to the transaction without invalidating it. For example, an attacker can add some data to the signature script that will be removed before processing the previous public key script (guaranteed to match the previous public key script).

Although these modifications are non-functional—so they don't change the inputs used by the transaction or the outputs paid for—they do change the computed hash of the transaction. Since each transaction is linked to the previous transaction using a hash as the transaction identifier (txid), the modified transaction will not have the txid expected by its creator.

For most bitcoin transactions that are intended to be added to the blockchain immediately, this is not a problem. However, this does become a problem if the output of the transaction is spent before the transaction is added to the blockchain.

Bitcoin developers have been working hard to reduce transaction malleability between standard transaction types, and one outcome of these efforts is BIP 141: Segregated Witness , which is supported by Bitcoin Core and activated in August 2017. When not using segwit, new transactions should not depend on previous transactions that have not been added to the blockchain, especially if a large number of satoshis are at stake.

Transaction malleability also affects payment tracking. Bitcoin Core's RPC interface lets you track transactions by their txid - but if the txid changes because the transaction was modified, the transaction may disappear from the network.

Transactions should be tracked by the transaction outputs (UTXOs) they spend as inputs, since they cannot be changed without invalidating them.

If a transaction does seem to disappear from the network and needs to be reissued, reissue it in a way that invalidates the missing transaction (i.e., issue a conflicting transaction). One approach that always works is to ensure that the reissued payment spends the same input as the lost transaction.

contract

Contracts are transactions that use the decentralized Bitcoin system to enforce financial agreements. Bitcoin contracts can often be designed to minimize reliance on external agents, such as the court system, which greatly reduces the risk of dealing with unknown entities in financial transactions.

Escrow and Arbitration

The customer Charlie wants to buy a product from the merchant Bob, but neither of them trusts the other, so they use a contract to help ensure that Charlie gets his item and Bob gets his payment.

A simple contract could say that Charlie will spend satoshis on an output that can only be spent if both Charlie and Bob have signed the input to spend it. This means Bob won't get paid unless Charlie gets his item, but Charlie can't get the item and keeps his payment.

This simple contract doesn't help much if there is a dispute, so Bob and Charlie enlist Alice's help to create an escrow contract . Charlie spends his satoshis on outputs, which can only be spent if two of the three people sign the input. Now, if everything works, Charlie can pay Bob, if something goes wrong, Bob can refund Charlie's money, or if there is a dispute, Alice can arbitrate and decide who should get the satoshis.

To create a multisignature ( multisig ) output, they each give the other a public key. Bob then creates the following P2SH multi-signature redemption script:

OP_2 [A's pubkey] [B's pubkey] [C's pubkey] OP_3 OP_CHECKMULTISIG

(The opcode to push the public key onto the stack is not shown.)

OP_2and OP_3push the actual numbers 2 and 3 onto the stack. OP_2Specifies that 2 signatures are required to sign; OP_3specifies that 3 public keys are provided (unhashed). This is a 2-of-3 multi-signature public key script, more generally known as an m-of-n public key script (where m is the minimum matching signature required and n is the number of public keys provided

Bob hands the redeem script to Charlie, who checks to make sure his public key and Alice's public key are included. He then hashes the redeem script to create a P2SH redeem script and pays satoshis to it. Bob sees the payment is added to the blockchain and ships the item.

Unfortunately, the item was slightly damaged during shipping. Charlie wants a full refund, but Bob thinks a 10% refund is enough. They turn to Alice to solve the problem. Alice asks Charlie for photo evidence and a copy of the redemption script that Bob created and checked by Charlie.

After looking at the evidence, Alice decides that a 40% refund is enough, so she creates and signs a transaction with two outputs, one that dedicates 60% of satoshis to Bob's public key, and one that dedicates the remaining 40% Public key for Charlie.

In the signing script, Alice puts her signature and a copy of the unhashed serialized redemption script created by Bob. She provides a copy of the incomplete transaction to Bob and Charlie. Either of them can do it by adding his signature to create the following signature script:

OP_0 [A's signature] [B's or C's signature] [serialized redeem script]

When the transaction is broadcast to the network, each node checks the signed script against Charlie's previously paid P2SH output, ensuring that the redeem script matches the previously provided redeem script hash. The redeem script is then executed, using the two signatures as input data. Assuming the redemption script is verified, the two transaction outputs appear as spendable balances in Bob's and Charlie's wallets.

However, if Alice creates and signs a transaction that neither of them agrees to, such as spending all satoshis to herself, Bob and Charlie can find a new arbitrator and sign a transaction that spends satoshis for another 2- of-3 multisignature redemption script hash, this one includes the public key from the second arbitrator. This means that Bob and Charlie never have to worry about their arbitrator stealing their money.

Source: BitRated provides a multi-signature arbitration service interface using HTML/JavaScript on a GNU AGPL-licensed website.

micropayment channel

Alice also moderates forum posts for Bob on a part-time basis. Every time someone posts on Bob's busy forum, Alice goes through the post to make sure it's not offensive or spam. Bob often forgets to pay her, so Alice demands payment as soon as she approves or rejects each post. Bob says he can't do this because hundreds of micropayments will cost him thousands of satoshis in transaction fees, so Alice suggests they use the micropayment channel .

Bob asks Alice for her public key, and creates two transactions. The first transaction pays 100 millibitcoins to a P2SH output, and its 2-of-2 multisig redemption script requires both Alice and Bob's signatures. This is a bond deal. Broadcasting this transaction would hold Alice hostage in millibitcoins, so Bob keeps this transaction private for now and creates a second transaction.

After the lock time enforces a 24 hour delay, the second transaction spends all the millibitcoins (minus transaction fees) from the first transaction back to Bob. This is a refund transaction. Bob cannot sign the refund transaction himself, so he gives it to Alice to sign, as shown in the figure below.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-fUcsv8Zc-1642693109144)(bitcoin.assets/en-micropayment-channel.svg)]

Alice checks that the refund transaction's lock time is 24 hours in the future, signs it, and returns a copy of it to Bob. She then asks Bob for the bond transaction, and checks to see if the refund transaction spent the output of the bond transaction. She can now broadcast the bond transaction to the network , ensuring that Bob has to wait for the timelock to expire before spending his milliBitcoins further. So far, Bob hasn't actually spent any money, except for a possible small transaction fee, and he will be able to get a refund within 24 hours .

Now, when Alice does some work worth 1 millibitcoin, she asks Bob to create and sign a new version of the refund transaction. The second version of the transaction spends 1 millibitcoin to Alice and returns 99 to Bob; it has no lock time, so Alice can sign and spend it whenever she wants. (But she won't do it right away.)

Alice and Bob repeat these work and payment steps until Alice finishes work for the day, or until the timelock is about to expire. Alice signs and broadcasts the final version of the refund transaction, pays herself and returns the remaining balance to Bob. The next day, when Alice goes to work, they create a new micropayment channel .

If Alice fails to broadcast a version of the refund transaction before the timelock expires , Bob can broadcast the first version and get a full refund . This is one of the reasons micropayment channels are best for small payments — if Alice's internet service is down for a few hours near the timelock expiration, she could be scammed out of payment.

Transaction malleability, discussed in the Transactions section above, is limited to micropayment channels . If someone uses transaction malleability to break the link between two transactions, Alice can seize Bob's 100 millibitcoins even if she did no work.

For larger payments, Bitcoin transaction fees are a very low percentage of the total transaction value, so it makes more sense to secure the payment with a separate transaction that is immediately broadcast.

Resources: bitcoinj A complete set of micropayment functions, a sample implementation and a tutorial all under the Apache license.

CoinJoin

Alice worries about her privacy. She knows that every transaction is added to the public blockchain, so when Bob and Charlie pay her, each of them can easily track those satoshis to know the bitcoin address she paid to, how much she paid, and where she might have satoshis. How many satoshis are left.

Alice is not a criminal, she just wants to plausibly deny where she spent her satoshis and how much she has left, so she starts Tor anonymity service on her computer and logs into the IRC chat room as "AnonGirl".

There are also "Nemo" and "Neminem" in the chat room. They collectively agree to transfer satoshis between each other, so no one but them can reliably determine who controls which satoshis. But they were faced with a dilemma: who would first transfer their satoshis to one of the two other aliases? CoinJoin-style contracts like the one pictured below make this decision easy: they create a single transaction that completes all payouts at the same time, ensuring that neither of them can steal the other's satoshis.

[External link picture transfer failed, the source site may have an anti-leech link mechanism, it is recommended to save the picture and upload it directly (img-nEIfgD3o-1642693109145)(https://developer.bitcoin.org/_images/en-coinjoin.svg)]

Each contributor looks at their set of unspent transaction outputs (UTXOs) looking for 100 millibitcoins that they can spend. They then each generate a brand new public key and provide the UTXO details and public key hash to the coordinator. In this case, the moderator is AnonGirl; she creates a transaction that uses each UTXO for three outputs of the same size. One output for each contributor's public key hash.

AnonGirl is then used SIGHASH_ALLto ensure that no one can change the input or output details. She hands the partially signed transaction to Nemo, who signs his input in the same way and passes it to Neminem, who signs it in the same way. Neminem then broadcasts the transaction to the Bitcoin peer-to-peer network , mixing all millibitcoins in one transaction.

As you can see in the illustration, no one other than AnonGirl, Nemo, and Neminem can confidently determine who received which output, so each of them can plausibly derogate from their output.

Now, when Bob or Charlie try to track Alice's transactions through the blockchain, they will also see the transactions made by Nemo and Neminem. If Alice does a few more CoinJoins, Bob and Charlie may have to guess which transactions from dozens or hundreds of people were actually made by Alice.

The full history of Alice's satoshis is still on the blockchain, so determined investigators can talk to people who joined AnonGirl Coin to find out the ultimate source of her satoshis and possibly reveal AnonGirl as Alice. But for anyone casually browsing the history of the blockchain, Alice gets plausible denial.

The CoinJoin technique described above requires participants to pay a small amount of satoshis to cover transaction fees. Another technique, Buyer CoinJoin, can actually save their Satoshi and improve their privacy at the same time.

AnonGirl waits in the IRC chat room until she wants to buy. She announces her intention to spend satoshis and waits until someone else wants to buy, possibly from a different merchant. Then they combine the inputs in the same way as before, but set the outputs to individual merchant addresses, so no one can figure out what one of them bought from the merchant just from the blockchain history.

Since they have to pay the transaction fee to make the purchase anyway, AnonGirl and her co-consumers don't pay any extra - but because they reduce overhead and save bytes by combining multiple transactions, they may be able to pay less Small total transaction fees, saving everyone a small amount of Satoshi.

Current working implementations: As of today, 2018, JoinMarket and Wasabi Wallet are operational CoinJoin implementations for Bitcoin.

JoinMarket-style CoinJoins differ from the above schemes by splitting the participants into two parts: market makers and market makers. Market makers are posting their CoinJoin intent to the IRC room and waiting for market takers to accept their offers. When a taker comes along, it selects a group of makers and creates a sharing transaction with them, paying a small fee. Unlike the scenarios above, this happens automatically.

Wasabi Wallet style CoinJoins are called Chaumian CoinJoins. It uses a CoinJoin coordinator where various peers can register. CoinJoin-round starts when a predetermined number of participants register. In this scheme, blind Chaumian signatures are used to prevent the coordinator and peers from learning which outputs correspond to which inputs. An example of a Chaumian CoinJoin is the following transaction: 8fee07b90f26e85e22e87da13e1618cd9eeaf98f3f3774273c9307cd40ff98e8

Guess you like

Origin blog.csdn.net/qq_45256489/article/details/122612347