def _send_healthcare_txn(self, txn_key, batch_key, inputs, outputs, payload, wait,
                             auth_user, auth_password):

        txn_header_bytes, signature = self._transaction_header(txn_key, inputs, outputs, payload)

        txn = Transaction(
            header=txn_header_bytes,
            header_signature=signature,
            payload=payload.SerializeToString()
        )

        transactions = [txn]

        batch_header_bytes, signature = self._batch_header(batch_key, transactions)

        batch = Batch(
            header=batch_header_bytes,
            header_signature=signature,
            transactions=transactions
        )

        batch_list = BatchList(batches=[batch])
        batch_id = batch_list.batches[0].header_signature

        if wait and wait > 0:
            wait_time = 0
            start_time = time.time()
            response = self._send_request(
                "batches", batch_list.SerializeToString(),
                'application/octet-stream',
                auth_user=auth_user,
                auth_password=auth_password)
            while wait_time < wait:
                status = self._get_status(
                    batch_id,
                    wait - int(wait_time),
                    auth_user=auth_user,
                    auth_password=auth_password)
                wait_time = time.time() - start_time

                if status != 'PENDING':
                    return response

            return response

        return self._send_request(
            "batches", batch_list.SerializeToString(),
            'application/octet-stream',
            auth_user=auth_user,
            auth_password=auth_password)
Ejemplo n.º 2
0
    def _wrap_and_send(self,
                       action,
                       kycCategoryAddress,
                       *values):

        # Generate a csv utf-8 encoded string as payload
        rawPayload = action

        for val in values:
            rawPayload = "$".join([rawPayload, str(val), str(kycCategoryAddress)])

        payload = rawPayload.encode()

        # Construct the address where we'll store our state
        address = self._address + _hash(KYC_CATEGORY.encode('utf-8'))[0:6] + _hash(kycCategoryAddress.encode('utf-8'))[0:58]
        inputAddressList = [address]
        outputAddressList = [address]

        # Create a TransactionHeader
        header = TransactionHeader(
            signer_public_key=self._publicKey,
            family_name=FAMILY_NAME,
            family_version="1.0",
            inputs=inputAddressList,
            outputs=outputAddressList,
            dependencies=[],
            payload_sha512=_hash(payload),
            batcher_public_key=self._publicKey,
            nonce=time.time().hex().encode()
        ).SerializeToString()

        # Create a Transaction from the header and payload above
        transaction = Transaction(
            header=header,
            payload=payload,
            header_signature=self._signer.sign(header)
        )

        transactionList = [transaction]

        # Create a BatchHeader from transactionList above
        header = BatchHeader(
            signer_public_key=self._publicKey,
            transaction_ids=[txn.header_signature for txn in transactionList]
        ).SerializeToString()

        #Create Batch using the BatchHeader and transactionList above
        batch = Batch(
            header=header,
            transactions=transactionList,
            header_signature=self._signer.sign(header))

        #Create a Batch List from Batch above
        batch_list = BatchList(batches=[batch])

        # Send batch_list to rest-api
        return self._send_to_restapi(
            "batches",
            batch_list.SerializeToString(),
            'application/octet-stream')
Ejemplo n.º 3
0
    def bat_gen(self, txns: TransactionList) -> bytes:
        """ Generates a valid batch for testing submissions,
        optional arguments are for payment transactions.

        Args:
            :arg txns: the list of transactions to be included
        Returns:
            :arg batch_list: A serialized BatchList

        """
        Transactions = [txn.header_signature for txn in txns.transactions]

        batch_header = BatchHeader(
            signer_public_key=self.signer.get_public_key().as_hex(),
            transaction_ids=Transactions)

        # encode batch header
        batch_header_bytes = batch_header.SerializeToString()

        # sign batch header
        batch_signature_hex = self.signer.sign(batch_header_bytes)

        # build the batch
        batch = Batch(header=batch_header_bytes,
                      header_signature=batch_signature_hex,
                      transactions=[txn for txn in txns.transactions])

        batch_list = BatchList(batches=[batch])
        # return the batch and the header signatures of the transactions
        # included
        return batch_list.SerializeToString()
Ejemplo n.º 4
0
    def _wrap_and_send(self, action, *values):
        '''Erstellt eine Transaktion, verpackt sie in ein Batch
        '''

        # Generate a csv utf-8 encoded string as payload
        rawPayload = action

        for val in values:
            rawPayload = ",".join([rawPayload, str(val)])

        payload = rawPayload.encode()

        # Construct the address where we'll store our state
        address = self._address
        inputAddressList = [address]
        outputAddressList = [address]

        if "transfer" == action:
            toAddress = _hash(FAMILY_NAME.encode('utf-8'))[0:6] + \
            _hash(values[1].encode('utf-8'))[0:64]
            inputAddressList.append(toAddress)
            outputAddressList.append(toAddress)

        # Create a TransactionHeader
        header = TransactionHeader(
            signer_public_key=self._publicKey,
            family_name=FAMILY_NAME,
            family_version="1.0",
            inputs=inputAddressList,
            outputs=outputAddressList,
            dependencies=[],
            payload_sha512=_hash(payload),
            batcher_public_key=self._publicKey,
            nonce=random.random().hex().encode()).SerializeToString()

        # Create a Transaction from the header and payload above
        transaction = Transaction(header=header,
                                  payload=payload,
                                  header_signature=self._signer.sign(header))

        transactionList = [transaction]

        # Create a BatchHeader from transactionList above
        header = BatchHeader(
            signer_public_key=self._publicKey,
            transaction_ids=[txn.header_signature
                             for txn in transactionList]).SerializeToString()

        #Create Batch using the BatchHeader and transactionList above
        batch = Batch(header=header,
                      transactions=transactionList,
                      header_signature=self._signer.sign(header))

        #Create a Batch List from Batch above
        batch_list = BatchList(batches=[batch])

        # Send batch_list to rest-api
        return self._send_to_restapi("batches", batch_list.SerializeToString(),
                                     'application/octet-stream')
Ejemplo n.º 5
0
    def _wrap_and_send(self, buyer, seller, house, wait=None):
        """
        Create a transaction, then wrap it in a batch.
        Even single transactions must be wrapped into a batch.
        """

        # Generate a CSV UTF-8 encoded string as the payload.
        raw_payload = "{".join([buyer, seller, house])
        payload = raw_payload.encode()  # Convert Unicode to bytes

        # Construct the address where we'll store our state.
        # We just have one input and output address (the same one).
        input_and_output_address_list = [self._address]

        # Create a TransactionHeader.
        header = TransactionHeader(
            signer_public_key=self._public_key,
            family_name=FAMILY_NAME,
            family_version="1.0",
            inputs=input_and_output_address_list,
            outputs=input_and_output_address_list,
            dependencies=[],
            payload_sha512=_hash(payload),
            batcher_public_key=self._public_key,
            nonce=random.random().hex().encode()
        ).SerializeToString()

        # Create a Transaction from the header and payload above.
        transaction = Transaction(
            header=header,
            payload=payload,
            header_signature=self._signer.sign(header)
        )

        transaction_list = [transaction]

        # Create a BatchHeader from transaction_list above.
        header = BatchHeader(
            signer_public_key=self._public_key,
            transaction_ids=[txn.header_signature for txn in transaction_list]
        ).SerializeToString()

        # Create Batch using the BatchHeader and transaction_list above.
        batch = Batch(
            header=header,
            transactions=transaction_list,
            header_signature=self._signer.sign(header))

        # Create a Batch List from Batch above
        batch_list = BatchList(batches=[batch])
        batch_id = batch_list.batches[0].header_signature

        # Send batch_list to the REST API
        result = self._send_to_rest_api("batches",
                                        batch_list.SerializeToString(),
                                        'application/octet-stream')

        # Wait until transaction status is COMMITTED, error, or timed out
        return self._wait_for_status(batch_id, wait, result)
Ejemplo n.º 6
0
    def _wrap_and_send(self,
                       action,
                       data,
                       input_and_output_address_list,
                       wait=None):
        '''Create a transaction, then wrap it in a batch.

           Even single transactions must be wrapped into a batch.
           Called by all submission methods.
        '''

        # Assemble an action and the actual payload in a dictionary
        transactionDictionary = {'Action': action, 'Payload': data}

        payload = cbor.dumps(transactionDictionary)

        # Create a TransactionHeader.
        header = TransactionHeader(
            signer_public_key=self._public_key,
            family_name=FAMILY_NAME,
            family_version="1.0",
            inputs=input_and_output_address_list,
            outputs=input_and_output_address_list,
            dependencies=[],
            payload_sha512=_hash(payload),
            batcher_public_key=self._public_key,
            nonce=random.random().hex().encode()).SerializeToString()

        # Create a Transaction from the header and payload above.
        transaction = Transaction(header=header,
                                  payload=payload,
                                  header_signature=self._signer.sign(header))

        transaction_list = [transaction]

        # Create a BatchHeader from transaction_list above.
        header = BatchHeader(
            signer_public_key=self._public_key,
            transaction_ids=[txn.header_signature
                             for txn in transaction_list]).SerializeToString()

        # Create Batch using the BatchHeader and transaction_list above.
        batch = Batch(header=header,
                      transactions=transaction_list,
                      header_signature=self._signer.sign(header))

        # Create a Batch List from Batch above
        batch_list = BatchList(batches=[batch])
        batch_id = batch_list.batches[0].header_signature

        # Send batch_list to the REST API
        result = self._send_to_rest_api("batches",
                                        batch_list.SerializeToString(),
                                        'application/octet-stream')

        # Wait until transaction status is COMMITTED, error, or timed out
        return self._wait_for_status(batch_id, wait, result)
Ejemplo n.º 7
0
def wrap_and_send(action, data='', wait=None):
        # Generate a CSV UTF-8 encoded string as the payload.
        raw_payload = ",".join([action,data])
        payload = raw_payload # Convert Unicode to bytes
        
        # Construct the address where we'll store our state.
        # We just have one input and output address (the same one).
        input_and_output_address_list = [namespace]

        # Create a TransactionHeader.
        header = TransactionHeader(
            signer_public_key=public_key,
            family_name="bidding",
            family_version="1.0",
            inputs=input_and_output_address_list,
            outputs=input_and_output_address_list,
            dependencies=[],
            payload_sha512=hash(payload),
            batcher_public_key=public_key,
            nonce=random.random().hex().encode()
        ).SerializeToString()

        # Create a Transaction from the header and payload above.
        transaction = Transaction(
            header=header,
            payload=payload.encode(),
            header_signature=signer.sign(header)
        )

        transaction_list = [transaction]

        # Create a BatchHeader from transaction_list above.
        header = BatchHeader(
            signer_public_key=public_key,
            transaction_ids=[txn.header_signature for txn in transaction_list]
        ).SerializeToString()

        # Create Batch using the BatchHeader and transaction_list above.
        batch = Batch(
            header=header,
            transactions=transaction_list,
            header_signature=signer.sign(header))

        # Create a Batch List from Batch above
        batch_list = BatchList(batches=[batch])
        batch_id = batch_list.batches[0].header_signature

        # Send batch_list to the REST API
        result = send_to_rest_api("batches",
                                       batch_list.SerializeToString(),
                                       'application/octet-stream')

        # Wait until transaction status is COMMITTED, error, or timed out
        return wait_for_status(batch_id, wait, result)
Ejemplo n.º 8
0
    def _wrap_and_send(self, *values):
        payload = ",".join(values)
        print(" Payload ")
        print(payload)
        # Construct the address where we'll store our state
        address = self._address
        inputAddressList = [address]
        outputAddressList = [address]

        if "transfer" == values[0]:
            toAddress = get_wallet_address(values[2])
            inputAddressList.append(toAddress)
            outputAddressList.append(toAddress)
            print("Inside the block")

        # Create a TransactionHeader
        header = TransactionHeader(
            signer_public_key=self._publicKey,
            family_name=FAMILY_NAME,
            family_version="1.0",
            inputs=inputAddressList,
            outputs=outputAddressList,
            dependencies=[],
            payload_sha512=hashlib.sha512(payload.encode()).hexdigest(),
            batcher_public_key=self._publicKey,
            nonce=random.random().hex().encode()).SerializeToString()

        # Create a Transaction from the header and payload above
        transaction = Transaction(header=header,
                                  payload=payload.encode(),
                                  header_signature=self._signer.sign(header))

        transactionList = [transaction]

        # Create a BatchHeader from transactionList above
        header = BatchHeader(
            signer_public_key=self._publicKey,
            transaction_ids=[txn.header_signature
                             for txn in transactionList]).SerializeToString()

        # Create Batch using the BatchHeader and transactionList above
        batch = Batch(header=header,
                      transactions=transactionList,
                      header_signature=self._signer.sign(header))

        # Create a Batch List from Batch above
        batch_list = BatchList(batches=[batch])
        batch_id = batch_list.batches[0].header_signature
        print(batch_id)

        # Send batch_list to rest-api
        return self._send_to_restapi("batches", batch_list.SerializeToString(),
                                     'application/octet-stream')
def wrap_and_send(action,
                  data,
                  input_address_list,
                  output_address_list,
                  wait=None):
    '''Create a transaction, then wrap it in a batch.
    '''
    payload = ",".join([action, str(data)])
    logging.info('payload: {}'.format(payload))

    # Construct the address where we'll store our state.
    # Create a TransactionHeader.
    header = TransactionHeader(
        signer_public_key=public_key,
        family_name=family_name,
        family_version="1.0",
        inputs=input_address_list,  # input_and_output_address_list,
        outputs=output_address_list,  # input_and_output_address_list,
        dependencies=[],
        payload_sha512=hash(payload),
        batcher_public_key=public_key,
        nonce=random.random().hex().encode()).SerializeToString()

    # Create a Transaction from the header and payload above.
    transaction = Transaction(
        header=header,
        payload=payload.encode(),  # encode the payload
        header_signature=signer.sign(header))

    transaction_list = [transaction]

    # Create a BatchHeader from transaction_list above.
    header = BatchHeader(signer_public_key=public_key,
                         transaction_ids=[
                             txn.header_signature for txn in transaction_list
                         ]).SerializeToString()

    # Create Batch using the BatchHeader and transaction_list above.
    batch = Batch(header=header,
                  transactions=transaction_list,
                  header_signature=signer.sign(header))

    # Create a Batch List from Batch above
    batch_list = BatchList(batches=[batch])
    batch_id = batch_list.batches[0].header_signature
    # Send batch_list to the REST API
    result = send_to_rest_api("batches", batch_list.SerializeToString(),
                              'application/octet-stream')

    # Wait until transaction status is COMMITTED, error, or timed out
    return wait_for_status(batch_id, result, wait=wait)
Ejemplo n.º 10
0
    def encode(self, batches):
        """Wraps one or more Batch messages in a BatchList and serializes it
        for transmission to a validator.

        Args:
            batches (list of Batch or Batch): The Batch or Batches to wrap in
                a BatchList

        Returns:
            bytes: a serialized BatchList
        """
        batches = _listify(batches)
        batch_list = BatchList(batches=batches)
        return batch_list.SerializeToString()
Ejemplo n.º 11
0
    def _wrap_and_send(self,address,action, amount, wait=None,uaddress=''):
        '''
        create and send transactions in batches  
        '''
        raw_payload = ",".join([action, str(amount)])
        payload = raw_payload.encode()
        input_and_output_address_list=[]
        if uaddress=='':
            input_and_output_address_list = [address]
        else:
            input_and_output_address_list=[address,uaddress]    
        header = TransactionHeader(
            signer_public_key=self._public_key,
            family_name=FAMILY_NAME,
            family_version="1.0",
            inputs=input_and_output_address_list,
            outputs=input_and_output_address_list,
            dependencies=[],
            payload_sha512=_hash(payload),
            batcher_public_key=self._public_key,
            nonce=random.random().hex().encode()
        ).SerializeToString()

        transaction = Transaction(
            header=header,
            payload=payload,
            header_signature=self._signer.sign(header)
        )

        transaction_list = [transaction]

        header = BatchHeader(
            signer_public_key=self._public_key,
            transaction_ids=[txn.header_signature for txn in transaction_list]
        ).SerializeToString()

        batch = Batch(
            header=header,
            transactions=transaction_list,
            header_signature=self._signer.sign(header))

        batch_list = BatchList(batches=[batch])
        batch_id = batch_list.batches[0].header_signature

        result = self._send_to_rest_api("batches",
                                       batch_list.SerializeToString(),
                                       'application/octet-stream')

        return self._wait_for_status(batch_id, wait, result)
Ejemplo n.º 12
0
    def _wrap_and_send(self, action, value):

        # Generate a csv utf-8 encoded string as payload
        payload = ",".join([action, str(value)]).encode()

        # Construct the address where we'll store our state
        address = self._address

        # Create a TransactionHeader
        header = TransactionHeader(
            signer_public_key=self._publicKey,
            family_name=FAMILY_NAME,
            family_version="1.0",
            inputs=[address],
            outputs=[address],
            dependencies=[],
            payload_sha512=_hash(payload),
            batcher_public_key=self._publicKey,
            nonce=time.time().hex().encode()).SerializeToString()

        # Create a Transaction from the header and payload above
        transaction = Transaction(header=header,
                                  payload=payload,
                                  header_signature=self._signer.sign(header))

        transactionList = [transaction]

        # Create a BatchHeader from TransactionList above
        header = BatchHeader(
            signer_public_key=self._publicKey,
            transaction_ids=[txn.header_signature
                             for txn in transactionList]).SerializeToString()

        #Create Batch using the BatchHeader and transactionList above
        batch = Batch(header=header,
                      transactions=transactionList,
                      header_signature=self._signer.sign(header))

        #Create a Batch List from Batch above
        batch_list = BatchList(batches=[batch])

        # Create a batch id
        # batch_id = batch_list.batches[0].header_signature

        # Send batch_list to rest-api
        return self._send_to_restapi("batches", batch_list.SerializeToString(),
                                     'application/octet-stream')
Ejemplo n.º 13
0
    def wrap_and_send(self, data_dict):
        # rawPayload = action
        # for val in values:
        #     rawPayload = ",".join([rawPayload, str(val)])

        payload = json.dumps(data_dict).encode()

        address = self._address
        inputAddressList = [address]
        outputAddressList = [address]

        header = TransactionHeader(
            signer_public_key=self._publicKey,
            family_name=FAMILY_NAME,
            family_version="1.0",
            inputs=inputAddressList,
            outputs=outputAddressList,
            dependencies=[],
            payload_sha512=_hash(payload),
            batcher_public_key=self._publicKey,
            nonce=time.time().hex().encode()
        ).SerializeToString()

        transaction = Transaction(
            header=header,
            payload=payload,
            header_signature=self._signer.sign(header)
        )

        transactionList = [transaction]

        header = BatchHeader(
            signer_public_key=self._publicKey,
            transaction_ids=[txn.header_signature for txn in transactionList]
        ).SerializeToString()

        batch = Batch(
            header=header,
            transactions=transactionList,
            header_signature=self._signer.sign(header))

        batch_list = BatchList(batches=[batch])
        return self._send_to_restapi(
            "batches",
            batch_list.SerializeToString(),
            'application/octet-stream')
Ejemplo n.º 14
0
    def construct_payload_and_send(self, action, amount, wait_time=None):
        raw_payload = ",".join([action, str(amount)])
        input_and_output_address_list = [self._address]
        print(self._address)
        header = TransactionHeader(
            signer_public_key=self._public_key,
            family_name=constants.FAMILY_NAME,
            family_version="1.0",
            inputs=input_and_output_address_list,
            outputs=input_and_output_address_list,
            dependencies=[],
            payload_sha512=generate_hash(raw_payload),
            batcher_public_key=self._public_key,
            nonce=random.random().hex().encode()
        ).SerializeToString()

        transaction = Transaction(
            header=header,
            payload=raw_payload.encode(),
            header_signature=self._signer.sign(header)
        )

        transaction_list = [transaction]
        header = BatchHeader(
            signer_public_key=self._public_key,
            transaction_ids=[txn.header_signature for txn in transaction_list]
        ).SerializeToString()

        batch = Batch(
            header=header,
            transactions=transaction_list,
            header_signature=self._signer.sign(header))

        batch_list = BatchList(batches=[batch])
        batch_id = batch_list.batches[0].header_signature
        print(batch_id)
        result = self.talk_to_validator("batches",
                                        batch_list.SerializeToString(),
                                        'application/octet-stream')
        # Wait until transaction status is COMMITTED, error, or timed out

        return self._wait_for_status(batch_id, wait_time, result)
Ejemplo n.º 15
0
    def create_batch(self, transactions):
        # Transactions have a header_signature;
        # TpProcessRequests have a signature
        try:
            txn_signatures = [txn.header_signature for txn in transactions]
        except AttributeError:
            txn_signatures = [txn.signature for txn in transactions]

        header = BatchHeader(
            signer_public_key=self._signer.get_public_key().as_hex(),
            transaction_ids=txn_signatures).SerializeToString()

        signature = self._signer.sign(header)

        batch = Batch(header=header,
                      transactions=transactions,
                      header_signature=signature)

        batch_list = BatchList(batches=[batch])

        return batch_list.SerializeToString()
Ejemplo n.º 16
0
def submit_omi_transaction(base_url,
                           private_key,
                           action,
                           message_type,
                           natural_key_field,
                           omi_obj,
                           additional_inputs=None):
    obj = message_type(**omi_obj)

    if additional_inputs is None:
        additional_inputs = []

    public_key_hex = signing.generate_pubkey(private_key)

    address = get_object_address(omi_obj[natural_key_field],
                                 TAG_MAP[message_type])

    data = obj.SerializeToString()

    payload = OMITransactionPayload(
        action=action,
        data=data,
    )

    payload_bytes = payload.SerializeToString()
    payload_sha512 = hashlib.sha512(payload_bytes).hexdigest()

    txn_header = TransactionHeader(
        batcher_pubkey=public_key_hex,
        family_name=FAMILY_NAME,
        family_version='1.0',
        inputs=[address] + additional_inputs,
        outputs=[address],
        nonce=str(randint(0, 1000000000)),
        payload_encoding='application/protobuf',
        payload_sha512=payload_sha512,
        signer_pubkey=public_key_hex,
    )
    txn_header_bytes = txn_header.SerializeToString()

    key_handler = signing.secp256k1_signer._decode_privkey(private_key)

    # ecdsa_sign automatically generates a SHA-256 hash
    txn_signature = key_handler.ecdsa_sign(txn_header_bytes)
    txn_signature_bytes = key_handler.ecdsa_serialize_compact(txn_signature)
    txn_signature_hex = txn_signature_bytes.hex()

    # print([txn_signature_hex])

    txn = Transaction(
        header=txn_header_bytes,
        header_signature=txn_signature_hex,
        payload=payload_bytes,
    )

    batch_header = BatchHeader(
        signer_pubkey=public_key_hex,
        transaction_ids=[txn.header_signature],
    )

    batch_header_bytes = batch_header.SerializeToString()

    batch_signature = key_handler.ecdsa_sign(batch_header_bytes)
    batch_signature_bytes = key_handler.ecdsa_serialize_compact(
        batch_signature)
    batch_signature_hex = batch_signature_bytes.hex()

    batch = Batch(
        header=batch_header_bytes,
        header_signature=batch_signature_hex,
        transactions=[txn],
    )

    batch_list = BatchList(batches=[batch])
    batch_bytes = batch_list.SerializeToString()

    batch_id = batch_signature_hex

    url = "%s/batches" % base_url
    headers = {
        'Content-Type': 'application/octet-stream',
    }
    r = requests.post(url, data=batch_bytes, headers=headers)
    r.raise_for_status()
    link = r.json()['link']
    return BatchStatus(batch_id, link)
    def _wrap_and_send(self, payload_data, wait=None):
        """
        Create a transaction, then wrap it in a batch.
        Even single transactions must be wrapped into a batch.
        Called by create() and check().
        """
        transaction_list = []

        # Create a transaction list from payload data
        for data in payload_data:
            # Construct the address where we'll store our state.
            # We just have one input and output address (the same one).
            product_id = data["Id"]
            # generate product address hash with Id
            product_address = addresser.get_product_address(product_id)

            # if product already exist with this ID, go next
            # TODO: remove in final version
            if self.is_product_already_exist(product_address):
                logger.info("product already exists")
                continue

            # create proto-buff object and encode data
            payload = payload_pb2.ProductInfoPayload(**data)
            payload_bytes = payload.SerializeToString()

            # Create a TransactionHeader.
            header = TransactionHeader(
                signer_public_key=self._public_key,
                family_name=FAMILY_NAME,
                family_version=FAMILY_VERSION,
                inputs=[product_address],
                outputs=[product_address],
                dependencies=[],
                payload_sha512=_hash(payload_bytes),
                batcher_public_key=self._public_key,
                nonce=random.random().hex().encode()
            ).SerializeToString()

            # Create a Transaction from the header and payload above.
            transaction = Transaction(
                header=header,
                payload=payload_bytes,
                header_signature=self._signer.sign(header)
            )
            # Append all transaction to transaction_list
            transaction_list.append(transaction)

        # Create a BatchHeader from transaction_list above.
        if len(transaction_list) == 0:
            logger.info("no transaction found. existing...")
            raise TransactionNotFound("Data Already exists.")

        header = BatchHeader(
            signer_public_key=self._public_key,
            transaction_ids=[txn.header_signature for txn in transaction_list]
        ).SerializeToString()

        # Create Batch using the BatchHeader and transaction_list above.
        batch = Batch(
            header=header,
            transactions=transaction_list,
            header_signature=self._signer.sign(header))

        # Create a Batch List from Batch above
        batch_list = BatchList(batches=[batch])
        batch_id = batch_list.batches[0].header_signature

        # Send batch_list to the REST API
        result = self._send_to_rest_api("batches",
                                        batch_list.SerializeToString(),
                                        'application/octet-stream')

        # # Wait until transaction status is COMMITTED, error, or timed out
        return self._wait_for_status(batch_id, wait, result)
Ejemplo n.º 18
0
    def write_bc(self, family_name, args, wait=10):
        '''Create a transaction, then wrap it in a batch.

           Even single transactions must be wrapped into a batch.
        '''
        self.init_bc(family_name=family_name)
        _logger.info(
            'Wrapping and sending to blockchain with TP {} and Public Key {}'.
            format(self._family_name, self._public_key))
        payload = str(json.dumps(args))

        payload = payload.encode()  # Convert Unicode to bytes

        # Construct the address where we'll store our state.
        # We just have one input and output address (the same one).
        input_and_output_address_list = [self._address]

        # Create a TransactionHeader.
        header = TransactionHeader(
            signer_public_key=self._public_key,
            family_name=self._family_name,
            family_version="1.0",
            inputs=input_and_output_address_list,
            outputs=input_and_output_address_list,
            dependencies=[],
            payload_sha512=_hash(payload),
            batcher_public_key=self._public_key,
            nonce=random.random().hex().encode()).SerializeToString()

        # Create a Transaction from the header and payload above.
        transaction = Transaction(header=header,
                                  payload=payload,
                                  header_signature=self._signer.sign(header))

        transaction_list = [transaction]

        # Create a BatchHeader from transaction_list above.
        header = BatchHeader(
            signer_public_key=self._public_key,
            transaction_ids=[txn.header_signature
                             for txn in transaction_list]).SerializeToString()

        # Create Batch using the BatchHeader and transaction_list above.
        batch = Batch(header=header,
                      transactions=transaction_list,
                      header_signature=self._signer.sign(header))

        # Create a Batch List from Batch above
        batch_list = BatchList(batches=[batch])
        batch_id = batch_list.batches[0].header_signature

        _logger.info('Transaction builded')
        # Send batch_list to the REST API
        result = self._send_to_rest_api(
            suffix="batches",
            data=batch_list.SerializeToString(),
            content_type='application/octet-stream',
            timeout=wait)
        _logger.info('Request sended')
        # Wait until transaction status is COMMITTED, error, or timed out
        return self._wait_for_status(batch_id, wait, result)
Ejemplo n.º 19
0
    def _wrap_and_send(self, action, amount, wait=None):
        '''Create a transaction, then wrap it in a batch.

           Even single transactions must be wrapped into a batch.
           Called by bake() and eat().
        '''
        amount=str(amount)
        
        amount=amount.replace('[','')
        amount=amount.replace(']','')


        print(amount)
        payload = str(amount).encode('utf-8')

        # Construct the address where we'll store our state.
        # We just have one input and output address (the same one).
        input_and_output_address_list = [self._address]

        # Create a TransactionHeader.
        header = TransactionHeader(
            signer_public_key=self._public_key,
            family_name=FAMILY_NAME,
            family_version="1.0",
            inputs=input_and_output_address_list,
            outputs=input_and_output_address_list,
            dependencies=[],
            payload_sha512=_hash(payload),
            batcher_public_key=self._public_key,
            nonce=random.random().hex().encode()
        ).SerializeToString()

        # Create a Transaction from the header and payload above.
        transaction = Transaction(
            header=header,
            payload=payload,
            header_signature=self._signer.sign(header)
        )

        transaction_list = [transaction]

        # Create a BatchHeader from transaction_list above.
        header = BatchHeader(
            signer_public_key=self._public_key,
            transaction_ids=[txn.header_signature for txn in transaction_list]
        ).SerializeToString()

        # Create Batch using the BatchHeader and transaction_list above.
        batch = Batch(
            header=header,
            transactions=transaction_list,
            header_signature=self._signer.sign(header))

        # Create a Batch List from Batch above
        batch_list = BatchList(batches=[batch])
        batch_id = batch_list.batches[0].header_signature

        # Send batch_list to the REST API
        result = self._send_to_rest_api("batches",
                                       batch_list.SerializeToString(),
                                       'application/octet-stream')
        
        filters = [events_pb2.EventFilter(key="address",
                                      match_string=
                                      TP_ADDRESS_PREFIX + ".*",
                                      filter_type=events_pb2.
                                      EventFilter.REGEX_ANY)]

        try:
            # To listen to all events, pass delta_filters=None :
            #listen_to_events(delta_filters=None)
            notification=listen_to_events(delta_filters=filters)
            #print(notification)
          
        except KeyboardInterrupt:
            pass
        except SystemExit as err:
            raise err
        except BaseException as err:
            traceback.print_exc(file=sys.stderr)
            sys.exit(1)
        
        # Wait until transaction status is COMMITTED, error, or timed out
        return self._wait_for_status(batch_id, wait, result),notification