Search code examples
javabitcoin

How to get the address the sender sent bitcoin to


Basicly, I'm building a server which has a bitcoin wallet with many receive addresses. The addresses can be linked to different clients.

If you send coins to any address they are gonna end up into the servers wallet.

The question is, how do I know what was the address the bitcoin sender sent the coins?

I'm using BitconJ. The server is written in Java.


Solution

  • I figured it out myself. This is my code for figuring out to which address the amount was sent to.

                    @Override
                    public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
                        System.out.println("Received a transaction.");
                        for (int i = 0; i < tx.getOutputs().size(); i++) {
                            for (ECKey addr : wallet().getImportedKeys()) {
                                Address expectedAddr = addr.toAddress(Main.PARAMS);
                                for (int j = 0; j < tx.getOutputs().size(); j++) 
                                    String incoming = tx.getOutputs().get(i).getAddressFromP2PKHScript(Main.PARAMS)
                                            .toBase58();
                                    if (incoming.equals(expectedAddr)){
                                     // Enter your code here
                                    }
                                }
                            }
                        }
                    }
    

    You might notice that I actually need to know what I'm looking for in the transaction outputs.