def _send_barcode_txn(self, name, action, location="", wait=None, auth_user=None, auth_password=None): # Serialization is just a delimited utf-8 encoded string payload = ",".join([name, action, location]).encode() # Construct the address address = self._get_address(name) header = TransactionHeader(signer_public_key=self._signer.get_public_key().as_hex(), family_name="barcode", 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)
def _send_transaction(self, payload, device): # Get the unique address for the device's tokens address = self._get_address(device) header = TransactionHeader( signer_public_key=self._signer.get_public_key().as_hex(), family_name=FAMILY_NAME, family_version=FAMILY_VERSION, 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]) return self._send_request( "batches", batch_list.SerializeToString(), 'application/octet-stream' )
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
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')
def _send_txn(self, action, action_payload, inputs=None, outputs=None, wait=None): payload = _pb_dumps( SupplyChainPayload(action=action, data=_pb_dumps(action_payload))) header = TransactionHeader( signer_public_key=self._public_key, family_name="sawtooth_supplychain", family_version="0.5", inputs=inputs or [], outputs=outputs or [], dependencies=[], payload_sha512=_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]) result = self._send_post("batches", batch_list.SerializeToString(), 'application/octet-stream', wait=wait) return result
def create_transaction(self, payload, inputs, outputs, deps): header, signature = self._create_header_and_sig( payload, inputs, outputs, deps) return Transaction(header=header, payload=payload, header_signature=signature)
def _send_xo_txn(self, name, action, space=""): # 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_pubkey=self._public_key, family_name="xo", family_version="1.0", inputs=[address], outputs=[address], dependencies=[], payload_encoding="csv-utf8", payload_sha512=_sha512(payload), batcher_pubkey=self._public_key).SerializeToString() signature = signing.sign(header, self._private_key) transaction = Transaction(header=header, payload=payload, header_signature=signature) batch_list = self._create_batch_list([transaction]) result = self._send_request("batches", batch_list.SerializeToString(), 'application/octet-stream') return result
def create_transaction(self, signer, payload_bytes): '''Bundles together a transaction that includes the given payload and is signed by given signer''' txn_header_bytes = TransactionHeader( family_name='todo', family_version='0.1', inputs=[addressing.NAMESPACE], outputs=[addressing.NAMESPACE], signer_public_key=signer.pubkey.serialize().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. # make a global batch_public_key batcher_public_key=signer.pubkey.serialize().hex(), # must have been generated from the private key being used to sign # the Batch, or validation will fail # 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=hashlib.sha512( payload_bytes).hexdigest()).SerializeToString() # Ecdsa signing standard, then remove extra ecdsa bytes using compact. txn_signature = signer.ecdsa_sign(txn_header_bytes) txn_signature_bytes = signer.ecdsa_serialize_compact(txn_signature) signature = txn_signature_bytes.hex() txn = Transaction(header=txn_header_bytes, header_signature=signature, payload=payload_bytes) return txn
def generateTransaction(self,inputAddressList, outputAddressList,raw_payload, url, Dependencies = [] ,createBatch = True): #encode the payload if isinstance(raw_payload, bytes): payload = raw_payload else: payload = raw_payload.encode() #set the transaction header and serialize it to string header = TransactionHeader( signer_public_key=self.publicKey, family_name=self.familyName, family_version=self.familyVersion, inputs=inputAddressList, outputs=outputAddressList, dependencies=Dependencies, payload_sha512=Hash(payload), batcher_public_key=self.publicKey, nonce=random.random().hex().encode("utf-8") ).SerializeToString() # setting the transactions transaction = Transaction( header=header, payload=payload, header_signature=self.signer.sign(header) ) if createBatch : response = self.postAsBatch(url, [transaction]) return response else: return transaction
def create_raw_transaction_send_token_payload(pub_key_to, amount=1): client = AccountClient() signer = client._signer address = client.make_address_from_data(pub_key_to) node_address = client.get_user_address() transfer = TransferPayload() transfer.address_to = address transfer.value = amount tr = TransactionPayload() tr.method = AccountMethod.TRANSFER tr.data = transfer.SerializeToString() payload = tr.SerializeToString() header = TransactionHeader( signer_public_key=signer.get_public_key().as_hex(), family_name=client._family_handler.family_name, family_version=client._family_handler.family_versions[-1], inputs=[node_address, address], outputs=[node_address, address], dependencies=[], payload_sha512=hash512(payload), batcher_public_key=signer.get_public_key().as_hex(), nonce=time.time().hex().encode()).SerializeToString() signature = signer.sign(header) transaction = Transaction(header=header, payload=payload, header_signature=signature) return transaction
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
def make_transaction(payload, signer, inputs, outputs): print('Creating Transaction...', end='', flush=True) # Addressing name = addresser.FAMILY_NAME version = addresser.FAMILY_VERSION # Signing signer_public_key = signer.get_public_key().as_hex() # Payload payload_hash = hashlib.sha512(payload).hexdigest() header = TransactionHeader( family_name=name, family_version=version, inputs=inputs, outputs=outputs, signer_public_key=signer_public_key, batcher_public_key=signer_public_key, dependencies=[], payload_sha512=payload_hash).SerializeToString() # Sign Header. signature = signer.sign(header) transaction = Transaction(header=header, header_signature=signature, payload=payload) print('[OK]') return transaction
def _send_transaction(self, verb, name, value, value1, value2, value3, value4, wait=None): payload = cbor.dumps({ 'Verb': verb, 'Name': name, 'Value': value, 'Value1': value1, 'Value2': value2, 'Value3': value3, 'Value4': value4, }) # Construct the address address = self._get_address(name) header = TransactionHeader( signer_public_key=self._signer.get_public_key().as_hex(), family_name="intkey", 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', ) while wait_time < wait: status = self._get_status( batch_id, 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 _send_transaction(self, device_id, metadata, timestamp): payload = cbor.dumps({ 'device_id': device_id, 'metadata': metadata, 'timestamp': timestamp, }) address = self._get_address(metadata) header = TransactionHeader( signer_public_key=self._signer.get_public_key().as_hex(), family_name="iot-tp", 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 return self._send_request( "batches", batch_list.SerializeToString(), 'application/octet-stream', )
def send_category_transactions(self, category_id, category_name, description, action, private_key, public_key): self._public_key = public_key self._private_key = private_key payload = ",".join([category_id, category_name, description, action]).encode() # Form the address address = self._get_address(category_id) header = TransactionHeader( signer_pubkey=self._public_key, family_name="category", family_version="1.0", inputs=[address], outputs=[address], dependencies=[], payload_encoding="csv-utf8", payload_sha512=_sha512(payload), batcher_pubkey=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]) return self._send_request("batches", batch_list.SerializeToString(), 'application/octet-stream')
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 _send_hw_txn(self, name, action, cu_add, nxt_add, wait=None): payload = ",".join([name, action, cu_add, nxt_add]).encode() key_add = self._get_key_address(nxt_add) cli_add = self._get_key_address(cu_add) address = self._get_address(name) #for a transaction processor to access an address in the state database, we have to specify it in #inputs of the transaction header. For a transaction processor to change an element at an address, #we have to specify that address in outputs if key_add is not None: header = TransactionHeader( signer_public_key=self._signer.get_public_key().as_hex(), family_name="hw", family_version="1.0", inputs=[address, key_add, cli_add], outputs=[address], dependencies=[], payload_sha512=_sha512(payload), batcher_public_key=self._signer.get_public_key().as_hex(), nonce=time.time().hex().encode()).SerializeToString() else: header = TransactionHeader( signer_public_key=self._signer.get_public_key().as_hex(), family_name="hw", 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') while wait_time < wait: status = self._get_status(batch_id, 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 _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')
def create_transaction(self, payload, inputs, outputs, deps, batcher=None): header, signature = self._create_header_and_sig( payload, inputs, outputs, deps, batcher=batcher) return Transaction( header=header.SerializeToString(), payload=payload, header_signature=signature)
def create_txn(obj, outputs: [] = None, inputs: [] = None): """ Creates both the transaction and header. You must calculate the input/output addresses needed to run the transaction before calling, though (for now) """ header = create_header(obj, outputs=outputs, inputs=inputs) return Transaction(header=header, header_signature=_signer.sign(header), payload=obj.SerializeToString())
def _make_transaction(payload, inputs, outputs, txn_signer, batch_signer): txn_header_bytes, signature = _transaction_header(txn_signer, batch_signer, inputs, outputs, payload) txn = Transaction(header=txn_header_bytes, header_signature=signature, payload=payload.SerializeToString()) return txn
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)
def create_artifact_transaction(self, artifact_id, short_id="", artifact_name="", artifact_type="", artifact_checksum="", path="", uri="", label="", openchain="", action="", sub_artifact_id="", auth_user=None, auth_password=None): payload = ",".join([ artifact_id, str(short_id), str(artifact_name), str(artifact_type), str(artifact_checksum), str(path), str(uri), str(label), str(openchain), action, str(sub_artifact_id) ]).encode() address = self._get_address(artifact_id) header = TransactionHeader( signer_pubkey=self._public_key, family_name="comp", family_version="1.0", inputs=[address], outputs=[address], dependencies=[], payload_encoding="csv-utf8", payload_sha512=_sha512(payload), batcher_pubkey=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 return self._send_request("batches", batch_list.SerializeToString(), 'application/octet-stream', auth_user=auth_user, auth_password=auth_password)
def txn_gen(self, verb: str, name: str, value: int, pub=None, deps=None) -> TransactionList: """ Generates a valid batch for testing submissions, optional arguments are for payment transactions. Args: :arg verb: the string 'inc', 'dec', or 'set' :arg name: the unique name used to identify a state address :arg value: the size of the transaction :arg pub: public key, defaults to self.signer if not provided :arg deps: A list of transaction header signature dependency this relies on. Returns: :var txn: a transaction list that includes the transaction porotobuf :var id: the transaction header signature used for dependnecies """ # build payload payload = {'Verb': str(verb), 'Name': str(name), 'Value': int(value)} # calculate the state store state_store = self.gen_addr('{name}'.format(name=name)) # encode the payload payload_bytes = cbor2.dumps(payload) # Create the header txn_header = TransactionHeader( batcher_public_key=pub if pub is not None else self.signer.get_public_key().as_hex(), dependencies=[] if deps is None else deps, family_name='intkey', family_version='1.0', inputs=[state_store], nonce=str(randint(0, 1000000000)), outputs=[state_store], payload_sha512=sha512(payload_bytes).hexdigest(), signer_public_key=pub if pub is not None else self.signer.get_public_key().as_hex()) current_app.logger.info('txn header: {}'.format(txn_header)) # encode the header to hex txn_header_bytes = txn_header.SerializeToString() # sign the header bytes, wif assumed. txn_signature_hex = self.signer.sign(txn_header_bytes) # build the transaction protobuf txn = Transaction(header=txn_header_bytes, header_signature=txn_signature_hex, payload=payload_bytes) return TransactionList(transactions=[txn]), txn.header_signature
def post(self, request): url = 'http://rest-api-0:8008/batches' values = json.loads(request.body)['values'] scantrust_id = values['itemID'] owner = values['receiver'] item_name = values['itemName'] item_info = values['itemInfo'] item_color = values['itemColor'] item_size = values['itemSize'] item_img = values['imageURL'] public_key_hex = values['public_key'] private_key_hex = values['private_key'] img = urllib.request.urlopen(item_img, timeout=ITEM_IMG_TIMEOUT).read() item_img_md5 = hashlib.md5(img).hexdigest() payload = json.dumps( (scantrust_id, owner, item_name, item_info, item_color, item_size, item_img, item_img_md5)).encode() address = get_address(scantrust_id) header = TransactionHeader(signer_public_key=public_key_hex, family_name="fashion", family_version="1.0", inputs=[address], outputs=[address], dependencies=[], payload_sha512=sha512(payload), batcher_public_key=public_key_hex, nonce=hex(random.randint( 0, 2**64))).SerializeToString() signature = sign(header, private_key_hex) transaction = Transaction(header=header, payload=payload, header_signature=signature) batch_list = create_batch_list([transaction], private_key_hex, public_key_hex) data = batch_list.SerializeToString() headers = {'Content-Type': 'application/octet-stream'} try: result = requests.post(url, headers=headers, data=data) response = result.text print(response) except requests.ConnectionError: response = 'Connection fail' except BaseException: response = 'Incorrect data' return JsonResponse({'response': response})
def _send_health_txn(self, txn_type=None, txn_id=None, data=None, state=None, url=None, txn_date=None): """ serialize payload and create header transaction Args: type (str): type of transaction id (str): asset id, will depend on type of transaction data (object): transaction data state (str): all transactions must have a state """ #serialization is just a delimited utf-8 encoded strings if txn_type == 'commit': payload = ",".join([txn_type, txn_id, data, state, url]).encode() elif txn_type == 'health': payload = ",".join([txn_type, txn_id, data, state, str(txn_date)]).encode() pprint("payload: {}".format(payload))######################################## pprint #construct the address address = self._get_address(txn_id) #construct header header = TransactionHeader( signer_public_key=self._signer.get_public_key().as_hex(), family_name="health", family_version="0.1", 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) #create transaction transaction = Transaction( header=header, payload=payload, header_signature=signature ) #create batch list, suserum policy: one transaction per batch batch_list = self._create_batch_list([transaction]) return self._send_request( "batches", batch_list.SerializeToString(), 'application/octet-stream')
async def create(self, family_name, family_version, inputs, outputs, payload_bytes): """ Create transactions. Args: family_name (string): enum RemmeFamilyName family_version (string): family version inputs (list): list of input address outputs (list): list of output address payload_bytes (bytes): payload bytes Returns: Transaction. References:: Documentation for building transactions - https://bit.ly/2NrNbNi To use: .. code-block:: python family_name = "pub_key" family_version = "0.1" inputs = outputs = [] payload_bytes = b"my transaction" transaction = await remme_transaction.create( family_name, family_version, inputs, outputs, payload_bytes, ) """ node_config = await self._remme_api.send_request( method=RemmeMethods.NODE_CONFIG) batcher_public_key = node_config.get('node_public_key') transaction_header_bytes = TransactionHeader( family_name=family_name, family_version=family_version, inputs=inputs + [self._remme_account.address], outputs=outputs + [self._remme_account.address], signer_public_key=self._remme_account.public_key_hex, batcher_public_key=batcher_public_key, nonce=create_nonce(), dependencies=[], payload_sha512=sha512_hexdigest( payload_bytes)).SerializeToString() signature = self._remme_account.sign(transaction_header_bytes) transaction = Transaction( header=transaction_header_bytes, header_signature=signature, payload=payload_bytes, ).SerializeToString() return base64.b64encode(transaction).decode('utf-8')
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)
def _send_xo_txn(self, name, action, space="", wait=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_pubkey=self._public_key, family_name="xo", family_version="1.0", inputs=[address], outputs=[address], dependencies=[], payload_encoding="csv-utf8", payload_sha512=_sha512(payload), batcher_pubkey=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 wait and wait > 0: wait_time = 0 start_time = time.time() self._send_request("batches", batch_list.SerializeToString(), 'application/octet-stream') while wait_time < wait: status = self._get_status(batch_id, wait - int(wait_time)) wait_time = time.time() - start_time if status[batch_id] == 'COMMITTED': return 'Game created in {:.6} sec'.format(wait_time) elif status[batch_id] == 'INVALID': return ('Error: You chose an invalid game name. ' 'Try again with a different name') elif status[batch_id] == 'UNKNOWN': return ('Error: Something went wrong with your game. ' 'Try again with a different name.') # Wait a moment so as not to hammer the Rest Api time.sleep(0.2) return ('Timed out while waiting for game to be created. ' 'It may need to be resubmitted.') return self._send_request("batches", batch_list.SerializeToString(), 'application/octet-stream')
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')