Building a block chain with Go--Part 5: Address __ block chain

Source: Internet
Author: User
Tags readable

The translation of the series of articles I have put on the GitHub: blockchain-tutorial, follow-up updates will be on the GitHub, may not be synchronized here. If you want to run the code directly, you can also clone GitHub on the Tutorial warehouse and go to the SRC directory to execute make. Introduction

In the last article, we have initially achieved the transaction. Believe you should understand some of the natural properties of the transaction, these attributes do not have the slightest "personal" color: in bitcoin, no user account, no need and will not store personal data anywhere (such as name, passport number or SSN). However, there is always a way to recognize that you are the owner of the output of the transaction (that is, you have the currency locked on those outputs). This is the task that the Bitcoin address needs to accomplish. In the previous article, we took a user-defined arbitrary string as an address, and now we're going to implement a real address like a bitcoin. The code implementation of this article has changed a lot, please click here to see all the code changes. bit-Currency address

This is a real bit-currency address: 1a1zp1ep5qgefi2dmptftl5slmv7divfna. This is the first bitcoin address in history, it is said to belong to the Cong. The Bitcoin address is completely public, and if you want to send a coin to someone, you just need to know his address. However, the address (although the address is also unique) is not used to prove that you are a "wallet" the owner of the token. In fact, the so-called address is simply to express the public key as a human readable form, because the native public key human is difficult to read. In Bitcoin, your identity is a pair of (or more pairs) of public keys (or "private" keys) that are stored on your computer (or where you can get it). Bitcoin creates these keys based on a combination of cryptographic algorithms, and ensures that no one else in the world can take your currency unless you get your key. Now, let's talk about what these algorithms are. Public Key Cryptography

The Public Key Cryptography (Public-key Cryptography) algorithm uses a pair of keys: a public key and a private key. Public keys are not sensitive information and can be told to others. However, the private key cannot be told to anyone: only the owner can know the private key, and it is the private key that identifies, authenticates, and proves the owner. In the world of encrypted money, your private key is what you are, and the private key is everything.

In essence, Bitcoin wallet is just such a key pair. When you install a wallet application or use a bit-currency client to generate a new address, it generates a pair of keys for you. In Bitcoin, who has the private key, who can control the currency that is sent to the public key.

Private and public keys are simply random byte sequences, so they cannot be printed on the screen, and humans cannot read them through the naked eye. That's why Bitcoin uses a conversion algorithm that converts a public key into a human-readable string (that is, the address we see). If you use a Bitcoin purse, it is likely that it will generate a mnemonic for you. Such mnemonics can be used to override the private key and can be used to generate the private key. BIP-039 has already implemented this mechanism.

Okay, now that we know that the identity of the user in the bitcoin is the private key. So how does bitcoin check the ownership of the transaction output (and the currency stored in it)? Digital Signatures

In mathematics and cryptography, there is a concept of digital signature (digital signature), which guarantees that data will not be modified when data is transmitted from sender to receiver, data is created by a certain sender, and the sender cannot deny the fact that the data has been sent.

By applying the signature algorithm (that is, signing the data) on the data, you can get a signature that will be validated later. A private key is required to generate a digital signature, and a public key is required to verify the signature. The signature is a bit similar to the seal, for example, I made a painting, finished with a seal, it shows that this painting is my work. To generate signatures for data is to cover the data.

In order to sign the data, we need two things: the private key of the data to be signed

The signature algorithm can be used to generate a signature, and the signature is stored in the transaction input. To verify a signature, we need three things: a signed data signature public key

In simple terms, the validation process can be described as checking that the signature is made from the signed data plus the private key, and that the public key happens to be generated by the private key. The data signature is not encrypted and you cannot reconstruct the data from a signature. This is a bit like a hash: you run a hash algorithm on the data and then get a unique representation of the data. The difference between a signature and a hash is a key pair: A key pair is available for signature verification. However, a key pair can also be used to encrypt data: The private key is used for encryption and the public key is used to decrypt the data. However, Bitcoin does not use cryptographic algorithms.

In bitcoin, each transaction entry is signed by the person who created the transaction. Each transaction must be validated before it is placed in a block. In addition to some other steps, validation means that checking the transaction input has the right to use the output from the previous transaction check that the transaction signature is correct

As shown in the figure, the process of signing and verifying the data is as follows:

Now to review the complete lifecycle of a transaction: At first, the Genesis block contained a Coinbase transaction. In Coinbase transactions, there is no input, so there is no need to sign. The output of the Coinbase transaction contains a hashed public key (using the
RIPEMD16 (SHA256 (PubKey) ) When a person sends a currency, a transaction is created. The input of this transaction will refer to the output of the previous transaction. Each input stores a public key (not hashed) and a signature for the entire transaction. Other nodes in the Bitcoin network that receive the transaction authenticate the transaction. In addition to some other things, they also check: in one input, the public key hash matches the referenced output hash (which guarantees that the sender can only spend its own currency); The signature is correct (this ensures that the transaction is created by the actual owner of the currency). When a miner prepares to dig a new block, he puts the deal in a block and starts digging. When a new block is dug out, all other nodes in the network receive a message telling others that the block has been dug up and added to the block chain. When a block is added to the block chain, the transaction is completed and its output can be referenced in the new transaction. Elliptic Curve Encryption

As mentioned previously, public and private keys are random byte sequences. The private key can be used to prove the identity of the bearer and requires a condition that the random algorithm must generate a truly random byte. Because no one wants to generate a private key, and the private key is accidentally owned by someone else.

The bitcoin uses an elliptic curve to generate the private key. The elliptic curve is a complex mathematical concept, and we are not going to explain too much here (if you are really curious to see this article, note: There are many mathematical formulas.) As long as we know that these curves can generate very large random numbers is enough. The curves used in Bitcoin can be randomly selected at 0 and 2 ^ 2 ^ 56 (presumably 10^77, and the total number of atoms in the visible universe is between 10^78 and 10^82). Having such a high ceiling means that it is almost impossible to generate the same private key for two of times.

Bitcoin uses the ECDSA (elliptic Curve Digital Signature) algorithm to sign the transaction, and we also use the algorithm. Base58

Go back to the Bitcoin address mentioned above: 1a1zp1ep5qgefi2dmptftl5slmv7divfna. Now we know that this is the public key in human-readable form. If we decode it, we see the public key as it is (16 bytes in binary):

0062e907b15cbf27d5425399ebf6f0fb50ebb88f18c29b7d93

Bitcoin uses the BASE58 algorithm to convert the public key into a human-readable form. This algorithm is similar to the famous Base64, except that it uses a shorter alphabet: To remove some letters from the alphabet in order to avoid attacks that use alphabetic similarity. That is, there are no these symbols: 0 (0), O (uppercase O), I (Capital I), l (lowercase l), because these letters look very much alike. In addition, there are no + and/symbols.

The following figure is the process of obtaining an address from a public key:

Therefore, the public key that is mentioned above contains three parts:

Version public  key hash                           Checksum       62e907b15cbf27d5425399ebf6f0fb50ebb88f18  c29b7d93

Since the hash function is one-way (which is also said to be irreversible), it is not possible to extract the public key from a Greek. However, by executing the hash function and making a hash comparison, we can examine whether a public key is used for the generation of hashes.

All right, all the details are ready to write code. Many concepts can only be understood more thoroughly when writing code. Implementation Address

Let's start with the wallet Wallet structure:

Type Wallet struct {
    privatekey ecdsa. Privatekey
    publickey  []byte
}

type wallets struct {
    wallets Map[string]*wallet
}

func Newwallet () *wallet {
    private, public: = Newkeypair ()
    Wallet: = wallet{private, public} return

    &wallet
}

Func Newkeypair () (ECDSA. Privatekey, []byte) {
    curve: = elliptic. P256 ()
    private, err: = Ecdsa. GenerateKey (Curve, Rand. Reader)
    PubKey: = Append (private. Publickey.x.bytes (), Private. Publickey.y.bytes () ...)

    Return *private, PubKey
}

A wallet has only one key pair. We need a wallets type to hold a combination of multiple wallets, save them to a file, or load them from a file. The Wallet constructor generates a new key pair. The Newkeypair function is very intuitive: ECDSA is based on an elliptic curve, so we need an elliptic curve. Next, the ellipse is used to generate a private key, and then a public key is generated from the private key. One thing to note: In an algorithm based on elliptic curves, the public key is the point on the curve. Therefore, the public key is a combination of x,y coordinates. In bitcoin, these coordinates are concatenated and form a public key.

Now, to generate an address:

Func (w Wallet) getaddress () []byte {
    Pubkeyhash: = Hashpubkey (W.publickey)

    versionedpayload: = Append ([]byte{ Version}, Pubkeyhash ...)
    Checksum: = Checksum (versionedpayload)

    fullpayload: = Append (Versionedpayload, checksum ...)
    Address: = Base58encode (fullpayload) return address
}

func Hashpubkey (PubKey []byte) []byte {
    publicSHA256: = sha256. Sum256 (PubKey)

    ripemd160hasher: = ripemd160. New ()
    _, Err: = Ripemd160hasher.write (publicsha256[:])
    publicRIPEMD160: = Ripemd160hasher.sum (nil)

    Return publicRIPEMD160
}

func checksum (payload []byte) []byte {
    Firstsha: = sha256. SUM256 (payload)
    Secondsha: = sha256. SUM256 (firstsha[:]) return

    Secondsha[:addresschecksumlen]
}

Converting a public key to an BASE58 address requires the following steps: Use the RIPEMD160 (SHA256 (PubKey) hash algorithm, take the public key and hash it two times to the hash plus the prefix of the address generation algorithm version for the results generated in the second step, use SHA256 ( Payload)), then hash, and compute the checksum. The checksum is the first four bytes of the result hash. Officers transferred Guevara and attached to the Version+pubkeyhash combination. Encodes a version+pubkeyhash+checksum combination using BASE58.

At this point, you can get a real bit-currency address , and you can even view its balance in Blockchain.info. However, I can responsibly say that no matter how many times a new address is generated, checking its balance is 0. This is why it is so important to choose an appropriate public key encryption algorithm: Given that the private key is a random number, the probability of generating the same number must be as low as possible. Ideally, it must be low to "forever" without repetition.

Also, note: You don't need to connect to a bitcoin node to get an address. The multiple open source algorithms used by the address generation algorithm can be implemented in many programming languages and libraries.

Now we need to modify the input and output to use the address:

type txinput struct {txid []byte Vout int Signature []byte pubkey []byte} func (in *TXINP UT) useskey (pubkeyhash []byte) bool {lockinghash: = Hashpubkey (in. PubKey) return bytes. Compare (Lockinghash, pubkeyhash) = = 0} type txoutput struct {Value int pubkeyhash []byte} func (out *txo
    Utput) Lock (address []byte) {pubkeyhash: = Base58decode (address) Pubkeyhash = Pubkeyhash[1:len (Pubkeyhash)-4] Out. Pubkeyhash = Pubkeyhash} func (out *txoutput) Islockedwithkey (Pubkeyhash [] 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.