org.bitcoinj.core.Context Java Examples

The following examples show how to use org.bitcoinj.core.Context. 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: WalletsSetup.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public void restoreSeedWords(@Nullable DeterministicSeed seed,
                             ResultHandler resultHandler,
                             ExceptionHandler exceptionHandler) {
    checkNotNull(seed, "Seed must be not be null.");

    backupWallets();

    Context ctx = Context.get();
    new Thread(() -> {
        try {
            Context.propagate(ctx);
            walletConfig.stopAsync();
            walletConfig.awaitTerminated();
            initialize(seed, resultHandler, exceptionHandler);
        } catch (Throwable t) {
            t.printStackTrace();
            log.error("Executing task failed. " + t.getMessage());
        }
    }, "RestoreBTCWallet-%d").start();
}
 
Example #2
Source File: WalletsSetup.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
public void restoreSeedWords(@Nullable DeterministicSeed seed, ResultHandler resultHandler, ExceptionHandler exceptionHandler) {
    checkNotNull(seed, "Seed must be not be null.");

    backupWallets();

    Context ctx = Context.get();
    new Thread(() -> {
        try {
            Context.propagate(ctx);
            walletConfig.stopAsync();
            walletConfig.awaitTerminated();
            initialize(seed, resultHandler, exceptionHandler);
        } catch (Throwable t) {
            t.printStackTrace();
            log.error("Executing task failed. " + t.getMessage());
        }
    }, "RestoreBTCWallet-%d").start();
}
 
Example #3
Source File: NetworkThreadFactoryTest.java    From cate with MIT License 6 votes vote down vote up
/**
 * Generate a thread and confirm the context is set on it.
 */
@Test
public void shouldSetContextOnThread() throws InterruptedException {
    final Context expected = new Context(TestNet3Params.get());
    final Context broken = new Context(DogecoinTestNet3Params.get());
    final NetworkThreadFactory factory = new NetworkThreadFactory(expected);

    // Progagate the wrong context onto this thread
    Context.propagate(broken);
    assertEquals(broken, Context.get());

    final ThreadMonitor monitor = new ThreadMonitor();
    final Thread thread = factory.newThread(monitor);
    thread.run();
    thread.join();
    
    assertEquals(expected, monitor.actual);
}
 
Example #4
Source File: NetworkThreadFactory.java    From cate with MIT License 6 votes vote down vote up
@Override
public Thread newThread(Runnable r) {
    final String name = context.getParams().getId() + " worker #"
            + (++threadCount);
    final Thread thread = new Thread(group, () -> {
        Context.propagate(context);
        r.run();
    }, name);

    if (uncaughtExceptionHandler != null) {
        thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
    }
    thread.setDaemon(true);

    return thread;
}
 
Example #5
Source File: WalletConfig.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void shutDown() throws Exception {
    // Runs in a separate thread.
    try {
        Context.propagate(context);
        vPeerGroup.stop();
        vBtcWallet.saveToFile(vBtcWalletFile);
        if (vBsqWallet != null && vBsqWalletFile != null)
            //noinspection ConstantConditions,ConstantConditions
            vBsqWallet.saveToFile(vBsqWalletFile);
        vStore.close();

        vPeerGroup = null;
        vBtcWallet = null;
        vBsqWallet = null;
        vStore = null;
        vChain = null;
    } catch (BlockStoreException e) {
        throw new IOException(e);
    } catch (Throwable ignore) {
    }
}
 
Example #6
Source File: WalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @param serializedTransaction The serialized transaction to be added to the wallet
 * @return The transaction we added to the wallet, which is different as the one we passed as argument!
 * @throws VerificationException
 */
public static Transaction maybeAddTxToWallet(byte[] serializedTransaction,
                                             Wallet wallet,
                                             TransactionConfidence.Source source) throws VerificationException {
    Transaction tx = new Transaction(wallet.getParams(), serializedTransaction);
    Transaction walletTransaction = wallet.getTransaction(tx.getHash());

    if (walletTransaction == null) {
        // We need to recreate the transaction otherwise we get a null pointer...
        tx.getConfidence(Context.get()).setSource(source);
        //wallet.maybeCommitTx(tx);
        wallet.receivePending(tx, null, true);
        return tx;
    } else {
        return walletTransaction;
    }
}
 
Example #7
Source File: WalletConfig.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void shutDown() throws Exception {
    // Runs in a separate thread.
    try {
        Context.propagate(context);
        vPeerGroup.stop();
        vBtcWallet.saveToFile(vBtcWalletFile);
        if (vBsqWallet != null && vBsqWalletFile != null)
            //noinspection ConstantConditions,ConstantConditions
            vBsqWallet.saveToFile(vBsqWalletFile);
        vStore.close();

        vPeerGroup = null;
        vBtcWallet = null;
        vBsqWallet = null;
        vStore = null;
        vChain = null;
    } catch (BlockStoreException e) {
        throw new IOException(e);
    } catch (Throwable ignore) {
    }
}
 
Example #8
Source File: WalletAppKitService.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Inject
public WalletAppKitService(NetworkParameters params,
                           Context context,
                           WalletAppKit kit) {
    this.netParams = params;
    this.context = context;
    this.kit = kit;
}
 
Example #9
Source File: LNPaymentLogicImplTest.java    From thundernetwork with GNU Affero General Public License v3.0 5 votes vote down vote up
@Before
public void prepare () {
    Context.getOrCreate(Constants.getNetwork());

    node1 = new NodeClient();
    node2 = new NodeClient();

    node1.isServer = false;
    node2.isServer = true;

    node1.name = "LNPayment1";
    node2.name = "LNPayment2";

    messageFactory1 = new LNPaymentMessageFactoryImpl(dbHandler1);
    messageFactory2 = new LNPaymentMessageFactoryImpl(dbHandler2);

    channel1 = new Channel();
    channel2 = new Channel();

    channel1.channelStatus.applyConfiguration(configuration);
    channel2.channelStatus.applyConfiguration(configuration);

    channel1.retrieveDataFromOtherChannel(channel2);
    channel2.retrieveDataFromOtherChannel(channel1);

    paymentLogic1 = new LNPaymentLogicImpl(messageFactory1, dbHandler1);
    paymentLogic2 = new LNPaymentLogicImpl(messageFactory2, dbHandler2);

    paymentLogic1.initialise(channel1);
    paymentLogic2.initialise(channel2);
}
 
Example #10
Source File: BitcoinConfig.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Bean
public Context getContext(NetworkParameters params) {
    log.info("Creating context with {}", params.getId());
    Context context = new Context(params);
    log.info("Context is {}", context.getParams().getId());
    return context;
}
 
Example #11
Source File: PaymentSessionTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    new Context(TESTNET);
    serverKey = new ECKey();
    tx = new Transaction(TESTNET);
    outputToMe = new TransactionOutput(TESTNET, tx, coin, serverKey);
    tx.addOutput(outputToMe);
}
 
Example #12
Source File: BitcoinFactory.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Singleton
public WalletAppKitService walletAppKitService(NetworkParameters params, Context context, WalletAppKit kit) {
    log.info("Returning WalletAppKitService bean");
    WalletAppKitService service = new WalletAppKitService(params, context, kit);
    service.start();
    return service;
}
 
Example #13
Source File: LNPaymentLogicImplTest.java    From thunder with GNU Affero General Public License v3.0 5 votes vote down vote up
@Before
    public void prepare () {
        Context.getOrCreate(Constants.getNetwork());

        node1 = new ClientObject();
        node2 = new ClientObject();

        node1.isServer = false;
        node2.isServer = true;

        node1.name = "LNPayment1";
        node2.name = "LNPayment2";

        messageFactory1 = new LNPaymentMessageFactoryImpl(dbHandler1);
        messageFactory2 = new LNPaymentMessageFactoryImpl(dbHandler2);

        channel1 = getMockChannel();
        channel2 = getMockChannel();

//        channel1.channelStatus.applyConfiguration(configuration);
//        channel2.channelStatus.applyConfiguration(configuration);

        channel1.retrieveDataFromOtherChannel(channel2);
        channel2.retrieveDataFromOtherChannel(channel1);

        paymentLogic1 = new LNPaymentLogicImpl(messageFactory1, dbHandler1);
        paymentLogic2 = new LNPaymentLogicImpl(messageFactory2, dbHandler2);

        paymentLogic1.initialise(channel1);
        paymentLogic2.initialise(channel2);
    }
 
Example #14
Source File: Network.java    From cate with MIT License 5 votes vote down vote up
/**
 * @param context context this network manages.
 * @param controller the controller to push events back to.
 * @param directory the data directory to store the wallet and SPV chain in.
 * @param networkExecutor executor for tasks belonging to this network.
 * Must exist after the lifecycle of network (so that service status listeners
 * can be attached to it).
 */
public Network(final Context context, final MainController controller,
        final File directory, final Executor networkExecutor,
        final BiConsumer<Network, Wallet> registerWalletHook) {
    super(context, directory, "cate_" + context.getParams().getId());
    this.controller = controller;
    this.networkExecutor = networkExecutor;
    autoStop = false;
    blockingStartup = true;
    this.registerWalletHook = registerWalletHook;

    monetaryFormatter = context.getParams().getMonetaryFormat();
    addListener(new Service.Listener() {
        @Override
        public void running() {
            estimatedBalance.set(monetaryFormatter.format(wallet().getBalance(Wallet.BalanceType.ESTIMATED)).toString());
            try {
                blocks.set(store().getChainHead().getHeight());
            } catch (BlockStoreException ex) {
                logger.error("Error getting current chain head while starting wallet "
                        + params.getId(), ex);
            }
            encrypted.set(wallet().isEncrypted());
        }

        @Override
        public void failed(Service.State from, Throwable failure) {
            controller.onNetworkFailed(Network.this, from, failure);
        }
    }, networkExecutor);
}
 
Example #15
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @param serializedTransaction The serialized transaction to be added to the wallet
 * @return The transaction we added to the wallet, which is different as the one we passed as argument!
 * @throws VerificationException
 */
public Transaction addTxToWallet(byte[] serializedTransaction) throws VerificationException {
    Log.traceCall();

    // We need to recreate the tx otherwise we get a null pointer...
    Transaction transaction = new Transaction(params, serializedTransaction);
    transaction.getConfidence(Context.get()).setSource(TransactionConfidence.Source.NETWORK);
    log.trace("transaction from serializedTransaction: " + transaction.toString());

    if (wallet != null)
        wallet.receivePending(transaction, null, true);
    return transaction;
}
 
Example #16
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @param transaction The transaction to be added to the wallet
 * @return The transaction we added to the wallet, which is different as the one we passed as argument!
 * @throws VerificationException
 */
public Transaction addTxToWallet(Transaction transaction) throws VerificationException {
    Log.traceCall("transaction " + transaction.toString());

    // We need to recreate the transaction otherwise we get a null pointer...
    Transaction result = new Transaction(params, transaction.bitcoinSerialize());
    result.getConfidence(Context.get()).setSource(TransactionConfidence.Source.SELF);

    if (wallet != null)
        wallet.receivePending(result, null, true);
    return result;
}
 
Example #17
Source File: NetworkThreadFactory.java    From cate with MIT License 5 votes vote down vote up
/**
 * @param context context to propagate to all threads created by this factory.
 */
public NetworkThreadFactory(final Context context) {
    assert context != null;
    this.context = context;
    this.group = new ThreadGroup(context.getParams().getId() + " threads");
    this.uncaughtExceptionHandler = null;
}
 
Example #18
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
public Transaction estimateBtcTradingFeeTxSize(Address fundingAddress,
                                               Address reservedForTradeAddress,
                                               Address changeAddress,
                                               Coin reservedFundsForOffer,
                                               boolean useSavingsWallet,
                                               Coin tradingFee,
                                               Coin txFee,
                                               String feeReceiverAddresses)
        throws InsufficientMoneyException, AddressFormatException {
    Transaction tradingFeeTx = new Transaction(params);
    tradingFeeTx.addOutput(tradingFee, Address.fromBase58(params, feeReceiverAddresses));
    tradingFeeTx.addOutput(reservedFundsForOffer, reservedForTradeAddress);

    SendRequest sendRequest = SendRequest.forTx(tradingFeeTx);
    sendRequest.shuffleOutputs = false;
    sendRequest.aesKey = aesKey;
    if (useSavingsWallet)
        sendRequest.coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE));
    else
        sendRequest.coinSelector = new BtcCoinSelector(fundingAddress);

    sendRequest.fee = txFee;
    sendRequest.feePerKb = Coin.ZERO;
    sendRequest.ensureMinRequiredFee = false;
    sendRequest.changeAddress = changeAddress;
    checkNotNull(wallet, "Wallet must not be null");
    log.info("estimateBtcTradingFeeTxSize");
    wallet.completeTx(sendRequest);
    return tradingFeeTx;
}
 
Example #19
Source File: LevelDBBlockStoreTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void basics() throws Exception {
    File f = File.createTempFile("leveldbblockstore", null);
    f.delete();

    Context context = new Context(UNITTEST);
    LevelDBBlockStore store = new LevelDBBlockStore(context, f);
    store.reset();

    // Check the first block in a new store is the genesis block.
    StoredBlock genesis = store.getChainHead();
    assertEquals(UNITTEST.getGenesisBlock(), genesis.getHeader());
    assertEquals(0, genesis.getHeight());

    // Build a new block.
    Address to = LegacyAddress.fromBase58(UNITTEST, "mrj2K6txjo2QBcSmuAzHj4nD1oXSEJE1Qo");
    StoredBlock b1 = genesis.build(genesis.getHeader().createNextBlock(to).cloneAsHeader());
    store.put(b1);
    store.setChainHead(b1);
    store.close();

    // Check we can get it back out again if we rebuild the store object.
    store = new LevelDBBlockStore(context, f);
    try {
        StoredBlock b2 = store.get(b1.getHeader().getHash());
        assertEquals(b1, b2);
        // Check the chain head was stored correctly also.
        StoredBlock chainHead = store.getChainHead();
        assertEquals(b1, chainHead);
    } finally {
        store.close();
        store.destroy();
    }
}
 
Example #20
Source File: TestWithWallet.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public void setUp() throws Exception {
    BriefLogFormatter.init();
    Context.propagate(new Context(UNITTEST, 100, Coin.ZERO, false));
    wallet = new Wallet(UNITTEST);
    myKey = wallet.currentReceiveKey();
    myAddress = LegacyAddress.fromKey(UNITTEST, myKey);
    blockStore = new MemoryBlockStore(UNITTEST);
    chain = new BlockChain(UNITTEST, wallet, blockStore);
}
 
Example #21
Source File: WalletConfig.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public WalletConfig(NetworkParameters params,
                    Socks5Proxy socks5Proxy,
                    File directory,
                    Config config,
                    LocalBitcoinNode localBitcoinNode,
                    String userAgent,
                    int numConnectionsForBtc,
                    @SuppressWarnings("SameParameterValue") String btcWalletFileName,
                    @SuppressWarnings("SameParameterValue") String bsqWalletFileName,
                    @SuppressWarnings("SameParameterValue") String spvChainFileName) {
    this.config = config;
    this.localBitcoinNode = localBitcoinNode;
    this.userAgent = userAgent;
    this.numConnectionsForBtc = numConnectionsForBtc;
    this.context = new Context(params);
    this.params = checkNotNull(context.getParams());
    this.directory = checkDir(directory);
    this.btcWalletFileName = checkNotNull(btcWalletFileName);
    this.bsqWalletFileName = bsqWalletFileName;
    this.spvChainFileName = spvChainFileName;
    this.socks5Proxy = socks5Proxy;

    walletFactory = new BisqWalletFactory() {
        @Override
        public Wallet create(NetworkParameters params, KeyChainGroup keyChainGroup) {
            // This is called when we load an existing wallet
            // We have already the chain here so we can use this to distinguish.
            List<DeterministicKeyChain> deterministicKeyChains = keyChainGroup.getDeterministicKeyChains();
            if (!deterministicKeyChains.isEmpty() && deterministicKeyChains.get(0) instanceof BisqDeterministicKeyChain) {
                return new BsqWallet(params, keyChainGroup);
            } else {
                return new Wallet(params, keyChainGroup);
            }
        }

        @Override
        public Wallet create(NetworkParameters params, KeyChainGroup keyChainGroup, boolean isBsqWallet) {
            // This is called at first startup when we create the wallet
            if (isBsqWallet) {
                return new BsqWallet(params, keyChainGroup);
            } else {
                return new Wallet(params, keyChainGroup);
            }
        }
    };

    String path = null;
    if (params.equals(MainNetParams.get())) {
        // Checkpoints are block headers that ship inside our app: for a new user, we pick the last header
        // in the checkpoints file and then download the rest from the network. It makes things much faster.
        // Checkpoint files are made using the BuildCheckpoints tool and usually we have to download the
        // last months worth or more (takes a few seconds).
        path = "/wallet/checkpoints.txt";
    } else if (params.equals(TestNet3Params.get())) {
        path = "/wallet/checkpoints.testnet.txt";
    }
    if (path != null) {
        try {
            setCheckpoints(getClass().getResourceAsStream(path));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
        }
    }
}
 
Example #22
Source File: WalletsSetup.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public Set<Address> getAddressesByContext(@SuppressWarnings("SameParameterValue") AddressEntry.Context context) {
    return ImmutableList.copyOf(addressEntryList.getList()).stream()
            .filter(addressEntry -> addressEntry.getContext() == context)
            .map(AddressEntry::getAddress)
            .collect(Collectors.toSet());
}
 
Example #23
Source File: NetworkThreadFactoryTest.java    From cate with MIT License 4 votes vote down vote up
public void run() {
    actual = Context.get();
}
 
Example #24
Source File: NamecoinConfig.java    From consensusj with Apache License 2.0 4 votes vote down vote up
@Bean
public WalletAppKitService walletAppKitService(NetworkParameters params, Context context, WalletAppKit kit) {
    return new WalletAppKitService(params, context, kit);
}
 
Example #25
Source File: NamecoinConfig.java    From consensusj with Apache License 2.0 4 votes vote down vote up
@Bean
public Context getContext(NetworkParameters params) {
    return new Context(params);
}
 
Example #26
Source File: BitcoinConfig.java    From consensusj with Apache License 2.0 4 votes vote down vote up
@Bean
public WalletAppKitService walletAppKitService(NetworkParameters params, Context context, WalletAppKit kit) {
    return new WalletAppKitService(params, context, kit);
}
 
Example #27
Source File: BlockHexDeserializer.java    From consensusj with Apache License 2.0 4 votes vote down vote up
public BlockHexDeserializer(NetworkParameters netParams) {
    this.context = new Context(netParams);
}
 
Example #28
Source File: BitcoinConfig.java    From consensusj with Apache License 2.0 4 votes vote down vote up
@Bean
PeerStompService peerStompService(Context context,
                                  PeerGroup peerGroup,
                                  SimpMessageSendingOperations messagingTemplate) {
    return new PeerStompService(context, peerGroup, messagingTemplate);
}
 
Example #29
Source File: BitcoinConfig.java    From consensusj with Apache License 2.0 4 votes vote down vote up
@Bean
public WalletAppKitService walletAppKitService(NetworkParameters params, Context context, WalletAppKit kit) {
    log.info("WalletAppKitService factory params are {}", params.getId());
    log.info("WalletAppKitService factory context is {}", context.getParams().getId());
    return new WalletAppKitService(params, context, kit);
}
 
Example #30
Source File: BitcoinConfig.java    From consensusj with Apache License 2.0 4 votes vote down vote up
@Bean
public Context getContext(NetworkParameters params) {
    return new Context(params);
}