Java 类org.bitcoinj.core.PeerGroup 实例源码

项目:BitcoinBlockExplorer    文件:Bitcoin.java   
public static void resume() {
    if (isInitialize == false)
        return;
    if (isPaused == false)
        return;
    isPaused = false;


    Log.d("BITCOINJ", "Create PeerGroup");
    peerGroup = new PeerGroup(netParams, blockChain);
    peerGroup.setUserAgent("PeerMonitor", "1.0");
    peerGroup.setMaxConnections(8);
    peerGroup.addPeerDiscovery(new DnsDiscovery(netParams));

    Log.d("BITCOINJ", "Start Asynchronous PeerGroup");
    peerGroup.start();
    Log.d("BITCOINJ", "Download Started");
    myDownload = new MyDownload();
    peerGroup.startBlockChainDownload(myDownload);

}
项目:bitnym    文件:ProofMessage.java   
public boolean isValidProof(BlockChain bc, PeerGroup pg, NetworkParameters params) {
    if(!isValidPath()) {
        System.out.println("path is not valid, thus proof not valid, abort");
        return false;
    }
    if(!isValidGPTx()) {
        System.out.println("gptx is not valid, abort");
        return false;
    }
    if(!isNymNotSpend(bc)) {
        System.out.println("nym is not locked anymore, consider spent, abort");
        return false;
    }
    if(!isNymTxInBlockChain(params, bc, pg)) {
        System.out.println("nymtx is not in blockchain, consider proof invalid, abort");
        return false;
    }
    System.out.println("proof seems valid");
    return true;
}
项目:payment-api    文件:BitcoinjConfiguration.java   
@Bean
public BlockChainService getBlockchainService(final NetworkParameters params,
                                              final BlockChain blockChain,
                                              final PeerGroup peerGroup,
                                              final TransactionStateService transactionService,
                                              final WalletDbService walletService,
                                              final AccountDbService accountService,
                                              final BlockchainSettings settings
                                              ){

    final BitcoinjBlockchainServiceImpl blockChainService =
            new BitcoinjBlockchainServiceImpl(params, blockChain, peerGroup, transactionService, walletService, accountService, settings);

    blockChainService.init();
    return blockChainService;
}
项目:libdohj    文件:NameLookupLatestLevelDBTransactionCache.java   
public NameLookupLatestLevelDBTransactionCache (Context context, File directory, DBFactory dbFactory, BlockChain chain, BlockStore store, PeerGroup peerGroup) throws IOException {
    this.chain = chain;
    this.store = store;
    this.peerGroup = peerGroup;

    this.context = context;
    this.params = context.getParams();

    this.path = directory;
    Options options = new Options();
    options.createIfMissing();

    try {
        tryOpen(directory, dbFactory, options);
    } catch (IOException e) {
        dbFactory.repair(directory, options);
        tryOpen(directory, dbFactory, options);
    }

    chain.addNewBestBlockListener(Threading.SAME_THREAD, this);
    chain.addReorganizeListener(Threading.SAME_THREAD, this);
    chain.addTransactionReceivedListener(Threading.SAME_THREAD, this);
}
项目:Wallet    文件:Authenticator.java   
/**
 * Full instantiation
 * 
 * @param wallet
 * @param peerGroup
 * @param appParams
 * @throws IOException
 * @throws AccountWasNotFoundException 
 */
public Authenticator(Wallet wallet, PeerGroup peerGroup, BAApplicationParameters appParams) {
    super(Authenticator.class);
    try {
        init(appParams);
        if(mWalletOperation == null){
            mWalletOperation = new WalletOperation(wallet,peerGroup,appParams);

            initPendingRequests();
        }

        init2();    
    }
    catch (Exception e) { 
        e.printStackTrace(); 
        throw new RuntimeException("Could not instantiate Authenticator");
    }

}
项目:dashj    文件:LevelDB.java   
public static void main(String[] args) throws Exception {
    /*
     * This is just a test runner that will download blockchain till block
     * 390000 then exit.
     */
    FullPrunedBlockStore store = new LevelDBFullPrunedBlockStore(
            MainNetParams.get(), args[0], 1000, 100 * 1024 * 1024l,
            10 * 1024 * 1024, 100000, true, 390000);

    FullPrunedBlockChain vChain = new FullPrunedBlockChain(
            MainNetParams.get(), store);
    vChain.setRunScripts(false);

    PeerGroup vPeerGroup = new PeerGroup(MainNetParams.get(), vChain);
    vPeerGroup.setUseLocalhostPeerWhenPossible(true);
    vPeerGroup.addAddress(InetAddress.getLocalHost());

    vPeerGroup.start();
    vPeerGroup.downloadBlockChain();
}
项目:dashj    文件:WatchMempool.java   
public static void main(String[] args) throws InterruptedException {
    BriefLogFormatter.init();
    PeerGroup peerGroup = new PeerGroup(PARAMS);
    peerGroup.setMaxConnections(32);
    peerGroup.addPeerDiscovery(new DnsDiscovery(PARAMS));
    peerGroup.addOnTransactionBroadcastListener(new OnTransactionBroadcastListener() {
        @Override
        public void onTransaction(Peer peer, Transaction tx) {
            Result result = DefaultRiskAnalysis.FACTORY.create(null, tx, NO_DEPS).analyze();
            incrementCounter(TOTAL_KEY);
            log.info("tx {} result {}", tx.getHash(), result);
            incrementCounter(result.name());
            if (result == Result.NON_STANDARD)
                incrementCounter(Result.NON_STANDARD + "-" + DefaultRiskAnalysis.isStandard(tx));
        }
    });
    peerGroup.start();

    while (true) {
        Thread.sleep(STATISTICS_FREQUENCY_MS);
        printCounters();
    }
}
项目:bitcoinj    文件:LevelDB.java   
public static void main(String[] args) throws Exception {
    /*
     * This is just a test runner that will download blockchain till block
     * 390000 then exit.
     */
    FullPrunedBlockStore store = new LevelDBFullPrunedBlockStore(
            MainNetParams.get(), args[0], 1000, 100 * 1024 * 1024l,
            10 * 1024 * 1024, 100000, true, 390000);

    FullPrunedBlockChain vChain = new FullPrunedBlockChain(
            MainNetParams.get(), store);
    vChain.setRunScripts(false);

    PeerGroup vPeerGroup = new PeerGroup(MainNetParams.get(), vChain);
    vPeerGroup.setUseLocalhostPeerWhenPossible(true);
    vPeerGroup.addAddress(InetAddress.getLocalHost());

    vPeerGroup.start();
    vPeerGroup.downloadBlockChain();
}
项目:bitcoinj    文件:WatchMempool.java   
public static void main(String[] args) throws InterruptedException {
    BriefLogFormatter.init();
    PeerGroup peerGroup = new PeerGroup(PARAMS);
    peerGroup.setMaxConnections(32);
    peerGroup.addPeerDiscovery(new DnsDiscovery(PARAMS));
    peerGroup.addOnTransactionBroadcastListener(new OnTransactionBroadcastListener() {
        @Override
        public void onTransaction(Peer peer, Transaction tx) {
            Result result = DefaultRiskAnalysis.FACTORY.create(null, tx, NO_DEPS).analyze();
            incrementCounter(TOTAL_KEY);
            log.info("tx {} result {}", tx.getHash(), result);
            incrementCounter(result.name());
            if (result == Result.NON_STANDARD)
                incrementCounter(Result.NON_STANDARD + "-" + DefaultRiskAnalysis.isStandard(tx));
        }
    });
    peerGroup.start();

    while (true) {
        Thread.sleep(STATISTICS_FREQUENCY_MS);
        printCounters();
    }
}
项目:bitnym    文件:TransactionGenerator.java   
public TransactionGenerator(NetworkParameters params, PeerGroup pg, Wallet w, BlockChain bc) {
    this.params = params;
    this.pg = pg;
    this.w = w;
    this.bc = bc;

}
项目:bitnym    文件:Mixer.java   
public Mixer(PTP ptp, BroadcastAnnouncement bca, ProofMessage pm, Wallet w, NetworkParameters params, PeerGroup pg, BlockChain bc) {
    this.ptp = ptp;
    this.bca = bca;
    this.mixPartnerAdress = new Identifier(bca.getOnionAdress() + ".onion");
    this.ownProof = pm;
    this.w = w;
    this.params = params;
    this.pg = pg;
    this.bc = bc;
    this.mfListeners = new ArrayList<MixFinishedEventListener>();
    this.lockTime = 0; 
}
项目:bitnym    文件:Mixer.java   
public Mixer(PTP ptp, String onionAddress, ProofMessage pm, Wallet w, NetworkParameters params, PeerGroup pg, BlockChain bc) {
    this.ptp = ptp;
    this.mixPartnerAdress = new Identifier(onionAddress);
    this.ownProof = pm;
    this.w = w;
    this.params = params;
    this.pg = pg;
    this.bc = bc;
    this.mfListeners = new ArrayList<MixFinishedEventListener>();
    this.lockTime = 0;

}
项目:bitnym    文件:Mixer.java   
public Mixer(PTP ptp, ProofMessage pm, Wallet w, NetworkParameters params, PeerGroup pg, BlockChain bc) {
    this.ptp = ptp;
    this.ownProof = pm;
    this.w = w;
    this.params = params;
    this.pg = pg;
    this.bc = bc;
    this.mfListeners = new ArrayList<MixFinishedEventListener>();
    this.lockTime = 0;
}
项目:bitnym    文件:ChallengeResponseVerifier.java   
public ChallengeResponseVerifier(PTP ptp, Wallet w, NetworkParameters params, PeerGroup pg, BlockChain bc) {
    this.ptp = ptp;
    this.w = w;
    this.params = params;
    this.pg = pg;
    this.bc = bc;
}
项目:bitnym    文件:MixPartnerDiscovery.java   
public MixPartnerDiscovery(NetworkParameters params, PeerGroup pg, BlockChain bc, Wallet wallet) {
    this.pg = pg;
    this.bc = bc;
    this.head = null;
    this.wallet = wallet;
    this.broadcasts = new ArrayList<Transaction>();
    this.listeners = new ArrayList<BroadcastAnnouncementChangeEventListener>();
}
项目:payment-api    文件:BitcoinjBlockchainServiceImplTest.java   
@Before
public void setUp() throws Exception {

    this.blockStore = new SPVBlockStore(this.params, new File("tbtc_blockstore"));
    final BlockChain chain = new BlockChain(new Context(this.params), this.blockStore);

    final PeerGroup peerGroup = new PeerGroup(this.params, chain);
    final BlockchainSettings settings = new BlockchainSettings(1, BigDecimal.ZERO, BigDecimal.TEN, "target", "central.wallet", "admin", "password");
    this.service = new BitcoinjBlockchainServiceImpl(this.params, chain, peerGroup, this.transactionService, this.walletService, this.accountService, settings);
    this.service.init();

    this.wallets.add(this.wallet);
    when(this.accountService.getByEmail("admin")).thenReturn(this.account);
    when(this.account.getWallets()).thenReturn(this.wallets);
    when(this.transactionService.getByReceiverHash(anyString())).thenReturn(this.transaction, this.transaction);
    when(this.wallet.toBuilder()).thenReturn(Wallet.builder());
    when(this.wallet.getContent()).thenAnswer(new Answer<String>() {
        @Override
        public String answer(final InvocationOnMock invocation) throws Throwable {
            counter ++;
            if (counter == 1) {
                return FileUtils.readFileToString(new File("src/test/resources/content.cnt"));
            }
            return FileUtils.readFileToString(new File("src/test/resources/content1.cnt"));
        }

    });
}
项目:consensusj    文件:PeerGroupService.java   
@Inject
public PeerGroupService(NetworkParameters params,
                   PeerDiscovery peerDiscovery) {
    this.netParams = params;
    this.peerGroup = new PeerGroup(params);
    peerGroup.setUserAgent(userAgentName, appVersion);
    peerGroup.addPeerDiscovery(peerDiscovery);
}
项目:EternityWallAndroid    文件:TimedLogStat.java   
@Override
public void run() {
    final WalletObservable walletObservable = ewApplication.getWalletObservable();

    if(walletObservable!=null) {
        Log.i(TAG, walletObservable.toString());
        final EWWalletService ewWalletService = ewApplication.getEwWalletService();
        if(ewWalletService.getBlockChain()!=null) {
            final int bestChainHeight = ewWalletService.getBlockChain().getBestChainHeight();
            Log.i(TAG, "blockchain height: " + bestChainHeight);
        }
        final PeerGroup peerGroup = ewWalletService.getPeerGroup();
        if(peerGroup !=null) {
            Log.i(TAG, "peerGroup is running? " + peerGroup.isRunning());
            Log.i(TAG, "peerGroup connected peers? " + peerGroup.numConnectedPeers());

        }
        final Wallet wallet = ewWalletService.getWallet();
        if(wallet !=null) {
            Log.i(TAG, "wallet height: " + wallet.getLastBlockSeenHeight());
            final Set<Transaction> transactions = wallet.getTransactions(true);
            final List<String> hashes=new LinkedList<>();
            for (Transaction tx : transactions) {
                hashes.add(tx.getHashAsString());
            }
            Log.i(TAG, "wallet txs: " + Joiner.on(",").join(hashes) );

        }
    } else {
        Log.i(TAG, "WalletObservable is null ()");
    }

}
项目:ostendo    文件:PeerListener.java   
/**
 * Starts a bitcoin network peer and begins to listen
 *
 * @throws BlockStoreException
 */
public void start() throws BlockStoreException {
    BlockChain blockChain = new BlockChain(NET_PARAMS, new MemoryBlockStore(NET_PARAMS));
    PeerGroup peerGroup = new PeerGroup(NET_PARAMS, blockChain);
    peerGroup.addPeerDiscovery(new DnsDiscovery(NET_PARAMS));
    peerGroup.addEventListener(peerEventListener);
    peerGroup.startAsync();


}
项目:Wallet    文件:BAWalletRestorer.java   
PeerGroup createPeerGroup() throws TimeoutException {
    if (useTor) {
        return PeerGroup.newWithTor(netParams, vChain, new TorClient());
    }
    else
        return new PeerGroup(netParams, vChain);
}
项目:Wallet    文件:WalletOperation.java   
/**
 * Instantiate WalletOperations with bitcoinj wallet
 * 
 * @param wallet
 * @param peerGroup
 * @throws IOException
 */
public WalletOperation(Wallet wallet, PeerGroup peerGroup, BAApplicationParameters params){
    super(WalletOperation.class);
    if(mWalletWrapper == null){
        mWalletWrapper = new WalletWrapper(wallet,peerGroup);
        mWalletWrapper.addEventListener(new WalletListener(WalletOperation.this));
    }

    init(params);
}
项目:uidcore-java    文件:NodeUtils.java   
/**
 * Synchronize a list of {@code Wallet} against the BlockChain.
 * 
 * @param params the NetworkParameters to use
 * @param wallets the list of Wallet
 * @param chainFile the chain file to use
 * @param listener the listener to inform for status changes
 */
public static void syncBlockChain(UniquidNodeConfiguration configuration, final List<Wallet> wallets, final File chainFile, 
        final DownloadProgressTracker listener, final NativePeerEventListener peerListener) {

    try {
        NetworkParameters params = configuration.getNetworkParameters();

        BlockStore chainStore = new SPVBlockStore(params, chainFile);

        for (Wallet wallet : wallets) {

            if ((wallet.getLastBlockSeenHeight() < 1) &&
                    (openStream(params) != null)) {

                try {

                    CheckpointManager.checkpoint(params, openStream(params), chainStore,
                            configuration.getCreationTime());

                    StoredBlock head = chainStore.getChainHead();
                    LOGGER.info("Skipped to checkpoint " + head.getHeight() + " at "
                             + Utils.dateTimeFormat(head.getHeader().getTimeSeconds() * 1000));

                } catch (Throwable t) {

                    LOGGER.warn("Problem using checkpoints", t);

                }

                break;
            }

        }

        BlockChain chain = new BlockChain(params, wallets, chainStore);

        final PeerGroup peerGroup = new PeerGroup(params, chain);
        peerGroup.setUserAgent("UNIQUID", "0.1");
        peerGroup.setMaxPeersToDiscoverCount(3);
        peerGroup.setMaxConnections(2);

        if (params.getDnsSeeds() != null &&
                params.getDnsSeeds().length > 0) {
            peerGroup.addPeerDiscovery(new DnsDiscovery(params));
        } else if (params.getAddrSeeds() != null &&
                    params.getAddrSeeds().length > 0) {
                        peerGroup.addPeerDiscovery(new SeedPeers(params.getAddrSeeds(), params));
        } else {
            throw new Exception("Problem with Peers discovery!");
        }

        LOGGER.info("BLOCKCHAIN Preparing to download blockchain...");

        peerGroup.addConnectedEventListener(peerListener);
        peerGroup.addDisconnectedEventListener(peerListener);
        peerGroup.addDiscoveredEventListener(peerListener);
        peerGroup.start();
        peerGroup.startBlockChainDownload(listener);
        listener.await();
        peerGroup.stop();
        chainStore.close();

        LOGGER.info("BLOCKCHAIN downloaded.");

    } catch (Exception ex) {

        LOGGER.error("Exception catched ", ex);

    }
}
项目:bitnym    文件:ProofMessage.java   
public boolean isProbablyValid(NetworkParameters params, BlockChain bc, PeerGroup pg) {
    return isValidPath() && isValidGPTx() && isNymTxInBlockChain(params, bc, pg);
}
项目:Shufflepuff    文件:Bitcoin.java   
public PeerGroup getPeerGroup(){
    return peerGroup;
}
项目:payment-api    文件:BitcoinjConfiguration.java   
@Bean
public PeerGroup getPeers(final NetworkParameters params,final BlockChain chain) {
    return new PeerGroup(params, chain);
}
项目:libdohj    文件:NameLookupByBlockHashOneFullBlock.java   
public NameLookupByBlockHashOneFullBlock (PeerGroup peerGroup) {
    this.peerGroup = peerGroup;
}
项目:libdohj    文件:NameLookupLatestLevelDBTransactionCache.java   
public NameLookupLatestLevelDBTransactionCache (Context context, File directory, BlockChain chain, BlockStore store, PeerGroup peerGroup) throws IOException {
    this(context, directory, JniDBFactory.factory, chain, store, peerGroup);
}
项目:EternityWallAndroid    文件:EWWalletService.java   
public PeerGroup getPeerGroup() {
    return peerGroup;
}
项目:EternityWallAndroid    文件:EWWalletServiceTest.java   
@Test
public void btcWalletTestWithCheckpoint() throws Exception {
    final byte[] seed = Bitcoin.getEntropyFromPassphrase("sweet field bless symptom play cherry fault curious mechanic cross gift thunder");
    EWDerivation ewDerivation = new EWDerivation(seed);

    final MainNetParams params = MainNetParams.get();
    final String blockpath  = "./spvblockstore"  + System.currentTimeMillis();
    //final File blockChainFile = new File(getDir("blockstore_" + receivingId, Context.MODE_PRIVATE), "blockchain.spvchain");
    //final String pathname = "./spvblockstore" + System.currentTimeMillis();
    //final String pathname = "./spvblockstore1448448596283";

    File blockFile = new File(blockpath);

    BlockStore blockStore = new SPVBlockStore(params, blockFile);
    StoredBlock chainHead = blockStore.getChainHead();
    if(chainHead.getHeight()==0) {  //first run
        CheckpointManager.checkpoint(PARAMS, BitcoinNetwork.getInstance().getCheckPointsStream() , blockStore, EPOCH);
    }
    //final StoredBlock checkpointBefore = manager.getCheckpointBefore(startFrom);
    //blockStore.setChainHead(checkpointBefore);

    Wallet wallet = new Wallet(PARAMS);

    BlockChain chain = new BlockChain(params, wallet, blockStore);
    //BlockChain chain = new BlockChain(params, blockStore);
    PeerGroup peerGroup = new PeerGroup(params, chain);
    //peerGroup.addAddress(InetAddress.getByName("10.106.137.73"));
    peerGroup.setMaxConnections(1);
    peerGroup.setDownloadTxDependencies(false);

    //peerGroup.addPeerDiscovery(new DnsDiscovery(params));
    //EWFilterProvider provider = new EWFilterProvider( );
    //System.out.println("provider " + provider);

    //peerGroup.addPeerFilterProvider(provider);

    DownloadProgressTracker downloadProgressTracker = new DownloadProgressTracker();


    EWChainListener listener = new EWChainListener();
    chain.addListener(listener);
    //peerGroup.setMaxConnections(10);

    peerGroup.setFastCatchupTimeSecs(EPOCH);  //24 Giugno 2015 12:00
    peerGroup.startBlockChainDownload(downloadProgressTracker);


    long startDownload = System.currentTimeMillis();
    peerGroup.downloadBlockChain();
    final long endDownload = System.currentTimeMillis() - startDownload;
    System.out.println("Download run for " + endDownload);

    System.out.println("---------FINISH----------");
    System.out.println("peerGroup.getConnectedPeers()=" + peerGroup.getConnectedPeers());
    System.out.println("blockpath " + blockpath);
    System.out.println("chain.getBestChainHeight()=" + chain.getBestChainHeight() );
    System.out.println("chainHeadHeightAtBeginning=" + chainHead.getHeight() );

    System.out.println("TX# " + listener.counter);


    //System.out.println("checkpointBefore.getHeight()=" + checkpointBefore.getHeight() );
    //System.out.println("Derivation took " + l);

    blockStore.close();
    //wallet.addFollowingAccountKeys(a,2);

}
项目:LockedTransactionServer    文件:WalletRunnable.java   
public static PeerGroup getPeergroup()
{
    if(appKit == null)
        log.error("appKit not initialized when peergroup requested.");
    return appKit.peerGroup();
}
项目:LockedTransactionServer    文件:WalletRunnable.java   
public static PeerGroup getTestPeergroup()
{
    if(testAppKit == null)
        log.error("appKit not initialized when peergroup requested.");
    return testAppKit.peerGroup();
}
项目:exchange    文件:Broadcaster.java   
public static void broadcastTx(Wallet wallet, PeerGroup peerGroup, Transaction tx, FutureCallback<Transaction> callback) {
    broadcastTx(wallet, peerGroup, tx, callback, DEFAULT_BROADCAST_TIMEOUT);
}
项目:exchange    文件:Broadcaster.java   
public static void broadcastTx(Wallet wallet, PeerGroup peerGroup, Transaction tx, FutureCallback<Transaction> callback, int timeoutInSec) {
    final Timer timeoutTimer;
    if (!broadcastTimerSet.contains(tx.getHashAsString())) {
        timeoutTimer = UserThread.runAfter(() -> {
            log.warn("Broadcast of tx {} not completed after {} sec. We optimistically assume that the tx broadcast succeeded and " +
                    "call onSuccess on the callback handler.", tx.getHashAsString(), timeoutInSec);

            wallet.maybeCommitTx(tx);

            callback.onSuccess(tx);

            broadcastTimerSet.remove(tx.getHashAsString());
        }, timeoutInSec);
        broadcastTimerSet.add(tx.getHashAsString());
    } else {
        timeoutTimer = null;
    }

    Futures.addCallback(peerGroup.broadcastTransaction(tx).future(), new FutureCallback<Transaction>() {
        @Override
        public void onSuccess(@Nullable Transaction result) {
            // At regtest we get called immediately back but we want to make sure that the handler is not called
            // before the caller is finished.
            UserThread.execute(() -> {
                if (broadcastTimerSet.contains(tx.getHashAsString())) {
                    // If the timeout has not been called we call the callback.onSuccess
                    stopAndRemoveTimer(timeoutTimer, tx);

                    if (result != null)
                        wallet.maybeCommitTx(result);

                    callback.onSuccess(tx);
                } else {
                    // Timeout was triggered, nothing to do anymore.
                    log.info("onSuccess for tx {} was already called from timeout handler. ", tx.getHashAsString());
                }
            });
        }

        @Override
        public void onFailure(@NotNull Throwable t) {
            UserThread.execute(() -> {
                stopAndRemoveTimer(timeoutTimer, tx);

                callback.onFailure(t);
            });
        }
    });
}
项目:Wallet    文件:WalletWrapper.java   
/**
 * If PeerGroup is Null, no broadcasting function is available
 * 
 * @param wallet
 * @param peerGroup
 */
public WalletWrapper(Wallet wallet, @Nullable PeerGroup peerGroup){
    super(WalletWrapper.class);
    this.trackedWallet = wallet;
    this.mPeerGroup = peerGroup;
}