Bläddra i källkod

Done

Padra code is now done and is tested with spacex api
Shayan 4 år sedan
förälder
incheckning
d314690995

+ 0 - 1
Smart-Contract/Padra.txt

@@ -1 +0,0 @@
-Hello From Mo and Padra :

+ 0 - 5
Smart-Contract/requirements.txt

@@ -1,5 +0,0 @@
-web3==5.12.1
-infura==0.2.1
-# infura user: zzj58582@cuoly.com
-# infura pass: qwertz123456
-ipfs-api ==0.2.3

+ 0 - 76
Smart-Contract/script.py

@@ -1,76 +0,0 @@
-from web3 import Web3
-import json
-import ipfshttpclient
-import pprint
-from web3.gas_strategies.time_based import medium_gas_price_strategy, fast_gas_price_strategy
-
-
-
-#infura_url_mainnet = "https://mainnet.infura.io/v3/88df052c847f4d80b839a6cdd00a515c"
-infura_kovan = "https://kovan.infura.io/v3/88df052c847f4d80b839a6cdd00a515c"
-# ganache_url = "http://127.0.0.1:7545"
-
-
-
-print("Connecting to IPFS...")
-ipfs_uri = "/dns/ipfs.infura.io/tcp/5001/https"
-client = ipfshttpclient.connect(ipfs_uri)
-
-result = client.add('Smart-Contract/Padra.txt')
-#print(result['Hash'])
-#print(type(result))
-result_hash = str(result['Hash'])
-print(f"Response saved on IPFS with this hash: {result_hash}")
-
-
-print("Connecting to Ethereum Test Network...")
-web3 = Web3(Web3.HTTPProvider(infura_kovan))
-# web3.eth.defaultAccount = web3.eth.accounts[0] #local
-web3.eth.defaultAccount = "0x92582427Bc16dEE757a20265F34460E13Fb05409"
-private_key = "c41170d8d93fb438f3a910d4a079d5e2140b55958c8f136b816c29280b2ed43d"
-print(f"Connected to Blockchain Test Network? {web3.isConnected()}")
-balance = web3.fromWei(web3.eth.getBalance(web3.eth.defaultAccount), 'gwei')
-#print(web3.eth.blockNumber)
-#print(web3.eth.getTransactionCount(web3.eth.defaultAccount))
-
-# sm_address_local = web3.toChecksumAddress("0x35341508Df8D36806171e4c62E2Df30004C8C774")
-sm_address = web3.toChecksumAddress("0x77161194E4d4B5af4Ec330CcE2f4F4A98a068d60")
-sm_abi = json.loads('[{"constant":false,"inputs":[{"name":"hash","type":"string"}],"name":"store","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"retrieve","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"}]')
-
-contract = web3.eth.contract(address = sm_address, abi= sm_abi)
-#print(contract)
-
-# local env
-# tx_hash = contract.functions.store(result_hash).transact()
-# print (tx_hash)
-# print(f"Access data from ipfs after writing to smart contract: https://ipfs.infura.io/ipfs/{contract.functions.retrieve().call()}")
-# tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash)
-# print(tx_receipt)
-
-# Ethernet testnet 
-gas_estimate = contract.functions.store(result_hash).estimateGas()
-print(f'Gas estimate to transact with store function: {gas_estimate}')
-web3.eth.setGasPriceStrategy(fast_gas_price_strategy)
-gasprice = web3.fromWei(web3.eth.generateGasPrice(), 'gwei')
-transaction_cost = gasprice * gas_estimate
-gas_limit = gas_estimate + (gas_estimate * 0.1)
-print(f'Transaction cost estimate: {transaction_cost}')
-if (balance > transaction_cost):
-    print("Enough balance, processing...")
-    print("Sending transaction to smart contract\n")
-    transaction = contract.functions.store(result_hash).buildTransaction()
-    transaction.update({ 'gas' : gas_estimate })
-    transaction.update({ 'nonce' : web3.eth.getTransactionCount(web3.eth.defaultAccount) })
-    signed_tx = web3.eth.account.signTransaction(transaction, private_key)
-    #print(signed_tx)
-    txn_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)
-    txn_receipt = web3.eth.waitForTransactionReceipt(txn_hash)
-    print("Transaction receipt mined:")
-    pprint.pprint(dict(txn_receipt))
-    if (txn_receipt["status"] == 1):
-        print("Transaction was successful?")
-        print(f"Access data from ipfs after writing to smart contract: https://ipfs.infura.io/ipfs/{contract.functions.retrieve().call()}")
-    else:
-        print(f"transaction was not successful")
-else:
-    print("Balance is not sufficent")

+ 7 - 1
command.py

@@ -6,8 +6,9 @@ def install():
     os.system("git submodule update")
     os.system("mkdir ./MP-SPDZ/Player-Data")
     os.system(
-        "apt-get install automake build-essential git libboost-dev libboost-thread-dev libsodium-dev libssl-dev libtool m4 python texinfo yasm pycrypto pycryptodome -y"
+        "apt-get install automake build-essential git libboost-dev libboost-thread-dev libsodium-dev libssl-dev libtool m4 python texinfo yasm pycrypto pyCrypto -y"
     )
+    os.system("pip install -r requirements.txt")
     os.system("./MP-SPDZ/Scripts/tldr.sh")
     os.system("cd MP-SPDZ && ls && make -j8 tldr")
     os.system("ln -s MP-SPDZ/Player-Data/ .")
@@ -24,3 +25,8 @@ def install():
 def comp(a):
     os.system("cp ./mpc/" + a + ".mpc ./Programs/Source/")
     os.system("./MP-SPDZ/compile.py " + a)
+
+
+
+if __name__ == "__main__":
+    install()

+ 7 - 1
connection/parser.py

@@ -1,7 +1,7 @@
 import json
 import config as cfg
 from Utils import *
-
+from tls.AES import AESCipher
 LenFunc = cfg.LenFunc
 
 
@@ -30,3 +30,9 @@ class Parser:
     def parser(self, data, addr, id):
         data = self.toJSON(data)
         gPrint("Simple parser", data)
+
+    def encrypt(self,key, msg):
+        return AESCipher(key).encrypt(msg)
+
+    def decrypt(self,key, msg):
+        return AESCipher(key).decrypt(msg)

+ 4 - 1
oracle/oracleParser.py

@@ -11,7 +11,7 @@ class OracleParser(Parser):
         self.oracle = oracle
         self.type = None
         self.id = None
-
+        self.user = None
     def parser(self, data, addr, Connection):
         try:
             if data["type"] == "requestOracleBroadcast":
@@ -19,6 +19,7 @@ class OracleParser(Parser):
             elif data["type"] == "socketConnecting":
                 self.socketConnecting(data)
             elif data["type"] == "oracleInitial":
+                self.user = Connection
                 self.type.oracleInitial(data)
             elif data["type"] == "keyExchange":
                 self.type.keyExchange(data)
@@ -32,6 +33,8 @@ class OracleParser(Parser):
                 self.type.fromContoCryHelloCLient(data)
             elif data["type"] == "fromCrytoConDone":
                 self.type.fromCrytoConDone(data)
+            elif data["type"] == "fromContoCryDone":
+                self.type.fromContoCryDone(data)
             elif data["type"] == "MPC":
                 self.type.MPC(data)
         except Exception as e:

+ 27 - 3
oracle/worker/connector.py

@@ -11,9 +11,12 @@ import tls as t
 from types import SimpleNamespace
 import subprocess
 from Crypto.Util.number import long_to_bytes, bytes_to_long
+from Crypto.Cipher import AES
 from tls.ghash import GhashCon
 from Utils import *
-
+from smartcontract.script import main
+import json
+import sys
 
 class Connector:
     def __init__(self, parser, socket):
@@ -37,7 +40,7 @@ class Connector:
         output = stream.read()
         self.path = output[:-1]
         self.t = threading.Thread(target=self.toCryptor)
-        self.done = threading.Thread(target=self.done)
+        self.doneThread = threading.Thread(target=self.done)
         self.doneTime = 5
         self.t.start()
 
@@ -47,6 +50,27 @@ class Connector:
                 time.sleep(1)
                 self.doneTime = self.doneTime - 1
             self.server.close()
+
+
+            d = {}
+            c = ""
+            for x in self.buffer:
+                c = c + x
+
+            
+            self.parser.add(d,"cipher",c)
+            res = self.parser.encrypt(self.key,self.parser.toSTRING(d))
+
+            file_path= "./Player-Data/connector.txt"
+            f = open(file_path, "w")
+            f.write(res)
+            f.close()
+            data_to_user = main(file_path)
+
+            self.parser.parserSend(data_to_user,self.parser.user,"connectorDone")
+            
+            sys.exit()
+
         except Exception as e:
             rBackPrint("An exception occurred done", e)
 
@@ -218,11 +242,11 @@ class Connector:
             gPrint("last_key ", self.last_key)
             self.GhashCon = GhashCon(self.auth_key, self.last_key)
             m = self.MPC()
-            self.done.start()
             self.server.send(bytes.fromhex(data["change"]))
             self.server.send(bytes.fromhex(data["finish"]))
             time.sleep(1)
             self.server.send((m))
+            self.doneThread.start()
 
         except Exception as e:
             rBackPrint("An exception occurred fromCrytoConDone", e)

+ 32 - 1
oracle/worker/cryptor.py

@@ -1,3 +1,4 @@
+import json
 import os
 import socket
 import threading
@@ -9,7 +10,9 @@ import time
 from Crypto.Util.number import long_to_bytes, bytes_to_long
 from tls.ghash import GhashCry
 from Utils import *
-
+from Crypto.Cipher import AES
+from smartcontract.script import main
+import sys
 
 def new_x25519():
     private_key = PrivateKey.generate()
@@ -24,6 +27,8 @@ class Cryptor:
         self.parser = parser
         self.connector = None
         self.key = None
+        
+        self.doneThread = threading.Thread(target=self.done)
         gBackPrint("CRYPTOR", "")
         gPrint("privatekey", self.privatekey)
         gPrint("key_exchange", self.key_exchange)
@@ -94,8 +99,33 @@ class Cryptor:
                 t = t + x
             self.counter2 = t
             self.connector.send(self.parser.toSEND(d))
+            self.doneThread.start()
+
+
         except Exception as e:
             rBackPrint("An exception occurred fromCrytoConDone", e)
+    def done(self):
+            d = {}
+
+            self.parser.add(d,"key",self.tls.peer_cipher.key.hex())
+            self.parser.add(d,"iv",self.tls.peer_cipher.ivhex.hex())
+
+            res = self.parser.encrypt(self.key,json.dumps(d))
+            # res = json.dumps(d)
+            print(res)
+            print(d)
+
+
+            file_path= "./Player-Data/cryptor.txt"
+            f = open(file_path, "w")
+            f.write(res)
+            f.close()
+            data_to_user = main(file_path)
+
+            self.parser.parserSend(data_to_user,self.parser.user,"cryptorDone")
+            sys.exit()
+
+
 
     def MPC(self, json):
         try:
@@ -106,6 +136,7 @@ class Cryptor:
                 str(bytes_to_long((self.counter2[4 * n : 4 * (1 + n)]))),
             )
 
+
             s = (
                 "echo "
                 + str(bytes_to_long((self.counter2[4 * n : 4 * (1 + n)])))

+ 11 - 0
requirements.txt

@@ -0,0 +1,11 @@
+pynacl
+web3==5.12.1
+infura==0.2.1
+ipfs-api ==0.2.3
+iofree
+hkdf
+pyCrypto
+pyCryptodome
+web3==5.12.1
+infura==0.2.1
+ipfs-api ==0.2.3

+ 81 - 0
smartcontract/script.py

@@ -0,0 +1,81 @@
+from web3 import Web3
+import json
+import ipfshttpclient
+import pprint
+from web3.gas_strategies.time_based import medium_gas_price_strategy, fast_gas_price_strategy
+from Utils import *
+
+def main(file_path):
+    #infura_url_mainnet = "https://mainnet.infura.io/v3/88df052c847f4d80b839a6cdd00a515c"
+    infura_kovan = "https://kovan.infura.io/v3/88df052c847f4d80b839a6cdd00a515c"
+    # ganache_url = "http://127.0.0.1:7545"
+
+
+
+    simplePrint("Connecting "," IPFS...")
+    ipfs_uri = "/dns/ipfs.infura.io/tcp/5001/https"
+    client = ipfshttpclient.connect(ipfs_uri)
+
+    result = client.add(file_path)
+    #print(result['Hash'])
+    #print(type(result))
+    result_hash = str(result['Hash'])
+    simplePrint("Response saved on IPFS with this hash", result_hash)
+
+
+    simplePrint("Connecting "," Ethereum Test Network...")
+    web3 = Web3(Web3.HTTPProvider(infura_kovan))
+    # web3.eth.defaultAccount = web3.eth.accounts[0] #local
+    web3.eth.defaultAccount = "0x92582427Bc16dEE757a20265F34460E13Fb05409"
+    private_key = "c41170d8d93fb438f3a910d4a079d5e2140b55958c8f136b816c29280b2ed43d"
+    bPrint("Connected to Blockchain Test Network?", web3.isConnected())
+    balance = web3.fromWei(web3.eth.getBalance(web3.eth.defaultAccount), 'gwei')
+    #print(web3.eth.blockNumber)
+    #print(web3.eth.getTransactionCount(web3.eth.defaultAccount))
+
+    # sm_address_local = web3.toChecksumAddress("0x35341508Df8D36806171e4c62E2Df30004C8C774")
+    sm_address = web3.toChecksumAddress("0x77161194E4d4B5af4Ec330CcE2f4F4A98a068d60")
+    sm_abi = json.loads('[{"constant":false,"inputs":[{"name":"hash","type":"string"}],"name":"store","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"retrieve","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"}]')
+
+    contract = web3.eth.contract(address = sm_address, abi= sm_abi)
+    #print(contract)
+
+    # local env
+    # tx_hash = contract.functions.store(result_hash).transact()
+    # print (tx_hash)
+    # print(f"Access data from ipfs after writing to smart contract: https://ipfs.infura.io/ipfs/{contract.functions.retrieve().call()}")
+    # tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash)
+    # print(tx_receipt)
+
+    # Ethernet testnet 
+    gas_estimate = contract.functions.store(result_hash).estimateGas()
+    bPrint('Gas estimate to transact with store function',gas_estimate)
+    web3.eth.setGasPriceStrategy(fast_gas_price_strategy)
+    gasprice = web3.fromWei(web3.eth.generateGasPrice(), 'gwei')
+    transaction_cost = gasprice * gas_estimate
+    gas_limit = gas_estimate + (gas_estimate * 0.1)
+    bBackPrint('Transaction cost estimate',transaction_cost)
+    if (balance > transaction_cost):
+        gBackPrint("Enough balance"," processing...")
+        gPrint("Sending transaction"," to smart contract")
+        transaction = contract.functions.store(result_hash).buildTransaction()
+        transaction.update({ 'gas' : gas_estimate })
+        transaction.update({ 'nonce' : web3.eth.getTransactionCount(web3.eth.defaultAccount) })
+        signed_tx = web3.eth.account.signTransaction(transaction, private_key)
+        #print(signed_tx)
+        txn_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)
+        txn_receipt = web3.eth.waitForTransactionReceipt(txn_hash)
+        gBackPrint("Transaction receipt mined:","")
+        pprint.pprint(dict(txn_receipt))
+        if (txn_receipt["status"] == 1):
+            gBackPrint("","Transaction was successful?")
+            gBackPrint("Access data from ipfs after writing to smart contract: ",f"https://ipfs.infura.io/ipfs/{contract.functions.retrieve().call()}")
+        else:
+            rBackPrint(f"transaction was not successful")
+            return None
+
+
+        return f"https://ipfs.infura.io/ipfs/{contract.functions.retrieve().call()}"
+    else:
+        yBackPrint("Balance is not sufficent")
+        return None

+ 0 - 0
Smart-Contract/storage.sol → smartcontract/storage.sol


+ 0 - 0
Smart-Contract/test.py → smartcontract/test.py


+ 35 - 0
tls/AES.py

@@ -0,0 +1,35 @@
+from hashlib import sha256
+import base64
+from Crypto import Random
+from Crypto.Cipher import AES
+
+BS = 16
+pad = lambda s: bytes(s + (BS - len(s) % BS) * chr(BS - len(s) % BS), 'utf-8')
+unpad = lambda s : s[0:-ord(s[-1:])]
+
+class AESCipher:
+
+    def __init__( self, key ):
+        self.key = bytes(key, 'utf-8')
+
+    def encrypt( self, raw ):
+        raw = pad(raw)
+        iv = Random.new().read( AES.block_size )
+        print(iv,raw)
+        cipher = AES.new(self.key, AES.MODE_CBC, iv )
+        return  (iv + cipher.encrypt( raw )).hex()
+
+    def decrypt( self, enc ):
+        enc = bytes.fromhex(enc)
+        iv = enc[:16]
+        print(iv,enc)
+
+        cipher = AES.new(self.key, AES.MODE_CBC, iv )
+        return unpad(cipher.decrypt( enc[16:] )).decode('utf8')
+
+cipher = AESCipher('mysecretpassword')
+encrypted = cipher.encrypt('Secret')
+decrypted = cipher.decrypt(encrypted)
+
+print(encrypted)
+print(decrypted)

+ 3 - 3
tls/ciphers.py

@@ -1,9 +1,9 @@
 import abc
 import nacl.bindings
 from .key_schedule import tls_sha256, tls_sha384
-from Cryptodome.Cipher import AES
-from Cryptodome.Util import Counter
-from Cryptodome.Util.number import long_to_bytes, bytes_to_long
+from Crypto.Cipher import AES
+from Crypto.Util import Counter
+from Crypto.Util.number import long_to_bytes, bytes_to_long
 from Utils import *
 
 # GF(2^128) defined by 1 + a + a^2 + a^7 + a^128

+ 4 - 1
tls/decrypt.py

@@ -93,6 +93,7 @@ class AES_GCM:
         return n
 
     def decrypt(self, c):
+        t = []
         while len(c) > 0:
             assert(c[:3] == b'\x17\x03\x03')
             a = bytes_to_long(c[3:5])
@@ -102,9 +103,11 @@ class AES_GCM:
             bPrint("auth_data", auth_data.hex())
             bPrint("cipher", cipher.hex())
             bPrint("auth_tag", auth_tag.hex())
-            self._decrypt(cipher, auth_tag, auth_data)
+            t.append(self._decrypt(cipher, auth_tag, auth_data))
             c = c[5+a:]
 
+        return t
+
     def _decrypt(self,  ciphertext, auth_tag, auth_data=b''):
         init_value = self.getNounce()
         # if auth_tag != self.__ghash(auth_data, ciphertext) ^\

+ 43 - 4
user/user.py

@@ -5,8 +5,12 @@ import config as cfg
 from .userParser import UserParser
 import secrets
 from Utils import *
+import requests
+from tls.decrypt import AES_GCM
+from Utils import *
+import threading
 
-
+import sys
 class User:
     def __init__(self, data, server, broadcast, broadcastPort):
         time.sleep(1)
@@ -25,7 +29,9 @@ class User:
         )
         self.keyCryptor = secrets.token_hex(16)
         self.keyConnector = secrets.token_hex(16)
-
+        self.cryData = None
+        self.conData = None
+        self.doneThread = threading.Thread(target=self.done)
     def run(self):
         self.broadcast.send(
             self.parser.requestOracleBroadcast(self.id), self.broadcast.addr
@@ -91,8 +97,41 @@ class User:
         )
 
 
-
-
+    def done(self):
+        while not( self.conData and self.cryData):
+            time.sleep(1)
+
+        cry = self.parser.toJSON(self.cryData)
+        key= cry["key"]
+        iv= cry["iv"]
+        con = self.parser.toJSON(self.conData)
+        cipher= con["cipher"]
+
+        dec = AES_GCM(int(key, 16),int(iv, 16))
+        p = dec.decrypt(bytes.fromhex(cipher))
+        gPrint("DATA IS",p)
+        sys.exit()
+        
+
+    def cryptorDone(self,data):
+        gPrint("cryptorDone", data["data"])
+        d = data["data"]
+        r = requests.get(d)
+        self.cryData = self.parser.decrypt(self.keyCryptor,r.text)
+        # self.cryData = r.text
+        print(self.cryData)
+        
+        self.doneThread.start()
+
+
+
+    def connectorDone(self,data):
+        gPrint("connectorDone",  data["data"])
+        d = data["data"]
+        r = requests.get(d)
+        self.conData = self.parser.decrypt(self.keyConnector,r.text)
+        # self.conData = r.text
+        print(self.conData)
 
 
 

+ 5 - 0
user/userParser.py

@@ -7,10 +7,15 @@ class UserParser(Parser):
         self.user = user
         print("createt User Parser")
 
+
     def parser(self, data, addr, Connection):
         try:
             if data["type"] == "responseUserBroadcast":
                 self.responseUserBroadcast(data, addr)
+            if data["type"] == "connectorDone":
+                self.user.connectorDone(data)
+            if data["type"] == "cryptorDone":
+                self.user.cryptorDone(data)
         except Exception as e:
             rBackPrint("An exception occurred parser", e)