def __init__(self, transactions=None, node_pubkey=None, timestamp=None, voters=None, signature=None): """The Block model is mainly used for (de)serialization and integrity checking. Args: transaction (:obj:`list` of :class:`~.Transaction`): Transactions to be included in the Block. node_pubkey (str): The public key of the node creating the Block. timestamp (str): The Unix time a Block was created. voters (:obj:`list` of :obj:`str`): A list of a federation nodes' public keys supposed to vote on the Block. signature (str): A cryptographic signature ensuring the integrity and validity of the creator of a Block. """ if transactions is not None and not isinstance(transactions, list): raise TypeError('`transactions` must be a list instance or None') else: self.transactions = transactions or [] if voters is not None and not isinstance(voters, list): raise TypeError('`voters` must be a list instance or None') else: self.voters = voters or [] if timestamp is not None: self.timestamp = timestamp else: self.timestamp = gen_timestamp() self.node_pubkey = node_pubkey self.signature = signature
def vote(self, block_id, previous_block_id, decision, invalid_reason=None): """Create a signed vote for a block given the :attr:`previous_block_id` and the :attr:`decision` (valid/invalid). Args: block_id (str): The id of the block to vote on. previous_block_id (str): The id of the previous block. decision (bool): Whether the block is valid or invalid. invalid_reason (Optional[str]): Reason the block is invalid """ if block_id == previous_block_id: raise exceptions.CyclicBlockchainError() vote = { 'voting_for_block': block_id, 'previous_block': previous_block_id, 'is_block_valid': decision, 'invalid_reason': invalid_reason, 'timestamp': gen_timestamp() } vote_data = serialize(vote) signature = crypto.SigningKey(self.me_private).sign(vote_data.encode()) vote_signed = { 'node_pubkey': self.me, 'signature': signature, 'vote': vote } return vote_signed
def vote(self, block_id, previous_block_id, decision, invalid_reason=None): """Create a signed vote for a block given the :attr:`previous_block_id` and the :attr:`decision` (valid/invalid). Args: block_id (str): The id of the block to vote on. previous_block_id (str): The id of the previous block. decision (bool): Whether the block is valid or invalid. invalid_reason (Optional[str]): Reason the block is invalid """ if block_id == previous_block_id: raise exceptions.CyclicBlockchainError() vote = { 'voting_for_block': block_id, 'previous_block': previous_block_id, 'is_block_valid': decision, 'invalid_reason': invalid_reason, 'timestamp': gen_timestamp() } vote_data = serialize(vote) signature = crypto.PrivateKey(self.me_private).sign(vote_data.encode()) vote_signed = { 'node_pubkey': self.me, 'signature': signature.decode(), 'vote': vote } return vote_signed
def __init__(self, operation, asset, fulfillments=None, conditions=None, metadata=None, timestamp=None, version=None): """The constructor allows to create a customizable Transaction. Note: When no `version` or `timestamp`, is provided, one is being generated by this method. Args: operation (str): Defines the operation of the Transaction. asset (:class:`~bigchaindb.common.transaction.Asset`): An Asset to be transferred or created in a Transaction. fulfillments (:obj:`list` of :class:`~bigchaindb.common. transaction.Fulfillment`, optional): Define the assets to spend. conditions (:obj:`list` of :class:`~bigchaindb.common. transaction.Condition`, optional): Define the assets to lock. metadata (:class:`~bigchaindb.common.transaction.Metadata`): Metadata to be stored along with the Transaction. timestamp (int): Defines the time a Transaction was created. version (int): Defines the version number of a Transaction. """ if operation not in Transaction.ALLOWED_OPERATIONS: allowed_ops = ', '.join(self.__class__.ALLOWED_OPERATIONS) raise ValueError( '`operation` must be one of {}'.format(allowed_ops)) # Only assets for 'CREATE' operations can be un-defined. if (asset and not isinstance(asset, Asset) or not asset and operation != Transaction.CREATE): raise TypeError('`asset` must be an Asset instance') if conditions and not isinstance(conditions, list): raise TypeError('`conditions` must be a list instance or None') if fulfillments and not isinstance(fulfillments, list): raise TypeError('`fulfillments` must be a list instance or None') if metadata is not None and not isinstance(metadata, Metadata): raise TypeError('`metadata` must be a Metadata instance or None') self.version = version if version is not None else self.VERSION self.timestamp = timestamp if timestamp else gen_timestamp() self.operation = operation self.asset = asset if asset else Asset() self.conditions = conditions if conditions else [] self.fulfillments = fulfillments if fulfillments else [] self.metadata = metadata
def tamper_block(): # Cryptographic Identities Generation alice, bob = generate_keypair(), generate_keypair() print(" ") # Digital Asset Definition (e.g. bicycle) asset = Asset(data={ "bicycle": { "manufacturer": "bkfab", "serial_number": "abcd1234" } }) # Metadata Definition metadata = {'planet': 'earth'} # create trnsaction TODO : owners_before might be node_pubkey in v0.8.0 tx = Transaction.create([alice.public_key], [([alice.public_key], 1)], metadata=metadata, asset=asset) # sign with private key tx = tx.sign([alice.private_key]) tx_id = tx.to_dict()['id'] print("tx_id : ", tx_id) # create block b = Bigchain() block = b.create_block([tx]) block_id = block.to_dict()['id'] block_voters = block.to_dict()['block']['voters'] print("last_block_id : ", block_id) print(block.to_dict()) # tamper block id block_dict = block.to_dict() block_dict['id'] = hash_data(gen_timestamp()) print("tamper_block_id : ", block_dict['id']) print(block_dict) print("db response : ", b.backend.write_block(serialize(block_dict))) sleep(delay) print("tamper_block status : ", b.block_election_status(block_dict['id'], block_voters)) print("blocks_status_containing_tx : ", b.get_blocks_status_containing_tx(tx_id)) print(" ")
def __init__(self, transactions=None, node_pubkey=None, timestamp=None, voters=None, signature=None): if transactions is not None and not isinstance(transactions, list): raise TypeError('`transactions` must be a list instance or None') else: self.transactions = transactions or [] if voters is not None and not isinstance(voters, list): raise TypeError('`voters` must be a list instance or None') else: self.voters = voters or [] if timestamp is not None: self.timestamp = timestamp else: self.timestamp = gen_timestamp() self.node_pubkey = node_pubkey self.signature = signature
def _fulfillment_valid(fulfillment, operation, tx_serialized, input_condition_uri=None): """Validates a single Fulfillment against a single Condition. Note: In case of a `CREATE` or `GENESIS` Transaction, this method does not validate against `input_condition_uri`. Args: fulfillment (:class:`~bigchaindb.common.transaction. Fulfillment`) The Fulfillment to be signed. operation (str): The type of Transaction. tx_serialized (str): The Transaction used as a message when initially signing it. input_condition_uri (str, optional): A Condition to check the Fulfillment against. Returns: bool: If the Fulfillment is valid. """ ccffill = fulfillment.fulfillment try: parsed_ffill = CCFulfillment.from_uri(ccffill.serialize_uri()) except (TypeError, ValueError, ParsingError): return False if operation in (Transaction.CREATE, Transaction.GENESIS): # NOTE: In the case of a `CREATE` or `GENESIS` transaction, the # input condition is always validate to `True`. input_cond_valid = True else: input_cond_valid = input_condition_uri == ccffill.condition_uri # NOTE: We pass a timestamp to `.validate`, as in case of a timeout # condition we'll have to validate against it # cryptoconditions makes no assumptions of the encoding of the # message to sign or verify. It only accepts bytestrings return parsed_ffill.validate(message=tx_serialized.encode(), now=gen_timestamp()) and input_cond_valid
def _fulfillment_valid(fulfillment, operation, tx_serialized, input_condition_uri=None): """Validates a single Fulfillment against a single Condition. Note: In case of a `CREATE` or `GENESIS` Transaction, this method does not validate against `input_condition_uri`. Args: fulfillment (:class:`~bigchaindb.common.transaction. Fulfillment`) The Fulfillment to be signed. operation (str): The type of Transaction. tx_serialized (str): The Transaction used as a message when initially signing it. input_condition_uri (str, optional): A Condition to check the Fulfillment against. Returns: bool: If the Fulfillment is valid. """ ccffill = fulfillment.fulfillment try: parsed_ffill = CCFulfillment.from_uri(ccffill.serialize_uri()) except (TypeError, ValueError, ParsingError): return False if operation in (Transaction.CREATE, Transaction.GENESIS): # NOTE: In the case of a `CREATE` or `GENESIS` transaction, the # input condition is always validate to `True`. input_cond_valid = True else: input_cond_valid = input_condition_uri == ccffill.condition_uri # NOTE: We pass a timestamp to `.validate`, as in case of a timeout # condition we'll have to validate against it # cryptoconditions makes no assumptions of the encoding of the # message to sign or verify. It only accepts bytestrings return parsed_ffill.validate(message=tx_serialized.encode(), now=gen_timestamp()) and input_cond_valid
def create_block(self, validated_transactions): """Creates a block given a list of `validated_transactions`. Note that this method does not validate the transactions. Transactions should be validated before calling create_block. Args: validated_transactions (list(Transaction)): list of validated transactions. Returns: Block: created block. """ # Prevent the creation of empty blocks if len(validated_transactions) == 0: raise exceptions.OperationError('Empty block creation is not ' 'allowed') voters = self.nodes_except_me + [self.me] block = Block(validated_transactions, self.me, gen_timestamp(), voters) block = block.sign(self.me_private) return block
def create_block(self, validated_transactions): """Creates a block given a list of `validated_transactions`. Note that this method does not validate the transactions. Transactions should be validated before calling create_block. Args: validated_transactions (list(Transaction)): list of validated transactions. Returns: Block: created block. """ # Prevent the creation of empty blocks if len(validated_transactions) == 0: raise exceptions.OperationError('Empty block creation is not ' 'allowed') voters = self.nodes_except_me + [self.me] block = Block(validated_transactions, self.me, gen_timestamp(), voters) block = block.sign(self.me_private) return block
def __init__(self, transactions=None, node_pubkey=None, timestamp=None, voters=None, signature=None): """The Block model is mainly used for (de)serialization and integrity checking. Args: transaction (:obj:`list` of :class:`~.Transaction`): Transactions to be included in the Block. node_pubkey (str): The public key of the node creating the Block. timestamp (str): The Unix time a Block was created. voters (:obj:`list` of :obj:`str`): A list of a federation nodes' public keys supposed to vote on the Block. signature (str): A cryptographic signature ensuring the integrity and validity of the creator of a Block. """ if transactions is not None and not isinstance(transactions, list): raise TypeError('`transactions` must be a list instance or None') else: self.transactions = transactions or [] if voters is not None and not isinstance(voters, list): raise TypeError('`voters` must be a list instance or None') else: self.voters = voters or [] if timestamp is not None: self.timestamp = timestamp else: self.timestamp = gen_timestamp() self.node_pubkey = node_pubkey self.signature = signature
def get_now_timestamp(self): return gen_timestamp()
time.sleep(1) print("m :create qsize:", create_queue.qsize()) # input("Press enter key to continue...") BANNER = """ ******************* * ready, go! * ******************* """ print(BANNER) # post transfer print("step 3 :post transfer tx ,please wait for all transfer tx valid") transfer_start = gen_timestamp() for x in range(num_clients): p = multiprocessing.Process(target=post_transfer, args=(x,)) p.start() # wait for post transfer while True: if transfer_queue.empty(): break time.sleep(1) print("m :transfer qsize:", transfer_queue.qsize()) transfer_end = gen_timestamp() transfer_cost = (int(transfer_end) - int(transfer_start)) / 1000 print("m :transfer_start:", transfer_start) print("m :transfer_end:", transfer_end) print("m :transfer_cost:", transfer_cost)