Java Code Examples for org.bitcoinj.core.Utils#currentTimeSeconds()

The following examples show how to use org.bitcoinj.core.Utils#currentTimeSeconds() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PaymentChannelServerTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldTruncateTooLargeTimeWindow() {
    final int maxTimeWindow = 40000;
    final int timeWindow = maxTimeWindow + 1;
    final TwoWayChannelMessage message = createClientVersionMessage(timeWindow);
    final Capture<TwoWayChannelMessage> initiateCapture = new Capture<>();
    connection.sendToClient(capture(initiateCapture));
    replay(connection);

    dut = new PaymentChannelServer(broadcaster, wallet, Coin.CENT, new PaymentChannelServer.DefaultServerChannelProperties(){
        @Override
        public long getMaxTimeWindow() {
            return maxTimeWindow;
        }
        @Override
        public long getMinTimeWindow() { return 20000; }
    }, connection);

    dut.connectionOpen();
    dut.receiveMessage(message);

    long expectedExpire = Utils.currentTimeSeconds() + maxTimeWindow;
    assertServerVersion();
    assertExpireTime(expectedExpire, initiateCapture);
}
 
Example 2
Source File: PaymentChannelServerTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldAllowExactTimeWindow() {
    final TwoWayChannelMessage message = createClientVersionMessage();
    final Capture<TwoWayChannelMessage> initiateCapture = new Capture<>();
    connection.sendToClient(capture(initiateCapture));
    replay(connection);
    final int expire = 24 * 60 * 60 - 60;  // This the default defined in paymentchannel.proto

    dut = new PaymentChannelServer(broadcaster, wallet, Coin.CENT, new PaymentChannelServer.DefaultServerChannelProperties(){
        @Override
        public long getMaxTimeWindow() { return expire; }
        @Override
        public long getMinTimeWindow() { return expire; }
    }, connection);
    dut.connectionOpen();
    long expectedExpire = Utils.currentTimeSeconds() + expire;
    dut.receiveMessage(message);

    assertServerVersion();
    assertExpireTime(expectedExpire, initiateCapture);
}
 
Example 3
Source File: BasicKeyChainTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void keysBeforeAndAfter() throws Exception {
    Utils.setMockClock();
    long now = Utils.currentTimeSeconds();
    final ECKey key1 = new ECKey();
    Utils.rollMockClock(86400);
    final ECKey key2 = new ECKey();
    final List<ECKey> keys = Lists.newArrayList(key1, key2);
    assertEquals(2, chain.importKeys(keys));

    assertNull(chain.findOldestKeyAfter(now + 86400 * 2));
    assertEquals(key1, chain.findOldestKeyAfter(now - 1));
    assertEquals(key2, chain.findOldestKeyAfter(now + 86400 - 1));

    assertEquals(2, chain.findKeysBefore(now + 86400 * 2).size());
    assertEquals(1, chain.findKeysBefore(now + 1).size());
    assertEquals(0, chain.findKeysBefore(now - 1).size());
}
 
Example 4
Source File: PaymentChannelServerTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldAcceptDefaultTimeWindow() {
    final TwoWayChannelMessage message = createClientVersionMessage();
    final Capture<TwoWayChannelMessage> initiateCapture = new Capture<>();
    connection.sendToClient(capture(initiateCapture));
    replay(connection);

    dut = new PaymentChannelServer(broadcaster, wallet, Coin.CENT, connection);

    dut.connectionOpen();
    dut.receiveMessage(message);

    long expectedExpire = Utils.currentTimeSeconds() + 24 * 60 * 60 - 60;  // This the default defined in paymentchannel.proto
    assertServerVersion();
    assertExpireTime(expectedExpire, initiateCapture);
}
 
Example 5
Source File: BasicKeyChainTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void keysBeforeAndAfter() throws Exception {
    Utils.setMockClock();
    long now = Utils.currentTimeSeconds();
    final ECKey key1 = new ECKey();
    Utils.rollMockClock(86400);
    final ECKey key2 = new ECKey();
    final List<ECKey> keys = Lists.newArrayList(key1, key2);
    assertEquals(2, chain.importKeys(keys));

    assertNull(chain.findOldestKeyAfter(now + 86400 * 2));
    assertEquals(key1, chain.findOldestKeyAfter(now - 1));
    assertEquals(key2, chain.findOldestKeyAfter(now + 86400 - 1));

    assertEquals(2, chain.findKeysBefore(now + 86400 * 2).size());
    assertEquals(1, chain.findKeysBefore(now + 1).size());
    assertEquals(0, chain.findKeysBefore(now - 1).size());
}
 
Example 6
Source File: PaymentChannelServerTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldAllowExactTimeWindow() {
    final TwoWayChannelMessage message = createClientVersionMessage();
    final Capture<TwoWayChannelMessage> initiateCapture = new Capture<>();
    connection.sendToClient(capture(initiateCapture));
    replay(connection);
    final int expire = 24 * 60 * 60 - 60;  // This the default defined in paymentchannel.proto

    dut = new PaymentChannelServer(broadcaster, wallet, Coin.CENT, new PaymentChannelServer.DefaultServerChannelProperties() {
        @Override
        public long getMaxTimeWindow() {
            return expire;
        }

        @Override
        public long getMinTimeWindow() {
            return expire;
        }
    }, connection);
    dut.connectionOpen();
    long expectedExpire = Utils.currentTimeSeconds() + expire;
    dut.receiveMessage(message);

    assertServerVersion();
    assertExpireTime(expectedExpire, initiateCapture);
}
 
Example 7
Source File: KeyChainGroupTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void earliestKeyTime() throws Exception {
    long now = Utils.currentTimeSeconds();   // mock
    long yesterday = now - 86400;
    assertEquals(now, group.getEarliestKeyCreationTime());
    Utils.rollMockClock(10000);
    group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    Utils.rollMockClock(10000);
    group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    // Check that all keys are assumed to be created at the same instant the seed is.
    assertEquals(now, group.getEarliestKeyCreationTime());
    ECKey key = new ECKey();
    key.setCreationTimeSeconds(yesterday);
    group.importKeys(key);
    assertEquals(yesterday, group.getEarliestKeyCreationTime());
}
 
Example 8
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void keyCreationTime() throws Exception {
    Utils.setMockClock();
    long now = Utils.currentTimeSeconds();
    wallet = new Wallet(PARAMS);
    assertEquals(now, wallet.getEarliestKeyCreationTime());
    Utils.rollMockClock(60);
    wallet.freshReceiveKey();
    assertEquals(now, wallet.getEarliestKeyCreationTime());
}
 
Example 9
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void keyCreationTime() throws Exception {
    Utils.setMockClock();
    long now = Utils.currentTimeSeconds();
    wallet = new Wallet(UNITTEST);
    assertEquals(now, wallet.getEarliestKeyCreationTime());
    Utils.rollMockClock(60);
    wallet.freshReceiveKey();
    assertEquals(now, wallet.getEarliestKeyCreationTime());
}
 
Example 10
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void scriptCreationTime() throws Exception {
    Utils.setMockClock();
    long now = Utils.currentTimeSeconds();
    wallet = new Wallet(PARAMS);
    assertEquals(now, wallet.getEarliestKeyCreationTime());
    Utils.rollMockClock(-120);
    wallet.addWatchedAddress(OTHER_ADDRESS);
    wallet.freshReceiveKey();
    assertEquals(now - 120, wallet.getEarliestKeyCreationTime());
}
 
Example 11
Source File: BasicKeyChainTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void importKeys() {
    long now = Utils.currentTimeSeconds();
    Utils.setMockClock(now);
    final ECKey key1 = new ECKey();
    Utils.rollMockClock(86400);
    final ECKey key2 = new ECKey();
    final ArrayList<ECKey> keys = Lists.newArrayList(key1, key2);

    // Import two keys, check the event is correct.
    assertEquals(2, chain.importKeys(keys));
    assertEquals(2, chain.numKeys());
    assertTrue(onKeysAddedRan.getAndSet(false));
    assertArrayEquals(keys.toArray(), onKeysAdded.get().toArray());
    assertEquals(now, chain.getEarliestKeyCreationTime());
    // Check we ignore duplicates.
    final ECKey newKey = new ECKey();
    keys.add(newKey);
    assertEquals(1, chain.importKeys(keys));
    assertTrue(onKeysAddedRan.getAndSet(false));
    assertEquals(newKey, onKeysAdded.getAndSet(null).get(0));
    assertEquals(0, chain.importKeys(keys));
    assertFalse(onKeysAddedRan.getAndSet(false));
    assertNull(onKeysAdded.get());

    assertTrue(chain.hasKey(key1));
    assertTrue(chain.hasKey(key2));
    assertEquals(key1, chain.findKeyFromPubHash(key1.getPubKeyHash()));
    assertEquals(key2, chain.findKeyFromPubKey(key2.getPubKey()));
    assertNull(chain.findKeyFromPubKey(key2.getPubKeyHash()));
}
 
Example 12
Source File: BasicKeyChainTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void importKeys() {
    long now = Utils.currentTimeSeconds();
    Utils.setMockClock(now);
    final ECKey key1 = new ECKey();
    Utils.rollMockClock(86400);
    final ECKey key2 = new ECKey();
    final ArrayList<ECKey> keys = Lists.newArrayList(key1, key2);

    // Import two keys, check the event is correct.
    assertEquals(2, chain.importKeys(keys));
    assertEquals(2, chain.numKeys());
    assertTrue(onKeysAddedRan.getAndSet(false));
    assertArrayEquals(keys.toArray(), onKeysAdded.get().toArray());
    assertEquals(now, chain.getEarliestKeyCreationTime());
    // Check we ignore duplicates.
    final ECKey newKey = new ECKey();
    keys.add(newKey);
    assertEquals(1, chain.importKeys(keys));
    assertTrue(onKeysAddedRan.getAndSet(false));
    assertEquals(newKey, onKeysAdded.getAndSet(null).get(0));
    assertEquals(0, chain.importKeys(keys));
    assertFalse(onKeysAddedRan.getAndSet(false));
    assertNull(onKeysAdded.get());

    assertTrue(chain.hasKey(key1));
    assertTrue(chain.hasKey(key2));
    assertEquals(key1, chain.findKeyFromPubHash(key1.getPubKeyHash()));
    assertEquals(key2, chain.findKeyFromPubKey(key2.getPubKey()));
    assertNull(chain.findKeyFromPubKey(key2.getPubKeyHash()));
}
 
Example 13
Source File: PaymentChannelServerTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void shouldTruncateTooLargeTimeWindow() {
    final int maxTimeWindow = 40000;
    final int timeWindow = maxTimeWindow + 1;
    final TwoWayChannelMessage message = createClientVersionMessage(timeWindow);
    final Capture<TwoWayChannelMessage> initiateCapture = new Capture<>();
    connection.sendToClient(capture(initiateCapture));
    replay(connection);

    dut = new PaymentChannelServer(broadcaster, wallet, Coin.CENT, new PaymentChannelServer.DefaultServerChannelProperties() {
        @Override
        public long getMaxTimeWindow() {
            return maxTimeWindow;
        }

        @Override
        public long getMinTimeWindow() {
            return 20000;
        }
    }, connection);

    dut.connectionOpen();
    dut.receiveMessage(message);

    long expectedExpire = Utils.currentTimeSeconds() + maxTimeWindow;
    assertServerVersion();
    assertExpireTime(expectedExpire, initiateCapture);
}
 
Example 14
Source File: PaymentChannelServerTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void shouldTruncateTooSmallTimeWindow() {
    final int minTimeWindow = 20000;
    final int timeWindow = minTimeWindow - 1;
    final TwoWayChannelMessage message = createClientVersionMessage(timeWindow);
    final Capture<TwoWayChannelMessage> initiateCapture = new Capture<>();
    connection.sendToClient(capture(initiateCapture));

    replay(connection);
    dut = new PaymentChannelServer(broadcaster, wallet, Coin.CENT, new PaymentChannelServer.DefaultServerChannelProperties() {
        @Override
        public long getMinTimeWindow() {
            return minTimeWindow;
        }

        @Override
        public long getMaxTimeWindow() {
            return 40000;
        }
    }, connection);

    dut.connectionOpen();
    dut.receiveMessage(message);

    long expectedExpire = Utils.currentTimeSeconds() + minTimeWindow;
    assertServerVersion();
    assertExpireTime(expectedExpire, initiateCapture);
}
 
Example 15
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void keyCreationTime() throws Exception {
    Utils.setMockClock();
    long now = Utils.currentTimeSeconds();
    wallet = new Wallet(PARAMS);
    assertEquals(now, wallet.getEarliestKeyCreationTime());
    Utils.rollMockClock(60);
    wallet.freshReceiveKey();
    assertEquals(now, wallet.getEarliestKeyCreationTime());
}
 
Example 16
Source File: Identity.java    From token-core-android with Apache License 2.0 4 votes vote down vote up
public String encryptDataToIPFS(String originData) {
  long unixTimestamp = Utils.currentTimeSeconds();
  byte[] iv = NumericUtil.generateRandomBytes(16);
  return encryptDataToIPFS(originData, unixTimestamp, iv);
}
 
Example 17
Source File: PaymentChannelClientConnection.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Attempts to open a new connection to and open a payment channel with the given host and port, blocking until the
 * connection is open.  The server is requested to keep the channel open for {@param timeWindow}
 * seconds. If the server proposes a longer time the channel will be closed.
 *
 * @param server The host/port pair where the server is listening.
 * @param timeoutSeconds The connection timeout and read timeout during initialization. This should be large enough
 *                       to accommodate ECDSA signature operations and network latency.
 * @param wallet The wallet which will be paid from, and where completed transactions will be committed.
 *               Can be encrypted if user key is supplied when needed. Must already have a
 *               {@link StoredPaymentChannelClientStates} object in its extensions set.
 * @param myKey A freshly generated keypair used for the multisig contract and refund output.
 * @param maxValue The maximum value this channel is allowed to request
 * @param serverId A unique ID which is used to attempt reopening of an existing channel.
 *                 This must be unique to the server, and, if your application is exposing payment channels to some
 *                 API, this should also probably encompass some caller UID to avoid applications opening channels
 *                 which were created by others.
 * @param userKeySetup Key derived from a user password, used to decrypt myKey, if it is encrypted, during setup.
 * @param clientChannelProperties Modifier to change the channel's configuration.
 *
 * @throws IOException if there's an issue using the network.
 * @throws ValueOutOfRangeException if the balance of wallet is lower than maxValue.
 */
public PaymentChannelClientConnection(InetSocketAddress server, int timeoutSeconds, Wallet wallet, ECKey myKey,
                                      Coin maxValue, String serverId,
                                      @Nullable KeyParameter userKeySetup, final ClientChannelProperties clientChannelProperties)
        throws IOException, ValueOutOfRangeException {
    // Glue the object which vends/ingests protobuf messages in order to manage state to the network object which
    // reads/writes them to the wire in length prefixed form.
    channelClient = new PaymentChannelClient(wallet, myKey, maxValue, Sha256Hash.of(serverId.getBytes()),
            userKeySetup, clientChannelProperties, new PaymentChannelClient.ClientConnection() {
        @Override
        public void sendToServer(Protos.TwoWayChannelMessage msg) {
            wireParser.write(msg);
        }

        @Override
        public void destroyConnection(PaymentChannelCloseException.CloseReason reason) {
            channelOpenFuture.setException(new PaymentChannelCloseException("Payment channel client requested that the connection be closed: " + reason, reason));
            wireParser.closeConnection();
        }

        @Override
        public boolean acceptExpireTime(long expireTime) {
            return expireTime <= (clientChannelProperties.timeWindow() + Utils.currentTimeSeconds() + 60);  // One extra minute to compensate for time skew and latency
        }

        @Override
        public void channelOpen(boolean wasInitiated) {
            wireParser.setSocketTimeout(0);
            // Inform the API user that we're done and ready to roll.
            channelOpenFuture.set(PaymentChannelClientConnection.this);
        }
    });

    // And glue back in the opposite direction - network to the channelClient.
    wireParser = new ProtobufConnection<Protos.TwoWayChannelMessage>(new ProtobufConnection.Listener<Protos.TwoWayChannelMessage>() {
        @Override
        public void messageReceived(ProtobufConnection<Protos.TwoWayChannelMessage> handler, Protos.TwoWayChannelMessage msg) {
            try {
                channelClient.receiveMessage(msg);
            } catch (InsufficientMoneyException e) {
                // We should only get this exception during INITIATE, so channelOpen wasn't called yet.
                channelOpenFuture.setException(e);
            }
        }

        @Override
        public void connectionOpen(ProtobufConnection<Protos.TwoWayChannelMessage> handler) {
            channelClient.connectionOpen();
        }

        @Override
        public void connectionClosed(ProtobufConnection<Protos.TwoWayChannelMessage> handler) {
            channelClient.connectionClosed();
            channelOpenFuture.setException(new PaymentChannelCloseException("The TCP socket died",
                    PaymentChannelCloseException.CloseReason.CONNECTION_CLOSED));
        }
    }, Protos.TwoWayChannelMessage.getDefaultInstance(), Short.MAX_VALUE, timeoutSeconds*1000);

    // Initiate the outbound network connection. We don't need to keep this around. The wireParser object will handle
    // things from here on out.
    new NioClient(server, wireParser, timeoutSeconds * 1000);
}
 
Example 18
Source File: DeterministicKeyChain.java    From green_android with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Generates a new key chain with entropy selected randomly from the given {@link java.security.SecureRandom}
 * object and the default entropy size.
 */
public DeterministicKeyChain(SecureRandom random) {
    this(random, DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS, DEFAULT_PASSPHRASE_FOR_MNEMONIC, Utils.currentTimeSeconds());
}
 
Example 19
Source File: DeterministicKeyChain.java    From green_android with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Generates a new key chain with entropy selected randomly from the given {@link java.security.SecureRandom}
 * object and of the requested size in bits.
 */
public DeterministicKeyChain(SecureRandom random, int bits) {
    this(random, bits, DEFAULT_PASSPHRASE_FOR_MNEMONIC, Utils.currentTimeSeconds());
}
 
Example 20
Source File: DeterministicKeyChain.java    From bcm-android with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Generates a new key chain with entropy selected randomly from the given {@link SecureRandom}
 * object and the default entropy size.
 */
public DeterministicKeyChain(SecureRandom random) {
    this(random, DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS, DEFAULT_PASSPHRASE_FOR_MNEMONIC, Utils.currentTimeSeconds());
}