2015-01-01 30 views
2

我的目標是手錶一個公共的比特幣地址,並打印到控制檯每當錢被髮送到該地址。就這樣。目前,我正在使用之前在Bitcoin Core中生成的地址。如何在Bitcoinj(java)中查看交易地址?

我做了以下內容:

NetworkParameters params = MainNetParams.get(); 
Wallet wallet = Wallet.loadFromFile(file); 
BlockStore blockStore = new MemoryBlockStore(params); 
BlockChain chain = new BlockChain(params, wallet, blockStore); 

PeerGroup peerGroup = new PeerGroup(params, chain); 
peerGroup.addPeerDiscovery(new DnsDiscovery(params)); 
peerGroup.setUseLocalhostPeerWhenPossible(true); 
peerGroup.startAsync(); 

Address add = new Address(params, "1NpxxxxxxxxxxxxxxxaSC4"); 
wallet.addWatchedAddress(add); 

wallet.addEventListener(new AbstractWalletEventListener() { 
     @Override 
     public synchronized void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) { 
      System.out.println("[main]: COINS RECIEVED!"); 
      System.out.println("\nReceived tx " + tx.getHashAsString()); 
      System.out.println(tx.toString()); 
     } 
    }); 

System.out.println("\nDone!\n"); 
System.out.println(wallet.toString()); 

我有我沒有正確處理AbstractWalletEventListener的感覺。當我向地址匯款時,我沒有看到我期望在控制檯中看到的文字。相反,我只是從peerGroup.startAsync()方法的[NioClientManager]中看到連續的「peer announce new transaction」。

我在做什麼錯,我該如何糾正它?我花了更多的時間比我應該做的事情看起來應該是這麼簡單的任務。

PS。我要求的「loadFromFile」文件只是由bitcoinj生成的一個空白的默認錢包文件。沒什麼特別的。

編輯:此外,我沒有看到錢包的總餘額。我只想知道何時進行新交易。舊計劃在我的計劃中無關緊要。

回答

2

我終於明白了。花了我很長時間。我決定只使用錢包應用工具包,而不是手動完成這些工作。這是我最後的代碼來做我想做的事(刪除公鑰和文件)。

final NetworkParameters params = MainNetParams.get(); 

try{ 

    //initialize files and stuff here 

    WalletAppKit kit = new WalletAppKit(params, wakfile, "_wak"); 
    kit.setAutoSave(true); 
    kit.connectToLocalHost(); 
    kit.startAsync(); 
    kit.awaitRunning(); 
    kit.peerGroup().addPeerDiscovery(new DnsDiscovery(params)); 
    kit.wallet().addWatchedAddress(new Address(params, "1NxxxxxxxxxxxxxxxxC4")); 
    kit.wallet().addEventListener(new AbstractWalletEventListener() { 
     @Override 
     public synchronized void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) { 
      System.out.println("[main]: COINS RECIEVED!"); 
      System.out.println("\nReceived tx " + tx.getHashAsString()); 
      System.out.println(tx.toString()); 
     } 
    }); 
} catch (IOException e) { 
    e.printStackTrace(); 
} catch (AddressFormatException e) { 
    e.printStackTrace(); 
} 

爲什麼這個工程,我發佈的東西沒有,我仍然不完全確定。我肯定錯過了什麼。如果你通過這篇文章來了解並知道我在上面做錯了什麼,請告訴我。它對未來的參考仍然有用。