@Before
  public void setUp() throws Exception {
    unitTestParams = UnitTestParams.get();
    wallet = new Wallet(unitTestParams);
    wallet.addKey(new ECKey());

    resetBlockStore();

    Transaction tx1 =
        createFakeTx(
            unitTestParams,
            Utils.toNanoCoins(2, 0),
            wallet.getKeys().get(0).toAddress(unitTestParams));

    // add a second input so can test granularity of byte cache.
    Transaction prevTx = new Transaction(unitTestParams);
    TransactionOutput prevOut =
        new TransactionOutput(
            unitTestParams,
            prevTx,
            Utils.toNanoCoins(1, 0),
            wallet.getKeys().get(0).toAddress(unitTestParams));
    prevTx.addOutput(prevOut);
    // Connect it.
    tx1.addInput(prevOut);

    Transaction tx2 =
        createFakeTx(
            unitTestParams, Utils.toNanoCoins(1, 0), new ECKey().toAddress(unitTestParams));

    Block b1 = createFakeBlock(blockStore, tx1, tx2).block;

    BitcoinSerializer bs = new BitcoinSerializer(unitTestParams);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bs.serialize(tx1, bos);
    tx1BytesWithHeader = bos.toByteArray();
    tx1Bytes = tx1.bitcoinSerialize();

    bos.reset();
    bs.serialize(tx2, bos);
    tx2BytesWithHeader = bos.toByteArray();
    tx2Bytes = tx2.bitcoinSerialize();

    bos.reset();
    bs.serialize(b1, bos);
    b1BytesWithHeader = bos.toByteArray();
    b1Bytes = b1.bitcoinSerialize();
  }
  public void setUp(BlockStore blockStore) throws Exception {
    BriefLogFormatter.init();

    unitTestParams = UnitTestParams.get();
    Wallet.SendRequest.DEFAULT_FEE_PER_KB = BigInteger.ZERO;
    this.blockStore = blockStore;
    wallet = new Wallet(unitTestParams);
    key = new ECKey();
    address = key.toAddress(unitTestParams);
    wallet.addKey(key);
    blockChain = new BlockChain(unitTestParams, wallet, blockStore);

    startPeerServers();
    if (clientType == ClientType.NIO_CLIENT_MANAGER
        || clientType == ClientType.BLOCKING_CLIENT_MANAGER) {
      channels.startAsync();
      channels.awaitRunning();
    }

    socketAddress = new InetSocketAddress("127.0.0.1", 1111);
  }
 public void setUp() throws Exception {
   setUp(new MemoryBlockStore(UnitTestParams.get()));
 }
public class PaymentProtocolTest {

  // static test data
  private static final NetworkParameters NETWORK_PARAMS = UnitTestParams.get();
  private static final BigInteger AMOUNT = BigInteger.ONE;
  private static final Address TO_ADDRESS = new ECKey().toAddress(NETWORK_PARAMS);
  private static final String MEMO = "memo";
  private static final String PAYMENT_URL = "https://example.com";
  private static final byte[] MERCHANT_DATA = new byte[] {0, 1, 2};

  private KeyStore caStore;
  private X509Certificate caCert;

  @Before
  public void setUp() throws Exception {
    caStore =
        X509Utils.loadKeyStore("JKS", "password", getClass().getResourceAsStream("test-cacerts"));
    caCert = (X509Certificate) caStore.getCertificate("test-cacert");
  }

  @Test
  public void testSignAndVerifyValid() throws Exception {
    Protos.PaymentRequest.Builder paymentRequest = minimalPaymentRequest().toBuilder();

    // Sign
    KeyStore keyStore =
        X509Utils.loadKeyStore(
            "JKS", "password", getClass().getResourceAsStream("test-valid-cert"));
    PrivateKey privateKey = (PrivateKey) keyStore.getKey("test-valid", "password".toCharArray());
    X509Certificate clientCert = (X509Certificate) keyStore.getCertificate("test-valid");
    PaymentProtocol.signPaymentRequest(
        paymentRequest, new X509Certificate[] {clientCert}, privateKey);

    // Verify
    PkiVerificationData verificationData =
        PaymentProtocol.verifyPaymentRequestPki(paymentRequest.build(), caStore);
    assertNotNull(verificationData);
    assertEquals(caCert, verificationData.rootAuthority.getTrustedCert());
  }

  @Test(expected = PkiVerificationException.class)
  public void testSignAndVerifyExpired() throws Exception {
    Protos.PaymentRequest.Builder paymentRequest = minimalPaymentRequest().toBuilder();

    // Sign
    KeyStore keyStore =
        X509Utils.loadKeyStore(
            "JKS", "password", getClass().getResourceAsStream("test-expired-cert"));
    PrivateKey privateKey = (PrivateKey) keyStore.getKey("test-expired", "password".toCharArray());
    X509Certificate clientCert = (X509Certificate) keyStore.getCertificate("test-expired");
    PaymentProtocol.signPaymentRequest(
        paymentRequest, new X509Certificate[] {clientCert}, privateKey);

    // Verify
    PaymentProtocol.verifyPaymentRequestPki(paymentRequest.build(), caStore);
  }

  private Protos.PaymentRequest minimalPaymentRequest() {
    Protos.PaymentDetails.Builder paymentDetails = Protos.PaymentDetails.newBuilder();
    paymentDetails.setTime(System.currentTimeMillis());
    Protos.PaymentRequest.Builder paymentRequest = Protos.PaymentRequest.newBuilder();
    paymentRequest.setSerializedPaymentDetails(paymentDetails.build().toByteString());
    return paymentRequest.build();
  }

  public void testPaymentRequest() throws Exception {
    // Create
    PaymentRequest paymentRequest =
        PaymentProtocol.createPaymentRequest(
                NETWORK_PARAMS, AMOUNT, TO_ADDRESS, MEMO, PAYMENT_URL, MERCHANT_DATA)
            .build();
    byte[] paymentRequestBytes = paymentRequest.toByteArray();

    // Parse
    PaymentSession parsedPaymentRequest =
        PaymentProtocol.parsePaymentRequest(PaymentRequest.parseFrom(paymentRequestBytes));
    final List<Output> parsedOutputs = parsedPaymentRequest.getOutputs();
    assertEquals(1, parsedOutputs.size());
    assertEquals(AMOUNT, parsedOutputs.get(0).amount);
    assertEquals(
        ScriptBuilder.createOutputScript(TO_ADDRESS).getProgram(), parsedOutputs.get(0).scriptData);
    assertEquals(MEMO, parsedPaymentRequest.getMemo());
    assertEquals(PAYMENT_URL, parsedPaymentRequest.getPaymentUrl());
    assertEquals(MERCHANT_DATA, parsedPaymentRequest.getMerchantData());
  }

  @Test
  public void testPaymentMessage() throws Exception {
    // Create
    List<Transaction> transactions = new LinkedList<Transaction>();
    transactions.add(FakeTxBuilder.createFakeTx(NETWORK_PARAMS, AMOUNT, TO_ADDRESS));
    BigInteger refundAmount = BigInteger.ONE;
    Address refundAddress = new ECKey().toAddress(NETWORK_PARAMS);
    Payment payment =
        PaymentProtocol.createPaymentMessage(
            transactions, refundAmount, refundAddress, MEMO, MERCHANT_DATA);
    byte[] paymentBytes = payment.toByteArray();

    // Parse
    Payment parsedPayment = Payment.parseFrom(paymentBytes);
    List<Transaction> parsedTransactions =
        PaymentProtocol.parseTransactionsFromPaymentMessage(NETWORK_PARAMS, parsedPayment);
    assertEquals(transactions, parsedTransactions);
    assertEquals(1, parsedPayment.getRefundToCount());
    assertEquals(MEMO, parsedPayment.getMemo());
    assertArrayEquals(MERCHANT_DATA, parsedPayment.getMerchantData().toByteArray());
  }

  @Test
  public void testPaymentAck() throws Exception {
    // Create
    Payment paymentMessage = Protos.Payment.newBuilder().build();
    PaymentACK paymentAck = PaymentProtocol.createPaymentAck(paymentMessage, MEMO);
    byte[] paymentAckBytes = paymentAck.toByteArray();

    // Parse
    PaymentACK parsedPaymentAck = PaymentACK.parseFrom(paymentAckBytes);
    assertEquals(paymentMessage, parsedPaymentAck.getPayment());
    assertEquals(MEMO, parsedPaymentAck.getMemo());
  }
}