net.jcip.annotations.GuardedBy Java Examples

The following examples show how to use net.jcip.annotations.GuardedBy. 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: PaymentChannelClient.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void receiveChannelOpen() throws VerificationException {
    checkState(step == InitStep.WAITING_FOR_CHANNEL_OPEN || (step == InitStep.WAITING_FOR_INITIATE && storedChannel != null), step);
    log.info("Got CHANNEL_OPEN message, ready to pay");

    boolean wasInitiated = true;
    if (step == InitStep.WAITING_FOR_INITIATE) {
        // We skipped the initiate step, because a previous channel that's still valid was resumed.
        wasInitiated = false;
        switch (majorVersion) {
            case 1:
                state = new PaymentChannelV1ClientState(storedChannel, wallet);
                break;
            case 2:
                state = new PaymentChannelV2ClientState(storedChannel, wallet);
                break;
            default:
                throw new IllegalStateException("Invalid version number " + majorVersion);
        }
    }
    step = InitStep.CHANNEL_OPEN;
    // channelOpen should disable timeouts, but
    // TODO accomodate high latency between PROVIDE_CONTRACT and here
    conn.channelOpen(wasInitiated);
}
 
Example #2
Source File: Authenticator.java    From LiquidDonkey with MIT License 6 votes vote down vote up
@GuardedBy("lock")
void authenticate(HttpClient client) throws IOException {
    if (id == null || id.isEmpty() || password == null || password.isEmpty()) {
        invalid = "Unable to re-authenticate expired token: missing appleId/ password.";

    } else {
        try {
            Auth auth = Auth.from(client, id, password);

            if (auth.dsPrsID().equals(token.auth().dsPrsID())) {
                token = Token.from(auth);

            } else {
                logger.error("-- reauthentication() > mismatched dsPrsID: {} > {}",
                        token.auth().dsPrsID(), auth.dsPrsID());
                invalid = "Unable to re-authenticate expired token: account mismatch.";
            }
        } catch (HttpResponseException ex) {
            if (ex.getStatusCode() == 401) {
                invalid = "Unable to re-authenticate expired token: invalid appleId/ password.";
            }
        }
    }

    testIsInvalid();
}
 
Example #3
Source File: PaymentChannelServer.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void settlePayment(final CloseReason clientRequestedClose) throws InsufficientMoneyException {
    // Setting channelSettling here prevents us from sending another CLOSE when state.close() calls
    // close() on us here below via the stored channel state.
    // TODO: Strongly separate the lifecycle of the payment channel from the TCP connection in these classes.
    channelSettling = true;
    ListenableFuture<KeyParameter> keyFuture = conn.getUserKey();
    ListenableFuture<Transaction> result;
    if (keyFuture != null) {
        result = Futures.transformAsync(conn.getUserKey(), new AsyncFunction<KeyParameter, Transaction>() {
            @Override
            public ListenableFuture<Transaction> apply(KeyParameter userKey) throws Exception {
                return state.close(userKey);
            }
        });
    } else {
        result = state.close();
    }
    Futures.addCallback(result, new FutureCallback<Transaction>() {
 
Example #4
Source File: PaymentChannelServer.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void receiveContractMessage(Protos.TwoWayChannelMessage msg) throws VerificationException {
    checkState(majorVersion == 1 || majorVersion == 2);
    checkState(step == InitStep.WAITING_ON_CONTRACT && msg.hasProvideContract());
    log.info("Got contract, broadcasting and responding with CHANNEL_OPEN");
    final Protos.ProvideContract providedContract = msg.getProvideContract();

    if (majorVersion == 2) {
        state = new PaymentChannelV2ServerState(broadcaster, wallet, myKey, expireTime);
        checkState(providedContract.hasClientKey(), "ProvideContract didn't have a client key in protocol v2");
        ((PaymentChannelV2ServerState)state).provideClientKey(providedContract.getClientKey().toByteArray());
    }

    //TODO notify connection handler that timeout should be significantly extended as we wait for network propagation?
    final Transaction contract = wallet.getParams().getDefaultSerializer().makeTransaction(providedContract.getTx().toByteArray());
    step = InitStep.WAITING_ON_MULTISIG_ACCEPTANCE;
    state.provideContract(contract)
            .addListener(new Runnable() {
                @Override
                public void run() {
                    multisigContractPropogated(providedContract, contract.getHash());
                }
            }, Threading.SAME_THREAD);
}
 
Example #5
Source File: PaymentChannelServer.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void receiveRefundMessage(Protos.TwoWayChannelMessage msg) throws VerificationException {
    checkState(majorVersion == 1);
    checkState(step == InitStep.WAITING_ON_UNSIGNED_REFUND && msg.hasProvideRefund());
    log.info("Got refund transaction, returning signature");

    Protos.ProvideRefund providedRefund = msg.getProvideRefund();
    state = new PaymentChannelV1ServerState(broadcaster, wallet, myKey, expireTime);
    // We can cast to V1 state since this state is only used in the V1 protocol
    byte[] signature = ((PaymentChannelV1ServerState) state)
            .provideRefundTransaction(wallet.getParams().getDefaultSerializer().makeTransaction(providedRefund.getTx().toByteArray()),
                    providedRefund.getMultisigKey().toByteArray());

    step = InitStep.WAITING_ON_CONTRACT;

    Protos.ReturnRefund.Builder returnRefundBuilder = Protos.ReturnRefund.newBuilder()
            .setSignature(ByteString.copyFrom(signature));

    conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
            .setReturnRefund(returnRefundBuilder)
            .setType(Protos.TwoWayChannelMessage.MessageType.RETURN_REFUND)
            .build());
}
 
Example #6
Source File: PaymentChannelClient.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void receiveClose(Protos.TwoWayChannelMessage msg) throws VerificationException {
    checkState(lock.isHeldByCurrentThread());
    if (msg.hasSettlement()) {
        Transaction settleTx = wallet.getParams().getDefaultSerializer().makeTransaction(msg.getSettlement().getTx().toByteArray());
        log.info("CLOSE message received with settlement tx {}", settleTx.getHash());
        // TODO: set source
        if (state != null && state().isSettlementTransaction(settleTx)) {
            // The wallet has a listener on it that the state object will use to do the right thing at this
            // point (like watching it for confirmations). The tx has been checked by now for syntactical validity
            // and that it correctly spends the multisig contract.
            wallet.receivePending(settleTx, null);
        }
    } else {
        log.info("CLOSE message received without settlement tx");
    }
    if (step == InitStep.WAITING_FOR_CHANNEL_CLOSE)
        conn.destroyConnection(CloseReason.CLIENT_REQUESTED_CLOSE);
    else
        conn.destroyConnection(CloseReason.SERVER_REQUESTED_CLOSE);
    step = InitStep.CHANNEL_CLOSED;
}
 
Example #7
Source File: PaymentChannelClient.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void receiveChannelOpen() throws VerificationException {
    checkState(step == InitStep.WAITING_FOR_CHANNEL_OPEN || (step == InitStep.WAITING_FOR_INITIATE && storedChannel != null), step);
    log.info("Got CHANNEL_OPEN message, ready to pay");

    boolean wasInitiated = true;
    if (step == InitStep.WAITING_FOR_INITIATE) {
        // We skipped the initiate step, because a previous channel that's still valid was resumed.
        wasInitiated  = false;
        switch (majorVersion) {
            case 1:
                state = new PaymentChannelV1ClientState(storedChannel, wallet);
                break;
            case 2:
                state = new PaymentChannelV2ClientState(storedChannel, wallet);
                break;
            default:
                throw new IllegalStateException("Invalid version number " + majorVersion);
        }
    }
    step = InitStep.CHANNEL_OPEN;
    // channelOpen should disable timeouts, but
    // TODO accomodate high latency between PROVIDE_CONTRACT and here
    conn.channelOpen(wasInitiated);
}
 
Example #8
Source File: Publisher.java    From nsq-j with MIT License 6 votes vote down vote up
@GuardedBy("this")
private void publishFailover(String topic, byte[] data) {
    try {
        if (failoverNsqd == null) {
            logger.warn("publish failed but no failoverNsqd configured. Will wait and retry once.");
            Util.sleepQuietly(10000); //could do exponential backoff or make configurable
            connect(nsqd);
        }
        else if (!isFailover) {
            failoverStart = Util.clock();
            isFailover = true;
            connect(failoverNsqd);
            logger.info("using failover nsqd:{}", failoverNsqd);
        }
        con.publish(topic, data);
    }
    catch (Exception e) {
        Util.closeQuietly(con);
        con = null;
        isFailover = false;
        throw new NSQException("publish failed", e);
    }
}
 
Example #9
Source File: PaymentChannelServer.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void settlePayment(final CloseReason clientRequestedClose) throws InsufficientMoneyException {
    // Setting channelSettling here prevents us from sending another CLOSE when state.close() calls
    // close() on us here below via the stored channel state.
    // TODO: Strongly separate the lifecycle of the payment channel from the TCP connection in these classes.
    channelSettling = true;
    ListenableFuture<KeyParameter> keyFuture = conn.getUserKey();
    ListenableFuture<Transaction> result;
    if (keyFuture != null) {
        result = Futures.transformAsync(conn.getUserKey(), new AsyncFunction<KeyParameter, Transaction>() {
            @Override
            public ListenableFuture<Transaction> apply(KeyParameter userKey) throws Exception {
                return state.close(userKey);
            }
        });
    } else {
        result = state.close();
    }
    Futures.addCallback(result, new FutureCallback<Transaction>() {
 
Example #10
Source File: PaymentChannelServer.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void receiveContractMessage(Protos.TwoWayChannelMessage msg) throws VerificationException {
    checkState(majorVersion == 1 || majorVersion == 2);
    checkState(step == InitStep.WAITING_ON_CONTRACT && msg.hasProvideContract());
    log.info("Got contract, broadcasting and responding with CHANNEL_OPEN");
    final Protos.ProvideContract providedContract = msg.getProvideContract();

    if (majorVersion == 2) {
        state = new PaymentChannelV2ServerState(broadcaster, wallet, myKey, expireTime);
        checkState(providedContract.hasClientKey(), "ProvideContract didn't have a client key in protocol v2");
        ((PaymentChannelV2ServerState)state).provideClientKey(providedContract.getClientKey().toByteArray());
    }

    //TODO notify connection handler that timeout should be significantly extended as we wait for network propagation?
    final Transaction contract = wallet.getParams().getDefaultSerializer().makeTransaction(providedContract.getTx().toByteArray());
    step = InitStep.WAITING_ON_MULTISIG_ACCEPTANCE;
    state.provideContract(contract)
            .addListener(new Runnable() {
                @Override
                public void run() {
                    multisigContractPropogated(providedContract, contract.getHash());
                }
            }, Threading.SAME_THREAD);
}
 
Example #11
Source File: PaymentChannelServer.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void receiveRefundMessage(Protos.TwoWayChannelMessage msg) throws VerificationException {
    checkState(majorVersion == 1);
    checkState(step == InitStep.WAITING_ON_UNSIGNED_REFUND && msg.hasProvideRefund());
    log.info("Got refund transaction, returning signature");

    Protos.ProvideRefund providedRefund = msg.getProvideRefund();
    state = new PaymentChannelV1ServerState(broadcaster, wallet, myKey, expireTime);
    // We can cast to V1 state since this state is only used in the V1 protocol
    byte[] signature = ((PaymentChannelV1ServerState) state)
            .provideRefundTransaction(wallet.getParams().getDefaultSerializer().makeTransaction(providedRefund.getTx().toByteArray()),
                    providedRefund.getMultisigKey().toByteArray());

    step = InitStep.WAITING_ON_CONTRACT;

    Protos.ReturnRefund.Builder returnRefundBuilder = Protos.ReturnRefund.newBuilder()
            .setSignature(ByteString.copyFrom(signature));

    conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
            .setReturnRefund(returnRefundBuilder)
            .setType(Protos.TwoWayChannelMessage.MessageType.RETURN_REFUND)
            .build());
}
 
Example #12
Source File: PaymentChannelClient.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void receiveClose(Protos.TwoWayChannelMessage msg) throws VerificationException {
    checkState(lock.isHeldByCurrentThread());
    if (msg.hasSettlement()) {
        Transaction settleTx = wallet.getParams().getDefaultSerializer().makeTransaction(msg.getSettlement().getTx().toByteArray());
        log.info("CLOSE message received with settlement tx {}", settleTx.getHash());
        // TODO: set source
        if (state != null && state().isSettlementTransaction(settleTx)) {
            // The wallet has a listener on it that the state object will use to do the right thing at this
            // point (like watching it for confirmations). The tx has been checked by now for syntactical validity
            // and that it correctly spends the multisig contract.
            wallet.receivePending(settleTx, null);
        }
    } else {
        log.info("CLOSE message received without settlement tx");
    }
    if (step == InitStep.WAITING_FOR_CHANNEL_CLOSE)
        conn.destroyConnection(CloseReason.CLIENT_REQUESTED_CLOSE);
    else
        conn.destroyConnection(CloseReason.SERVER_REQUESTED_CLOSE);
    step = InitStep.CHANNEL_CLOSED;
}
 
Example #13
Source File: PaymentChannelClient.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void receiveChannelOpen() throws VerificationException {
    checkState(step == InitStep.WAITING_FOR_CHANNEL_OPEN || (step == InitStep.WAITING_FOR_INITIATE && storedChannel != null), step);
    log.info("Got CHANNEL_OPEN message, ready to pay");

    boolean wasInitiated = true;
    if (step == InitStep.WAITING_FOR_INITIATE) {
        // We skipped the initiate step, because a previous channel that's still valid was resumed.
        wasInitiated  = false;
        switch (majorVersion) {
            case 1:
                state = new PaymentChannelV1ClientState(storedChannel, wallet);
                break;
            case 2:
                state = new PaymentChannelV2ClientState(storedChannel, wallet);
                break;
            default:
                throw new IllegalStateException("Invalid version number " + majorVersion);
        }
    }
    step = InitStep.CHANNEL_OPEN;
    // channelOpen should disable timeouts, but
    // TODO accomodate high latency between PROVIDE_CONTRACT and here
    conn.channelOpen(wasInitiated);
}
 
Example #14
Source File: PaymentChannelClient.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void receiveClose(Protos.TwoWayChannelMessage msg) throws VerificationException {
    checkState(lock.isHeldByCurrentThread());
    if (msg.hasSettlement()) {
        Transaction settleTx = wallet.getParams().getDefaultSerializer().makeTransaction(msg.getSettlement().getTx().toByteArray());
        log.info("CLOSE message received with settlement tx {}", settleTx.getHash());
        // TODO: set source
        if (state != null && state().isSettlementTransaction(settleTx)) {
            // The wallet has a listener on it that the state object will use to do the right thing at this
            // point (like watching it for confirmations). The tx has been checked by now for syntactical validity
            // and that it correctly spends the multisig contract.
            wallet.receivePending(settleTx, null);
        }
    } else {
        log.info("CLOSE message received without settlement tx");
    }
    if (step == InitStep.WAITING_FOR_CHANNEL_CLOSE)
        conn.destroyConnection(CloseReason.CLIENT_REQUESTED_CLOSE);
    else
        conn.destroyConnection(CloseReason.SERVER_REQUESTED_CLOSE);
    step = InitStep.CHANNEL_CLOSED;
}
 
Example #15
Source File: PaymentChannelServer.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void receiveRefundMessage(Protos.TwoWayChannelMessage msg) throws VerificationException {
    checkState(majorVersion == 1);
    checkState(step == InitStep.WAITING_ON_UNSIGNED_REFUND && msg.hasProvideRefund());
    log.info("Got refund transaction, returning signature");

    Protos.ProvideRefund providedRefund = msg.getProvideRefund();
    state = new PaymentChannelV1ServerState(broadcaster, wallet, myKey, expireTime);
    // We can cast to V1 state since this state is only used in the V1 protocol
    byte[] signature = ((PaymentChannelV1ServerState) state)
            .provideRefundTransaction(wallet.getParams().getDefaultSerializer().makeTransaction(providedRefund.getTx().toByteArray()),
                    providedRefund.getMultisigKey().toByteArray());

    step = InitStep.WAITING_ON_CONTRACT;

    Protos.ReturnRefund.Builder returnRefundBuilder = Protos.ReturnRefund.newBuilder()
            .setSignature(ByteString.copyFrom(signature));

    conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
            .setReturnRefund(returnRefundBuilder)
            .setType(Protos.TwoWayChannelMessage.MessageType.RETURN_REFUND)
            .build());
}
 
Example #16
Source File: PaymentChannelServer.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void receiveContractMessage(Protos.TwoWayChannelMessage msg) throws VerificationException {
    checkState(majorVersion == 1 || majorVersion == 2);
    checkState(step == InitStep.WAITING_ON_CONTRACT && msg.hasProvideContract());
    log.info("Got contract, broadcasting and responding with CHANNEL_OPEN");
    final Protos.ProvideContract providedContract = msg.getProvideContract();

    if (majorVersion == 2) {
        state = new PaymentChannelV2ServerState(broadcaster, wallet, myKey, expireTime);
        checkState(providedContract.hasClientKey(), "ProvideContract didn't have a client key in protocol v2");
        ((PaymentChannelV2ServerState) state).provideClientKey(providedContract.getClientKey().toByteArray());
    }

    //TODO notify connection handler that timeout should be significantly extended as we wait for network propagation?
    final Transaction contract = wallet.getParams().getDefaultSerializer().makeTransaction(providedContract.getTx().toByteArray());
    step = InitStep.WAITING_ON_MULTISIG_ACCEPTANCE;
    state.provideContract(contract)
            .addListener(new Runnable() {
                @Override
                public void run() {
                    multisigContractPropogated(providedContract, contract.getHash());
                }
            }, Threading.SAME_THREAD);
}
 
Example #17
Source File: PaymentChannelServer.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@GuardedBy("lock")
private void settlePayment(final CloseReason clientRequestedClose) throws InsufficientMoneyException {
    // Setting channelSettling here prevents us from sending another CLOSE when state.close() calls
    // close() on us here below via the stored channel state.
    // TODO: Strongly separate the lifecycle of the payment channel from the TCP connection in these classes.
    channelSettling = true;
    ListenableFuture<KeyParameter> keyFuture = conn.getUserKey();
    ListenableFuture<Transaction> result;
    if (keyFuture != null) {
        result = Futures.transformAsync(conn.getUserKey(), new AsyncFunction<KeyParameter, Transaction>() {
            @Override
            public ListenableFuture<Transaction> apply(KeyParameter userKey) throws Exception {
                return state.close(userKey);
            }
        });
    } else {
        result = state.close();
    }
    Futures.addCallback(result, new FutureCallback<Transaction>() {
 
Example #18
Source File: PaymentChannelClient.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@GuardedBy("lock")
private void receiveRefund(Protos.TwoWayChannelMessage refundMsg, @Nullable KeyParameter userKey) throws VerificationException {
    checkState(majorVersion == 1);
    checkState(step == InitStep.WAITING_FOR_REFUND_RETURN && refundMsg.hasReturnRefund());
    log.info("Got RETURN_REFUND message, providing signed contract");
    Protos.ReturnRefund returnedRefund = refundMsg.getReturnRefund();
    // Cast is safe since we've checked the version number
    ((PaymentChannelV1ClientState) state).provideRefundSignature(returnedRefund.getSignature().toByteArray(), userKey);
    step = InitStep.WAITING_FOR_CHANNEL_OPEN;

    // Before we can send the server the contract (ie send it to the network), we must ensure that our refund
    // transaction is safely in the wallet - thus we store it (this also keeps it up-to-date when we pay)
    state.storeChannelInWallet(serverId);

    Protos.ProvideContract.Builder contractMsg = Protos.ProvideContract.newBuilder()
            .setTx(ByteString.copyFrom(state.getContract().unsafeBitcoinSerialize()));
    try {
        // Make an initial payment of the dust limit, and put it into the message as well. The size of the
        // server-requested dust limit was already sanity checked by this point.
        PaymentChannelClientState.IncrementedPayment payment = state().incrementPaymentBy(Coin.valueOf(minPayment), userKey);
        Protos.UpdatePayment.Builder initialMsg = contractMsg.getInitialPaymentBuilder();
        initialMsg.setSignature(ByteString.copyFrom(payment.signature.encodeToBitcoin()));
        initialMsg.setClientChangeValue(state.getValueRefunded().value);
    } catch (ValueOutOfRangeException e) {
        throw new IllegalStateException(e);  // This cannot happen.
    }

    final Protos.TwoWayChannelMessage.Builder msg = Protos.TwoWayChannelMessage.newBuilder();
    msg.setProvideContract(contractMsg);
    msg.setType(Protos.TwoWayChannelMessage.MessageType.PROVIDE_CONTRACT);
    conn.sendToServer(msg.build());
}
 
Example #19
Source File: PaymentChannelServer.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@GuardedBy("lock")
private void receiveCloseMessage() throws InsufficientMoneyException {
    log.info("Got CLOSE message, closing channel");
    if (state != null) {
        settlePayment(CloseReason.CLIENT_REQUESTED_CLOSE);
    } else {
        conn.destroyConnection(CloseReason.CLIENT_REQUESTED_CLOSE);
    }
}
 
Example #20
Source File: PaymentChannelServer.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@GuardedBy("lock")
private void receiveCloseMessage() throws InsufficientMoneyException {
    log.info("Got CLOSE message, closing channel");
    if (state != null) {
        settlePayment(CloseReason.CLIENT_REQUESTED_CLOSE);
    } else {
        conn.destroyConnection(CloseReason.CLIENT_REQUESTED_CLOSE);
    }
}
 
Example #21
Source File: PaymentChannelClient.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@GuardedBy("lock")
private void receiveRefund(Protos.TwoWayChannelMessage refundMsg, @Nullable KeyParameter userKey) throws VerificationException {
    checkState(majorVersion == 1);
    checkState(step == InitStep.WAITING_FOR_REFUND_RETURN && refundMsg.hasReturnRefund());
    log.info("Got RETURN_REFUND message, providing signed contract");
    Protos.ReturnRefund returnedRefund = refundMsg.getReturnRefund();
    // Cast is safe since we've checked the version number
    ((PaymentChannelV1ClientState)state).provideRefundSignature(returnedRefund.getSignature().toByteArray(), userKey);
    step = InitStep.WAITING_FOR_CHANNEL_OPEN;

    // Before we can send the server the contract (ie send it to the network), we must ensure that our refund
    // transaction is safely in the wallet - thus we store it (this also keeps it up-to-date when we pay)
    state.storeChannelInWallet(serverId);

    Protos.ProvideContract.Builder contractMsg = Protos.ProvideContract.newBuilder()
            .setTx(ByteString.copyFrom(state.getContract().unsafeBitcoinSerialize()));
    try {
        // Make an initial payment of the dust limit, and put it into the message as well. The size of the
        // server-requested dust limit was already sanity checked by this point.
        PaymentChannelClientState.IncrementedPayment payment = state().incrementPaymentBy(Coin.valueOf(minPayment), userKey);
        Protos.UpdatePayment.Builder initialMsg = contractMsg.getInitialPaymentBuilder();
        initialMsg.setSignature(ByteString.copyFrom(payment.signature.encodeToBitcoin()));
        initialMsg.setClientChangeValue(state.getValueRefunded().value);
    } catch (ValueOutOfRangeException e) {
        throw new IllegalStateException(e);  // This cannot happen.
    }

    final Protos.TwoWayChannelMessage.Builder msg = Protos.TwoWayChannelMessage.newBuilder();
    msg.setProvideContract(contractMsg);
    msg.setType(Protos.TwoWayChannelMessage.MessageType.PROVIDE_CONTRACT);
    conn.sendToServer(msg.build());
}
 
Example #22
Source File: Publisher.java    From nsq-j with MIT License 5 votes vote down vote up
@GuardedBy("this")
private void connect(HostAndPort host) throws IOException {
    if (con != null) {
        con.close();
    }
    con = new PubConnection(client, host, this);
    con.connect(config);
    logger.info("publisher connected:{}", host);
}
 
Example #23
Source File: Publisher.java    From nsq-j with MIT License 5 votes vote down vote up
@GuardedBy("this")
private void checkConnection() throws IOException {
    if (con == null) {
        if (isStopping) {
            throw new NSQException("publisher stopped");
        }
        connect(nsqd);
    }
    else if (isFailover && Util.clock() - failoverStart > failoverDurationSecs * 1000) {
        isFailover = false;
        connect(nsqd);
        logger.info("using primary nsqd");
    }
}
 
Example #24
Source File: SubConnection.java    From nsq-j with MIT License 5 votes vote down vote up
@GuardedBy("this")
private void checkFlush() throws IOException {
    if (unflushedCount >= maxUnflushed) {
        flush();
    }
    else {
        unflushedCount++;
    }
}
 
Example #25
Source File: SubConnection.java    From nsq-j with MIT License 5 votes vote down vote up
@GuardedBy("this")
private void messageDone() throws IOException {
    inFlight = Math.max(inFlight - 1, 0);
    if (inFlight == 0 && isStopping) {
        flushAndClose();
    }
    else {
        checkFlush();
    }
}
 
Example #26
Source File: PaymentChannelClient.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@GuardedBy("lock")
private void receiveRefund(Protos.TwoWayChannelMessage refundMsg, @Nullable KeyParameter userKey) throws VerificationException {
    checkState(majorVersion == 1);
    checkState(step == InitStep.WAITING_FOR_REFUND_RETURN && refundMsg.hasReturnRefund());
    log.info("Got RETURN_REFUND message, providing signed contract");
    Protos.ReturnRefund returnedRefund = refundMsg.getReturnRefund();
    // Cast is safe since we've checked the version number
    ((PaymentChannelV1ClientState)state).provideRefundSignature(returnedRefund.getSignature().toByteArray(), userKey);
    step = InitStep.WAITING_FOR_CHANNEL_OPEN;

    // Before we can send the server the contract (ie send it to the network), we must ensure that our refund
    // transaction is safely in the wallet - thus we store it (this also keeps it up-to-date when we pay)
    state.storeChannelInWallet(serverId);

    Protos.ProvideContract.Builder contractMsg = Protos.ProvideContract.newBuilder()
            .setTx(ByteString.copyFrom(state.getContract().unsafeBitcoinSerialize()));
    try {
        // Make an initial payment of the dust limit, and put it into the message as well. The size of the
        // server-requested dust limit was already sanity checked by this point.
        PaymentChannelClientState.IncrementedPayment payment = state().incrementPaymentBy(Coin.valueOf(minPayment), userKey);
        Protos.UpdatePayment.Builder initialMsg = contractMsg.getInitialPaymentBuilder();
        initialMsg.setSignature(ByteString.copyFrom(payment.signature.encodeToBitcoin()));
        initialMsg.setClientChangeValue(state.getValueRefunded().value);
    } catch (ValueOutOfRangeException e) {
        throw new IllegalStateException(e);  // This cannot happen.
    }

    final Protos.TwoWayChannelMessage.Builder msg = Protos.TwoWayChannelMessage.newBuilder();
    msg.setProvideContract(contractMsg);
    msg.setType(Protos.TwoWayChannelMessage.MessageType.PROVIDE_CONTRACT);
    conn.sendToServer(msg.build());
}
 
Example #27
Source File: PaymentChannelServer.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@GuardedBy("lock")
private void receiveCloseMessage() throws InsufficientMoneyException {
    log.info("Got CLOSE message, closing channel");
    if (state != null) {
        settlePayment(CloseReason.CLIENT_REQUESTED_CLOSE);
    } else {
        conn.destroyConnection(CloseReason.CLIENT_REQUESTED_CLOSE);
    }
}
 
Example #28
Source File: Connection.java    From nsq-j with MIT License 4 votes vote down vote up
@GuardedBy("this")
protected void flush() throws IOException {
    out.flush();
    lastActionFlush = Util.clock();
    unflushedCount = 0;
}
 
Example #29
Source File: Connection.java    From nsq-j with MIT License 4 votes vote down vote up
@GuardedBy("this")
protected void write(byte[] data) throws IOException {
    out.writeInt(data.length);
    out.write(data);
}
 
Example #30
Source File: Connection.java    From nsq-j with MIT License 4 votes vote down vote up
@GuardedBy("this")
protected void writeCommand(String cmd, Object param) throws IOException {
    out.write((cmd + " " +  param + "\n").getBytes(Util.US_ASCII));
}