def mine_new_block(self): previous_hash = self.target_in_string if len(self.chain) == 0 else hash(self.get_latest_block()) block_data = to_json_string(self.mempool) block = Block(block_data, len(self.chain)+1, previous_hash) nonce, timestamp = self.find_nonce(block) block.seal(nonce, timestamp) self.chain.append(block)
def main(): #fntdb = Database() currentBlockNum = Database().getBlockNumber() print('getBlockNumber:', currentBlockNum) if currentBlockNum == 0: genesisBlock = Genesis.genesis() Database().createBlock(genesisBlock) else: while True: #for j in range(3): time.sleep(2) newBlock = Block.block() transactions = [] for i in range(5): pendingTran = Database().getPendingTransaction() print(pendingTran) if pendingTran == {}: print('There is no pending transaction now.') continue else: if not Transaction.verifyTransaction(pendingTran): continue #balance verify and nonce if not Database().verifyBalanceAndNonce(pendingTran): print("verify balance and nonce error") continue if not Database().updateBalanceAndNonce(pendingTran): print("update error") continue newBlock = Block.pushTransactionToArray( newBlock, pendingTran) transactions.append(pendingTran) #print("newBlock:", newBlock) parentBlock = Database().getBlockByID(currentBlockNum - 1) key = '97ddae0f3a25b92268175400149d65d6887b9cefaf28ea2c078e05cdc15a3c0a' #print('parent', parentBlock) newBlock = Block.newBlock_POA(newBlock, parentBlock, key) try: Database().createBlock(newBlock) except: print('Error occurs when saving block into db.') continue #fntdb.updateDBAccountStatus(newBlock) #transactions = newBlock['transaction'] if len(transactions) == 0: continue for transaction in transactions: try: Database().createTransaction(transaction) except: print("Error occurs when saving transaction into db.") continue
def add_block(self, block_id, pos_list, label_dict): self.__block_list.append(Block(block_id, pos_list, label_dict)) for pos, label in label_dict.items(): if label > 0: if label not in self.__terminals_dict: self.__terminals_dict[label] = list() self.__terminals_dict[label].append((block_id, pos))
def __create_block(self, blocknode): """\brief Creates a block \param blocknode (\c xml.dom.Node) The block in xml form """ block_name = blocknode.attributes['id'].value block_type = blocknode.attributes['type'].value active = False tpool_id = "" if blocknode.attributes.has_key('sched_type'): active = True if (blocknode.attributes['sched_type'].value == 'active') else False if active: tpool_id = blocknode.attributes['threadpool'].value params = blocknode.getElementsByTagName('params') params = params[0].toxml() tpool = None if (active): tpool = self.__thread_pools[str(tpool_id)] self.__blocks[block_name] = Block(block_name,\ block_type,\ self.__comp_id,\ active,\ params,\ tpool_id,\ tpool,\ self.__blockmon,\ self.__logger)
def main(): fntdb = Database() currentBlockNum = fntdb.getBlockNumber() print('getBlockNumber:', currentBlockNum) if currentBlockNum == 0: genesisBlock = Genesis.genesis() fntdb.createBlock(genesisBlock) else: #while True: for j in range(1): time.sleep(2) newBlock = Block.block() for i in range(5): pendingTran = fntdb.getPendingTransaction() print(pendingTran) if pendingTran == {}: print('There is no pending transaction now.') continue else: if not Transaction.verifyTransaction(pendingTran): continue #balance verify and nonce if not fntdb.verifyBalanceAndNonce(pendingTran): print("verify balance and nonce error") continue if not fntdb.updateBalanceAndNonce(pendingTran): print("update error") return False newBlock = Block.pushTransactionToArray(newBlock, pendingTran) #print("newBlock:", newBlock) parentBlock = fntdb.getBlockByID(currentBlockNum - 1) key = '8c1eba13a46fd0e18ee22e5e3da7cf139977090040622a83' #print('parent', parentBlock) newBlock = Block.newBlock_POA(newBlock, parentBlock, key) try: fntdb.createBlock(newBlock) except: print('Error occurs when saving block into db.') continue #fntdb.updateDBAccountStatus(newBlock) """
def make_genesis(self) -> HashedBlock: b = Block( 0, # block num None, # parent hash BlockConfig(DEFAULT_DIFFICULTY), []) hb = HashedBlock(b) while not hb.hash_meets_difficulty(): hb.replace_mining_entropy(os.urandom(32)) return hb
def generate(cls, user: User, magicnumber: str = None) -> 'Chain': """ Generate new chain. New chain has 2 block; first element is closed, and second element is not closed. >>> chain = Chain.generate(User.generate()) >>> len(chain) 2 >>> chain[0].is_closed() True >>> chain[1].is_closed() False >>> chain[0].verify() True """ root = Block.make_root(user, magicnumber) return cls([root, Block(root)])
def join(self, block: Block) -> None: """ Join new block. """ if (block.is_root() or (block.is_closed() and not block.verify())): raise errors.InvalidChainError() leaf = self[-1] if (leaf.is_closed() and leaf.signature == block.parent.signature and leaf.index + 1 == block.index): self._chain.append(block) elif (block.is_closed() and not leaf.is_closed() and block.index == leaf.index): self._chain.insert(-1, block) self[-1].parent = block self[-1].index += 1 else: raise errors.InvalidChainError() if not self.verify(): raise errors.InvalidChainError()
def generateNextBlock(previousBlock: Block, transactions: List[Transaction]) -> Block: """ Attempts to generate the next block in given new data """ nextIndex = previousBlock.index + 1 nextTimestamp = time.time() noonce = 0 while True: hash = hashBlock(nextIndex, nextTimestamp, transactions, noonce, previousBlock.hash) if hasProofOfWork(hash): return Block(index=nextIndex, timestamp=nextTimestamp, transactions=transactions, noonce=noonce, previousHash=previousBlock.hash) noonce += 1 return None
def mine_on(self, parent: HashedBlock, difficulty: int) -> Optional[HashedBlock]: reward = self.make_reward() config = BlockConfig(difficulty) txns = self.transaction_storage.get_all_transactions() txns.append(reward) self.l.debug("Mining on {} txns".format(len(txns))) block = Block(parent.block_num() + 1, parent.mining_hash(), config, txns) hb = HashedBlock(block) start = time.time() while time.time() - start < 1.0: hb.replace_mining_entropy(os.urandom(32)) if hb.hash_meets_difficulty(): return hb return None
def init_genesis_block(self): genesis_data = "Some random data for genesis block!" genesis_block = Block(genesis_data, 1, self.target_in_string) nonce, timestamp = self.find_nonce(genesis_block) genesis_block.seal(nonce, timestamp) return genesis_block
def __init__(self): self.out = 0 self.blck = Block()
def from_dict(cls, data: typing.Tuple[dict]) -> 'Chain': """ Convert from dictoinary for deserialize. """ return cls([Block.from_dict(b) for b in data])