Ejemplo n.º 1
0
  def update(self, request, pk=None):
    r = requests.get(API_URL+'/state',params={'address':PREFIX}).json()
    residuo = None
    for product in r['data']:
      decoded = base64.decodebytes(product['data'].encode())
      data = json.loads(decoded.decode())
      data['bc_address'] = product['address']
      if data['code'] == pk:
        residuo=data
        break

    if residuo == None:
      return Response('No existe producto')
    

    residuo['estados'].append(request.data)
    # encoding payload

    payload = {
      "action":"update",
      "residuo":residuo
    }

    payload_bytes = cbor.dumps(payload)

    ## BUILD TRANSACTION
    # Build transaction header
    txn_header_bytes = TransactionHeader(
      family_name=FAMILY,
      family_version=VERSION,
      inputs=[PREFIX],
      outputs=[PREFIX],
      signer_public_key=signer.get_public_key().as_hex(),
      # In this example, we're signing the batch with the same private key,
      # but the batch can be signed by another party, in which case, the
      # public key will need to be associated with that key.
      batcher_public_key=signer.get_public_key().as_hex(),
      dependencies=[],
      payload_sha512=sha512(payload_bytes).hexdigest()
    ).SerializeToString()

    # Create transaction
    signature = signer.sign(txn_header_bytes)

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

    # Encode the Transaction
    txn_list_bytes = TransactionList(
      transactions=[txn]
    ).SerializeToString()

    txn_bytes = txn.SerializeToString()

    ## BUILD BATCH
    # create batch header
    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()

    # create Batch
    signature = signer.sign(batch_header_bytes)

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

    # BATCHLIST
    batch_list_bytes = BatchList(batches=[batch]).SerializeToString()

    response = None
    # ENVIAR A SERVIDOR 
    try:
      request = urllib.request.Request(
        API_URL+'/batches', ## URL SERVIDOR
        batch_list_bytes,
        method='POST',
        headers={'Content-Type': 'application/octet-stream'})
      response = urllib.request.urlopen(request)

    except HTTPError as e:
      response = e.file

    response = json.loads(response.read().decode('utf-8'))
    link = response["link"].split('=')[1]
    requests.get(API_URL+'/batch_statuses',params={'id':link, 'wait':1}).json()

    return self.retrieve(None,pk)
Ejemplo n.º 2
0
    def _wrap_and_send(self, action, *values):
        '''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 payload
        rawPayload = action
        '''split with ,'''
        for val in values:
            rawPayload = ",".join([rawPayload, str(val)])
        '''generate payload'''
        payload = rawPayload.encode()

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

        if "transport" == 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()

        # random.random generate float between 0,1
        # 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
                      outputs=[tx_addr[i]],
                      signer_public_key=signer.get_public_key().as_hex(),
                      batcher_public_key=signer.get_public_key().as_hex(),
                      dependencies=[],
                      payload_sha512=sha512(
                          payload[i]).hexdigest()).SerializeToString()
    for i in lenNums
]

#Signer signs the header:
signature_arr = [signer.sign(tx_header_arr[i]) for i in lenNums]

#Generate an array with all the transactions
tx_arr = [
    Transaction(header=tx_header_arr[i],
                header_signature=signature_arr[i],
                payload=payload[i]) for i in lenNums
]

#Create the BatchHeader
batch_header = BatchHeader(signer_public_key=signer.get_public_key().as_hex(),
                           transaction_ids=[
                               tx_arr[i].header_signature for i in lenNums
                           ]).SerializeToString()

#Create the batch with the tx
signature_batch = signer.sign(batch_header)

batch = Batch(header=batch_header,
              header_signature=signature_batch,
              transactions=tx_arr)
Ejemplo n.º 4
0
    def _send_battleship_txn(self, update):
        """The client needs to have the same
            defaults as the Transaction subclass
            before it is signed inside sendtxn
        """
        if 'Name' not in update:
            raise BattleshipException('Game name required')
        if 'Action' not in update:
            update['Action'] = None
        if 'Ships' not in update:
            update['Ships'] = None
        if update['Action'] == 'JOIN':
            if 'Board' not in update:
                update['Board'] = None
        if update['Action'] == 'FIRE':
            if 'Column' not in update:
                update['Column'] = None
            if 'Row' not in update:
                update['Row'] = None

        payload = json.dumps(update).encode()
        address = self._get_address(update['Name'])

        header = TransactionHeader(
            signer_public_key=self._public_key,
            family_name=self._transaction_family,
            family_version=self._family_version,
            inputs=[address],
            outputs=[address],
            dependencies=[],
            payload_sha512=self._sha512(payload),
            batcher_public_key=self._public_key,
            nonce=time.time().hex().encode()).SerializeToString()

        signature = signing.sign(header, self._private_key)

        transaction = Transaction(header=header,
                                  payload=payload,
                                  header_signature=signature)

        batch_list = self._create_batch_list([transaction])
        batch_id = batch_list.batches[0].header_signature

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

                if status != 'PENDING':
                    return response

            return response

        return self._send_request("batches", batch_list.SerializeToString(),
                                  'application/octet-stream')
def gogogo(stri, starting_balance, aadhar_number, NAME, account_no):
    LOGGER.info('entered 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]
    privatek = open("priv.txt", 'r').read()[0:-1]

    private_key = Secp256k1PrivateKey.from_hex(privatek)

    signer = CryptoFactory(context).new_signer(private_key)
    message = id_generator()
    key = signer.sign(str.encode(message))
    goyu = True
    while goyu:
        try:
            code = id_generator(size=3, chars=string.digits) + id_generator(
                size=3, chars=string.ascii_lowercase)
            #code = "234sdf"
            print('a')
            input = hash("bankregister".encode('utf-8'))[0:6] + hash(
                "overclockedbrain".encode('utf-8'))[0:58] + hash(
                    code.encode('utf-8'))[0:6]

            #input = "0fb30d96b1f101ff209462abcce07bb477627730dde6d4284799fcb9f733d2892f3cc9"
            print(input)

            p = json.loads(
                requests.get(
                    "http://rest-api:8008/state/{}".format(input)).text)
            print(p)
            try:
                a = p['data']
                print(a)
            except:
                print("exited")
                goyu = False
                break

        except:
            pass
    conn.execute("UPDATE BANK set code = '{}' where account_no = '{}'".format(
        code, account_no))
    conn.commit()
    conn.close()
    payload = "CREATE,{},{},{},{},{},{},{},{}".format(stri, starting_balance,
                                                      code, aadhar_number,
                                                      account_no, NAME,
                                                      message, key)
    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 code, batch_list_bytes
Ejemplo n.º 6
0
    def _send_xo_txn(self,
                     name,
                     action,
                     space="",
                     wait=None,
                     auth_user=None,
                     auth_password=None):
        # Serialization is just a delimited utf-8 encoded string
        payload = ",".join([name, action, str(space)]).encode()

        # Construct the address
        address = self._get_address(name)

        header = TransactionHeader(
            signer_public_key=self._signer.get_public_key().as_hex(),
            family_name="xo",
            family_version="1.0",
            inputs=[address],
            outputs=[address],
            dependencies=[],
            payload_sha512=_sha512(payload),
            batcher_public_key=self._signer.get_public_key().as_hex(),
            nonce=time.time().hex().encode()
        ).SerializeToString()

        signature = self._signer.sign(header)

        transaction = Transaction(
            header=header,
            payload=payload,
            header_signature=signature
        )

        batch_list = self._create_batch_list([transaction])
        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.º 7
0
    # In this example, we're signing the batch with the same private key,
    # but the batch can be signed by another party, in which case, the
    # public key will need to be associated with that key.
    batcher_public_key=signer.get_public_key().as_hex(),
    # In this example, there are no dependencies.  This list should include
    # an previous transaction header signatures that must be applied for
    # this transaction to successfully commit.
    # For example,
    # dependencies=['540a6803971d1880ec73a96cb97815a95d374cbad5d865925e5aa0432fcf1931539afe10310c122c5eaae15df61236079abbf4f258889359c4d175516934484a'],
    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)
Ejemplo n.º 8
0
    def _send_transaction(self, verb, name, value, wait=None):
        LOGGER.warning("in send transaction")
        payload = cbor.dumps({
            'Verb': verb,
            'Name': name,
            'Value': value,
        })

        # Construct the address
        address = self._get_address(name)

        header = TransactionHeader(
            signer_public_key=self._signer.get_public_key().as_hex(),
            family_name="kvstore",
            family_version="1.0",
            inputs=[address],
            outputs=[address],
            dependencies=[],
            payload_sha512=_sha512(payload),
            batcher_public_key=self._signer.get_public_key().as_hex(),
            nonce=hex(random.randint(0, 2**64))
        ).SerializeToString()

        signature = self._signer.sign(header)

        transaction = Transaction(
            header=header,
            payload=payload,
            header_signature=signature
        )

        batch_list = self._create_batch_list([transaction])

        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',
            )
            LOGGER.warning("response :")
            LOGGER.warning(response)
            while wait_time < wait:
                status = self._get_status(
                    batch_id,
                    wait - int(wait_time),
                )
                wait_time = time.time() - start_time

                if status != 'PENDING':
                    return signature

            return signature

        res =self._send_request(
            "batches", batch_list.SerializeToString(),
            'application/octet-stream',
        )
        LOGGER.warning("response :")
        LOGGER.warning(res)
        return signature
Ejemplo n.º 9
0
    def artifact_transaction(self, private_key, public_key, artifact_id,
                             artifact_alias, artifact_name, artifact_type,
                             artifact_checksum, artifact_label,
                             artifact_openchain, prev, cur, timestamp, action,
                             artifact_list, uri_list):
        """
        Constructs the Batch to be posted and sent the request to be posted on
        the ledger.
        
        Args:
            private_key (str): The private key of the user
            public_key (str): The public key of the user
            artifact_id (str): The uuid of the artifact
            artifact_alias (str): The alias of the artifact
            artifact_name (str): The name of the artifact
            artifact_type (str): The type of the artifact
            artifact_checksum (str): The checksum of the artifact
            artifact_label (str): The label of the artifact
            artifact_openchain (str): The openchain of the artifact
            artifact_list (list of dict):
                The list of the sub-artifact dictionary associated with
                the artifact
            uri_list (list of dict):
                The list of the uri dictionary associated with the artifact
            prev (str): The previous block id of the transaction (default "0")
            cur (str): the current block id of the transaction
            timestamp (str): The UTC time for when the transaction was submitted
            action (str): The action performed
            
        Returns:
            type: str
            Data associated with suffix as a string.
            
                or
            
            type: None
            None object if _send_request failed.
            
        """
        # Constructing Batch to be sent and stored
        self._public_key = public_key
        self._private_key = private_key

        payload = {
            "uuid": str(artifact_id),
            "alias": str(artifact_alias),
            "name": str(artifact_name),
            "content_type": str(artifact_type),
            "checksum": str(artifact_checksum),
            "label": str(artifact_label),
            "openchain": str(artifact_openchain),
            "action": str(action),
            "prev_block": str(prev),
            "cur_block": str(cur),
            "timestamp": str(timestamp),
            "artifact_list": artifact_list,
            "uri_list": uri_list
        }
        payload = json.dumps(payload).encode()
        address = self._get_address(artifact_id)

        header = TransactionHeader(
            signer_public_key=self._public_key,
            family_name="artifact",
            family_version="1.0",
            inputs=[address],
            outputs=[address],
            dependencies=[],
            payload_sha512=_sha512(payload),
            batcher_public_key=self._public_key,
            nonce=time.time().hex().encode()).SerializeToString()

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

        transaction = Transaction(header=header,
                                  payload=payload,
                                  header_signature=signature)

        # Creating batch list
        batch_list = self._create_batch_list([transaction])

        return self._send_request("batches", batch_list.SerializeToString(),
                                  "application/octet-stream")
Ejemplo n.º 10
0
 def create_txn(self):
     signature = self.signer.sign(self.txn_header_bytes)
     txn = Transaction(header=self.txn_header_bytes,
                       header_signature=signature,
                       payload=self.payload_bytes)
     self.txns = [txn]