Beispiel #1
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')
    async def submit_batches(self, request):
        """Accepts a binary encoded BatchList and submits it to the validator.

        Request:
            body: octet-stream BatchList of one or more Batches
        Response:
            status:
                 - 202: Batches submitted and pending
            link: /batches or /batch_statuses link for submitted batches

        """
        timer_ctx = self._post_batches_total_time.time()
        self._post_batches_count.inc()

        # Parse request
        if request.headers['Content-Type'] != 'application/octet-stream':
            LOGGER.debug('Submission headers had wrong Content-Type: %s',
                         request.headers['Content-Type'])
            self._post_batches_error.inc()
            raise errors.SubmissionWrongContentType()

        body = await request.read()
        if not body:
            LOGGER.debug('Submission contained an empty body')
            self._post_batches_error.inc()
            raise errors.NoBatchesSubmitted()

        try:
            batch_list = BatchList()
            batch_list.ParseFromString(body)
        except DecodeError:
            LOGGER.debug('Submission body could not be decoded: %s', body)
            self._post_batches_error.inc()
            raise errors.BadProtobufSubmitted()

        # Query validator
        error_traps = [
            error_handlers.BatchInvalidTrap, error_handlers.BatchQueueFullTrap
        ]
        validator_query = client_batch_submit_pb2.ClientBatchSubmitRequest(
            batches=batch_list.batches)

        with self._post_batches_validator_time.time():
            await self._query_validator(
                Message.CLIENT_BATCH_SUBMIT_REQUEST,
                client_batch_submit_pb2.ClientBatchSubmitResponse,
                validator_query, error_traps)

        # Build response envelope
        id_string = ','.join(b.header_signature for b in batch_list.batches)

        status = 202
        link = self._build_url(request, path='/batch_statuses', id=id_string)

        retval = self._wrap_response(request,
                                     metadata={'link': link},
                                     status=status)

        timer_ctx.stop()
        return retval
Beispiel #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()
Beispiel #4
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)
    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')
Beispiel #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)
Beispiel #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)
Beispiel #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)
Beispiel #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()
    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)
Beispiel #12
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)
Beispiel #13
0
    def _create_batch_list(self, transactions):
        """
        Create the list of batches that the client will send to the REST API

        Args:
            transactions (transaction): transaction(s) included in the batch

        Returns:
            BatchList: a list of batches to send to the REST API
        """
        transaction_signatures = [t.header_signature for t in transactions]

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

        signature = self._signer.sign(header)

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

        return BatchList(batches=[batch])
Beispiel #14
0
def banktransfer(family, input, pubpos, signer):
    txn_header_bytes = TransactionHeader(
        family_name=family,
        family_version='1.0',
        inputs=[input, pubpos],
        outputs=[input, pubpos],
        signer_public_key=signer.get_public_key().as_hex(),
        batcher_public_key=signer.get_public_key().as_hex(),
        dependencies=[],
        payload_sha512=sha512(payload_bytes).hexdigest()).SerializeToString()
    signature = signer.sign(txn_header_bytes)

    txn = Transaction(header=txn_header_bytes,
                      header_signature=signature,
                      payload=payload_bytes)
    txns = [txn]

    batch_header_bytes = BatchHeader(
        signer_public_key=signer.get_public_key().as_hex(),
        transaction_ids=[txn.header_signature for txn in txns],
    ).SerializeToString()

    signature = signer.sign(batch_header_bytes)

    batch = Batch(header=batch_header_bytes,
                  header_signature=signature,
                  transactions=txns)
    batch_list_bytes = BatchList(batches=[batch]).SerializeToString()
    return batch_list_bytes
Beispiel #15
0
    def submit(self):
        batch_header_bytes = BatchHeader(
            signer_public_key=self.signer.get_public_key().as_hex(),
            transaction_ids=[t.header_signature for t in self._transactions],
        ).SerializeToString()

        signature = self.signer.sign(batch_header_bytes)

        batch = Batch(
            header=batch_header_bytes,
            header_signature=signature,
            transactions=self._transactions
        )

        batch_list_bytes = BatchList(batches=[batch]).SerializeToString()
        resp = requests.post(
            url='http://localhost:8008/batches',
            data=batch_list_bytes,
            headers={
                'Content-Type': 'application/octet-stream'
            }
        )
        resp_data = resp.json()
        print(json.dumps(resp_data, indent=4))

        if 'link' in resp_data:
            self.poll_status(resp_data['link'])
Beispiel #16
0
def submit_batch(transactions: []) -> dict:
    """
    Submits a batch, returning the JSON return value from the Sawtooth API
    :param transactions:
    :return:
    """

    transactions = as_list(transactions)

    batch_header_bytes = BatchHeader(
        signer_public_key=_signer.get_public_key().as_hex(),
        transaction_ids=[t.header_signature for t in transactions],
    ).SerializeToString()

    signature = _signer.sign(batch_header_bytes)
    batch = Batch(header=batch_header_bytes,
                  header_signature=signature,
                  transactions=transactions)

    batch_list_bytes = BatchList(batches=[batch]).SerializeToString()
    resp = _post("/batches", batch_list_bytes)
    resp_data = resp.json()
    print(json.dumps(resp_data, indent=4))

    return resp_data
Beispiel #17
0
def make_BCMCS_transaction(signer, payload):
    payload_bytes = cbor.dumps(payload)

    # sha512('bcmcs'.encode('utf-8')).hexdigest()[0:6] == 'e92c0c'
    txn_header_bytes = TransactionHeader(
        family_name='bcmcs',
        family_version='1.0',
        inputs=['e92c0c'],
        outputs=['e92c0c'],
        signer_public_key=signer.get_public_key().as_hex(),
        batcher_public_key=signer.get_public_key().as_hex(),
        dependencies=[],
        payload_sha512=sha512(payload_bytes).hexdigest()).SerializeToString()

    signature = signer.sign(txn_header_bytes)

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

    txns = [txn]

    batch_header_bytes = BatchHeader(
        signer_public_key=signer.get_public_key().as_hex(),
        transaction_ids=[txn.header_signature for txn in txns],
    ).SerializeToString()

    signature = signer.sign(batch_header_bytes)

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

    batch_list_bytes = BatchList(batches=[batch]).SerializeToString()
    return batch_list_bytes
Beispiel #18
0
    def main(self):
        print('Generating Addresses...', end='', flush=True)
        # Generate an Address for the new Certificate.
        certificate_address = addresser.make_certificate_address(
            self._certificate_identifier.encode())

        print('[OK]')

        print('Generating Payload...', end='', flush=True)
        # Create and encode the payload.
        payload = self._make_payload()
        encoded_payload = cbor.dumps(payload)
        print('[OK]')

        # Create Transaction.
        transaction = utils.make_transaction(encoded_payload,
                                             self._transaction_signer,
                                             [certificate_address],
                                             [certificate_address])

        # Create Batch.
        batch = utils.make_batch(transaction, self._transaction_signer)
        batch_list = BatchList(batches=[batch]).SerializeToString()

        # Submit new Batch.
        link = utils.submit_batch(batch_list)

        print('identifier:', self._certificate_identifier)
        print('Status:')
        print(link)
Beispiel #19
0
    def _create_batch_list(self, transactions):
        """
        Helps create a batch list to be transmitted to the ledger.
        
        Args:
            transactions (list of Transaction): List containing transaction IDs
        
        Returns:
            type: BatchList
            BatchList object where each batch in the list are constructed in
            the function. 
            
        """
        transaction_signatures = [t.header_signature for t in transactions]

        header = BatchHeader(
            signer_public_key=self._public_key,
            transaction_ids=transaction_signatures).SerializeToString()

        signature = CryptoFactory(create_context("secp256k1")) \
            .new_signer(Secp256k1PrivateKey.from_hex(self._private_key)) \
            .sign(header)

        batch = Batch(header=header,
                      transactions=transactions,
                      header_signature=signature)
        return BatchList(batches=[batch])
Beispiel #20
0
def wrap_payload_in_txn_batch(txn_key, payload, header, batch_key):
    """Takes the serialized RBACPayload and creates a batch_list, batch
    signature tuple.
    Args:
        txn_key (sawtooth_signing.Signer): The txn signer's key pair.
        payload (bytes): The serialized RBACPayload.
        header (bytes): The serialized TransactionHeader.
        batch_key (sawtooth_signing.Signer): The batch signer's key pair.
    Returns:
        tuple
            The zeroth element is a BatchList, and the first element is
            the batch header_signature.
    """

    transaction = transaction_pb2.Transaction(
        payload=payload, header=header, header_signature=txn_key.sign(header))

    transaction_ids = [transaction.header_signature]
    logging.info(f"This is the transaction id {transaction_ids}")
    batch_header = batch_pb2.BatchHeader(
        signer_public_key=batch_key.get_public_key().as_hex(),
        transaction_ids=[transaction.header_signature]).SerializeToString()

    batch = batch_pb2.Batch(header=batch_header,
                            header_signature=batch_key.sign(batch_header),
                            transactions=[transaction])

    batch_list_bytes = BatchList(batches=[batch]).SerializeToString()
    return transaction_ids, [batch], batch.header_signature, batch_list_bytes
Beispiel #21
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')
Beispiel #22
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')
Beispiel #23
0
def create_batchlist(batch):
    """
    In order to submit Batches to the validator, they must be collected into a BatchList.
    Multiple batches can be submitted in one BatchList, though the Batches themselves don’t
    necessarily need to depend on each other. Unlike Batches, a BatchList is not atomic.
    Batches from other clients may be interleaved with yours.
    """
    batch_list_bytes = BatchList(batches=[batch]).SerializeToString()
    return batch_list_bytes
    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)
Beispiel #25
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()
def gogogox(todo, amount, account_no):
    print('gogogo')
    context = create_context('secp256k1')
    #    conn = sqlite3.connect('bank.db')
    #    cursor = conn.execute("SELECT private_key from key")
    #    for row in cursor:
    #        privatek=row[0]
    #    conn.close()
    #    private_key = Secp256k1PrivateKey.from_hex(privatek)
    conn = sqlite3.connect('bank.db')

    cursor = conn.execute(
        "SELECT code from BANK WHERE account_no='{}'".format(account_no))
    for row in cursor:
        code = row[0]
    conn.close()
    private_key = context.new_random_private_key()
    signer = CryptoFactory(context).new_signer(private_key)

    input = hash("bankregister".encode('utf-8'))[0:6] + hash(
        "overclockedbrain".encode('utf-8'))[0:58] + hash(
            code.encode('utf-8'))[0:6]
    payload = "{},{},{}".format(todo, amount, code)
    payload_bytes = cbor.dumps(payload)
    txn_header_bytes = TransactionHeader(
        family_name='bankregister',
        family_version='1.0',
        inputs=[input],
        outputs=[input],
        signer_public_key=signer.get_public_key().as_hex(),
        batcher_public_key=signer.get_public_key().as_hex(),
        dependencies=[],
        payload_sha512=sha512(payload_bytes).hexdigest()).SerializeToString()
    signature = signer.sign(txn_header_bytes)

    txn = Transaction(header=txn_header_bytes,
                      header_signature=signature,
                      payload=payload_bytes)
    txns = [txn]

    batch_header_bytes = BatchHeader(
        signer_public_key=signer.get_public_key().as_hex(),
        transaction_ids=[txn.header_signature for txn in txns],
    ).SerializeToString()

    signature = signer.sign(batch_header_bytes)

    batch = Batch(header=batch_header_bytes,
                  header_signature=signature,
                  transactions=txns)
    batch_list_bytes = BatchList(batches=[batch]).SerializeToString()
    return batch_list_bytes
Beispiel #27
0
def create_batch_list(transactions, private_key_hex, public_key_hex):
    transaction_signatures = [t.header_signature for t in transactions]

    header = BatchHeader(
        signer_public_key=public_key_hex,
        transaction_ids=transaction_signatures).SerializeToString()

    signature = sign(header, private_key_hex)

    batch = Batch(header=header,
                  transactions=transactions,
                  header_signature=signature)
    return BatchList(batches=[batch])
Beispiel #28
0
    def create_batch(self, transactions):
        batch_header = BatchHeader(
            signer_public_key=self.signer.get_public_key().as_hex(),
            transaction_ids=[txn.header_signature for txn in transactions],
        ).SerializeToString()

        batch = Batch(
            header=batch_header,
            header_signature=self.signer.sign(batch_header),
            transactions=transactions,
        )

        return BatchList(batches=[batch]).SerializeToString()
Beispiel #29
0
    def _create_batch_list(self, transactions):
        transaction_signatures = [t.header_signature for t in transactions]

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

        signature = self._signer.sign(header)

        batch = Batch(header=header,
                      transactions=transactions,
                      header_signature=signature)
        return BatchList(batches=[batch])
Beispiel #30
0
    def create_batch(self):
        batch_header_bytes = BatchHeader(
            signer_public_key=self.signer.get_public_key().as_hex(),
            transaction_ids=[txn.header_signature for txn in self.txns],
        ).SerializeToString()

        signature = self.signer.sign(batch_header_bytes)

        batch = Batch(header=batch_header_bytes,
                      header_signature=signature,
                      transactions=self.txns)

        self.batch_list_bytes = BatchList(batches=[batch]).SerializeToString()