I'am trying to send transaction by wallet, there are 3 steps in my code:
1. create transaction;
2. sign transaction;
3. send transaction.
but in step3, by bitcoinj test code,  in 
WalletTest.java, sendCoinsWithBroadcasterTest(), there is a 
function receiveATransactionAmount(wallet, myAddress, Coin.COIN), how to 
replace FakeTxBuilder.BlockPair?

step1: create transaction

public Transaction createTransaction(List<SendIn> sendInList,
List<SendOut> sendOutList) {
NetworkParameters networkParameters = null;
if (testNet)
networkParameters = NetworkParameters.testNet3();
else {
networkParameters = NetworkParameters.prodNet();
}

Transaction tx = new Transaction(networkParameters);

try {
for (int i = 0; i < sendInList.size(); i++) {
String address = sendInList.get(i).getAddress();
String txHashStr = sendInList.get(i).getTxHash();

// Sha256Hash txHash = Sha256Hash.wrap(txHashStr);
// Wallet wallet = new Wallet(networkParameters);
// Transaction transaction = wallet.getTransaction(txHash);
// String txRaw;
// if (transaction == null) {
// txRaw = null;
// break;
// } else {
// txRaw = transaction.toString();
// }

String txRaw = getTxData(txHashStr);

byte[] bytes = Utils.HEX.decode(txRaw);
Transaction spentTx = new Transaction(networkParameters, bytes);
for (int j = 0; j < spentTx.getOutputs().size(); j++) {
if (address.equals(spentTx.getOutput(j).getScriptPubKey()
.getToAddress(networkParameters).toString())) {
tx.addInput(spentTx.getOutput(j));
break;
}
}
}

for (int i = 0; i < sendOutList.size(); i++) {
String addressJson = sendOutList.get(i).getAddress();
String coinJson = sendOutList.get(i).getValue().toString();
Address address = new Address(networkParameters, addressJson);
Coin coin = org.bitcoinj.core.Coin.parseCoin(coinJson);
tx.addOutput(coin, address);
}
} catch (Exception e) {
e.printStackTrace();
}

return tx;
}

step2: sign transaction
 
public String sign(List<String> privateKeys, Transaction tx)
throws Exception {
NetworkParameters networkParameters = null;
if (testNet)
networkParameters = NetworkParameters.testNet3();
else {
networkParameters = NetworkParameters.prodNet();
}

try {
Wallet wallet = new Wallet(networkParameters);
for (String privateKey : privateKeys) {
DumpedPrivateKey key = new DumpedPrivateKey(networkParameters,
privateKey);
wallet.addKey(key.getKey());
}

SendRequest req = SendRequest.forTx(tx);
wallet.signTransaction(req);

byte[] txRawBytes = tx.bitcoinSerialize();
String txSignData = Utils.HEX.encode(txRawBytes);

return txSignData;
} catch (Exception e) {
System.out.println(e.getMessage());
}

return null;
}

step3:  send transaction

public String sendTx(String signTx) throws Exception {
NetworkParameters networkParameters = null;
if (testNet) {
networkParameters = NetworkParameters.testNet3();
} else {
networkParameters = NetworkParameters.prodNet();
}

byte[] txRawBytes = Utils.HEX.decode(signTx);
Transaction tx = new Transaction(networkParameters, txRawBytes);
TransactionInput txIn = tx.getInputs().get(0);
TransactionOutput txOut = tx.getOutputs().get(0);
// tx add to wallet
WalletTransaction wtx = new WalletTransaction(Pool.PENDING, tx);
Wallet wallet = new Wallet(networkParameters);
wallet.addWalletTransaction(wtx);
SendRequest req = SendRequest.forTx(tx); 
Address myAddress = 
wallet.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
// receiveATransactionAmount(wallet, myAddress, Coin.CENT); // 0.01 比特币
Transaction t1 = sendMoneyToWallet(wallet, null, Coin.CENT, myAddress);
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, t1);
wallet.completeTx(req);
wallet.commitTx(req.tx);
TransactionBroadcaster broadcaster = new PeerGroup(networkParameters);
// MockTransactionBroadcaster broadcaster = new 
MockTransactionBroadcaster(wallet);
wallet.setTransactionBroadcaster(broadcaster);
SendResult result = wallet.sendCoins(req);
        
        return result.toString();
}

@Nullable
private Transaction sendMoneyToWallet(Wallet wallet, 
AbstractBlockChain.NewBlockType type, Transaction... transactions)
            throws VerificationException {
MemoryBlockStore blockStore = new 
MemoryBlockStore(NetworkParameters.testNet3());
        if (type == null) {
            // Pending transaction
            for (Transaction tx : transactions)
                if (wallet.isPendingTransactionRelevant(tx))
                    wallet.receivePending(tx, null);
        } else {
            FakeTxBuilder.BlockPair bp = 
FakeTxBuilder.createFakeBlock(blockStore, 0, transactions);
            for (Transaction tx : transactions)
                wallet.receiveFromBlock(tx, bp.storedBlock, type, 0);
            if (type == AbstractBlockChain.NewBlockType.BEST_CHAIN)
                wallet.notifyNewBestBlock(bp.storedBlock);
        }
        if (transactions.length == 1)
            return wallet.getTransaction(transactions[0].getHash());  // 
Can be null if tx is a double spend that's otherwise irrelevant.
        else
            return null;
    }

@Nullable
private Transaction sendMoneyToWallet(Wallet wallet, 
AbstractBlockChain.NewBlockType type, Coin value, Address toAddress)
throws VerificationException {
return sendMoneyToWallet(wallet, type, 
FakeTxBuilder.createFakeTx(NetworkParameters.testNet3(), value, toAddress));
}
    public Transaction createFakeTx(NetworkParameters params, Coin value, 
Address to) {
        return createFakeTxWithChangeAddress(params, value, to, null);
    }
public Transaction createFakeTxWithChangeAddress(NetworkParameters params, 
Coin value, Address to, Address changeOutput) {
        Transaction t = new Transaction(params);
        TransactionOutput outputToMe = new TransactionOutput(params, t, 
value, to);
        t.addOutput(outputToMe);
        TransactionOutput change = new TransactionOutput(params, t, 
valueOf(1, 11), changeOutput);
        t.addOutput(change);
        // Make a previous tx simply to send us sufficient coins. This prev 
tx is not really valid but it doesn't
        // matter for our purposes.
        Transaction prevTx = new Transaction(params);
        TransactionOutput prevOut = new TransactionOutput(params, prevTx, 
value, to);
        prevTx.addOutput(prevOut);
        // Connect it.
        
t.addInput(prevOut).setScriptSig(ScriptBuilder.createInputScript(TransactionSignature.dummy()));
        // Fake signature.
        // Serialize/deserialize to ensure internal state is stripped, as 
if it had been read from the wire.
        return roundTripTransaction(params, t);
    }





-- 
You received this message because you are subscribed to the Google Groups 
"bitcoinj" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to