Ejemplo n.º 1
0
 /**
  * Let's insert a block into our blockchain.
  * 
  * @param stirng $jsondata
  * @param string $merkleroot
  * @param int $blockId
  * @param string $prevhash
  */
 private function insertBlock($jsondata, $merkleroot, $blockId, $prevhash)
 {
     $msg = \json_decode($jsondata, true);
     // This still ought to be a JSON encoded string:
     $blockdata = \base64_decode($msg['blockdata']);
     $mtree = new Structs\MerkleTree(\json_decode($blockdata, true));
     /* 1. Verify merkle root (both should be hex encoded) */
     if (!\hash_equals($merkleroot, $mtree->getRoot())) {
         echo \json_encode(['error' => 'Invalid Merkle Root.'], JSON_PRETTY_PRINT);
         exit;
     }
     // Grab previous tailhash:
     $tail = $this->db->selectRow('blocks', ['id', 'hash'], [], [['id', DESC]]);
     // If our previous hash does not equal the pointer to the prevhash in
     // the current block, something screwy is going on.
     if (!\hash_equals($tail['hash'], $prevhash)) {
         echo \json_encode(['error' => 'Blockchain tail hash mismatch!'], JSON_PRETTY_PRINT);
         exit;
     }
     // Update previous tail block to point to the new addition
     $this->db->update('blocks', ['nexthash' => $merkleroot, 'nextblock' => $blockId], ['id' => $tail['id']]);
     // Insert a new block
     return $this->db->insert('blocks', ['id' => $blockId, 'hash' => $merkleroot, 'prevblock' => $tail['id'], 'prevhash' => $tail['hash'], 'contents' => $blockdata, 'verified' => 0]);
 }
Ejemplo n.º 2
0
 public function testHash()
 {
     $tree1 = new Structs\MerkleTree(['a', 'b', 'c', 'd', 'e']);
     $tree2 = new Structs\MerkleTree(['a', 'b', 'c', 'd', 'e', 'e', 'e', 'e']);
     $this->assertTrue(\hash_equals($tree1->getRoot(), $tree2->getRoot()));
 }