daily pastebin goal
45%
SHARE
TWEET

Untitled

a guest Apr 16th, 2018 51 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Blockchain : Codable  {
  2.    
  3.     var blocks :[Block] = [Block]()
  4.    
  5.    
  6.     init(genesisBlock :Block) {
  7.         addBlock(genesisBlock)
  8.     }
  9.    
  10.    
  11.     func addBlock(_ block :Block) {
  12.        
  13.         if self.blocks.isEmpty {
  14.             block.previousHash = "0000000000000000"
  15.             block.hash = generateHash(for :block)
  16.         }
  17.        
  18.         self.blocks.append(block)
  19.     }
  20.    
  21.    
  22.     func getNextBlock(transactions :[Transaction]) -> Block {
  23.        
  24.         let block = Block()
  25.         transactions.forEach { transaction in
  26.            
  27.             block.addTransaction(transaction: transaction)
  28.         }
  29.        
  30.         let previousBlock = getPreviousBlock()
  31.         block.index = self.blocks.count
  32.         block.previousHash = previousBlock.hash
  33.         block.hash = generateHash(for: block)
  34.         return block
  35.        
  36.     }
  37.    
  38.     private func getPreviousBlock() -> Block {
  39.         return self.blocks[self.blocks.count - 1]
  40.     }
  41.    
  42.     func generateHash(for block :Block) -> String {
  43.        
  44.         var hash = block.key.sha1Hash()
  45.        
  46.         while(!hash.hasPrefix("00")) {
  47.             block.nonce += 1
  48.             hash = block.key.sha1Hash()
  49.             print(hash)
  50.         }
  51.        
  52.         return hash
  53.     }
  54.    
  55. }
RAW Paste Data
Top