def insert(database, table, register): if saveModo_bandera is False: Block.activar_SaveModo(register) #print("validacion correcta") if searchInMode(database) != None: currentMode = searchInMode(database) if currentMode == 'avl': # avlList.append(tableNew) return avl.insert(database, table, register) elif currentMode == 'b': # bList.append(tableNew) return b.insert(database, table, register) elif currentMode == 'bplus': # bplusList.append(tableNew) return bplus.insert(database, table, register) elif currentMode == 'dict': # dictList.append(tableNew) return DM.insert(database, table, register) elif currentMode == 'isam': # isamList.append(tableNew) return isam.insert(database, table, register) elif currentMode == 'json': # jsonList.append(tableNew) return j.insert(database, table, register) elif currentMode == 'hash': # hashList.append(tableNew) return Hash.insert(database, table, register) else: return 2
def __init__(self, genesisBlock: Block = None, nodeID = None): self.id = nodeID self.miningNodeList = [] self.blockChain = BlockChain(genesisBlock) self.blockQueue = Queue() self.globalUnverifiedTxPool : List[Transaction] = [] self.alreadyMinedTx : List[Transaction] = [] self.miningDifficulty = 0x07FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
def do_POST(self): content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) nextBlock = bc.generateBlock(post_data) bc.addBlockToChain(nextBlock) BlockChain.blockChain = bc.blockChain self._set_headers() self.wfile.write(self.blockChainToString())
def setup_greyhash_se(our_node): node_list = [] node_list.append(our_node) if os.path.isfile("greychain.txt"): with open("greychain.txt") as json_file: data = json.load(json_file) blockchain = BlockChain.json_to_blockchain(data) else: blockchain = BlockChain.create() genesis_block = Block.create_genesis_block() blockchain.add_genesis_block(genesis_block) blockchain.save_chain("greychain.txt") return node_list, blockchain
def server_program(): blockchain = BlockChain.BlockChain() # get the hostname host = '127.0.0.1' port = 5000 # initiate port no above 1024 server_socket = socket.socket() # get instance # look closely. The bind() function takes tuple as argument server_socket.bind((host, port)) # bind host address and port together # configure how many client the server can listen simultaneously server_socket.listen(2) conn, address = server_socket.accept() # accept new connection while True: # receive data stream. it won't accept data packet greater than 1024 bytes data = recieveMessages(conn) if not data: break if(data[0] == 100): print("data recieved") blockchain.add_block(data[1]) conn.send(pickle.dumps([2000])) # send data to the client elif(data[0] == 200): print("Authentication") break conn.close() # close the connection
def create_identity(self, name, last_name, ID, birth_date, sex): self.my_identity = BlockChain.Identity(name, last_name, ID, birth_date, sex, self.my_key.public_pair()) self.my_identity.signature = self.sign(self.my_identity.get_hash()) if not os.path.exists("./Wallet"): f = io.open("./Wallet.dat", 'xb') else: f=f = io.open("./Wallet.dat", 'wb') pickle.dump(self, f) f.close()
def sendBoardcast(self): while True: try: data = bytes(input(""), 'utf-8') # if u type "exit" to console # It will terminate program if (len(data.split()) == 2): BlockChain.editBlock(blockchain, genesisBlock, int(data.split()[1])) if (data == "exit"): print("Close Server") os.kill(os.getpid(), 9) # sending msg to all client # for connection in self.connections: # connection.send(data) # catch error when press CTRL+C and Terminate program except EOFError as error: print("Close Server") os.kill(os.getpid(), 9)
def post_blockchain(self, data): self.lock.acquire() chain = BlockChain.json_to_blockchain(data) if chain is None or self.blockchain.replace_chain(chain): self.blockchain.save_chain("greychain.txt") self.lock.release() return b'{"Blockchain accepted": false}' self.lock.release() return b'{"Blockchain accepted": true}'
def download_blockchain(node_list, our_node): chain = BlockChain.create() for node in range(0, len(node_list)): try: if node_list[node].id == our_node.id: continue if node_list[node].protocol == "https": data = urllib.request.urlopen(node_list[node].protocol + "://" + node_list[node].ip + ":" + node_list[node].port + "/download", timeout=3, context=ssl._create_unverified_context()).read().decode('utf8') else: data = urllib.request.urlopen(node_list[node].protocol + "://" + node_list[node].ip + ":" + node_list[node].port + "/download", timeout=3).read().decode('utf8') data = json.loads(data) data = BlockChain.json_to_blockchain(data) if data is None: continue chain.replace_chain(data) return chain except: pass return None
def main(): usr1 = GenAddress.GenAddress() usr2 = GenAddress.GenAddress() usr3 = GenAddress.GenAddress() minor = GenAddress.GenAddress() blockChain = BlockChain.BlockChain() # usr1がトランザクションを生成 transaction = { 'sender_blockchain_address': usr1.address, 'recipient_blockchain_address': usr2.address, 'value': float(30) } signature = Transaction.VerifyTransaction().generate_signature( usr1.privkey, transaction) blockChain.add_transaction(transaction, signature, usr1.pubkey) # usr2がトランザクションを生成 transaction = { 'sender_blockchain_address': usr2.address, 'recipient_blockchain_address': usr3.address, 'value': float(10) } signature = Transaction.VerifyTransaction().generate_signature( usr2.privkey, transaction) blockChain.add_transaction(transaction, signature, usr2.pubkey) # usr3がトランザクションを生成 transaction = { 'sender_blockchain_address': usr3.address, 'recipient_blockchain_address': usr1.address, 'value': float(10) } signature = Transaction.VerifyTransaction().generate_signature( usr3.privkey, transaction) blockChain.add_transaction(transaction, signature, usr3.pubkey) # minorがトランザクションをblockに格納 if blockChain.mining(minor.address): pprint.pprint(blockChain.chain) else: print("マイニング失敗")
def handler(self, c, a): while True: try: data = c.recv(1024) # Catch error when client disconnected then remove that client connection except Exception as error: print(str(a[0]) + ':' + str(a[1]) + " disconnected") self.connections.remove(c) c.close() break #create new block data when msg recieved block = BlockChain.Block(data.decode('utf-8')) blockchain.mine(block) # Send new block data to all Clients for connection in self.connections: connection.send(bytes(str(block.data), 'utf-8')) # Disconnect client when they close program if not data: print(str(a[0]) + ':' + str(a[1]) + " disconnected") self.connections.remove(c) c.close() break
import hashlib import json import testdata import BlockChain # Main eth = BlockChain.BlockChain() eth.generate_genesis_block() eth.addblock(testdata.blocks[0]) eth.addblock(testdata.blocks[1]) eth.details() eth.hack(1, 'HACKED') eth.details() eth.check()
class Node: def __init__(self, genesisBlock: Block = None, nodeID = None): self.id = nodeID self.miningNodeList = [] self.blockChain = BlockChain(genesisBlock) self.blockQueue = Queue() self.globalUnverifiedTxPool : List[Transaction] = [] self.alreadyMinedTx : List[Transaction] = [] self.miningDifficulty = 0x07FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF def miningBlock(self, tx : Transaction): if self.verifyTranscation(tx): nonce = 0 blockPOW = str(self.miningDifficulty + 1) #TODO: Check if prev is the pow prevBlockNode = self.blockChain.last_block prevHashing = prevBlockNode.curBlockNode.hashing() txAndPrevBeforeHash = tx.toString() + prevHashing while int(blockPOW, 16) > self.miningDifficulty: blockInfo = txAndPrevBeforeHash + str(nonce) blockPOW = sha256(blockInfo.encode('utf-8')).hexdigest() nonce += 1 nonce -= 1 # add to the longest chain newBlock = Block(tx, prevHashing, nonce, blockPOW) newBlockLinkedNode = BlockLinkedNode(prevBlockNode, newBlock, prevBlockNode.height + 1) self.broadCastBlock(newBlock) txBroadcastList = self.addBlockToChain(newBlockLinkedNode) if txBroadcastList: self.__broadcastTx(txBroadcastList) def addBroadcastBlock(self): if self.blockQueue.empty(): return while not self.blockQueue.empty(): newBlock = self.blockQueue.get() if not self.__verifyBlockPOW(newBlock): logger.error("Verification Failed! Block POW not match for blocks from other node") continue if not self.verifyTranscation(newBlock.tx): # logger.error("Verification Failed! Transcation not valid for blocks from other node") continue for blockLinkedNode in self.blockChain.chain: if blockLinkedNode.hashing() == newBlock.prev: foundPrevBlock = blockLinkedNode break if not foundPrevBlock: logger.error("Verification Failed! Prev hash not match for blocks from other node") continue newBlockLinkedNode = BlockLinkedNode(foundPrevBlock, newBlock, foundPrevBlock.height + 1) self.blockChain.addBlock(newBlockLinkedNode) def __verifyBlockPOW(self, newBlock): blockInfo = newBlock.tx.toString() + newBlock.prev + str(newBlock.nonce) blockPOW = sha256(blockInfo.encode('utf-8')).hexdigest() if str(blockPOW) != newBlock.proofOfWork: logger.error("In Node " + str(self.id) + " :" + "POW does not match") return false return True def verifyTranscation(self, tx: Transaction) : # verify a Tx """ 1. Ensure the transaction is not already on the blockchain (included in an existing valid block) 2. Ensure the transaction is validly structured """ return self.verifyTxNotAlreadyOnBlockchain(tx) and self.verifyTxValidStruct(tx) def verifyTxNotAlreadyOnBlockchain(self, tx: Transaction): # Ensure the transaction is not already on the blockchain (included in an existing valid block) prevBlock = self.blockChain.last_block while prevBlock: if tx.txNumber == prevBlock.curBlockNode.tx.txNumber: logger.error("Verification Failed! Tx is already on the blockchain") return False prevBlock = prevBlock.prevBlockNode return True def verifyTxValidStruct(self, tx: Transaction): """ Ensure the transaction is validly structured """ TxNumHash = self.verifyTxNumberHash(tx) # number hash is correct TxInNum = self.verifyTxInputsNumber(tx) # each number in the input exists as a transaction already on the blockchain, each output in the input actually exists in the named transaction TxPKsig = self.verifyTxPubKeyAndSig(tx) # each output in the input has the same public key, and that key can verify the signature on this transaction TxDS = self.verifyTxDoubleSpend(tx) # that public key is the most recent recipient of that output (i.e. not a double-spend) TxIOSum = self.verifyTxInOutSum(tx) # the sum of the input and output values are equal return TxNumHash and TxInNum and TxPKsig and TxDS and TxIOSum def verifyTxNumberHash(self, tx: Transaction): # Ensure number hash is correct num_Hash = tx.txNumber now_Hash = tx.hashingTxNumber() if tx.txNumber != '' and now_Hash == num_Hash: return True else: logger.error("In Node " + str(self.id) + " :" + "Tx Verification Failed! Number hash is not correct") def verifyTxInputsNumber(self, tx: Transaction): # each number in the input exists as a transaction already on the blockchain # each output in the input actually exists in the named transaction validInput_count= 0 for Input in tx.inputList: num_Exist = False outputright = False prevBlock = self.blockChain.last_block while prevBlock: if Input.number == prevBlock.curBlockNode.tx.txNumber: # find that old transaction in the current block num_Exist = True for pBlockTxOutput in prevBlock.curBlockNode.tx.outputList: if Input.output.isEqual(pBlockTxOutput): # verify the output content outputright = True break break prevBlock = prevBlock.prevBlockNode if num_Exist and outputright: validInput_count += 1 if validInput_count == len(tx.inputList): return True else: logger.error("Node " + str(self.id) + " :" + "Tx Verification Failed! Inputs are not correct") def verifyTxPubKeyAndSig(self, tx: Transaction): # each output in the input has the same public key, and that key can be used to verify the signature of the transaction if not tx.inputList: return False sender_PublicKey: bytes = tx.inputList[0].output.pubkey for Input in tx.inputList: if Input.output.pubkey != sender_PublicKey: logger.error("In Node " + str(self.id) + " :" + "Tx Verification Failed! Input pubkey is not unique") return False verifyKey = VerifyKey(sender_PublicKey, HexEncoder) try: verifyKey.verify(tx.sig.encode('utf-8'), encoder=HexEncoder) return True except BadSignatureError: logger.error("In Node " + str(self.id) + " :" + "Tx Verification Failed! Signature verification failed") return False # return True def verifyTxDoubleSpend(self, tx:Transaction): # that public key is the most recent recipient of that output (i.e. not a double-spend) for Input in tx.inputList: prevBlock = self.blockChain.last_block while prevBlock: for pBlockTxInput in prevBlock.curBlockNode.tx.inputList: if Input.isEqual(pBlockTxInput): logger.error("In Node " + str(self.id) + " :" + "Tx Verification Failed! Double spend detected") return False prevBlock = prevBlock.prevBlockNode return True def verifyTxInOutSum(self, tx: Transaction) : # the sum of the input and output values are equal inSum, outSum = 0, 0 inSum = np.sum([x.output.value for x in tx.inputList]) outSum = np.sum([y.value for y in tx.outputList]) if not inSum == outSum: logger.error("In Node " + str(self.id) + " :" + "Tx Verification Failed! Tx Inputs val sum is not equal to outputs sum") return bool(inSum == outSum) def broadCastBlock(self, newBlock): for tempNode in self.miningNodeList: if tempNode != self: tempNode.blockQueue.put(newBlock) def addBlockToChain(self, newBlockLinkedNode : BlockLinkedNode): self.blockChain.addBlock(newBlockLinkedNode) def __broadcastTx(self, txBroadcastList): for tempNode in self.miningNodeList: if tempNode != self: for tx in txBroadcastList: tempNode.globalUnverifiedTxPool.append(tx) tempNode.alreadyMinedTx.remove(tx) def getJson(self): jsonOut = {"Blocks": []} for linkedBlockNode in self.blockChain.chain: jsonOut["Blocks"].append(linkedBlockNode.curBlockNode.getJson()) return json.dumps(jsonOut, indent=4, sort_keys=True, separators=(',', ':')) def writeToFile(self): nodeJson = self.getJson() with open("./nodeOutputs/Node" + str(self.id) + '.json', 'w', encoding='utf-8') as f: f.write(nodeJson)
import socket import sys import threading import BlockChain import json thechain = BlockChain.BlockChain() theq = [] def getfile(cmt): rqd = [] for i in range(2, len(thechain.chain)): dt = blk.data.split(' ## ') if cmt == int(dt[0]): rqd = dt break return rdq def addFile(cmt, nme, fsize, fcode, pf): data = cmt + ' ## ' + nme + ' ## ' + fsize + ' ## ' + fcode + ' ## ' + pf theq.append(data) port = 5000 host = 'localhost' cl = set() class tr(threading.Thread): def __init__(self, port, host, data):
import AES_Cyptography # Module for colorfull console from colorama import init init() from colorama import Fore, Back, Style ### Example of colorama ### # print(Fore.RED + 'some red text') # print(Back.GREEN + 'and with a green background') # print(Style.DIM + 'and in dim text') # print(Style.RESET_ALL) # print('back to normal now') # Run BlockChain blockchain = BlockChain.Blockchain() genesisBlock = blockchain.head #Random String for Generate Key and GroupId def randomString(stringLength=10): """Generate a random string of fixed length """ letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength)) # Server Class class Server: # port connection port = 0 # create socket for connection
def abrir_archivoImage(): Block.abrir()
def modificarBloque(indice, registro): Block.modificar_cadena(indice,registro)
import BlockChain import Block blockchain = BlockChain() print("***Mining ElmoCoin 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", #implies new block recipient="Elmo", quantity=1, #new block ) last_hash = last_block.calculate_hash block = blockchain.construct_block(proof_no, last_hash) print("***Mining ElmoCoin has been successful***") print(blockchain.chain)
run_date=dd, kwargs={ 'scheduler': scheduler, 'blockchain': blockchain }) if (slot < 5): blockchain.forge_new_block() else: blockchain.new_genesis_block() stakeholder = Stakeholder.Stakeholder(wallet1['public_key'], "http://127.0.0.1:" + str(5000) + "/", wallet1['wallet_address']) blockchain = BlockChain.BlockChain(True, stakeholder, wallet1['private_key']) print(blockchain.get_current_slot()) print(blockchain.get_current_epoch()) time.sleep(6) print(blockchain.get_current_slot()) print(blockchain.get_current_epoch()) """ wallet2 = BlockChain.BlockChain.generate_new_wallet() wallet3 = BlockChain.BlockChain.generate_new_wallet() blockchain.register_new_node(wallet3['public_key'], "http://127.0.0.1:5001", wallet3['wallet_address']) transaction = { "sender_address": wallet1['wallet_address'],
# 程序从这里执行 import Message import Block import BlockChain print("game start") m1 = Message.MoneyMessage("yincheng pay baidu 100a") m2 = Message.MoneyMessage("yincheng pay baidu 1000b") m3 = Message.MoneyMessage("yincheng pay baidu 10000c") yin1 = Block.MoneyBlock(m1, m2, m3) # 一次加入三条记录 yin1.seal() # 数据密封 # yin1.moneymessage[0]=m3 #纂改 m4 = Message.MoneyMessage("yincheng pay baidu 100ab") m5 = Message.MoneyMessage("yincheng pay baidu 1000bc") m6 = Message.MoneyMessage("yincheng pay baidu 10000cd") yin2 = Block.MoneyBlock(m4, m5, m6) # 一次加入三条记录 yin2.seal() # 数据密封 m7 = Message.MoneyMessage("yincheng pay baidu 100abc") m8 = Message.MoneyMessage("yincheng pay baidu 1000bcd") m9 = Message.MoneyMessage("yincheng pay baidu 10000cde") yin3 = Block.MoneyBlock(m7, m8, m9) yin3.seal() # 数据密封 mydada = BlockChain.DaDaMoneyBlockChain() mydada.add_block(yin1) mydada.add_block(yin2) mydada.add_block(yin3) mydada.validate()
#/usr/bin/python3 import BlockChain import Block import Miner from datetime import datetime print("Hello world") b = BlockChain.BlockChain() m = Miner.Miner(b) print(b.lastBlock) m.mineNewBlock({ "123fdssd3": "1dfds32fds", "amount": 0.00231 }) m.mineNewBlock({ "b23fdssd3": "1dfds32fds", "amount": 0.00231 }) m.mineNewBlock({ "a3fdssd3": "1dfds32fds", "amount": 0.00231 }) m.mineNewBlock({ "fdssd3": "1dfds32fds", "amount": 0.00431 }) m.mineNewBlock({ "c23fdssd3": "1dfds32fds", "amount": 0.01231 }) m.mineNewBlock({
if os.path.isfile("./seed2.txt"): seed2 = Key.load_seed("./seed2.txt") else: seed2 = Key.create_seed() Key.save_seed(seed2, "./seed2.txt") priv, pub = Key.create("change_me", seed) priv2, pub2 = Key.create("change_me2", seed2) tt = str(time.time()) for x in range(0, 5): data = download_chain() if debug: print ("Data from download:") print (data) blockchain = BlockChain.json_to_blockchain(data) if x == 1 or x == 3: data = send_false_transaction() if debug: print ("Data from post_transaction:") print (data) else: data = send_transaction() if debug: print ("Data from post_transaction:") print (data) time.sleep(0.5)
import os, pickle, io, BlockChain, FunctionNetwork, Authorization, sys, signal import threading from time import sleep import Wallet trusted_parties = [("10.6.123.65", FunctionNetwork.PORT), ("10.6.123.65", FunctionNetwork.PORT - 1), ("10.6.123.65", FunctionNetwork.PORT - 2)] ip = "10.6.123.65" port = FunctionNetwork.PORT kill = False bc = BlockChain.BlockChain("./BlockChain.sqlite3") trie = bc.trie addrSeed = ("10.6.123.65", FunctionNetwork.PORT) if os.path.exists("./netData") == False: file_net = io.open("./netData", 'xb') seed = 1 full = 0 print("desea ser un full node s/n: ") s = input() if s == "s": full = 1 elif s == "n": full = 0 else: print("\n argumento incorrecto") exit(0) net = FunctionNetwork.node(bc,
import json app = Flask(__name__) from BlockChain import * from Transaction import * from Network import * from Node import * from Nodes import * n0 = Node("0.0.0.0", 1337, str(uuid4()).replace('-', '')) n1 = Node("0.0.0.0", 1338, str(uuid4()).replace('-', '')) nodes = Nodes([n0, n1]) blockchain = BlockChain() blockchain.chain.append(blockchain.genesis()) # add into db # share to other nodes walletAlice = Wallet(blockchain, "Alice") walletBob = Wallet(blockchain, "Bob") @app.route('/valid', methods=['GET']) def valid(): return jsonify(blockchain.is_valid()) @app.route('/minerate', methods=['POST']) def minerate():
import FunctionNetwork as Net import BlockChain import Wallet from pycoin import merkle bc = BlockChain.BlockChain() #bc.add_block(BlockChain.Block("0",1,0,0)) w = Wallet.Wallet() w.create_identity("ale", "nardo", "95042429425", "24/4/1995", "m") b = BlockChain.Block("0", merkle.merkle([w.my_identity.get_hash()]), "0", "0") b.set_identities([w.my_identity]) bc.add_block(b) bc.add_block(BlockChain.Block(bc.tip.get_hash(), 1, 0, 0)) a = Net.node(blockChain=bc, ip="127.0.0.1", port=Net.PORT, is_seed=1)
from BlockChain import * if __name__ == '__main__': bc = BlockChain(INITIAL_BITS) print('generating genesis block ...') bc.create_genesis() for i in range(30): print('generating {}th block ...'.format(i + 2)) # genesis + 1-origin bc.add_new_block(i)
"private_key": private_key1, "public_key": public_key1, "address": "http://127.0.0.1:" + str(5001) + "/" } private_key2, public_key2 = EcdsaSigning.generate_keys() account3 = { "private_key": private_key2, "public_key": public_key2, "address": "http://127.0.0.1:" + str(5002) + "/" } stakeholder = Stakeholder.Stakeholder(account['public_key'], account['address']) block_chain = BlockChain.BlockChain(True, stakeholder, account['private_key']) values = { 'receiver_public_key': account2['public_key'], 'amount': 10000, 'sender_public_key': account['public_key'], 'sender_private_key': account['private_key'] } values1 = { 'receiver_public_key': account3['public_key'], 'amount': 10000, 'sender_public_key': account['public_key'], 'sender_private_key': account['private_key'] }
from BlockChain import * # 创建一个区块链 bc = BlockChain() # 添加区块 bc.add_block(data='second block') bc.add_block(data='third block') bc.add_block(data='fourth block') for bl in bc.blocks: print("Index:{}".format(bl.index)) print("Nonce:{}".format(bl.nonce)) print("Hash:{}".format(bl.hash)) print("Pre_Hash:{}".format(bl.previous_hash)) print("Time:{}".format(bl.time_stamp)) print("Data:{}".format(bl.data)) print('\n')
def setUp(self) -> None: self.chain = bc._BlockChain()