DAY 4
2
Blockchain

1. 調整哈希難度
2. 計算帳戶餘額
3. 確認哈希值是否正確

調整哈希難度

``````def adjust_difficulty(self):
if len(self.chain) % self.adjust_difficulty_blocks != 1:
return self.difficulty
return self.difficulty
else:
finish = self.chain[-1].timestamp
average_time_consumed = round((finish - start) / (self.adjust_difficulty_blocks), 2)
if average_time_consumed > self.block_time:
print(f"Average block time:{average_time_consumed}s. Lower the difficulty")
self.difficulty -= 1
else:
print(f"Average block time:{average_time_consumed}s. High up the difficulty")
self.difficulty += 1
``````

)

1. 幣價上漲導致更多人參與挖礦以獲取Bitcoin
2. 硬體效能的進步使運算能力飛速成長

計算帳戶餘額

• 區塊獎勵：挖出區塊的礦工能得到區塊的獎勵
• 手續費收入：挖出區塊的礦工能得到該比區塊內所有交易的手續費
• 匯款收入：收到別人匯款的款項

``````def get_balance(self, account):
balance = 0
for block in self.chain:
# Check miner reward
miner = False
if block.miner == account:
miner = True
balance += block.miner_rewards
for transaction in block.transactions:
if miner:
balance += transaction.fee
if transaction.sender == account:
balance -= transaction.amounts
balance -= transaction.fee
balance += transaction.amounts
return balance
``````

確認哈希值是否正確

1. 前一個區塊的hash(`previous_hash`)
2. 區塊產生的時間戳
3. 所有的交易紀錄
4. `nonce`

``````def verify_blockchain(self):
previous_hash = ''
for idx,block in enumerate(self.chain):
if self.get_hash(block, block.nonce) != block.hash:
print("Error:Hash not matched!")
return False
elif previous_hash != block.previous_hash and idx:
print("Error:Hash not matched to previous_hash")
return False
previous_hash = block.hash
print("Hash correct!")
return True
``````

測試一下：

``````if __name__ == '__main__':
block = BlockChain()
block.create_genesis_block()
block.mine_block('lkm543')

block.verify_blockchain()

print("Insert fake transaction.")
fake_transaction = Transaction('test123', address, 100, 1, 'Test')
block.chain[1].transactions.append(fake_transaction)
block.mine_block('lkm543')

block.verify_blockchain()
``````

`"I am Bill Gates"`