예제 #1
0
 public void testEquals() {
   Block b = new Block(123, 100, 200, 122); // random block
   Block c = new Block(123, 100, 200, 122);
   Block d = new Block(123, 100, 200, 123);
   assertTrue(b.equals(c));
   assertFalse(b.equals(d));
 }
예제 #2
0
파일: BlockTest.java 프로젝트: veeyu/veeju
 @Test
 public void testEquals() {
   final Block block = new Block(program), block2 = new Block(program);
   assertTrue(block.equals(block2));
   assertTrue(block2.equals(block2));
   assertFalse(block.equals(new Block()));
 }
예제 #3
0
  private synchronized boolean add(Block block, boolean tryConnecting)
      throws BlockStoreException, VerificationException, ScriptException {
    if (System.currentTimeMillis() - statsLastTime > 1000) {
      // More than a second passed since last stats logging.
      log.info("{} blocks per second", statsBlocksAdded);
      statsLastTime = System.currentTimeMillis();
      statsBlocksAdded = 0;
    }
    // We check only the chain head for double adds here to avoid potentially expensive block chain
    // misses.
    if (block.equals(chainHead.getHeader())) {
      // Duplicate add of the block at the top of the chain, can be a natural artifact of the
      // download process.
      return true;
    }

    // Prove the block is internally valid: hash is lower than target, merkle root is correct and so
    // on.
    try {
      block.verify();
    } catch (VerificationException e) {
      log.error("Failed to verify block:", e);
      log.error(block.toString());
      throw e;
    }

    // Try linking it to a place in the currently known blocks.
    StoredBlock storedPrev = blockStore.get(block.getPrevBlockHash());

    if (storedPrev == null) {
      // We can't find the previous block. Probably we are still in the process of downloading the
      // chain and a
      // block was solved whilst we were doing it. We put it to one side and try to connect it later
      // when we
      // have more blocks.
      log.warn("Block does not connect: {}", block.getHashAsString());
      unconnectedBlocks.add(block);
      return false;
    } else {
      // It connects to somewhere on the chain. Not necessarily the top of the best known chain.
      //
      // Create a new StoredBlock from this block. It will throw away the transaction data so when
      // block goes
      // out of scope we will reclaim the used memory.
      StoredBlock newStoredBlock = storedPrev.build(block);
      checkDifficultyTransitions(storedPrev, newStoredBlock);
      blockStore.put(newStoredBlock);
      // block.transactions may be null here if we received only a header and not a full block. This
      // does not
      // happen currently but might in future if getheaders is implemented.
      connectBlock(newStoredBlock, storedPrev, block.transactions);
    }

    if (tryConnecting) tryConnectingUnconnected();

    statsBlocksAdded++;
    return true;
  }
예제 #4
0
 @Override
 public boolean equals(Object o) {
   if (this == o) return true;
   if (o == null || getClass() != o.getClass()) return false;
   StoredBlock other = (StoredBlock) o;
   return header.equals(other.header)
       && chainWork.equals(other.chainWork)
       && height == other.height;
 }
  // filteredTxHashList contains all transactions, filteredTxn just a subset
  private boolean add(
      Block block,
      boolean tryConnecting,
      @Nullable List<Sha256Hash> filteredTxHashList,
      @Nullable Map<Sha256Hash, Transaction> filteredTxn)
      throws BlockStoreException, VerificationException, PrunedException {
    // TODO: Use read/write locks to ensure that during chain download properties are still low
    // latency.
    lock.lock();
    try {
      // Quick check for duplicates to avoid an expensive check further down (in findSplit). This
      // can happen a lot
      // when connecting orphan transactions due to the dumb brute force algorithm we use.
      if (block.equals(getChainHead().getHeader())) {
        return true;
      }
      if (tryConnecting && orphanBlocks.containsKey(block.getHash())) {
        return false;
      }

      // If we want to verify transactions (ie we are running with full blocks), verify that block
      // has transactions
      if (shouldVerifyTransactions() && block.transactions == null)
        throw new VerificationException("Got a block header while running in full-block mode");

      // Check for already-seen block, but only for full pruned mode, where the DB is
      // more likely able to handle these queries quickly.
      if (shouldVerifyTransactions() && blockStore.get(block.getHash()) != null) {
        return true;
      }

      // Does this block contain any transactions we might care about? Check this up front before
      // verifying the
      // blocks validity so we can skip the merkle root verification if the contents aren't
      // interesting. This saves
      // a lot of time for big blocks.
      boolean contentsImportant = shouldVerifyTransactions();
      if (block.transactions != null) {
        contentsImportant = contentsImportant || containsRelevantTransactions(block);
      }

      // Prove the block is internally valid: hash is lower than target, etc. This only checks the
      // block contents
      // if there is a tx sending or receiving coins using an address in one of our wallets. And
      // those transactions
      // are only lightly verified: presence in a valid connecting block is taken as proof of
      // validity. See the
      // article here for more details: http://code.google.com/p/bitcoinj/wiki/SecurityModel
      try {
        block.verifyHeader();
        if (contentsImportant) block.verifyTransactions();

      } catch (VerificationException e) {
        log.error("Failed to verify block: ", e);
        log.error(block.getHashAsString());
        throw e;
      }

      // Try linking it to a place in the currently known blocks.
      StoredBlock storedPrev = getStoredBlockInCurrentScope(block.getPrevBlockHash());
      if (storedPrev == null) {
        // We can't find the previous block. Probably we are still in the process of downloading the
        // chain and a
        // block was solved whilst we were doing it. We put it to one side and try to connect it
        // later when we
        // have more blocks.
        checkState(tryConnecting, "bug in tryConnectingOrphans");
        log.warn(
            "Block does not connect: {} prev {}",
            block.getHashAsString(),
            block.getPrevBlockHash());
        orphanBlocks.put(block.getHash(), new OrphanBlock(block, filteredTxHashList, filteredTxn));
        return false;
      } else {
        checkState(lock.isHeldByCurrentThread());
        // It connects to somewhere on the chain. Not necessarily the top of the best known chain.
        params.checkDifficultyTransitions(storedPrev, block, blockStore);
        connectBlock(
            block, storedPrev, shouldVerifyTransactions(), filteredTxHashList, filteredTxn);
      }
      if (tryConnecting) tryConnectingOrphans();
      return true;
    } finally {
      lock.unlock();
    }
  }
예제 #6
0
 private void load(File file) throws IOException, BlockStoreException {
   log.info("Reading block store from {}", file);
   InputStream input = null;
   try {
     input = new BufferedInputStream(new FileInputStream(file));
     // Read a version byte.
     int version = input.read();
     if (version == -1) {
       // No such file or the file was empty.
       throw new FileNotFoundException(file.getName() + " does not exist or is empty");
     }
     if (version != 1) {
       throw new BlockStoreException("Bad version number: " + version);
     }
     // Chain head pointer is the first thing in the file.
     byte[] chainHeadHash = new byte[32];
     if (input.read(chainHeadHash) < chainHeadHash.length)
       throw new BlockStoreException("Truncated block store: cannot read chain head hash");
     this.chainHead = new Sha256Hash(chainHeadHash);
     log.info("Read chain head from disk: {}", this.chainHead);
     long now = System.currentTimeMillis();
     // Rest of file is raw block headers.
     byte[] headerBytes = new byte[Block.HEADER_SIZE];
     try {
       while (true) {
         // Read a block from disk.
         if (input.read(headerBytes) < 80) {
           // End of file.
           break;
         }
         // Parse it.
         Block b = new Block(params, headerBytes);
         // Look up the previous block it connects to.
         StoredBlock prev = get(b.getPrevBlockHash());
         StoredBlock s;
         if (prev == null) {
           // First block in the stored chain has to be treated specially.
           if (b.equals(params.genesisBlock)) {
             s =
                 new StoredBlock(
                     params.genesisBlock.cloneAsHeader(), params.genesisBlock.getWork(), 0);
           } else {
             throw new BlockStoreException(
                 "Could not connect "
                     + b.getHash().toString()
                     + " to "
                     + b.getPrevBlockHash().toString());
           }
         } else {
           // Don't try to verify the genesis block to avoid upsetting the unit tests.
           b.verifyHeader();
           // Calculate its height and total chain work.
           s = prev.build(b);
         }
         // Save in memory.
         blockMap.put(b.getHash(), s);
       }
     } catch (ProtocolException e) {
       // Corrupted file.
       throw new BlockStoreException(e);
     } catch (VerificationException e) {
       // Should not be able to happen unless the file contains bad blocks.
       throw new BlockStoreException(e);
     }
     long elapsed = System.currentTimeMillis() - now;
     log.info("Block chain read complete in {}ms", elapsed);
   } finally {
     if (input != null) input.close();
   }
 }
예제 #7
0
 public void testClone() {
   Block b = new Block(123, 100, 200, 122); // random block
   Block bclone = b.clone();
   assertTrue(b.equals(bclone));
 }
예제 #8
0
  private static void runProblem2() throws IOException {
    table = createTable(Double.class, 4, 3, -0.04);

    table.removeCell(2, 2);
    table.getCellAt(4, 3).setContent(1.0);
    table.getCellAt(4, 2).setContent(-1.0);

    MarkovProc<Block<Double>, BlockAction> mdp = createMDP(table);
    VI<Block<Double>, BlockAction> vi = new VI<Block<Double>, BlockAction>(1.0);

    Map<Block<Double>, BlockAction> optimalAction = new LinkedHashMap<Block<Double>, BlockAction>();

    Map<Block<Double>, Double> U = vi.valueIteration(mdp, 0.0001, optimalAction);

    Map<Double, Integer> run10 = new LinkedHashMap();
    Map<Double, Integer> run100 = new LinkedHashMap();
    Map<Double, Integer> run1000 = new LinkedHashMap();

    int i = 0;

    ArrayList<Double> rewardsHolder = new ArrayList<Double>();
    ArrayList<Double> rewardsHolder1 = new ArrayList<Double>();
    ArrayList<Double> rewardsHolder2 = new ArrayList<Double>();

    Double firstRunReward = 0.0;

    while (i++ < 10) {

      Block<Double> start = table.getCellAt(4, 1);
      Block<Double> end1 = table.getCellAt(4, 3);
      Block<Double> end2 = table.getCellAt(4, 2);

      Block<Double> current = start;
      double rewards = 0.0;

      while (current.equals(end1) == false && current.equals(end2) == false) {

        BlockAction a = optimalAction.get(current);
        rewards += current.getContent();
        double r = Math.random() * 100;
        if (r > 20.0) {
          current = table.result(current, a);
        } else if (r > 10.0 && r <= 20.0) {
          current = table.result(current, a.getFirstRightAngledAction());
        } else {
          current = table.result(current, a.getSecondRightAngledAction());
        }
      }

      rewards += current.getContent();

      if (i == 1) {
        firstRunReward = rewards;
      }

      if (run10.containsKey(rewards)) {
        Integer k = run10.get(rewards);
        k++;
        run10.put(rewards, k);
        rewardsHolder.add(rewards);
      } else {
        run10.put(rewards, 1);
        rewardsHolder.add(rewards);
      }
    }

    i = 0;

    while (i++ < 100) {

      Block<Double> start = table.getCellAt(4, 1);
      Block<Double> end1 = table.getCellAt(4, 3);
      Block<Double> end2 = table.getCellAt(4, 2);

      Block<Double> current = start;
      double rewards = 0.0;

      while (current != end1 && current != end2) {

        BlockAction a = optimalAction.get(current);
        rewards += current.getContent();
        double r = Math.random() * 100;
        if (r > 20.0) {
          current = table.result(current, a);
        } else if (r > 10.0 && r <= 20.0) {
          current = table.result(current, a.getFirstRightAngledAction());
        } else {
          current = table.result(current, a.getSecondRightAngledAction());
        }
      }

      rewards += current.getContent();

      if (run100.containsKey(rewards)) {
        Integer k = run100.get(rewards);
        k++;
        run100.put(rewards, k);
        rewardsHolder1.add(rewards);

      } else {
        run100.put(rewards, 1);
        rewardsHolder1.add(rewards);
      }
    }

    i = 0;

    while (i++ < 1000) {

      Block<Double> start = table.getCellAt(4, 1);
      Block<Double> end1 = table.getCellAt(4, 3);
      Block<Double> end2 = table.getCellAt(4, 2);

      Block<Double> current = start;
      double rewards = 0.0;

      while (current != end1 && current != end2) {

        BlockAction a = optimalAction.get(current);
        rewards += current.getContent();
        double r = Math.random() * 100;
        if (r > 20.0) {
          current = table.result(current, a);
        } else if (r > 10.0 && r <= 20.0) {
          current = table.result(current, a.getFirstRightAngledAction());
        } else {
          current = table.result(current, a.getSecondRightAngledAction());
        }
      }

      rewards += current.getContent();

      if (run1000.containsKey(rewards)) {
        Integer k = run1000.get(rewards);
        k++;
        run1000.put(rewards, k);
        rewardsHolder2.add(rewards);
      } else {
        run1000.put(rewards, 1);
        rewardsHolder2.add(rewards);
      }
    }

    Block<Double> start = table.getCellAt(4, 1);
    Block<Double> end1 = table.getCellAt(4, 3);
    Block<Double> end2 = table.getCellAt(4, 2);

    Block<Double> current = start;
    Double exprewards = 0.0;

    while (current != end1 && current != end2) {

      BlockAction a = optimalAction.get(current);
      exprewards += current.getContent();

      current = table.result(current, a);
    }

    exprewards += current.getContent();

    FileWriter fstream = new FileWriter("P2-histogram.txt");
    BufferedWriter out = new BufferedWriter(fstream);

    out.write("10 runs");
    out.write(System.getProperty("line.separator"));

    TreeSet<Double> keys = new TreeSet<Double>(run10.keySet());
    for (Double rewards : keys) {
      Integer count = run10.get(rewards);
      // do something

      String rewstr = rewards.toString();
      if (rewards.toString().length() > 8) {
        rewstr = rewstr.substring(0, 7);
      }
      out.write(rewstr + "\t\t" + count.toString());
      out.write(System.getProperty("line.separator"));

      // System.out.println(pairs.getKey() + " = " + pairs.getValue());
      // it.remove(); // avoids a ConcurrentModificationException
    }

    out.write("100 runs");
    out.write(System.getProperty("line.separator"));

    keys = new TreeSet<Double>(run100.keySet());
    for (Double rewards : keys) {
      Integer count = run100.get(rewards);
      // do something

      String rewstr = rewards.toString();
      if (rewards.toString().length() > 8) {
        rewstr = rewstr.substring(0, 7);
      }
      out.write(rewstr + "\t\t" + count.toString());
      out.write(System.getProperty("line.separator"));

      // System.out.println(pairs.getKey() + " = " + pairs.getValue());
      // it.remove(); // avoids a ConcurrentModificationException
    }

    out.write("1000 runs");
    out.write(System.getProperty("line.separator"));

    keys = new TreeSet<Double>(run1000.keySet());
    for (Double rewards : keys) {
      Integer count = run1000.get(rewards);
      // do something

      String rewstr = rewards.toString();
      if (rewards.toString().length() > 8) {
        rewstr = rewstr.substring(0, 7);
      }
      out.write(rewstr + "\t\t" + count.toString());
      out.write(System.getProperty("line.separator"));

      // System.out.println(pairs.getKey() + " = " + pairs.getValue());
      // it.remove(); // avoids a ConcurrentModificationException
    }

    out.close();

    FileWriter fstream1 = new FileWriter("P2-output.txt");
    BufferedWriter out1 = new BufferedWriter(fstream1);
    out1.write("Optimum utility when  -0.04");
    out1.write(System.getProperty("line.separator"));

    printUtil(4, 3, U, out1);

    out1.write(System.getProperty("line.separator"));
    out1.write("______________________________________________________");

    out1.write(System.getProperty("line.separator"));

    out1.write("First Run reward is " + roundString(firstRunReward.toString()));
    out1.write(System.getProperty("line.separator"));

    out1.write("Mean for 10 runs :");
    // Set<Double> rewVec = (Set<Double>) run10.keySet();
    Double meanval = FindMean(rewardsHolder);
    out1.write(roundString(meanval.toString()));
    out1.write(System.getProperty("line.separator"));

    out1.write("SD for 10 runs: ");
    Double sdVal = FindSD(rewardsHolder, meanval);

    out1.write(roundString(sdVal.toString()));
    out1.write(System.getProperty("line.separator"));

    out1.write("Mean for 100 runs :");
    // rewVec = (Set<Double>) run100.keySet();
    meanval = FindMean(rewardsHolder1);
    out1.write(roundString(meanval.toString()));
    out1.write(System.getProperty("line.separator"));

    out1.write("SD for 100 runs: ");
    sdVal = FindSD(rewardsHolder1, meanval);

    out1.write(roundString(sdVal.toString()));
    out1.write(System.getProperty("line.separator"));

    out1.write("Mean for 1000 runs :");
    // rewVec = (Set<Double>) run1000.keySet();
    meanval = FindMean(rewardsHolder2);
    out1.write(roundString(meanval.toString()));
    out1.write(System.getProperty("line.separator"));

    out1.write("SD for 1000 runs: ");
    sdVal = FindSD(rewardsHolder2, meanval);

    out1.write(roundString(sdVal.toString()));
    out1.write(System.getProperty("line.separator"));
    out1.write(System.getProperty("line.separator"));

    out1.write("Expected reward from start state: ");
    out1.write(roundString(exprewards.toString()));
    out1.close();
  }
예제 #9
0
 @Override
 public boolean equals(
     int position, int offset, Block otherBlock, int otherPosition, int otherOffset, int length) {
   return value.equals(0, offset, otherBlock, otherPosition, otherOffset, length);
 }