Пример #1
0
  public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();
    System.out.println("=== DNS ===");
    printDNS();
    System.out.println("=== Version/chain heights ===");

    ArrayList<InetAddress> addrs = new ArrayList<InetAddress>();
    for (InetSocketAddress peer : dnsPeers) addrs.add(peer.getAddress());
    System.out.println("Scanning " + addrs.size() + " peers:");

    final NetworkParameters params = MainNetParams.get();
    final Object lock = new Object();
    final long[] bestHeight = new long[1];

    List<ListenableFuture<TCPNetworkConnection>> futures = Lists.newArrayList();
    for (final InetAddress addr : addrs) {
      final ListenableFuture<TCPNetworkConnection> future =
          TCPNetworkConnection.connectTo(
              params, new InetSocketAddress(addr, params.getPort()), 1000 /* timeout */);
      futures.add(future);
      // Once the connection has completed version handshaking ...
      Futures.addCallback(
          future,
          new FutureCallback<TCPNetworkConnection>() {
            public void onSuccess(TCPNetworkConnection conn) {
              // Check the chain height it claims to have.
              VersionMessage ver = conn.getVersionMessage();
              long nodeHeight = ver.bestHeight;
              synchronized (lock) {
                long diff = bestHeight[0] - nodeHeight;
                if (diff > 0) {
                  System.out.println("Node is behind by " + diff + " blocks: " + addr);
                } else if (diff == 0) {
                  System.out.println("Node " + addr + " has " + nodeHeight + " blocks");
                  bestHeight[0] = nodeHeight;
                } else if (diff < 0) {
                  System.out.println("Node is ahead by " + Math.abs(diff) + " blocks: " + addr);
                  bestHeight[0] = nodeHeight;
                }
              }
              conn.close();
            }

            public void onFailure(Throwable throwable) {
              System.out.println("Failed to talk to " + addr + ": " + throwable.getMessage());
            }
          });
    }
    // Wait for every tried connection to finish.
    Futures.successfulAsList(futures).get();
  }
Пример #2
0
  public Importer(NetworkParameters params, Jelectrum jelly, BlockStore block_store)
      throws com.google.bitcoin.store.BlockStoreException {
    this.jelly = jelly;
    this.params = params;
    this.file_db = jelly.getDB();
    this.block_store = (MapBlockStore) block_store;

    Config config = jelly.getConfig();
    config.require("block_save_threads");
    config.require("transaction_save_threads");

    block_queue = new LinkedBlockingQueue<Block>(32);
    tx_queue = new LinkedBlockingQueue<TransactionWork>(4096);
    transaction_cache = new LRUCache<Sha256Hash, Transaction>(100000);

    in_progress = new LRUCache<Sha256Hash, Semaphore>(1024);

    save_thread_list = new LinkedList<StatusContext>();
    for (int i = 0; i < config.getInt("block_save_threads"); i++) {
      BlockSaveThread t = new BlockSaveThread();
      save_thread_list.add(t);
      t.start();
    }

    for (int i = 0; i < config.getInt("transaction_save_threads"); i++) {
      TransactionSaveThread t = new TransactionSaveThread();
      save_thread_list.add(t);
      t.start();
    }

    putInternal(params.getGenesisBlock());

    // checkConsistency();

  }
Пример #3
0
  public void checkConsistency() throws com.google.bitcoin.store.BlockStoreException {
    StoredBlock head = block_store.getChainHead();

    StoredBlock curr_block = head;

    Sha256Hash genisis_hash = params.getGenesisBlock().getHash();
    int checked = 0;

    while (true) {
      Sha256Hash curr_hash = curr_block.getHeader().getHash();

      if (curr_block.getHeight() % 10000 == 0) {
        System.out.println("Block: " + curr_block.getHeight());
      }
      if (!file_db.getBlockMap().containsKey(curr_hash)) {
        throw new RuntimeException("Missing block: " + curr_hash);
      }
      checked++;
      // if (checked > 20) return;

      if (curr_hash.equals(genisis_hash)) return;

      curr_block = curr_block.getPrev(block_store);
    }
  }
Пример #4
0
 private void parsePaymentRequest(Protos.PaymentRequest request) throws PaymentRequestException {
   try {
     if (request == null) throw new PaymentRequestException("request cannot be null");
     if (!request.hasPaymentDetailsVersion())
       throw new PaymentRequestException.InvalidVersion("No version");
     if (request.getPaymentDetailsVersion() != 1)
       throw new PaymentRequestException.InvalidVersion(
           "Version 1 required. Received version " + request.getPaymentDetailsVersion());
     paymentRequest = request;
     if (!request.hasSerializedPaymentDetails())
       throw new PaymentRequestException("No PaymentDetails");
     paymentDetails =
         Protos.PaymentDetails.newBuilder()
             .mergeFrom(request.getSerializedPaymentDetails())
             .build();
     if (paymentDetails == null) throw new PaymentRequestException("Invalid PaymentDetails");
     if (!paymentDetails.hasNetwork()) params = MainNetParams.get();
     else params = NetworkParameters.fromPmtProtocolID(paymentDetails.getNetwork());
     if (params == null)
       throw new PaymentRequestException.InvalidNetwork(
           "Invalid network " + paymentDetails.getNetwork());
     if (paymentDetails.getOutputsCount() < 1)
       throw new PaymentRequestException.InvalidOutputs("No outputs");
     for (Protos.Output output : paymentDetails.getOutputsList()) {
       if (output.hasAmount()) totalValue = totalValue.add(BigInteger.valueOf(output.getAmount()));
     }
     // This won't ever happen in practice. It would only happen if the user provided outputs
     // that are obviously invalid. Still, we don't want to silently overflow.
     if (totalValue.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0)
       throw new PaymentRequestException.InvalidOutputs("The outputs are way too big.");
   } catch (InvalidProtocolBufferException e) {
     throw new PaymentRequestException(e);
   }
 }
  /**
   * Parses a wallet from the given stream, using the provided Wallet instance to load data into.
   * This is primarily used when you want to register extensions. Data in the proto will be added
   * into the wallet where applicable and overwrite where not.
   */
  public Wallet readWallet(InputStream input) throws IOException {
    Protos.Wallet walletProto = parseToProto(input);

    // System.out.println(TextFormat.printToString(walletProto));

    NetworkParameters params = NetworkParameters.fromID(walletProto.getNetworkIdentifier());
    Wallet wallet = new Wallet(params);
    readWallet(walletProto, wallet);
    return wallet;
  }
Пример #6
0
public class Constants {

  public static final NetworkParameters NETWORK_PARAMETERS = MainNetParams.get();
  private static final String FILENAME_NETWORK_SUFFIX =
      NETWORK_PARAMETERS.getId().equals(NetworkParameters.ID_MAINNET) ? "" : "-testnet";
  public static final String WALLET_FILENAME_PROTOBUF = "hardwarewallet" + FILENAME_NETWORK_SUFFIX;
  public static final String INI_KEY_FILENAME = "ini" + FILENAME_NETWORK_SUFFIX;
  public static final Charset UTF_8 = Charset.forName("UTF-8");
  public static final Charset US_ASCII = Charset.forName("US-ASCII");
}
Пример #7
0
  public void run() {

    PeerDiscovery peerDiscovery = new DnsDiscovery(NetworkParameters.prodNet());
    try {
      while (true) {
        InetSocketAddress addresses[] = peerDiscovery.getPeers();
        // InetSocketAddress addresses[]={new InetSocketAddress("localhost",8333)};
        System.out.println("peers " + addresses.length);
        NetworkConnection conn;
        Peer peer;
        System.out.println("connecting to peers");

        for (InetSocketAddress a : addresses) {
          try {
            System.out.println("Trying " + a);
            conn =
                new NetworkConnection(
                    a.getAddress(),
                    Bitten.networkParameters,
                    blockChain.getChainHead().getHeight(),
                    3000);
            System.out.println("after network connection");
            peer = new Peer(Bitten.networkParameters, conn, blockChain);
            System.out.println("starting chain download");
            peer.start();
            peer.startBlockChainDownload();
            while (true) {
              if (!peer.running()) {
                System.out.println("peer stopped!");
                break;
              }
              sleep(1000);
            }
          } catch (IOException e) {
            System.out.println(e);
            continue;
          } catch (ProtocolException e) {
            continue;
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            continue;
          }
        }
      }

    } catch (PeerDiscoveryException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Пример #8
0
  public static void main(String[] args) throws AddressFormatException {

    Node lenode = Node.getInstance();
    NodeWallet lewallet = lenode.getWallet();
    BigInteger leinteger = BigInteger.valueOf(20000000);
    System.out.print(leinteger);
    NetworkParameters netParams = NetworkParameters.testNet();
    // leaddress.equals("mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn");
    Address targetAddress = new Address(netParams, "mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn");
    // Address.getParametersFromAddress("mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn");
    lewallet.setBalance(targetAddress, leinteger);
    // BigInteger result = lewallet.getBalance(leaddress);
    System.out.print(targetAddress.toString());
  }
Пример #9
0
  @Test
  public void testReplayManagerSyncSingleWallet() throws Exception {
    // Get the system property runFunctionalTest to see if the functional
    // tests need running.
    String runFunctionalTests = System.getProperty(Constants.RUN_FUNCTIONAL_TESTS_PARAMETER);
    if (Boolean.TRUE.toString().equalsIgnoreCase(runFunctionalTests)) {
      // Date format is UTC with century, T time separator and Z for UTC
      // timezone.
      formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
      formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

      // Initialise replay manager
      ReplayManager replayManager = ReplayManager.INSTANCE;
      assertNotNull(replayManager);

      replayManager.initialise(controller, true);

      String replayWalletPath =
          multiBitDirectory.getAbsolutePath() + File.separator + "replay.wallet";

      // Create a new wallet.
      Wallet replayWallet = new Wallet(NetworkParameters.prodNet());

      // Add in the replay key.
      DumpedPrivateKey replayDumpedPrivateKey =
          new DumpedPrivateKey(NetworkParameters.prodNet(), REPLAY1_PRIVATE_KEY);
      ECKey replayKey = replayDumpedPrivateKey.getKey();
      replayKey.setCreationTimeSeconds(formatter.parse(START_OF_REPLAY_PERIOD).getTime() / 1000);
      log.debug("replayPrivateKey getCreationTimeSeconds = " + replayKey.getCreationTimeSeconds());

      replayWallet.addKey(replayKey);
      WalletData perWalletModelData = new WalletData();
      perWalletModelData.setWalletInfo(
          new WalletInfoData(replayWalletPath, replayWallet, MultiBitWalletVersion.PROTOBUF));
      perWalletModelData.setWallet(replayWallet);
      perWalletModelData.setWalletFilename(replayWalletPath);
      perWalletModelData.setWalletDescription("testReplayManagerSyncSingleWallet test");
      controller.getModel().getPerWalletModelDataList().add(perWalletModelData);

      log.debug("Replay wallet before replay = \n" + replayWallet.toString());

      assertEquals(BALANCE_AT_START, replayWallet.getBalance());

      log.debug("Replaying blockchain");
      // Create a ReplayTask to replay the replay wallet from the
      // START_OF_REPLAY_PERIOD.
      List<WalletData> perWalletModelDataList = new ArrayList<WalletData>();
      perWalletModelDataList.add(perWalletModelData);

      ReplayTask replayTask =
          new ReplayTask(
              perWalletModelDataList,
              formatter.parse(START_OF_REPLAY_PERIOD),
              ReplayTask.UNKNOWN_START_HEIGHT);
      replayManager.offerReplayTask(replayTask);

      // Run for a while.
      log.debug("Twiddling thumbs for 60 seconds ...");
      Thread.sleep(60000);
      log.debug("... 60 seconds later.");

      // Check the wallet - there should be some transactions in there.
      if (replayWallet.getTransactions(true).size() > 0) {
        // We are done.
      } else {
        // Run for a while longer.
        log.debug("Twiddling thumbs for another 60 seconds ...");
        Thread.sleep(60000);
        log.debug("... 60 seconds later.");
        if (replayWallet.getTransactions(true).size() > 0) {
          // We are done.
        } else {
          if (simpleViewSystem.getNumberOfBlocksDownloaded() > 0) {
            // Well it tried but probably got a slow connection -
            // give it a pass.
          } else {
            fail("No blocks were downloaded on replay");
          }
        }
      }

      // Print out replay wallet after replay.
      log.debug("Replay wallet after replay = \n" + replayWallet);
    } else {
      log.debug(
          "Not running functional test: ReplayManagerTest#testReplayManagerSyncSingleWallet. Add '-DrunFunctionalTests=true' to run");
    }
  }
  @Test
  public void testReplayMiningTransaction() throws Exception {
    // Get the system property runFunctionalTest to see if the functional tests need running.
    String runFunctionalTests = System.getProperty(Constants.RUN_FUNCTIONAL_TESTS_PARAMETER);
    if (Boolean.TRUE.toString().equalsIgnoreCase(runFunctionalTests)) {

      // Date format is UTC with century, T time separator and Z for UTC timezone.
      formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
      formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

      File multiBitDirectory = createMultiBitRuntime();

      // Set the application data directory to be the one we just created.
      ApplicationDataDirectoryLocator applicationDataDirectoryLocator =
          new ApplicationDataDirectoryLocator(multiBitDirectory);
      log.debug("applicationDataDirectoryLocator = " + applicationDataDirectoryLocator);

      // Create MultiBit controller.
      final CreateControllers.Controllers controllers =
          CreateControllers.createControllers(applicationDataDirectoryLocator);

      log.debug("Creating Bitcoin service");
      // Create the MultiBitService that connects to the bitcoin network.
      MultiBitService multiBitService = new MultiBitService(controllers.bitcoinController);
      log.debug("multiBitService = " + multiBitService);

      controllers.bitcoinController.setMultiBitService(multiBitService);

      // Add the simple view system (no Swing).
      SimpleViewSystem simpleViewSystem = new SimpleViewSystem();
      controllers.coreController.registerViewSystem(simpleViewSystem);
      log.debug("simpleViewSystem = " + simpleViewSystem);

      ReplayManager.INSTANCE.initialise(controllers.bitcoinController);

      //
      // MultiBit runtime is now setup and running.
      //

      String miningWalletPath =
          multiBitDirectory.getAbsolutePath() + File.separator + "mining.wallet";

      // Create a new wallet.
      Wallet miningWallet = new Wallet(NetworkParameters.prodNet());

      // Add in the mining key that has the coinbase transactions.
      DumpedPrivateKey miningPrivateKey =
          new DumpedPrivateKey(NetworkParameters.prodNet(), MINING_PRIVATE_KEY);

      miningWallet.addKey(miningPrivateKey.getKey());
      WalletData perWalletModelData = new WalletData();
      perWalletModelData.setWalletInfo(
          new WalletInfoData(miningWalletPath, MultiBitWalletVersion.PROTOBUF));
      perWalletModelData.setWallet(miningWallet);
      perWalletModelData.setWalletFilename(miningWalletPath);
      perWalletModelData.setWalletDescription("testReplayMiningTransaction test");

      // Save the new wallet.
      controllers
          .bitcoinController
          .getFileHandler()
          .savePerWalletModelData(perWalletModelData, true);

      // Get the multibitService to load it up and hook it up to the blockchain.
      controllers.bitcoinController.getMultiBitService().addWalletFromFilename(miningWalletPath);
      controllers.bitcoinController.getModel().setActiveWalletByFilename(miningWalletPath);

      log.debug("Mining wallet = \n" + miningWallet.toString());

      assertEquals(BALANCE_AT_START, miningWallet.getBalance());

      // Wait for a peer connection.
      log.debug("Waiting for peer connection. . . ");
      while (!simpleViewSystem.isOnline()) {
        Thread.sleep(1000);
      }
      log.debug("Now online.");

      log.debug("Replaying blockchain");
      // multiBitService.replayBlockChain(formatter.parse(START_OF_REPLAY_PERIOD));
      List<WalletData> perWalletModelDataList = new ArrayList<WalletData>();
      perWalletModelDataList.add(
          controllers.bitcoinController.getModel().getActivePerWalletModelData());
      ReplayTask replayTask =
          new ReplayTask(
              perWalletModelDataList,
              formatter.parse(START_OF_REPLAY_PERIOD),
              ReplayTask.UNKNOWN_START_HEIGHT);
      ReplayManager.INSTANCE.offerReplayTask(replayTask);

      // Run for a minute.
      log.debug("Twiddling thumbs for a minute ...");
      Thread.sleep(60000);
      log.debug("... one minute later.");

      // Check new balance on wallet - estimated balance should be at least the
      // expected (may have later tx too)..

      log.debug(
          "Mining wallet estimated balance is:\n"
              + controllers
                  .bitcoinController
                  .getModel()
                  .getActiveWallet()
                  .getBalance(BalanceType.ESTIMATED)
                  .toString());
      log.debug(
          "Mining wallet spendable balance is:\n"
              + controllers.bitcoinController.getModel().getActiveWallet().getBalance().toString());
      log.debug(
          "Mining wallet is:\n"
              + controllers.bitcoinController.getModel().getActiveWallet().toString());
      assertTrue(
          "Estimated balance of mining wallet is incorrect",
          BALANCE_AFTER_REPLAY.compareTo(
                  controllers
                      .bitcoinController
                      .getModel()
                      .getActiveWallet()
                      .getBalance(BalanceType.ESTIMATED))
              <= 0);
      // assertTrue("Available balance of mining wallet is incorrect",
      // BigInteger.ZERO.compareTo(controller.getModel().getActiveWallet().getBalance()) == 0);

      // See if the first transaction is a coinbase.
      miningWallet = controllers.bitcoinController.getModel().getActiveWallet();

      Set<Transaction> transactions = miningWallet.getTransactions(true);
      assertTrue("Transactions are missing", !(transactions == null || transactions.isEmpty()));
      Transaction transaction = transactions.iterator().next();
      assertNotNull("First transaction is null", transaction);
      System.out.println("First transaction before roundtrip\n" + transaction);

      assertTrue(
          "The first transaction in the wallet is not a coinbase but it should be",
          transaction.isCoinBase());

      // Force save the wallet, reload it and check the transaction is still coinbase.
      controllers
          .bitcoinController
          .getFileHandler()
          .savePerWalletModelData(perWalletModelData, true);

      WalletData rebornPerWalletModelData =
          controllers.bitcoinController.getFileHandler().loadFromFile(new File(miningWalletPath));
      assertNotNull("No reborn perWalletModelData", rebornPerWalletModelData);
      ;
      assertNotNull("No reborn wallet", rebornPerWalletModelData.getWallet());

      Wallet rebornMiningWallet = rebornPerWalletModelData.getWallet();

      // See if the first transaction in the reborn wallet is a coinbase.
      Set<Transaction> rebornTransactions = rebornMiningWallet.getTransactions(true);
      assertTrue(
          "No reborn transactions", !(rebornTransactions == null || rebornTransactions.isEmpty()));
      Transaction rebornTransaction = rebornTransactions.iterator().next();
      assertNotNull("No reborn first transaction", rebornTransaction);
      System.out.println("First transaction after roundtrip\n" + rebornTransaction);

      assertTrue(
          "The first transaction in the wallet is not a coinbase but it should be",
          rebornTransaction.isCoinBase());

      // Tidy up.
      multiBitService.getPeerGroup().stop();

      controllers
          .bitcoinController
          .getFileHandler()
          .deleteWalletAndWalletInfo(
              controllers.bitcoinController.getModel().getActivePerWalletModelData());
    } else {
      log.debug(
          "Not running functional test: MiningCoinBaseTransactionsSeenTest#testReplayMiningTransaction. Add '-DrunFunctionalTests=true' to run");
    }
  }