python能搞区块链吗?

python能搞区块链吗


MM们
浏览 759回答 1
1回答

森林海

当然可以1 import hashlib as hasher2 import datetime as date34 # Define what a Snakecoin block is5 class Block:6 def __init__(self, index, timestamp, data, previous_hash):7 self.index = index8 self.timestamp = timestamp9 self.data = data10 self.previous_hash = previous_hash11 self.hash = self.hash_block()1213 def hash_block(self):14 sha = hasher.sha256()15 sha.update(str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash))16 return sha.hexdigest()1718 # Generate genesis block19 def create_genesis_block():20 # Manually construct a block with21 # index zero and arbitrary previous hash22 return Block(0, date.datetime.now(), "Genesis Block", "0")2324 # Generate all later blocks in the blockchain25 def next_block(last_block):26 this_index = last_block.index + 127 this_timestamp = date.datetime.now()28 this_data = "Hey! I'm block " + str(this_index)29 this_hash = last_block.hash30 return Block(this_index, this_timestamp, this_data, this_hash)3132 # Create the blockchain and add the genesis block33 blockchain = [create_genesis_block()]34 previous_block = blockchain[0]3536 # How many blocks should we add to the chain37 # after the genesis block38 num_of_blocks_to_add = 203940 # Add blocks to the chain41 for i in range(0, num_of_blocks_to_add):42 block_to_add = next_block(previous_block)43 blockchain.append(block_to_add)44 previous_block = block_to_add45 # Tell everyone about it!46 print "Block #{} has been added to the blockchain!".format(block_to_add.index)47 print "Hash: {}\n".format(block_to_add.hash)
打开App,查看更多内容
随时随地看视频慕课网APP