Beispiel #1
0
def insert_data(target, connection, **kw):
    with open('/Users/fraccaman/Projects/BlockchainBar/network/data.data',
              'rb') as data:
        transactions = pickle.loads(data.read())
        # len(transactions) - math.floor(len(transactions) * 0.9)
        known_transactions = random.sample(transactions, k=250)
        for known_tx in known_transactions:
            d = bytearray.fromhex(known_tx[0])
            d_short_hash = Crypto.get_instance().get_hasher().short_hash(d)
            d_full_hash = Crypto.get_instance().get_hasher().hash(d)
            connection.execute(target.insert(), {
                'data': d,
                'short_id': d_short_hash,
                'full_id': d_full_hash
            })
Beispiel #2
0
 async def send_pom(self):
     while True:
         key, pom_message = await PubSub.get_subscriber_pom_instance(
         ).consume()
         bns = BootstrapIdentity.get_all()
         for bn in bns:
             bn_public_key = Crypto.get_instance().get_ec(
             ).load_public_key_from_string(bn.public_key)
             if Crypto.get_instance().get_ec().verify(
                     pom_message.token.bn_signature,
                 (pom_message.token.base + pom_message.token.proof +
                  pom_message.token.epoch).encode('utf-8'), bn_public_key):
                 writer = self.connections[bn.address]
                 writer.write(pom_message.serialize())
                 await writer.drain()
                 break
Beispiel #3
0
 def verify_signature(self):
     sig = copy.deepcopy(self.signature)
     self.signature = None
     res = Crypto.get_ec().verify(sig, self.serialize(),
                                  self.from_peer.public_key)
     self.signature = sig
     return res
Beispiel #4
0
 def sort(peer_list, epoch) -> Union[List[Peer], List[None]]:
     peer_list.sort(key=lambda x: int(x.__dict__['public_key'].split('.')[0]), reverse=True)
     n_of_peers = len(peer_list)
     random_indexes = Crypto.get_instance().get_random().prng_unique(epoch, n_of_peers, n_of_peers)
     shuffled_peer_list = [None for _ in range(n_of_peers)]
     for index, random_index in enumerate(random_indexes):
         shuffled_peer_list[random_index] = peer_list[index]
     return shuffled_peer_list
Beispiel #5
0
 def short_hash(self):
     return Crypto().get_hasher().short_hash(self.data)
Beispiel #6
0
 def _compute_hash(self):
     return Crypto().get_hasher().hash(self.data)
Beispiel #7
0
 def is_valid_signature(self) -> bool:
     return Crypto.get_instance().get_ec().verify(
         self.bn_signature,
         (self.base + self.proof + str(self.epoch)).encode('utf-8'),
         Crypto.get_instance().get_ec().public_key)
Beispiel #8
0
 def setup(private_key: int, log_level: LogLevels, file: int) -> NoReturn:
     Logger(LogLevels(log_level))
     Crypto(private_key)
     Store.setup_bn_store(file)
Beispiel #9
0
 def get_public_key(private_key: int) -> Point:
     return Crypto.get_instance().get_ec().generate_public_from_private(
         private_key)
 def verify(self, bn_public_key):
     return Crypto.get_instance().get_ec().verify(
         self.token.token, (self.token.base + self.token.proof +
                            self.token.epoch).encode('utf-8'),
         bn_public_key)
Beispiel #11
0
class Controller(ABC):
    def __init__(self, config: Config):
        self.config = config
        self.crypto = Crypto()
        self.pub_sub = PubSub()
        self.connection_lock = asyncio.Lock()

    @staticmethod
    @abstractmethod
    def is_valid_controller_for(message: Message) -> bool:
        raise Exception("Not Implemented!")

    async def handle(self, connection: StreamWriter,
                     message: Message) -> NoReturn:
        self.on_receiving(message)
        await self._handle(connection, message)
        self.on_sending(message)

    @staticmethod
    def get_puzzle_difficulty() -> float:
        return REGISTRATION_DIFFICULTY

    @staticmethod
    def format_public_key(x: str) -> Tuple[int, int, str]:
        tmp = x.split('.')
        return int(tmp[0]), int(tmp[1]), tmp[2]

    def verify_token(self, message, public_key):
        x, y, curve = self.format_public_key(public_key)
        bn_public_key = self.crypto.get_ec().load_public_key(x, y, curve)
        return self.crypto.get_ec().verify(
            message.token.bn_signature,
            (message.token.base + message.token.proof +
             message.token.epoch).encode('utf-8'), bn_public_key)

    async def close_connection(self, connection: StreamWriter):
        async with self.connection_lock:
            try:
                connection.close()
                await asyncio.sleep(0.5)
            finally:
                print('closed')
                await connection.wait_closed()

    @staticmethod
    def get_current_epoch() -> Epoch:
        current_epoch = Epoch.get_current_epoch()
        return current_epoch

    @staticmethod
    def get_next_epoch() -> Epoch:
        next_epoch = Epoch.get_next_epoch()
        return next_epoch

    @staticmethod
    def format_address(address: str) -> str:
        return '{}:{}'.format(
            address[0] if address[0] != '127.0.0.1' else '0.0.0.0', address[1])

    @abstractmethod
    async def _handle(self, connection: StreamWriter,
                      message: Message) -> NoReturn:
        pass

    async def send(self, connection: StreamWriter,
                   message: Message) -> NoReturn:
        async with self.connection_lock:
            try:
                connection.write(message.serialize())
                await connection.drain()
            except ConnectionResetError or ConnectionAbortedError as _:
                print('connection closed')
                pass
            except Exception as e:
                print('random error', e)
                print(message)
                pass

    @staticmethod
    def on_receiving(message: Message) -> NoReturn:
        pass

    @staticmethod
    def on_sending(message: Message) -> NoReturn:
        pass
Beispiel #12
0
 def compute_signature(self):
     self.signature = Crypto.get_ec().sign(self.serialize())
Beispiel #13
0
 def _compute_prev_hash(prev_msg: Message):
     return Crypto.get_instance().get_hasher().hash(
         prev_msg.serialize()) if prev_msg is not None else '0' * 64
Beispiel #14
0
 def compute_key(self):
     return Crypto.get_instance().get_hasher().hash(
         Crypto.get_instance().get_ec().private_key.to_bytes(
             length=256, byteorder='big', signed=True) +
         self.epoch.encode() + self.get_peer_public_key().encode())
Beispiel #15
0
 def __init__(self, config: Config):
     self.config = config
     self.crypto = Crypto()
     self.pub_sub = PubSub()
     self.connection_lock = asyncio.Lock()
Beispiel #16
0
 def bn_sign(self) -> NoReturn:
     message = (self.base + self.proof + self.epoch).encode('utf-8')
     self.bn_signature = Crypto.get_instance().get_ec().sign(message)
Beispiel #17
0
 def generate_puzzle(public_key: Point) -> str:
     nonce = Crypto().get_instance().get_random().generate_random_bytes()
     formatted_public_key = Crypto.get_instance().get_ec().dump_public_key(
         public_key)
     return '{}-{}'.format(formatted_public_key, nonce)