The basic concept of blockchain is simple: a distributed database that stores an ever-lengthening list containing many ordered records. The following article mainly introduces you to the relevant information about blockchain for learning Python. The article introduces it in detail through sample code. Friends who need it can take a look below.
Preface
This article will give you a brief introduction to the relevant knowledge about blockchain (BlockChain), and use Python to make a simple implementation. Not much to say below, let’s take a look at the detailed introduction:
What is blockchain
In short, blockchain It is a permanent and irreversibly modified record generated by superimposing (chaining) encrypted data (blocks) in chronological order. Specifically, the blockchain is composed of a series of data blocks generated using cryptographic methods. Each block contains the hash value of the previous block, starting from the genesis block. Start connecting to the current block to form a block chain. Each block is guaranteed to be generated after the previous block in chronological order, otherwise the hash value of the previous block is unknown. It is an important concept in Bitcoin.
Features
The blockchain has the following characteristics:
Decentralization: The blockchain does not rely on a central node, but on distributed nodes.
No trust system required: The blockchain is based on cryptographic algorithms, and data requires approval by other users within the network, so there is no need for a third-party intermediary structure or endorsement by a trust organization.
Untamperable and encrypted security: The blockchain adopts a one-way hash algorithm, and each newly generated block is strictly advanced in linear order according to time. The irreversibility of time causes any Attempts to intrude and tamper with data information in the blockchain can be easily traced, leading to rejection by other nodes, which can limit related illegal activities.
#The above characteristics enable blockchain to have more and more applications in many fields such as banking, securities markets, and finance.
How blockchain works
Blockchain is a series of encrypted data blocks. These blocks consist of a block header containing metadata, followed by a long list of transactions that make up the body of the block. The block structure in Bitcoin is as follows:
Block header
The block header contains information related to other areas in the blockchain The connection information, timestamp, nonce and other information in the block are as follows:
Block identifier
The block has Two identifiers, one is the hash value of the block header, and the other is the block height. The hash value of the block header is a number obtained by performing a secondary hash calculation on the block header using the SHA256 algorithm. The block hash value uniquely and unambiguously identifies a block, and any node can independently obtain the block hash value by simply hashing the block header. Block height refers to the position of the block in the blockchain. Block height is not a unique identifier. While a single block will always have a clear, fixed block height, the converse is not true and a block height does not always identify a single block. Two or more blocks may have the same block height and compete for the same position in the blockchain.
After understanding the above basics, let’s start using Python to implement a simple blockchain.
Python implementation of blockchain
1. Define the block structure
In [ 16]:
# block.py import hashlib import uuid class Block(object): def __init__(self, data=None, previous_hash=None): self.identifier = uuid.uuid4().hex # 产生唯一标示 self.nonce = None # nonce值 self.data = data # 区块内容 self.previous_hash = previous_hash # 父节点哈希值 def hash(self, nonce=None): ''' 计算区块的哈希值 ''' message = hashlib.sha256() message.update(self.identifier.encode('utf-8')) message.update(str(nonce).encode('utf-8')) message.update(str(self.data).encode('utf-8')) message.update(str(self.previous_hash).encode('utf-8')) return message.hexdigest() def hash_is_valid(self, the_hash): ''' 校验区块哈希值有否有效 ''' return the_hash.startswith('0000') def __repr__(self): return 'Block<Hash: {}, Nonce: {}>'.format(self.hash(), self.nonce)
The above is a block structure. What is implemented here is a simplified version, which does not fully correspond to the blocks in Bitcoin. The block here contains a unique identifier, the hash value of the parent node, the nonce value and the content field of the block. You can see that the hash value of a block must meet certain conditions to be valid, such as starting with 0000. Next, initialize this block structure.
In [37]:
# 创建一个内容为hello world的内容块 block = Block('Hello World') block
Out[37]:
Block<Hash: 238a65a101c8829d7fc406eb78a71cfc19ad702b437e2c1be8d9061ddb81e900, Nonce: None>
Although the above block has been created, its hash value is not valid.
In [38]:
block.hash_is_valid(block.hash())
Out[38]:
False
Change the value of nonce to get a new hash value.
In [39]:
block.hash(1)
Out[39]:
'a6431938ba10270dfcfdf7a2371312446914fedadf79632c2c0adb3b463f4838'
The hash value was updated, but is not yet a valid hash value. In order to obtain a valid hash value, it is a process of constantly updating the nonce value, or a mining process. Add a mine function below to get a suitable nonce value.
In [78]:
# block.py import hashlib import uuid class Block(object): def __init__(self, data=None, previous_hash=None): self.identifier = uuid.uuid4().hex # 产生唯一标示 self.nonce = None # nonce值 self.data = data # 区块内容 self.previous_hash = previous_hash # 父节点哈希值 def hash(self, nonce=None): ''' 计算区块的哈希值 ''' message = hashlib.sha256() message.update(self.identifier.encode('utf-8')) message.update(str(nonce).encode('utf-8')) message.update(str(self.data).encode('utf-8')) message.update(str(self.previous_hash).encode('utf-8')) return message.hexdigest() def hash_is_valid(self, the_hash): ''' 校验区块哈希值有否有效 ''' return the_hash.startswith('0000') def __repr__(self): return 'Block<Hash: {}, Nonce: {}>'.format(self.hash(self.nonce), self.nonce) ''' 新增挖矿函数 ''' def mine(self): # 初始化nonce为0 cur_nonce = self.nonce or 0 # 循环直到生成一个有效的哈希值 while True: the_hash = self.hash(nonce=cur_nonce) if self.hash_is_valid(the_hash): # 如果生成的哈希值有效 self.nonce = cur_nonce # 保持当前nonce值 break # 并退出 else: cur_nonce += 1 # 若当前哈希值无效,更新nonce值,进行加1操作
In [75]:
block = Block('Hello World') # 挖矿,循环直至找到合适的nonce block.mine() # 打印 block
Out[75]:
Block<Hash: 000087359d5264153d624556f0a0c6f25cba06e453975c1c02587862e823911b, Nonce: 64751>
至此,第一个有效的区块生成完成,下面开始定义区块链。
二、定义区块链结构
In [81]:
class BlockChain(object): def __init__(self): self.head = None # 指向最新的一个区块 self.blocks = {} # 包含所有区块的一个字典 ''' 添加区块函数 ''' def add_block(self, new_block): previous_hash = self.head.hash() if self.head else None new_block.previous_hash = previous_hash self.blocks[new_block.identifier] = { 'block': new_block, 'previous_hash': previous_hash, 'previous': self.head, } self.head = new_block def __repr__(self): num_existing_blocks = len(self.blocks) return 'Blockchain<{} Blocks, Head: {}>'.format( num_existing_blocks, self.head.identifier if self.head else None )
定义好区块链结构后,下面就开始初始化一条区块链。
In [82]:
# 初始化 chain = BlockChain() # 打印 chain
Out[82]:
Blockchain<0 Blocks, Head: None>
In [83]:
# 添加区块 chain.add_block(block) # 打印 chain
Out[83]:
Blockchain<1 Blocks, Head: 364c0cf963384ca28a2763499a140405>
In [84]:
# 添加更多的区块 for i in range(6): new_block = Block(i) new_block.mine() chain.add_block(new_block) # 打印 chain
Out[84]:
Blockchain<7 Blocks, Head: e7cb24ec7acd42a4aaebe7faee9e0713>
以上就是一个简单区块链,后面还会涉及到区块链的有效性。当区块链中一个区块被改变后,这个区块的哈希就会改变,从而影响到这块区块之后的区块,致使这个区块链不再有效。这些将在后续继续深入。
The above is the detailed content of Introduction to Python Basics--Blockchain. For more information, please follow other related articles on the PHP Chinese website!

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver Mac version
Visual web development tools
