Ejemplo n.º 1
0
def _blake2b_ed25519_deploy_data(current_height,
                                 bytecode,
                                 privatekey,
                                 receiver=None):
    sender = get_sender(private_key, True)
    print(sender)
    nonce = get_nonce(sender)
    print("nonce is {}".format(nonce))

    tx = Transaction()
    tx.valid_until_block = current_height + 88
    tx.nonce = nonce
    if receiver is not None:
        tx.to = receiver
    tx.data = hex2bytes(bytecode)

    message = _blake2b(tx.SerializeToString())
    print("msg is {}".format(message))
    sig = pysodium.crypto_sign_detached(message, hex2bytes(privatekey))
    print("sig {}".format(binascii.b2a_hex(sig)))

    pubkey = pysodium.crypto_sign_sk_to_pk(hex2bytes(privatekey))
    print("pubkey is {}".format(binascii.b2a_hex(pubkey)))
    signature = binascii.hexlify(sig[:]) + binascii.hexlify(pubkey[:])
    print("signature is {}".format(signature))

    unverify_tx = UnverifiedTransaction()
    unverify_tx.transaction.CopyFrom(tx)
    unverify_tx.signature = hex2bytes(signature)
    unverify_tx.crypto = Crypto.Value('SECP')

    print("unverify_tx is {}".format(
        binascii.hexlify(unverify_tx.SerializeToString())))
    return binascii.hexlify(unverify_tx.SerializeToString())
Ejemplo n.º 2
0
def generate_deploy_data(bytecode, privatekey, receiver=None):
    privkey = PrivateKey(hex2bytes(privatekey))
    sender = get_sender()
    print(sender)
    nonce = get_nonce(sender)
    print("nonce is {}".format(nonce))

    tx = Transaction()
    tx.valid_until_block = 4294967296
    tx.nonce = nonce
    if receiver is not None:
        tx.to = receiver
    tx.data = hex2bytes(bytecode)

    message = sha3(tx.SerializeToString())
    sign_recover = privkey.ecdsa_sign_recoverable(message, raw=True)
    sig = privkey.ecdsa_recoverable_serialize(sign_recover)
    signature = binascii.hexlify(
        sig[0]) + binascii.hexlify(bytes(bytearray([sig[1]])))

    unverify_tx = UnverifiedTransaction()
    unverify_tx.transaction.CopyFrom(tx)
    unverify_tx.signature = hex2bytes(signature)
    unverify_tx.crypto = Crypto.Value('SECP')

    signed_transaction = SignedTransaction()
    signed_transaction.transaction_with_sig.CopyFrom(unverify_tx)
    signed_transaction.tx_hash = sha3(unverify_tx.SerializeToString())
    pub = recover_pub(hex2bytes(privatekey))
    signed_transaction.signer = pub
    #print(binascii.hexlify(pub))

    return binascii.hexlify(signed_transaction.SerializeToString())
Ejemplo n.º 3
0
    def send_message(self, message_type):
        url = 'http://{}:{}/'.format(self.address,
                                     self.port)  # Set destination URL here
        message = Transaction()
        method = ''

        if message_type == 'balance_start':
            method = 'broadcast_tx_sync'
            message.balance_start.timestamp = int(time.time())
            message.balance_start.round_number = self.round

        elif message_type == 'balance':
            method = 'broadcast_tx_sync'
            message.balance.timestamp = int(time.time())
            message.balance.round_number = self.round
            for trade in self.last_trade_list:
                new_trade = message.balance.trades.add()
                new_trade.uuid = trade.uuid
                new_trade.order_id = trade.order_id
                new_trade.order_type = trade.order_type
                new_trade.volume = trade.volume
                new_trade.price = trade.price

        elif message_type == 'balance_end':
            method = 'broadcast_tx_sync'
            message.balance_end.timestamp = int(time.time())
            message.balance_end.round_number = self.round

        print("Sending message: {}".format(message))
        binarystring = message.SerializeToString()
        request = Request(
            url,
            json.dumps({
                "method":
                method,
                "params": [base64.b64encode(binarystring).decode('ascii')],
                "jsonrpc":
                "2.0",
                "id":
                "not_important"
            }).encode())
        result = urlopen(request, None, 10)
        print(result.read().decode())
Ejemplo n.º 4
0
def _sha3_secp256k1_deploy_data(current_height,
                                bytecode,
                                privatekey,
                                receiver=None):
    sender = get_sender(privatekey, False)
    if privatekey is None:
        temp = private_key()
        privkey = PrivateKey(hex2bytes(temp))
    else:
        privkey = PrivateKey(hex2bytes(privatekey))

    print(sender)
    nonce = get_nonce(sender)
    print("nonce is {}".format(nonce))

    tx = Transaction()
    tx.valid_until_block = current_height + 88
    tx.nonce = nonce
    tx.quota = 9999999
    if receiver is not None:
        tx.to = receiver
    tx.data = hex2bytes(bytecode)

    message = sha3(tx.SerializeToString())

    print("message: {}".format(message))
    sign_recover = privkey.ecdsa_sign_recoverable(message, raw=True)
    sig = privkey.ecdsa_recoverable_serialize(sign_recover)

    signature = binascii.hexlify(sig[0]) + binascii.hexlify(
        bytes(bytearray([sig[1]])))

    unverify_tx = UnverifiedTransaction()
    unverify_tx.transaction.CopyFrom(tx)
    unverify_tx.signature = hex2bytes(signature)
    unverify_tx.crypto = Crypto.Value('SECP')

    print("unverify_tx is {}".format(
        binascii.hexlify(unverify_tx.SerializeToString())))
    return binascii.hexlify(unverify_tx.SerializeToString())
Ejemplo n.º 5
0
    def on_deliver_tx(self, msg: RequestDeliverTx):
        tx = msg.tx
        try:
            transaction = Transaction.FromString(tx)
        except:
            res = Response()
            res.deliver_tx.code = 400
            return res

        if self.debug['deliver_tx']:
            print(transaction)

        descriptor, value = transaction.ListFields()[0]
        transaction_type = descriptor.name

        if transaction_type == 'balance_start' or transaction_type == 'balance':
            h = sha256(msg.tx).hexdigest()
            if h not in self.checked_txs_hashes:
                print(transaction_type, 'ignored', h)
                res = Response()
                res.deliver_tx.code = 0
                return res
            else:
                self.checked_txs_hashes.remove(h)

        if transaction.HasField('new_contract'):
            self.state["contracts"][self.bytes_to_string_uuid(
                transaction.new_contract.uuid)] = {
                    "public_key": transaction.new_contract.public_key.hex(),
                    "consumption": 0,
                    "production": 0,
                    "prediction_consumption": {},
                    "prediction_production": {},
                    "consumption_flexibility": {},
                    "production_flexibility": {},
                    "default_consumption_price": 0,
                    "default_production_price": 0,
                    "is_used": False
                }

        # self.contract[transaction.new_contract.uuid] = transaction.new_contract.public_key
        elif transaction.HasField('usage'):
            contract_uuid = self.bytes_to_string_uuid(
                transaction.usage.contract_uuid)
            # We need to have the maps in dictionary format.
            usage = json_format.MessageToDict(transaction.usage, False, True)

            self.state["contracts"][contract_uuid]["consumption"] = int(
                transaction.usage.consumption)
            self.state["contracts"][contract_uuid]["production"] = int(
                transaction.usage.production)

            self.state["contracts"][contract_uuid][
                "prediction_consumption"] = dict(
                    [time, int(value)]
                    for time, value in usage["prediction_consumption"].items())
            self.state["contracts"][contract_uuid][
                "prediction_production"] = dict(
                    [time, int(value)]
                    for time, value in usage["prediction_production"].items())

            self.state["contracts"][contract_uuid][
                "consumption_flexibility"] = dict(
                    [int(price), int(amount)] for price, amount in
                    usage["consumption_flexibility"].items())
            self.state["contracts"][contract_uuid][
                "production_flexibility"] = dict(
                    [int(price), int(amount)] for price, amount in
                    usage["production_flexibility"].items())

            self.state["contracts"][contract_uuid][
                "default_consumption_price"] = int(
                    usage["default_consumption_price"])
            self.state["contracts"][contract_uuid][
                "default_production_price"] = int(
                    usage["default_production_price"])

            self.state['contracts'][contract_uuid]['is_used'] = True

        elif transaction.HasField('close_contract'):
            uuid = self.bytes_to_string_uuid(transaction.close_contract.uuid)
            del (self.state['contracts'][uuid])

        elif transaction.HasField('balance_start'):
            if self.state["balance"]["mode"] == COLLECTING_MODE:
                if self.debug['deliver_tx']:
                    self.log("onBalanceStart")
                self.select_node()
                self.state["balance"]["mode"] = BALANCING_MODE
                self.run_balance()
                self.multiprocessing_que.put(
                    ["balance_start", self.last_trade_list])
                if self.public_key == self.current_node_id:
                    self.pending_changes.append("balance")

        elif transaction.HasField('balance'):
            if self.debug['deliver_tx']:
                self.log("onBalance")
            if self.public_key == self.current_node_id:
                self.pending_changes.append("balance_end")

        elif transaction.HasField('balance_end'):
            if self.debug['deliver_tx']:
                self.log("onBalanceEnd")

            self.state["balance"]["round"] += 1

            self.multiprocessing_que.put(
                ["balance_end", self.state["balance"]["round"]])

            self.state["balance"]["mode"] = COLLECTING_MODE
            self.last_balance_timestamp = int(time.time())

        else:
            res = Response()
            res.deliver_tx.code = 400
            return res

        res = Response()
        res.deliver_tx.code = 0

        type_tag = res.deliver_tx.tags.add()
        type_tag.key = 'type'
        type_tag.value_string = transaction_type

        return res
Ejemplo n.º 6
0
    def on_check_tx(self, msg: RequestCheckTx):
        tx = msg.tx
        try:
            transaction = Transaction.FromString(tx)
        except Exception as e:
            print('check_tx decode error:', e)
            res = Response()
            res.check_tx.code = 400
            return res
        if self.debug['check_tx']:
            print(transaction)

        descriptor, value = transaction.ListFields()[0]
        transaction_type = descriptor.name
        if signed_types.count(transaction_type) > 0:
            if not self.check_signature(transaction_type, value):
                res = Response()
                res.check_tx.code = 401
                return res

        if transaction_type == 'new_contract':
            if self.bytes_to_string_uuid(transaction.new_contract.uuid
                                         ) in self.pending_state["contracts"]:
                res = Response()
                res.check_tx.code = 401
                return res

            self.pending_state["contracts"][self.bytes_to_string_uuid(
                value.uuid)] = {
                    "public_key": value.public_key.hex(),
                    "consumption": 0,
                    "production": 0
                }

        # todo: verify contractor_signature
        elif transaction.HasField('usage'):
            if self.bytes_to_string_uuid(
                    transaction.usage.contract_uuid
            ) not in self.pending_state["contracts"] or self.state["balance"][
                    "mode"] != COLLECTING_MODE:
                res = Response()
                res.check_tx.code = 401
                return res

            self.pending_state["contracts"][self.bytes_to_string_uuid(
                transaction.usage.contract_uuid
            )]["consumption"] = transaction.usage.consumption
            self.pending_state["contracts"][self.bytes_to_string_uuid(
                transaction.usage.contract_uuid
            )]["production"] = transaction.usage.production

        elif transaction.HasField('close_contract'):
            if self.bytes_to_string_uuid(transaction.close_contract.uuid
                                         ) not in self.state['contracts']:
                res = Response()
                res.check_tx.code = 401
                return res

        elif transaction.HasField('balance_start'):
            if self.state["balance"][
                    "mode"] != COLLECTING_MODE or transaction.balance_start.round_number != self.state[
                        "balance"]["round"]:
                self.log("onCheckBalanceStart: Reject invalid mode")
                res = Response()
                res.check_tx.code = 401
                return res
            if self.debug['check_tx']:
                self.log("onCheckBalanceStart: Accept")
            self.checked_txs_hashes.append(sha256(msg.tx).hexdigest())

        elif transaction.HasField('balance'):
            if self.state["balance"][
                    "mode"] != BALANCING_MODE or transaction.balance.round_number != self.state[
                        "balance"]["round"]:
                self.log("onCheckBalance: Reject invalid mode")
                res = Response()
                res.check_tx.code = 401
                return res
            else:
                for (received_trade, trade) in zip(transaction.balance.trades,
                                                   self.last_trade_list):
                    attributes = operator.attrgetter('uuid', 'order_id',
                                                     'order_type', 'volume',
                                                     'price')
                    new_trade = Trade(*attributes(received_trade))
                    if new_trade != trade:
                        self.log("onCheckBalance: Reject invalid trade")
                        res = Response()
                        res.check_tx.code = 401
                        return res
            if self.debug['check_tx']:
                self.log("onCheckBalance: Accept")
            self.checked_txs_hashes.append(sha256(msg.tx).hexdigest())

        elif transaction.HasField('balance_end'):
            if self.state["balance"][
                    "mode"] != BALANCING_MODE or transaction.balance_end.round_number != self.state[
                        "balance"]["round"]:
                self.log("onCheckBalanceEnd: Reject invalid mode")
                res = Response()
                res.check_tx.code = 401
                return res
            if self.debug['check_tx']:
                self.log("onCheckBalanceEnd: Accept")
        else:
            res = Response()
            res.check_tx.code = 400
            return res

        res = Response()
        res.check_tx.code = 0
        return res