示例#1
0
    def __init__(self, address):
        self.address = address

        key = RSA.generate(1024)

        self.private_key = binascii.hexlify(
            key.exportKey(format='DER')).decode('ascii')

        self.public_key = binascii.hexlify(
            key.publickey().exportKey(format='DER')).decode('ascii')

        self.chain = BlockChain()
示例#2
0
    def handle_receive_blockchain(self, blockchain: dict):
        other_blockchain = BlockChain.deserialize(blockchain)

        if other_blockchain.length > self.blockchain.length:
            self.blockchain.replace(other_blockchain)

        self.transport.close()
示例#3
0
    def __init__(self, known_ports, state_map, config):

        self.bot_instance = bot(config["port"], config, 0, 0)
        self.port = config["port_socket"]
        known_ports.discard(self.port)
        self.other_ports = known_ports
        self.chain = BlockChain(state_map)

        self.vrep_port = config["port"]
        pos = self.bot_instance.Get_postiton()
        # print("this is pos in main bot: ", pos)
        self.coordinates = {"x": pos[0], "y": pos[1]}
        # print("coordinats::: ", self.coordinates)
        # self.get_coordinates_from_vrep()
        self.status = None  # * "Picked" or "Placed" or "Dropped" or "Free"
        self.block = None
示例#4
0
 def verify_blockchain_depth(cls) -> bool:
     """深入验证区块链(区块、交易)"""
     if not cls.verify_blockchain():
         return False
     for block in BlockChain.get_instance().get_blocks()[1:]:  # 第一个区块不作检查
         if not cls.verify_block_depth(block):
             return False
     return True
示例#5
0
    def __init__(self, my_port, known_ports, data):

        # ! DO THIS
        self.coordinates = self.get_coordinates_from_vrep()
        self.port = my_port
        known_ports.discard(my_port)
        self.other_ports = known_ports
        self.chain = BlockChain(data)

        # ! INSTEAD OF THIS
        self.coordinates = {
            "x": -0.024999968707561493,
            "y": 0.04999999701976776
        }
        bot_coordinates = self.coordinates
        self.status = None  # * "Picked" or "Placed" or "Dropped" or "Free"
        self.block = None
示例#6
0
 def is_ok(self) -> bool:
     blc = BlockChain.get_instance()
     for block in blc.get_blocks():
         # 区块的时间戳肯定比区块链要后
         if block.get_timestap() < blc.get_start_time():
             return False
         # 区块的时间戳肯定比现在前
         if block.get_timestap() > time.localtime():
             return False
     return True
示例#7
0
 def verify_new_transaction(cls, trans: Transaction) -> bool:
     """验证一笔新交易"""
     if not cls.verify_transaction(trans):
         return False
     # 验证输入的有效性
     for inp in trans.get_inputs():
         if not BlockChain.get_instance().verify_utxo(
                 inp.block, inp.trans, inp.output):
             return False
     return True
示例#8
0
 def is_ok(self) -> bool:
     pre_hash = FIREST_BLOCK_PREHASH
     for i, block in enumerate(BlockChain.get_instance().get_blocks()):
         # 索引值index应合法
         if block.get_index() != i + 1:
             return False
         # pre_hash值应为上一个区块
         if pre_hash != block.get_prehash():
             return False
         pre_hash = block.get_hash()
     return True
示例#9
0
 def is_ok(self) -> bool:
     address_list = [key.get_address() for key in self.trans.get_pub_keys()]
     # 签名必须有效
     if not self.trans.verify_transaction():
         return False
     # 每一个输入都为本人的utxo
     for inp in self.trans.get_inputs():
         outp = BlockChain.get_instance().input_to_output(inp)
         if outp.address not in address_list:
             return False
     return True
示例#10
0
class Node(object):
    def __init__(self, address):
        self.address = address

        key = RSA.generate(1024)

        self.private_key = binascii.hexlify(
            key.exportKey(format='DER')).decode('ascii')

        self.public_key = binascii.hexlify(
            key.publickey().exportKey(format='DER')).decode('ascii')

        self.chain = BlockChain()

    def __repr__(self):
        return 'node: {} len: {}'.format(self.address, len(self.chain))

    def make_transaction(self, to, amount):
        trans = {
            'sender': self.address,
            'to': to.address,
            'amount': str(amount)
        }

        return Transaction(**trans, signature=self.sign(trans))

    def sign(self, transaction):
        private_key = RSA.importKey(binascii.unhexlify(self.private_key))
        signer = PKCS1_v1_5.new(private_key)
        h = SHA.new(str(transaction).encode('utf8'))
        return binascii.hexlify(signer.sign(h)).decode('ascii')

    def verify(self, transaction):
        public_key = RSA.importKey(binascii.unhexlify(transaction.sender))
        verifier = PKCS1_v1_5.new(public_key)
        h = SHA.new(str(transaction).encode('utf8'))
        return verifier.verify(h, binascii.unhexlify(transaction.signature))

    def add_next_block(self, transactions, proof):
        self.chain.next_block(transactions, proof)
示例#11
0
 def verify_new_block(cls, block: Block) -> bool:
     """验证一个新块"""
     if not cls.verify_block_depth(block):
         return False
     # pre_hash的值要正确
     if block.get_prehash() != BlockChain.get_instance().get_top_block(
     ).get_hash():
         return False
     # 验证每笔交易的有效性
     inputs = []
     for trans in block.get_user_transactions():
         if not cls.verify_new_transaction(trans):
             return False
         inputs.extend(trans.get_inputs())
     # 不同的交易不能有相同的输入
     if len(set(inputs)) != len(inputs):
         return False
     return True
示例#12
0
 def verify_block_depth(cls, block: Block) -> bool:
     """深入验证区块(包括区块中的交易)"""
     if not cls.verify_block(block):
         return False
     # 验证用户的交易
     for trans in block.get_user_transactions():
         if not cls.verify_transaction(trans):
             return False
     # 验证第一笔交易
     trans = block.get_head_transaction()
     # 计算交易费
     fee = BlockChain.get_instance().compute_block_fee(block)
     # 计算矿工奖励
     mini_fee = trans.compute_outputs_btcs() - fee
     # 计算这个区块时的矿工奖励
     mini_btcs = block.get_now_ming_btcs()
     # 验证矿工奖励合法性
     if mini_fee != mini_btcs:
         return False
     return True
示例#13
0
class Bot:
    def __init__(self, known_ports, state_map, config):

        self.bot_instance = bot(config["port"], config, 0, 0)
        self.port = config["port_socket"]
        known_ports.discard(self.port)
        self.other_ports = known_ports
        self.chain = BlockChain(state_map)

        self.vrep_port = config["port"]
        pos = self.bot_instance.Get_postiton()
        # print("this is pos in main bot: ", pos)
        self.coordinates = {"x": pos[0], "y": pos[1]}
        # print("coordinats::: ", self.coordinates)
        # self.get_coordinates_from_vrep()
        self.status = None  # * "Picked" or "Placed" or "Dropped" or "Free"
        self.block = None

    # TODO INTEGRATION:
    def get_coordinates_from_vrep(self):
        self.coordinates = self.bot_instance.coordinates
        # print("these are the bots coord", self.coordinates)
        # return coordinates

    # * computes euclideian distance between two points
    def euclidean_dist(self, c1, c2):
        # print("this is c1: ", c1)
        # print("this is  c2: ", c2)
        delta_x = c1["x"] - c2["x"]
        delta_y = c1["y"] - c2["y"]
        # delta_x = 5
        # delta_y = 10
        return (delta_x**2 + delta_y**2)**(0.5)

    def spit_weighted_number(self, length):
        if length == 0:
            return 0
        random_array = []
        for i in range(1, length + 1):
            random_array.append([i] * (length + 1 - i))
        flattened = [item for sublist in random_array for item in sublist]
        return random.choice(flattened)

    def force_update(self):
        pass

    def sort_coords(self, c1):
        # print("this is bot coords:", self.coordinates)
        # print("this is c1", c1)
        c1 = {"x": c1["current"]["x"], "y": c1["current"]["y"]}
        dist1 = self.euclidean_dist(c1, self.coordinates)
        # dist2 = euclidean_dist(c2, bot_coordinates)
        # if dist1 < dist2:
        #     return -1
        # elif dist1 > dist2:
        #     return 1
        # else:
        #     return 0
        return dist1

    # * query the blockchain and obtains the state_map (topmost block) as data
    def queryBlockChain(self):
        response = self.chain[len(self.chain.blocks) - 1]
        # print("this is response::::", response.data)
        return response

    def prepare_to_send(self):
        latest_block = self.chain.get_block()
        json_string = json.dumps(latest_block.data)
        return json_string

    async def send_block(self):
        print("sending block to all other ports: ")
        block_json = self.prepare_to_send()
        for port in self.other_ports:
            async with websockets.connect(host + str(port)) as websocket:
                await websocket.send("block " + block_json)
                print("data sent to port number: ", port)

    def start_server_loop_in_thread(self):
        new_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(new_loop)
        start_server = websockets.serve(self.bot_server, "localhost",
                                        self.port)
        new_loop.run_until_complete(start_server)
        new_loop.run_forever()

    # * Gets the blockchain and updates it
    def update_blockchain(self, state):
        # print("update blockchain called")
        latest_block = self.queryBlockChain()
        latest_copy = latest_block
        # print("this is latest_copy", latest_copy)
        # print("its type??: ", type(latest_copy))
        # print("its data:: ", latest_copy.data)
        block_data = latest_copy.data["block_data"]
        block = block_data[self.block["id"]]
        print(
            "!!!!!!!!!!!!!!----------BLOCKCHAIN UPDATED-------------!!!!!!!!!!!!!!!!!!!!"
        )
        data_str = json.dumps(block_data)
        data_dict = {"data": data_str}
        G.add_node(data_dict)
        print(data_dict["data"])
        block["status"] = state
        # block["current"]["x"] = self.coordinates["x"]
        # block["current"]["y"] = self.coordinates["y"]
        block_data[self.block["id"]] = block
        latest_copy.data["block_data"] = block_data
        self.chain.add_block(latest_copy.data)
        new_loop = asyncio.new_event_loop()
        new_loop.run_until_complete(self.send_block())
        G.layout()
        G.draw('blockchain_plot.png')

    # * Returns the kth closest block to the bot
    # * Return data:
    # * {
    # * "current":
    # *   {
    # *   "x":..
    # *   "y":..
    # *   },
    # * "final":
    # *    {
    # *      "x"...,
    # *      "y"...
    # *    },
    # * "id"..
    # * }

    # * if all blocks are picked or placed, it returns None
    def get_kth_closest_block(self, k=1):
        latest_block = self.queryBlockChain()
        block_array = []
        # self.coordinates = self.get_coordinates_from_vrep()
        for block_id in latest_block.data["block_data"].keys():
            block = latest_block.data["block_data"][block_id]
            if (block["status"] != states["PLACED"]
                    and block["status"] != states["PICKED"]):
                block_array.append({
                    "current": {
                        "x": block["current"]["x"],
                        "y": block["current"]["y"],
                    },
                    "final": {
                        "x": block["final"]["x"],
                        "y": block["final"]["y"]
                    },
                    "id": block_id,
                })
        if len(block_array) == 0:
            return None
        block_array = sorted(block_array, key=self.sort_coords)
        if k <= len(block_array):
            return block_array[k - 1]
        else:
            return block_array[len(block_array) - 1]

    # * chooses a block and tries to pick it
    def choose_block(self):

        length = 0
        latest_block = self.queryBlockChain()
        # print(latest_block)
        for bl in latest_block.data["block_data"]:
            block = latest_block.data["block_data"][bl]
            # print(block)
            if (block["status"] == states["IDLE"]
                    or block["status"] == states["DROPPED"]):
                length += 1
        k = self.spit_weighted_number(length)
        print("chosen k:: ", k)
        if k == 0:
            return None
        block = self.get_kth_closest_block(k)
        return block

    # * pick_block if threshold error is less than given threshold
    def state_block_check(self, state=states["MOVING"], threshold=0.1):
        if state == states["MOVING"]:
            block_coords = self.block["current"]
        elif state == states["PICKED"]:
            block_coords = self.block.final
        if euclidean_dist(self.coordinates, block_coords) <= threshold:
            return True
        return False

    def pick_block(self):

        self.bot_instance.pick()
        if self.bot_instance.objectPicked != 0:
            self.update_blockchain(states["PICKED"])
            return True
        return False

    def goto_destination(self):
        pass

    async def bot_server(self, websocket, path):
        print("server running at port: ", self.port)
        message = await websocket.recv()
        print("MESSAGE RECEIVED")
        if message[0:6] == "block ":
            print("receiving block")
            message = message[6:]
            block = json.loads(message)
            self.chain.add_block(block)
        elif message[0:6] == "chain?":
            chain_string = json.dumps(self.chain)
            await websocket.send(chain_string)

    def is_block_pickable(self):
        latest_block = self.queryBlockChain()
        block = latest_block.data["block_data"][self.block["id"]]
        if block["status"] == states["DROPPED"] or block["status"] == states[
                "IDLE"]:
            return True
        return False

    def place_block(self):
        self.update_blockchain(states["PLACED"])
        self.bot_instance.place()
        # self.coordinates = self.get_coordinates_from_vrep()
        # self.status = states["LOOKING"]
        # block_coords = latest_block["block_data"][block_id].final

    def follow_path(self, block, final=False):
        if final:
            x = block["final"]["x"]
            y = block["final"]["y"]
        else:
            x = block["current"]["x"]
            y = block["current"]["y"]
        # print(block)
        # print(x,y)
        self.bot_instance.Follow_path([x, y, 0.05])

    def chooseTargetBlock(self, chosenLabel, labels):
        pass

    # choose closest block from chosen cluster
    def infinite_loop(self):
        # r=print("inside infinite loop")
        self.state = states["BEGIN"]
        while self.state != states["END"]:
            self.block = self.choose_block()
            if self.block == None:
                print("No block to pick")
                self.state = states["END"]
                break
            else:
                print("chosen block id: ", self.block["id"])
                self.state = states["MOVING"]
                self.follow_path(self.block)
                if self.is_block_pickable():
                    # print("before time sleep")
                    time.sleep(2)
                    # print("after time sleep")
                    status = self.pick_block()
                    print(status)
                    if status:
                        self.state = states["PICKED"]
                        self.follow_path(self.block, True)
                        self.place_block()
                        self.state = states["PLACED"]
                self.states = states["BEGIN"]
                continue

    async def force_update(self):
        chain_array = []
        for port in self.other_ports:
            async with websockets.connect(host + str(port)) as websocket:
                await websocket.send("chain?")
                response = await websocket.recv()
                chain = json.loads(response)
                chain_array.append(chain)
        for chain in chain_array:
            if len(chain) > len(self.chain):
                self.chain = chain

    def main_driver(self):

        # inter = setInterval(3, self.get_coordinates_from_vrep)

        t1 = threading.Thread(target=self.infinite_loop, args=[])
        t1.start()
        t3 = threading.Thread(target=self.start_server_loop_in_thread)
        t3.start()
        # foce_push_interval = setInterval(60, self.force_update)
        # TODO: FORCE PUSH
        t1.join()
        t3.join()
示例#14
0
    def test_blockchain(self):
        bc = BlockChain()
        blocks_to_mine = 5
        for i in range(blocks_to_mine):
            bc.mine("data")

        self.assertSerializable(BlockChain, bc, globals())

        self.assertTrue(bc.validate_blocks(0, 1))
        self.assertTrue(bc.validate_blocks(1, 3))
        self.assertTrue(bc.is_valid_chain())
        self.assertFalse(bc.replace(bc))
        self.assertEqual(bc.blocks, bc.blocks)
        self.assertIs(bc[0], bc.blocks[0])
        self.assertEqual(len(bc), blocks_to_mine + 1)
        self.assertEqual(bc[0:-1:2], bc.blocks[0:-1:2])
        self.assertEqual(bc[::-1], bc.blocks[::-1])

        last_block = bc[-1]
        bc1 = BlockChain()
        bc1.mine("any")
        self.assertFalse(bc1.add_block(last_block))
        self.assertNotEqual(bc, bc1)
        self.assertFalse(bc.replace(bc1))
        self.assertEqual(bc[-1], last_block)
        self.assertTrue(bc1.replace(bc))
        self.assertEqual(bc1, bc)
        print()
        for i in range(blocks_to_mine):
            bc1.mine("another data")

        self.assertIs(bc1.blocks, bc.blocks)
        self.assertEqual(bc, bc1)
示例#15
0
import asyncio
import websockets
import jsonpickle
import requests
from chain import BlockChain
from block import Block
import time
from sklearn.cluster import DBSCAN
import sys
import numpy as np

chain = BlockChain()
thisbot.id = "Bot1"


"""
The static parameters
    bot_id
"""


class Bot:
    def __init__(self, coordinates, bot_id):
        self.coordinates = [coordinates.x, coordinates.y]
        self.id = bot_id

    def chooseTargetCluster(self, cluster_center, labels):
        dist = sys.maxint
        chosenLabel = sys.maxint
        for point in cluster_center:
            curr_dist = euclidean_dist(self.coordinates, point[1])
示例#16
0
class Bot:
    def __init__(self, my_port, known_ports, data):

        # ! DO THIS
        self.coordinates = self.get_coordinates_from_vrep()
        self.port = my_port
        known_ports.discard(my_port)
        self.other_ports = known_ports
        self.chain = BlockChain(data)

        # ! INSTEAD OF THIS
        self.coordinates = {
            "x": -0.024999968707561493,
            "y": 0.04999999701976776
        }
        bot_coordinates = self.coordinates
        self.status = None  # * "Picked" or "Placed" or "Dropped" or "Free"
        self.block = None

    # TODO INTEGRATION:
    def get_coordinates_from_vrep(self):
        # <<<<<<< dev_blockchain

        #*port is the port which the vrep simulation is running
        # scene = scene(port)
        # map = scene.scenesinit(port)
        map = []
        #*process map here according to req and return
        return map
        # =======
        global bot_coordinates
        self.coordinates = {
            "x": -0.024999968707561493,
            "y": 0.04999999701976776
        }
        bot_coordinates = self.coordinates
        pass
# >>>>>>> master

# * query the blockchain and obtains the map as json data

    def force_update():
        pass

    def queryBlockChain(self):
        response = self.chain.get_block()
        # JSONresponse = jsonpickle.decode(response)
        # plotBots(JSONresponse)
        # plotBlocks(JSONresponse)
        return response

    # * Comparator -> Sorts coordinatse based on least distance from bots cordinates

    def prepare_to_send(self):
        latset_block = self.chain.get_block()
        json_string = json.dumps(latset_block)
        return json_string

    async def send_block(self):
        global host
        block_json = self.prepare_to_send()
        for port in self.other_ports:
            async with websockets.connect(host + str(port)) as websocket:
                await websocket.send("block " + block_json)

    # * Gets the blockchain and updates it
    def update_blockchain(self, state):
        latest_block = self.queryBlockChain()
        block_data = latest_block.data["block_data"]
        block = block_data[self.block["id"]]
        block["state"] = state
        block["current"]["x"] = self.coordinates["x"]
        block["current"]["y"] = self.coordinates["y"]
        block_data[self.block["id"]] = block
        self.chain.add_block(block_data)
        asyncio.get_event_loop().run_until_complete(self.send_block())

    # * Returns the kth closest block to the bot
    # * Return data:
    # * {
    # * "current":
    # *   {
    # *   "x":..
    # *   "y":..
    # *   },
    # * "final":
    # *    {
    # *      "x"...,
    # *      "y"...
    # *    },
    # * "id"..
    # * }

    # * if all blocks are picked or placed, it returns None
    def get_kth_closest_block(self, k=1):
        latest_block = self.queryBlockChain()
        block_array = []
        for block_id in latest_block.data["block_data"].keys():
            block = latest_block.data["block_data"][block_id]
            if (block["status"] != states["PLACED"]
                    and block["status"] != states["PICKED"]):
                block_array.append({
                    "current": {
                        "x": block["current"]["x"],
                        "y": block["current"]["y"],
                    },
                    "final": {
                        "x": block["final"]["x"],
                        "y": block["final"]["y"]
                    },
                    "id": block_id,
                })
        if len(block_array) == 0:
            return None
        block_array = sorted(block_array, key=sort_coords)
        if k <= len(block_array):
            return block_array[k - 1]
        else:
            return block_array[len(block_array) - 1]

    # * chooses a block and tries to pick it
    def choose_block(self):
        length = 0
        latest_block = self.queryBlockChain()
        print(latest_block)
        for bl in latest_block.data["block_data"]:
            block = latest_block.data["block_data"][bl]
            print(block)
            if (block["status"] == states["IDLE"]
                    or block["status"] == states["DROPPED"]):
                length += 1
        k = spit_weighted_number(length)
        block = self.get_kth_closest_block(k)
        return block

    # * pick_block if threshold error is less than given threshold
    def state_block_check(self, state=states["MOVING"], threshold=0.1):
        if state == states["MOVING"]:
            block_coords = self.block["current"]
        elif state == states["PICKED"]:
            block_coords = self.block.final
        if euclidean_dist(self.coordinates, block_coords) <= threshold:
            return True
        return False

    def pick_block(self):
        # self.status = states["PICKED"]
        self.update_blockchain(states["PICKED"])

    def goto_destination(self):
        pass

    async def bot_server(self, websocket, path):
        while True:
            message = await websocket.recv()
            if message[0:6] == "block ":
                message = message[6:]
                block = json.loads(message)
                self.chain.add_block(block)
            elif message[0:6] == "chain?":
                chain_string = json.dumps(self.chain)
                await websocket.send(chain_string)

    def is_block_pickable(self):
        latest_block = self.queryBlockChain()
        block = latest_block.data["block_data"][self.block["id"]]
        if block["status"] == states["DROPPED"] or block["status"] == states[
                "IDLE"]:
            return True
        return False

    def place_block(self):
        self.update_blockchain(states["PLACED"])
        # self.status = states["LOOKING"]
        # block_coords = latest_block["block_data"][block_id].final

    def chooseTargetBlock(self, chosenLabel, labels):
        pass

    # choose closest block from chosen cluster
    def infinite_loop(self):
        self.state = states["BEGIN"]
        while self.state != states["END"]:
            self.block = self.choose_block()
            if self.block == None:
                self.state = states["END"]
                break
            else:
                self.state = states["MOVING"]
                while not self.state_block_check(states["MOVING"], 0.5):
                    pass
                if self.is_block_pickable():
                    self.state = states["PICKED"]
                    self.pick_block()
                    while not self.state_block_check(states["PICKED"], 0.5):
                        pass
                    self.state = states["PLACED"]
                    self.place_block()
                    self.state = states["BEGIN"]
                    continue

                else:
                    self.state = states["BEGIN"]
                    continue

    async def force_update(self):
        chain_array = []
        for port in self.other_ports:
            async with websockets.connect(host + str(port)) as websocket:
                await websocket.send("chain?")
                response = await websocket.recv()
                chain = json.loads(response)
                chain_array.append(chain)
        for chain in chain_array:
            if len(chain) >= len(self.chain):
                self.chain = chain

    def main_driver(self):

        inter = setInterval(1, self.get_coordinates_from_vrep())
        start_server = websockets.serve(self.bot_server, "localhost",
                                        self.port)
        t1 = threading.Thread(target=self.infinite_loop, args=[])
        t1.start()
        foce_push_interval = setInterval(60, self.force_update)
        loop = asyncio.get_event_loop()
        loop.run_until_complete(start_server)
        loop.run_forever()
示例#17
0
 def is_ok(self) -> bool:
     # 交易费必须大于0
     blc = BlockChain.get_instance()
     return blc.compute_transaction_fee(self.trans) > Btc("0")
示例#18
0
 def send_blockchain(cls, blockchain: BlockChain) -> dict:
     return dict(type=cls.RECEIVE_BLOCKCHAIN.value,
                 blockchain=blockchain.serialize())
示例#19
0
#!/usr/bin/python3
from chain import BlockChain
from wallet import Wallet
from transactions import Transaction

bch = BlockChain()

w1 = Wallet("Abdou")
w2 = Wallet("Aymen")

tr = Transaction(w1, w2, "50000")
late = bch.latest_block
bch.construct_block(late.proof_nonce, late.prev_hash, tr.to_dict(), {
    w1.user_id: "00",
    w2.user_id: "00"
})
tr1 = Transaction(w2, w1, "50000")
late = bch.latest_block
bch.construct_block(late.proof_nonce, late.prev_hash, tr1.to_dict(), {
    w1.user_id: "00",
    w2.user_id: "00"
})

w3 = Wallet("Ons")
bch.construct_block(late.proof_nonce, late.prev_hash, [], {
    w1.user_id: "00",
    w2.user_id: "00",
    w3.user_id: "00"
})

print(bch.chain)
示例#20
0
 def __blc(self) -> BlockChain:
     return BlockChain.get_instance()
示例#21
0
 def read_blockchain(self) -> None:
     # read from local or init
     self.blockchain = BlockChain()
示例#22
0
#!/usr/bin/python3
from block import Block
from chain import BlockChain
from wallet import Wallet

my_wallet = Wallet("aymen")
blockchain = BlockChain()

print("Blockchain Records Status :")
print(blockchain.chain)

last_block = blockchain.latest_block
last_proof_nonce = last_block.proof_nonce
proof_nonce = blockchain.proof_of_work(last_proof_nonce)
print("***Mining CyberCellCoin about to start***")

blockchain.add_transaction(
    sender="Ons_Jannet",  #it implies that this node has created a new block
    recipient="Aymen_Haddaji",  #let's send Aymen some coins!
    amount=10,  #creating a new block (or identifying the proof number) is awarded with 10
)

last_hash = last_block.calculate_hash
block = blockchain.construct_block(proof_nonce, last_hash)
print(blockchain.chain)

print("***Transaction seccessfully executed***")
print("===============================================")
print("let's execute another transaction !")
print("===============================================")
示例#23
0
 def __import_blc_from_db(self) -> None:
     """从sqlite数据库导入区块链"""
     for block in self.sqlite_driver.get_blocks():
         BlockChain.get_instance().add_block(block)
示例#24
0
# import jsonpickle
import requests
from chain import BlockChain
from block import Block
import time
from sklearn.cluster import DBSCAN
import sys
import numpy as np
import random

# from pyhton import intial
#*not so sure about the import statement

data = []
chain = BlockChain(data)
import json
from setInterval import setInterval
import threading
import websockets
import enum
"""
The static parameters
    bot_id
"""
host = "ws://localhost:"

states = {
    "IDLE": "idle",
    "PLACED": "placed",
    "PICKED": "picked",
示例#25
0
 def set_blockchain(self, blc: BlockChain) -> None:
     """设定区块链数据库"""
     BlockChain.set_instance(blc)
示例#26
0
def main():
    manufacturer = {
        'transactions': [{
            'timestamp': datetime.now().timestamp(),
            'product_id': 1,
            'product_serial': 500,
            'name': 'cotton pants',
            'from': 'Manufacturer X',
            'to': 'Transportation X',
            'message': 'good condition',
            'digital signature': 'approved',
            'flagged': 'N'
        }, {
            'timestamp': datetime.now().timestamp(),
            'product_id': 2,
            'product_serial': 501,
            'name': 'cotton shirt',
            'from': 'Manufacturer X',
            'to': 'Transportation X',
            'message': 'good condition',
            'digital signature': 'approved',
            'flagged': 'N'
        }, {
            'timestamp': datetime.now().timestamp(),
            'product_id': 2,
            'product_serial': 502,
            'name': 'cotton shirt',
            'from': 'Manufacturer X',
            'to': 'Transportation X',
            'message': 'good condition',
            'digital signature': 'approved',
            'flagged': 'N'
        }]
    }
    transportation = {
        'transactions': [{
            'timestamp': datetime.now().timestamp(),
            'product_id': 1,
            'product_serial': 500,
            'name': 'cotton pants',
            'from': 'Transportation X',
            'to': 'Vendor X',
            'shipping_id': 100,
            'message': 'good condition',
            'digital signature': 'approved',
            'flagged': 'N'
        }, {
            'timestamp': datetime.now().timestamp(),
            'product_id': 2,
            'product_serial': 501,
            'name': 'cotton shirt',
            'from': 'Transportation X',
            'to': 'Vendor X',
            'shipping_id': 101,
            'message': 'good condition',
            'digital signature': 'approved',
            'flagged': 'N'
        }, {
            'timestamp': datetime.now().timestamp(),
            'product_id': 2,
            'product_serial': 502,
            'name': 'cotton shirt',
            'from': 'Transportation X',
            'to': 'Vendor X',
            'shipping_id': 102,
            'message': 'poor condition',
            'digital signature': 'retailer review',
            'flagged': 'Y'
        }]
    }

    vendor = {
        'transactions': [{
            'timestamp': datetime.now().timestamp(),
            'product_id': 1,
            'product_serial': 500,
            'name': 'cotton pants',
            'from': 'Vendor X',
            'to': 'Shelf X',
            'receiving_id': 300,
            'message': 'good condition',
            'digital signature': 'approved',
            'flagged': 'N'
        }, {
            'timestamp': datetime.now().timestamp(),
            'product_id': 2,
            'product_serial': 501,
            'name': 'cotton shirt',
            'from': 'Vendor X',
            'to': 'Shelf X',
            'receiving_id': 301,
            'message': 'good condition',
            'digital signature': 'approved',
            'flagged': 'N'
        }, {
            'timestamp': datetime.now().timestamp(),
            'product_id': 2,
            'product_serial': 502,
            'name': 'cotton shirt',
            'from': 'Vendor X',
            'to': 'RTM',
            'receiving_id': 302,
            'message': 'Box Damaged',
            'digital signature': 'rejected',
            'flagged': 'Y'
        }]
    }

    B = BlockChain()
    a = B.add(manufacturer)
    b = B.add(transportation)
    c = B.add(vendor)
    B.getTransactions('all')
    print(B.getLastBlock())
示例#27
0
from key import UserKey
from chain import Btc, TransOutput, TransInput, Transaction, Block, BlockChain
from config import MINING_BTCS
from verify import Verify

if __name__ == "__main__":
    print(BlockChain.__qualname__, BlockChain.get_instance.__qualname__)
    # 创建区块链
    bc = BlockChain.get_instance()
    print(bc.get_start_time())
    # 初始的两个用户
    key1 = UserKey()
    key2 = UserKey()
    # 初始区块的创币交易(只有输出,没有输入)
    t1 = Transaction()
    t1.add_output(TransOutput(Btc("5000"), key1.get_address()))
    t1.add_output(TransOutput(Btc("5000"), key2.get_address()))
    # 创世区块
    b1 = Block()
    b1.add_transaction(t1)
    # 添加矿工奖励交易
    mt1 = Transaction()
    mt1.add_output(TransOutput(Btc(MINING_BTCS), key1.get_address()))
    b1.set_head_transaction(mt1)
    b1.set_index(1)
    # 挖矿
    b1.find_randnum()
    # 添加区块
    bc.add_block(b1)
    # key1向key2转账
    t2 = Transaction()
#!/usr/bin/python3

from wallet import Wallet
from chain import BlockChain
from block import Block
#sign transaction
my_wallet = Wallet("A")
b = BlockChain()
my_wallet.create_keys()
my_wallet.save_keys()
my_wallet.load_keys()
pub = my_wallet.public_key
prv = my_wallet.private_key

verf = my_wallet.verify_transaction(b.add_transaction().data[TRANSACTION])

signer = my_wallet.sign_transaction(sender="Ons_Jannet",
                                    recipient="Aymen_Haddaji",
                                    amount=10)

print(" signature user is:", signer, verf)