src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ImageRecord implements Comparable<ImageRecord> { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ImageRecord other = (ImageRecord) obj; if (pHash != other.pHash) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; return true; } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }
@Test public void testEquals() throws Exception { EqualsVerifier.forClass(ImageRecord.class).suppress(Warning.NONFINAL_FIELDS).verify(); }
ImageRecord implements Comparable<ImageRecord> { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("ImageRecord"); sb.append("{"); sb.append("path:"); sb.append(path); sb.append(","); sb.append("hash:"); sb.append(pHash); sb.append("}"); return sb.toString(); } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }
@Test public void testToString() throws Exception { assertThat(imageRecord.toString(), is(EXPECTED_TO_STRING)); }
BadFileRecord { public String getPath() { return path; } @Deprecated BadFileRecord(); BadFileRecord(Path path); String getPath(); }
@Test public void testGetPath() throws Exception { assertThat(badFileRecord.getPath(), is("bad")); }
RepositoryException extends Exception { public final String getMessage() { return message; } RepositoryException(String message, Throwable cause); RepositoryException(String message); final String getMessage(); final Throwable getCause(); }
@Test public void testRepositoryExceptionStringThrowableMessage() throws Exception { cut = new RepositoryException(TEST_MESSAGE, testException); assertThat(cut.getMessage(), is(TEST_MESSAGE)); } @Test public void testRepositoryExceptionStringMessage() throws Exception { cut = new RepositoryException(TEST_MESSAGE); assertThat(cut.getMessage(), is(TEST_MESSAGE)); }
RepositoryException extends Exception { public final Throwable getCause() { return cause; } RepositoryException(String message, Throwable cause); RepositoryException(String message); final String getMessage(); final Throwable getCause(); }
@Test public void testRepositoryExceptionStringThrowableCause() throws Exception { cut = new RepositoryException(TEST_MESSAGE, testException); assertThat(cut.getCause(), is(testException)); } @Test public void testRepositoryExceptionStringCause() throws Exception { cut = new RepositoryException(TEST_MESSAGE); assertThat(cut.getCause(), nullValue()); }
OrmliteRepositoryFactory implements RepositoryFactory { @Override public FilterRepository buildFilterRepository() throws RepositoryException { return new OrmliteFilterRepository(filterRecordDao, thumbnailDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }
@Test public void testBuildFilterRepository() throws Exception { FilterRepository fr = cut.buildFilterRepository(); fr.store(new FilterRecord(0, new Tag(TEST_STRING))); }
OrmliteRepositoryFactory implements RepositoryFactory { @Override public ImageRepository buildImageRepository() throws RepositoryException { return new OrmliteImageRepository(imageRecordDao, ignoreDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }
@Test public void testBuildImageRepository() throws Exception { ImageRepository ir = cut.buildImageRepository(); ir.store(new ImageRecord(TEST_STRING, 0)); }
OrmliteRepositoryFactory implements RepositoryFactory { @Override public TagRepository buildTagRepository() throws RepositoryException { return new OrmliteTagRepository(tagDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }
@Test public void testBuildTagRepository() throws Exception { TagRepository tr = cut.buildTagRepository(); tr.store(new Tag(TEST_STRING)); }
OrmliteRepositoryFactory implements RepositoryFactory { @Override public PendingHashImageRepository buildPendingHashImageRepository() throws RepositoryException { return new OrmlitePendingHashImage(pendingDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }
@Test public void testBuildPendingImageRepository() throws Exception { PendingHashImageRepository phir = cut.buildPendingHashImageRepository(); phir.store(new PendingHashImage(TEST_STRING, 0, 0)); }
OrmliteRepositoryFactory implements RepositoryFactory { @Override public IgnoreRepository buildIgnoreRepository() throws RepositoryException { return new OrmliteIgnoreRepository(ignoreDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }
@Test public void testBuildIgnoreRepository() throws Exception { IgnoreRepository ir = cut.buildIgnoreRepository(); ir.store(new IgnoreRecord(new ImageRecord(TEST_STRING, 0))); }
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public synchronized boolean store(PendingHashImage image) throws RepositoryException { try { if (pendingDao.queryForMatchingArgs(image).isEmpty()) { pendingDao.create(image); return true; } else { return false; } } catch (SQLException e) { throw new RepositoryException("Failed to store entry", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }
@Test public void testStoreQueryDatabase() throws Exception { cut.store(newEntry); assertThat(dao.queryForMatchingArgs(newEntry), hasSize(1)); } @Test public void testStoreReturnValue() throws Exception { assertThat(cut.store(newEntry), is(true)); } @Test public void testStoreDuplicate() throws Exception { assertThat(cut.store(existingEntry), is(false)); }
ExtendedAttribute implements ExtendedAttributeQuery { public static boolean supportsExtendedAttributes(Path path) { try { return Files.getFileStore(path).supportsFileAttributeView(UserDefinedFileAttributeView.class); } catch (IOException e) { LOGGER.debug("Failed to check extended attributes via FileStore ({}) for {}, falling back to write test...", e.toString(), path); return checkSupportWithWrite(path); } } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); static final String SIMILARIMAGE_NAMESPACE; }
@Test public void testSupportsExtendedAttributes() throws Exception { assertThat(ExtendedAttribute.supportsExtendedAttributes(tempFile), is(true)); } @Test public void testSupportsExtendedAttributesNoFile() throws Exception { assertThat(ExtendedAttribute.supportsExtendedAttributes(Jimfs.newFileSystem().getPath("noEAsupport")), is(false)); }
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public boolean exists(PendingHashImage image) throws RepositoryException { try { if (pendingDao.refresh(image) == 0) { return !pendingDao.queryForMatching(image).isEmpty(); } else { return true; } } catch (SQLException e) { throw new RepositoryException("Failed to lookup entry", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }
@Test public void testExistsById() throws Exception { assertThat(cut.exists(existingEntry), is(true)); } @Test public void testExistsByPath() throws Exception { assertThat(cut.exists(new PendingHashImage(EXISTING_PATH, UUID_EXISTING)), is(true)); } @Test public void testExistsNotFound() throws Exception { assertThat(cut.exists(newEntry), is(false)); }
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public List<PendingHashImage> getAll() throws RepositoryException { try { return pendingDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query for all entries", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }
@Test public void testGetAll() throws Exception { dao.create(newEntry); assertThat(cut.getAll(), containsInAnyOrder(newEntry, existingEntry)); }
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public PendingHashImage getByUUID(long most, long least) throws RepositoryException { try { synchronized (uuidQuery) { mostParam.setValue(most); leastParam.setValue(least); return pendingDao.queryForFirst(uuidQuery); } } catch (SQLException e) { throw new RepositoryException("Failed to get entry by id", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }
@Test public void testGetByUuidNonExisting() throws Exception { assertThat(cut.getByUUID(UUID_NEW.getMostSignificantBits(), UUID_NEW.getLeastSignificantBits()), is(nullValue())); } @Test public void testGetByUuidExisting() throws Exception { assertThat(cut.getByUUID(UUID_EXISTING.getMostSignificantBits(), UUID_EXISTING.getLeastSignificantBits()), is(existingEntry)); }
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public void remove(PendingHashImage image) throws RepositoryException { try { pendingDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove entry", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }
@Test public void testRemove() throws Exception { assertThat(dao.queryForSameId(existingEntry), is(notNullValue())); cut.remove(existingEntry); assertThat(dao.queryForSameId(existingEntry), is(nullValue())); }
OrmliteImageRepository implements ImageRepository { @Override public void store(ImageRecord image) throws RepositoryException { try { imageDao.createOrUpdate(image); } catch (SQLException e) { throw new RepositoryException("Failed to store image", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); }
@Test public void testStore() throws Exception { cut.store(imageNew); assertThat(imageDao.queryForId(pathNew), is(imageNew)); }
SeedPeers implements PeerDiscovery { public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); InetSocketAddress getPeer(); InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit); void shutdown(); static int[] seedAddrs; }
@Test public void getPeer_one() throws Exception{ SeedPeers seedPeers = new SeedPeers(NetworkParameters.prodNet()); assertThat(seedPeers.getPeer(), notNullValue()); } @Test public void getPeer_all() throws Exception{ SeedPeers seedPeers = new SeedPeers(NetworkParameters.prodNet()); for(int i = 0; i < SeedPeers.seedAddrs.length; ++i){ assertThat("Failed on index: "+i, seedPeers.getPeer(), notNullValue()); } assertThat(seedPeers.getPeer(), equalTo(null)); }
LitecoinURI { public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); static final String FIELD_MESSAGE; static final String FIELD_LABEL; static final String FIELD_AMOUNT; static final String FIELD_ADDRESS; static final String LITECOIN_SCHEME; }
@Test public void testBad_Amount() throws LitecoinURIParseException { try { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?amount="); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("amount")); } try { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?amount=12X4"); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("amount")); } } @Test public void testBad_Label() throws LitecoinURIParseException { try { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?label="); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("label")); } } @Test public void testBad_Message() throws LitecoinURIParseException { try { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?message="); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("message")); } } @Test public void testBad_Duplicated() throws LitecoinURIParseException { try { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?address=aardvark"); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("address")); } } @Test public void testBad_TooManyEquals() throws LitecoinURIParseException { try { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?label=aardvark=zebra"); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("cannot parse name value pair")); } } @Test public void testBad_TooManyQuestionMarks() throws LitecoinURIParseException { try { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?label=aardvark?message=zebra"); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("Too many question marks")); } } @Test public void testBad_BadSyntax() { try { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + "|" + PRODNET_GOOD_ADDRESS); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("Bad URI syntax")); } try { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "\\"); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("Bad URI syntax")); } try { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":"); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("Bad URI syntax")); } } @Test public void testBad_IncorrectAddressType() { try { testObject = new LitecoinURI(NetworkParameters.testNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("Bad address")); } } @Test public void testGood_Message() throws LitecoinURIParseException { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?message=Hello%20World"); assertEquals("Hello World", testObject.getMessage()); }
WalletProtobufSerializer { public Protos.Wallet walletToProto(Wallet wallet) { Protos.Wallet.Builder walletBuilder = Protos.Wallet.newBuilder(); walletBuilder.setNetworkIdentifier(wallet.getNetworkParameters().getId()); if (wallet.getDescription() != null) { walletBuilder.setDescription(wallet.getDescription()); } for (WalletTransaction wtx : wallet.getWalletTransactions()) { Protos.Transaction txProto = makeTxProto(wtx); walletBuilder.addTransaction(txProto); } for (ECKey key : wallet.getKeys()) { Protos.Key.Builder keyBuilder = Protos.Key.newBuilder().setCreationTimestamp(key.getCreationTimeSeconds() * 1000) .setType(Protos.Key.Type.ORIGINAL); if (key.getPrivKeyBytes() != null) keyBuilder.setPrivateKey(ByteString.copyFrom(key.getPrivKeyBytes())); EncryptedPrivateKey encryptedPrivateKey = key.getEncryptedPrivateKey(); if (encryptedPrivateKey != null) { Protos.EncryptedPrivateKey.Builder encryptedKeyBuilder = Protos.EncryptedPrivateKey.newBuilder() .setEncryptedPrivateKey(ByteString.copyFrom(encryptedPrivateKey.getEncryptedBytes())) .setInitialisationVector(ByteString.copyFrom(encryptedPrivateKey.getInitialisationVector())); if (key.getKeyCrypter() == null) { throw new IllegalStateException("The encrypted key " + key.toString() + " has no KeyCrypter."); } else { if (key.getKeyCrypter().getUnderstoodEncryptionType() == Protos.Wallet.EncryptionType.ENCRYPTED_SCRYPT_AES) { keyBuilder.setType(Protos.Key.Type.ENCRYPTED_SCRYPT_AES); } else { throw new IllegalArgumentException("The key " + key.toString() + " is encrypted with a KeyCrypter of type " + key.getKeyCrypter().getUnderstoodEncryptionType() + ". This WalletProtobufSerialiser does not understand that type of encryption."); } } keyBuilder.setEncryptedPrivateKey(encryptedKeyBuilder); } keyBuilder.setPublicKey(ByteString.copyFrom(key.getPubKey())); walletBuilder.addKey(keyBuilder); } Sha256Hash lastSeenBlockHash = wallet.getLastBlockSeenHash(); if (lastSeenBlockHash != null) { walletBuilder.setLastSeenBlockHash(hashToByteString(lastSeenBlockHash)); walletBuilder.setLastSeenBlockHeight(wallet.getLastBlockSeenHeight()); } KeyCrypter keyCrypter = wallet.getKeyCrypter(); if (keyCrypter == null) { walletBuilder.setEncryptionType(EncryptionType.UNENCRYPTED); } else { walletBuilder.setEncryptionType(keyCrypter.getUnderstoodEncryptionType()); if (keyCrypter instanceof KeyCrypterScrypt) { KeyCrypterScrypt keyCrypterScrypt = (KeyCrypterScrypt) keyCrypter; walletBuilder.setEncryptionParameters(keyCrypterScrypt.getScryptParameters()); } else { throw new RuntimeException("The wallet has encryption of type '" + keyCrypter.getUnderstoodEncryptionType() + "' but this WalletProtobufSerializer does not know how to persist this."); } } walletBuilder.setVersion(wallet.getVersion()); Collection<Protos.Extension> extensions = helper.getExtensionsToWrite(wallet); for(Protos.Extension ext : extensions) { walletBuilder.addExtension(ext); } return walletBuilder.build(); } WalletProtobufSerializer(); void setWalletExtensionSerializer(WalletExtensionSerializer h); void writeWallet(Wallet wallet, OutputStream output); String walletToText(Wallet wallet); Protos.Wallet walletToProto(Wallet wallet); static ByteString hashToByteString(Sha256Hash hash); static Sha256Hash byteStringToHash(ByteString bs); Wallet readWallet(InputStream input); static Protos.Wallet parseToProto(InputStream input); }
@Test public void oneTx() throws Exception { BigInteger v1 = Utils.toNanoCoins(1, 0); Transaction t1 = createFakeTx(params, v1, myAddress); t1.getConfidence().markBroadcastBy(new PeerAddress(InetAddress.getByName("1.2.3.4"))); t1.getConfidence().markBroadcastBy(new PeerAddress(InetAddress.getByName("5.6.7.8"))); t1.getConfidence().setSource(TransactionConfidence.Source.NETWORK); myWallet.receivePending(t1, new ArrayList<Transaction>()); Wallet wallet1 = roundTrip(myWallet); assertEquals(1, wallet1.getTransactions(true, true).size()); assertEquals(v1, wallet1.getBalance(Wallet.BalanceType.ESTIMATED)); Transaction t1copy = wallet1.getTransaction(t1.getHash()); assertArrayEquals(t1.litecoinSerialize(), t1copy.litecoinSerialize()); assertEquals(2, t1copy.getConfidence().numBroadcastPeers()); assertEquals(TransactionConfidence.Source.NETWORK, t1copy.getConfidence().getSource()); Protos.Wallet walletProto = new WalletProtobufSerializer().walletToProto(myWallet); assertEquals(Protos.Key.Type.ORIGINAL, walletProto.getKey(0).getType()); assertEquals(0, walletProto.getExtensionCount()); assertEquals(1, walletProto.getTransactionCount()); assertEquals(1, walletProto.getKeyCount()); Protos.Transaction t1p = walletProto.getTransaction(0); assertEquals(0, t1p.getBlockHashCount()); assertArrayEquals(t1.getHash().getBytes(), t1p.getHash().toByteArray()); assertEquals(Protos.Transaction.Pool.PENDING, t1p.getPool()); assertFalse(t1p.hasLockTime()); assertFalse(t1p.getTransactionInput(0).hasSequence()); assertArrayEquals(t1.getInputs().get(0).getOutpoint().getHash().getBytes(), t1p.getTransactionInput(0).getTransactionOutPointHash().toByteArray()); assertEquals(0, t1p.getTransactionInput(0).getTransactionOutPointIndex()); assertEquals(t1p.getTransactionOutput(0).getValue(), v1.longValue()); } @Test public void testLastBlockSeenHash() throws Exception { Wallet wallet = new Wallet(params); Protos.Wallet walletProto = new WalletProtobufSerializer().walletToProto(wallet); ByteString lastSeenBlockHash = walletProto.getLastSeenBlockHash(); assertTrue(lastSeenBlockHash.isEmpty()); Block block = new Block(params, BlockTest.blockBytes); Sha256Hash blockHash = block.getHash(); wallet.setLastBlockSeenHash(blockHash); wallet.setLastBlockSeenHeight(1); Wallet wallet1 = roundTrip(wallet); assertEquals(blockHash, wallet1.getLastBlockSeenHash()); assertEquals(1, wallet1.getLastBlockSeenHeight()); Block genesisBlock = NetworkParameters.prodNet().genesisBlock; wallet.setLastBlockSeenHash(genesisBlock.getHash()); Wallet wallet2 = roundTrip(wallet); assertEquals(genesisBlock.getHash(), wallet2.getLastBlockSeenHash()); }
Wallet implements Serializable, BlockChainListener { public Transaction createSend(Address address, BigInteger nanocoins) { SendRequest req = SendRequest.to(address, nanocoins); if (completeTx(req)) { return req.tx; } else { return null; } } Wallet(NetworkParameters params); Wallet(NetworkParameters params, KeyCrypter keyCrypter); NetworkParameters getNetworkParameters(); Iterable<ECKey> getKeys(); int getKeychainSize(); void saveToFile(File f); void setAcceptTimeLockedTransactions(boolean acceptTimeLockedTransactions); boolean doesAcceptTimeLockedTransactions(); void autosaveToFile(File f, long delayTime, TimeUnit timeUnit, AutosaveEventListener eventListener); void saveToFileStream(OutputStream f); NetworkParameters getParams(); static Wallet loadFromFile(File f); boolean isConsistent(); static Wallet loadFromFileStream(InputStream stream); void notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, BlockChain.NewBlockType blockType); void receivePending(Transaction tx, List<Transaction> dependencies); boolean isTransactionRelevant(Transaction tx); void receiveFromBlock(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType); void notifyNewBestBlock(StoredBlock block); void addEventListener(WalletEventListener listener); boolean removeEventListener(WalletEventListener listener); void commitTx(Transaction tx); Set<Transaction> getTransactions(boolean includeDead, boolean includeInactive); Iterable<WalletTransaction> getWalletTransactions(); void addWalletTransaction(WalletTransaction wtx); List<Transaction> getTransactionsByTime(); List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead); Transaction getTransaction(Sha256Hash hash); void clearTransactions(int fromHeight); Transaction createSend(Address address, BigInteger nanocoins); Transaction createSend(SendRequest req); Transaction sendCoinsOffline(SendRequest request); SendResult sendCoins(PeerGroup peerGroup, Address to, BigInteger value); SendResult sendCoins(PeerGroup peerGroup, SendRequest request); Transaction sendCoins(Peer peer, SendRequest request); boolean completeTx(SendRequest req); boolean addKey(final ECKey key); int addKeys(final List<ECKey> keys); ECKey findKeyFromPubHash(byte[] pubkeyHash); boolean hasKey(ECKey key); boolean isPubKeyHashMine(byte[] pubkeyHash); ECKey findKeyFromPubKey(byte[] pubkey); boolean isPubKeyMine(byte[] pubkey); BigInteger getBalance(); BigInteger getBalance(BalanceType balanceType); BigInteger getBalance(CoinSelector selector); @Override String toString(); String toString(boolean includePrivateKeys, AbstractBlockChain chain); void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks); Collection<Transaction> getPendingTransactions(); long getEarliestKeyCreationTime(); Sha256Hash getLastBlockSeenHash(); void setLastBlockSeenHash(Sha256Hash lastBlockSeenHash); void setLastBlockSeenHeight(int lastBlockSeenHeight); int getLastBlockSeenHeight(); KeyParameter encrypt(CharSequence password); void encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); void decrypt(KeyParameter aesKey); ECKey addNewEncryptedKey(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey addNewEncryptedKey(CharSequence password); boolean checkPassword(CharSequence password); boolean checkAESKey(KeyParameter aesKey); KeyCrypter getKeyCrypter(); EncryptionType getEncryptionType(); boolean isEncrypted(); int getVersion(); void setVersion(int version); void setDescription(String description); String getDescription(); int getBloomFilterElementCount(); BloomFilter getBloomFilter(double falsePositiveRate); BloomFilter getBloomFilter(int size, double falsePositiveRate, long nTweak); CoinSelector getCoinSelector(); void setCoinSelector(CoinSelector coinSelector); void trim(final int minTransactionsToKeep); public ArrayList<ECKey> keychain; }
@Test public void balances() throws Exception { BigInteger nanos = Utils.toNanoCoins(1, 0); Transaction tx1 = sendMoneyToWallet(nanos, AbstractBlockChain.NewBlockType.BEST_CHAIN); assertEquals(nanos, tx1.getValueSentToMe(wallet, true)); Transaction send1 = wallet.createSend(new ECKey().toAddress(params), toNanoCoins(0, 10)); Transaction send2 = new Transaction(params, send1.litecoinSerialize()); assertEquals(nanos, send2.getValueSentFromMe(wallet)); assertEquals(BigInteger.ZERO.subtract(toNanoCoins(0, 10)), send2.getValue(wallet)); }
Wallet implements Serializable, BlockChainListener { public Sha256Hash getLastBlockSeenHash() { lock.lock(); try { return lastBlockSeenHash; } finally { lock.unlock(); } } Wallet(NetworkParameters params); Wallet(NetworkParameters params, KeyCrypter keyCrypter); NetworkParameters getNetworkParameters(); Iterable<ECKey> getKeys(); int getKeychainSize(); void saveToFile(File f); void setAcceptTimeLockedTransactions(boolean acceptTimeLockedTransactions); boolean doesAcceptTimeLockedTransactions(); void autosaveToFile(File f, long delayTime, TimeUnit timeUnit, AutosaveEventListener eventListener); void saveToFileStream(OutputStream f); NetworkParameters getParams(); static Wallet loadFromFile(File f); boolean isConsistent(); static Wallet loadFromFileStream(InputStream stream); void notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, BlockChain.NewBlockType blockType); void receivePending(Transaction tx, List<Transaction> dependencies); boolean isTransactionRelevant(Transaction tx); void receiveFromBlock(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType); void notifyNewBestBlock(StoredBlock block); void addEventListener(WalletEventListener listener); boolean removeEventListener(WalletEventListener listener); void commitTx(Transaction tx); Set<Transaction> getTransactions(boolean includeDead, boolean includeInactive); Iterable<WalletTransaction> getWalletTransactions(); void addWalletTransaction(WalletTransaction wtx); List<Transaction> getTransactionsByTime(); List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead); Transaction getTransaction(Sha256Hash hash); void clearTransactions(int fromHeight); Transaction createSend(Address address, BigInteger nanocoins); Transaction createSend(SendRequest req); Transaction sendCoinsOffline(SendRequest request); SendResult sendCoins(PeerGroup peerGroup, Address to, BigInteger value); SendResult sendCoins(PeerGroup peerGroup, SendRequest request); Transaction sendCoins(Peer peer, SendRequest request); boolean completeTx(SendRequest req); boolean addKey(final ECKey key); int addKeys(final List<ECKey> keys); ECKey findKeyFromPubHash(byte[] pubkeyHash); boolean hasKey(ECKey key); boolean isPubKeyHashMine(byte[] pubkeyHash); ECKey findKeyFromPubKey(byte[] pubkey); boolean isPubKeyMine(byte[] pubkey); BigInteger getBalance(); BigInteger getBalance(BalanceType balanceType); BigInteger getBalance(CoinSelector selector); @Override String toString(); String toString(boolean includePrivateKeys, AbstractBlockChain chain); void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks); Collection<Transaction> getPendingTransactions(); long getEarliestKeyCreationTime(); Sha256Hash getLastBlockSeenHash(); void setLastBlockSeenHash(Sha256Hash lastBlockSeenHash); void setLastBlockSeenHeight(int lastBlockSeenHeight); int getLastBlockSeenHeight(); KeyParameter encrypt(CharSequence password); void encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); void decrypt(KeyParameter aesKey); ECKey addNewEncryptedKey(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey addNewEncryptedKey(CharSequence password); boolean checkPassword(CharSequence password); boolean checkAESKey(KeyParameter aesKey); KeyCrypter getKeyCrypter(); EncryptionType getEncryptionType(); boolean isEncrypted(); int getVersion(); void setVersion(int version); void setDescription(String description); String getDescription(); int getBloomFilterElementCount(); BloomFilter getBloomFilter(double falsePositiveRate); BloomFilter getBloomFilter(int size, double falsePositiveRate, long nTweak); CoinSelector getCoinSelector(); void setCoinSelector(CoinSelector coinSelector); void trim(final int minTransactionsToKeep); public ArrayList<ECKey> keychain; }
@Test public void rememberLastBlockSeenHash() throws Exception { BigInteger v1 = toNanoCoins(5, 0); BigInteger v2 = toNanoCoins(0, 50); BigInteger v3 = toNanoCoins(0, 25); Transaction t1 = createFakeTx(params, v1, myAddress); Transaction t2 = createFakeTx(params, v2, myAddress); Transaction t3 = createFakeTx(params, v3, myAddress); Block genesis = blockStore.getChainHead().getHeader(); Block b10 = makeSolvedTestBlock(genesis, t1); Block b11 = makeSolvedTestBlock(genesis, t2); Block b2 = makeSolvedTestBlock(b10, t3); Block b3 = makeSolvedTestBlock(b2); chain.add(b10); assertEquals(b10.getHash(), wallet.getLastBlockSeenHash()); chain.add(b11); assertEquals(b10.getHash(), wallet.getLastBlockSeenHash()); chain.add(b2); assertEquals(b2.getHash(), wallet.getLastBlockSeenHash()); chain.add(b3); assertEquals(b3.getHash(), wallet.getLastBlockSeenHash()); }
Wallet implements Serializable, BlockChainListener { public boolean completeTx(SendRequest req) { lock.lock(); try { Preconditions.checkArgument(!req.completed, "Given SendRequest has already been completed."); BigInteger value = BigInteger.ZERO; for (TransactionOutput output : req.tx.getOutputs()) { value = value.add(output.getValue()); } value = value.add(req.fee); log.info("Completing send tx with {} outputs totalling {}", req.tx.getOutputs().size(), litecoinValueToFriendlyString(value)); LinkedList<TransactionOutput> candidates = calculateSpendCandidates(true); CoinSelection selection = coinSelector.select(value, candidates); if (selection.valueGathered.compareTo(value) < 0) { log.warn("Insufficient value in wallet for send, missing " + litecoinValueToFriendlyString(value.subtract(selection.valueGathered))); return false; } checkState(selection.gathered.size() > 0); req.tx.getConfidence().setConfidenceType(ConfidenceType.NOT_SEEN_IN_CHAIN); BigInteger change = selection.valueGathered.subtract(value); if (change.compareTo(BigInteger.ZERO) > 0) { Address changeAddress = req.changeAddress != null ? req.changeAddress : getChangeAddress(); log.info(" with {} coins change", litecoinValueToFriendlyString(change)); req.tx.addOutput(new TransactionOutput(params, req.tx, change, changeAddress)); } for (TransactionOutput output : selection.gathered) { req.tx.addInput(output); } try { req.tx.signInputs(Transaction.SigHash.ALL, this, req.aesKey); } catch (ScriptException e) { throw new RuntimeException(e); } int size = req.tx.litecoinSerialize().length; if (size > Transaction.MAX_STANDARD_TX_SIZE) { log.error("Transaction could not be created without exceeding max size: {} vs {}", size, Transaction.MAX_STANDARD_TX_SIZE); return false; } req.tx.getConfidence().setSource(TransactionConfidence.Source.SELF); req.completed = true; log.info(" completed {} with {} inputs", req.tx.getHashAsString(), req.tx.getInputs().size()); return true; } finally { lock.unlock(); } } Wallet(NetworkParameters params); Wallet(NetworkParameters params, KeyCrypter keyCrypter); NetworkParameters getNetworkParameters(); Iterable<ECKey> getKeys(); int getKeychainSize(); void saveToFile(File f); void setAcceptTimeLockedTransactions(boolean acceptTimeLockedTransactions); boolean doesAcceptTimeLockedTransactions(); void autosaveToFile(File f, long delayTime, TimeUnit timeUnit, AutosaveEventListener eventListener); void saveToFileStream(OutputStream f); NetworkParameters getParams(); static Wallet loadFromFile(File f); boolean isConsistent(); static Wallet loadFromFileStream(InputStream stream); void notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, BlockChain.NewBlockType blockType); void receivePending(Transaction tx, List<Transaction> dependencies); boolean isTransactionRelevant(Transaction tx); void receiveFromBlock(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType); void notifyNewBestBlock(StoredBlock block); void addEventListener(WalletEventListener listener); boolean removeEventListener(WalletEventListener listener); void commitTx(Transaction tx); Set<Transaction> getTransactions(boolean includeDead, boolean includeInactive); Iterable<WalletTransaction> getWalletTransactions(); void addWalletTransaction(WalletTransaction wtx); List<Transaction> getTransactionsByTime(); List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead); Transaction getTransaction(Sha256Hash hash); void clearTransactions(int fromHeight); Transaction createSend(Address address, BigInteger nanocoins); Transaction createSend(SendRequest req); Transaction sendCoinsOffline(SendRequest request); SendResult sendCoins(PeerGroup peerGroup, Address to, BigInteger value); SendResult sendCoins(PeerGroup peerGroup, SendRequest request); Transaction sendCoins(Peer peer, SendRequest request); boolean completeTx(SendRequest req); boolean addKey(final ECKey key); int addKeys(final List<ECKey> keys); ECKey findKeyFromPubHash(byte[] pubkeyHash); boolean hasKey(ECKey key); boolean isPubKeyHashMine(byte[] pubkeyHash); ECKey findKeyFromPubKey(byte[] pubkey); boolean isPubKeyMine(byte[] pubkey); BigInteger getBalance(); BigInteger getBalance(BalanceType balanceType); BigInteger getBalance(CoinSelector selector); @Override String toString(); String toString(boolean includePrivateKeys, AbstractBlockChain chain); void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks); Collection<Transaction> getPendingTransactions(); long getEarliestKeyCreationTime(); Sha256Hash getLastBlockSeenHash(); void setLastBlockSeenHash(Sha256Hash lastBlockSeenHash); void setLastBlockSeenHeight(int lastBlockSeenHeight); int getLastBlockSeenHeight(); KeyParameter encrypt(CharSequence password); void encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); void decrypt(KeyParameter aesKey); ECKey addNewEncryptedKey(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey addNewEncryptedKey(CharSequence password); boolean checkPassword(CharSequence password); boolean checkAESKey(KeyParameter aesKey); KeyCrypter getKeyCrypter(); EncryptionType getEncryptionType(); boolean isEncrypted(); int getVersion(); void setVersion(int version); void setDescription(String description); String getDescription(); int getBloomFilterElementCount(); BloomFilter getBloomFilter(double falsePositiveRate); BloomFilter getBloomFilter(int size, double falsePositiveRate, long nTweak); CoinSelector getCoinSelector(); void setCoinSelector(CoinSelector coinSelector); void trim(final int minTransactionsToKeep); public ArrayList<ECKey> keychain; }
@Test public void respectMaxStandardSize() throws Exception { sendMoneyToWallet(Utils.toNanoCoins(100, 0), AbstractBlockChain.NewBlockType.BEST_CHAIN); Transaction tx = new Transaction(params); byte[] bits = new byte[20]; new Random().nextBytes(bits); BigInteger v = Utils.toNanoCoins(0, 1); for (int i = 0; i < 3100; i++) { tx.addOutput(v, new Address(params, bits)); } Wallet.SendRequest req = Wallet.SendRequest.forTx(tx); assertFalse(wallet.completeTx(req)); }
Script { public boolean isSentToRawPubKey() { if (chunks.size() != 2) return false; return chunks.get(1).equalsOpCode(OP_CHECKSIG) && !chunks.get(0).isOpCode && chunks.get(0).data.length > 1; } private Script(); Script(NetworkParameters params, byte[] programBytes, int offset, int length); String toString(); static String getOpCodeName(byte opCode); boolean isSentToRawPubKey(); boolean isSentToAddress(); byte[] getPubKeyHash(); byte[] getPubKey(); Address getFromAddress(); Address getToAddress(); static byte[] createOutputScript(Address to); static byte[] createOutputScript(byte[] pubkey); static byte[] createOutputScript(ECKey pubkey); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); boolean isPayToScriptHash(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, boolean enforceP2SH); static final int OP_0; static final int OP_FALSE; static final int OP_PUSHDATA1; static final int OP_PUSHDATA2; static final int OP_PUSHDATA4; static final int OP_1NEGATE; static final int OP_RESERVED; static final int OP_1; static final int OP_TRUE; static final int OP_2; static final int OP_3; static final int OP_4; static final int OP_5; static final int OP_6; static final int OP_7; static final int OP_8; static final int OP_9; static final int OP_10; static final int OP_11; static final int OP_12; static final int OP_13; static final int OP_14; static final int OP_15; static final int OP_16; static final int OP_NOP; static final int OP_VER; static final int OP_IF; static final int OP_NOTIF; static final int OP_VERIF; static final int OP_VERNOTIF; static final int OP_ELSE; static final int OP_ENDIF; static final int OP_VERIFY; static final int OP_RETURN; static final int OP_TOALTSTACK; static final int OP_FROMALTSTACK; static final int OP_2DROP; static final int OP_2DUP; static final int OP_3DUP; static final int OP_2OVER; static final int OP_2ROT; static final int OP_2SWAP; static final int OP_IFDUP; static final int OP_DEPTH; static final int OP_DROP; static final int OP_DUP; static final int OP_NIP; static final int OP_OVER; static final int OP_PICK; static final int OP_ROLL; static final int OP_ROT; static final int OP_SWAP; static final int OP_TUCK; static final int OP_CAT; static final int OP_SUBSTR; static final int OP_LEFT; static final int OP_RIGHT; static final int OP_SIZE; static final int OP_INVERT; static final int OP_AND; static final int OP_OR; static final int OP_XOR; static final int OP_EQUAL; static final int OP_EQUALVERIFY; static final int OP_RESERVED1; static final int OP_RESERVED2; static final int OP_1ADD; static final int OP_1SUB; static final int OP_2MUL; static final int OP_2DIV; static final int OP_NEGATE; static final int OP_ABS; static final int OP_NOT; static final int OP_0NOTEQUAL; static final int OP_ADD; static final int OP_SUB; static final int OP_MUL; static final int OP_DIV; static final int OP_MOD; static final int OP_LSHIFT; static final int OP_RSHIFT; static final int OP_BOOLAND; static final int OP_BOOLOR; static final int OP_NUMEQUAL; static final int OP_NUMEQUALVERIFY; static final int OP_NUMNOTEQUAL; static final int OP_LESSTHAN; static final int OP_GREATERTHAN; static final int OP_LESSTHANOREQUAL; static final int OP_GREATERTHANOREQUAL; static final int OP_MIN; static final int OP_MAX; static final int OP_WITHIN; static final int OP_RIPEMD160; static final int OP_SHA1; static final int OP_SHA256; static final int OP_HASH160; static final int OP_HASH256; static final int OP_CODESEPARATOR; static final int OP_CHECKSIG; static final int OP_CHECKSIGVERIFY; static final int OP_CHECKMULTISIG; static final int OP_CHECKMULTISIGVERIFY; static final int OP_NOP1; static final int OP_NOP2; static final int OP_NOP3; static final int OP_NOP4; static final int OP_NOP5; static final int OP_NOP6; static final int OP_NOP7; static final int OP_NOP8; static final int OP_NOP9; static final int OP_NOP10; static final int OP_INVALIDOPCODE; }
@Test public void testIp() throws Exception { byte[] bytes = Hex.decode("41043e96222332ea7848323c08116dddafbfa917b8e37f0bdf63841628267148588a09a43540942d58d49717ad3fabfe14978cf4f0a8b84d2435dad16e9aa4d7f935ac"); Script s = new Script(params, bytes, 0, bytes.length); assertTrue(s.isSentToRawPubKey()); }
Script { public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, boolean enforceP2SH) throws ScriptException { if (program.length > 10000 || scriptPubKey.program.length > 10000) throw new ScriptException("Script larger than 10,000 bytes"); LinkedList<byte[]> stack = new LinkedList<byte[]>(); LinkedList<byte[]> p2shStack = null; executeScript(txContainingThis, scriptSigIndex, this, stack); if (enforceP2SH) p2shStack = new LinkedList<byte[]>(stack); executeScript(txContainingThis, scriptSigIndex, scriptPubKey, stack); if (stack.size() == 0) throw new ScriptException("Stack empty at end of script execution."); if (!castToBool(stack.pollLast())) throw new ScriptException("Script resulted in a non-true stack"); if (enforceP2SH && scriptPubKey.isPayToScriptHash()) { for (ScriptChunk chunk : chunks) if (chunk.isOpCode && (chunk.data[0] & 0xff) > OP_16) throw new ScriptException("Attempted to spend a P2SH scriptPubKey with a script that contained script ops"); byte[] scriptPubKeyBytes = p2shStack.pollLast(); Script scriptPubKeyP2SH = new Script(params, scriptPubKeyBytes, 0, scriptPubKeyBytes.length); executeScript(txContainingThis, scriptSigIndex, scriptPubKeyP2SH, p2shStack); if (p2shStack.size() == 0) throw new ScriptException("P2SH stack empty at end of script execution."); if (!castToBool(p2shStack.pollLast())) throw new ScriptException("P2SH script execution resulted in a non-true stack"); } } private Script(); Script(NetworkParameters params, byte[] programBytes, int offset, int length); String toString(); static String getOpCodeName(byte opCode); boolean isSentToRawPubKey(); boolean isSentToAddress(); byte[] getPubKeyHash(); byte[] getPubKey(); Address getFromAddress(); Address getToAddress(); static byte[] createOutputScript(Address to); static byte[] createOutputScript(byte[] pubkey); static byte[] createOutputScript(ECKey pubkey); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); boolean isPayToScriptHash(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, boolean enforceP2SH); static final int OP_0; static final int OP_FALSE; static final int OP_PUSHDATA1; static final int OP_PUSHDATA2; static final int OP_PUSHDATA4; static final int OP_1NEGATE; static final int OP_RESERVED; static final int OP_1; static final int OP_TRUE; static final int OP_2; static final int OP_3; static final int OP_4; static final int OP_5; static final int OP_6; static final int OP_7; static final int OP_8; static final int OP_9; static final int OP_10; static final int OP_11; static final int OP_12; static final int OP_13; static final int OP_14; static final int OP_15; static final int OP_16; static final int OP_NOP; static final int OP_VER; static final int OP_IF; static final int OP_NOTIF; static final int OP_VERIF; static final int OP_VERNOTIF; static final int OP_ELSE; static final int OP_ENDIF; static final int OP_VERIFY; static final int OP_RETURN; static final int OP_TOALTSTACK; static final int OP_FROMALTSTACK; static final int OP_2DROP; static final int OP_2DUP; static final int OP_3DUP; static final int OP_2OVER; static final int OP_2ROT; static final int OP_2SWAP; static final int OP_IFDUP; static final int OP_DEPTH; static final int OP_DROP; static final int OP_DUP; static final int OP_NIP; static final int OP_OVER; static final int OP_PICK; static final int OP_ROLL; static final int OP_ROT; static final int OP_SWAP; static final int OP_TUCK; static final int OP_CAT; static final int OP_SUBSTR; static final int OP_LEFT; static final int OP_RIGHT; static final int OP_SIZE; static final int OP_INVERT; static final int OP_AND; static final int OP_OR; static final int OP_XOR; static final int OP_EQUAL; static final int OP_EQUALVERIFY; static final int OP_RESERVED1; static final int OP_RESERVED2; static final int OP_1ADD; static final int OP_1SUB; static final int OP_2MUL; static final int OP_2DIV; static final int OP_NEGATE; static final int OP_ABS; static final int OP_NOT; static final int OP_0NOTEQUAL; static final int OP_ADD; static final int OP_SUB; static final int OP_MUL; static final int OP_DIV; static final int OP_MOD; static final int OP_LSHIFT; static final int OP_RSHIFT; static final int OP_BOOLAND; static final int OP_BOOLOR; static final int OP_NUMEQUAL; static final int OP_NUMEQUALVERIFY; static final int OP_NUMNOTEQUAL; static final int OP_LESSTHAN; static final int OP_GREATERTHAN; static final int OP_LESSTHANOREQUAL; static final int OP_GREATERTHANOREQUAL; static final int OP_MIN; static final int OP_MAX; static final int OP_WITHIN; static final int OP_RIPEMD160; static final int OP_SHA1; static final int OP_SHA256; static final int OP_HASH160; static final int OP_HASH256; static final int OP_CODESEPARATOR; static final int OP_CHECKSIG; static final int OP_CHECKSIGVERIFY; static final int OP_CHECKMULTISIG; static final int OP_CHECKMULTISIGVERIFY; static final int OP_NOP1; static final int OP_NOP2; static final int OP_NOP3; static final int OP_NOP4; static final int OP_NOP5; static final int OP_NOP6; static final int OP_NOP7; static final int OP_NOP8; static final int OP_NOP9; static final int OP_NOP10; static final int OP_INVALIDOPCODE; }
@Test public void dataDrivenValidScripts() throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader( getClass().getResourceAsStream("script_valid.json"), Charset.forName("UTF-8"))); NetworkParameters params = NetworkParameters.testNet(); String script = ""; while (in.ready()) { String line = in.readLine(); if (line == null || line.equals("")) continue; script += line; if (line.equals("]") && script.equals("]") && !in.ready()) break; if (line.trim().endsWith("],") || line.trim().endsWith("]")) { String[] scripts = script.split(","); Script scriptSig = parseScriptString(params, scripts[0].replaceAll("[\"\\[\\]]", "").trim()); Script scriptPubKey = parseScriptString(params, scripts[1].replaceAll("[\"\\[\\]]", "").trim()); scriptSig.correctlySpends(new Transaction(params), 0, scriptPubKey, true); script = ""; } } in.close(); } @Test public void dataDrivenInvalidScripts() throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader( getClass().getResourceAsStream("script_invalid.json"), Charset.forName("UTF-8"))); NetworkParameters params = NetworkParameters.testNet(); String script = ""; while (in.ready()) { String line = in.readLine(); if (line == null || line.equals("")) continue; script += line; if (line.equals("]") && script.equals("]") && !in.ready()) break; if (line.trim().endsWith("],") || line.trim().equals("]")) { String[] scripts = script.split(","); try { Script scriptSig = parseScriptString(params, scripts[0].replaceAll("[\"\\[\\]]", "").trim()); Script scriptPubKey = parseScriptString(params, scripts[1].replaceAll("[\"\\[\\]]", "").trim()); scriptSig.correctlySpends(new Transaction(params), 0, scriptPubKey, true); fail(); } catch (VerificationException e) { } script = ""; } } in.close(); }
Address extends VersionedChecksummedBytes { public byte[] getHash160() { return bytes; } Address(NetworkParameters params, byte[] hash160); Address(NetworkParameters params, String address); byte[] getHash160(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); static final int LENGTH; }
@Test public void decoding() throws Exception { Address a = new Address(testParams, "n4eA2nbYqErp7H6jebchxAN59DmNpksexv"); assertEquals("fda79a24e50ff70ff42f7d89585da5bd19d9e5cc", Utils.bytesToHexString(a.getHash160())); Address b = new Address(prodParams, "LQz2pJYaeqntA9BFB8rDX5AL2TTKGd5AuN"); assertEquals("3f2ebb6c8d88e586b551303d2c29eba15518d8d1", Utils.bytesToHexString(b.getHash160())); }
Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return new Address(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } Address(NetworkParameters params, byte[] hash160); Address(NetworkParameters params, String address); byte[] getHash160(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); static final int LENGTH; }
@Test public void getNetwork() throws Exception { NetworkParameters params = Address.getParametersFromAddress("LQz2pJYaeqntA9BFB8rDX5AL2TTKGd5AuN"); assertEquals(NetworkParameters.prodNet().getId(), params.getId()); params = Address.getParametersFromAddress("n4eA2nbYqErp7H6jebchxAN59DmNpksexv"); assertEquals(NetworkParameters.testNet().getId(), params.getId()); }
VersionMessage extends Message { @Override public boolean equals(Object o) { if (!(o instanceof VersionMessage)) return false; VersionMessage other = (VersionMessage) o; return other.bestHeight == bestHeight && other.clientVersion == clientVersion && other.localServices == localServices && other.time == time && other.subVer.equals(subVer) && other.myAddr.equals(myAddr) && other.theirAddr.equals(theirAddr) && other.relayTxesBeforeFilter == relayTxesBeforeFilter; } VersionMessage(NetworkParameters params, byte[] msg); VersionMessage(NetworkParameters params, int newBestHeight); VersionMessage(NetworkParameters params, int newBestHeight, boolean relayTxesBeforeFilter); @Override void parse(); @Override void litecoinSerializeToStream(OutputStream buf); boolean hasBlockChain(); @Override boolean equals(Object o); @Override int hashCode(); String toString(); VersionMessage duplicate(); void appendToSubVer(String name, String version, String comments); boolean isPingPongSupported(); boolean isBloomFilteringSupported(); static final int NODE_NETWORK; public int clientVersion; public long localServices; public long time; public PeerAddress myAddr; public PeerAddress theirAddr; public String subVer; public long bestHeight; public boolean relayTxesBeforeFilter; static final String LITECOINJ_VERSION; static final String LIBRARY_SUBVER; }
@Test public void testDecode() throws Exception { NetworkParameters params = NetworkParameters.unitTests(); VersionMessage ver = new VersionMessage(params, Hex.decode("71110100000000000000000048e5e95000000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d0000000000000000172f426974436f696e4a3a302e372d534e415053484f542f0004000000")); assertTrue(!ver.relayTxesBeforeFilter); assertTrue(ver.bestHeight == 1024); assertTrue(ver.subVer.equals("/LitecoinJ:0.7-SNAPSHOT/")); ver = new VersionMessage(params, Hex.decode("71110100000000000000000048e5e95000000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d0000000000000000172f426974436f696e4a3a302e372d534e415053484f542f00040000")); assertTrue(ver.relayTxesBeforeFilter); assertTrue(ver.bestHeight == 1024); assertTrue(ver.subVer.equals("/LitecoinJ:0.7-SNAPSHOT/")); ver = new VersionMessage(params, Hex.decode("71110100000000000000000048e5e95000000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d0000000000000000172f426974436f696e4a3a302e372d534e415053484f542f")); assertTrue(ver.relayTxesBeforeFilter); assertTrue(ver.bestHeight == 0); assertTrue(ver.subVer.equals("/LitecoinJ:0.7-SNAPSHOT/")); ver = new VersionMessage(params, Hex.decode("71110100000000000000000048e5e95000000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d0000000000000000")); assertTrue(ver.relayTxesBeforeFilter); assertTrue(ver.bestHeight == 0); assertTrue(ver.subVer.equals("")); }
Block extends Message { public BigInteger getWork() throws VerificationException { BigInteger target = getDifficultyTargetAsInteger(); return LARGEST_HASH.divide(target.add(BigInteger.ONE)); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); static final int HEADER_SIZE; static final int MAX_BLOCK_SIZE; static final int MAX_BLOCK_SIGOPS; }
@Test public void testWork() throws Exception { BigInteger work = params.genesisBlock.getWork(); assertEquals(BigInteger.valueOf(536879104L), work); }
Block extends Message { public Date getTime() { return new Date(getTimeSeconds()*1000); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); static final int HEADER_SIZE; static final int MAX_BLOCK_SIZE; static final int MAX_BLOCK_SIGOPS; }
@SuppressWarnings("deprecation") @Test public void testDate() throws Exception { Block block = new Block(params, blockBytes); assertEquals("4 Nov 2010 16:06:04 GMT", block.getTime().toGMTString()); }
Block extends Message { public void verify() throws VerificationException { verifyHeader(); verifyTransactions(); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); static final int HEADER_SIZE; static final int MAX_BLOCK_SIZE; static final int MAX_BLOCK_SIGOPS; }
@Test public void testBadTransactions() throws Exception { Block block = new Block(params, blockBytes); Transaction tx1 = block.transactions.get(0); Transaction tx2 = block.transactions.get(1); block.transactions.set(0, tx2); block.transactions.set(1, tx1); try { block.verify(); fail(); } catch (VerificationException e) { } }
SeedPeers implements PeerDiscovery { public InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException { try { return allPeers(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); InetSocketAddress getPeer(); InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit); void shutdown(); static int[] seedAddrs; }
@Test public void getPeers_length() throws Exception{ SeedPeers seedPeers = new SeedPeers(NetworkParameters.prodNet()); InetSocketAddress[] addresses = seedPeers.getPeers(0, TimeUnit.SECONDS); assertThat(addresses.length, equalTo(SeedPeers.seedAddrs.length)); }
Block extends Message { private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); hash = null; } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); static final int HEADER_SIZE; static final int MAX_BLOCK_SIZE; static final int MAX_BLOCK_SIGOPS; }
@Test public void testJavaSerialiazation() throws Exception { Block block = new Block(params, blockBytes); Transaction tx = block.transactions.get(1); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(tx); oos.close(); byte[] javaBits = bos.toByteArray(); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(javaBits)); Transaction tx2 = (Transaction) ois.readObject(); ois.close(); assertEquals(tx, tx2); }
Peer { public void addEventListener(PeerEventListener listener) { eventListeners.add(listener); } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); }
@Test public void testAddEventListener() throws Exception { control.replay(); connect(); PeerEventListener listener = new AbstractPeerEventListener(); peer.addEventListener(listener); assertTrue(peer.removeEventListener(listener)); assertFalse(peer.removeEventListener(listener)); }
Peer { public void startBlockChainDownload() throws IOException { setDownloadData(true); final int blocksLeft = getPeerBlockHeightDifference(); if (blocksLeft >= 0) { for (PeerEventListener listener : eventListeners) listener.onChainDownloadStarted(this, blocksLeft); blockChainDownload(Sha256Hash.ZERO_HASH); } } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); }
@Test public void chainDownloadEnd2End() throws Exception { Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); Block b3 = makeSolvedTestBlock(b2); Block b4 = makeSolvedTestBlock(b3); Block b5 = makeSolvedTestBlock(b4); control.replay(); connect(); peer.startBlockChainDownload(); GetBlocksMessage getblocks = (GetBlocksMessage)outbound(); assertEquals(blockStore.getChainHead().getHeader().getHash(), getblocks.getLocator().get(0)); assertEquals(Sha256Hash.ZERO_HASH, getblocks.getStopHash()); InventoryMessage inv = new InventoryMessage(unitTestParams); inv.addBlock(b2); inv.addBlock(b3); inbound(peer, inv); GetDataMessage getdata = (GetDataMessage)outbound(); assertEquals(b2.getHash(), getdata.getItems().get(0).hash); assertEquals(b3.getHash(), getdata.getItems().get(1).hash); assertEquals(2, getdata.getItems().size()); inbound(peer, b2); inbound(peer, b3); inv = new InventoryMessage(unitTestParams); inv.addBlock(b5); inbound(peer, inv); getdata = (GetDataMessage)outbound(); assertEquals(b5.getHash(), getdata.getItems().get(0).hash); assertEquals(1, getdata.getItems().size()); inbound(peer, b5); getblocks = (GetBlocksMessage)outbound(); assertEquals(b5.getHash(), getblocks.getStopHash()); assertEquals(b3.getHash(), getblocks.getLocator().get(0)); Block b6 = makeSolvedTestBlock(b5); inv = new InventoryMessage(unitTestParams); inv.addBlock(b6); inbound(peer, inv); getdata = (GetDataMessage)outbound(); assertEquals(1, getdata.getItems().size()); assertEquals(b6.getHash(), getdata.getItems().get(0).hash); inbound(peer, b6); assertFalse(event.hasCaptured()); inv = new InventoryMessage(unitTestParams); inv.addBlock(b4); inv.addBlock(b5); inbound(peer, inv); getdata = (GetDataMessage)outbound(); assertEquals(1, getdata.getItems().size()); assertEquals(b4.getHash(), getdata.getItems().get(0).hash); inbound(peer, b4); assertFalse(event.hasCaptured()); closePeer(peer); control.verify(); } @Test public void startBlockChainDownload() throws Exception { PeerEventListener listener = control.createMock(PeerEventListener.class); Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); blockChain.add(b2); listener.onChainDownloadStarted(peer, 108); expectLastCall(); control.replay(); connect(); peer.addEventListener(listener); peer.startBlockChainDownload(); control.verify(); List<Sha256Hash> expectedLocator = new ArrayList<Sha256Hash>(); expectedLocator.add(b2.getHash()); expectedLocator.add(b1.getHash()); expectedLocator.add(unitTestParams.genesisBlock.getHash()); GetBlocksMessage message = (GetBlocksMessage) event.getValue().getMessage(); assertEquals(message.getLocator(), expectedLocator); assertEquals(message.getStopHash(), Sha256Hash.ZERO_HASH); }
Peer { public void setDownloadData(boolean downloadData) { this.vDownloadData = downloadData; } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); }
@Test public void invNoDownload() throws Exception { peer.setDownloadData(false); control.replay(); connect(); Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); InventoryMessage inv = new InventoryMessage(unitTestParams); InventoryItem item = new InventoryItem(InventoryItem.Type.Block, b2.getHash()); inv.addItem(item); inbound(peer, inv); control.verify(); } @Test public void invDownloadTx() throws Exception { control.replay(); connect(); peer.setDownloadData(true); BigInteger value = Utils.toNanoCoins(1, 0); Transaction tx = createFakeTx(unitTestParams, value, address); InventoryMessage inv = new InventoryMessage(unitTestParams); InventoryItem item = new InventoryItem(InventoryItem.Type.Transaction, tx.getHash()); inv.addItem(item); inbound(peer, inv); GetDataMessage getdata = (GetDataMessage) outbound(); assertEquals(1, getdata.getItems().size()); assertEquals(tx.getHash(), getdata.getItems().get(0).hash); inbound(peer, tx); getdata = (GetDataMessage) outbound(); inbound(peer, new NotFoundMessage(unitTestParams, getdata.getItems())); assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED)); }
Peer { public ListenableFuture<Block> getBlock(Sha256Hash blockHash) throws IOException { log.info("Request to fetch block {}", blockHash); GetDataMessage getdata = new GetDataMessage(params); getdata.addBlock(blockHash); return sendSingleGetData(getdata); } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); }
@Test public void getBlock() throws Exception { control.replay(); connect(); Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); Block b3 = makeSolvedTestBlock(b2); Future<Block> resultFuture = peer.getBlock(b3.getHash()); assertFalse(resultFuture.isDone()); GetDataMessage message = (GetDataMessage) event.getValue().getMessage(); assertEquals(message.getItems().get(0).hash, b3.getHash()); assertFalse(resultFuture.isDone()); inbound(peer, b3); Block b = resultFuture.get(); assertEquals(b, b3); }
Peer { public ChannelFuture setMinProtocolVersion(int minProtocolVersion) { this.vMinProtocolVersion = minProtocolVersion; if (getVersionMessage().clientVersion < minProtocolVersion) { log.warn("{}: Disconnecting due to new min protocol version {}", this, minProtocolVersion); return Channels.close(vChannel); } else { return null; } } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); }
@Test public void disconnectOldVersions2() throws Exception { expect(channel.close()).andReturn(null); control.replay(); handler.connectRequested(ctx, new UpstreamChannelStateEvent(channel, ChannelState.CONNECTED, socketAddress)); VersionMessage peerVersion = new VersionMessage(unitTestParams, OTHER_PEER_CHAIN_HEIGHT); peerVersion.clientVersion = 70000; DownstreamMessageEvent versionEvent = new DownstreamMessageEvent(channel, Channels.future(channel), peerVersion, null); handler.messageReceived(ctx, versionEvent); peer.setMinProtocolVersion(500); }
PeerGroup extends AbstractIdleService { public void addPeerDiscovery(PeerDiscovery peerDiscovery) { lock.lock(); try { if (getMaxConnections() == 0) setMaxConnections(DEFAULT_CONNECTIONS); peerDiscoverers.add(peerDiscovery); } finally { lock.unlock(); } } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); static ClientBootstrap createClientBootstrap(); void setMaxConnections(int maxConnections); int getMaxConnections(); void setVersionMessage(VersionMessage ver); VersionMessage getVersionMessage(); void setUserAgent(String name, String version, String comments); void setUserAgent(String name, String version); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); List<Peer> getConnectedPeers(); List<Peer> getPendingPeers(); void addAddress(PeerAddress peerAddress); void addAddress(InetAddress address); void addPeerDiscovery(PeerDiscovery peerDiscovery); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); void setBloomFilterFalsePositiveRate(double bloomFilterFPRate); int numConnectedPeers(); ChannelFuture connectTo(SocketAddress address); static Peer peerFromChannelFuture(ChannelFuture future); static Peer peerFromChannel(Channel channel); void startBlockChainDownload(PeerEventListener listener); void downloadBlockChain(); MemoryPool getMemoryPool(); void setFastCatchupTimeSecs(long secondsSinceEpoch); long getFastCatchupTimeSecs(); ListenableFuture<PeerGroup> waitForPeers(final int numPeers); int getMinBroadcastConnections(); void setMinBroadcastConnections(int value); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx, final int minConnections); long getPingIntervalMsec(); void setPingIntervalMsec(long pingIntervalMsec); int getMostCommonChainHeight(); Peer getDownloadPeer(); static final long DEFAULT_PING_INTERVAL_MSEC; static final double DEFAULT_BLOOM_FILTER_FP_RATE; }
@Test public void peerDiscoveryPolling() throws Exception { final Semaphore sem = new Semaphore(0); final boolean[] result = new boolean[1]; result[0] = false; peerGroup.addPeerDiscovery(new PeerDiscovery() { public InetSocketAddress[] getPeers(long unused, TimeUnit unused2) throws PeerDiscoveryException { if (result[0] == false) { result[0] = true; throw new PeerDiscoveryException("test failure"); } else { sem.release(); return new InetSocketAddress[]{new InetSocketAddress("localhost", 0)}; } } public void shutdown() { } }); peerGroup.startAndWait(); sem.acquire(); assertTrue(result[0]); }
PeerGroup extends AbstractIdleService { public int numConnectedPeers() { return peers.size(); } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); static ClientBootstrap createClientBootstrap(); void setMaxConnections(int maxConnections); int getMaxConnections(); void setVersionMessage(VersionMessage ver); VersionMessage getVersionMessage(); void setUserAgent(String name, String version, String comments); void setUserAgent(String name, String version); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); List<Peer> getConnectedPeers(); List<Peer> getPendingPeers(); void addAddress(PeerAddress peerAddress); void addAddress(InetAddress address); void addPeerDiscovery(PeerDiscovery peerDiscovery); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); void setBloomFilterFalsePositiveRate(double bloomFilterFPRate); int numConnectedPeers(); ChannelFuture connectTo(SocketAddress address); static Peer peerFromChannelFuture(ChannelFuture future); static Peer peerFromChannel(Channel channel); void startBlockChainDownload(PeerEventListener listener); void downloadBlockChain(); MemoryPool getMemoryPool(); void setFastCatchupTimeSecs(long secondsSinceEpoch); long getFastCatchupTimeSecs(); ListenableFuture<PeerGroup> waitForPeers(final int numPeers); int getMinBroadcastConnections(); void setMinBroadcastConnections(int value); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx, final int minConnections); long getPingIntervalMsec(); void setPingIntervalMsec(long pingIntervalMsec); int getMostCommonChainHeight(); Peer getDownloadPeer(); static final long DEFAULT_PING_INTERVAL_MSEC; static final double DEFAULT_BLOOM_FILTER_FP_RATE; }
@Test public void singleDownloadPeer1() throws Exception { peerGroup.startAndWait(); FakeChannel p1 = connectPeer(1); FakeChannel p2 = connectPeer(2); assertEquals(2, peerGroup.numConnectedPeers()); Block b1 = TestUtils.createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = TestUtils.makeSolvedTestBlock(b1); Block b3 = TestUtils.makeSolvedTestBlock(b2); InventoryMessage inv = new InventoryMessage(params); inv.addBlock(b3); inbound(p1, inv); assertTrue(outbound(p1) instanceof GetDataMessage); assertNull(outbound(p2)); closePeer(peerOf(p1)); inbound(p2, inv); assertTrue(outbound(p2) instanceof GetDataMessage); peerGroup.stop(); }
IrcDiscovery implements PeerDiscovery { static ArrayList<InetSocketAddress> parseUserList(String[] userNames) throws UnknownHostException { ArrayList<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>(); for (String user : userNames) { if (!user.startsWith("u")) { continue; } byte[] addressBytes; try { addressBytes = Base58.decodeChecked(user.substring(1)); } catch (AddressFormatException e) { log.warn("IRC nick does not parse as base58: " + user); continue; } if (addressBytes.length != 6) { continue; } byte[] ipBytes = new byte[]{addressBytes[0], addressBytes[1], addressBytes[2], addressBytes[3]}; int port = Utils.readUint16BE(addressBytes, 4); InetAddress ip; try { ip = InetAddress.getByAddress(ipBytes); } catch (UnknownHostException e) { continue; } InetSocketAddress address = new InetSocketAddress(ip, port); addresses.add(address); } return addresses; } IrcDiscovery(String channel); IrcDiscovery(String channel, String server, int port); void shutdown(); InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit); }
@Test public void testParseUserList() throws UnknownHostException { String[] userList = new String[]{ "x201500200","u4stwEBjT6FYyVV", "u5BKEqDApa8SbA7"}; ArrayList<InetSocketAddress> addresses = IrcDiscovery.parseUserList(userList); assertEquals("Too many addresses.", 2, addresses.size()); String[] ips = new String[]{"69.4.98.82:8333","74.92.222.129:8333"}; InetSocketAddress[] decoded = addresses.toArray(new InetSocketAddress[]{}); for (int i = 0; i < decoded.length; i++) { String formattedIP = decoded[i].getAddress().getHostAddress() + ":" + ((Integer)decoded[i].getPort()) .toString(); assertEquals("IPs decoded improperly", ips[i], formattedIP); } }
PeerGroup extends AbstractIdleService { public void startBlockChainDownload(PeerEventListener listener) { lock.lock(); try { this.downloadListener = listener; synchronized (peers) { if (!peers.isEmpty()) { startBlockChainDownloadFromPeer(peers.iterator().next()); } } } finally { lock.unlock(); } } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); static ClientBootstrap createClientBootstrap(); void setMaxConnections(int maxConnections); int getMaxConnections(); void setVersionMessage(VersionMessage ver); VersionMessage getVersionMessage(); void setUserAgent(String name, String version, String comments); void setUserAgent(String name, String version); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); List<Peer> getConnectedPeers(); List<Peer> getPendingPeers(); void addAddress(PeerAddress peerAddress); void addAddress(InetAddress address); void addPeerDiscovery(PeerDiscovery peerDiscovery); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); void setBloomFilterFalsePositiveRate(double bloomFilterFPRate); int numConnectedPeers(); ChannelFuture connectTo(SocketAddress address); static Peer peerFromChannelFuture(ChannelFuture future); static Peer peerFromChannel(Channel channel); void startBlockChainDownload(PeerEventListener listener); void downloadBlockChain(); MemoryPool getMemoryPool(); void setFastCatchupTimeSecs(long secondsSinceEpoch); long getFastCatchupTimeSecs(); ListenableFuture<PeerGroup> waitForPeers(final int numPeers); int getMinBroadcastConnections(); void setMinBroadcastConnections(int value); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx, final int minConnections); long getPingIntervalMsec(); void setPingIntervalMsec(long pingIntervalMsec); int getMostCommonChainHeight(); Peer getDownloadPeer(); static final long DEFAULT_PING_INTERVAL_MSEC; static final double DEFAULT_BLOOM_FILTER_FP_RATE; }
@Test public void singleDownloadPeer2() throws Exception { peerGroup.startAndWait(); FakeChannel p1 = connectPeer(1); Block b1 = TestUtils.createFakeBlock(blockStore).block; Block b2 = TestUtils.makeSolvedTestBlock(b1); Block b3 = TestUtils.makeSolvedTestBlock(b2); peerGroup.startBlockChainDownload(new AbstractPeerEventListener() { }); GetBlocksMessage getblocks = (GetBlocksMessage) outbound(p1); assertEquals(Sha256Hash.ZERO_HASH, getblocks.getStopHash()); InventoryMessage inv = new InventoryMessage(params); inv.addBlock(b1); inv.addBlock(b2); inv.addBlock(b3); inbound(p1, inv); assertTrue(outbound(p1) instanceof GetDataMessage); inbound(p1, b1); FakeChannel p2 = connectPeer(2); Message message = (Message)outbound(p2); assertNull(message == null ? "" : message.toString(), message); peerGroup.stop(); }
LitecoinSerializer { public Message deserialize(InputStream in) throws ProtocolException, IOException { seekPastMagicBytes(in); LitecoinPacketHeader header = new LitecoinPacketHeader(in); return deserializePayload(header, in); } LitecoinSerializer(NetworkParameters params); LitecoinSerializer(NetworkParameters params, boolean parseLazy, boolean parseRetain); void serialize(Message message, OutputStream out); Message deserialize(InputStream in); LitecoinPacketHeader deserializeHeader(InputStream in); Message deserializePayload(LitecoinPacketHeader header, InputStream in); void seekPastMagicBytes(InputStream in); boolean isParseLazyMode(); boolean isParseRetainMode(); }
@Test public void testHeaders1() throws Exception { LitecoinSerializer bs = new LitecoinSerializer(NetworkParameters.prodNet()); ByteArrayInputStream bais = new ByteArrayInputStream(Hex.decode("fbc0b6db686561" + "646572730000000000520000005d4fab8101010000006fe28c0ab6f1b372c1a6a246ae6" + "3f74f931e8365e15a089c68d6190000000000982051fd1e4ba744bbbe680e1fee14677b" + "a1a3c3540bf7b1cdb606e857233e0e61bc6649ffff001d01e3629900")); HeadersMessage hm = (HeadersMessage) bs.deserialize(bais); Block block = hm.getBlockHeaders().get(0); String hash = block.getHashAsString(); assertEquals(hash, "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048"); assertNull(block.transactions); assertEquals(Utils.bytesToHexString(block.getMerkleRoot().getBytes()), "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098"); } @Test public void testHeaders2() throws Exception { LitecoinSerializer bs = new LitecoinSerializer(NetworkParameters.prodNet()); ByteArrayInputStream bais = new ByteArrayInputStream(Hex.decode("fbc0b6db6865616465" + "72730000000000e701000085acd4ea06010000006fe28c0ab6f1b372c1a6a246ae63f74f931e" + "8365e15a089c68d6190000000000982051fd1e4ba744bbbe680e1fee14677ba1a3c3540bf7b1c" + "db606e857233e0e61bc6649ffff001d01e3629900010000004860eb18bf1b1620e37e9490fc8a" + "427514416fd75159ab86688e9a8300000000d5fdcc541e25de1c7a5addedf24858b8bb665c9f36" + "ef744ee42c316022c90f9bb0bc6649ffff001d08d2bd610001000000bddd99ccfda39da1b108ce1" + "a5d70038d0a967bacb68b6b63065f626a0000000044f672226090d85db9a9f2fbfe5f0f9609b387" + "af7be5b7fbb7a1767c831c9e995dbe6649ffff001d05e0ed6d00010000004944469562ae1c2c74" + "d9a535e00b6f3e40ffbad4f2fda3895501b582000000007a06ea98cd40ba2e3288262b28638cec" + "5337c1456aaf5eedc8e9e5a20f062bdf8cc16649ffff001d2bfee0a9000100000085144a84488e" + "a88d221c8bd6c059da090e88f8a2c99690ee55dbba4e00000000e11c48fecdd9e72510ca84f023" + "370c9a38bf91ac5cae88019bee94d24528526344c36649ffff001d1d03e4770001000000fc33f5" + "96f822a0a1951ffdbf2a897b095636ad871707bf5d3162729b00000000379dfb96a5ea8c81700ea4" + "ac6b97ae9a9312b2d4301a29580e924ee6761a2520adc46649ffff001d189c4c9700")); HeadersMessage hm = (HeadersMessage) bs.deserialize(bais); int nBlocks = hm.getBlockHeaders().size(); assertEquals(nBlocks, 6); Block zeroBlock = hm.getBlockHeaders().get(0); String zeroBlockHash = zeroBlock.getHashAsString(); assertEquals("00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048", zeroBlockHash); assertEquals(zeroBlock.getNonce(), 2573394689L); Block thirdBlock = hm.getBlockHeaders().get(3); String thirdBlockHash = thirdBlock.getHashAsString(); assertEquals("000000004ebadb55ee9096c9a2f8880e09da59c0d68b1c228da88e48844a1485", thirdBlockHash); assertEquals(thirdBlock.getNonce(), 2850094635L); }
ECKey implements Serializable { public void verifyMessage(String message, String signatureBase64) throws SignatureException { ECKey key = ECKey.signedMessageToKey(message, signatureBase64); if (!Arrays.equals(key.getPubKey(), pub)) throw new SignatureException("Signature did not match for message"); } ECKey(); ECKey(BigInteger privKey); ECKey(BigInteger privKey, BigInteger pubKey); ECKey(byte[] privKeyBytes, byte[] pubKey); ECKey(EncryptedPrivateKey encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter); ECKey(BigInteger privKey, byte[] pubKey, boolean compressed); private ECKey(BigInteger privKey, byte[] pubKey); static ECKey fromASN1(byte[] asn1privkey); byte[] toASN1(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getPubKeyHash(); byte[] getPubKey(); boolean isCompressed(); String toString(); String toStringWithPrivate(); Address toAddress(NetworkParameters params); void clearPrivateKey(); ECDSASignature sign(Sha256Hash input); ECDSASignature sign(Sha256Hash input, KeyParameter aesKey); static boolean verify(byte[] data, byte[] signature, byte[] pub); boolean verify(byte[] data, byte[] signature); String signMessage(String message); String signMessage(String message, KeyParameter aesKey); static ECKey signedMessageToKey(String message, String signatureBase64); void verifyMessage(String message, String signatureBase64); static ECKey recoverFromSignature(int recId, ECDSASignature sig, Sha256Hash message, boolean compressed); byte[] getPrivKeyBytes(); DumpedPrivateKey getPrivateKeyEncoded(NetworkParameters params); long getCreationTimeSeconds(); void setCreationTimeSeconds(long newCreationTimeSeconds); @Override boolean equals(Object o); @Override int hashCode(); ECKey encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey decrypt(KeyCrypter keyCrypter, KeyParameter aesKey); static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey); boolean isEncrypted(); EncryptedPrivateKey getEncryptedPrivateKey(); KeyCrypter getKeyCrypter(); }
@Test public void verifyMessage() throws Exception { String message = "hello"; String sigBase64 = "HxNZdo6ggZ41hd3mM3gfJRqOQPZYcO8z8qdX2BwmpbF11CaOQV+QiZGGQxaYOncKoNW61oRuSMMF8udfK54XqI8="; Address expectedAddress = new Address(NetworkParameters.prodNet(), "LNmLhahYB2gb3Hf3ZJsGaTyhG3HPDEPXfn"); ECKey key = ECKey.signedMessageToKey(message, sigBase64); Address gotAddress = key.toAddress(NetworkParameters.prodNet()); assertEquals(expectedAddress, gotAddress); }
ECKey implements Serializable { public static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey) { String genericErrorText = "The check that encryption could be reversed failed for key " + originalKey.toString() + ". "; try { ECKey rebornUnencryptedKey = encryptedKey.decrypt(keyCrypter, aesKey); if (rebornUnencryptedKey == null) { log.error(genericErrorText + "The test decrypted key was missing."); return false; } byte[] originalPrivateKeyBytes = originalKey.getPrivKeyBytes(); if (originalPrivateKeyBytes != null) { if (rebornUnencryptedKey.getPrivKeyBytes() == null) { log.error(genericErrorText + "The test decrypted key was missing."); return false; } else { if (originalPrivateKeyBytes.length != rebornUnencryptedKey.getPrivKeyBytes().length) { log.error(genericErrorText + "The test decrypted private key was a different length to the original."); return false; } else { for (int i = 0; i < originalPrivateKeyBytes.length; i++) { if (originalPrivateKeyBytes[i] != rebornUnencryptedKey.getPrivKeyBytes()[i]) { log.error(genericErrorText + "Byte " + i + " of the private key did not match the original."); return false; } } } } } } catch (KeyCrypterException kce) { log.error(kce.getMessage()); return false; } return true; } ECKey(); ECKey(BigInteger privKey); ECKey(BigInteger privKey, BigInteger pubKey); ECKey(byte[] privKeyBytes, byte[] pubKey); ECKey(EncryptedPrivateKey encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter); ECKey(BigInteger privKey, byte[] pubKey, boolean compressed); private ECKey(BigInteger privKey, byte[] pubKey); static ECKey fromASN1(byte[] asn1privkey); byte[] toASN1(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getPubKeyHash(); byte[] getPubKey(); boolean isCompressed(); String toString(); String toStringWithPrivate(); Address toAddress(NetworkParameters params); void clearPrivateKey(); ECDSASignature sign(Sha256Hash input); ECDSASignature sign(Sha256Hash input, KeyParameter aesKey); static boolean verify(byte[] data, byte[] signature, byte[] pub); boolean verify(byte[] data, byte[] signature); String signMessage(String message); String signMessage(String message, KeyParameter aesKey); static ECKey signedMessageToKey(String message, String signatureBase64); void verifyMessage(String message, String signatureBase64); static ECKey recoverFromSignature(int recId, ECDSASignature sig, Sha256Hash message, boolean compressed); byte[] getPrivKeyBytes(); DumpedPrivateKey getPrivateKeyEncoded(NetworkParameters params); long getCreationTimeSeconds(); void setCreationTimeSeconds(long newCreationTimeSeconds); @Override boolean equals(Object o); @Override int hashCode(); ECKey encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey decrypt(KeyCrypter keyCrypter, KeyParameter aesKey); static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey); boolean isEncrypted(); EncryptedPrivateKey getEncryptedPrivateKey(); KeyCrypter getKeyCrypter(); }
@Test public void testEncryptionIsReversible() throws Exception { ECKey originalUnencryptedKey = new ECKey(); EncryptedPrivateKey encryptedPrivateKey = keyCrypter.encrypt(originalUnencryptedKey.getPrivKeyBytes(), keyCrypter.deriveKey(PASSWORD1)); ECKey encryptedKey = new ECKey(encryptedPrivateKey, originalUnencryptedKey.getPubKey(), keyCrypter); assertTrue("Key not encrypted at start", encryptedKey.isEncrypted()); assertTrue("Key encryption is not reversible but it should be", ECKey.encryptionIsReversible(originalUnencryptedKey, encryptedKey, keyCrypter, keyCrypter.deriveKey(PASSWORD1))); assertTrue("Key encryption is reversible with wrong password", !ECKey.encryptionIsReversible(originalUnencryptedKey, encryptedKey, keyCrypter, keyCrypter.deriveKey(WRONG_PASSWORD))); byte[] goodEncryptedPrivateKeyBytes = encryptedPrivateKey.getEncryptedBytes(); byte[] badEncryptedPrivateKeyBytes = goodEncryptedPrivateKeyBytes; badEncryptedPrivateKeyBytes[16] = (byte) (badEncryptedPrivateKeyBytes[12] ^ new Byte("12").byteValue()); encryptedPrivateKey.setEncryptedPrivateBytes(badEncryptedPrivateKeyBytes); ECKey badEncryptedKey = new ECKey(encryptedPrivateKey, originalUnencryptedKey.getPubKey(), keyCrypter); assertTrue("Key encryption is reversible with faulty encrypted bytes", !ECKey.encryptionIsReversible(originalUnencryptedKey, badEncryptedKey, keyCrypter, keyCrypter.deriveKey(PASSWORD1))); }
ECKey implements Serializable { public String toString() { StringBuilder b = new StringBuilder(); b.append("pub:").append(Utils.bytesToHexString(pub)); if (creationTimeSeconds != 0) { b.append(" timestamp:").append(creationTimeSeconds); } if (isEncrypted()) { b.append(" encrypted"); } return b.toString(); } ECKey(); ECKey(BigInteger privKey); ECKey(BigInteger privKey, BigInteger pubKey); ECKey(byte[] privKeyBytes, byte[] pubKey); ECKey(EncryptedPrivateKey encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter); ECKey(BigInteger privKey, byte[] pubKey, boolean compressed); private ECKey(BigInteger privKey, byte[] pubKey); static ECKey fromASN1(byte[] asn1privkey); byte[] toASN1(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getPubKeyHash(); byte[] getPubKey(); boolean isCompressed(); String toString(); String toStringWithPrivate(); Address toAddress(NetworkParameters params); void clearPrivateKey(); ECDSASignature sign(Sha256Hash input); ECDSASignature sign(Sha256Hash input, KeyParameter aesKey); static boolean verify(byte[] data, byte[] signature, byte[] pub); boolean verify(byte[] data, byte[] signature); String signMessage(String message); String signMessage(String message, KeyParameter aesKey); static ECKey signedMessageToKey(String message, String signatureBase64); void verifyMessage(String message, String signatureBase64); static ECKey recoverFromSignature(int recId, ECDSASignature sig, Sha256Hash message, boolean compressed); byte[] getPrivKeyBytes(); DumpedPrivateKey getPrivateKeyEncoded(NetworkParameters params); long getCreationTimeSeconds(); void setCreationTimeSeconds(long newCreationTimeSeconds); @Override boolean equals(Object o); @Override int hashCode(); ECKey encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey decrypt(KeyCrypter keyCrypter, KeyParameter aesKey); static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey); boolean isEncrypted(); EncryptedPrivateKey getEncryptedPrivateKey(); KeyCrypter getKeyCrypter(); }
@Test public void testToString() throws Exception { ECKey key = new ECKey(BigInteger.TEN); assertEquals("pub:04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7", key.toString()); assertEquals("pub:04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7 priv:0a", key.toStringWithPrivate()); }
Utils { public static BigInteger toNanoCoins(int coins, int cents) { checkArgument(cents < 100); BigInteger bi = BigInteger.valueOf(coins).multiply(COIN); bi = bi.add(BigInteger.valueOf(cents).multiply(CENT)); return bi; } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1, byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); static final String LITECOIN_SIGNED_MESSAGE_HEADER; static final BigInteger COIN; static final BigInteger CENT; static volatile Date mockTime; }
@Test public void testToNanoCoins() { assertEquals(CENT, toNanoCoins("0.01")); assertEquals(CENT, toNanoCoins("1E-2")); assertEquals(COIN.add(Utils.CENT), toNanoCoins("1.01")); try { toNanoCoins("2E-20"); org.junit.Assert.fail("should not have accepted fractional nanocoins"); } catch (ArithmeticException e) { } assertEquals(CENT, toNanoCoins(0, 1)); assertEquals(COIN.subtract(CENT), toNanoCoins(1, -1)); assertEquals(COIN.negate(), toNanoCoins(-1, 0)); assertEquals(COIN.negate(), toNanoCoins("-1")); }
Utils { public static String litecoinValueToPlainString(BigInteger value) { if (value == null) { throw new IllegalArgumentException("Value cannot be null"); } BigDecimal valueInBTC = new BigDecimal(value).divide(new BigDecimal(Utils.COIN)); return valueInBTC.toPlainString(); } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1, byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); static final String LITECOIN_SIGNED_MESSAGE_HEADER; static final BigInteger COIN; static final BigInteger CENT; static volatile Date mockTime; }
@Test public void testLitecoinValueToPlainString() { try { litecoinValueToPlainString(null); org.junit.Assert.fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("Value cannot be null")); } assertEquals("0.0015", litecoinValueToPlainString(BigInteger.valueOf(150000))); assertEquals("1.23", litecoinValueToPlainString(toNanoCoins("1.23"))); assertEquals("-1.23", litecoinValueToPlainString(toNanoCoins("-1.23"))); assertEquals("0.1", litecoinValueToPlainString(toNanoCoins("0.1"))); assertEquals("1.1", litecoinValueToPlainString(toNanoCoins("1.1"))); assertEquals("21.12", litecoinValueToPlainString(toNanoCoins("21.12"))); assertEquals("321.123", litecoinValueToPlainString(toNanoCoins("321.123"))); assertEquals("4321.1234", litecoinValueToPlainString(toNanoCoins("4321.1234"))); assertEquals("54321.12345", litecoinValueToPlainString(toNanoCoins("54321.12345"))); assertEquals("654321.123456", litecoinValueToPlainString(toNanoCoins("654321.123456"))); assertEquals("7654321.1234567", litecoinValueToPlainString(toNanoCoins("7654321.1234567"))); assertEquals("87654321.12345678", litecoinValueToPlainString(toNanoCoins("87654321.12345678"))); assertEquals("1", litecoinValueToPlainString(toNanoCoins("1.0"))); assertEquals("2", litecoinValueToPlainString(toNanoCoins("2.00"))); assertEquals("3", litecoinValueToPlainString(toNanoCoins("3.000"))); assertEquals("4", litecoinValueToPlainString(toNanoCoins("4.0000"))); assertEquals("5", litecoinValueToPlainString(toNanoCoins("5.00000"))); assertEquals("6", litecoinValueToPlainString(toNanoCoins("6.000000"))); assertEquals("7", litecoinValueToPlainString(toNanoCoins("7.0000000"))); assertEquals("8", litecoinValueToPlainString(toNanoCoins("8.00000000"))); }
Utils { public static byte[] reverseBytes(byte[] bytes) { byte[] buf = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) buf[i] = bytes[bytes.length - 1 - i]; return buf; } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1, byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); static final String LITECOIN_SIGNED_MESSAGE_HEADER; static final BigInteger COIN; static final BigInteger CENT; static volatile Date mockTime; }
@Test public void testReverseBytes() { Assert.assertArrayEquals(new byte[] {1,2,3,4,5}, Utils.reverseBytes(new byte[] {5,4,3,2,1})); }
Utils { public static byte[] reverseDwordBytes(byte[] bytes, int trimLength) { checkArgument(bytes.length % 4 == 0); checkArgument(trimLength < 0 || trimLength % 4 == 0); byte[] rev = new byte[trimLength >= 0 && bytes.length > trimLength ? trimLength : bytes.length]; for (int i = 0; i < rev.length; i += 4) { System.arraycopy(bytes, i, rev, i , 4); for (int j = 0; j < 4; j++) { rev[i + j] = bytes[i + 3 - j]; } } return rev; } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1, byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); static final String LITECOIN_SIGNED_MESSAGE_HEADER; static final BigInteger COIN; static final BigInteger CENT; static volatile Date mockTime; }
@Test public void testReverseDwordBytes() { Assert.assertArrayEquals(new byte[] {1,2,3,4,5,6,7,8}, Utils.reverseDwordBytes(new byte[] {4,3,2,1,8,7,6,5}, -1)); Assert.assertArrayEquals(new byte[] {1,2,3,4}, Utils.reverseDwordBytes(new byte[] {4,3,2,1,8,7,6,5}, 4)); Assert.assertArrayEquals(new byte[0], Utils.reverseDwordBytes(new byte[] {4,3,2,1,8,7,6,5}, 0)); Assert.assertArrayEquals(new byte[0], Utils.reverseDwordBytes(new byte[0], 0)); }
LitecoinURI { public static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message) { return convertToLitecoinURI(address.toString(), amount, label, message); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); static final String FIELD_MESSAGE; static final String FIELD_LABEL; static final String FIELD_AMOUNT; static final String FIELD_ADDRESS; static final String LITECOIN_SCHEME; }
@Test public void testConvertToLitecoinURI() throws Exception { Address goodAddress = new Address(NetworkParameters.prodNet(), PRODNET_GOOD_ADDRESS); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=12.34&label=Hello&message=AMessage", LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("12.34"), "Hello", "AMessage")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=12.34&label=Hello%20World&message=Mess%20%26%20age%20%2B%20hope", LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("12.34"), "Hello World", "Mess & age + hope")); try { LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("-0.1"), "hope", "glory"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("Amount must be positive")); } assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?label=Hello&message=glory", LitecoinURI.convertToLitecoinURI(goodAddress, null, "Hello", "glory")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=0.1&message=glory", LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("0.1"), null, "glory")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=0.1&message=glory", LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("0.1"), "", "glory")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=12.34&label=Hello", LitecoinURI.convertToLitecoinURI(goodAddress,Utils.toNanoCoins("12.34"), "Hello", null)); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=12.34&label=Hello", LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("12.34"), "Hello", "")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=1000", LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("1000"), null, null)); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=1000", LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("1000"), "", "")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?label=Hello", LitecoinURI.convertToLitecoinURI(goodAddress, null, "Hello", null)); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?message=Agatha", LitecoinURI.convertToLitecoinURI(goodAddress, null, null, "Agatha")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?message=Agatha", LitecoinURI.convertToLitecoinURI(goodAddress, null, "", "Agatha")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS, LitecoinURI.convertToLitecoinURI(goodAddress, null, null, null)); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS, LitecoinURI.convertToLitecoinURI(goodAddress, null, "", "")); }
LitecoinURI { public String getLabel() { return (String) parameterMap.get(FIELD_LABEL); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); static final String FIELD_MESSAGE; static final String FIELD_LABEL; static final String FIELD_AMOUNT; static final String FIELD_ADDRESS; static final String LITECOIN_SCHEME; }
@Test public void testGood_Label() throws LitecoinURIParseException { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?label=Hello%20World"); assertEquals("Hello World", testObject.getLabel()); }
LitecoinURI { @Override public String toString() { StringBuilder builder = new StringBuilder("LitecoinURI["); boolean first = true; for (Map.Entry<String, Object> entry : parameterMap.entrySet()) { if (first) { first = false; } else { builder.append(","); } builder.append("'").append(entry.getKey()).append("'=").append("'").append(entry.getValue().toString()).append("'"); } builder.append("]"); return builder.toString(); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); static final String FIELD_MESSAGE; static final String FIELD_LABEL; static final String FIELD_AMOUNT; static final String FIELD_ADDRESS; static final String LITECOIN_SCHEME; }
@Test public void testGood_Combinations() throws LitecoinURIParseException { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?amount=9876543210&label=Hello%20World&message=Be%20well"); assertEquals( "LitecoinURI['address'='LQz2pJYaeqntA9BFB8rDX5AL2TTKGd5AuN','amount'='987654321000000000','label'='Hello World','message'='Be well']", testObject.toString()); }
CloudNoticeDAO { public List<Recipient> getRecipients() { return mapper.scan(Recipient.class, new DynamoDBScanExpression()); } CloudNoticeDAO(boolean local); List<Recipient> getRecipients(); void saveRecipient(Recipient recip); void deleteRecipient(Recipient recip); void shutdown(); static final String TABLE_NAME; }
@Test public void getRecipients() { dao.getRecipients(); }
DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); }
@Test public void nowWithoutSpacesAndTime() { Queue<Token> words = parser.parse("now+03:04"); Assert.assertTrue(words.poll() instanceof TimeToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof TimeToken); } @Test public void nowWithoutSpacesAndUnitOfMeasure() { Queue<Token> tokens = parser.parse("now+3h4m"); Assert.assertEquals(tokens.size(), 6); Assert.assertTrue(tokens.poll() instanceof TimeToken); Assert.assertTrue(tokens.poll() instanceof OperatorToken); Assert.assertTrue(tokens.poll() instanceof IntegerToken); Assert.assertTrue(tokens.poll() instanceof UnitOfMeasureToken); Assert.assertTrue(tokens.poll() instanceof IntegerToken); Assert.assertTrue(tokens.poll() instanceof UnitOfMeasureToken); } @Test public void timeAdditionWithSpaces() { Queue<Token> words = parser.parse("12:37 + 0:42"); Assert.assertTrue(words.poll() instanceof TimeToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof TimeToken); } @Test public void timeAdditionWithoutSpaces() { Queue<Token> words = parser.parse("12:37+0:42"); Assert.assertTrue(words.poll() instanceof TimeToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof TimeToken); } @Test public void dateMathWithSpaces() { Queue<Token> words = parser.parse("2016/09/27 - 3 months"); Assert.assertTrue(words.poll() instanceof DateToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof IntegerToken); Assert.assertTrue(words.poll() instanceof UnitOfMeasureToken); } @Test public void dateDiffWithoutSpaces() { Queue<Token> words = parser.parse("2016/12/25-2016/07/04"); Assert.assertTrue(words.poll() instanceof DateToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof DateToken); } @Test public void dateMinusDuration() { Queue<Token> tokens = parser.parse("2016/09/27 - 3 months"); Assert.assertEquals(tokens.size(), 4); Assert.assertTrue(tokens.poll() instanceof DateToken); Assert.assertTrue(tokens.poll() instanceof OperatorToken); Assert.assertTrue(tokens.poll() instanceof IntegerToken); Assert.assertTrue(tokens.poll() instanceof UnitOfMeasureToken); } @Test public void dateMinusDate() { Queue<Token> tokens = parser.parse("2016/12/25-2016/07/04"); Assert.assertEquals(tokens.size(), 3); Assert.assertTrue(tokens.poll() instanceof DateToken); Assert.assertTrue(tokens.poll() instanceof OperatorToken); Assert.assertTrue(tokens.poll() instanceof DateToken); } @Test public void dateMinusDateWithSpaces() { Queue<Token> tokens = parser.parse("2016/12/25 - 2016/07/04"); Assert.assertEquals(tokens.size(), 3); Assert.assertTrue(tokens.poll() instanceof DateToken); Assert.assertTrue(tokens.poll() instanceof OperatorToken); Assert.assertTrue(tokens.poll() instanceof DateToken); } @Test public void dateMinusDateWithInvalidOperator() { try { Queue<Token> tokens = parser.parse("2016/12/25 * 2016/07/04"); Assert.fail("A DateCalcException should have been thrown for an illegal character"); } catch (DateCalcException dce) { } } @Test public void timePlusDuration() { Queue<Token> tokens = parser.parse("12:37+42m"); Assert.assertEquals(tokens.size(), 4); Assert.assertTrue(tokens.poll() instanceof TimeToken); Assert.assertTrue(tokens.poll() instanceof OperatorToken); Assert.assertTrue(tokens.poll() instanceof IntegerToken); Assert.assertTrue(tokens.poll() instanceof UnitOfMeasureToken); } @Test public void timePlusDurationWithSpaces() { Queue<Token> tokens = parser.parse("12:37 + 42 m"); Assert.assertEquals(tokens.size(), 4); Assert.assertTrue(tokens.poll() instanceof TimeToken); Assert.assertTrue(tokens.poll() instanceof OperatorToken); Assert.assertTrue(tokens.poll() instanceof IntegerToken); Assert.assertTrue(tokens.poll() instanceof UnitOfMeasureToken); } @Test public void invalidStringsShouldFail() { try { parser.parse("2016/12/25 this is nonsense"); Assert.fail("A DateCalcException should have been thrown (Unable to identify token)"); } catch (DateCalcException dce) { } } @Test public void testWithAm() { Queue<Token> words = parser.parse("12:37am"); Assert.assertEquals(words.size(), 1); Assert.assertTrue(words.poll() instanceof TimeToken); } @Test public void testTimeDiffWithAm() { Queue<Token> words = parser.parse("12:37am-5:00am"); Assert.assertEquals(words.size(), 3); Assert.assertTrue(words.poll() instanceof TimeToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof TimeToken); } @Test(expectedExceptions = {DateCalcException.class}) public void shouldRejectBadTimes() { parser.parse("22:89"); } @Test public void paddedWithSpaces() { parser.parse(" now + 15 weeks "); } @Test public void todayWithSpaces() { Queue<Token> words = parser.parse("today + 2 weeks"); Assert.assertTrue(words.poll() instanceof DateToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof IntegerToken); Assert.assertTrue(words.poll() instanceof UnitOfMeasureToken); } @Test public void todayWithoutSpaces() { Queue<Token> words = parser.parse("today+2w"); Assert.assertTrue(words.poll() instanceof DateToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof IntegerToken); Assert.assertTrue(words.poll() instanceof UnitOfMeasureToken); } @Test public void nowWithSpacesAndTime() { Queue<Token> words = parser.parse("now + 03:04"); Assert.assertTrue(words.poll() instanceof TimeToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof TimeToken); } @Test public void nowWithSpacesAndUnitOfMeasure() { Queue<Token> tokens = parser.parse("now + 3h4m"); Assert.assertEquals(tokens.size(), 6); Assert.assertTrue(tokens.poll() instanceof TimeToken); Assert.assertTrue(tokens.poll() instanceof OperatorToken); Assert.assertTrue(tokens.poll() instanceof IntegerToken); Assert.assertTrue(tokens.poll() instanceof UnitOfMeasureToken); Assert.assertTrue(tokens.poll() instanceof IntegerToken); Assert.assertTrue(tokens.poll() instanceof UnitOfMeasureToken); }
CloudNoticeDAO { public void deleteRecipient(Recipient recip) { mapper.delete(recip); } CloudNoticeDAO(boolean local); List<Recipient> getRecipients(); void saveRecipient(Recipient recip); void deleteRecipient(Recipient recip); void shutdown(); static final String TABLE_NAME; }
@Test public void deleteRecipient() { Recipient recip = new Recipient("SMS", "[email protected]"); dao.saveRecipient(recip); Assert.assertEquals(1, dao.getRecipients().size()); dao.deleteRecipient(recip); Assert.assertEquals(0, dao.getRecipients().size()); }
DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } DateCalculatorResult calculate(String text); }
@Test public void testDateMath() { final String expression = "today + 2 weeks 3 days"; DateCalculatorResult result = dc.calculate(expression); Assert.assertNotNull(result.getDate().get(), "'" + expression + "' should have returned a result."); } @Test public void testDateDiff() { final String expression = "2016/07/04 - 1776/07/04"; DateCalculatorResult result = dc.calculate(expression); Assert.assertEquals(result.getPeriod().get(), Period.of(240,0,0), "'" + expression + "' should..."); } @Test public void timeMath() { final String expression = "12:37 + 42 m"; DateCalculatorResult result = dc.calculate(expression); Assert.assertEquals(result.getTime().get(), LocalTime.parse("13:19")); } @Test public void timeDiff() { final String expression = "12:37 - 7:15"; DateCalculatorResult result = dc.calculate(expression); Assert.assertEquals(result.getDuration().get().toHoursPart(), 5); Assert.assertEquals(result.getDuration().get().toMinutesPart(), 22); }
Book { public void addAuthor(Author author) { authors.add(createAuthorRef(author)); } void addAuthor(Author author); }
@Test public void booksAndAuthors() { Author author = new Author(); author.name = "Greg L. Turnquist"; author = authorRepo.save(author); Book book = new Book(); book.title = "Spring Boot"; book.addAuthor(author); bookRepo.save(book); bookRepo.deleteAll(); assertThat(authorRepo.count()).isEqualTo(1); }
EnumeratedBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.ENUMERATED; return context.getType().optimize( context.getScope(), IntegerBerDecoder.readInteger( context.getReader(), context.getLength() ) ); } @Override Value decode( @NotNull ReaderContext context ); }
@Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new EnumeratedBerDecoder().decode( new ReaderContext( reader, scope, type, tag, -1, false ) ); fail( "Must fail" ); } }
AbstractSyntaxObjectRef implements Ref<Value> { @Override public Value resolve( Scope scope ) throws ResolutionException { Type type = scope.getTypeOrDie(); while( type != null && !( type instanceof ClassType ) ) type = type.hasSibling() ? type.getSibling() : null; if( type == null ) throw new ResolutionException( "Unable to find ClassType" ); Module module = scope.getModule(); ModuleResolver resolver = module.getModuleResolver(); assert resolver != null; ClassType classType = (ClassType)type; try { AbstractSyntaxParser parser = new AbstractSyntaxParser( module, classType ); Map<String, Ref<?>> result = parser.parse( abstractSyntax ); return new ObjectValue( result ); } catch( AbstractSyntaxParserException e ) { throw new ResolutionException( "Unable to unwrap abstract syntax: " + abstractSyntax, e ); } } AbstractSyntaxObjectRef( String abstractSyntax ); @Override Value resolve( Scope scope ); }
@Test( expected = ResolutionException.class ) public void testParserOptionalFail() throws Exception { ModuleImpl module = ModuleImpl.newDummy( new ModuleSet() ); ClassTypeImpl classType = new ClassTypeImpl(); classType.setSyntaxList( Arrays.asList( "&Type", "IDENTIFIED", "BY", "&id", "[", "CONSTRAINED", "BY", "&TypeConstraint", "]" ) ); classType.add( new ValueFieldType( "&id", UniversalType.OBJECT_IDENTIFIER.ref(), true, false ) ); classType.add( new TypeFieldType( "&Type", false, null ) ); classType.add( new TypeFieldType( "&TypeConstraint", false, null ) ); classType.validate( module.createScope() ); Ref<Value> ref = new AbstractSyntaxObjectRef( "{ My-Module.Type-External IDENTIFIED BY { rootOid 3 } CONSTRAINED BY type-Constraint}" ); Value value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); } @Test( expected = ResolutionException.class ) public void testParserOptionalFailValue() throws Exception { ModuleImpl module = ModuleImpl.newDummy( new ModuleSet() ); ClassTypeImpl classType = new ClassTypeImpl(); classType.setSyntaxList( Arrays.asList( "&Type", "IDENTIFIED", "BY", "&id", "[", "CONSTRAINED", "BY", "&TypeConstraint", "]" ) ); classType.add( new ValueFieldType( "&id", UniversalType.OBJECT_IDENTIFIER.ref(), true, false ) ); classType.add( new TypeFieldType( "&Type", false, null ) ); classType.add( new TypeFieldType( "&TypeConstraint", false, null ) ); classType.validate( module.createScope() ); Ref<Value> ref = new AbstractSyntaxObjectRef( "{ My-Module.Type-External IDENTIFIED BY}" ); Value value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); } @Test( expected = ResolutionException.class ) public void testParserFail() throws Exception { ModuleImpl module = ModuleImpl.newDummy( new ModuleSet() ); AbstractSyntaxObjectRef ref = new AbstractSyntaxObjectRef( "{ ID &id }" ); ClassType classType = new ClassTypeImpl(); Scope scope = classType.getScope( module.createScope() ); AbstractSyntaxParser parser = PowerMockito.mock( AbstractSyntaxParser.class ); PowerMockito.whenNew( AbstractSyntaxParser.class ).withAnyArguments().thenReturn( parser ); when( parser.parse( anyString() ) ).thenThrow( new IllegalStateException() ); ref.resolve( scope ); } @Test public void testParser() throws Exception { ModuleImpl module = ModuleImpl.newDummy( new ModuleSet() ); ClassTypeImpl classType = new ClassTypeImpl(); classType.setSyntaxList( Arrays.asList( "&Type", "IDENTIFIED", "BY", "&id", "[", "CONSTRAINED", "BY", "&TypeConstraint", "]" ) ); classType.add( new ValueFieldType( "&id", UniversalType.OBJECT_IDENTIFIER.ref(), true, false ) ); classType.add( new TypeFieldType( "&Type", false, null ) ); classType.add( new TypeFieldType( "&TypeConstraint", false, null ) ); classType.validate( module.createScope() ); Ref<Value> ref = new AbstractSyntaxObjectRef( "{Super-Type IDENTIFIED BY { rootOid 3 } CONSTRAINED BY TYPE-Constraint}" ); Value value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); ref = new AbstractSyntaxObjectRef( "{OBJECT IDENTIFIER IDENTIFIED BY { rootOid 3 } }" ); value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); } @Test( expected = ResolutionException.class ) public void testNoClassType() throws Exception { AbstractSyntaxObjectRef ref = new AbstractSyntaxObjectRef( "{ ID &id }" ); ModuleImpl module = ModuleImpl.newDummy( new ModuleSet() ); DefinedTypeImpl myInt = new DefinedTypeImpl( module, "MyInt", UniversalType.INTEGER.ref() ); ref.resolve( myInt.createScope() ); } @Test( expected = ResolutionException.class ) public void testParserValueFail() throws Exception { ModuleImpl module = ModuleImpl.newDummy( new ModuleSet() ); ClassTypeImpl classType = new ClassTypeImpl(); classType.setSyntaxList( Arrays.asList( "&Type", "IDENTIFIED", "BY", "&id", "[", "CONSTRAINED", "BY", "&TypeConstraint", "]" ) ); classType.add( new ValueFieldType( "&id", UniversalType.OBJECT_IDENTIFIER.ref(), true, false ) ); classType.add( new TypeFieldType( "&Type", false, null ) ); classType.add( new TypeFieldType( "&TypeConstraint", false, null ) ); classType.validate( module.createScope() ); Ref<Value> ref = new AbstractSyntaxObjectRef( "{BIT STRING IDENTIFIED BY NAME { rootOid 3 } CONSTRAINED BY TYPE-Constraint}" ); Value value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); } @Test public void testParserValueSequence() throws Exception { ModuleImpl module = ModuleImpl.newDummy( new ModuleSet() ); ClassTypeImpl classType = new ClassTypeImpl(); classType.setSyntaxList( Arrays.asList( "&Type", "IDENTIFIED", "BY", "&id", "[", "CONSTRAINED", "BY", "&TypeConstraint", "]" ) ); classType.add( new ValueFieldType( "&id", new SequenceType( true ), true, false ) ); classType.add( new TypeFieldType( "&Type", false, null ) ); classType.add( new TypeFieldType( "&TypeConstraint", false, null ) ); classType.validate( module.createScope() ); Ref<Value> ref = new AbstractSyntaxObjectRef( "{INTEGER IDENTIFIED BY { rootOid 3, a 2 } CONSTRAINED BY TYPE-Constraint}" ); Value value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); ref = new AbstractSyntaxObjectRef( "{CHARACTER STRING IDENTIFIED BY { rootOid 3, a 2 } CONSTRAINED BY TYPE-Constraint}" ); value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); ref = new AbstractSyntaxObjectRef( "{OCTET STRING IDENTIFIED BY { rootOid 3, a 2 } CONSTRAINED BY TYPE-Constraint}" ); value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); ref = new AbstractSyntaxObjectRef( "{EMBEDDED PDV IDENTIFIED BY { rootOid 3, a 2 } CONSTRAINED BY TYPE-Constraint}" ); value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); ref = new AbstractSyntaxObjectRef( "{EMBEDDED PDV IDENTIFIED BY 1 CONSTRAINED BY TYPE-Constraint}" ); value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); ref = new AbstractSyntaxObjectRef( "{EMBEDDED PDV IDENTIFIED BY 1.0 CONSTRAINED BY TYPE-Constraint}" ); value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); ref = new AbstractSyntaxObjectRef( "{EMBEDDED PDV IDENTIFIED BY 'AF'H CONSTRAINED BY TYPE-Constraint}" ); value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); ref = new AbstractSyntaxObjectRef( "{EMBEDDED PDV IDENTIFIED BY '0101'B CONSTRAINED BY TYPE-Constraint}" ); value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); ref = new AbstractSyntaxObjectRef( "{EMBEDDED PDV IDENTIFIED BY 'Word' CONSTRAINED BY TYPE-Constraint}" ); value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); } @Test( expected = ResolutionException.class ) public void testParserFailTypeExpected() throws Exception { ModuleImpl module = ModuleImpl.newDummy( new ModuleSet() ); ClassTypeImpl classType = new ClassTypeImpl(); classType.setSyntaxList( Arrays.asList( "&Type", "IDENTIFIED", "BY", "&id", "[", "CONSTRAINED", "BY", "&TypeConstraint", "]" ) ); classType.add( new ValueFieldType( "&id", UniversalType.OBJECT_IDENTIFIER.ref(), true, false ) ); classType.add( new TypeFieldType( "&Type", false, null ) ); classType.add( new TypeFieldType( "&TypeConstraint", false, null ) ); classType.validate( module.createScope() ); Ref<Value> ref = new AbstractSyntaxObjectRef( "{1 IDENTIFIED BY { rootOid 3 } CONSTRAINED BY TYPE-Constraint}" ); Value value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); } @Test public void testParserExternalRef() throws Exception { ModuleImpl module = ModuleImpl.newDummy( new ModuleSet() ); ClassTypeImpl classType = new ClassTypeImpl(); classType.setSyntaxList( Arrays.asList( "&Type", "IDENTIFIED", "BY", "&id", "[", "CONSTRAINED", "BY", "&TypeConstraint", "]" ) ); classType.add( new ValueFieldType( "&id", UniversalType.OBJECT_IDENTIFIER.ref(), true, false ) ); classType.add( new TypeFieldType( "&Type", false, null ) ); classType.add( new TypeFieldType( "&TypeConstraint", false, null ) ); classType.validate( module.createScope() ); Ref<Value> ref = new AbstractSyntaxObjectRef( "{ My-Module.Type-External IDENTIFIED BY { rootOid 3 } CONSTRAINED BY TYPE-Constraint}" ); Value value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); }
Elements implements Constraint { public Elements( @NotNull Constraint unions, @Nullable Constraint exclusion ) { this.unions = unions; this.exclusion = exclusion; } Elements( @NotNull Constraint unions, @Nullable Constraint exclusion ); @Override void check( Scope scope, Ref<Value> valueRef ); @NotNull @Override Constraint copyForType( @NotNull Scope scope, @NotNull Type type ); @NotNull @Override Value getMinimumValue( @NotNull Scope scope ); @NotNull @Override Value getMaximumValue( @NotNull Scope scope ); @Override String toString(); @Override void setScopeOptions( Scope scope ); @Override void assertConstraintTypes( Collection<ConstraintType> allowedTypes ); @Override void collectValues( @NotNull Collection<Value> values, @NotNull Collection<Kind> requiredKinds ); }
@Test public void doTest() throws Exception { Asn1Factory factory = new DefaultAsn1Factory(); Module module = factory.types().dummyModule(); DefinedType type = factory.types().define( "MyInt", factory.types().builtin( "INTEGER" ), null ); module.validate(); ConstraintTemplate e = factory.constraints().elements( constraint, except ); boolean actual = ConstraintTestUtils.checkConstraint( e, factory.values().integer( 1 ), type, module.createScope() ); Assert.assertEquals( title + ": failed", expectedResult, actual ); }
ElementSetSpec implements Constraint { public ElementSetSpec( List<Constraint> unions ) { this.unions = new ArrayList<>( unions ); } ElementSetSpec( List<Constraint> unions ); @Override void check( Scope scope, Ref<Value> valueRef ); @NotNull @Override Value getMinimumValue( @NotNull Scope scope ); @NotNull @Override Value getMaximumValue( @NotNull Scope scope ); @Override String toString(); @NotNull @Override Constraint copyForType( @NotNull Scope scope, @NotNull Type type ); @Override void setScopeOptions( Scope scope ); @Override void assertConstraintTypes( Collection<ConstraintType> allowedTypes ); @Override void collectValues( @NotNull Collection<Value> values, @NotNull Collection<Kind> requiredKinds ); }
@Test public void doTest() { Asn1Factory factory = new DefaultAsn1Factory(); Module module = factory.types().dummyModule(); DefinedType type = factory.types().define( "MyInt", factory.types().builtin( "INTEGER" ), null ); ConstraintTemplate specs = unions == null ? factory.constraints().elementSetSpec( exclusion ) : factory.constraints().elementSetSpec( unions ); boolean actual = ConstraintTestUtils.checkConstraint( specs, factory.values().integer( 1 ), type, module.createScope() ); Assert.assertEquals( title + ": failed", expectedResult, actual ); }
TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" ) @NotNull static final Charset CHARSET; }
@Test public void testUTCParse() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withNano( 0 ).toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyMMddHHmmss" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ) + 'Z'; Instant instant = TimeUtils.parseUTCTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } @Test public void testUTCParseMinutes() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withSecond( 0 ).withNano( 0 ).toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyMMddHHmm" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ) + 'Z'; Instant instant = TimeUtils.parseUTCTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } @Test public void testUTCParseCustomTz() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withNano( 0 ).toInstant( ZoneOffset.ofHours( 4 ) ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyMMddHHmmssZ" ).withZone( ZoneId.systemDefault() ); String result = formatter.format( now ); Instant instant = TimeUtils.parseUTCTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } @Test public void testUTCParseMinutesCustomTz() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withSecond( 0 ).withNano( 0 ).toInstant( ZoneOffset.ofHours( 4 ) ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyMMddHHmmZ" ).withZone( ZoneId.systemDefault() ); String result = formatter.format( now ); Instant instant = TimeUtils.parseUTCTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); }
TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" ) @NotNull static final Charset CHARSET; }
@Test public void testGeneralizedParse() throws Exception { Instant now = Instant.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmmss.SSS" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ) + 'Z'; Instant instant = TimeUtils.parseGeneralizedTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } @Test public void testGeneralizedParseNoZ() throws Exception { Instant now = Instant.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmmss.SSS" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ); Instant instant = TimeUtils.parseGeneralizedTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } @Test public void testGeneralizedParseNoFracture() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withNano( 0 ).toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmmss" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ) + 'Z'; Instant instant = TimeUtils.parseGeneralizedTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } @Test public void testGeneralizedParseNoFractureNoSeconds() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withSecond( 0 ).withNano( 0 ).toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmm" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ) + 'Z'; Instant instant = TimeUtils.parseGeneralizedTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } @Test public void testGeneralizedParseNoFractureNoZ() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withNano( 0 ).toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmmss" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ); Instant instant = TimeUtils.parseGeneralizedTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } @Test public void testGeneralizedParseNoMinutesWithFracture() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); ldt = ldt.withMinute( 59 ).withSecond( 52 ).withNano( 800000000 ); now = ldt.toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHH" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ) + ".998Z"; Instant instant = TimeUtils.parseGeneralizedTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } @Test public void testGeneralizedParseCustomTz() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withNano( 0 ).toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmmssZ" ).withZone( ZoneId.systemDefault() ); String result = formatter.format( now ); Instant instant = TimeUtils.parseGeneralizedTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); }
NullBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) { assert context.getType().getFamily() == Family.NULL; assert context.getLength() == 0; return NullValue.INSTANCE; } @Override Value decode( @NotNull ReaderContext context ); }
@Test( expected = AssertionError.class ) public void testDecode_fail_length() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.NULL.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new NullBerDecoder().decode( new ReaderContext( reader, scope, type, tag, 1, false ) ); fail( "Must fail" ); } } @Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new NullBerDecoder().decode( new ReaderContext( reader, scope, type, tag, 0, false ) ); fail( "Must fail" ); } }
TimeUtils { @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" ) @NotNull static final Charset CHARSET; }
@Test public void testFormatInstant000() { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); ldt = ldt.withYear( 2000 ).withMonth( 1 ).withDayOfMonth( 1 ).withHour( 1 ).withMinute( 0 ).withSecond( 0 ).withNano( 0 ); now = ldt.toInstant( ZoneOffset.UTC ); String result = TimeUtils.formatInstant( now, TimeUtils.GENERALIZED_TIME_FORMAT, true ); Assert.assertEquals( "Values are not equal", "200001010100Z", result ); } @Test public void testFormatInstant00() { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); ldt = ldt.withYear( 2000 ).withMonth( 1 ).withDayOfMonth( 1 ).withHour( 1 ).withMinute( 0 ).withSecond( 0 ) .withNano( 880000000 ); now = ldt.toInstant( ZoneOffset.UTC ); String result = TimeUtils.formatInstant( now, TimeUtils.GENERALIZED_TIME_FORMAT, true ); Assert.assertEquals( "Values are not equal", "20000101010000.88Z", result ); } @Test public void testFormatInstant0() { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); ldt = ldt.withYear( 2000 ).withMonth( 1 ).withDayOfMonth( 1 ).withHour( 1 ).withMinute( 0 ).withSecond( 0 ) .withNano( 800000000 ); now = ldt.toInstant( ZoneOffset.UTC ); String result = TimeUtils.formatInstant( now, TimeUtils.GENERALIZED_TIME_FORMAT, true ); Assert.assertEquals( "Values are not equal", "20000101010000.8Z", result ); }
NRxUtils { public static String toCanonicalNR3( String value ) { if( "-Infinity".equals( value ) || "Infinity".equals( value ) || "NaN".equals( value ) ) return value; if( !FORMAT_PATTERN.matcher( value ).matches() ) throw new IllegalArgumentException(); value = value.toUpperCase(); String mantisStr; String exponentStr; int expIndex = value.indexOf( 'E' ); if( expIndex == -1 ) { mantisStr = value; exponentStr = "0"; } else { mantisStr = value.substring( 0, expIndex ).trim(); exponentStr = value.substring( expIndex + 1 ).trim(); } int scale; String actualMantis; int dotIndex = mantisStr.indexOf( '.' ); if( dotIndex == -1 ) { scale = 0; actualMantis = mantisStr; } else { scale = mantisStr.length() - dotIndex - 1; String fracture = mantisStr.substring( dotIndex + 1 ); if( isAllZeros( fracture ) ) { scale -= fracture.length(); fracture = ""; } actualMantis = mantisStr.substring( 0, dotIndex ) + fracture; } return formatInt( actualMantis ) + ".E" + formatExponent( scale, exponentStr ); } private NRxUtils(); static String toCanonicalNR3( String value ); }
@Test public void testValues() throws Exception { assertEquals( "Not equal", "1.E-1", NRxUtils.toCanonicalNR3( "0.01E1" ) ); assertEquals( "Not equal", "+0.E1", NRxUtils.toCanonicalNR3( "0.00000E1" ) ); assertEquals( "Not equal", "12312.E+0", NRxUtils.toCanonicalNR3( "12312" ) ); assertEquals( "Not equal", "12312123121231212312123121212.E-1231212312123121231212316", NRxUtils.toCanonicalNR3( "1231212312123121231212312.1212E-1231212312123121231212312" ) ); }
RefUtils { public static void assertTypeRef( String name ) { if( !isTypeRef( name ) ) throw new IllegalArgumentException( "Not a type reference: " + name ); } private RefUtils(); static void assertTypeRef( String name ); static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ); static boolean isTypeRef( CharSequence name ); static void assertValueRef( String name ); static boolean isValueRef( CharSequence name ); static boolean isIriValue( CharSequence value ); static void assertIriValue( String value ); static void resolutionValidate( Scope scope, Validation validation ); static Value toBasicValue( Scope scope, Ref<Value> ref ); static boolean isValueRef( @Nullable Ref<?> ref ); static boolean isTypeRef( @Nullable Ref<?> ref ); }
@Test( expected = IllegalArgumentException.class ) public void testNotTypeRef() { RefUtils.assertTypeRef( "a" ); }
DefaultBerReader extends AbstractBerReader { @SuppressWarnings( "NumericCastThatLosesPrecision" ) @Override public byte read() throws IOException { int read = is.read(); if( read != -1 ) position++; return (byte)read; } DefaultBerReader( InputStream is, ValueFactory valueFactory ); @Override int position(); @Override void skip( int amount ); @Override void skipToEoc(); @SuppressWarnings( "NumericCastThatLosesPrecision" ) @Override byte read(); @Override int read( byte[] buffer ); @Override void close(); }
@Test public void writeHugeReal() throws Exception { Asn1Factory factory = new DefaultAsn1Factory(); Module module = factory.types().dummyModule(); Scope scope = module.createScope(); ConstraintTemplate constraintTemplate = factory.constraints().valueRange( new RealValueFloat( 0.0f ), false, null, false ); Type tagged = factory.types().constrained( constraintTemplate, UniversalType.REAL.ref() ); Type defined = factory.types().define( "MyReal", tagged, null ); module.validate(); Value expected = new RealValueBig( new BigDecimal( BigInteger.valueOf( 34645 ).pow( 16663 ) ) ); byte[] result = InputUtils.writeValue( scope, defined, expected ); try( ByteArrayInputStream is = new ByteArrayInputStream( result ); AbstractBerReader reader = new DefaultBerReader( is, new CoreValueFactory() ) ) { Value value = reader.read( scope, defined ); Assert.assertEquals( "Values are not equal", expected, value ); } } @Test public void testHugeTagNumber() throws Exception { TypeFactory factory = new CoreTypeFactory(); Module module = factory.dummyModule(); Scope scope = module.createScope(); Type tagged = factory.tagged( TagEncoding.application( 2048 ), UniversalType.INTEGER.ref() ); Type defined = factory.define( "MyTagged", tagged, null ); module.validate(); Value expected = new IntegerValueInt( 0 ); byte[] result = InputUtils.writeValue( scope, defined, expected ); try( ByteArrayInputStream is = new ByteArrayInputStream( result ); AbstractBerReader reader = new DefaultBerReader( is, new CoreValueFactory() ) ) { Value value = reader.read( scope, defined ); Assert.assertEquals( "Values are not equal", expected, value ); } }
RefUtils { public static void assertValueRef( String name ) { if( !isValueRef( name ) ) throw new IllegalArgumentException( "Not a value reference: " + name ); } private RefUtils(); static void assertTypeRef( String name ); static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ); static boolean isTypeRef( CharSequence name ); static void assertValueRef( String name ); static boolean isValueRef( CharSequence name ); static boolean isIriValue( CharSequence value ); static void assertIriValue( String value ); static void resolutionValidate( Scope scope, Validation validation ); static Value toBasicValue( Scope scope, Ref<Value> ref ); static boolean isValueRef( @Nullable Ref<?> ref ); static boolean isTypeRef( @Nullable Ref<?> ref ); }
@Test( expected = IllegalArgumentException.class ) public void testNotValueRef() { RefUtils.assertValueRef( "A" ); }
RefUtils { public static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ) throws ResolutionException { if( component.getDefaultValue() == null ) return false; resolve = toBasicValue( scope, resolve ); Value value = toBasicValue( scope, component.getDefaultValue() ); return resolve.isEqualTo( value ); } private RefUtils(); static void assertTypeRef( String name ); static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ); static boolean isTypeRef( CharSequence name ); static void assertValueRef( String name ); static boolean isValueRef( CharSequence name ); static boolean isIriValue( CharSequence value ); static void assertIriValue( String value ); static void resolutionValidate( Scope scope, Validation validation ); static Value toBasicValue( Scope scope, Ref<Value> ref ); static boolean isValueRef( @Nullable Ref<?> ref ); static boolean isTypeRef( @Nullable Ref<?> ref ); }
@Test public void testSameAsDefault() throws Exception { MyIntegerValue value = new MyIntegerValue(); assertTrue( "Must be true", RefUtils.isSameAsDefaultValue( new MyScope(), new MyAbstractComponentType( value ), value ) ); }
HexUtils { @SuppressWarnings( "MagicNumber" ) public static String toHexString( byte[] array ) { if( ArrayUtils.isEmpty( array ) ) return ""; StringBuilder sb = new StringBuilder(); for( byte value : array ) { if( ( value & 0xF0 ) == 0 ) sb.append( '0' ); sb.append( Integer.toHexString( value & 0xFF ).toUpperCase() ); } return sb.toString(); } private HexUtils(); @SuppressWarnings( "MagicNumber" ) static String toHexString( byte[] array ); }
@Test public void testConversion() throws Exception { assertEquals( "Is not equal", "0A", HexUtils.toHexString( new byte[]{0x0A} ) ); assertEquals( "Is not equal", "0A0A", HexUtils.toHexString( new byte[]{0x0A, 0x0A} ) ); assertEquals( "Is not equal", "", HexUtils.toHexString( new byte[]{} ) ); }
CollectionUtils { @NotNull public static String convertToBString( Iterable<? extends Ref<Value>> valueList, int desiredSize ) { Collection<Long> values = new HashSet<>(); Long maxValue = 0L; for( Ref<Value> valueRef : valueList ) { NamedValue value = (NamedValue)valueRef; if( value.getReferenceKind() != Kind.INTEGER || !value.toIntegerValue().isLong() ) throw new IllegalStateException(); Long longValue = value.toIntegerValue().asLong(); values.add( longValue ); maxValue = Math.max( maxValue, longValue ); } if( desiredSize > -1 ) { if( maxValue > ( desiredSize - 1 ) ) throw new IllegalArgumentException( "Unable to truncate data. Desired size is smaller than expected: current = " + ( maxValue + 1 ) + " desired = " + desiredSize ); maxValue = (long)desiredSize - 1; } StringBuilder sb = new StringBuilder(); sb.append( '\'' ); for( long value = 0; value <= maxValue; value++ ) sb.append( values.contains( value ) ? '1' : '0' ); sb.append( "'B" ); return sb.toString(); } private CollectionUtils(); @NotNull static String convertToBString( Iterable<? extends Ref<Value>> valueList, int desiredSize ); }
@Test public void testConversion() throws Exception { IntegerValue value = new MyIntegerValue(); MyScope scope = new MyScope(); MyNamedValue namedValue = new MyNamedValue( (IntegerValue)RefUtils.toBasicValue( scope, value ) ); String result = CollectionUtils.convertToBString( Collections.singletonList( namedValue ), 4 ); assertEquals( "Is not equals", "'0100'B", result ); assertEquals( "Must be equal", value, RefUtils.toBasicValue( scope, namedValue ) ); }
TemplateParameter implements Comparable<TemplateParameter> { public String getName() { if( reference instanceof TypeNameRef ) return ( (TypeNameRef)reference ).getName(); if( reference instanceof ValueNameRef ) return ( (ValueNameRef)reference ).getName(); throw new IllegalStateException(); } TemplateParameter( int index, @NotNull Ref<?> reference, @Nullable Ref<Type> governor ); int getIndex(); String getName(); @SuppressWarnings( "unchecked" ) Ref<T> getReference(); @Nullable Ref<Type> getGovernor(); boolean isTypeRef(); boolean isValueRef(); @SuppressWarnings( "unchecked" ) @Override boolean equals( Object obj ); @Override int hashCode(); @Override String toString(); @Override int compareTo( @NotNull TemplateParameter o ); }
@Test( expected = IllegalStateException.class ) public void testIllegalRef() throws Exception { TemplateParameter parameter = new TemplateParameter( 0, scope -> { throw new UnsupportedOperationException(); }, null ); parameter.getName(); fail( "Must fail" ); }
Template { public Template() { this( false ); } Template(); Template( boolean instance ); void addParameter( TemplateParameter parameter ); @Nullable TemplateParameter getParameter( @NotNull String name ); @NotNull TemplateParameter getParameter( int index ); int getParameterCount(); boolean isInstance(); }
@Test public void testTemplate() throws Exception { Template template = new Template(); assertEquals( "Parameter count must be 0", 0, template.getParameterCount() ); template.addParameter( new TemplateParameter( 0, new TypeNameRef( "A" ), null ) ); assertEquals( "Parameter count must be 1", 1, template.getParameterCount() ); assertNotNull( "Must not be null", template.getParameter( 0 ) ); assertNotNull( "Must not be null", template.getParameter( "A" ) ); assertFalse( "Must not be instance", template.isInstance() ); }
Template { @Nullable public TemplateParameter getParameter( @NotNull String name ) { return parameterMap.get( name ); } Template(); Template( boolean instance ); void addParameter( TemplateParameter parameter ); @Nullable TemplateParameter getParameter( @NotNull String name ); @NotNull TemplateParameter getParameter( int index ); int getParameterCount(); boolean isInstance(); }
@Test( expected = IllegalArgumentException.class ) public void testIllegalIndexGet() throws Exception { Template template = new Template(); template.getParameter( 1 ); fail( "Must fail" ); }
EnumTypeMapperFactory implements TypeMapperFactory { @SuppressWarnings( "unchecked" ) @Override public TypeMapper mapType( Type type, TypeMetadata metadata ) { if( !isSupportedFor( type ) ) throw new IllegalArgumentException( "Only enum types allowed" ); return mapEnum( (Class<Enum<?>>)type ); } EnumTypeMapperFactory( TypeMapperContext context, Asn1Factory factory ); @Override int getPriority(); @Override boolean isSupportedFor( Type type ); @SuppressWarnings( "unchecked" ) @Override TypeMapper mapType( Type type, TypeMetadata metadata ); }
@Test( expected = IllegalArgumentException.class ) public void testDuplicateFail() throws Exception { mapperFactory.mapType( Values.class, null ); fail( "Must fail" ); } @Test( expected = IllegalArgumentException.class ) public void testUnsupportedType() throws Exception { mapperFactory.mapType( Integer.class, null ); fail( "Must fail!" ); } @Test( expected = IllegalStateException.class ) public void testNoEnumConstantsFail() throws Exception { mapperFactory.mapType( ValuesEmpty.class, null ); fail( "Must fail" ); } @Test( expected = IllegalStateException.class ) public void testIllegalIndexes() throws Exception { mapperFactory.mapType( IllegalEnum.class, null ); fail( "Must fail" ); } @Test( expected = IllegalStateException.class ) public void testIllegalIndexes2() throws Exception { mapperFactory.mapType( IllegalEnum2.class, null ); fail( "Must fail" ); }
Introspector { @NotNull public JavaType introspect( Type type ) { if( typeMap.containsKey( type.getTypeName() ) ) return typeMap.get( type.getTypeName() ); if( type instanceof Class<?> ) return forClass( (Class<?>)type ); if( type instanceof ParameterizedType ) return forParameterized( (ParameterizedType)type ); if( type instanceof TypeVariable<?> ) { JavaType javaType = new JavaType( type ); typeMap.put( type.getTypeName(), javaType ); return javaType; } throw new UnsupportedOperationException(); } @NotNull JavaType introspect( Type type ); }
@Test public void testIntrospection() throws Exception { Introspector introspector = new Introspector(); JavaType type = introspector.introspect( Element.class ); int k = 0; }
RealTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( isFloat() && isAssignableToFloat( value ) ) return factory.real( (Float)value ); if( isDouble() && isAssignableToDouble( value ) ) return factory.real( (Double)value ); if( isBigDecimal() && Objects.equals( value.getClass(), BigDecimal.class ) ) return factory.real( (BigDecimal)value ); throw new IllegalArgumentException( "Unable to convert value: " + value ); } RealTypeMapper( Class<?> realClass, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }
@Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new RealTypeMapper( double.class, REAL ); mapper.toAsn1( FACTORY, true ); fail( "Must fail" ); }
RealTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.REAL ) throw new IllegalArgumentException( "Unable to handle value of kind: " + value.getKind() ); RealValue rv = value.toRealValue(); if( isFloat() ) return rv.asFloat(); if( isDouble() ) return rv.asDouble(); if( isBigDecimal() ) return rv.asBigDecimal(); throw new UnsupportedOperationException(); } RealTypeMapper( Class<?> realClass, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }
@Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new RealTypeMapper( double.class, REAL ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); }
StringTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( !javaType.isAssignableFrom( value.getClass() ) ) throw new IllegalArgumentException( "Unable to convert value: " + value ); return factory.cString( (String)value ); } StringTypeMapper( Class<?> javaType, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }
@Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new StringTypeMapper( String.class, UTF8_STRING ); mapper.toAsn1( FACTORY, 1L ); fail( "Must fail" ); }
StringTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.C_STRING ) throw new IllegalArgumentException( "Unable to convert value of kind: " + value.getKind() ); return value.toStringValue().asString(); } StringTypeMapper( Class<?> javaType, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }
@Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new StringTypeMapper( String.class, UTF8_STRING ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); }
IntegerTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( isByte() && isAssignableToByte( value ) ) return factory.integer( (Byte)value ); if( isShort() && isAssignableToShort( value ) ) return factory.integer( (Short)value ); if( isInteger() && isAssignableToInt( value ) ) return factory.integer( (Integer)value ); if( isLong() && isAssignableToLong( value ) ) return factory.integer( (Long)value ); if( isBigInteger() && Objects.equals( value.getClass(), BigInteger.class ) ) return factory.integer( (BigInteger)value ); throw new IllegalArgumentException( "Unable to convert value: " + value ); } IntegerTypeMapper( Class<?> integerClass, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }
@Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new IntegerTypeMapper( Long.class, INTEGER ); mapper.toAsn1( FACTORY, true ); fail( "Must fail" ); }
IntegerTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.INTEGER ) throw new IllegalArgumentException( "Unable to convert to integer value of kind: " + value.getKind() ); IntegerValue iv = value.toIntegerValue(); if( isByte() ) return (byte)iv.asInt(); if( isShort() ) return (short)iv.asInt(); if( isInteger() ) return iv.asInt(); if( isLong() ) return iv.asLong(); if( isBigInteger() ) return iv.asBigInteger(); throw new UnsupportedOperationException(); } IntegerTypeMapper( Class<?> integerClass, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }
@Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new IntegerTypeMapper( Long.class, INTEGER ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); }
ByteArrayTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( !byte[].class.isAssignableFrom( value.getClass() ) ) throw new IllegalArgumentException( "Unable to convert value: " + value ); byte[] array = (byte[])value; return factory.byteArrayValue( array.length * 8, array ); } ByteArrayTypeMapper( Class<?> javaType, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }
@Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new ByteArrayTypeMapper( byte[].class, OCTET_STRING ); mapper.toAsn1( FACTORY, 1L ); fail( "Must fail" ); }
BitStringBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.BIT_STRING; assert !context.getTag().isConstructed(); if( context.getLength() == 0 ) return context.getValueFactory().emptyByteArray(); byte unusedBits = context.read(); if( unusedBits < 0 || unusedBits > 7 ) throw new IllegalValueException( "Unused bits must be in range: [0,7]" ); if( context.getLength() == -1 ) return OctetStringBerDecoder.readByteArrayValueIndefinite( context.getReader(), unusedBits ); return OctetStringBerDecoder.readByteArrayValue( context.getReader(), context.getLength() - 1, unusedBits ); } @Override Value decode( @NotNull ReaderContext context ); }
@Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new BitStringBerDecoder().decode( new ReaderContext( reader, scope, type, tag, -1, false ) ); fail( "Must fail" ); } }
ByteArrayTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.BYTE_ARRAY ) throw new IllegalArgumentException( "Unable to handle value of kind: " + value.getKind() ); return value.toByteArrayValue().asByteArray(); } ByteArrayTypeMapper( Class<?> javaType, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }
@Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new ByteArrayTypeMapper( byte[].class, OCTET_STRING ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); }
DateTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( !javaType.isAssignableFrom( value.getClass() ) ) throw new IllegalArgumentException( "Unable to convert value: " + value ); if( isDate() ) return factory.timeValue( ( (Date)value ).toInstant() ); if( isInstant() ) return factory.timeValue( (Instant)value ); throw new UnsupportedOperationException(); } DateTypeMapper( Class<?> javaType, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }
@Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new DateTypeMapper( Instant.class, G_TIME ); mapper.toAsn1( FACTORY, 1L ); fail( "Must fail" ); }
DateTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.TIME ) throw new IllegalArgumentException( "Unable to convert values of kind: " + value.getKind() ); Instant instant = value.toDateValue().asInstant(); if( isInstant() ) return instant; if( isDate() ) return Date.from( instant ); throw new UnsupportedOperationException(); } DateTypeMapper( Class<?> javaType, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }
@Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new DateTypeMapper( Instant.class, G_TIME ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); }
BooleanTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( !isBooleanClass( value ) ) throw new IllegalArgumentException( "Unable to convert value: " + value ); if( Boolean.TRUE.equals( value ) ) return BooleanValue.TRUE; if( Boolean.FALSE.equals( value ) ) return BooleanValue.FALSE; throw new UnsupportedOperationException(); } BooleanTypeMapper( Class<?> booleanClass, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }
@Test public void toAsn1() throws Exception { BooleanTypeMapper mapper = new BooleanTypeMapper( boolean.class, BOOLEAN ); assertEquals( "Not equals", BooleanValue.TRUE, mapper.toAsn1( FACTORY, true ) ); assertEquals( "Not equals", BooleanValue.FALSE, mapper.toAsn1( FACTORY, false ) ); } @Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { BooleanTypeMapper mapper = new BooleanTypeMapper( boolean.class, BOOLEAN ); mapper.toAsn1( FACTORY, 1L ); fail( "Must fail" ); }
BooleanTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.BOOLEAN ) throw new IllegalArgumentException( "Unable to handle value of kind: " + value.getKind() ); if( Objects.equals( value, BooleanValue.TRUE ) ) return Boolean.TRUE; if( Objects.equals( value, BooleanValue.FALSE ) ) return Boolean.FALSE; throw new UnsupportedOperationException(); } BooleanTypeMapper( Class<?> booleanClass, NamedType asnType ); @Override Type getJavaType(); @Override NamedType getAsn1Type(); @NotNull @Override Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ); @NotNull @Override Object toJava( @NotNull Value value ); }
@Test public void toJava() throws Exception { BooleanTypeMapper mapper = new BooleanTypeMapper( boolean.class, BOOLEAN ); assertEquals( "Not equals", Boolean.TRUE, mapper.toJava( BooleanValue.TRUE ) ); assertEquals( "Not equals", Boolean.FALSE, mapper.toJava( BooleanValue.FALSE ) ); } @Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { BooleanTypeMapper mapper = new BooleanTypeMapper( boolean.class, BOOLEAN ); mapper.toJava( FACTORY.integer( 1 ) ); fail( "Must fail" ); }
GeneralizedTimeBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.GENERALIZED_TIME; assert context.getValue().getKind() == Kind.TIME; Instant instant = context.getValue().toDateValue().asInstant(); boolean optimize = context.getRules() != BerRules.DER; String content = TimeUtils.formatInstant( instant, TimeUtils.GENERALIZED_TIME_FORMAT, optimize ); byte[] bytes = content.getBytes( TimeUtils.CHARSET ); context.writeHeader( TAG, bytes.length ); context.write( bytes ); } @Override void encode( @NotNull WriterContext context ); }
@Test public void testWrite_Der() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.GENERALIZED_TIME.ref().resolve( scope ); Value value = new DateValueImpl( TimeUtils.parseGeneralizedTime( TIME_VALUE ) ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.getRules() ).thenReturn( BerRules.DER ); new GeneralizedTimeBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).getRules(); verify( writer ).writeHeader( TAG, 15 ); verify( writer ).write( new byte[]{0x32, 0x30, 0x31, 0x37, 0x30, 0x36, 0x30, 0x31, 0x31, 0x31, 0x35, 0x37, 0x30, 0x30, 0x5A} ); verifyNoMoreInteractions( writer ); } } @Test public void testWrite_Ber() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.GENERALIZED_TIME.ref().resolve( scope ); Value value = new DateValueImpl( TimeUtils.parseGeneralizedTime( TIME_VALUE ) ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.getRules() ).thenReturn( BerRules.BER ); new GeneralizedTimeBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).getRules(); verify( writer ).writeHeader( TAG, 13 ); verify( writer ).write( new byte[]{0x32, 0x30, 0x31, 0x37, 0x30, 0x36, 0x30, 0x31, 0x31, 0x31, 0x35, 0x37, 0x5A} ); verifyNoMoreInteractions( writer ); } } @Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = new DateValueImpl( TimeUtils.parseGeneralizedTime( TIME_VALUE ) ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new GeneralizedTimeBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } @Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.GENERALIZED_TIME.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new GeneralizedTimeBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } }
StringBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.RESTRICTED_STRING; assert context.getValue().getKind() == Kind.C_STRING; Type type = context.getType(); while( !( type instanceof StringType ) ) { assert type != null; type = type.getSibling(); } Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); byte[] bytes = context.getValue().toStringValue().asString().getBytes( ( (StringType)type ).getCharset() ); context.writeHeader( tag, bytes.length ); context.write( bytes ); } @Override void encode( @NotNull WriterContext context ); }
@Test public void testEncode_0() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.UTF8_STRING.ref().resolve( scope ); Value value = new StringValueImpl( "A" ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new StringBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 1 ); verify( writer ).write( new byte[]{65} ); verifyNoMoreInteractions( writer ); } } @Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = new StringValueImpl( "Value" ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new StringBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } @Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.UTF8_STRING.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new StringBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } }
ObjectIDBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.OID; assert context.getLength() > 0; List<Ref<Value>> list = new ArrayList<>(); int length = context.getLength(); while( length > 0 ) length = readObjectIDItem( context.getReader(), length, list ); ObjectIdentifierValue objectIdentifierValue = context.getValueFactory().objectIdentifier( list ); return context.getType().optimize( context.getScope(), objectIdentifierValue ); } @Override Value decode( @NotNull ReaderContext context ); }
@Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new ObjectIDBerDecoder().decode( new ReaderContext( reader, scope, type, tag, -1, false ) ); fail( "Must fail" ); } }
SequenceOfBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.SEQUENCE_OF; assert context.getValue().getKind() == Kind.COLLECTION || context.getValue().getKind() == Kind.NAMED_COLLECTION; if( !context.isWriteHeader() ) writeCollection( context ); else if( context.isBufferingAvailable() ) { context.startBuffer( -1 ); writeCollection( context ); context.stopBuffer( SequenceBerEncoder.TAG ); } else if( context.getRules() == BerRules.DER ) throw new Asn1Exception( "Buffering is required for DER rules" ); else { context.writeHeader( SequenceBerEncoder.TAG, -1 ); writeCollection( context ); context.write( 0 ); context.write( 0 ); } } @Override void encode( @NotNull WriterContext context ); }
@Test public void testWriteSequenceOf_Buffered() throws Exception { Scope scope = CoreModule.getInstance().createScope(); SequenceOfType type = new SequenceOfType(); type.setComponent( "a", UniversalType.INTEGER.ref() ); type.validate( scope ); ComponentType component = type.getComponentType(); Assert.assertNotNull( "No component a", component ); ValueCollection value = new ValueCollectionImpl( false ); Value valueInt = new IntegerValueInt( 0 ); value.add( valueInt ); try( AbstractBerWriter writer = new DefaultBerWriter( BerRules.DER ) ) { new SequenceOfBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); byte[] bytes = writer.toByteArray(); Assert.assertArrayEquals( "Arrays are not equal", new byte[]{0x30, 0x03, 0x02, 0x01, 0x00}, bytes ); } } @Test public void testWriteSequenceOf_NonBuffered() throws Exception { Scope scope = CoreModule.getInstance().createScope(); SequenceOfType type = new SequenceOfType(); type.setComponent( "a", UniversalType.INTEGER.ref() ); type.validate( scope ); ComponentType component = type.getComponentType(); Assert.assertNotNull( "No component a", component ); ValueCollection value = new ValueCollectionImpl( false ); Value valueInt = new IntegerValueInt( 0 ); value.add( valueInt ); try( AbstractBerWriter writer = new DefaultBerWriter( BerRules.BER ) ) { new SequenceOfBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) { @Override public boolean isBufferingAvailable() { return false; } } ); byte[] bytes = writer.toByteArray(); Assert.assertArrayEquals( "Arrays are not equal", new byte[]{0x30, (byte)0x80, 0x02, 0x01, 0x00, 0x00, 0x00}, bytes ); } } @Test( expected = Asn1Exception.class ) public void testWriteSequenceOf_NonBuffered_Der() throws Exception { Scope scope = CoreModule.getInstance().createScope(); SequenceOfType type = new SequenceOfType(); type.setComponent( "a", UniversalType.INTEGER.ref() ); type.validate( scope ); ComponentType component = type.getComponentType(); Assert.assertNotNull( "No component a", component ); ValueCollection value = new ValueCollectionImpl( false ); Value valueInt = new IntegerValueInt( 0 ); value.add( valueInt ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.isBufferingAvailable() ).thenReturn( false ); when( writer.getRules() ).thenReturn( BerRules.DER ); new SequenceOfBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); fail( "Must fail" ); } } @Test public void testWriteSequenceOf_NoHeader() throws Exception { Scope scope = CoreModule.getInstance().createScope(); SequenceOfType type = new SequenceOfType(); type.setComponent( "a", UniversalType.INTEGER.ref() ); type.validate( scope ); ComponentType component = type.getComponentType(); Assert.assertNotNull( "No component a", component ); ValueCollection value = new ValueCollectionImpl( false ); Value valueInt = new IntegerValueInt( 0 ); value.add( valueInt ); try( AbstractBerWriter writer = new DefaultBerWriter( BerRules.DER ) ) { new SequenceOfBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); byte[] bytes = writer.toByteArray(); Assert.assertArrayEquals( "Arrays are not equal", new byte[]{0x02, 0x01, 0x00}, bytes ); } } @Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = new ValueCollectionImpl( true ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new SequenceOfBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } @Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = new SequenceOfType(); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new SequenceOfBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } }
BitStringBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException { assert context.getType().getFamily() == Family.BIT_STRING; assert context.getValue().getKind() == Kind.BYTE_ARRAY; ByteArrayValue arrayValue = context.getValue().toByteArrayValue(); boolean hasNamedValues = !context.getType().getNamedValues().isEmpty(); byte[] bytes = arrayValue.asByteArray(); int usedBits = arrayValue.getUsedBits(); int emptyBits = bytes.length * 8 - usedBits; if( context.getRules() == BerRules.DER ) { boolean hasSizeConstraint = Boolean.TRUE.equals( context.getScope().getScopeOption( ConstraintUtils.OPTION_HAS_SIZE_CONSTRAINT ) ); if( !hasSizeConstraint && hasNamedValues ) { if( hasEmptyBytesAtEnd( bytes ) ) bytes = removeZerosFromEnd( bytes ); if( bytes.length > 0 ) emptyBits = getTrailingZerosCount( bytes[bytes.length - 1] ); } } int length = bytes.length == 0 ? 1 : 1 + bytes.length; context.writeHeader( TAG, length ); if( length > 1 ) { context.write( emptyBits ); context.write( bytes ); } else context.write( 0 ); } @Override void encode( @NotNull WriterContext context ); }
@Test public void testWrite_0101_Der() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BIT_STRING.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromBitString( VALUE_0101B ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.getRules() ).thenReturn( BerRules.DER ); new BitStringBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).getRules(); verify( writer ).writeHeader( TAG, 2 ); verify( writer ).write( 4 ); verify( writer ).write( new byte[]{0x50} ); verifyNoMoreInteractions( writer ); } } @Test public void testWrite_0101_Ber() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BIT_STRING.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromBitString( VALUE_0101B ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.getRules() ).thenReturn( BerRules.BER ); new BitStringBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).getRules(); verify( writer ).writeHeader( TAG, 2 ); verify( writer ).write( 4 ); verify( writer ).write( new byte[]{0x50} ); verifyNoMoreInteractions( writer ); } } @Test public void testWrite_01010000000000_Der_noNamed() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BIT_STRING.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromBitString( VALUE_01010000000000B ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.getRules() ).thenReturn( BerRules.DER ); new BitStringBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).getRules(); verify( writer ).writeHeader( TAG, 3 ); verify( writer ).write( 2 ); verify( writer ).write( new byte[]{0x50, 0x0} ); verifyNoMoreInteractions( writer ); } } @Test public void testWrite_01010000000000_Der_hasNamed() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = new BitStringType( Arrays.asList( new NamedValueImpl( "a", new IntegerValueInt( 1 ) ), new NamedValueImpl( "b", new IntegerValueInt( 2 ) ), new NamedValueImpl( "c", new IntegerValueInt( 3 ) ), new NamedValueImpl( "d", new IntegerValueInt( 4 ) ) ) ); type.validate( scope ); Value value = CoreUtils.byteArrayFromBitString( VALUE_01010000000000B ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.getRules() ).thenReturn( BerRules.DER ); new BitStringBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).getRules(); verify( writer ).writeHeader( TAG, 2 ); verify( writer ).write( 4 ); verify( writer ).write( new byte[]{0x50} ); verifyNoMoreInteractions( writer ); } } @Test public void testWrite_0000_Der_hasNamed() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = new BitStringType( Arrays.asList( new NamedValueImpl( "a", new IntegerValueInt( 1 ) ), new NamedValueImpl( "b", new IntegerValueInt( 2 ) ), new NamedValueImpl( "c", new IntegerValueInt( 3 ) ), new NamedValueImpl( "d", new IntegerValueInt( 4 ) ) ) ); type.validate( scope ); Value value = CoreUtils.byteArrayFromBitString( VALUE_0000B ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.getRules() ).thenReturn( BerRules.DER ); new BitStringBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).getRules(); verify( writer ).writeHeader( TAG, 2 ); verify( writer ).write( 1 ); verify( writer ).write( new byte[]{0x0} ); verifyNoMoreInteractions( writer ); } } @Test public void testWrite_0000_Ber() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BIT_STRING.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromBitString( VALUE_0000B ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.getRules() ).thenReturn( BerRules.BER ); new BitStringBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).getRules(); verify( writer ).writeHeader( TAG, 2 ); verify( writer ).write( 4 ); verify( writer ).write( new byte[]{0x0} ); verifyNoMoreInteractions( writer ); } } @Test public void testWrite_Empty_Ber() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BIT_STRING.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromBitString( "''B" ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.getRules() ).thenReturn( BerRules.BER ); new BitStringBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).getRules(); verify( writer ).writeHeader( TAG, 1 ); verify( writer ).write( 0 ); verifyNoMoreInteractions( writer ); } } @Test public void testWrite_01010000000000_Ber() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BIT_STRING.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromBitString( VALUE_01010000000000B ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.getRules() ).thenReturn( BerRules.BER ); new BitStringBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).getRules(); verify( writer ).writeHeader( TAG, 3 ); verify( writer ).write( 2 ); verify( writer ).write( new byte[]{0x50, 0x0} ); verifyNoMoreInteractions( writer ); } } @Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromBitString( VALUE_0101B ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new BitStringBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } @Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BIT_STRING.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new BitStringBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } }
BooleanBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException { assert context.getType().getFamily() == Family.BOOLEAN; assert context.getLength() == 1; byte content = context.read(); return content == BerUtils.BOOLEAN_FALSE ? BooleanValue.FALSE : BooleanValue.TRUE; } @Override Value decode( @NotNull ReaderContext context ); }
@Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new BooleanBerDecoder().decode( new ReaderContext( reader, scope, type, tag, 1, false ) ); fail( "Must fail" ); } } @Test( expected = AssertionError.class ) public void testDecode_fail_length() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BOOLEAN.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new BooleanBerDecoder().decode( new ReaderContext( reader, scope, type, tag, 2, false ) ); fail( "Must fail" ); } }
BooleanBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException { assert context.getType().getFamily() == Family.BOOLEAN; assert context.getValue().getKind() == Kind.BOOLEAN; context.writeHeader( TAG, 1 ); boolean value = context.getValue().toBooleanValue().asBoolean(); context.write( value ? BerUtils.BOOLEAN_TRUE : BerUtils.BOOLEAN_FALSE ); } @Override void encode( @NotNull WriterContext context ); }
@Test public void testEncode_true() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BOOLEAN.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new BooleanBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 1 ); verify( writer ).write( BerUtils.BOOLEAN_TRUE ); verifyNoMoreInteractions( writer ); } } @Test public void testEncode_false() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BOOLEAN.ref().resolve( scope ); Value value = BooleanValue.FALSE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new BooleanBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 1 ); verify( writer ).write( BerUtils.BOOLEAN_FALSE ); verifyNoMoreInteractions( writer ); } } @Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new BooleanBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } @Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BOOLEAN.ref().resolve( scope ); Value value = NullValue.INSTANCE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new BooleanBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } }
SetOfBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.SET_OF; assert context.getValue().getKind() == Kind.COLLECTION || context.getValue().getKind() == Kind.NAMED_COLLECTION; if( !context.isWriteHeader() ) SequenceOfBerEncoder.writeCollection( context ); else if( context.isBufferingAvailable() ) { context.startBuffer( -1 ); SequenceOfBerEncoder.writeCollection( context ); context.stopBuffer( SetBerEncoder.TAG ); } else if( context.getRules() == BerRules.DER ) throw new Asn1Exception( "Buffering is required for DER rules" ); else { context.writeHeader( SetBerEncoder.TAG, -1 ); SequenceOfBerEncoder.writeCollection( context ); context.write( 0 ); context.write( 0 ); } } @Override void encode( @NotNull WriterContext context ); }
@Test public void testWriteSetOf_Buffered() throws Exception { Scope scope = CoreModule.getInstance().createScope(); SetOfType type = new SetOfType(); type.setComponent( "a", UniversalType.INTEGER.ref() ); type.validate( scope ); ComponentType component = type.getComponentType(); Assert.assertNotNull( "No component a", component ); ValueCollection value = new ValueCollectionImpl( false ); Value valueInt = new IntegerValueInt( 0 ); value.add( valueInt ); try( AbstractBerWriter writer = new DefaultBerWriter( BerRules.DER ) ) { new SetOfBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); byte[] bytes = writer.toByteArray(); Assert.assertArrayEquals( "Arrays are not equal", new byte[]{0x31, 0x03, 0x02, 0x01, 0x00}, bytes ); } } @Test public void testWriteSetOf_NonBuffered() throws Exception { Scope scope = CoreModule.getInstance().createScope(); SetOfType type = new SetOfType(); type.setComponent( "a", UniversalType.INTEGER.ref() ); type.validate( scope ); ComponentType component = type.getComponentType(); Assert.assertNotNull( "No component a", component ); ValueCollection value = new ValueCollectionImpl( false ); Value valueInt = new IntegerValueInt( 0 ); value.add( valueInt ); try( AbstractBerWriter writer = new DefaultBerWriter( BerRules.BER ) ) { new SetOfBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) { @Override public boolean isBufferingAvailable() { return false; } } ); byte[] bytes = writer.toByteArray(); Assert.assertArrayEquals( "Arrays are not equal", new byte[]{0x31, (byte)0x80, 0x02, 0x01, 0x00, 0x00, 0x00}, bytes ); } } @Test( expected = Asn1Exception.class ) public void testWriteSetOf_NonBuffered_Der() throws Exception { Scope scope = CoreModule.getInstance().createScope(); SetOfType type = new SetOfType(); type.setComponent( "a", UniversalType.INTEGER.ref() ); type.validate( scope ); ComponentType component = type.getComponentType(); Assert.assertNotNull( "No component a", component ); ValueCollection value = new ValueCollectionImpl( false ); Value valueInt = new IntegerValueInt( 0 ); value.add( valueInt ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.isBufferingAvailable() ).thenReturn( false ); when( writer.getRules() ).thenReturn( BerRules.DER ); new SetOfBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); fail( "Must fail" ); } } @Test public void testWriteSetOf_NoHeader() throws Exception { Scope scope = CoreModule.getInstance().createScope(); SetOfType type = new SetOfType(); type.setComponent( "a", UniversalType.INTEGER.ref() ); type.validate( scope ); ComponentType component = type.getComponentType(); Assert.assertNotNull( "No component a", component ); ValueCollection value = new ValueCollectionImpl( false ); Value valueInt = new IntegerValueInt( 0 ); value.add( valueInt ); try( AbstractBerWriter writer = new DefaultBerWriter( BerRules.DER ) ) { new SetOfBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); byte[] bytes = writer.toByteArray(); Assert.assertArrayEquals( "Arrays are not equal", new byte[]{0x02, 0x01, 0x00}, bytes ); } } @Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = new ValueCollectionImpl( true ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new SetOfBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } @Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = new SetOfType(); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new SetOfBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } }
OctetStringBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException { assert context.getType().getFamily() == Family.OCTET_STRING; assert context.getValue().getKind() == Kind.BYTE_ARRAY; byte[] bytes = context.getValue().toByteArrayValue().asByteArray(); int length = bytes == null ? 0 : bytes.length; context.writeHeader( TAG, length ); context.write( bytes ); } @Override void encode( @NotNull WriterContext context ); }
@Test public void testEncode_Empty() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.OCTET_STRING.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromHexString( "''H" ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new OctetStringBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 0 ); verifyNoMoreInteractions( writer ); } } @Test public void testEncode_AF() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.OCTET_STRING.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromHexString( "'AF'H" ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new OctetStringBerEncoder().encode( new WriterContext( writer, scope, type, value, true ) ); verify( writer ).writeHeader( TAG, 1 ); verify( writer ).write( new byte[]{(byte)0xAF} ); verifyNoMoreInteractions( writer ); } } @Test( expected = AssertionError.class ) public void testEncode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromHexString( "'AF'H" ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new OctetStringBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } } @Test( expected = AssertionError.class ) public void testEncode_fail_value() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.OCTET_STRING.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new OctetStringBerEncoder().encode( new WriterContext( writer, scope, type, value, false ) ); fail( "Must fail" ); } }