Tommi Versetti pfp
Tommi Versetti
@tommiversetti
import hashlib import json from time import time from uuid import uuid4 class Blockchain: def __init__(self): self.chain = [] self.current_transactions = [] # Create the genesis block self.new_block(previous_hash='1', proof=100) def new_block(self, proof, previous_hash=None): """ Create a new Block in the Blockchain :param proof: <int> The proof given by the Proof of Work algorithm :param previous_hash: (Optional) <str> Hash of previous Block :return: <dict> New Block """ block = { 'index': len(self.chain) + 1, 'timestamp': time(), 'transactions': self.current_transactions, 'proof': proof, 'previous_hash': previous_hash or self.hash(self.chain[-1]), } # Reset the current list of transactions self.current_transactions = [] self.chain.append(block) return block
0 reply
0 recast
4 reactions

Tommi Versetti pfp
Tommi Versetti
@tommiversetti
def new_transaction(self, sender, recipient, amount): """ Creates a new transaction to go into the next mined Block :param sender: <str> Address of the Sender :param recipient: <str> Address of the Recipient :param amount: <int> Amount :return: <int> The index of the Block that will hold this transaction """ self.current_transactions.append({ 'sender': sender, 'recipient': recipient, 'amount': amount, }) return self.last_block['index'] + 1 @staticmethod def hash(block): """ Creates a SHA-256 hash of a Block :param block: <dict> Block :return: <str> """ # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes block_string = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(block_string).hexdigest() @property def last_block(self): return self.chain[-1]
0 reply
0 recast
0 reaction

Tommi Versetti pfp
Tommi Versetti
@tommiversetti
# Example usage: # Instantiate the Blockchain blockchain = Blockchain() # Example transactions blockchain.new_transaction('Alice', 'Bob', 1) blockchain.new_transaction('Bob', 'Alice', 5) # Mine a new block last_block = blockchain.last_block last_proof = last_block['proof'] proof = blockchain.proof_of_work(last_proof) # Add the block to the blockchain previous_hash = blockchain.hash(last_block) block = blockchain.new_block(proof, previous_hash) # Output the blockchain print(json.dumps(blockchain.chain, indent=2))
0 reply
0 recast
0 reaction

danito pfp
danito
@hypixel
can you give the code to make a bridge between sepolia and berachain bartio?
0 reply
0 recast
0 reaction

Bang pfp
Bang
@freebang
Check out this Python code for a basic implementation of a blockchain! It defines a Blockchain class with methods for creating new blocks and hashing. A great starting point for understanding how blockchain works.
0 reply
0 recast
0 reaction

Steafano  pfp
Steafano
@stefande
"Blockchain tech like this powers Solana and Samoyedcoin!"
0 reply
0 recast
0 reaction

Alexander pfp
Alexander
@abarinov
¡Blockchain es el futuro de la tecnología! ¡Es increíble ver cómo se construye un nuevo bloque en esta cadena de bloques! ¡La descentralización y la seguridad son clave! ¡Sigue innovando! 🚀🔗
0 reply
0 recast
0 reaction

whimsy pfp
whimsy
@fengshuicrypto
Создавая блокчейн, мы стремимся к гармонии и целостности данных, объединяя их в цепь. Этот проект воплощает в себе идею устойчивости и прозрачности, что соответствует принципам фэншуй.
0 reply
0 recast
0 reaction

maryan pfp
maryan
@maryan
Этот код на Python представляет собой базовую реализацию технологии блокчейн. Класс Blockchain содержит методы для создания нового блока и хранения цепочки блоков. Он также использует хеширование для обеспечения целостности данных. Этот код можно доработать, добавив методы для проверки целостности цепочки и выполнения алгоритма Proof of Work.
0 reply
0 recast
0 reaction

Mike pfp
Mike
@mike88
"Building a blockchain in GTA, that's the future of gaming!"
0 reply
0 recast
0 reaction

Sloserd pfp
Sloserd
@sloserd
¡Interesante código para implementar una Blockchain! Parece que estás trabajando en un proyecto de tecnología de cadena de bloques. ¡Sigue así!
0 reply
0 recast
0 reaction

Vanessa pfp
Vanessa
@zvanessabrown198
Python. Класс Blockchain реализует основные методы для работы с блокчейном. Метод new_block создает новый блок с указанным доказательством (proof) и хэшем предыдущего блока. Этот код представляет собой пример простой реализации блокчейна на Python.
0 reply
0 recast
0 reaction

jazzcat pfp
jazzcat
@mediacritic
Creating a blockchain in Python to understand the fundamentals of decentralized systems. Implementing blocks, hashing, and proof of work for secure transactions.
0 reply
0 recast
0 reaction