In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "the concept of block chain and the realization method with Python". In the daily operation, I believe that many people have doubts about the concept of block chain and the realization method with Python. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about the concept of block chain and the realization method with Python. Next, please follow the editor to study!
Concept interpretation
Blockchain has almost become a well-known term for several days, and this term has aroused my strong interest, but by collecting materials on the Internet and reading it in many ways, I have found that many documents introducing blockchain are either ambiguous. Or the author's own understanding is also very limited, resulting in many key issues are not clearly described. I spent some time summing up, hoping to give readers a more comprehensive and clear understanding.
The official definition of a blockchain is a distributed ledger, a technical solution that collectively maintains a reliable database through decentralization and de-trust. So how do you understand outsiders? Below I will describe in detail the generation process and implementation significance of a blockchain, so as to build a clear concept of blockchain. We first talk about the principle, then the characteristics, then the use, and finally return to the code, so that you will have a sudden sense of enlightenment.
Let's take btc as an example: "blockchain", as the name implies, is a chain made up of blocks connected in turn, which can be compared to a straight chain of infinite length, and each ring is a block. So what should the content of the block be? In a narrow sense, there are two kinds of blocks, one is the ordinary block, the other is the Genesis block. Genesis Block is the first block in a blockchain project. Due to limited personal level, Chuangshi Block has not been studied in detail, but as far as I know, Chuangshi Block should have a structure similar to that of ordinary blocks, but it will certainly add something that the founder wants to say, and there may be one more record in some projects, that is, the circulation of coin. For example, the 600 billion number of swtc is written in the Genesis Block and cannot be modified once released.
So, what exactly is in an ordinary block?
1.index: this is the number generated in turn from 0mern, which can be called chain height.
2.hash: a 256-digit random number that is the unique number of this chunk.
3.previous hash: the hash of the previous block, an ordinary block has one and only one previous hash, which is why the block chain is called a chain.
4.tempstamp: used to record when the chunk was born.
5.difficulty: visually reflects the difficulty of creating the block.
6.nonce: a random number used to generate the next block.
All of the above are stored in the block.
7.data: stored transactions. Only this exists in the block.
Ok, the above mentioned some of the most basic elements of a block, you may still be in a confused state: how on earth do these things work? Next, I will analyze the working process of the blockchain step by step, but here are two questions: why should new blocks be generated? How do you create a new block?
Why does the new area come into being?
As mentioned before, a block records a bill, which stores several transaction records, which is the strongest proof of the specific activities of both buyers and sellers. For example, our purchase records on Taobao are our consumption bills. People's daily consumption records are growing and cannot be kept in the same block forever, so what's the difference from the current centralized storage mechanism? Therefore, with the increasing number of trading records, it is necessary to generate new blocks to store these data.
How do you create a new block?
I believe that recently, in addition to the term blockchain, "mining" should also be heard a lot. Mining is actually the process in which the miners generate new blocks. In the btc project, btc miners can get a certain amount of btc reward for successful mining (in fact, the successful creation of a block), so the number of btc is slowly increasing within a certain range. In the block chain projects that generally allow mining (there are also block chain projects that limit the number of coin and do not allow mining), the number of miners is generally more than 6, and generally more than 6 new blocks approved by miners can be added to the block chain. At this point, some people will say: wow! Btc is so valuable, isn't it fun to dig a mine? In fact, if the block increases rapidly without limit, it will cause great problems. According to Satoshi Nakamoto's setting, at present, the whole network can only produce one new block every 10 minutes. And these 10 minutes do not rely on their own table calculation, the generation of new blocks requires a lot of calculation, these 10 minutes are pre-designed by others, so that the amount of calculation is so large that only one can be generated in 10 minutes of the whole network.
All right, now that the basic concept of blockchain has been introduced, let's get down to business and talk about the workflow of blockchain:
1. If A wants to make a deal with B, for example, A transfers a btc,B to B and gives An a 10w RMB. First of all, A sends his btc source information, trader, etc., to B, and at the same time, a copy is sent to the whole network. What? Is there any privacy in this? Of course, the clever Satoshi Nakamoto would not have made such a low-level mistake. In the blockchain, each transaction individual (also understood as each network node) will have a pair of public key and private key, the public key is equivalent to a "collection address", and the private key is a 256-bit number indicating their identity, which is usually generated by sha265, so that others do not know who the two parties to the transaction are. When sending a message, the sender uses a hash function to generate the message digest from the message text, then encrypts the digest with its own private key, and the encrypted digest will be sent to the receiver as the digital signature of the message. The receiver first uses the same hash function as the sender to calculate the message digest from the original message received. Then the digital signature attached to the message is decrypted with the sender's public key, and if the two digests are the same, then the receiver can confirm that the digital signature belongs to the sender.
two。 So at this point, will the deal be completed? If this is done, what is the difference between An and A directly sending 10w cash in parcels to B? At this time, all miners in the network will get this transaction record, and all miners in the network will start to create blocks for several rewards. The miners will use the hash function to generate a 256-bit unique number to assign to the block, but this number is not simply generated casually. The number is uniquely determined according to the specific content of the block, such as transaction content, nonce, etc., in other words, the corresponding number of two blocks with the same content must be unique. But you will ask: what's wrong with this? It's not that hard. Wrong! In order to control the block generation time and make the block generation rate meet the standard of every 10 minutes of the whole network, Satoshi Nakamoto has formulated strict block generation verification rules, that is to say, whether you can generate a successful block depends on whether your number conforms to this rule. For example, the first n bits in the generation number must be'0'.
Since the trading content of the block cannot be modified, the miners can only try this function by modifying the nonce until a successful block is generated. If the average generation time of blocks becomes faster or slower, the system will adjust the block verification rules accordingly, so that the average generation time can be controlled in the prescribed range.
If a miner completes a block, he will immediately inform other miners that if the other miners do not complete the new block generation at this time, they will stop their work and verify the block. The main information that needs to be confirmed is as follows:
1)。 The number of the block is valid; just put the block into the hash function to see if the resulting number is the same as the number in the block.
2)。 The previous block of the block is valid; as mentioned earlier, the block is in series, and each ordinary block records the number of the previous block, which requires other miners to compare the last block of the current block chain to see if it is the same.
3)。 The transaction list is valid; that is, to verify whether A has this btc to B. In the trading information of the blockchain, the past and present lives of all the btc in the transaction will be recorded, and the blockchain can be traced back to its source, so where each btc is and why it is here can be known at a glance, so this is no problem.
When a new block is verified, the whole network will consider the block to be valid, add it to the end of the existing block chain, and end the mining work for the block and put it into the next mining cycle.
3. However, it is not difficult to imagine that there is a hidden danger of conflict in such a mechanism. it is such a coincidence that two miners have made a correct block at the same time, so it is not necessary to choose one of the two, and the original linear block chain can be changed into a tree:
But this will lead to the increase of corresponding blocks after An and B in the future, so that whoever is long will be extended as the main chain, and the other may gradually be forgotten, unless one day it becomes longer.
Well, this is the most basic knowledge of blockchain, and then it's time to talk about the advantages and disadvantages.
Nothing in the world can be said to be flawless, you know, like the blockchain, although it has been labeled as a future disruptor, it still has its limitations:
1. Timeliness. It is easy to find that there are many verification and transmission links in the block chain, which will lead to its poor timeliness.
2. Energy consumption, which is also obvious, block chain requires a large number of useless calculations to control the generation time of blocks. Therefore, blockchain is not suitable for high-aging networks.
As for the advantages of blockchain, such as security, decentralization, etc., which have been described very clearly on the network, I will not repeat them here. Next I use a piece of python code to simply implement a mining process.
Code example
First create a class that represents the blockchain:
Class BlockChain: def _ init__ (self, initialHash): # init block chain self.chain = [] # init pitman self.pitmen = [] for i in range (6): self.pitmen.append (Pitman) # collect mine results self.results = [] # generate GenesisBlock self.new_block (initialHash)
The chain in the initialization function represents the current blockchain, in which I will store the blockchain objects; pitmen represents the miners who serve this blockchain, and the miner objects will also be stored in this list; results stores the blocks generated in each stage; the new_block method is the method to create chunks. If the current generated block is the first block, it will generate a Genesis block.
Let's take a look at the method of the blockchain type:
@ propertydef last_block (self): if len (self.chain): return self.chain [- 1] else: return None
Last_block returns the last chunk object of the current blockchain.
Def get_trans (self): return json.dumps ({'sender':' '.join (random.sample (string.ascii_letters + string.digits, 8)),' recipient':''.join (random.sample (string.ascii_letters + string.digits, 8)),' amount': random.randrange (1, 10000)})
The get_trans method is used to randomly generate a transaction information.
Def new_block (self, initialHash=None): if initialHash: # generate Genesis Block block = Block () block.index = 0 block.nonce = random.randrange (0 99999) block.previousHash ='0' block.difficulty = 0 block.transactionData = self.get_trans () guess = f'{block.previousHash} {block.transactionData} '.encode () block.hash = hashlib.sha256 (guess). Hexdigest () block.time = time () self.chain.append (block) else: for i in range (len ( Self.pitmen): pm = MyThread (target= self.pitmen.mine) Args= (self.pitmen [I], len (self.chain), self.last_block.get_block () ['Hash'] Self.get_trans ()) pm.start () pm.join () self.results.append (pm.get_result ()) # show all blocks print ("All blocks generated by pitmen:") for result in self.results: print (result [0] .get _ block () # get new block firstblock = self.results [0] [0] mintime = Decimal (self.results [0] [1]) for i in range (1) Len (self.results): if Decimal (self.results [I] [1]) < mintime: firstblock = self.results [I] [0] else: continue self.chain.append (firstblock) self.results = []
This is the core part of the generated block, and this method is mainly divided into two parts: to distinguish whether it is a creation block according to the passed parameters, and if a creation block is needed, a block is automatically generated by this type to occupy the first position of the block chain. If ordinary blocks need to be generated, some basic information will be distributed to the miners for digging operations. I have set up six miners here, and for the sake of fairness, there is also a multi-thread here so that the miners can receive messages at the same time so that they can dig at the same time. According to theory, the first successful miner will send the news to other miners, and other miners will immediately stop checking, but due to time constraints, this step of verification has not been realized. Here, I allow all miners to complete the work, submit the results and the corresponding working time, and generate the shortest time-consuming blocks to be added to the block chain as the correct blocks. In essence, it is also in accordance with the "fast first" block chain generation principle.
After talking for a long time, what is it like inside the block? Class Block: def _ init__ (self): self.index = None self.time = None self.difficulty = None self.nonce = None self.hash = None self.previousHash = None self.transactionData = None def get_block (self): return {'Index': self.index,' Time': self.time, 'Difficulty': self.difficulty 'Hash': self.hash, 'Nonce': self.nonce,' PreviousHash': self.previousHash, 'TransactionData': self.transactionData}
I use a relatively simple type to represent the block, where the block is a very simple data structure, and all the fields here are described in detail in the above, so I won't repeat them.
Then let's take a look at the miners. After all, the miners are the producers and promoters of the blockchain, and their status is the core. In the miner category, I designed two methods, a mine method, which means mining, to generate a new block and return the time it took to generate the block.
Def mine (self, index, previousHash, transactionData): beginTime = time () block = Block () block.index = index block.previousHash = previousHash block.transactionData = transactionData block.difficulty, block.hash, block.nonce = self.generate_hash (previousHash, transactionData) block.time = time () endTime = time () return block, endTime-beginTime
Another method is the hash generation method, the generation principle I imagined a, you do not blame, because my computer is really not good, the success standard of the block is very simple, that is, the code generated by sha256 ends with 0 to meet the requirements, if changed to 00, then there will be no results for a long time.
Let's take a look at the running results of this set of examples. I have set a block chain with a length of 6. Since the first block is a Genesis block, the real creation of the block starts from the second. Please pay attention to index.
This is the first block completed by six miners:
All blocks generated by pitmen: {'Index': 1,' Time': 1516268156.5971138, 'Difficulty': 2,' Hash': '01f505a276e3f55a868d9ee18f70bcff75429e1de70f5ab59471a3551cc67a30eggs,' Nonce': 91554, 'PreviousHash':' 7532402844a1c130833a27600298d09a007d6124603cf44be9c05fcd5428c34awings, 'TransactionData':' {"sender": "OY8z0Rrx", "recipient": "iSGFJsEm", "amount": 8723} {'Index': 1,' Time': 1516268156.5971138, 'Difficulty': 5,' Hash': 'c340babad087d8f629830a1576938bfa44842470e2470a2490a87d82372 'PreviousHash':' 7532402844a1c130833a27600298d09a007d6124603cf44be9c05fcd5428c34aThe 'TransactionData':' {"sender": "9o8UMDLe", "recipient": "qTOQu7kv", "amount": 2746}'{'Index': 1,' Time': 1516268156.5981123, 'Difficulty': 5,' Hash': '8ff243885e9017296aa2ef1a611ef5b3927ddce818cb7255a04ff3228c982c60thanks,' Nonce': 67644, 'PreviousHash':' 7532402844a1c130833a27600298d09a007d6124603cf449cf44c05fcd5428a343cf44cf44c05fcd5428c34a3ff449f5fcd5428a343ff449fcd5fcd54c34a34ef5b3927ddce818cb7255a04ff3228c982c60A611ef5b39ddce818cb7255a04ff3228c98c60A67644, PreviousHash': '7532402844a1c130833a27600298d09a007d6124603cf449cfcd5428c34a343cf44cf44c05fcd5428c34a34ef5b3927ddce818cb7255a04ff3228c90296a2ef1a611ef5b3927ddce818cb7255a04ff3228c7844,' Nonce': 67644, 'PreviousHash':' 7532402844 "amount": 9329} {'Index': 1,' Time': 1516268156.5981123, 'Difficulty': 3,' Hash': 'ff9716bf9379e2ab7a8640419e7c7b7c7329a5e6e1bbf83a1249f49d070ca8b0',' Nonce': 37336, 'PreviousHash':' 7532402844a1c130833a27600298d09a007d6124603cf44be9c05fcd5428c34asituation, 'TransactionData':' {"sender": "vBwU0luH", "recipient": "d7o6cRCj", "amount": 5628}'} {'Index': 1,' Time': 1516268156.5981123, 'Difficulty': 3,' Hash': '3410c70c31f9fbbd74d63f25f69f27d36075e2d44bddaa60b7d72fa042e60' 'Nonce': 34617,' PreviousHash': '7532402844a1c130833a27600298d09a007d6124603cf44be9c05fcd5428c34asituation,' TransactionData':'{"sender": "yzcNpBnh", "recipient": "vbIr7SKo", "amount": 6387} {'Index': 1,' Time': 1516268156.5981123, 'Difficulty': 27,' Hash': '91e3dc3ef1a151557a1ed837528410b916362bcfb77dbb14dc54c8929f5a0d0d0d14dc54c892929f5a0d0d0d0A1130833a276008d09a007d6124603cf449cf44c54c54c54c34c007d6124603cf449fcfb77dbb0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0 "amount": 7356}'}
Obviously, the first two are the fastest. For simplicity, I randomly choose one of the fastest, as long as I know it. As you can see, the difficulty value, as mentioned above, reflects the difficulty and difficulty of generating a block, and here I will show how many attempts the miner has made to get the block. Looking at this, you may ask: why is the most difficult time not obviously long? That is, the time of use does not increase with the increase of difficulty. I guess it is because my example algorithm is simple, so the results are not very accurate, if the amount of calculation reaches a certain scale, there should be a significant gap. If anyone knows, you can reply to me. Thank you here! The third to sixth block creation result format is the same, so the screen will not be brushed.
Finally, let's take a look at the results of the whole blockchain: {'Index': 0,' Time': 1516268156.5971138, 'Difficulty': 0,' Hash': '7532402844a1c130833a27600298d09a007d6124603cf44be9c05fcd5428c34achains,' Nonce': 87688, 'PreviousHash':' 035, 'TransactionData':' {"sender": "OuVCmHbs", "recipient": "kFxbwSLc", "amount": 503}} {'Index': 1,' Time': 1516268156.5971138, 'Difficulty': 2,' Hash': '01f505a276e3fa55868d9ee18f70bff75429e1def5ab59471c67ca30' 'Nonce': 91554,' PreviousHash': '7532402844a1c130833a27600298d09a007d6124603cf44be9c05fcd5428c34asituation,' TransactionData':'{"sender": "OY8z0Rrx", "recipient": "iSGFJsEm", "amount": 8723} {'Index': 2,' Time': 1516268156.5991132, 'Difficulty': 4,' Hash': '098544436793881e804c0c903c96c0055e163961c903c96c0055e16396113d73c63bc55e7ba78ec130,' Nonce': 12875, 'PreviousHash':' 01f505a276e3f55a868d9ee18f70bcff429e1def5947a355c67ca303, TransactionData': 'sender ":" HJZSX1hk "," recipient ":" j82k51yY " "amount": 3521} {'Index': 3,' Time': 1516268156.6001143, 'Difficulty': 27,' Hash': '7c10243223caf39bc5a6067de8d93f6ea4662c4a0fbcc0aa4e086585d8200,' Nonce': 18663, 'PreviousHash':' 098544436793881e804c0c903c96c0055e16396113d73c63bc55e7ba78cc130mm, 'TransactionData':' {"sender": "cJrGxN5R", "recipient": "wkZI8QCv", "amount": 1224} {'Index': "," Time': 1516268156.601114,' Difficulty': 3, 'Hash':' 60a099d3fee031800669cc1d5ab6f1d5f18043510a3992c0d08992c0d09ccc1d9fcc1d9fcc580399cc03992cc0903bc55e7ba78cc55e7ba78cc5a1639613c63bc55e7ba78cc5a6067de83f6ea466c4a0fbc0aa4e086585d8200, 'Index': 18663,' PreviousHash': '09854436793881e804c903c96c0055e1639613d73c63bc55e7ba78137cc013799cc0992f3992c0d099d399c0d099dcc1bcc55e1639613d73c63bc55e7ba78c130mm, "recipient": "wkZI8QCv", "amount": 1224} {Index': 4,' Time': 1516268156.601114, 'Difficulty': 3,' Hash':'60 'Nonce': 51446,' PreviousHash': '7c10243223caf39bc5a6067de8d93f6ea46bad62c4a0fbcc0aa4e086585d8200,' TransactionData':'{"sender": "nCNJoy52", "recipient": "kYBT9f65", "amount": 3603} {'Index': 5,' Time': 1516268156.605163, 'Difficulty': 2,' Hash': '765f69163cf9558471015e3ce819c19803372f8a4dea553dbedd39f8920foam,' Nonce': 31804, 'PreviousHash':' 60a099d3fe53e031800669fcc1d9b5ab6fa80403543541353 10a7892fcc3d03dea553bedd39f8a4dea553dbedd39f8a4dea553dbedd39f8dea553dbedd39f8920,' Nonce': 31804, 'PreviousHash':' 60a099d3fe53e031800669fcc1d9b5ab6fa8040354353133a7892fc3d0dea553dbedd39f8a4dea553dbedd39f8a4dea5567de8d93f6a4dea5567de8d93f6ea46bad62c0a4e0865858aa4e01800669fcc1d9bc0a4e01800669fcc1d9b5ab6f8a4dea553dbedd39f8920mm, 'Nonce': 31804,' PreviousHash': '60a099dfe53e031800669fcc1d9b5ab6fa804035 "amount": 4185}'}
These are the six blocks created by the six miners in turn, interlinked according to the hash value.
In the end, what I want to say is basically over. Finally, I would like to say that blockchain is a magical technology, which has attracted me deeply since I heard it. I hope that blockchain can really bring about great changes in the future. You know, with the rise of AI and the advent of blockchain, the digital age that belongs to programmers will be further sublimated, and the Internet era is just the beginning! Thank you for reading, my level is limited, if you find a problem or I understand the deviation can be pointed out in time, thank you again. The complete code will be attached at the end of the article.
Import hashlibimport randomimport stringimport jsonimport threadingfrom decimal import Decimalfrom time import timeclass MyThread (threading.Thread): def _ _ init__ (self, target, args= ()): super (MyThread Self). _ init__ () self.func = target self.args = args def run (self): self.result = self.func (* self.args) def get_result (self): try: return self.result except Exception: return Noneclass BlockChain: def _ init__ (self InitialHash): # init block chain self.chain = [] # init pitman self.pitmen = [] for i in range (6): self.pitmen.append (Pitman) # collect mine results self.results = [] # generate GenesisBlock self.new_block (initialHash) @ property def last_block (self): if len (self.chain) ): return self.chain [- 1] else: return None def get_trans (self): return json.dumps ({'sender':'. Join (random.sample (string.ascii_letters + string.digits) 8), 'recipient':' .join (random.sample (string.ascii_letters + string.digits, 8)), 'amount': random.randrange (1, 10000)}) def new_block (self, initialHash=None): if initialHash: # generate Genesis Block block = Block () block.index = 0 block.nonce = random.randrange (0 99999) block.previousHash ='0' block.difficulty = 0 block.transactionData = self.get_trans () guess = f'{block.previousHash} {block.nonce} {block.transactionData} '.encode () block.hash = hashlib.sha256 (guess). Hexdigest () block.time = time () self.chain.append (block) Else: for i in range (len (self.pitmen)): pm = MyThread (target= self.pitmen.mine) Args= (self.pitmen [I], len (self.chain), self.last_block.get_block () ['Hash'] Self.get_trans ()) pm.start () pm.join () self.results.append (pm.get_result ()) # show all blocks print ("All blocks generated by pitmen:") for result in self.results: Print (result [0] .get _ block ()) # get new block firstblock = self.results [0] [0] mintime = Decimal (self.results [0] [1]) for i in range (1) Len (self.results): if Decimal (self.results [I] [1]) < mintime: firstblock = self.results [I] [0] else: continue self.chain.append (firstblock) self.results = [] def show_chain (self): print ('This is mine firstblock results') For block in self.chain: print (block.get_block ()) class Block: def _ _ init__ (self): self.index = None self.time = None self.difficulty = None self.nonce = None self.previousHash = None self.transactionData = None def get_block (self): return {'Index': self.index 'Time': self.time,' Difficulty': self.difficulty, 'Hash': self.hash,' Nonce': self.nonce, 'PreviousHash': self.previousHash,' TransactionData': self.transactionData} class Pitman: def mine (self, index, previousHash TransactionData: beginTime = time () block = Block () block.index = index block.previousHash = previousHash block.transactionData = transactionData block.difficulty, block.hash, block.nonce = self.generate_hash (previousHash, transactionData) block.time = time () endTime = time () return block, endTime-beginTime @ staticmethod def generate_hash (previousHash TransactionData): difficulty = 0 nonce = random.randrange (0 99999) guess = f'{previousHash} {transactionData} '.encode () myhash = hashlib.sha256 (guess). Hexdigest () while myhash [- 1]! =' 0mm: difficulty + = 1 nonce + = difficulty guess = f'{previousHash} {transactionData} '.encode () myhash = hashlib.sha256 (guess). Hexdigest () return difficulty, myhash Nonceif _ _ name__ = ='_ _ main__': chain = BlockChain (1) length = 5 for i in range (length): chain.new_block () chain.show_chain () so far The study on "the concept of blockchain and how to implement it with Python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 244
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.