Skip to content

Blockchain network integration #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 43 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
1a91e21
fix(genesis_block): transactions as array
Nov 2, 2019
a78b8e4
add(base ihm)
Nov 2, 2019
e8e52aa
fix(blockchain): check if transaction signature valid and stock valid
mxmaxime Nov 5, 2019
10c5912
Merge branch 'master' into blockchain_network_integration
mxmaxime Nov 5, 2019
c02f0b9
feat(network_integration): send real things.
mxmaxime Nov 5, 2019
060902f
Change Messages
mxmaxime Nov 5, 2019
66d9a30
feat(blockchain): initialize blockchain when a new node connect
Nov 5, 2019
ec19064
add ask chain when we are connected
soso0084 Nov 5, 2019
36007b5
wip fix init bc
mxmaxime Nov 5, 2019
6d0a84e
up size of buffer
soso0084 Nov 5, 2019
1007821
same
soso0084 Nov 5, 2019
7714692
wip debug
mxmaxime Nov 5, 2019
14dd356
feat(integration of mine)
mxmaxime Nov 5, 2019
bcd0f45
fix ask chain
soso0084 Nov 5, 2019
cc1e51d
same
soso0084 Nov 5, 2019
ff09174
wip debug block broadcast
mxmaxime Nov 5, 2019
010fdde
wip debug
mxmaxime Nov 5, 2019
9753b12
wip tests(blockchain): genesis block
mxmaxime Nov 5, 2019
1291aad
Merge branch 'master' into blockchain_network_integration
mxmaxime Nov 5, 2019
1ad5d99
Auto stash before merge of "blockchain_network_integration" and "orig…
soso0084 Nov 5, 2019
7ed84d8
fix(blockchain): broadcast block
mxmaxime Nov 5, 2019
0830b5c
Merge remote-tracking branch 'origin/blockchain_network_integration' …
mxmaxime Nov 5, 2019
344cefb
wip debug
mxmaxime Nov 5, 2019
0c273e0
fix(blockchain): handle block that I already have
mxmaxime Nov 6, 2019
5596dbd
fix prev commit
mxmaxime Nov 6, 2019
4a6fa71
add two other node to ping when we are online
soso0084 Nov 6, 2019
cdbb5ca
Auto stash before merge of "blockchain_network_integration" and "orig…
Nov 6, 2019
bece209
Merge branch 'master' into ihm
Nov 6, 2019
87fba19
fix(test): blockchain
Nov 6, 2019
e899f6e
Merge branch 'ihm' into blockchain_network_integration
Nov 6, 2019
abd46ac
ihm
Nov 6, 2019
a723a9f
add IP in list
soso0084 Nov 6, 2019
a7c8940
Merge remote-tracking branch 'origin/blockchain_network_integration' …
soso0084 Nov 6, 2019
5cee766
delete some line
soso0084 Nov 6, 2019
ca9c241
wip app
Nov 6, 2019
215769e
Merge remote-tracking branch 'origin/blockchain_network_integration' …
Nov 6, 2019
457bb06
same
soso0084 Nov 6, 2019
cd1b61a
Merge remote-tracking branch 'origin/blockchain_network_integration' …
Nov 6, 2019
bd529cf
wip network
Nov 6, 2019
1fc5116
fix network
Nov 6, 2019
3993fa1
wip ihm
Nov 6, 2019
c953a27
same
soso0084 Nov 6, 2019
24c035e
imgs
Lonaeri Nov 6, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import time
from flask import Flask, render_template
from network_integration import run

app = Flask(__name__)

"""
- List transactions that are currently not in a block.
- List blocks

"""


@app.route('/')
def accueil():
my_blockchain, network = run()

chain = my_blockchain.chain
current_transactions = my_blockchain.current_transactions
return render_template('index.html', chain=chain, current_transactions=current_transactions)


if __name__ == '__main__':
app.run(port=3333, debug=True)
4 changes: 3 additions & 1 deletion block.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,11 @@ def proof_of_work(last_block):

@staticmethod
def valid_block(block_to_validate, previous_block):
print('validating', block_to_validate.index, 'with prev_block', previous_block.index)
previous_block_hash = Block.hash(previous_block)

if block_to_validate.previous_hash != previous_block_hash:
print('block_to_validate.previous_hash != previous_block_hash')
print('block_to_validate.previous_hash != previous_block_hash', block_to_validate.previous_hash, '!=', previous_block_hash)
return False

# Check that the Proof of Work is correct
Expand All @@ -84,6 +85,7 @@ def valid_block(block_to_validate, previous_block):
block_to_validate.nonce, ' prev_nonce=', previous_block.nonce)
return False

print('Block valid')
return True

def check_sender_stock(self, tx, nb):
Expand Down
76 changes: 56 additions & 20 deletions blockchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def chain_for_network(self):
return jsonpickle.encode(self.chain)

def check_sender_stock(self, tx):
#check sur le block en cours
# check sur le block en cours
i = 1
nb = 0
while 1 > nb and i <= len(self.current_transactions):
Expand All @@ -74,8 +74,8 @@ def check_sender_stock(self, tx):
nb = nb + 1
i = i + 1

#check sur les anciens blocs
if len(self.chain) >= 1 :
# check sur les anciens blocs
if len(self.chain) >= 1:
current_block = self.last_block
i = current_block.index
while 1 > nb and i >= 0:
Expand All @@ -94,9 +94,9 @@ def submit_transaction(self, transaction):
# from the network, is a str that contains a json.
if isinstance(transaction, str):
transaction = jsonpickle.decode(transaction)
print('I received a new Transaction', transaction)
print('I received a new Transaction', transaction, transaction.time)
else:
print("I'm sending a new Transaction", transaction)
print("I'm sending a new Transaction", transaction, transaction.time)

if transaction in self.current_transactions:
print('I received an transaction, but I already know it, so I ignore it.')
Expand All @@ -106,18 +106,26 @@ def submit_transaction(self, transaction):
raise ValueError(
'transaction parameter should be a Transaction instance.')

transaction_verification = transaction.verify_signature() and self.check_sender_stock(transaction)
is_signature_valid = transaction.verify_signature()
is_stock_valid = self.check_sender_stock(transaction)

if transaction_verification:
print("Transaction signature is valid")
if not is_signature_valid:
print("Transaction signature is invalid")

if not is_stock_valid:
print("Transaction is impossible because stock invalid")

if is_stock_valid and is_signature_valid:
self.current_transactions.append(transaction)
self.network.broadcast_transaction(jsonpickle.encode(transaction))

# Should I mine?
# if len(self.current_transactions) == NB_TRANSACTIONS_MAX:
# self.mine()
if len(self.current_transactions) == NB_TRANSACTIONS_MAX:
self.mine()

return len(self.chain)

print("Transaction signature is invalid")
print("Transaction is invalid")
return False

def create_block(self, nonce, previous_hash):
Expand All @@ -129,26 +137,30 @@ def create_block(self, nonce, previous_hash):
"""

# Why we have this OR condition? Seems useless.
block = Block(nonce, self.current_transactions, len(self.chain),
previous_hash or Block.hash(self.chain[-1]))
block = Block(nonce, self.current_transactions, len(self.chain),
previous_hash or Block.hash(self.chain[-1]))

# Reset the current list of transactions
self.current_transactions = []

self.chain.append(block)
self.network.broadcast_block(jsonpickle.encode(block))
self.submit_block(block)

return block

def submit_block(self, block):
print('handling block: ', block)

if isinstance(block, str):
block = jsonpickle.decode(block)
print("I received a new Block", block, "prev hash:", block.previous_hash)

if not isinstance(block, Block):
raise ValueError('block should be an instance of Block')

# If I already have the block, I ignore the received one.
if block.index == self.last_block.index:
print("I received a block, but I already have it, so I ignore it.")
return False

"""
Add a Block in the Blockchain if the Block signature is valid.
"""
Expand All @@ -159,6 +171,12 @@ def submit_block(self, block):

self.chain.append(block)

# Idk If I have to do this, but... :)
self.current_transactions = []

print("I'm sending a block", block)
self.network.broadcast_block(jsonpickle.encode(block))

return True

def valid_chain(self, chain):
Expand All @@ -168,8 +186,6 @@ def valid_chain(self, chain):
:return: True if valid, False if not
"""

chain = jsonpickle.decode(chain)

previous_block = chain[0]

current_index = 1
Expand All @@ -187,6 +203,24 @@ def valid_chain(self, chain):

return True

def initialize_chain(self, chain_from_network):
"""
When I'm a new Node on the Network, I have to initialize my chain.
To do this, I ask the network the chain and initialize mine with this chain.
We should to something like a concensus (the largest chain win), but it's not done yet.
"""
chain = jsonpickle.decode(chain_from_network)

# I keep my chain because its larger.
if len(chain) < len(self.chain):
False

if self.valid_chain(chain):
print("Initialize chain: I'm taking the chain:", chain)
self.chain = chain
else:
print('Intialize chain impossible because the chain is not valid.')

def mine(self):
"""
Take the last Block, mine it and add it to the Blockchain.
Expand All @@ -212,9 +246,11 @@ def mine(self):
response = {
'message': "New Block Forged",
'index': block.index,
'transactions': block.transactions,
# 'transactions': block.transactions,
'nonce': block.nonce,
'previous_hash': block.previous_hash,
# 'previous_hash': block.previous_hash,
}

print(response)

return response
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
File renamed without changes
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
32 changes: 18 additions & 14 deletions network/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,18 @@

class Network:

def __init__(self):
self.node = Node("192.168.1.82", True)
self.nodes = []
def __init__(self, test=False):
self.blockchain = None

# Thread management
self._running = True
self.t1 = threading.Thread(target=self.receiv)
self.t1.start()
self._broadcast_ping()
if test == False:
self.node = Node("192.168.43.183", True)

self.nodes = [Node("192.168.43.59"), Node("192.168.43.161"), Node("192.168.43.32")]
# Thread management
self._running = True
self.t1 = threading.Thread(target=self.receiv)
self.t1.start()
self._broadcast_ping()

def stop(self):
self._running = False
Expand All @@ -35,24 +37,25 @@ def broadcast_ask_chain(self): # Done
for nodeList in self.nodes:
self.node.send("-c ", nodeList, "")

def _broadcast_ping(self): #Not use
nodeBroadcast = Node("192.168.1.62")
def _broadcast_ping(self): # Done
myNodeToSend = jsonpickle.encode(self.node)
self.node.send("-p ", nodeBroadcast, myNodeToSend)
for nodeList in self.nodes:
self.node.send("-p ", nodeList, myNodeToSend)

def receiv(self):
print("ready to receiv")

while self._running is True:
data, addr = self.node.my_socket.recvfrom(4096)
data, addr = self.node.my_socket.recvfrom(65536)

cureNode = addr

myData = data.decode()

if myData[:3] == "-c ": # Done
# Retourne le JSON de la chaine
self.node.send("-ac", cureNode, self.blockchain.chain_for_network)
self.node.send("-ac", cureNode,
self.blockchain.chain_for_network)

elif myData[:3] == "-n ": # Done
print("I received a Node")
Expand Down Expand Up @@ -89,7 +92,7 @@ def receiv(self):
notFind = False

elif myData[:3] == "-ac": # En suspend
some = None
self.blockchain.initialize_chain(myData[3:len(myData)])

elif myData[:3] == "-ap": # Done
nodeReceiv = jsonpickle.decode(myData[3:len(myData)])
Expand All @@ -103,5 +106,6 @@ def receiv(self):

if notFind:
print("Connecting to a new Node: ", nodeReceiv.host)
self.node.send("-c ", Node(addr[0]), "")
self.nodes.append(nodeReceiv)
notFind = False
37 changes: 26 additions & 11 deletions network_integration.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,36 @@
from blockchain_factory import blockchain_factory
from wallet import Wallet
from transaction import Transaction
from init_transactions import hashImg
import time


bc, network = blockchain_factory()
def run():
appleHash = hashImg('./items/apple.png')

time.sleep(5)
bc, network = blockchain_factory()

wallet = Wallet()
wallet2 = Wallet(1024, True)
transaction = Transaction(wallet.address, wallet2.address, "bonjour")
transaction2 = Transaction(wallet.address, wallet2.address, "bonjour2")
transaction3 = Transaction(wallet.address, wallet2.address, "bonjour3")
time.sleep(5)

transaction.sign(wallet)
wallet = Wallet(testDatas=True)
wallet2 = Wallet(testDatas=True)

bc.submit_transaction(transaction)
bc.submit_transaction(transaction2)
bc.submit_transaction(transaction3)
transaction = Transaction(wallet.address, wallet2.address, appleHash)
transaction2 = Transaction(wallet.address, wallet2.address, appleHash)
transaction3 = Transaction(wallet.address, wallet2.address, appleHash)

transaction.sign(wallet)
transaction2.sign(wallet)
transaction3.sign(wallet)

bc.submit_transaction(transaction)
bc.submit_transaction(transaction2)
bc.submit_transaction(transaction3)

print("Les transaction : ", bc.current_transactions)

return bc, network


if __name__ == '__main__':
run()
Loading