Пример #1
0
  public String toString() {
    if (operation == null) return "";
    StringBuffer res = new StringBuffer("(");
    res.append(operation.toString()).append(",");
    if (Operand1 != null) res.append(Operand1.toString());
    res.append(",");
    if (Operand2 != null) res.append(Operand2.toString());
    res.append(",");
    if (Operand3 != null) res.append(Operand3.toString());
    res.append(")");

    return res.toString();
  }
Пример #2
0
  /** Test various combinations of the toString (multi) method */
  public void testToStringMulti() {
    final Address[] address = Address.parse("*****@*****.**");
    final Address[] addresses = Address.parse(MULTI_ADDRESSES_LIST);

    assertEquals("multi addrsses count", MULTI_ADDRESSES_COUNT, addresses.length);

    {
      String line = Address.toString(address);
      assertEquals("toString multi-1", "*****@*****.**", line);
    }
    {
      String line = Address.toString(addresses);
      assertEquals(
          "toString multi-n",
          "[email protected],"
              + "[email protected],"
              + "simple name <*****@*****.**>,"
              + "\"name,4\" <*****@*****.**>,"
              + "\"big \"G\"\" <*****@*****.**>,"
              + "\u65E5\u672C\u8A9E <*****@*****.**>,"
              + "\u65E5\u672C\u8A9E <*****@*****.**>,"
              + "\uD834\uDF01\uD834\uDF46 <*****@*****.**>,"
              + "\uD834\uDF01\uD834\uDF46 <*****@*****.**>,"
              + "*****@*****.**",
          line);
    }

    // With custom separator
    {
      String line = Address.toString(address, "$");
      assertEquals("toString multi-1", "*****@*****.**", line);
    }

    {
      String line = Address.toString(addresses, "$");
      assertEquals(
          "toString multi-n",
          "[email protected]$"
              + "[email protected]$"
              + "simple name <*****@*****.**>$"
              + "\"name,4\" <*****@*****.**>$"
              + "\"big \"G\"\" <*****@*****.**>$"
              + "\u65E5\u672C\u8A9E <*****@*****.**>$"
              + "\u65E5\u672C\u8A9E <*****@*****.**>$"
              + "\uD834\uDF01\uD834\uDF46 <*****@*****.**>$"
              + "\uD834\uDF01\uD834\uDF46 <*****@*****.**>$"
              + "*****@*****.**",
          line);
    }
  }
Пример #3
0
 @Override
 public BitcoinSigner findSignerByPublicKey(PublicKey publicKey) {
   Address address = publicKey.toAddress(_network);
   InMemoryPrivateKey privateKey;
   try {
     privateKey = getPrivateKeyForAddress(address, _cipher);
   } catch (InvalidKeyCipher e) {
     throw new RuntimeException(
         "Unable to decrypt private key for address " + address.toString());
   }
   if (privateKey != null) {
     return privateKey;
   }
   throw new RuntimeException("Unable to find private key for address " + address.toString());
 }
  /**
   * Calculate the balance for a coinbase, to-address, or p2sh address.
   *
   * @param address The address to calculate the balance of
   * @return The balance of the address supplied. If the address has not been seen, or there are no
   *     outputs open for this address, the return value is 0
   * @throws BlockStoreException
   */
  public BigInteger calculateBalanceForAddress(Address address) throws BlockStoreException {
    maybeConnect();
    PreparedStatement s = null;

    try {
      s =
          conn.get()
              .prepareStatement(
                  "select sum(('x'||lpad(substr(value::text, 3, 50),16,'0'))::bit(64)::bigint) "
                      + "from openoutputs where toaddress = ?");
      s.setString(1, address.toString());
      ResultSet rs = s.executeQuery();
      if (rs.next()) {
        return BigInteger.valueOf(rs.getLong(1));
      } else {
        throw new BlockStoreException("Failed to execute balance lookup");
      }

    } catch (SQLException ex) {
      throw new BlockStoreException(ex);
    } finally {
      if (s != null)
        try {
          s.close();
        } catch (SQLException e) {
          throw new BlockStoreException("Could not close statement");
        }
    }
  }
Пример #5
0
 @Test
 public void toStringTest() {
   InMemoryPrivateKey priv = new InMemoryPrivateKey(RANDOM_SOURCE);
   PublicKey pub = priv.getPublicKey();
   Address addr = Address.fromStandardPublicKey(pub, NetworkParameters.productionNetwork);
   System.out.println(addr.toString());
 }
Пример #6
0
 /** Utility method which returns a string suitable for msg header display. */
 private String getDisplayAddress(Address a) {
   String pers = null;
   String addr = null;
   if (a instanceof InternetAddress && ((pers = ((InternetAddress) a).getPersonal()) != null)) {
     addr = pers + "  " + "&lt;" + ((InternetAddress) a).getAddress() + "&gt;";
   } else addr = a.toString();
   return addr;
 }
Пример #7
0
 @Override
 public PublicKey findPublicKeyByAddress(Address address) {
   PublicKey publicKey = getPublicKeyForAddress(address);
   if (publicKey != null) {
     return publicKey;
   }
   throw new RuntimeException("Unable to find public key for address " + address.toString());
 }
Пример #8
0
 @Test
 public void testScriptSig() throws Exception {
   byte[] sigProgBytes = Hex.decode(sigProg);
   Script script = new Script(sigProgBytes);
   // Test we can extract the from address.
   byte[] hash160 = Utils.sha256hash160(script.getPubKey());
   Address a = new Address(params, hash160);
   assertEquals("mkFQohBpy2HDXrCwyMrYL5RtfrmeiuuPY2", a.toString());
 }
  @Test
  public void testGetOpenTransactionOutputs() throws Exception {
    final int UNDOABLE_BLOCKS_STORED = 10;
    store = createStore(params, UNDOABLE_BLOCKS_STORED);
    chain = new FullPrunedBlockChain(params, store);

    // Check that we aren't accidentally leaving any references
    // to the full StoredUndoableBlock's lying around (ie memory leaks)
    ECKey outKey = new ECKey();
    int height = 1;

    // Build some blocks on genesis block to create a spendable output
    Block rollingBlock =
        params
            .getGenesisBlock()
            .createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height++);
    chain.add(rollingBlock);
    Transaction transaction = rollingBlock.getTransactions().get(0);
    TransactionOutPoint spendableOutput = new TransactionOutPoint(params, 0, transaction.getHash());
    byte[] spendableOutputScriptPubKey = transaction.getOutputs().get(0).getScriptBytes();
    for (int i = 1; i < params.getSpendableCoinbaseDepth(); i++) {
      rollingBlock =
          rollingBlock.createNextBlockWithCoinbase(
              Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height++);
      chain.add(rollingBlock);
    }
    rollingBlock = rollingBlock.createNextBlock(null);

    // Create bitcoin spend of 1 BTC.
    ECKey toKey = new ECKey();
    Coin amount = Coin.valueOf(100000000);
    Address address = new Address(params, toKey.getPubKeyHash());
    Coin totalAmount = Coin.ZERO;

    Transaction t = new Transaction(params);
    t.addOutput(new TransactionOutput(params, t, amount, toKey));
    t.addSignedInput(spendableOutput, new Script(spendableOutputScriptPubKey), outKey);
    rollingBlock.addTransaction(t);
    rollingBlock.solve();
    chain.add(rollingBlock);
    totalAmount = totalAmount.add(amount);

    List<UTXO> outputs = store.getOpenTransactionOutputs(Lists.newArrayList(address));
    assertNotNull(outputs);
    assertEquals("Wrong Number of Outputs", 1, outputs.size());
    UTXO output = outputs.get(0);
    assertEquals("The address is not equal", address.toString(), output.getAddress());
    assertEquals("The amount is not equal", totalAmount, output.getValue());

    outputs = null;
    output = null;
    try {
      store.close();
    } catch (Exception e) {
    }
  }
Пример #10
0
 private String addressToString(Address a) {
   if (a == null) {
     if (is64Bit) {
       return "0x0000000000000000";
     } else {
       return "0x00000000";
     }
   }
   return a.toString();
 }
Пример #11
0
  /** Tests that fromHeaderToString() returns the same result as toString(fromHeader()). */
  public void testFromHeaderToString() {
    assertNull(Address.fromHeaderToString(null));
    assertNull(Address.fromHeaderToString(""));

    for (Address[] list : TO_HEADER_CASES) {
      String packed = Address.toHeader(list);
      String s1 = Address.fromHeaderToString(packed);
      String s2 = Address.toString(Address.fromHeader(packed));
      assertEquals(s2, s2, s1);
    }
  }
Пример #12
0
 @Test
 public void testScriptPubKey() throws Exception {
   // Check we can extract the to address
   byte[] pubkeyBytes = Hex.decode(pubkeyProg);
   Script pubkey = new Script(pubkeyBytes);
   assertEquals(
       "DUP HASH160 [33e81a941e64cda12c6a299ed322ddbdd03f8d0e] EQUALVERIFY CHECKSIG",
       pubkey.toString());
   Address toAddr = new Address(params, pubkey.getPubKeyHash());
   assertEquals("mkFQohBpy2HDXrCwyMrYL5RtfrmeiuuPY2", toAddr.toString());
 }
Пример #13
0
 @Override
 public String toString() {
   return "RealEstate{"
       + "name='"
       + name
       + '\''
       + ", building="
       + building.toString()
       + ", address="
       + address.toString()
       + '}';
 }
Пример #14
0
 public void connect() {
   try {
     channel.connect("TOTAL_TOKEN_DEMO_GROUP");
   } catch (ChannelException e) {
     e.printStackTrace();
   }
   receiverThread = new ReceiverThread();
   receiverThread.start();
   Address a = channel.getAddress();
   if (a != null) setTitle(a.toString());
   else setTitle("Not connected");
   control.connected();
 }
    @Test
    public void nemesisAddressesAreValid() {
      // Arrange:
      final Block block = this.loadNemesisBlock();

      // Act:
      final Set<Address> allAddresses =
          block
              .getTransactions()
              .stream()
              .flatMap(t -> t.getAccounts().stream().map(Account::getAddress))
              .collect(Collectors.toSet());

      // Assert:
      for (final Address address : allAddresses) {
        Assert.assertThat(address.toString(), address.isValid(), IsEqual.equalTo(true));
      }
    }
Пример #16
0
 @Override
 public void formatKeyWithAddress(
     boolean includePrivateKeys, StringBuilder builder, NetworkParameters params) {
   final Address address = toAddress(params);
   builder.append("  addr:");
   builder.append(address.toString());
   builder.append("  hash160:");
   builder.append(Utils.HEX.encode(getPubKeyHash()));
   builder.append("  (");
   builder.append(getPathAsString());
   builder.append(")");
   builder.append("\n");
   if (includePrivateKeys) {
     builder.append("  ");
     builder.append(toStringWithPrivate(params));
     builder.append("\n");
   }
 }
Пример #17
0
 @ManagedAttribute
 public String getLocalAddress() {
   return local_addr != null ? local_addr.toString() : "null";
 }
  public static List<String> getText(BytesWritable value, Boolean tokenizep)
      throws InterruptedException {
    Session s = Session.getDefaultInstance(new Properties());
    InputStream is = new ByteArrayInputStream(value.getBytes());
    List<String> out = new ArrayList<String>();
    try {
      MimeMessage message = new MimeMessage(s, is);
      message.getAllHeaderLines();

      Analyzer standard_analyzer = new StandardAnalyzer(Version.LUCENE_43);
      Analyzer email_analyzer = new UAX29URLEmailAnalyzer(Version.LUCENE_43);

      Address[] fromAddrs = message.getFrom();
      String fromAddrstr = "";
      if (fromAddrs != null) {
        for (Address addr : fromAddrs) {
          fromAddrstr += (addr.toString() + " ");
        }
      }

      Address[] toAddrs = message.getAllRecipients();
      String toAddrstr = "";
      if (toAddrs != null) {
        for (Address addr : toAddrs) {
          toAddrstr += (addr.toString() + " ");
        }
      }

      String subject = message.getSubject();

      String body = "";
      try {
        Object content = message.getContent();
        // System.err.println(content.getContentType());
        if (content instanceof String) {
          body = (String) content;
        } else if (content instanceof Multipart) {
          Multipart mp = (Multipart) content;
          for (int i = 0; i < mp.getCount(); i++) {
            BodyPart bp = mp.getBodyPart(i);
            // System.err.println(bp.getContentType());
            Object c = bp.getContent();
            if (c instanceof String) {
              body = (String) c;
            }
          }
        }
        // people do really evil things with email, we're not sorting through it all now
      } catch (DecodingException e) {
        System.err.println("DecodingException");
      } catch (UnsupportedEncodingException e) {
        System.err.println("UnsuportedEncodingException");
      } catch (IOException e) {
        System.err.println("IOException");
      }

      if (tokenizep) {
        List<String> fromData = new ArrayList<String>();
        List<String> toData = new ArrayList<String>();
        List<String> subjectData = new ArrayList<String>();
        List<String> bodyData = new ArrayList<String>();

        if (fromAddrstr != null) {
          fromData = tokenizeString(email_analyzer, fromAddrstr);
        }
        if (toAddrstr != null) {
          toData = tokenizeString(email_analyzer, toAddrstr);
        }
        if (subject != null) {
          subjectData = tokenizeString(standard_analyzer, subject);
        }
        if (body != null) {
          bodyData = tokenizeString(standard_analyzer, body);
        }

        out.add("FROM ");
        out.addAll(fromData);

        out.add("TO ");
        out.addAll(toData);

        out.add("SUBJECT ");
        out.addAll(subjectData);

        out.add("BODY ");
        out.addAll(bodyData);
      } else {
        // if not tokenizep, return list with from and subject fields only
        out.add(fromAddrstr);
        out.add(subject);
      }

    } catch (MessagingException e) {
      System.err.println("MessagineException");
    }

    return out;
  }
Пример #19
0
 @ManagedAttribute(description = "The address of the current coordinator")
 public String getCurrentCoord() {
   return current_coord != null ? current_coord.toString() : "n/a";
 }
  /**
   * parses received phones list and creates/resolves groups and contacts
   *
   * @param objReceived the obj with data.
   */
  private void phonesRecieved(JSONObject objReceived) {
    try {
      if (!objReceived.get("function").equals("sendlist") || !objReceived.containsKey("payload"))
        return;

      JSONObject payload = (JSONObject) objReceived.get("payload");
      /*
       * FIXME The following contains two very inefficient Map-iterating
       * loops.
       */
      Iterator iter = payload.keySet().iterator();
      List<JSONObject> phoneList = new ArrayList<JSONObject>();
      while (iter.hasNext()) {
        JSONObject obj = (JSONObject) payload.get(iter.next());
        Iterator phonesIter = obj.keySet().iterator();
        while (phonesIter.hasNext()) phoneList.add((JSONObject) obj.get(phonesIter.next()));
      }

      for (JSONObject phone : phoneList) {
        try {
          // don't handle non sip phones
          if (!((String) phone.get("tech")).equalsIgnoreCase("sip")) continue;

          String groupName = (String) phone.get("context");

          ContactGroupSipImpl parentGroup = findGroupByName(groupName);

          if (parentGroup == null) {
            parentGroup = new ContactGroupSipImpl(groupName, sipProvider);
            parentGroup.setPersistent(true);
            getRootGroup().addSubgroup(parentGroup);

            fireGroupEvent(parentGroup, ServerStoredGroupEvent.GROUP_CREATED_EVENT);
          }

          String number = (String) phone.get("number");

          Address address = sipProvider.parseAddressString(number);

          // if the contact is already in the contact list
          ContactSipImpl contact = parentOperationSet.resolveContactID(address.toString());

          if (contact == null) {
            contact = new ContactSipImpl(address, sipProvider);
            contact.setDisplayName(phone.get("firstname") + " " + phone.get("lastname"));
            contact.setResolved(true);
            parentGroup.addContact(contact);

            fireContactAdded(parentGroup, contact);
          } else {
            contact.setDisplayName(phone.get("firstname") + " " + phone.get("lastname"));
            contact.setResolved(true);

            fireContactResolved(parentGroup, contact);
          }
        } catch (Throwable t) {
          logger.error("Error parsing " + phone);
        }
      }
    } catch (Throwable t) {
      logger.error("Error init list from server", t);
    }
  }
  public void addUnspentTransactionOutput(StoredTransactionOutput out) throws BlockStoreException {
    maybeConnect();
    PreparedStatement s = null;

    // Calculate the toAddress (if any)
    String dbAddress = "";
    int type = 0;
    Script outputScript = null;
    try {
      outputScript = new Script(out.getScriptBytes());
    } catch (ScriptException e) {
      // Unparseable, but this isn't an error - it's an output not containing an address
      log.info("Could not parse script for output: " + out.getHash().toString());
    }
    if (outputScript != null
        && (outputScript.isSentToAddress()
            || outputScript.isSentToRawPubKey()
            || outputScript.isPayToScriptHash())) {
      if (outputScript.isSentToAddress()) {
        Address targetAddr = new Address(params, outputScript.getPubKeyHash());
        dbAddress = targetAddr.toString();
        type = 1;
      } else if (outputScript.isSentToRawPubKey()) {
        /*
         *   Note we use the deprecated getFromAddress here.  Coinbase outputs seem to have the target address
         *   in the pubkey of the script - perhaps we can rename this function?
         */

        dbAddress = outputScript.getFromAddress(params).toString();
        type = 2;
      } else if (outputScript.isPayToScriptHash()) {
        dbAddress = Address.fromP2SHHash(params, outputScript.getPubKeyHash()).toString();
        type = 3;
      }
    }

    try {
      s =
          conn.get()
              .prepareStatement(
                  "INSERT INTO openOutputs (hash, index, height, value, scriptBytes, toAddress, addressTargetable) "
                      + "VALUES (?, ?, ?, ?, ?, ?, ?)");
      s.setBytes(1, out.getHash().getBytes());
      // index is actually an unsigned int
      s.setInt(2, (int) out.getIndex());
      s.setInt(3, out.getHeight());
      s.setBytes(4, out.getValue().toByteArray());
      s.setBytes(5, out.getScriptBytes());
      s.setString(6, dbAddress);
      s.setInt(7, type);
      s.executeUpdate();
      s.close();
    } catch (SQLException e) {
      if (!(e.getSQLState().equals(POSTGRES_DUPLICATE_KEY_ERROR_CODE)))
        throw new BlockStoreException(e);
    } finally {
      if (s != null)
        try {
          s.close();
        } catch (SQLException e) {
          throw new BlockStoreException(e);
        }
    }
  }
Пример #22
0
 public void setReplyToAddress(Address replyTo) {
   this.replyTo = (replyTo != null) ? replyTo.toString() : null;
 }
Пример #23
0
 @ManagedAttribute(name = "address")
 public String getAddressAsString() {
   return local_addr != null ? local_addr.toString() : "n/a";
 }
Пример #24
0
 protected static String addressAsString(Address address) {
   if (address == null) return "";
   if (address instanceof UUID) return ((UUID) address).toStringLong();
   return address.toString();
 }