python使用md5加密_如何使用Python创建自己的加密货币

python使用md5加密

With the current rise of cryptocurrencies, blockchain is creating a buzz in the technology world. This technology has attracted so much attention mainly because of its ability to guarantee security, enforce decentralization, and quicken processes to several industries—especially to the financial industry.
随着当前加密货币的兴起,区块链正在技术界引起轰动。 这项技术之所以吸引了如此多的关注,主要是因为它具有保证安全,强制分权以及加快多个行业(尤其是金融行业)流程的能力。

Essentially, a blockchain is a public database that irreversibly documents and authenticates the possession and transmission of digital assets. Digital currencies, like Bitcoin and Ethereum, are based on this concept. Blockchain is an exciting technology that you can use to transform the capabilities of your applications.

本质上,区块链是一个公共数据库,不可逆地记录和认证数字资产的拥有和传输。 比特币和以太坊等数字货币都基于此概念。 区块链是一项令人兴奋的技术,可用于转换应用程序的功能。

Of late, we’ve been seeing governments, organizations, and individuals using the blockchain technology to create their own cryptocurrencies—and avoid being left behind. Notably, when Facebook proposed its own cryptocurrency, called Libra, the announcement stirred many waters across the world.

最近,我们一直在看到政府,组织和个人使用区块链技术来创建自己的加密货币,并避免被抛在后面。 值得注意的是,当Facebook提出自己的名为Libra的加密货币时,这一公告激起了全世界的许多热潮。

What if you could also follow suit and create your own version of a cryptocurrency?

如果您也可以效仿并创建自己的加密货币版本怎么办?

I thought about this and decided to develop an algorithm that creates a crypto.

我考虑了这一点,决定开发一种可以创建加密货币的算法。

I decided to call the cryptocurrency fccCoin.

我决定将加密货币称为fccCoin

In this tutorial, I’m going to illustrate the step-by-step process I used to build the digital currency (I used the object-oriented concepts of the Python programming language).

在本教程中,我将逐步说明构建数字货币的过程(我使用了Python编程语言的面向对象概念)。

Here is the basic blueprint of the blockchain algorithm for creating the fccCoin:

这是用于创建fccCoin的区块链算法的基本蓝图:

class Block:

    def __init__():

    #first block class

        pass
    
    def calculate_hash():
    
    #calculates the cryptographic hash of every block
        
    
class BlockChain:
    
    def __init__(self):
     # constructor method
    pass
    
    def construct_genesis(self):
        # constructs the initial block
        pass

    def construct_block(self, proof_no, prev_hash):
        # constructs a new block and adds it to the chain
        pass

    @staticmethod
    def check_validity():
        # checks whether the blockchain is valid
        pass

    def new_data(self, sender, recipient, quantity):
        # adds a new transaction to the data of the transactions
        pass

    @staticmethod
    def construct_proof_of_work(prev_proof):
        # protects the blockchain from attack
        pass
   
    @property
    def last_block(self):
        # returns the last block in the chain
        return self.chain[-1]

Now, let me explain what is taking place…

现在,让我解释一下发生了什么……

1.建立第一个Block类 (1. Building the first Block class)

A blockchain comprises of several blocks that are joined to each other (that sounds familiar, right?).

区块链由多个相互连接的块组成(听起来很熟悉,对吧?)。

The chaining of blocks takes place such that if one block is tampered with, the rest of the chain becomes invalid.

块的链接发生,以便如果一个块被篡改,则链的其余部分将变为无效。

In applying the above concept, I created the following initial block class:

在应用上述概念时,我创建了以下初始块类:

import hashlib
import time

class Block:

    def __init__(self, index, proof_no, prev_hash, data, timestamp=None):
        self.index = index
        self.proof_no = proof_no
        self.prev_hash = prev_hash
        self.data = data
        self.timestamp = timestamp or time.time()

    @property
    def calculate_hash(self):
        block_of_string = "{}{}{}{}{}".format(self.index, self.proof_no,
                                              self.prev_hash, self.data,
                                              self.timestamp)

        return hashlib.sha256(block_of_string.encode()).hexdigest()

    def __repr__(self):
        return "{} - {} - {} - {} - {}".format(self.index, self.proof_no,
                                               self.prev_hash, self.data,
                                               self.timestamp)

As you can see from the code above, I defined the __init__() function, which will be executed when the Block class is being initiated, just like in any other Python class.

从上面的代码中可以看到,我定义了__init __()函数,该函数将在启动Block类时执行,就像在其他任何Python类中一样。

I provided the following parameters to the initiation function:

我为启动函数提供了以下参数:

  • self—this refers to the instance of the Block class, making it possible to access the methods and attributes associated with the class;

    self-引用Block类的实例,从而可以访问与该类关联的方法和属性;

  • index—this keeps track of the position of the block within the blockchain;

    索引 —跟踪区块链在区块链中的位置;

  • proof_no—this is the number produced during the creation of a new block (called mining);

    proof_no-这是在创建新块(称为挖矿)期间产生的数量;

  • prev_hash—this refers to the hash of the previous block within the chain;

    prev_hash —指链中上一个块的哈希;

  • data—this gives a record of all transactions completed, such as the quantity bought;

    数据 -提供所有已完成交易的记录,例如购买数量;

  • timestamp—this places a timestamp for the transactions.

    时间戳记 -为事务放置时间戳记。

The second method in the class, calculate_hash, will generate the hash of the blocks using the above values. The SHA-256 module is imported into the project to assist in obtaining the hashes of the blocks.

类中的第二个方法calculate_hash将使用上述值生成块的哈希。 SHA-256模块被导入到项目中,以帮助获得块的哈希值。

After the values have been inputted into the cryptographic hash algorithm, the function will return a 256-bit string representing the contents of the block.

将值输入到密码哈希算法后,该函数将返回一个256位字符串,表示该块的内容。

This is how security is achieved in blockchains—every block will have a hash and that hash will rely on the hash of the previous block.

这就是在区块链中实现安全性的方式-每个区块都有一个哈希,而该哈希将依赖于前一个区块的哈希。

As such, if someone tries to compromise any block in the chain, the other blocks will have invalid hashes, leading to disruption of the entire blockchain network.

因此,如果有人试图破坏链中的任何区块,其他区块将具有无效的哈希值,从而导致整个区块链网络的破坏。

Ultimately, a block will look like this:

最终,一个块将如下所示:

{
    "index": 2,
    "proof": 21,
    "prev_hash": "6e27587e8a27d6fe376d4fd9b4edc96c8890346579e5cbf558252b24a8257823",
    "transactions": [
        {'sender': '0', 'recipient': 'Quincy Larson', 'quantity': 1}
    ],
    "timestamp": 1521646442.4096143
}

2.建立区块链类 (2. Building the Blockchain class)

The main idea of a blockchain, just as the name implies, involves “chaining” several blocks to one another.

顾名思义,区块链的主要思想涉及将多个区块相互“链接”。

Therefore, I’m going to construct a Blockchain class that will be useful in managing the workings of the whole chain. This is where most of the action is going to take place.

因此,我将构建一个对管理整个链的工作很有用的Blockchain类。 这是大多数动作将要发生的地方。

The Blockchain class will have various helper methods for completing various tasks in the blockchain.

Blockchain类将具有各种帮助程序方法,以完成区块链中的各种任务。

Let me explain the role of each of the methods in the class.

让我解释一下每个方法在类中的作用。

一个。 构造方法
(a. Constructor method)

This method ensures the blockchain is instantiated.

该方法确保区块链被实例化。

class BlockChain:

    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.construct_genesis()

Here are the roles of its attributes:

以下是其属性的作用:

  • self.chain—this variable keeps all blocks;

    self.chain-此变量保留所有块;

  • self.current_data—this variable keeps all the completed transactions in the block;

    self.current_data —此变量将所有已完成的事务保留在该块中;

  • self.construct_genesis()—this method will take care of constructing the initial block.

    self.construct_genesis() -此方法将负责构造初始块。

b。 构建创世块
(b. Constructing the genesis block)

The blockchain requires a construct_genesis method to build the initial block in the chain. In the blockchain convention, this block is special because it symbolizes the start of the blockchain.

区块链需要一个construct_genesis方法来构建链中的初始块。 在区块链惯例中,此块是特殊的,因为它象征着区块链的开始。

In this case, let’s construct it by simply passing some default values to the construct_block method.

在这种情况下,让我们通过简单地将一些默认值传递给Construct_block方法来构造它。

I gave both proof_no and prev_hash a value of zero, although you can provide any value you want.

尽管您可以提供所需的任何值,但我都给了proof_noprev_hash一个零值。

def construct_genesis(self):
    self.construct_block(proof_no=0, prev_hash=0)


def construct_block(self, proof_no, prev_hash):
    block = Block(
        index=len(self.chain),
        proof_no=proof_no,
        prev_hash=prev_hash,
        data=self.current_data)
    self.current_data = []

    self.chain.append(block)
    return block


C。 建造新的街区 (
c. Constructing new blocks)

The construct_block method is used for creating new blocks in the blockchain.

Construct_block方法用于在区块链中创建新块。

Here is what is taking place with the various attributes of this method:

这是此方法的各种属性所发生的情况:

  • index—this represents the length of the blockchain;

    索引 -代表区块链的长度;

  • proof_nor & prev_hash—the caller method passes them;

    proof_nor&prev_hash —调用者方法传递它们;

  • data—this contains a record of all the transactions that are not included in any block on the node;

    数据 -包含节点上任何块中未包含的所有事务的记录;

  • self.current_data—this is used to reset the transaction list on the node. If a block has been constructed and the transactions allocated to it, the list is reset to ensure that future transactions are added into this list. And, this process will take place continuously;

    self.current_data-用于重置节点上的事务列表。 如果已经构造了一个块并将事务分配给该块,则会重置该列表以确保将来的事务被添加到该列表中。 并且,该过程将连续进行;

  • self.chain.append()—this method joins newly constructed blocks to the chain;

    self.chain.append()-此方法将新构建的块连接到链;

  • return—lastly, a constructed block object is returned.

    return —最后, 返回一个构造的块对象。

    return—lastly, a constructed block object is returned.

    return-最后, 返回一个构造的块对象。

d。 检查有效性 (d. Checking validity)

The check_validity method is important in assessing the integrity of the blockchain and ensuring anomalies are absent.

check_validity方法对于评估区块链的完整性并确保不存在异常非常重要。

As mentioned earlier, hashes are essential for the security of the blockchain as even the slightest change in the object will lead to the generation of a completely new hash.

如前所述,散列对于区块链的安全至关重要,因为即使对象中的任何细微变化都将导致生成全新的哈希。

Therefore, this check_validity method uses if statements to check whether the hash of every block is correct.

因此,此check_validity方法使用if语句检查每个块的哈希是否正确。

It also verifies if every block points to the right previous block, through comparing the value of their hashes. If everything is correct, it returns true; otherwise, it returns false.

它还通过比较哈希值来验证每个块是否指向正确的前一个块。 如果一切正确,则返回true;否则,返回true。 否则,它返回false。

@staticmethod
def check_validity(block, prev_block):
    if prev_block.index + 1 != block.index:
        return False

    elif prev_block.calculate_hash != block.prev_hash:
        return False

    elif not BlockChain.verifying_proof(block.proof_no, prev_block.proof_no):
        return False

    elif block.timestamp <= prev_block.timestamp:
        return False

    return True

e。 添加交易数据 (e. Adding data of transactions)

The new_data method is used for adding the data of transactions to a block. It’s a very simple method: it accepts three parameters (sender’s details, receiver’s details, and quantity) and append the transaction data to self.current_data list.

new_data方法用于将事务数据添加到块中。 这是一个非常简单的方法:它接受三个参数(发送者的详细信息,接收者的详细信息和数量),并将交易数据附加到self.current_data列表中。

Anytime a new block is created, this list is allocated to that block and reset once more as explained in the construct_block method.

每当创建新块时,都会将该列表分配给该块,并再次按Construct_block方法中的说明进行重置。

Once the transaction data has been added to the list, the index of the next block to be created is returned.

将交易数据添加到列表后,将返回要创建的下一个块的索引。

This index is calculated by adding 1 to the index of the current block (which is the last in the blockchain). The data will assist a user in submitting the transaction in future.

该索引是通过将当前块的索引(即区块链中的最后一个)的索引加1来计算的。 数据将帮助用户将来提交交易。

def new_data(self, sender, recipient, quantity):
    self.current_data.append({
        'sender': sender,
        'recipient': recipient,
        'quantity': quantity
    })
    return True


F。 添加工作证明 (
f. Adding proof of work)

Proof of work is a concept that prevents the blockchain from abuse. Simply, its objective is to identify a number that solves a problem after a certain amount of computing work is done.

工作量证明是防止区块链滥用的概念。 简而言之,其目的是在完成一定数量的计算工作后,确定一个可以解决问题的编号。

If the difficulty level of identifying the number is high, it discourages spamming and tampering with the blockchain.

如果识别数字的难度很高,则不鼓励发送垃圾邮件和篡改区块链。

In this case, we’ll use a simple algorithm that discourages people from mining blocks or creating blocks easily.

在这种情况下,我们将使用一种简单的算法来阻止人们挖掘区块或轻松创建区块。

@staticmethod
def proof_of_work(last_proof):
    '''this simple algorithm identifies a number f' such that hash(ff') contain 4 leading zeroes
         f is the previous f'
         f' is the new proof
        '''
    proof_no = 0
    while BlockChain.verifying_proof(proof_no, last_proof) is False:
        proof_no += 1

    return proof_no


@staticmethod
def verifying_proof(last_proof, proof):
    #verifying the proof: does hash(last_proof, proof) contain 4 leading zeroes?

    guess = f'{last_proof}{proof}'.encode()
    guess_hash = hashlib.sha256(guess).hexdigest()
    return guess_hash[:4] == "0000"

G。 获取最后一块 (g. Getting the last block)

Lastly, the latest_block method is a helper method that assists in obtaining the last block in the blockchain. Remember that the last block is actually the current block in the chain.

最后, latest_block方法是一种帮助程序方法,可帮助获取区块链中的最后一个块。 请记住,最后一个块实际上是链中的当前块。

@property
    def latest_block(self):
        return self.chain[-1]

让我们总结一切 (Let’s sum everything together)

Here is the entire code for creating the fccCoin cryptocurrency.

这是用于创建fccCoin加密货币的完整代码。

You can also get the code on this GitHub repository.

您也可以在此GitHub存储库上获取代码。

import hashlib
import time


class Block:

    def __init__(self, index, proof_no, prev_hash, data, timestamp=None):
        self.index = index
        self.proof_no = proof_no
        self.prev_hash = prev_hash
        self.data = data
        self.timestamp = timestamp or time.time()

    @property
    def calculate_hash(self):
        block_of_string = "{}{}{}{}{}".format(self.index, self.proof_no,
                                              self.prev_hash, self.data,
                                              self.timestamp)

        return hashlib.sha256(block_of_string.encode()).hexdigest()

    def __repr__(self):
        return "{} - {} - {} - {} - {}".format(self.index, self.proof_no,
                                               self.prev_hash, self.data,
                                               self.timestamp)


class BlockChain:

    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.construct_genesis()

    def construct_genesis(self):
        self.construct_block(proof_no=0, prev_hash=0)

    def construct_block(self, proof_no, prev_hash):
        block = Block(
            index=len(self.chain),
            proof_no=proof_no,
            prev_hash=prev_hash,
            data=self.current_data)
        self.current_data = []

        self.chain.append(block)
        return block

    @staticmethod
    def check_validity(block, prev_block):
        if prev_block.index + 1 != block.index:
            return False

        elif prev_block.calculate_hash != block.prev_hash:
            return False

        elif not BlockChain.verifying_proof(block.proof_no,
                                            prev_block.proof_no):
            return False

        elif block.timestamp <= prev_block.timestamp:
            return False

        return True

    def new_data(self, sender, recipient, quantity):
        self.current_data.append({
            'sender': sender,
            'recipient': recipient,
            'quantity': quantity
        })
        return True

    @staticmethod
    def proof_of_work(last_proof):
        '''this simple algorithm identifies a number f' such that hash(ff') contain 4 leading zeroes
         f is the previous f'
         f' is the new proof
        '''
        proof_no = 0
        while BlockChain.verifying_proof(proof_no, last_proof) is False:
            proof_no += 1

        return proof_no

    @staticmethod
    def verifying_proof(last_proof, proof):
        #verifying the proof: does hash(last_proof, proof) contain 4 leading zeroes?

        guess = f'{last_proof}{proof}'.encode()
        guess_hash = hashlib.sha256(guess).hexdigest()
        return guess_hash[:4] == "0000"

    @property
    def latest_block(self):
        return self.chain[-1]

    def block_mining(self, details_miner):

        self.new_data(
            sender="0",  #it implies that this node has created a new block
            receiver=details_miner,
            quantity=
            1,  #creating a new block (or identifying the proof number) is awarded with 1
        )

        last_block = self.latest_block

        last_proof_no = last_block.proof_no
        proof_no = self.proof_of_work(last_proof_no)

        last_hash = last_block.calculate_hash
        block = self.construct_block(proof_no, last_hash)

        return vars(block)

    def create_node(self, address):
        self.nodes.add(address)
        return True

    @staticmethod
    def obtain_block_object(block_data):
        #obtains block object from the block data

        return Block(
            block_data['index'],
            block_data['proof_no'],
            block_data['prev_hash'],
            block_data['data'],
            timestamp=block_data['timestamp'])

Now, let’s test our code to see if it works.

现在,让我们测试我们的代码,看看它是否有效。

blockchain = BlockChain()

print("***Mining fccCoin about to start***")
print(blockchain.chain)

last_block = blockchain.latest_block
last_proof_no = last_block.proof_no
proof_no = blockchain.proof_of_work(last_proof_no)

blockchain.new_data(
    sender="0",  #it implies that this node has created a new block
    recipient="Quincy Larson",  #let's send Quincy some coins!
    quantity=
    1,  #creating a new block (or identifying the proof number) is awarded with 1
)

last_hash = last_block.calculate_hash
block = blockchain.construct_block(proof_no, last_hash)

print("***Mining fccCoin has been successful***")
print(blockchain.chain)

It worked!

有效!

Here is the output of the mining process:

这是挖掘过程的输出:

***Mining fccCoin about to start***
[0 - 0 - 0 - [] - 1566930640.2707076]
***Mining fccCoin has been successful***
[0 - 0 - 0 - [] - 1566930640.2707076, 1 - 88914 - a8d45cb77cddeac750a9439d629f394da442672e56edfe05827b5e41f4ba0138 - [{'sender': '0', 'recipient': 'Quincy Larson', 'quantity': 1}] - 1566930640.5363243]


结论 (
Conclusion)

There you have it!

你有它!

That’s how you could create your own blockchain using Python.

这就是使用Python创建自己的区块链的方式。

Let me say that this tutorial just demonstrates the basic concepts for getting your feet wet in the innovative blockchain technology.

让我说,本教程只是演示了在创新的区块链技术中弄湿自己的基本概念。

If this coin were deployed as-is, it could not meet the present market demands for a stable, secure, and easy-to-use cryptocurrency.

如果按原样部署此代币 ,它将无法满足当前市场对稳定,安全且易于使用的加密货币的需求。

Therefore, it can still be improved by adding additional features to enhance its capabilities for mining and sending financial transactions.

因此,仍可以通过添加其他功能来增强其挖掘和发送财务交易的功能来进行改进。

Nonetheless, it’s a good starting point if you decide to make your name known in the amazing world of cryptos.

尽管如此,如果您决定在惊人的加密货币世界中广为人知,这是一个很好的起点。

If you have any comments or questions, please post them below.

如果您有任何意见或疑问,请在下面发布。

Happy (crypto) coding!

快乐的(加密)编码!

翻译自: https://www.freecodecamp.org/news/create-cryptocurrency-using-python/

python使用md5加密

你可能感兴趣的:(算法,区块链,python,java,人工智能)