Sådan oprettes din egen kryptovaluta ved hjælp af Python

Med den nuværende stigning i kryptokurver skaber blockchain en brummer i teknologiverden. Denne teknologi har tiltrukket så meget opmærksomhed primært på grund af dens evne til at garantere sikkerhed, håndhæve decentralisering og hurtigere processer til flere industrier - især til den finansielle industri.

I det væsentlige er en blockchain en offentlig database, der irreversibelt dokumenterer og godkender besiddelse og transmission af digitale aktiver. Digitale valutaer, som Bitcoin og Ethereum, er baseret på dette koncept. Blockchain er en spændende teknologi, som du kan bruge til at transformere funktionerne i dine applikationer.

For sent har vi set regeringer, organisationer og enkeltpersoner, der bruger blockchain-teknologien til at oprette deres egne kryptokurver - og undgå at blive efterladt. Især da Facebook foreslog sin egen kryptokurrency, kaldet Libra, rørte bekendtgørelsen mange farvande over hele verden.

Hvad hvis du også kunne følge trop og oprette din egen version af en kryptovaluta?

Jeg tænkte på dette og besluttede at udvikle en algoritme, der opretter en krypto.

Jeg besluttede at kalde kryptokurrency fccCoin .

I denne vejledning skal jeg illustrere den trinvise proces, jeg brugte til at opbygge den digitale valuta (jeg brugte de objektorienterede begreber i Python-programmeringssprog).

Her er den grundlæggende plan for blockchain-algoritmen til oprettelse af 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] 

Lad mig nu forklare, hvad der foregår ...

1. Opbygning af den første blokklasse

En blockchain består af flere blokke, der er forbundet med hinanden (det lyder velkendt, ikke?).

Kædingen af ​​blokke finder sted således, at hvis en blok manipuleres med, bliver resten af ​​kæden ugyldig.

Ved anvendelse af ovenstående koncept oprettede jeg følgende indledende blokklasse:

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) 

Som du kan se fra koden ovenfor, definerede jeg __init __ () -funktionen, som udføres, når Block- klassen startes, ligesom i enhver anden Python-klasse.

Jeg leverede følgende parametre til startfunktionen:

  • selv - dette refererer til forekomsten af Block- klassen, hvilket gør det muligt at få adgang til de metoder og attributter, der er knyttet til klassen;
  • indeks — dette holder styr på placeringen af ​​blokken inden for blockchain;
  • proof_no — dette er antallet produceret under oprettelsen af ​​en ny blok (kaldet minedrift);
  • prev_hash — dette refererer til hash af den forrige blok inden i kæden;
  • data — dette giver en oversigt over alle gennemførte transaktioner, såsom den købte mængde;
  • tidsstempel - dette placerer et tidsstempel for transaktionerne.

Den anden metode i klassen, beregner_hash , genererer hash af blokkene ved hjælp af ovenstående værdier. SHA-256-modulet importeres til projektet for at hjælpe med at opnå blokeringernes hash.

Når værdierne er blevet indsat i den kryptografiske hashalgoritme, returnerer funktionen en 256-bit streng, der repræsenterer indholdet af blokken.

Sådan opnås sikkerhed i blokkæder - hver blok har en hash, og den hash vil stole på hashen fra den forrige blok.

Som sådan, hvis nogen forsøger at kompromittere en blok i kæden, vil de andre blokke have ugyldige hashes, hvilket fører til forstyrrelse af hele blockchain-netværket.

I sidste ende vil en blok se sådan ud:

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

2. Opbygning af Blockchain-klassen

Hovedideen med en blockchain, ligesom navnet antyder, indebærer at "kæde" flere blokke til hinanden.

Derfor vil jeg konstruere en Blockchain- klasse, der vil være nyttig til styring af hele kæden. Det er her, det meste af handlingen skal finde sted.

Den Blockchain klasse vil have forskellige helper metoder til at fuldføre forskellige opgaver i blockchain.

Lad mig forklare rollen for hver af metoderne i klassen.

en. Konstruktormetode

Denne metode sikrer, at blockchain er instantieret.

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

Her er rollerne for dets attributter:

  • self.chain — denne variabel holder alle blokke;
  • self.current_data — denne variabel holder alle de gennemførte transaktioner i blokken;
  • self.construct_genesis () - denne metode tager sig af konstruktionen af ​​den oprindelige blok.

b. Konstruktion af oprindelsesblokken

Blockchain kræver en construct_genesis- metode til at opbygge den indledende blok i kæden. I blockchain-konventionen er denne blok speciel, fordi den symboliserer starten på blockchain.

Lad os i dette tilfælde konstruere det ved blot at overføre nogle standardværdier til construct_block- metoden.

Jeg gav både proof_no og prev_hash en værdi på nul, selvom du kan give den ønskede værdi.

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. Konstruktion af nye blokke

Metoden construct_block bruges til at oprette nye blokke i blockchain.

Her er hvad der finder sted med de forskellige egenskaber ved denne metode:

  • indeks — dette repræsenterer længden af ​​blockchain;
  • proof_nor & prev_hashopkaldsmetoden passerer dem;
  • data — dette indeholder en registrering af alle de transaktioner, der ikke er inkluderet i nogen blok på noden;
  • 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.chain.append()—this method joins newly constructed blocks to the chain;
  • return—lastly, a constructed block object is returned.

d. Checking validity

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

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_validitymethod uses if statements to check whether the hash of every block is correct.

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.

@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. 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.

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

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.

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

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. Getting the last block

Lastly, the latest_blockmethod 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.

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

Let’s sum everything together

Here is the entire code for creating the fccCoin cryptocurrency.

You can also get the code on this GitHub repository.

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.

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

Hvis denne mønt blev brugt som den er, kunne den ikke imødekomme de nuværende markedskrav om en stabil, sikker og brugervenlig kryptovaluta.

Derfor kan det stadig forbedres ved at tilføje yderligere funktioner for at forbedre dets muligheder for minedrift og afsendelse af finansielle transaktioner.

Ikke desto mindre er det et godt udgangspunkt, hvis du beslutter at gøre dit navn kendt i den fantastiske verden af ​​kryptoer.

Hvis du har kommentarer eller spørgsmål, bedes du sende dem nedenfor.

Glad (krypto) kodning!